All files / owid-grapher/baker siteRenderers.tsx

32.93% Statements 109/331
100% Branches 0/0
0% Functions 0/15
32.93% Lines 109/331

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 5311x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x                                                                     1x 1x 1x 1x 1x 1x       1x 1x       1x 1x       1x 1x                                                                               1x 1x                                           1x 1x     1x 1x 1x 1x 1x 1x                                   1x 1x 1x 1x 1x   1x                                                                                     1x 1x 1x                                               1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
import {
    formatWordpressEditLink,
    LongFormPage,
    PageOverrides,
} from "../site/LongFormPage"
import { BlogIndexPage } from "../site/BlogIndexPage"
import { FrontPage } from "../site/FrontPage"
import { ChartsIndexPage, ChartIndexItem } from "../site/ChartsIndexPage"
import { CovidPage } from "../site/CovidPage"
import { SearchPage } from "../site/SearchPage"
import { NotFoundPage } from "../site/NotFoundPage"
import { DonatePage } from "../site/DonatePage"
import * as React from "react"
import * as ReactDOMServer from "react-dom/server"
import * as lodash from "lodash"
import {
    extractFormattingOptions,
    formatCountryProfile,
    formatLinks,
    isStandaloneInternalLink,
} from "./formatting"
import {
    bakeGrapherUrls,
    getGrapherExportsByUrl,
    GrapherExports,
} from "../baker/GrapherBakingUtils"
import * as cheerio from "cheerio"
import { Post } from "../db/model/Post"
import { BAKED_BASE_URL, BLOG_POSTS_PER_PAGE } from "../settings/serverSettings"
import { RECAPTCHA_SITE_KEY } from "../settings/clientSettings"
import {
    EntriesByYearPage,
    EntriesForYearPage,
} from "../site/EntriesByYearPage"
import { VariableCountryPage } from "../site/VariableCountryPage"
import { FeedbackPage } from "../site/FeedbackPage"
import { getCountry, Country } from "../clientUtils/countries"
import { memoize } from "../clientUtils/Util"
import { CountryProfileSpec } from "../site/countryProfileProjects"
import {
    FormattedPost,
    FormattingOptions,
    FullPost,
    JsonError,
    PostRow,
    WP_PostType,
} from "../clientUtils/owidTypes"
import { formatPost } from "./formatWordpressPost"
import {
    getBlogIndex,
    getEntriesByCategory,
    getFullPost,
    getLatestPostRevision,
    getMediaThumbnailUrl,
    getPostBySlug,
    getPosts,
    selectHomepagePosts,
    isPostCitable,
    getBlockContent,
} from "../db/wpdb"
import { mysqlFirst, queryMysql, knexTable } from "../db/db"
import { getPageOverrides, isPageOverridesCitable } from "./pageOverrides"
import { Url } from "../clientUtils/urls/Url"
import { logErrorAndMaybeSendToSlack } from "../serverUtils/slackLog"
import {
    ProminentLink,
    ProminentLinkStyles,
} from "../site/blocks/ProminentLink"
import { GrapherInterface } from "../grapher/core/GrapherInterface"
import { Grapher, GrapherProgrammaticInterface } from "../grapher/core/Grapher"
import { ExplorerProgram } from "../explorer/ExplorerProgram"
import { ExplorerPageUrlMigrationSpec } from "../explorer/urlMigrations/ExplorerPageUrlMigrationSpec"
import { ExplorerPage } from "../site/ExplorerPage"
export const renderToHtmlPage = (element: any) =>
    `<!doctype html>${ReactDOMServer.renderToStaticMarkup(element)}`
 
export const renderChartsPage = async () => {
    const chartItems = (await queryMysql(`
        SELECT
            id,
            config->>"$.slug" AS slug,
            config->>"$.title" AS title,
            config->>"$.variantName" AS variantName
        FROM charts
        WHERE
            is_indexable IS TRUE
            AND publishedAt IS NOT NULL
            AND config->"$.isPublished" IS TRUE
    `)) as ChartIndexItem[]

    const chartTags = await queryMysql(`
        SELECT ct.chartId, ct.tagId, t.name as tagName, t.parentId as tagParentId FROM chart_tags ct
        JOIN charts c ON c.id=ct.chartId
        JOIN tags t ON t.id=ct.tagId
    `)

    for (const c of chartItems) {
        c.tags = []
    }

    const chartsById = lodash.keyBy(chartItems, (c) => c.id)

    for (const ct of chartTags) {
        const c = chartsById[ct.chartId]
        if (c) c.tags.push({ id: ct.tagId, name: ct.tagName })
    }

    return renderToHtmlPage(
        <ChartsIndexPage chartItems={chartItems} baseUrl={BAKED_BASE_URL} />
    )
}
 
