Skip to content

Commit

Permalink
enhance(multi-dim): all props now available under `window._OWID_MULTI…
Browse files Browse the repository at this point in the history
…_DIM_PROPS`
  • Loading branch information
marcelgerber committed Aug 12, 2024
1 parent f1c5a4d commit 1928c5e
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 96 deletions.
41 changes: 18 additions & 23 deletions baker/MultiDimBaker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
IndicatorsAfterPreProcessing,
MultiDimDataPageConfigPreProcessed,
MultiDimDataPageConfigRaw,
MultiDimDataPageProps,
} from "../site/multiDim/MultiDimDataPageTypes.js"
import { MultiDimDataPageConfig } from "../site/multiDim/MultiDimDataPageConfig.js"
import * as db from "../db/db.js"
Expand All @@ -25,17 +26,15 @@ import {
keyBy,
mapValues,
OwidVariableWithSource,
pick,
} from "@ourworldindata/utils"
import {
fetchAndParseFaqs,
getPrimaryTopic,
resolveFaqsForVariable,
} from "./DatapageHelpers.js"
import { logErrorAndMaybeSendToBugsnag } from "../serverUtils/errorLog.js"
import {
FaqEntryKeyedByGdocIdAndFragmentId,
PrimaryTopic,
} from "@ourworldindata/types/dist/gdocTypes/Datapage.js"
import { FaqEntryKeyedByGdocIdAndFragmentId } from "@ourworldindata/types/dist/gdocTypes/Datapage.js"

// TODO Make this dynamic
const baseDir = findProjectBaseDir(__dirname)
Expand All @@ -56,12 +55,6 @@ const MULTI_DIM_SITES_BY_SLUG: Record<string, MultiDimDataPageConfigRaw> = {
"mdd-poverty": readMultiDimConfig("poverty.yml"),
}

interface BakingAdditionalContext {
tagToSlugMap: Record<string, string>
faqEntries: FaqEntryKeyedByGdocIdAndFragmentId
primaryTopic: PrimaryTopic | undefined
}

