{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"download-button","type":"registry:component","title":"Download button","description":"The arrow drops into the tray while the button fills with progress.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/download-button.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n  animate,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useMotionValueEvent,\n  useTransform,\n  type AnimationPlaybackControls,\n  type MotionValue,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type DownloadStatus = \"idle\" | \"downloading\" | \"done\";\n\n// Progress events land every few hundred ms; this glides between them\n// without trailing so far behind that the fill feels dishonest.\nconst FILL = { type: \"spring\", visualDuration: 0.4, bounce: 0 } as const;\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// Cancelling drains the fill back out, fast: the system is responding.\nconst DRAIN = { duration: 0.2, ease: EASE_OUT } as const;\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n// The icon's small sideways glide as the word beside it changes length.\nconst SHIFT = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n// Close enough to full that the check never waits on the spring's tail.\nconst FULL = 0.995;\n\nexport function DownloadButton({\n  status,\n  progress,\n  onStart,\n  onCancel,\n  onReset,\n  label = \"Download\",\n  doneLabel = \"Done\",\n  // Long enough to register the check, short enough to be ready again.\n  resetAfter = 1800,\n  className,\n}: {\n  status: DownloadStatus;\n  /** 0 to 1. Only read while downloading. */\n  progress: number;\n  onStart: () => void;\n  onCancel: () => void;\n  /** Called `resetAfter` ms after the check appears; set status to idle. */\n  onReset: () => void;\n  label?: string;\n  doneLabel?: string;\n  resetAfter?: number;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const fill = useMotionValue(0);\n  const cover = useMotionValue(1);\n  const [full, setFull] = useState(false);\n  const [note, setNote] = useState(\"\");\n  const prevStatus = useRef<DownloadStatus>(status);\n  const run = useRef<AnimationPlaybackControls>(undefined);\n  const fade = useRef<AnimationPlaybackControls>(undefined);\n\n  useEffect(() => {\n    const prev = prevStatus.current;\n    prevStatus.current = status;\n\n    if (status === \"idle\") {\n      if (prev === \"downloading\") {\n        run.current?.stop();\n        if (reduceMotion) fill.jump(0);\n        else run.current = animate(fill, 0, DRAIN);\n      } else if (prev === \"done\") {\n        // A finished download fades back to plain rather than draining, so\n        // it never looks like the file was taken back.\n        fade.current = animate(cover, 0, {\n          duration: reduceMotion ? 0 : 0.2,\n          ease: EASE_OUT,\n          onComplete: () => {\n            fill.jump(0);\n            cover.jump(1);\n          },\n        });\n      }\n      return;\n    }\n\n    if (prev === \"idle\") {\n      // A fresh run starts empty, even if the last fade was still going.\n      fade.current?.stop();\n      run.current?.stop();\n      cover.jump(1);\n      fill.jump(0);\n    }\n    const target = status === \"done\" ? 1 : Math.min(Math.max(progress, 0), 1);\n    if (reduceMotion) fill.jump(target);\n    else run.current = animate(fill, target, FILL);\n  }, [status, progress, reduceMotion, fill, cover]);\n\n  useEffect(\n    () => () => {\n      run.current?.stop();\n      fade.current?.stop();\n    },\n    [],\n  );\n\n  useMotionValueEvent(fill, \"change\", (v) => setFull(v >= FULL));\n\n  // The check waits for the fill to visibly reach the end, not just the\n  // status, so it never appears over a bar that is still moving.\n  const checked = status === \"done\" && (full || !!reduceMotion);\n\n  useEffect(() => {\n    if (!checked) return;\n    const timer = setTimeout(onReset, resetAfter);\n    return () => clearTimeout(timer);\n  }, [checked, onReset, resetAfter]);\n\n  const uncovered = useTransform(fill, (v) => (1 - v) * 100);\n  const clip = useMotionTemplate`inset(0 ${uncovered}% 0 0)`;\n  const percent = useTransform(fill, (v) => `${Math.round(v * 100)}%`);\n\n  const click = () => {\n    if (status === \"downloading\") {\n      setNote(\"Download cancelled\");\n      onCancel();\n    } else if (status === \"idle\") {\n      setNote(\"Downloading\");\n      onStart();\n    }\n  };\n\n  const downloading = status === \"downloading\";\n  const view: View = checked ? \"done\" : status === \"idle\" ? \"idle\" : \"busy\";\n\n  return (\n    <span className={cn(\"relative inline-flex\", className)}>\n      <button\n        type=\"button\"\n        aria-label={downloading ? \"Cancel download\" : label}\n        aria-disabled={status === \"done\" || undefined}\n        onClick={click}\n        className={cn(\n          // Fixed width: every state fits inside, so nothing around it moves.\n          \"group relative isolate inline-flex h-11 w-[168px] max-w-full touch-manipulation items-center justify-center overflow-hidden rounded-full bg-muted text-[15px] font-medium text-foreground shadow-raised outline-hidden select-none\",\n          \"transition-[scale] duration-150 ease-out active:scale-[0.96] motion-reduce:transition-none\",\n          \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground\",\n          status === \"done\" && \"cursor-default\",\n        )}\n      >\n        <Content\n          view={view}\n          cancellable={downloading}\n          label={label}\n          doneLabel={doneLabel}\n          percent={percent}\n          reduceMotion={reduceMotion}\n        />\n        {/* The same content again, inverted and clipped to the fill, so the\n            text and icon change color exactly where the fill passes them. */}\n        <motion.span\n          aria-hidden\n          className=\"absolute inset-0 flex items-center justify-center bg-foreground text-background\"\n          style={{ clipPath: clip, opacity: cover }}\n        >\n          <Content\n            view={view}\n            cancellable={downloading}\n            label={label}\n            doneLabel={doneLabel}\n            percent={percent}\n            reduceMotion={reduceMotion}\n          />\n        </motion.span>\n      </button>\n\n      {/* Outside the button: a button's children are presentational, so a\n          progressbar nested inside would never reach assistive tech. */}\n      <span\n        role=\"progressbar\"\n        aria-label=\"Download progress\"\n        aria-valuemin={0}\n        aria-valuemax={100}\n        aria-valuenow={downloading ? Math.round(progress * 100) : undefined}\n        aria-hidden={!downloading}\n        className=\"sr-only\"\n      />\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {checked ? \"Download complete\" : note}\n      </span>\n    </span>\n  );\n}\n\ntype View = \"idle\" | \"busy\" | \"done\";\n\nfunction Content({\n  view,\n  cancellable,\n  label,\n  doneLabel,\n  percent,\n  reduceMotion,\n}: {\n  view: View;\n  cancellable: boolean;\n  label: string;\n  doneLabel: string;\n  percent: MotionValue<string>;\n  reduceMotion: boolean | null;\n}) {\n  const busy = view === \"busy\";\n  // Only the live word takes up space, so the icon and word stay centered\n  // as a pair in every state; the icon glides to its new spot instead of\n  // jumping, and the words cross-fade in place.\n  const glide = reduceMotion ? { duration: 0 } : SHIFT;\n  return (\n    <span aria-hidden className=\"flex items-center gap-2\">\n      <motion.span layout=\"position\" transition={glide} className=\"grid\">\n        <motion.svg\n          viewBox=\"0 0 24 24\"\n          className=\"col-start-1 row-start-1 size-5\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={1.75}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          initial={false}\n          animate={view === \"done\" ? hidden(reduceMotion) : shown}\n          transition={ICON_SWAP}\n        >\n          {/* Drops 3.5px so the tip lands inside the tray and stays there\n              while the file comes in. No spring: a bounce would read as the\n              arrow hitting a floor. */}\n          <g\n            className={cn(\n              \"transition-[translate] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\",\n              busy ? \"translate-y-[3.5px] duration-300\" : \"duration-200\",\n            )}\n          >\n            <path d=\"M12 3.75v10M7.75 9.5 12 13.75l4.25-4.25\" />\n          </g>\n          <path d=\"M4.25 14.5v3.25c0 1.1.9 2 2 2h11.5c1.1 0 2-.9 2-2V14.5\" />\n        </motion.svg>\n        <motion.svg\n          viewBox=\"0 0 24 24\"\n          className=\"col-start-1 row-start-1 size-5\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={2}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          initial={false}\n          animate={view === \"done\" ? shown : hidden(reduceMotion)}\n          transition={ICON_SWAP}\n        >\n          <path d=\"m5 12.5 4.5 4.5L19 7\" />\n        </motion.svg>\n      </motion.span>\n\n      <motion.span layout=\"position\" transition={glide} className=\"relative\">\n        <Word visible={view === \"idle\"}>{label}</Word>\n        {/* A slot as wide as \"Cancel\" holds both the percent and the hover\n            swap, so neither the digits nor the swap nudge the icon. */}\n        <Word\n          visible={busy}\n          className={cn(\n            \"w-14 text-center tabular-nums\",\n            cancellable &&\n              \"group-hover:-translate-y-0.5 group-hover:opacity-0 group-hover:blur-[4px] group-focus-visible:-translate-y-0.5 group-focus-visible:opacity-0 group-focus-visible:blur-[4px]\",\n          )}\n        >\n          <motion.span>{percent}</motion.span>\n        </Word>\n        {/* Percent gives way to Cancel on hover or keyboard focus, which is\n            how the cancel action becomes discoverable. */}\n        <Word\n          visible={false}\n          className={cn(\n            \"w-14 text-center\",\n            cancellable &&\n              \"group-hover:translate-y-0 group-hover:opacity-100 group-hover:blur-[0px] group-focus-visible:translate-y-0 group-focus-visible:opacity-100 group-focus-visible:blur-[0px]\",\n          )}\n        >\n          Cancel\n        </Word>\n        <Word visible={view === \"done\"}>{doneLabel}</Word>\n      </motion.span>\n    </span>\n  );\n}\n\nconst shown = { scale: 1, opacity: 1, filter: \"blur(0px)\" };\nconst hidden = (reduceMotion: boolean | null) =>\n  reduceMotion\n    ? { scale: 1, opacity: 0, filter: \"blur(0px)\" }\n    : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" };\n\n// Enters over 200ms, leaves in 100ms, so two words never read as\n// overlapping. Hidden words leave the flow (pinned to the left edge) so only\n// the live one sizes the row.\nfunction Word({\n  visible,\n  className,\n  children,\n}: {\n  visible: boolean;\n  className?: string;\n  children: React.ReactNode;\n}) {\n  return (\n    <span\n      className={cn(\n        \"block whitespace-nowrap transition-[opacity,filter,translate] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity]\",\n        visible\n          ? \"relative translate-y-0 opacity-100 blur-[0px] duration-200\"\n          : \"absolute top-0 left-0 translate-y-0.5 opacity-0 blur-[4px] duration-100 motion-reduce:translate-y-0 motion-reduce:blur-[0px]\",\n        className,\n      )}\n    >\n      {children}\n    </span>\n  );\n}\n\n// Quick start, a long stall around 60% (the server thinking), then a fast\n// finish: roughly how a real download looks. [ms from start, progress]\nconst STEPS: [number, number][] = [\n  [150, 0.08],\n  [340, 0.19],\n  [560, 0.31],\n  [800, 0.44],\n  [1050, 0.56],\n  [1300, 0.61],\n  [1900, 0.64],\n  [2300, 0.7],\n  [2550, 0.81],\n  [2780, 0.9],\n  [2980, 0.96],\n  [3200, 1],\n];\n\nexport default function DownloadButtonDemo() {\n  const [status, setStatus] = useState<DownloadStatus>(\"idle\");\n  const [progress, setProgress] = useState(0);\n  const timers = useRef<ReturnType<typeof setTimeout>[]>([]);\n\n  const clear = () => {\n    timers.current.forEach(clearTimeout);\n    timers.current = [];\n  };\n\n  useEffect(() => clear, []);\n\n  const start = () => {\n    clear();\n    setProgress(0);\n    setStatus(\"downloading\");\n    for (const [at, value] of STEPS) {\n      // Up to 100ms of jitter, less than any gap between steps so order\n      // holds, keeps repeat runs from feeling canned.\n      const jitter = value === 1 ? 0 : Math.random() * 100;\n      timers.current.push(\n        setTimeout(() => {\n          setProgress(value);\n          if (value === 1) setStatus(\"done\");\n        }, at + jitter),\n      );\n    }\n  };\n\n  const cancel = () => {\n    clear();\n    setStatus(\"idle\");\n  };\n\n  const reset = useCallback(() => setStatus(\"idle\"), []);\n\n  return (\n    // 30px outer radius around 8px of padding hugs the 22px button radius.\n    <div className=\"flex w-[min(460px,100%)] items-center gap-4 rounded-[30px] bg-muted p-2 pl-5 shadow-raised\">\n      <div className=\"min-w-0 flex-1\">\n        <p className=\"truncate text-[15px] font-medium text-foreground\">\n          brand-assets.zip\n        </p>\n        <p className=\"text-[13px] text-muted-foreground tabular-nums\">24.8 MB</p>\n      </div>\n      <DownloadButton\n        status={status}\n        progress={progress}\n        onStart={start}\n        onCancel={cancel}\n        onReset={reset}\n        className=\"shrink-0 [&>button]:bg-background\"\n      />\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["buttons"],"docs":"From ui lab: https://lab.xevrion.dev/lab/download-button"}