oss-ecosystem-data / code /web /src /components /download-button.tsx
saladday1's picture
code: sync from git
0953253 verified
Raw History Blame Contribute Delete
2.02 kB
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>
)
}