oss-ecosystem-data / code /web /src /lib /export.ts
saladday1's picture
code: sync from git
2471af3 verified
Raw History Blame Contribute Delete
2.16 kB
import { getFontEmbedCSS, toPng } from "html-to-image"
/** Elements carrying this attribute (the download buttons) are left out of the picture. */
export const EXPORT_IGNORE = "data-export-ignore"
// The page's fonts, inlined once and reused by every export. The rule after them freezes the
// copy at what is on screen: entrance animations would otherwise start over inside the image.
let css: Promise<string> | null = null
const embedCSS = (node: HTMLElement) =>
(css ??= getFontEmbedCSS(node).catch(() => "")).then(
(fonts) => `${fonts}\n*,*::before,*::after{animation:none!important;transition:none!important}`,
)
const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9.]+/g, "-").replace(/^-|-$/g, "")
/**
* Saves `node` as a PNG at twice its size. `background` fills a node that has none of its own
* (a chart straight on the page; a card keeps its own colour and rounded corners), and `pad`
* adds a margin of it around the chart.
*/
export async function savePng(node: HTMLElement, name: string, { background, pad = 0 }: { background?: string; pad?: number }) {
const w = node.offsetWidth, h = node.offsetHeight
const url = await toPng(node, {
pixelRatio: 2,
backgroundColor: background,
fontEmbedCSS: await embedCSS(node),
width: w + 2 * pad,
height: h + 2 * pad,
style: pad ? { margin: "0", padding: `${pad}px`, boxSizing: "content-box", width: `${w}px`, height: `${h}px` } : { margin: "0" },
filter: (n) => !(n instanceof Element && n.hasAttribute(EXPORT_IGNORE)),
})
const a = document.createElement("a")
a.href = url
a.download = `${slug(name)}.png`
a.click()
}
const filled = (n: Element) => {
const c = getComputedStyle(n).backgroundColor
return !!c && c !== "transparent" && !/rgba\(.*,\s*0\)$/.test(c) ? c : null
}
/** What to fill `node` with: nothing when it has a colour of its own, else what shows behind it. */
export function backgroundFor(node: HTMLElement) {
if (filled(node)) return undefined
for (let n = node.parentElement; n; n = n.parentElement) {
const c = filled(n)
if (c) return c
}
return getComputedStyle(document.body).backgroundColor
}