const resolveMultiDimDataPageCatalogPathsToIndicatorIds = async (
knex: db.KnexReadonlyTransaction,
rawConfig: MultiDimDataPageConfigRaw
Expand Down Expand Up @@ -223,12 +216,17 @@ export const renderMultiDimDataPageBySlug = async (
const rawConfig = MULTI_DIM_SITES_BY_SLUG[slug]
if (!rawConfig) throw new Error(`No multi-dim site found for slug: ${slug}`)

// TAGS
const tagToSlugMap = await getTagToSlugMap(knex)
// Only embed the tags that are actually used by the datapage, instead of the complete JSON object with ~240 properties
const minimalTagToSlugMap = pick(tagToSlugMap, rawConfig.topicTags ?? [])

// PRE-PROCESS CONFIG
const preProcessedConfig =
await resolveMultiDimDataPageCatalogPathsToIndicatorIds(knex, rawConfig)
const config = MultiDimDataPageConfig.fromObject(preProcessedConfig)

// FAQs
const variableMetaDict =
await getRelevantVariableMetadata(preProcessedConfig)
const faqEntries = await getFaqEntries(
Expand All @@ -237,28 +235,25 @@ export const renderMultiDimDataPageBySlug = async (
variableMetaDict
)

// PRIMARY TOPIC
const primaryTopic = await getPrimaryTopic(
knex,
preProcessedConfig.topicTags?.[0]
)

const bakingContext = { tagToSlugMap, faqEntries, primaryTopic }
const props = {
configObj: config.config,
tagToSlugMap: minimalTagToSlugMap,
faqEntries,
primaryTopic,
}

return renderMultiDimDataPage(config, bakingContext)
return renderMultiDimDataPage(props)
}

export const renderMultiDimDataPage = async (
config: MultiDimDataPageConfig,
bakingContext?: BakingAdditionalContext
) => {
export const renderMultiDimDataPage = async (props: MultiDimDataPageProps) => {
return renderToHtmlPage(
<MultiDimDataPage
baseUrl={BAKED_BASE_URL}
config={config}
tagToSlugMap={bakingContext?.tagToSlugMap}
faqEntries={bakingContext?.faqEntries}
primaryTopic={bakingContext?.primaryTopic}
/>
<MultiDimDataPage baseUrl={BAKED_BASE_URL} multiDimProps={props} />
)
}

Expand Down
5 changes: 0 additions & 5 deletions packages/@ourworldindata/types/src/gdocTypes/Datapage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,6 @@ export interface DataPageV2ContentFields {
imageMetadata: Record<string, ImageMetadata>
}

export type MultiDimDataPageContentFields = DataPageV2ContentFields & {
faqEntries: FaqEntryKeyedByGdocIdAndFragmentId
primaryTopic?: PrimaryTopic | undefined
}

export interface DisplaySource {
label: string
description?: string
Expand Down
43 changes: 6 additions & 37 deletions site/multiDim/MultiDimDataPage.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,21 @@
import React from "react"
import { MultiDimDataPageConfig } from "./MultiDimDataPageConfig.js"
import { Head } from "../Head.js"
import { IFrameDetector } from "../IframeDetector.js"
import { SiteHeader } from "../SiteHeader.js"
import { OWID_DATAPAGE_CONTENT_ROOT_ID } from "../DataPageV2Content.js"
import { SiteFooter } from "../SiteFooter.js"
import {
SiteFooterContext,
pick,
serializeJSONForHTML,
} from "@ourworldindata/utils"
import {
FaqEntryKeyedByGdocIdAndFragmentId,
PrimaryTopic,
} from "@ourworldindata/types/dist/gdocTypes/Datapage.js"
import { SiteFooterContext, serializeJSONForHTML } from "@ourworldindata/utils"
import { MultiDimDataPageProps } from "./MultiDimDataPageTypes.js"

export const MultiDimDataPage = (props: {
baseUrl: string
config: MultiDimDataPageConfig
tagToSlugMap?: Record<string, string>
faqEntries?: FaqEntryKeyedByGdocIdAndFragmentId
primaryTopic?: PrimaryTopic | undefined
multiDimProps: MultiDimDataPageProps
}) => {
const { config, faqEntries } = props
const { multiDimProps } = props

const canonicalUrl = "" // TODO
const baseUrl = props.baseUrl // TODO

// Only embed the tags that are actually used by the datapage, instead of the complete JSON object with ~240 properties
const minimalTagToSlugMap = pick(
props.tagToSlugMap,
config.config.topicTags ?? []
)

return (
<html>
<Head
Expand Down Expand Up @@ -63,15 +46,8 @@ export const MultiDimDataPage = (props: {
<main>
<script
dangerouslySetInnerHTML={{
__html: `window._OWID_DATAPAGEV2_PROPS = ${JSON.stringify(
{
// datapageData,
canonicalUrl,
tagToSlugMap: minimalTagToSlugMap,
faqEntries,
primaryTopic: props.primaryTopic,
// imageMetadata,
}
__html: `window._OWID_MULTI_DIM_PROPS = ${serializeJSONForHTML(
multiDimProps
)}`,
}}
/>
Expand All @@ -94,13 +70,6 @@ export const MultiDimDataPage = (props: {
context={SiteFooterContext.multiDimDataPage}
// isPreviewing={isPreviewing}
/>
<script
dangerouslySetInnerHTML={{
__html: `window._OWID_MULTI_DIM_CONFIG = ${serializeJSONForHTML(
props.config.config
)}`,
}}
/>
</body>
</html>
)
Expand Down
45 changes: 14 additions & 31 deletions site/multiDim/MultiDimDataPageContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,11 @@ import {
import ReactDOM from "react-dom"
import { RelatedCharts } from "../blocks/RelatedCharts.js"
import {
DataPageV2ContentFields,
formatAuthors,
intersection,
DataPageDataV2,
GrapherInterface,
joinTitleFragments,
ImageMetadata,
DimensionProperty,
OwidVariableWithSource,
getLastUpdatedFromVariable,
Expand All @@ -34,7 +32,7 @@ import { DebugProvider } from "../gdocs/DebugContext.js"
import { BAKED_BASE_URL, DATA_API_URL } from "../../settings/clientSettings.js"
import Image from "../gdocs/components/Image.js"
import { MultiDimDataPageConfig } from "./MultiDimDataPageConfig.js"
import { MultiDimDataPageConfigPreProcessed } from "./MultiDimDataPageTypes.js"
import { MultiDimDataPageProps } from "./MultiDimDataPageTypes.js"
import AboutThisData from "../AboutThisData.js"
import TopicTags from "../TopicTags.js"
import MetadataSection from "../MetadataSection.js"
Expand All @@ -45,14 +43,9 @@ import {
import { reaction } from "mobx"
import { useElementBounds } from "../hooks.js"
import { MultiDimSettingsPanel } from "./MultiDimDataPageSettingsPanel.js"
import {
FaqEntryKeyedByGdocIdAndFragmentId,
MultiDimDataPageContentFields,
PrimaryTopic,
} from "@ourworldindata/types/dist/gdocTypes/Datapage.js"
declare global {
interface Window {
_OWID_MULTI_DIM_CONFIG: MultiDimDataPageConfigPreProcessed
_OWID_MULTI_DIM_PROPS: MultiDimDataPageProps
}
}
export const OWID_DATAPAGE_CONTENT_ROOT_ID = "owid-datapageJson-root"
Expand Down Expand Up @@ -145,25 +138,22 @@ const cachedGetVariableMetadata = memoize(

export const MultiDimDataPageContent = ({
// _datapageData,
config,
grapherConfig,
configObj,
// isPreviewing = false,
faqEntries,
primaryTopic,
canonicalUrl = "{URL}", // when we bake pages to their proper url this will be set correctly but on preview pages we leave this undefined
tagToSlugMap,
// imageMetadata,
initialQueryStr,
}: DataPageV2ContentFields & {
config: MultiDimDataPageConfig
grapherConfig?: GrapherInterface
faqEntries: FaqEntryKeyedByGdocIdAndFragmentId
imageMetadata: Record<string, ImageMetadata>
initialQueryStr?: string
primaryTopic?: PrimaryTopic | undefined
}) => {
}: MultiDimDataPageProps) => {
const grapherFigureRef = useRef<HTMLDivElement>(null)

const config = useMemo(
() => MultiDimDataPageConfig.fromObject(configObj),
[configObj]
)

const [initialChoices] = useState(() =>
initialQueryStr
? extractDimensionChoicesFromQueryStr(initialQueryStr, config)
Expand Down Expand Up @@ -216,10 +206,10 @@ export const MultiDimDataPageContent = ({
const variableMetadata = cachedGetVariableMetadata(variableId)

variableMetadata
.then((json) => getDatapageDataV2(json, grapherConfig))
.then((json) => getDatapageDataV2(json, currentView?.config))
.then(setDatapageDataFromVar)
.catch(console.error)
}, [dimensionsConfig, currentView?.indicators, grapherConfig])
}, [dimensionsConfig, currentView?.indicators, currentView?.config])

const titleFragments = joinTitleFragments(
title.titleVariant,
Expand Down Expand Up @@ -325,7 +315,7 @@ export const MultiDimDataPageContent = ({
const faqEntriesForView = useMemo(() => {
return compact(
datapageDataFromVar?.faqs?.flatMap(
(faq) => faqEntries.faqs?.[faq.gdocId]?.[faq.fragmentId]
(faq) => faqEntries?.faqs?.[faq.gdocId]?.[faq.fragmentId]
)
)
}, [datapageDataFromVar?.faqs, faqEntries])
Expand All @@ -339,7 +329,7 @@ export const MultiDimDataPageContent = ({
<h1 className="header__title">{title.title}</h1>
<div className="header__source">{titleFragments}</div>
</div>
{hasTopicTags && (
{hasTopicTags && tagToSlugMap && (
<TopicTags
className="header__right col-start-10 span-cols-4 col-sm-start-2 span-sm-cols-12"
topicTagsLinks={config.config.topicTags ?? []}
Expand Down Expand Up @@ -539,20 +529,13 @@ export const MultiDimDataPageContent = ({

export const hydrateMultiDimDataPageContent = (isPreviewing?: boolean) => {
const wrapper = document.querySelector(`#${OWID_DATAPAGE_CONTENT_ROOT_ID}`)
const props: MultiDimDataPageContentFields =
window._OWID_DATAPAGEV2_PROPS as MultiDimDataPageContentFields
const grapherConfig = window._OWID_GRAPHER_CONFIG
const props: MultiDimDataPageProps = window._OWID_MULTI_DIM_PROPS
const initialQueryStr = getWindowQueryStr()
const config = MultiDimDataPageConfig.fromObject(
window._OWID_MULTI_DIM_CONFIG
)

ReactDOM.hydrate(
<DebugProvider debug={isPreviewing}>
<MultiDimDataPageContent
{...props}
config={config}
grapherConfig={grapherConfig}
isPreviewing={isPreviewing}
initialQueryStr={initialQueryStr}
/>
Expand Down
15 changes: 15 additions & 0 deletions site/multiDim/MultiDimDataPageTypes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { IndicatorTitleWithFragments } from "@ourworldindata/types"
import {
FaqEntryKeyedByGdocIdAndFragmentId,
PrimaryTopic,
} from "@ourworldindata/types/dist/gdocTypes/Datapage.js"

// Indicator ID, catalog path, or maybe an array of those
export type IndicatorEntryBeforePreProcessing = string | number | undefined
Expand Down Expand Up @@ -69,3 +73,14 @@ export interface Config {
title?: string
subtitle?: string
}

export interface MultiDimDataPageProps {
configObj: MultiDimDataPageConfigPreProcessed
tagToSlugMap?: Record<string, string>
faqEntries?: FaqEntryKeyedByGdocIdAndFragmentId
primaryTopic?: PrimaryTopic | undefined

initialQueryStr?: string
canonicalUrl?: string
isPreviewing?: boolean
}

0 comments on commit 1928c5e

Please sign in to comment.