All files / owid-grapher/site/multiembedder MultiEmbedder.tsx

59.12% Statements 94/159
66.67% Branches 4/6
33.33% Functions 3/9
59.12% Lines 94/159

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 2131x 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 6x 6x 6x 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 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x             1x 1x 1x                                                                                                                                                                                                          
import React from "react"
import ReactDOM from "react-dom"
import { fetchText, isMobile } from "../../clientUtils/Util"
import { isPresent } from "../../clientUtils/isPresent"
import { GRAPHER_EMBEDDED_FIGURE_ATTR } from "../../grapher/core/GrapherConstants"
import { deserializeJSONFromHTML } from "../../clientUtils/serializers"
import {
    Grapher,
    GrapherProgrammaticInterface,
} from "../../grapher/core/Grapher"
import { Explorer, ExplorerProps } from "../../explorer/Explorer"
import {
    EMBEDDED_EXPLORER_DELIMITER,
    EMBEDDED_EXPLORER_GRAPHER_CONFIGS,
    EXPLORER_EMBEDDED_FIGURE_SELECTOR,
} from "../../explorer/ExplorerConstants"
import {
    GLOBAL_ENTITY_SELECTOR_DEFAULT_COUNTRY,
    GLOBAL_ENTITY_SELECTOR_ELEMENT,
} from "../../grapher/controls/globalEntitySelector/GlobalEntitySelectorConstants"
import { getWindowUrl, Url } from "../../clientUtils/urls/Url"
import { SelectionArray } from "../../grapher/selection/SelectionArray"
import {
    getSelectedEntityNamesParam,
    migrateSelectedEntityNamesParam,
} from "../../grapher/core/EntityUrlBuilder"
import { hydrateGlobalEntitySelectorIfAny } from "../../grapher/controls/globalEntitySelector/GlobalEntitySelector"
import { action } from "mobx"
import { Annotation } from "../../clientUtils/owidTypes"
import { hydrateAnnotatingDataValue } from "../AnnotatingDataValue"
 
const figuresFromDOM = (
    container: HTMLElement | Document = document,
    selector: string
) =>
    Array.from(
        container.querySelectorAll<HTMLElement>(`*[${selector}]`)
    ).filter(isPresent)
 
// Determine whether this device is powerful enough to handle
// loading a bunch of inline interactive charts
// 680px is also used in CSS – keep it in sync if you change this
export const shouldProgressiveEmbed = () =>
    !isMobile() ||
    window.screen.width > 680 ||
    pageContainsGlobalEntitySelector()
 
const pageContainsGlobalEntitySelector = () =>
    globalEntitySelectorElement() !== null
 
const globalEntitySelectorElement = () =>
    document.querySelector(GLOBAL_ENTITY_SELECTOR_ELEMENT)
 
class MultiEmbedder {
    private figuresObserver: IntersectionObserver | undefined
    selection: SelectionArray = new SelectionArray()
    graphersAndExplorersToUpdate: Set<SelectionArray> = new Set()
 
    constructor() {
        if (typeof window !== "undefined" && "IntersectionObserver" in window) {
            this.figuresObserver = new IntersectionObserver(
                this.onIntersecting.bind(this),
                {
                    rootMargin: "200%",
                }
            )
        } else {
            console.warn(
                "IntersectionObserver not available; interactive embeds won't load on this page"
            )
        }
    }
 
    /**
     * Finds all <figure data-grapher-src="..."> and <figure
     * data-explorer-src="..."> elements in the document and loads the
     * iframeless interactive charts when the user's viewport approaches them.
     * Uses an IntersectionObserver (see constructor).
     *
     * BEWARE: this method is hardcoded in some scripts, make sure to check
     * thoroughly before making any changes.
     */
    embedAll() {
        this.observeFigures()
    }
 
