File size: 2,021 Bytes
2471af3
 
 
0953253
2471af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0953253
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
import { useEffect, useRef, useState } from "react"
import { Check, Download, LoaderCircle } from "lucide-react"
import { backgroundFor, EXPORT_IGNORE, savePng } from "@/lib/export"
import { T } from "@/lib/i18n"

/**
 * Round icon button in the top right of a chart: saves `target` as a PNG named after `name`.
 * `tone` matches what it sits on (a card on the page, or the dark stage).
 */
export function DownloadButton({ target, name, tone = "card", pad = 0, big = false, className = "" }: {
  target: React.RefObject<HTMLElement | null>; name: string; tone?: "card" | "stage"; pad?: number; big?: boolean; className?: string
}) {
  const [state, setState] = useState<"idle" | "busy" | "done">("idle")
  const timer = useRef<number>(0)
  useEffect(() => () => window.clearTimeout(timer.current), [])

  const run = async () => {
    const node = target.current
    if (!node || state === "busy") return
    setState("busy")
    try {
      await savePng(node, name, { background: backgroundFor(node), pad })
      setState("done")
      timer.current = window.setTimeout(() => setState("idle"), 1400)
    } catch {
      setState("idle")
    }
  }

  const look = tone === "stage"
    ? "border-white/15 bg-white/[0.06] text-white/70 backdrop-blur hover:border-white/35 hover:bg-white/12 hover:text-white focus-visible:outline-white/60"
    : "border-border bg-card text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-ring"
  const Icon = state === "busy" ? LoaderCircle : state === "done" ? Check : Download
  return (
    <button type="button" onClick={run} {...{ [EXPORT_IGNORE]: "" }}
            aria-label={T.downloadAria(name)} title={T.downloadPng} aria-busy={state === "busy"}
            className={`inline-flex ${big ? "size-10" : "size-9"} shrink-0 items-center justify-center rounded-full border transition-colors focus-visible:outline-2 ${look} ${className}`}>
      <Icon className={`size-4 ${state === "busy" ? "animate-spin" : ""}`} strokeWidth={2} />
    </button>
  )
}