File size: 2,159 Bytes
2471af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
}