    /**
     * Make the embedder aware of new <figure> elements that are injected into the DOM.
     *
     * Use this when you programmatically create/replace charts.
     */
    observeFigures(container: HTMLElement | Document = document) {
        const figures = figuresFromDOM(
            container,
            GRAPHER_EMBEDDED_FIGURE_ATTR
        ).concat(figuresFromDOM(container, EXPLORER_EMBEDDED_FIGURE_SELECTOR))
 
        figures.forEach((figure) => {
            this.figuresObserver?.observe(figure)
        })
    }
 
    async onIntersecting(entries: IntersectionObserverEntry[]) {
        entries.forEach((entry) => {
            if (entry.isIntersecting) {
                this.renderInteractiveFigure(entry.target)
            }
        })
    }
 
    @action.bound
    async renderInteractiveFigure(figure: Element, annotation?: Annotation) {
        const isExplorer = figure.hasAttribute(
            EXPLORER_EMBEDDED_FIGURE_SELECTOR
        )

        const dataSrc = figure.getAttribute(
            isExplorer
                ? EXPLORER_EMBEDDED_FIGURE_SELECTOR
                : GRAPHER_EMBEDDED_FIGURE_ATTR
        )

        if (!dataSrc) return

        const hasPreview = isExplorer ? false : !!figure.querySelector("img")
        if (!shouldProgressiveEmbed() && hasPreview) return

        // Stop observing visibility as soon as possible, that is not before
        // shouldProgressiveEmbed gets a chance to reevaluate a possible change
        // in screen size on mobile (i.e. after a rotation). Stopping before
        // shouldProgressiveEmbed would prevent rendering interactive charts
        // when going from portrait to landscape mode (without page reload).
        this.figuresObserver?.unobserve(figure)

        const { fullUrl, queryStr } = Url.fromURL(dataSrc)

        const common: GrapherProgrammaticInterface = {
            isEmbeddedInAnOwidPage: true,
            queryStr,
        }

        const html = await fetchText(fullUrl)

        if (isExplorer) {
            const props: ExplorerProps = {
                ...common,
                ...deserializeJSONFromHTML(html, EMBEDDED_EXPLORER_DELIMITER),
                grapherConfigs: deserializeJSONFromHTML(
                    html,
                    EMBEDDED_EXPLORER_GRAPHER_CONFIGS
                ),
                queryStr,
                selection: new SelectionArray(
                    this.selection.selectedEntityNames
                ),
            }
            if (props.selection)
                this.graphersAndExplorersToUpdate.add(props.selection)
            ReactDOM.render(<Explorer {...props} />, figure)
        } else {
            figure.classList.remove("grapherPreview")
            const config: GrapherProgrammaticInterface = {
                ...deserializeJSONFromHTML(html),
                ...common,
                manager: {
                    selection: new SelectionArray(
                        this.selection.selectedEntityNames
                    ),
                },
                annotation,
            }
            if (config.manager?.selection)
                this.graphersAndExplorersToUpdate.add(config.manager.selection)
 
            const grapherInstance = Grapher.renderGrapherIntoContainer(
                config,
                figure
            )
            if (!grapherInstance) return
            hydrateAnnotatingDataValue(grapherInstance, figure)
        }
    }
 
    setUpGlobalEntitySelectorForEmbeds() {
        const element = globalEntitySelectorElement()
        if (!element) return
 
        const embeddedDefaultCountriesParam = element.getAttribute(
            GLOBAL_ENTITY_SELECTOR_DEFAULT_COUNTRY
        )
 
        const [defaultEntityNames, windowEntityNames] = [
            Url.fromQueryParams({
                country: embeddedDefaultCountriesParam || undefined,
            }),
            getWindowUrl(),
        ]
            .map(migrateSelectedEntityNamesParam)
            .map(getSelectedEntityNamesParam)
 
        this.selection = new SelectionArray(
            windowEntityNames ?? defaultEntityNames
        )
 
        hydrateGlobalEntitySelectorIfAny(
            this.selection,
            this.graphersAndExplorersToUpdate
        )
    }
}
 
export const MultiEmbedderSingleton = new MultiEmbedder()