{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "copy-button",
  "title": "Copy button",
  "description": "Copy-to-clipboard button whose icon blurs from copy into a drawn check with a popping Copied! tooltip, plus a fallback when the Clipboard API is blocked.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json",
    "https://goodui.dev/r/sounds.json"
  ],
  "files": [
    {
      "path": "registry/components/buttons/copy-button.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\"\nimport { Copy } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport type { SoundName } from \"@/lib/goodui-sounds\"\nimport { GooduiTokens, spring } from \"@/lib/goodui-motion\"\n\nconst VARIANTS = {\n  ghost: \"text-muted-foreground hover:bg-muted hover:text-foreground\",\n  outline: \"border bg-background text-foreground shadow-xs hover:bg-muted dark:bg-input/30 dark:hover:bg-input/50\",\n  secondary: \"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n  default: \"bg-primary text-primary-foreground shadow-[var(--pc-e1)] hover:bg-primary/90\",\n} as const\n\nconst SIZES = {\n  \"icon-sm\": \"size-7 rounded-md [&_svg]:size-3.5\",\n  icon: \"size-9 rounded-lg [&_svg]:size-4\",\n  sm: \"h-8 gap-1.5 rounded-md px-2.5 text-xs [&_svg]:size-3.5\",\n  md: \"h-9 gap-2 rounded-lg px-3.5 text-sm [&_svg]:size-4\",\n} as const\n\ntype Status = \"idle\" | \"copied\" | \"failed\"\n\nexport type CopyButtonLabels = {\n  /** Default hint (tooltip and aria-label of icon-only buttons); the hint prop overrides it. */\n  hint: string\n  /** Default visible text after copying; the copiedLabel prop overrides it. */\n  copied: string\n  /** Default tooltip when copying is blocked; gets whether the user is on a Mac. The failedLabel prop overrides it. */\n  blocked: (mac: boolean) => string\n  /** Screen reader announcement after a successful copy. */\n  copiedAnnouncement: string\n  /** Screen reader announcement when copying failed. */\n  failedAnnouncement: string\n}\nconst DEFAULT_LABELS: CopyButtonLabels = {\n  hint: \"Copy\",\n  copied: \"Copied!\",\n  blocked: (mac) => (mac ? \"Copy blocked · press ⌘C\" : \"Copy blocked · press Ctrl+C\"),\n  copiedAnnouncement: \"Copied to clipboard\",\n  failedAnnouncement: \"Copy failed. Select the text and press Control C.\",\n}\n\n/** Clipboard API first; falls back to a hidden textarea + execCommand for insecure contexts and old browsers. */\nasync function writeClipboard(text: string) {\n  try {\n    if (navigator.clipboard && window.isSecureContext) {\n      await navigator.clipboard.writeText(text)\n      return true\n    }\n  } catch {\n    /* fall through */\n  }\n  const active = document.activeElement as HTMLElement | null\n  try {\n    const ta = document.createElement(\"textarea\")\n    ta.value = text\n    ta.setAttribute(\"readonly\", \"\")\n    Object.assign(ta.style, { position: \"fixed\", top: \"0\", left: \"-9999px\", opacity: \"0\", pointerEvents: \"none\" })\n    document.body.appendChild(ta)\n    ta.select()\n    const ok = document.execCommand(\"copy\")\n    ta.remove()\n    return ok\n  } catch {\n    return false\n  } finally {\n    active?.focus({ preventScroll: true })\n  }\n}\n\nexport type CopyButtonProps = Omit<React.ComponentProps<\"button\">, \"value\" | \"onCopy\"> & {\n  /** Text to copy, or a function that returns it (can be async). */\n  value: string | (() => string | Promise<string>)\n  /** Milliseconds the \"copied\" state stays. */\n  timeout?: number\n  /** Called with the copied text after a successful copy. */\n  onCopied?: (text: string) => void\n  /** Called with the text when both the Clipboard API and the fallback fail, or with \"\" when the value function throws or rejects. */\n  onCopyError?: (text: string) => void\n  /** Visible text beside the icon; leave empty for an icon-only button. */\n  label?: React.ReactNode\n  /** Text shown in the tooltip (and the label) after copying. */\n  copiedLabel?: string\n  /** Tooltip text when copying is blocked; defaults to a ⌘C / Ctrl+C hint. */\n  failedLabel?: string\n  /** Hint shown in the tooltip on hover for icon-only buttons. */\n  hint?: string\n  /** \"ghost\" | \"outline\" | \"secondary\" | \"default\". Ghost also turns the icon emerald after copying. */\n  variant?: keyof typeof VARIANTS\n  /** \"icon-sm\" | \"icon\" | \"sm\" | \"md\". Defaults to \"icon-sm\" without a label and \"sm\" with one. */\n  size?: keyof typeof SIZES\n  /** Show the floating tooltip. */\n  tooltip?: boolean\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<CopyButtonLabels>\n  /** Plays \"pop\" after a copy (and \"error\" when it fails) when the visitor has sounds on (lib/goodui-sounds); a sound name replaces the pop. Off by default. */\n  sound?: boolean | SoundName\n}\n\n// Optional UI sound: the sound module is loaded only when `sound` is on, so silent apps pay nothing.\nfunction useCue(sound: boolean | SoundName | undefined) {\n  React.useEffect(() => {\n    if (sound) void import(\"@/lib/goodui-sounds\")\n  }, [sound])\n  return React.useCallback(\n    (fallback: SoundName, o?: { rate?: number; exact?: boolean }) => {\n      if (!sound) return\n      void import(\"@/lib/goodui-sounds\").then((m) => m.play(sound === true || o?.exact ? fallback : sound, { rate: o?.rate }))\n    },\n    [sound],\n  )\n}\n\nfunction CheckDraw({ reduce }: { reduce: boolean }) {\n  return (\n    <svg viewBox=\"0 0 24 24\" fill=\"none\" aria-hidden=\"true\">\n      <motion.path\n        d=\"M4.5 12.5 9.5 17.5 19.5 6.5\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2.4\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        initial={reduce ? false : { pathLength: 0 }}\n        animate={{ pathLength: 1 }}\n        transition={{ duration: 0.25, delay: 0.05, ease: \"easeOut\" }}\n      />\n    </svg>\n  )\n}\n\nfunction XDraw() {\n  return (\n    <svg viewBox=\"0 0 24 24\" fill=\"none\" aria-hidden=\"true\">\n      <path d=\"M7 7l10 10M17 7 7 17\" stroke=\"currentColor\" strokeWidth=\"2.4\" strokeLinecap=\"round\" />\n    </svg>\n  )\n}\n\n/** Copy-to-clipboard button: icon morphs copy → check, a \"Copied!\" tooltip pops, with a fallback when the Clipboard API is blocked. */\nexport function CopyButton({\n  value,\n  timeout = 1600,\n  onCopied,\n  onCopyError,\n  label,\n  copiedLabel: copiedLabelProp,\n  failedLabel,\n  hint: hintProp,\n  variant = \"ghost\",\n  size,\n  tooltip = true,\n  labels,\n  sound,\n  className,\n  onClick,\n  onPointerEnter,\n  onPointerLeave,\n  onFocus,\n  onBlur,\n  \"aria-label\": ariaLabel,\n  ...props\n}: CopyButtonProps) {\n  const l = useLabels(\"copy-button\", DEFAULT_LABELS, labels)\n  const copiedLabel = copiedLabelProp ?? l.copied\n  const hint = hintProp ?? l.hint\n  const reduce = useReducedMotion() ?? false\n  const cue = useCue(sound)\n  const [status, setStatus] = React.useState<Status>(\"idle\")\n  const [hover, setHover] = React.useState(false)\n  const [mac, setMac] = React.useState(false)\n  const timer = React.useRef(0)\n  const sz = size ?? (label ? \"sm\" : \"icon-sm\")\n\n  React.useEffect(() => () => window.clearTimeout(timer.current), [])\n\n  const copy = async () => {\n    let text = \"\"\n    let ok = false\n    try {\n      text = typeof value === \"function\" ? await value() : value\n      ok = await writeClipboard(text)\n    } catch {\n      // The value function threw or rejected: show the failed state instead of an unhandled rejection.\n      ok = false\n    }\n    if (!ok) setMac(/Mac|iPhone|iPad/.test(navigator.userAgent))\n    setStatus(ok ? \"copied\" : \"failed\")\n    if (ok) cue(\"pop\")\n    else cue(\"error\", { exact: true })\n    if (ok) onCopied?.(text)\n    else onCopyError?.(text)\n    window.clearTimeout(timer.current)\n    timer.current = window.setTimeout(() => setStatus(\"idle\"), ok ? timeout : timeout + 1200)\n  }\n\n  const tip = status === \"copied\" ? copiedLabel : status === \"failed\" ? (failedLabel ?? l.blocked(mac)) : hover && !label ? hint : null\n  const pop = reduce ? { duration: 0.1 } : spring.play\n\n  return (\n    <span className=\"relative inline-flex\">\n      <GooduiTokens />\n      <button\n        type=\"button\"\n        data-slot=\"button\"\n        data-status={status}\n        aria-label={ariaLabel ?? (label ? undefined : hint)}\n        onClick={(e) => {\n          onClick?.(e)\n          if (!e.defaultPrevented) void copy()\n        }}\n        onPointerEnter={(e) => {\n          if (e.pointerType === \"mouse\") setHover(true)\n          onPointerEnter?.(e)\n        }}\n        onPointerLeave={(e) => {\n          setHover(false)\n          onPointerLeave?.(e)\n        }}\n        onFocus={(e) => {\n          if (e.currentTarget.matches(\":focus-visible\")) setHover(true)\n          onFocus?.(e)\n        }}\n        onBlur={(e) => {\n          setHover(false)\n          onBlur?.(e)\n        }}\n        className={cn(\n          \"pc-press relative inline-flex shrink-0 items-center justify-center font-medium whitespace-nowrap transition-[background-color,color,box-shadow,transform] outline-none select-none focus-visible:ring-3 focus-visible:ring-ring/50 active:scale-95 disabled:pointer-events-none disabled:opacity-50 [&_svg]:shrink-0\",\n          VARIANTS[variant],\n          SIZES[sz],\n          status === \"copied\" && variant === \"ghost\" && \"text-emerald-700 hover:text-emerald-700 dark:text-emerald-400 dark:hover:text-emerald-400\",\n          className,\n        )}\n        {...props}\n      >\n        <span className=\"relative grid place-items-center [&>*]:col-start-1 [&>*]:row-start-1\">\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            <motion.span\n              key={status}\n              className=\"grid place-items-center\"\n              initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.4, filter: \"blur(3px)\" }}\n              animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n              exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.4, filter: \"blur(3px)\" }}\n              transition={pop}\n            >\n              {status === \"copied\" ? <CheckDraw reduce={reduce} /> : status === \"failed\" ? <XDraw /> : <Copy />}\n            </motion.span>\n          </AnimatePresence>\n        </span>\n        {label && <span>{status === \"copied\" ? copiedLabel : label}</span>}\n      </button>\n      {tooltip && (\n        <AnimatePresence>\n          {tip && (\n            <motion.span\n              key={status === \"idle\" ? \"hint\" : status}\n              aria-hidden=\"true\"\n              initial={reduce ? { opacity: 0 } : { opacity: 0, y: 4, scale: 0.85 }}\n              animate={{ opacity: 1, y: 0, scale: 1 }}\n              exit={reduce ? { opacity: 0 } : { opacity: 0, y: 2, scale: 0.9, transition: { duration: 0.1 } }}\n              transition={pop}\n              className={cn(\n                \"pointer-events-none absolute bottom-full left-1/2 z-50 mb-2 -translate-x-1/2 rounded-md px-2 py-1 text-xs font-medium whitespace-nowrap shadow-[var(--pc-e2)]\",\n                // emerald-700 and a darkened destructive in dark mode keep the white text at 4.5:1.\n                status === \"copied\"\n                  ? \"bg-emerald-700 text-white\"\n                  : status === \"failed\"\n                    ? \"bg-destructive text-white dark:bg-[color-mix(in_oklab,var(--destructive)_75%,black)]\"\n                    : \"bg-foreground text-background\",\n              )}\n            >\n              {tip}\n              <span className=\"absolute top-full left-1/2 -mt-1 size-2 -translate-x-1/2 rotate-45 rounded-[1px] bg-inherit\" />\n            </motion.span>\n          )}\n        </AnimatePresence>\n      )}\n      <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {status === \"copied\" ? l.copiedAnnouncement : status === \"failed\" ? l.failedAnnouncement : \"\"}\n      </span>\n    </span>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/copy-button.tsx"
    }
  ],
  "categories": [
    "components",
    "buttons"
  ],
  "type": "registry:component"
}