{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "confirm-button",
  "title": "Confirm button",
  "description": "A Button for an action that is hard to take back, confirmed in place. It grows into a question with Cancel beside the action, shows a spinner while the action runs, then says how it went, with Undo.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/cut.json",
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/announce.json",
    "https://kinoui.com/r/notice.json",
    "https://kinoui.com/r/settle.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/confirm-button.tsx",
      "content": "'use client'\n\nimport { Button } from '@/registry/components/kino/button'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { announce } from '@/registry/lib/announce'\nimport { CutTooltip } from '@/registry/lib/cut'\nimport { noticeIcon } from '@/registry/lib/notice'\nimport { settle } from '@/registry/lib/settle'\nimport { Swap, useSwapFocus } from '@/registry/lib/swap'\nimport {\n  type ComponentProps,\n  type FocusEvent,\n  type KeyboardEvent,\n  type MouseEvent,\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\ntype ButtonProps = ComponentProps<typeof Button>\ntype ConfirmSize = NonNullable<ButtonProps['size']>\n\n/** Where the button is: at rest, asking, running the action, or showing how it went. */\ntype ConfirmStatus = 'rest' | 'asking' | 'working' | 'done' | 'failed'\n\ntype ConfirmEvent = 'press' | 'cancel' | 'confirm' | 'succeed' | 'fail' | 'end'\n\n/** The size of the text buttons beside an icon-only one. */\nconst textSize = {\n  default: 'default',\n  xs: 'xs',\n  sm: 'sm',\n  lg: 'lg',\n  icon: 'default',\n  'icon-xs': 'xs',\n  'icon-sm': 'sm',\n  'icon-lg': 'lg',\n} as const satisfies Record<ConfirmSize, ConfirmSize>\n\n/** The result's height and text, the same as a button of its size, so nothing moves when it arrives. */\nconst resultSize = {\n  default: 'h-(--control-height) text-sm',\n  xs: 'h-(--control-height-xs) text-xs',\n  sm: 'h-(--control-height-sm) text-sm',\n  lg: 'h-(--control-height-lg) text-sm',\n}\n\n/*\n * A button for an action that is hard to take back, confirmed in place. It\n * grows into a question with Cancel beside the action, shows the Button's\n * spinner while the action runs, then says how it went, with Undo. Escape, a\n * press elsewhere and Tab away cancel the question; the result is announced\n * and goes back to rest after `timeout`, which waits while it is hovered or\n * focused.\n */\nfunction ConfirmButton({\n  onConfirm,\n  onUndo,\n  question = 'Delete?',\n  confirmSentence,\n  confirmLabel = 'Delete',\n  cancelLabel = 'Cancel',\n  doneLabel = 'Deleted',\n  failedLabel = 'Couldn’t delete',\n  undoLabel = 'Undo',\n  undoneLabel = 'Restored',\n  undoFailedLabel = 'Couldn’t undo',\n  retryLabel = 'Try again',\n  timeout = 5000,\n  variant = 'outline',\n  size = 'default',\n  className,\n  children,\n  ...props\n}: Omit<ButtonProps, 'onClick' | 'loading' | 'render'> & {\n  /** Runs the action. A promise keeps the spinner until it settles; a rejection shows `failedLabel`. */\n  onConfirm: () => unknown\n  /** Shows Undo in the result. A promise keeps Undo's spinner until it settles. */\n  onUndo?: () => unknown\n  /** What the question asks, beside Cancel and the action. */\n  question?: string\n  /** What a person is asked when an agent presses the confirm, as a whole sentence that names the thing. Without it, the `question`. */\n  confirmSentence?: string\n  /** The action's label in the question. Name what it does, never \"OK\". */\n  confirmLabel?: string\n  cancelLabel?: string\n  doneLabel?: string\n  failedLabel?: string\n  undoLabel?: string\n  /** What a screen reader hears once Undo has worked. */\n  undoneLabel?: string\n  undoFailedLabel?: string\n  retryLabel?: string\n  /** How long the result shows before the button goes back to rest, in ms. `Infinity` keeps it. */\n  timeout?: number\n}) {\n  const [status, setStatus] = useState<ConfirmStatus>('rest')\n  const [undoing, setUndoing] = useState(false)\n  const [undoFailed, setUndoFailed] = useState(false)\n  const [hovered, setHovered] = useState(false)\n  const [focused, setFocused] = useState(false)\n  const questionId = useId()\n  const rootRef = useRef<HTMLSpanElement>(null)\n  // Focus follows the change when it was inside, so it never falls to the page.\n  const followFocus = useSwapFocus(rootRef, status)\n  const run = useRef(0)\n\n  const go = useCallback(\n    (event: ConfirmEvent, follow?: boolean) => {\n      followFocus(follow)\n      setStatus((current) => confirmStatus(current, event))\n    },\n    [followFocus],\n  )\n\n  // A press anywhere else cancels the question.\n  useEffect(() => {\n    if (status !== 'asking') return\n    const press = (event: PointerEvent) => {\n      if (!rootRef.current?.contains(event.target as Node)) go('cancel', false)\n    }\n    document.addEventListener('pointerdown', press, true)\n    return () => document.removeEventListener('pointerdown', press, true)\n  }, [status, go])\n\n  // The result goes back to rest after `timeout`, but never while someone is reading it.\n  const resting = status === 'done' || status === 'failed'\n  const paused = hovered || focused || undoing\n  useEffect(() => {\n    if (!resting || paused || !Number.isFinite(timeout)) return\n    const timer = setTimeout(() => go('end'), timeout)\n    return () => clearTimeout(timer)\n  }, [resting, paused, timeout, go])\n\n  // A run that ends after the component has gone, or after another began, changes nothing.\n  useEffect(() => () => void (run.current += 1), [])\n\n  const confirm = (event: MouseEvent) => {\n    // The second press of a double click lands on whatever arrived under the pointer.\n    if (event.detail > 1) return\n    const id = ++run.current\n    go('confirm', true)\n    const finish = (ok: boolean) => {\n      if (run.current !== id) return\n      setUndoFailed(false)\n      go(ok ? 'succeed' : 'fail')\n      announce(ok ? doneLabel : failedLabel)\n    }\n    settle(onConfirm, finish)\n  }\n\n  const undo = () => {\n    setUndoing(true)\n    settle(onUndo, (ok) => {\n      setUndoing(false)\n      setUndoFailed(!ok)\n      announce(ok ? undoneLabel : undoFailedLabel)\n      if (ok) go('end')\n    })\n  }\n\n  const keyDown = (event: KeyboardEvent) => {\n    // A held key repeats its press, which would answer the question it just opened.\n    if (event.repeat && (event.key === 'Enter' || event.key === ' '))\n      event.preventDefault()\n    if (event.key === 'Escape' && status === 'asking') {\n      event.preventDefault()\n      event.stopPropagation()\n      go('cancel', true)\n    }\n  }\n\n  const blur = (event: FocusEvent) => {\n    const to = event.relatedTarget as Node | null\n    if (rootRef.current?.contains(to)) return\n    setFocused(false)\n    // Tab away cancels; focus lost to a part on its way out doesn't.\n    if (to && status === 'asking') go('cancel', false)\n  }\n\n  const shownSize = textSize[size ?? 'default']\n\n  let view: ReactNode\n  if (status === 'rest') {\n    view = (\n      <Button\n        data-focus-target=''\n        variant={variant}\n        size={size}\n        onClick={() => go('press', true)}\n        // Focus that returns here after the result keeps its place, even once the action is unavailable.\n        focusableWhenDisabled\n        {...props}\n      >\n        {children}\n      </Button>\n    )\n  } else if (status === 'asking' || status === 'working') {\n    view = (\n      <span\n        role='group'\n        aria-labelledby={questionId}\n        // A question too long for one line takes its own, and the buttons go below it.\n        className='inline-flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-2'\n      >\n        <span\n          id={questionId}\n          className={cn(\n            // It wraps, never truncates: what it asks is the point of the step.\n            'min-w-0 flex-[1_1_auto] pe-0.5 font-medium break-words text-pretty',\n            shownSize === 'xs' ? 'text-xs' : 'text-sm',\n          )}\n        >\n          {question}\n        </span>\n        <span className='flex shrink-0 items-center gap-1.5'>\n          <Button\n            data-focus-target={status === 'asking' ? '' : undefined}\n            variant='ghost'\n            size={shownSize}\n            disabled={status === 'working'}\n            onClick={(event) => {\n              // The second press of a double click on the button can land here.\n              if (event.detail <= 1) go('cancel', true)\n            }}\n          >\n            {cancelLabel}\n          </Button>\n          <Button\n            data-focus-target={status === 'working' ? '' : undefined}\n            variant='destructive'\n            size={shownSize}\n            loading={status === 'working'}\n            data-agent-confirm={confirmSentence ?? question}\n            onClick={confirm}\n          >\n            {confirmLabel}\n          </Button>\n        </span>\n      </span>\n    )\n  } else {\n    const done = status === 'done'\n    view = (\n      <span className='inline-flex min-w-0 items-center gap-1.5'>\n        <CutTooltip\n          render={\n            <span\n              data-focus-target={done && !onUndo ? '' : undefined}\n              tabIndex={-1}\n              className={cn(\n                'inline-flex min-w-0 items-center gap-1.5 rounded-(--control-radius) px-(--control-padding) font-medium focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-hidden [&_svg]:size-4 [&_svg]:shrink-0',\n                resultSize[shownSize],\n              )}\n            >\n              {done && !undoFailed ? (\n                <IconPlaceholder\n                  lucide='CheckIcon'\n                  tabler='IconCheck'\n                  hugeicons='Tick02Icon'\n                  phosphor='CheckIcon'\n                  remixicon='RiCheckLine'\n                  aria-hidden\n                />\n              ) : (\n                noticeIcon('error', undefined)\n              )}\n              <span data-cut className='min-w-0 truncate'>\n                {done ? (undoFailed ? undoFailedLabel : doneLabel) : failedLabel}\n              </span>\n            </span>\n          }\n        />\n        {done && onUndo ? (\n          <Button\n            data-focus-target=''\n            variant='ghost'\n            size={shownSize}\n            loading={undoing}\n            onClick={undo}\n          >\n            {undoLabel}\n          </Button>\n        ) : null}\n        {done ? null : (\n          <Button\n            data-focus-target=''\n            variant='ghost'\n            size={shownSize}\n            // It runs the action again, which a person agreed to once.\n            data-agent-confirm={confirmSentence ?? question}\n            onClick={confirm}\n          >\n            {retryLabel}\n          </Button>\n        )}\n      </span>\n    )\n  }\n\n  return (\n    // oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- it hears what bubbles from its parts: Escape, a held key's repeats, a press beside its buttons, focus and hover\n    <span\n      ref={rootRef}\n      data-slot='confirm-button'\n      data-status={status}\n      className={cn('inline-flex max-w-full min-w-0', className)}\n      onKeyDown={keyDown}\n      // A press on the question or a gap, such as a double click's second,\n      // keeps focus on Cancel, where Escape still cancels.\n      onMouseDown={(event) => {\n        if (status === 'asking' && !(event.target as Element).closest('button')) {\n          event.preventDefault()\n        }\n      }}\n      // Only focus a person can see holds the result: focus moved after a pointer press doesn't.\n      onFocus={(event) => setFocused(event.target.matches(':focus-visible'))}\n      onBlur={blur}\n      onPointerEnter={() => setHovered(true)}\n      onPointerLeave={() => setHovered(false)}\n    >\n      {/* A block, so a question that wraps onto a second line grows the height on `layout` too. */}\n      <Swap align='start' block id={viewOf(status)} className='max-w-full'>\n        {view}\n      </Swap>\n    </span>\n  )\n}\n\n/** The status after `event`; an event that doesn't apply where the button is changes nothing. */\nfunction confirmStatus(status: ConfirmStatus, event: ConfirmEvent): ConfirmStatus {\n  switch (event) {\n    case 'press':\n      return status === 'rest' ? 'asking' : status\n    case 'cancel':\n      return status === 'asking' ? 'rest' : status\n    case 'confirm':\n      return status === 'asking' || status === 'failed' ? 'working' : status\n    case 'succeed':\n      return status === 'working' ? 'done' : status\n    case 'fail':\n      return status === 'working' ? 'failed' : status\n    case 'end':\n      return status === 'done' || status === 'failed' ? 'rest' : status\n  }\n}\n\n/** Which view shows: the question stays while its action runs, so only the button inside changes. */\nfunction viewOf(status: ConfirmStatus) {\n  return status === 'working' ? 'asking' : status\n}\n\nexport { ConfirmButton, confirmStatus, viewOf }\nexport type { ConfirmEvent, ConfirmStatus }\n",
      "type": "registry:component",
      "target": "@components/kino/confirm-button.tsx"
    }
  ],
  "type": "registry:component"
}