// Only used in the dev server
export const renderCovidPage = () =>
    renderToHtmlPage(<CovidPage baseUrl={BAKED_BASE_URL} />)
 
export const renderPageBySlug = async (slug: string) => {
    const post = await getPostBySlug(slug)
    return renderPost(post)
}
 
export const renderPreview = async (postId: number): Promise<string> => {
    const postApi = await getLatestPostRevision(postId)
    return renderPost(postApi)
}
 
export const renderMenuJson = async () => {
    const categories = await getEntriesByCategory()
    return JSON.stringify({ categories: categories })
}
 
export const renderPost = async (
    post: FullPost,
    baseUrl: string = BAKED_BASE_URL,
    grapherExports?: GrapherExports
) => {
    let exportsByUrl = grapherExports

    if (!grapherExports) {
        const $ = cheerio.load(post.content)

        const grapherUrls = $("iframe")
            .toArray()
            .filter((el) => (el.attribs["src"] || "").match(/\/grapher\//))
            .map((el) => el.attribs["src"].trim())

        // This can be slow if uncached!
        await bakeGrapherUrls(grapherUrls)

        exportsByUrl = await getGrapherExportsByUrl()
    }

    // Extract formatting options from post HTML comment (if any)
    const formattingOptions = extractFormattingOptions(post.content)

    const formatted = await formatPost(post, formattingOptions, exportsByUrl)

    const pageOverrides = await getPageOverrides(post, formattingOptions)
    const citationStatus =
        (await isPostCitable(post)) || isPageOverridesCitable(pageOverrides)

    return renderToHtmlPage(
        <LongFormPage
            withCitation={citationStatus}
            post={formatted}
            overrides={pageOverrides}
            formattingOptions={formattingOptions}
            baseUrl={baseUrl}
        />
    )
}
 
export const renderFrontPage = async () => {
    const entries = await getEntriesByCategory()
    const posts = await getBlogIndex()
    const totalCharts = (
        await queryMysql(
            `SELECT COUNT(*) AS count
            FROM charts
            WHERE
                is_indexable IS TRUE
                AND publishedAt IS NOT NULL
                AND config -> "$.isPublished" IS TRUE`
        )
    )[0].count as number
    return renderToHtmlPage(
        <FrontPage
            entries={entries}
            posts={posts}
            totalCharts={totalCharts}
            baseUrl={BAKED_BASE_URL}
        />
    )
}
 
export const renderDonatePage = () =>
    renderToHtmlPage(
        <DonatePage
            baseUrl={BAKED_BASE_URL}
            recaptchaKey={RECAPTCHA_SITE_KEY}
        />
    )
 
export const renderBlogByPageNum = async (pageNum: number) => {
    const allPosts = await getBlogIndex()

    const numPages = Math.ceil(allPosts.length / BLOG_POSTS_PER_PAGE)
    const posts = allPosts.slice(
        (pageNum - 1) * BLOG_POSTS_PER_PAGE,
        pageNum * BLOG_POSTS_PER_PAGE
    )

    return renderToHtmlPage(
        <BlogIndexPage
            posts={posts}
            pageNum={pageNum}
            numPages={numPages}
            baseUrl={BAKED_BASE_URL}
        />
    )
}
 
export const renderSearchPage = () =>
    renderToHtmlPage(<SearchPage baseUrl={BAKED_BASE_URL} />)
 
export const renderNotFoundPage = () =>
    renderToHtmlPage(<NotFoundPage baseUrl={BAKED_BASE_URL} />)
 
export async function makeAtomFeed() {
    const postsApi = await getPosts([WP_PostType.Post], selectHomepagePosts, 10)
    const posts = await Promise.all(
        postsApi.map((postApi) => getFullPost(postApi, true))
    )

    const feed = `<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Our World in Data</title>
<subtitle>Research and data to make progress against the world’s largest problems</subtitle>
<id>${BAKED_BASE_URL}/</id>
<link type="text/html" rel="alternate" href="${BAKED_BASE_URL}"/>
<link type="application/atom+xml" rel="self" href="${BAKED_BASE_URL}/atom.xml"/>
<updated>${posts[0].date.toISOString()}</updated>
${posts
    .map((post) => {
        const postUrl = `${BAKED_BASE_URL}/${post.path}`
        const image = post.imageUrl
            ? `<br><br><a href="${postUrl}" target="_blank"><img src="${post.imageUrl}"/></a>`
            : ""

        return `<entry>
            <title><![CDATA[${post.title}]]></title>
            <id>${postUrl}</id>
            <link rel="alternate" href="${postUrl}"/>
            <published>${post.date.toISOString()}</published>
            <updated>${post.modifiedDate.toISOString()}</updated>
            ${post.authors
                .map(
                    (author: string) =>
                        `<author><name>${author}</name></author>`
                )
                .join("")}
            <summary><![CDATA[${post.excerpt}${image}]]></summary>
            </entry>`
    })
    .join("\n")}
</feed>
`

    return feed
}
 
// These pages exist largely just for Google Scholar
export const entriesByYearPage = async (year?: number) => {
    const entries = (await knexTable(Post.table)
        .where({ status: "publish" })
        .join("post_tags", { "post_tags.post_id": "posts.id" })
        .join("tags", { "tags.id": "post_tags.tag_id" })
        .where({ "tags.name": "Entries" })
        .select("title", "slug", "published_at")) as Pick<
        PostRow,
        "title" | "slug" | "published_at"
    >[]

    if (year !== undefined)
        return renderToHtmlPage(
            <EntriesForYearPage
                entries={entries}
                year={year}
                baseUrl={BAKED_BASE_URL}
            />
        )

    return renderToHtmlPage(
        <EntriesByYearPage entries={entries} baseUrl={BAKED_BASE_URL} />
    )
}
 
export const pagePerVariable = async (
    variableId: number,
    countryName: string
) => {
    const variable = await mysqlFirst(
        `
        SELECT v.id, v.name, v.unit, v.shortUnit, v.description, v.sourceId, u.fullName AS uploadedBy,
               v.display, d.id AS datasetId, d.name AS datasetName, d.namespace AS datasetNamespace
        FROM variables v
        JOIN datasets d ON d.id=v.datasetId
        JOIN users u ON u.id=d.dataEditedByUserId
        WHERE v.id = ?
    `,
        [variableId]
    )

    if (!variable) throw new JsonError(`No variable by id '${variableId}'`, 404)

    variable.display = JSON.parse(variable.display)
    variable.source = await mysqlFirst(
        `SELECT id, name FROM sources AS s WHERE id = ?`,
        variable.sourceId
    )

    const country = await knexTable("entities")
        .select("id", "name")
        .whereRaw("lower(name) = ?", [countryName])
        .first()

    return renderToHtmlPage(
        <VariableCountryPage
            variable={variable}
            country={country}
            baseUrl={BAKED_BASE_URL}
        />
    )
}
 
export const feedbackPage = () =>
    renderToHtmlPage(<FeedbackPage baseUrl={BAKED_BASE_URL} />)
 
const getCountryProfilePost = memoize(
    async (
        profileSpec: CountryProfileSpec,
        grapherExports?: GrapherExports
    ): Promise<[FormattedPost, FormattingOptions]> => {
        // Get formatted content from generic covid country profile page.
        const genericCountryProfilePost = await getPostBySlug(
            profileSpec.genericProfileSlug
        )
 
        const profileFormattingOptions = extractFormattingOptions(
            genericCountryProfilePost.content
        )
        const formattedPost = await formatPost(
            genericCountryProfilePost,
            profileFormattingOptions,
            grapherExports
        )
 
        return [formattedPost, profileFormattingOptions]
    }
)
 
// todo: we used to flush cache of this thing.
const getCountryProfileLandingPost = memoize(
    async (profileSpec: CountryProfileSpec) => {
        return getPostBySlug(profileSpec.landingPageSlug)
    }
)
 
export const renderCountryProfile = async (
    profileSpec: CountryProfileSpec,
    country: Country,
    grapherExports?: GrapherExports
) => {
    const [formatted, formattingOptions] = await getCountryProfilePost(
        profileSpec,
        grapherExports
    )
 
    const formattedCountryProfile = formatCountryProfile(formatted, country)
 
    const landing = await getCountryProfileLandingPost(profileSpec)
 
    const overrides: PageOverrides = {
        pageTitle: `${country.name}: ${profileSpec.pageTitle} Country Profile`,
        pageDesc: `${country.name}: ${formattedCountryProfile.pageDesc}`,
        canonicalUrl: `${BAKED_BASE_URL}/${profileSpec.rootPath}/${country.slug}`,
        citationTitle: landing.title,
        citationSlug: landing.slug,
        citationCanonicalUrl: `${BAKED_BASE_URL}/${landing.slug}`,
        citationAuthors: landing.authors,
        citationPublicationDate: landing.date,
    }
    return renderToHtmlPage(
        <LongFormPage
            withCitation={true}
            post={formattedCountryProfile}
            overrides={overrides}
            formattingOptions={formattingOptions}
            baseUrl={BAKED_BASE_URL}
        />
    )
}
 
export const countryProfileCountryPage = async (
    profileSpec: CountryProfileSpec,
    countrySlug: string
) => {
    const country = getCountry(countrySlug)
    if (!country) throw new JsonError(`No such country ${countrySlug}`, 404)
 
    // Voluntarily not dealing with grapherExports on devServer for simplicity
    return renderCountryProfile(profileSpec, country)
}
 
export const flushCache = () => getCountryProfilePost.cache.clear?.()
 
export const renderAutomaticProminentLinks = async (
    cheerioEl: CheerioStatic,
    currentPost: FullPost
) => {
    const anchorElements = cheerioEl("a").toArray()
    await Promise.all(
        anchorElements.map(async (anchor) => {
            if (!isStandaloneInternalLink(anchor, cheerioEl)) return
            const url = Url.fromURL(anchor.attribs.href)
            if (!url.slug) return
 
            // todo: remove early return when "/uploads" standalone links removed from content
            // conversion failing silently on purpose
            // see https://www.notion.so/owid/Automatic-prominent-links-1eafcce85953483d912b6e5f20b928ec#55ca3ed4f72e41b8bd477f2eba2455b6
            if (url.isUpload) return
 
            if (url.isGrapher) {
                logErrorAndMaybeSendToSlack(
                    new Error(
                        `Automatic prominent link conversion failed for ${
                            anchor.attribs.href
                        } in ${formatWordpressEditLink(
                            currentPost.id
                        )}. Grapher link are not yet supported.`
                    )
                )
                return
            }
 
            let targetPost
            try {
                targetPost = await getPostBySlug(url.slug)
            } catch (err) {
                // not throwing here as this is not considered a critical error.
                // Standalone links will just show up as such (and get
                // netlify-redirected upon click if applicable).
                logErrorAndMaybeSendToSlack(
                    new Error(
                        `Automatic prominent link conversion failed: no post found at ${
                            anchor.attribs.href
                        } in ${formatWordpressEditLink(
                            currentPost.id
                        )}. This might be because the URL of the target has been recently changed.`
                    )
                )
            }
            if (!targetPost) return
 
            let image
            if (targetPost.imageId) {
                const mediaThumbnailUrl = await getMediaThumbnailUrl(
                    targetPost.imageId
                )
                if (mediaThumbnailUrl) {
                    image = ReactDOMServer.renderToStaticMarkup(
                        <img src={formatLinks(mediaThumbnailUrl)} />
                    )
                }
            }
 
            const rendered = ReactDOMServer.renderToStaticMarkup(
                <div className="block-wrapper">
                    <ProminentLink
                        href={anchor.attribs.href}
                        style={ProminentLinkStyles.thin}
                        title={targetPost.title}
                        image={image}
                    />
                </div>
            )
 
            const $anchorParent = cheerioEl(anchor.parent)
            $anchorParent.after(rendered)
            $anchorParent.remove()
        })
    )
}
 
export const renderExplorerPage = async (
    program: ExplorerProgram,
    urlMigrationSpec?: ExplorerPageUrlMigrationSpec
) => {
    const { requiredGrapherIds } = program.decisionMatrix
    let grapherConfigRows: any[] = []
    if (requiredGrapherIds.length)
        grapherConfigRows = await queryMysql(
            `SELECT id, config FROM charts WHERE id IN (?)`,
            [requiredGrapherIds]
        )
 
    const wpContent = program.wpBlockId
        ? await getBlockContent(program.wpBlockId)
        : undefined
 
    const grapherConfigs: GrapherInterface[] = grapherConfigRows.map((row) => {
        const config: GrapherProgrammaticInterface = JSON.parse(row.config)
        config.id = row.id // Ensure each grapher has an id
        config.manuallyProvideData = true
        return new Grapher(config).toObject()
    })
 
    return (
        `<!doctype html>` +
        ReactDOMServer.renderToStaticMarkup(
            <ExplorerPage
                grapherConfigs={grapherConfigs}
                program={program}
                wpContent={wpContent}
                baseUrl={BAKED_BASE_URL}
                urlMigrationSpec={urlMigrationSpec}
            />
        )
    )
}