{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "copy-button",
  "title": "Copy button",
  "description": "A Button that copies a value. Its icon rolls to a tick and its label to “Copied”, a status region says so, and it goes back after two seconds. Icon-only, it is named in a tooltip; a copy that fails shows an error.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/tooltip.json",
    "https://kinoui.com/r/announce.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/copy-button.tsx",
      "content": "'use client'\n\nimport { Button } from '@/registry/components/kino/button'\nimport {\n  Tooltip,\n  TooltipContent,\n  type TooltipContentProps,\n  TooltipTrigger,\n} from '@/registry/components/kino/tooltip'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { announce } from '@/registry/lib/announce'\nimport { mergeProps } from '@ui-sdk/react/primitive'\nimport {\n  cloneElement,\n  type ComponentProps,\n  type ReactElement,\n  type ReactNode,\n  useEffect,\n  useRef,\n  useState,\n} from 'react'\n\ntype CopyStatus = 'idle' | 'copied' | 'failed'\n\n/** What goes on the clipboard: the text, or a function read at the press that returns it or a promise of it. */\ntype CopyValue = string | (() => string | Promise<string>)\n\n/** The Copy button's element, or the one `render` gives, which takes its props and keeps its own. */\nfunction Rendered({\n  element,\n  ...props\n}: Record<string, unknown> & { element: ReactElement<Record<string, unknown>> }) {\n  return cloneElement(element, mergeProps(props, element.props))\n}\n\n/*\n * A Button that copies a value. Its icon rolls to a tick, its label changes to\n * \"Copied\", a status region says so, and after `timeout` it goes back. An\n * icon-only one is named in a tooltip, which says how the copy went.\n */\nfunction CopyButton({\n  value,\n  timeout = 2000,\n  icon,\n  copiedLabel = 'Copied',\n  failedLabel = 'Couldn’t copy',\n  tooltipProps,\n  render,\n  variant,\n  size,\n  children = 'Copy',\n  onClick,\n  'aria-label': ariaLabel,\n  ...props\n}: Omit<ComponentProps<typeof Button>, 'value' | 'render'> & {\n  /**\n   * What goes on the clipboard. A function is read at the press, for text that\n   * is only on the page; it may return a promise, for text it has to fetch.\n   */\n  value: CopyValue\n  /** How long the result shows before the button goes back, in ms. `Infinity` keeps it. */\n  timeout?: number\n  /** The icon at rest, in place of the copy icon. */\n  icon?: ReactNode\n  copiedLabel?: string\n  failedLabel?: string\n  /** An icon-only button's tooltip; its text is the button's `aria-label`, then the result. */\n  tooltipProps?: Omit<TooltipContentProps, 'children'>\n  /**\n   * The button to render in place of the Button, such as a `ToolbarButton` or\n   * a `SplitButtonAction`. Its own props win over the Copy button's.\n   */\n  render?: ReactElement\n}) {\n  const [status, setStatus] = useState<CopyStatus>('idle')\n  const [waiting, setWaiting] = useState(false)\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)\n  useEffect(() => () => clearTimeout(timer.current), [])\n\n  const copy = async (...args: Parameters<NonNullable<typeof onClick>>) => {\n    onClick?.(...args)\n    const result = await copyText(value, () => setWaiting(true))\n    clearTimeout(timer.current)\n    setWaiting(false)\n    setStatus(result)\n    announce(result === 'copied' ? copiedLabel : failedLabel)\n    if (Number.isFinite(timeout)) {\n      timer.current = setTimeout(() => setStatus('idle'), timeout)\n    }\n  }\n\n  const iconOnly = size?.startsWith('icon') ?? false\n  const name = ariaLabel ?? 'Copy'\n  // Each result is its own span, so the Button's swap rolls from one to the next.\n  const shownIcon = (\n    <span key={status} data-icon='inline-start' className='flex'>\n      {status === 'copied' ? (\n        <IconPlaceholder\n          lucide='CheckIcon'\n          tabler='IconCheck'\n          hugeicons='Tick02Icon'\n          phosphor='CheckIcon'\n          remixicon='RiCheckLine'\n          aria-hidden\n        />\n      ) : status === 'failed' ? (\n        <IconPlaceholder\n          lucide='CircleAlertIcon'\n          tabler='IconAlertCircle'\n          hugeicons='AlertCircleIcon'\n          phosphor='WarningCircleIcon'\n          remixicon='RiErrorWarningLine'\n          className='text-destructive'\n          aria-hidden\n        />\n      ) : (\n        (icon ?? (\n          <IconPlaceholder\n            lucide='CopyIcon'\n            tabler='IconCopy'\n            hugeicons='Copy01Icon'\n            phosphor='CopyIcon'\n            remixicon='RiFileCopyLine'\n            aria-hidden\n          />\n        ))\n      )}\n    </span>\n  )\n  const result =\n    status === 'copied' ? copiedLabel : status === 'failed' ? failedLabel : undefined\n\n  const buttonProps = {\n    'data-copy-button': '',\n    'data-copied': status === 'copied' ? '' : undefined,\n    'data-failed': status === 'failed' ? '' : undefined,\n    // A rendered button keeps its own look unless one is asked for, as a\n    // Split button's action takes the group's.\n    ...(variant || !render ? { variant: variant ?? 'ghost' } : null),\n    ...(size ? { size } : null),\n    ...(waiting ? { loading: true } : null),\n    'aria-label': iconOnly ? name : ariaLabel,\n    // The copy shows its own wait, so the Button never goes pending on its promise.\n    onClick: (...args: Parameters<NonNullable<typeof onClick>>) => {\n      void copy(...args)\n    },\n    ...props,\n    children: iconOnly ? (\n      shownIcon\n    ) : (\n      <>\n        {shownIcon}\n        {result ?? children}\n      </>\n    ),\n  }\n  const button = <Rendered element={render ?? <Button />} {...buttonProps} />\n\n  if (iconOnly) {\n    return (\n      // It stays open on the press, so the tooltip can say how it went.\n      <Tooltip closeOnPress={false}>\n        <TooltipTrigger render={button} />\n        <TooltipContent {...tooltipProps}>{result ?? name}</TooltipContent>\n      </Tooltip>\n    )\n  }\n\n  return button\n}\n\n/**\n * Puts `value` on the clipboard. Where the Clipboard API is missing or refuses,\n * as on plain http or in an iframe without `clipboard-write`, it copies a\n * selection instead. A value that throws or rejects, or a browser that refuses\n * every way, is a failure. `onWait` runs when the value is a promise.\n */\nasync function copyText(\n  value: CopyValue,\n  onWait?: () => void,\n): Promise<'copied' | 'failed'> {\n  let read: string | Promise<string>\n  try {\n    read = typeof value === 'function' ? value() : value\n  } catch {\n    return 'failed'\n  }\n  let text: string\n  if (typeof read === 'string') {\n    text = read\n  } else {\n    onWait?.()\n    // Safari allows a write only inside the press, so the text goes in as a\n    // promise; the browser waits for it.\n    if (await writeLater(read)) return 'copied'\n    try {\n      text = await read\n    } catch {\n      return 'failed'\n    }\n  }\n  try {\n    await navigator.clipboard.writeText(text)\n    return 'copied'\n  } catch {\n    return copyBySelection(text) ? 'copied' : 'failed'\n  }\n}\n\n/** Writes text that is still on its way, where the browser takes a `ClipboardItem`. */\nasync function writeLater(text: Promise<string>): Promise<boolean> {\n  if (typeof ClipboardItem === 'undefined' || !navigator.clipboard?.write) return false\n  try {\n    await navigator.clipboard.write([\n      new ClipboardItem({\n        'text/plain': text.then((done) => new Blob([done], { type: 'text/plain' })),\n      }),\n    ])\n    return true\n  } catch {\n    return false\n  }\n}\n\n/** The older way to copy: select the text in a hidden box and ask the browser to copy it. */\nfunction copyBySelection(text: string): boolean {\n  if (typeof document === 'undefined') return false\n  const focused = document.activeElement\n  const box = document.createElement('textarea')\n  box.value = text\n  box.setAttribute('readonly', '')\n  box.setAttribute('aria-hidden', 'true')\n  box.style.cssText = 'position:fixed;inset-block-start:0;opacity:0;pointer-events:none'\n  document.body.append(box)\n  box.select()\n  let copied: boolean\n  try {\n    // Deprecated, but still the only way to copy where the Clipboard API is refused.\n    copied = document.execCommand('copy')\n  } catch {\n    copied = false\n  }\n  box.remove()\n  if (focused instanceof HTMLElement) focused.focus({ preventScroll: true })\n  return copied\n}\n\nexport { CopyButton }\n\nexport { copyText }\n",
      "type": "registry:component",
      "target": "@components/kino/copy-button.tsx"
    }
  ],
  "type": "registry:component"
}