All files / owid-grapher/site/blocks AdditionalInformation.tsx

19.42% Statements 27/139
100% Branches 0/0
0% Functions 0/2
19.42% Lines 27/139

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 1921x 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 * as React from "react"
import { useState, useRef, useEffect } from "react"
import * as ReactDOM from "react-dom"
import * as ReactDOMServer from "react-dom/server"
import AnimateHeight from "react-animate-height"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faAngleRight } from "@fortawesome/free-solid-svg-icons/faAngleRight"
import { MultiEmbedderSingleton } from "../../site/multiembedder/MultiEmbedder"
 
export const CLASS_NAME = "wp-block-owid-additional-information"
const VARIATION_MERGE_LEFT = "merge-left"
const VARIATION_FULL_WIDTH = "full-width"
 
/*
 * This block has 2 variations (on large screens):
 * 1- merge left, with or without image.
 * 2- full width, with its content using the usual automatic layout
 *
 * For both these variations, the title is optional and is
 * assumed to be contained in the first h3 tag.
 */
 
const AdditionalInformation = ({
    content,
    title,
    image,
    variation,
    defaultOpen,
}: {
    content: string | null
    title: string | null
    image: string | null
    variation: string
    defaultOpen: boolean
}) => {
    const [height, setHeight] = useState<number | string>(
        defaultOpen ? "auto" : 0
    )
    const [hasBeenOpened, setHasBeenOpened] = useState(defaultOpen)
    const refContainer = useRef<HTMLDivElement>(null)
    const classes = [CLASS_NAME]

    useEffect(() => {
        if (refContainer.current) {
            // Trigger embedder check for new figures that may have become visible.
            MultiEmbedderSingleton.observeFigures(refContainer.current)
        }
        // Expands accordions for print media.
        window.addEventListener("beforeprint", () => {
            onOpenHandler()
        })
    }, [hasBeenOpened])

    const onClickHandler = () => {
        setHeight(height === 0 ? "auto" : 0)
        if (!hasBeenOpened) {
            setHasBeenOpened(true)
        }
    }

    const onOpenHandler = () => {
        setHeight("auto")
        if (!hasBeenOpened) {
            setHasBeenOpened(true)
        }
    }

    if (image) {
        classes.push("with-image")
    }
    if (height !== 0) {
        classes.push("open")
    }

    const renderFullWidthVariation = () => {
        return (
            <div
                className="content"
                dangerouslySetInnerHTML={{ __html: content || "" }}
            ></div>
        )
    }

    const renderMergeLeftVariation = () => {
        return (
            <div className="content-wrapper">
                {image ? (
                    <figure
                        dangerouslySetInnerHTML={{ __html: image || "" }}
                    ></figure>
                ) : null}
                <div
                    className="content"
                    dangerouslySetInnerHTML={{ __html: content || "" }}
                ></div>
            </div>
        )
    }

    return (
        <div
            data-variation={variation}
            data-default-open={defaultOpen}
            ref={refContainer}
            className={classes.join(" ")}
        >
            <h3
                onClick={onClickHandler}
                data-track-note="additional-information-toggle"
            >
                <FontAwesomeIcon icon={faAngleRight} />
                {title}
            </h3>
            <AnimateHeight height={height} animateOpacity={true}>
                {variation === VARIATION_MERGE_LEFT
                    ? renderMergeLeftVariation()
                    : renderFullWidthVariation()}
            </AnimateHeight>
        </div>
    )
}
 
export default AdditionalInformation
 
export const render = ($: CheerioStatic) => {
    $("block[type='additional-information']").each(function (
        this: CheerioElement
    ) {
        const $block = $(this)
        const variation = $block.find(".is-style-merge-left").length
            ? VARIATION_MERGE_LEFT
            : VARIATION_FULL_WIDTH
        const title =
            $block.find("h3").remove().text() || "Additional information"
        const image =
            variation === VARIATION_MERGE_LEFT
                ? $block
                      .find(".wp-block-column:first-child img[src]") // Wordpress outputs empty <img> tags when none is selected so we need to filter those out
                      .first()
                      .parent() // Get the wrapping <figure>
                      .html()
                : null
        const content =
            variation === VARIATION_MERGE_LEFT
                ? $block.find(".wp-block-column:last-child").html()
                : $block.find("content").html() // the title has been removed so the rest of a variation "full width" block is content.
        // Side note: "content" refers here to the <content> tag output by the block on the PHP side, not
        // the ".content" class.
        const defaultOpen = $block.attr("default-open") === "true"
        const rendered = ReactDOMServer.renderToString(
            <div className="block-wrapper">
                <AdditionalInformation
                    content={content}
                    title={title}
                    image={image}
                    variation={variation}
                    defaultOpen={defaultOpen}
                />
            </div>
        )
        $block.after(rendered)
        $block.remove()
    })
}
 
export const hydrate = () => {
    document
        .querySelectorAll<HTMLElement>(`.${CLASS_NAME}`)
        .forEach((block) => {
            const blockWrapper = block.parentElement
            const titleEl = block.querySelector("h3")
            const title = titleEl ? titleEl.textContent : null
            const variation = block.getAttribute("data-variation") || ""
            const defaultOpen =
                block.getAttribute("data-default-open") === "true"
            const figureEl = block.querySelector(".content-wrapper > figure")
            const image = figureEl ? figureEl.innerHTML : null
            const contentEl = block.querySelector(".content")
            const content = contentEl ? contentEl.innerHTML : null
            ReactDOM.hydrate(
                <AdditionalInformation
                    content={content}
                    title={title}
                    image={image}
                    variation={variation}
                    defaultOpen={defaultOpen}
                />,
                blockWrapper
            )
        })
}