{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"copy-button","type":"registry:component","title":"Copy button","description":"Copies on the press: the icon blurs into a self-drawing check, the label morphs to Copied, and a failed copy shakes and says so.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/copy-button.tsx","type":"registry:component","content":"// Hairline UI · copy-button · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { Copy } from \"lucide-react\";\nimport { TextMorph } from \"./text-morph\";\nimport { EASE_OUT, INTERACTION_FOCUS, INTERACTION_PRESS, interactionIcon, useInteractionReducedMotion } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * COPY BUTTON: copies, and says so the moment you press\n *\n *   idle     the copy icon (and \"Copy\" when labelled)\n *   copied   flips on the press itself, not after the clipboard\n *            answers: the icon blurs out, a check draws itself,\n *            \"Copy\" morphs to \"Copied\" and the pill eases wider\n *   error    if the clipboard refuses, the check gives way to an\n *            alert, the label says \"Failed\" and the button shakes\n *\n * Pressing again while copied copies again and restarts the timer.\n * A status region outside the button tells screen readers.\n * ───────────────────────────────────────────────────────── */\n\nexport type CopyState = \"idle\" | \"copied\" | \"error\";\n\nexport interface CopyButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, \"children\"> {\n  /** The text to copy. */\n  text: string;\n  /** Label while idle; also the icon-only button's accessible name. */\n  label?: string;\n  /** Label once copied. */\n  copiedLabel?: string;\n  /** Label if the clipboard refuses. */\n  errorLabel?: string;\n  /** Show the label beside the icon. Defaults to false (icon only). */\n  showLabel?: boolean;\n  /** How long \"Copied\" stays before it returns to idle (ms). */\n  timeoutMs?: number;\n  variant?: \"secondary\" | \"outline\" | \"ghost\";\n  /** xs 24px, sm 28px, md 36px tall. */\n  size?: \"xs\" | \"sm\" | \"md\";\n  onCopySuccess?: (text: string) => void;\n  onCopyError?: (error: unknown) => void;\n}\n\nconst SIZES = {\n  xs: { square: \"size-6\", pill: \"h-6 pl-2 pr-2.5 text-[12px]\", icon: 12, gap: 5 },\n  sm: { square: \"size-7\", pill: \"h-7 pl-2.5 pr-3 text-[12px]\", icon: 13, gap: 6 },\n  md: { square: \"size-9\", pill: \"h-9 pl-3.5 pr-4 text-[13px]\", icon: 15, gap: 7 },\n};\n\nconst TONES = {\n  secondary: \"bg-card text-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent\",\n  outline: \"bg-transparent text-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent\",\n  ghost: \"bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground\",\n};\n\nconst ERROR_TONE =\n  \"bg-red-500/10 text-red-600 shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--color-red-500)_30%,transparent)] dark:text-red-400\";\n\nfunction writeClipboard(text: string): Promise<void> {\n  if (navigator.clipboard?.writeText) return navigator.clipboard.writeText(text);\n  // Older browsers and plain-http pages: the selection fallback.\n  return new Promise((resolve, reject) => {\n    const area = document.createElement(\"textarea\");\n    area.value = text;\n    area.setAttribute(\"readonly\", \"\");\n    area.style.cssText = \"position:fixed;top:0;left:0;opacity:0;pointer-events:none\";\n    document.body.appendChild(area);\n    area.select();\n    const ok = document.execCommand(\"copy\");\n    area.remove();\n    if (ok) resolve();\n    else reject(new Error(\"Copy was refused\"));\n  });\n}\n\nfunction Check({ drawn, reduced }: { drawn: boolean; reduced: boolean }) {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-full\">\n      <path\n        d=\"M3.5 8.5 6.5 11.5 12.5 4.5\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        pathLength={1}\n        strokeDasharray={1}\n        style={{\n          strokeDashoffset: drawn ? 0 : 1,\n          // Draws on the way in; on the way out it stays whole until its layer has faded.\n          transition: reduced ? \"none\" : drawn ? `stroke-dashoffset 360ms ${EASE_OUT} 70ms` : \"stroke-dashoffset 0ms linear 300ms\",\n        }}\n      />\n    </svg>\n  );\n}\n\nfunction Alert() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-full\">\n      <circle cx=\"8\" cy=\"8\" r=\"6.25\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n      <path d=\"M8 4.75v3.75\" stroke=\"currentColor\" strokeWidth=\"1.75\" strokeLinecap=\"round\" />\n      <circle cx=\"8\" cy=\"11\" r=\"1\" fill=\"currentColor\" />\n    </svg>\n  );\n}\n\nexport function CopyButton({\n  text,\n  label = \"Copy\",\n  copiedLabel = \"Copied\",\n  errorLabel = \"Failed\",\n  showLabel = false,\n  timeoutMs = 2000,\n  variant = \"ghost\",\n  size = \"sm\",\n  onCopySuccess,\n  onCopyError,\n  className = \"\",\n  disabled,\n  onClick,\n  ...props\n}: CopyButtonProps) {\n  const reduced = useInteractionReducedMotion();\n  const ref = React.useRef<HTMLButtonElement>(null);\n  const [state, setState] = React.useState<CopyState>(\"idle\");\n  // Bumped on every copy so a second press restarts the timer.\n  const [stamp, setStamp] = React.useState(0);\n\n  React.useEffect(() => {\n    if (state === \"idle\") return;\n    const timer = window.setTimeout(() => setState(\"idle\"), timeoutMs);\n    return () => window.clearTimeout(timer);\n  }, [state, stamp, timeoutMs]);\n\n  React.useEffect(() => {\n    if (state !== \"error\" || reduced) return;\n    ref.current?.animate(\n      [{ transform: \"none\" }, { transform: \"translateX(-4px)\" }, { transform: \"translateX(4px)\" }, { transform: \"translateX(-2px)\" }, { transform: \"none\" }],\n      { duration: 380, easing: \"ease-out\" },\n    );\n  }, [state, stamp, reduced]);\n\n  const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {\n    onClick?.(e);\n    if (e.defaultPrevented || disabled || !text) return;\n    // Optimistic: the feedback lands on the press, the clipboard catches up.\n    setState(\"copied\");\n    setStamp((n) => n + 1);\n    writeClipboard(text).then(\n      () => onCopySuccess?.(text),\n      (error: unknown) => {\n        setState(\"error\");\n        setStamp((n) => n + 1);\n        onCopyError?.(error);\n      },\n    );\n  };\n\n  const s = SIZES[size];\n  const current = state === \"copied\" ? copiedLabel : state === \"error\" ? errorLabel : label;\n\n  return (\n    <>\n      <button\n        ref={ref}\n        type=\"button\"\n        disabled={disabled}\n        onClick={handleClick}\n        aria-label={showLabel ? undefined : label}\n        data-state={state}\n        className={`relative inline-flex shrink-0 select-none items-center justify-center whitespace-nowrap rounded-full font-medium cursor-pointer disabled:cursor-default disabled:opacity-45 ${INTERACTION_PRESS} ${INTERACTION_FOCUS} ${\n          state === \"error\" ? ERROR_TONE : TONES[variant]\n        } ${showLabel ? s.pill : s.square} ${className}`}\n        {...props}\n      >\n        <span aria-hidden=\"true\" className=\"relative shrink-0\" style={{ width: s.icon, height: s.icon }}>\n          <span className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(state === \"idle\", reduced)}>\n            <Copy size={s.icon} strokeWidth={1.75} />\n          </span>\n          <span className=\"absolute inset-0 text-emerald-600 dark:text-emerald-400\" style={interactionIcon(state === \"copied\", reduced)}>\n            <Check drawn={state === \"copied\"} reduced={reduced} />\n          </span>\n          <span className=\"absolute inset-0\" style={interactionIcon(state === \"error\", reduced)}>\n            <Alert />\n          </span>\n        </span>\n        {showLabel && <TextMorph style={{ marginLeft: s.gap }}>{current}</TextMorph>}\n      </button>\n      {/* Outside the button, so the announcement isn't read as part of its name. */}\n      <span role=\"status\" className=\"sr-only\">\n        {state === \"idle\" ? \"\" : current}\n      </span>\n    </>\n  );\n}\n\nexport default CopyButton;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · copy-button · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/copy-button. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}