{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "undoable",
  "title": "Undoable",
  "description": "Wraps a list item or table row. Removing it collapses the row in place to a label and an Undo button at the same height, then runs onConfirm when the undo window ends.",
  "dependencies": [
    "@base-ui/react"
  ],
  "registryDependencies": [
    "button"
  ],
  "files": [
    {
      "path": "components/ui/sureui/confirmation.ts",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\ntype Fill = {\n  from: number\n  to: number\n  duration: number\n  startedAt: number\n  easing?: string\n}\n\nfunction prefersReducedMotion() {\n  return (\n    typeof window.matchMedia === \"function\" &&\n    window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n  )\n}\n\nfunction keyframes(element: Element, fill: Fill) {\n  if (element instanceof SVGElement)\n    return [\n      { strokeDashoffset: `${1 - fill.from}` },\n      { strokeDashoffset: `${1 - fill.to}` },\n    ]\n  return [{ scale: `${fill.from} 1` }, { scale: `${fill.to} 1` }]\n}\n\nfunction playFill(element: Element | null, fill: Fill) {\n  if (!element || typeof element.animate !== \"function\") return null\n  const animation = element.animate(keyframes(element, fill), {\n    duration: fill.duration,\n    easing: prefersReducedMotion() ? \"step-end\" : (fill.easing ?? \"linear\"),\n    fill: \"forwards\",\n  })\n  animation.currentTime = performance.now() - fill.startedAt\n  return animation\n}\n\nfunction useFill(\n  ref: React.RefObject<Element | null>,\n  fill: Fill | null,\n  paused: boolean\n) {\n  const animationRef = React.useRef<Animation | null>(null)\n\n  React.useEffect(() => {\n    if (!fill) return\n    const animation = playFill(ref.current, fill)\n    animationRef.current = animation\n    return () => {\n      animation?.cancel()\n      animationRef.current = null\n    }\n  }, [ref, fill])\n\n  React.useEffect(() => {\n    const animation = animationRef.current\n    if (paused) animation?.pause()\n    else if (animation?.playState === \"paused\") animation.play()\n  }, [paused, fill])\n}\n\ntype UndoPauseReason = \"hover\" | \"focus\" | \"hidden\"\n\ntype UndoDuration = boolean | number | \"manual\"\n\ntype UndoWindowOptions = {\n  duration?: UndoDuration\n  onExpire: () => void\n  onPauseChange?: (paused: boolean) => void\n  within?: () => Element | null\n}\n\ntype UndoWindow = {\n  duration: number\n  manual: boolean\n  elapsed: () => number\n  paused: () => boolean\n  pause: (reason: UndoPauseReason) => void\n  resume: (reason: UndoPauseReason) => void\n  cancel: () => void\n}\n\nfunction undoDuration(value: UndoDuration | undefined) {\n  if (typeof value !== \"number\" || !Number.isFinite(value)) return 5000\n  return Math.min(Math.max(value, 4000), 60000)\n}\n\nfunction startManualWindow({\n  onExpire,\n  within,\n}: UndoWindowOptions): UndoWindow {\n  let open = true\n\n  function stop() {\n    open = false\n    document.removeEventListener(\"pointerdown\", onOutside, true)\n    document.removeEventListener(\"focusin\", onOutside, true)\n  }\n\n  function onOutside(event: Event) {\n    const container = within?.()\n    const target = event.target\n    if (!open || !container || !(target instanceof Node)) return\n    if (container.contains(target)) return\n    stop()\n    onExpire()\n  }\n\n  if (within) {\n    document.addEventListener(\"pointerdown\", onOutside, true)\n    document.addEventListener(\"focusin\", onOutside, true)\n  }\n\n  return {\n    duration: Infinity,\n    manual: true,\n    elapsed: () => 0,\n    paused: () => false,\n    pause: () => {},\n    resume: () => {},\n    cancel: stop,\n  }\n}\n\nfunction startUndoWindow(options: UndoWindowOptions): UndoWindow {\n  const { duration, onExpire, onPauseChange } = options\n  if (duration === \"manual\") return startManualWindow(options)\n  const total = undoDuration(duration)\n  const pausedBy = new Set<UndoPauseReason>()\n  let open = true\n  let remaining = total\n  let startedAt = performance.now()\n  let timer = setTimeout(expire, remaining)\n\n  function stop() {\n    open = false\n    clearTimeout(timer)\n    document.removeEventListener(\"visibilitychange\", onVisibilityChange)\n  }\n\n  function expire() {\n    stop()\n    onExpire()\n  }\n\n  function pause(reason: UndoPauseReason) {\n    if (!open || pausedBy.has(reason)) return\n    pausedBy.add(reason)\n    if (pausedBy.size > 1) return\n    clearTimeout(timer)\n    remaining -= performance.now() - startedAt\n    onPauseChange?.(true)\n  }\n\n  function resume(reason: UndoPauseReason) {\n    if (!open || !pausedBy.delete(reason) || pausedBy.size > 0) return\n    startedAt = performance.now()\n    timer = setTimeout(expire, remaining)\n    onPauseChange?.(false)\n  }\n\n  function onVisibilityChange() {\n    if (document.visibilityState === \"hidden\") pause(\"hidden\")\n    else resume(\"hidden\")\n  }\n\n  document.addEventListener(\"visibilitychange\", onVisibilityChange)\n  onVisibilityChange()\n\n  return {\n    duration: total,\n    manual: false,\n    elapsed: () =>\n      total -\n      remaining +\n      (pausedBy.size > 0 ? 0 : performance.now() - startedAt),\n    paused: () => pausedBy.size > 0,\n    pause,\n    resume,\n    cancel: stop,\n  }\n}\n\ntype ConfirmationState = \"idle\" | \"armed\" | \"holding\" | \"undo\" | \"pending\"\n\ntype PauseReason = \"hover\" | \"focus\"\n\ntype InlineUndo = {\n  window: UndoWindow\n  pausable: Set<PauseReason>\n}\n\ninterface ConfirmationOptions {\n  onConfirm: () => void | Promise<unknown>\n  onCancel?: () => void\n  onConfirmError?: (error: unknown) => void\n  undo?: boolean | number | \"manual\"\n  pauseUndoOnHover?: boolean\n  pauseUndoOnFocus?: boolean\n}\n\ninterface GestureOptions {\n  gesture?: \"click\" | \"click-again\" | \"hold\" | \"slide\"\n  timeout?: number\n  duration?: number\n  holdFallback?: \"click-again\" | \"none\"\n  armDelay?: number\n  wait?: number\n  disabled?: boolean\n}\n\ntype TriggerProps<T extends Element> = {\n  disabled?: boolean\n  onClick?(event: React.MouseEvent<T>): void\n  onBlur?(event: React.FocusEvent<T>): void\n  onFocus?(event: React.FocusEvent<T>): void\n  onPointerDown?(event: React.PointerEvent<T>): void\n  onPointerUp?(event: React.PointerEvent<T>): void\n  onPointerMove?(event: React.PointerEvent<T>): void\n  onPointerEnter?(event: React.PointerEvent<T>): void\n  onPointerLeave?(event: React.PointerEvent<T>): void\n  onPointerCancel?(event: React.PointerEvent<T>): void\n  onKeyDown?(event: React.KeyboardEvent<T>): void\n  onKeyUp?(event: React.KeyboardEvent<T>): void\n  onContextMenu?(event: React.MouseEvent<T>): void\n  onMouseDown?(event: React.MouseEvent<T>): void\n}\n\nfunction hasSelection() {\n  const selection = window.getSelection()\n  return !!selection && !selection.isCollapsed\n}\n\nfunction clearSelection() {\n  if (hasSelection()) window.getSelection()?.removeAllRanges()\n}\n\nfunction isPromise(value: unknown): value is PromiseLike<unknown> {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    typeof (value as PromiseLike<unknown>).then === \"function\"\n  )\n}\n\nfunction toMs(value: number, fallback: number, min: number) {\n  return Number.isFinite(value)\n    ? Math.min(Math.max(value, min), 60000)\n    : fallback\n}\n\nfunction composeHandlers<E>(\n  theirs: ((event: E) => void) | undefined,\n  ours: (event: E) => void\n) {\n  return (event: E) => {\n    theirs?.(event)\n    ours(event)\n  }\n}\n\nfunction isPressKey(event: React.KeyboardEvent) {\n  return event.key === \" \" || event.key === \"Enter\"\n}\n\nfunction isVirtualPress(event: React.PointerEvent) {\n  const { width, height, pressure, pointerType } = event.nativeEvent\n  const android = /Android/i.test(navigator.userAgent)\n  if (width < 1 && height < 1) return !android\n  return (\n    android &&\n    pointerType === \"mouse\" &&\n    width === 1 &&\n    height === 1 &&\n    pressure === 0\n  )\n}\n\nfunction useConfirmationMachine(\n  options: ConfirmationOptions,\n  triggerRef: React.RefObject<Element | null>\n) {\n  const [state, setState] = React.useState<ConfirmationState>(\"idle\")\n  const [fill, setFill] = React.useState<Fill | null>(null)\n  const [paused, setPaused] = React.useState(false)\n  const [failed, setFailed] = React.useState(false)\n  const [undoSeconds, setUndoSeconds] = React.useState<number | null>(null)\n  const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n  const holdStartRef = React.useRef(0)\n  const holdDurationRef = React.useRef(0)\n  const undoRef = React.useRef<InlineUndo | null>(null)\n  const optionsRef = React.useRef(options)\n\n  React.useEffect(() => {\n    optionsRef.current = options\n  })\n\n  const clearTimer = React.useCallback(() => {\n    undoRef.current?.window.cancel()\n    undoRef.current = null\n    if (timerRef.current !== null) {\n      clearTimeout(timerRef.current)\n      timerRef.current = null\n    }\n  }, [])\n\n  React.useEffect(() => clearTimer, [clearTimer])\n\n  const enter = React.useCallback(\n    (next: ConfirmationState, nextFill: Fill | null = null) => {\n      setState(next)\n      setFill(nextFill)\n      setPaused(false)\n      setFailed(false)\n    },\n    []\n  )\n\n  const fail = React.useCallback((error: unknown) => {\n    setFailed(true)\n    const { onConfirmError } = optionsRef.current\n    if (!onConfirmError) throw error\n    onConfirmError(error)\n  }, [])\n\n  const commit = React.useCallback(\n    (run: ConfirmationOptions[\"onConfirm\"]) => {\n      clearTimer()\n      let result: ReturnType<ConfirmationOptions[\"onConfirm\"]>\n      try {\n        result = run()\n      } catch (error) {\n        enter(\"idle\")\n        return fail(error)\n      }\n      if (isPromise(result)) {\n        enter(\"pending\")\n        ;(async () => {\n          try {\n            await result\n            setState(\"idle\")\n          } catch (error) {\n            setState(\"idle\")\n            fail(error)\n          }\n        })()\n      } else {\n        enter(\"idle\")\n      }\n    },\n    [clearTimer, enter, fail]\n  )\n\n  const confirm = React.useCallback(() => {\n    const { undo, onConfirm } = optionsRef.current\n    clearTimer()\n    if (!undo) return commit(onConfirm)\n    const undoWindow = startUndoWindow({\n      duration: undo,\n      onExpire: () => commit(onConfirm),\n      onPauseChange: setPaused,\n      within: () => triggerRef.current,\n    })\n    undoRef.current = { window: undoWindow, pausable: new Set() }\n    setUndoSeconds(\n      undoWindow.manual ? null : Math.ceil(undoWindow.duration / 1000)\n    )\n    enter(\n      \"undo\",\n      undoWindow.manual\n        ? null\n        : {\n            from: 1,\n            to: 0,\n            duration: undoWindow.duration,\n            startedAt: performance.now(),\n          }\n    )\n    setPaused(undoWindow.paused())\n  }, [commit, clearTimer, enter, triggerRef])\n\n  const pauseUndo = React.useCallback((reason: PauseReason) => {\n    const { pauseUndoOnHover = true, pauseUndoOnFocus = true } =\n      optionsRef.current\n    if (reason === \"hover\" ? !pauseUndoOnHover : !pauseUndoOnFocus) return\n    const undo = undoRef.current\n    if (undo?.pausable.has(reason)) undo.window.pause(reason)\n  }, [])\n\n  const resumeUndo = React.useCallback((reason: PauseReason) => {\n    const undo = undoRef.current\n    if (!undo) return\n    undo.pausable.add(reason)\n    undo.window.resume(reason)\n  }, [])\n\n  React.useEffect(() => {\n    const undo = undoRef.current?.window\n    if (state !== \"undo\" || paused || !undo || undo.manual) return\n    let timer: ReturnType<typeof setTimeout>\n    function tick() {\n      const left = undo!.duration - undo!.elapsed()\n      setUndoSeconds(Math.max(1, Math.ceil(left / 1000)))\n      timer = setTimeout(tick, (left % 1000 || 1000) + 1)\n    }\n    timer = setTimeout(\n      tick,\n      ((undo.duration - undo.elapsed()) % 1000 || 1000) + 1\n    )\n    return () => clearTimeout(timer)\n  }, [state, paused])\n\n  const arm = React.useCallback(() => {\n    clearTimer()\n    enter(\"armed\")\n  }, [clearTimer, enter])\n\n  const hold = React.useCallback(\n    (duration: number) => {\n      const ms = toMs(duration, 1200, 800)\n      holdStartRef.current = performance.now()\n      holdDurationRef.current = ms\n      enter(\"holding\", {\n        from: 0,\n        to: 1,\n        duration: ms,\n        startedAt: holdStartRef.current,\n      })\n      timerRef.current = setTimeout(confirm, ms)\n    },\n    [confirm, enter]\n  )\n\n  const slide = React.useCallback(\n    (fraction: number) => {\n      enter(\"holding\", {\n        from: fraction,\n        to: fraction,\n        duration: 0,\n        startedAt: performance.now(),\n      })\n    },\n    [enter]\n  )\n\n  const release = React.useCallback(\n    (from?: number) => {\n      const now = performance.now()\n      const fraction =\n        from ??\n        Math.min((now - holdStartRef.current) / holdDurationRef.current, 1)\n      clearTimer()\n      enter(\"idle\", {\n        from: fraction,\n        to: 0,\n        duration: 200,\n        startedAt: now,\n        easing: \"ease-out\",\n      })\n      optionsRef.current.onCancel?.()\n    },\n    [clearTimer, enter]\n  )\n\n  const cancel = React.useCallback(() => {\n    clearTimer()\n    enter(\"idle\")\n    optionsRef.current.onCancel?.()\n  }, [clearTimer, enter])\n\n  const reset = React.useCallback(() => {\n    clearTimer()\n    enter(\"idle\")\n  }, [clearTimer, enter])\n\n  return {\n    state,\n    fill,\n    paused,\n    failed,\n    arm,\n    hold,\n    slide,\n    release,\n    confirm,\n    cancel,\n    pauseUndo,\n    resumeUndo,\n    reset,\n    undoSeconds: state === \"undo\" ? undoSeconds : null,\n  }\n}\n\nfunction useConfirmation<\n  T extends Element = HTMLElement,\n  F extends Element = HTMLSpanElement,\n>({\n  gesture = \"click\",\n  timeout = 3000,\n  duration = 1200,\n  holdFallback = \"click-again\",\n  armDelay = 0,\n  wait = 0,\n  disabled = false,\n  ...options\n}: ConfirmationOptions & GestureOptions) {\n  const triggerRef = React.useRef<T | null>(null)\n  const {\n    state,\n    fill,\n    paused,\n    failed,\n    arm,\n    hold,\n    slide,\n    release,\n    confirm,\n    cancel,\n    pauseUndo,\n    resumeUndo,\n    reset,\n    undoSeconds,\n  } = useConfirmationMachine(options, triggerRef)\n  const fillRef = React.useRef<F>(null)\n  useFill(fillRef, fill, paused)\n  const [waiting, setWaiting] = React.useState(() => waitSeconds(wait))\n\n  React.useEffect(() => {\n    if (waiting <= 0) return\n    const timer = setTimeout(() => setWaiting((left) => left - 1), 1000)\n    return () => clearTimeout(timer)\n  }, [waiting])\n  const armDelayRef = React.useRef(armDelay)\n  const quietRef = React.useRef(false)\n  const quietTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n  const repeatRef = React.useRef(false)\n  const undoPressRef = React.useRef(false)\n  const pressRef = React.useRef<\"none\" | \"pointer\" | \"virtual\" | \"key\">(\"none\")\n  const fallbackRef = React.useRef(false)\n  const selectedRef = React.useRef(false)\n  const slideRef = React.useRef<{\n    id: number\n    startX: number\n    width: number\n    progress: number\n    moved: boolean\n  } | null>(null)\n  const slidClickRef = React.useRef(false)\n\n  React.useEffect(() => {\n    armDelayRef.current = armDelay\n  })\n\n  const quiet = React.useCallback(() => {\n    const ms = toMs(armDelayRef.current, 0, 0)\n    if (quietTimerRef.current !== null) clearTimeout(quietTimerRef.current)\n    quietTimerRef.current = null\n    quietRef.current = ms > 0\n    if (ms <= 0) return\n    quietTimerRef.current = setTimeout(() => {\n      quietTimerRef.current = null\n      quietRef.current = false\n    }, ms)\n  }, [])\n\n  React.useEffect(() => {\n    quiet()\n    return () => {\n      if (quietTimerRef.current !== null) clearTimeout(quietTimerRef.current)\n      quietTimerRef.current = null\n      quietRef.current = false\n    }\n  }, [quiet])\n\n  React.useEffect(() => {\n    if (state !== \"armed\") fallbackRef.current = false\n  }, [state])\n\n  React.useEffect(() => {\n    if (state !== \"armed\" || fallbackRef.current) return\n    const timer = setTimeout(cancel, toMs(timeout, 3000, 0))\n    return () => clearTimeout(timer)\n  }, [state, timeout, cancel])\n\n  const isHold = gesture === \"hold\"\n  const isSlide = gesture === \"slide\"\n  const isHolding = state === \"holding\"\n  const fallback = isHold && holdFallback === \"click-again\"\n  const fallbackArmed = state === \"armed\" && fallbackRef.current\n\n  function undoFromPress() {\n    if (state !== \"undo\" || !undoPressRef.current) return\n    undoPressRef.current = false\n    cancel()\n  }\n\n  function armNow() {\n    arm()\n    quiet()\n  }\n\n  function armFallback() {\n    fallbackRef.current = true\n    armNow()\n  }\n\n  function holdClick() {\n    const press = pressRef.current\n    pressRef.current = \"none\"\n    const unpressed = press === \"none\" || press === \"virtual\"\n    if (state === \"undo\") {\n      if (fallback && press === \"none\") undoPressRef.current = true\n      return undoFromPress()\n    }\n    if (!fallback) return\n    if (fallbackArmed) confirm()\n    else if (state === \"idle\" && unpressed) armFallback()\n  }\n\n  function endSlide(target: Element) {\n    const current = slideRef.current\n    if (!current) return\n    slideRef.current = null\n    if (target.hasPointerCapture?.(current.id))\n      target.releasePointerCapture(current.id)\n    if (!current.moved) return\n    slidClickRef.current = true\n    if (current.progress >= 1) confirm()\n    else release(current.progress)\n  }\n\n  const handlers: Required<Omit<TriggerProps<T>, \"disabled\">> = {\n    onClick() {\n      if (quietRef.current) return\n      if (slidClickRef.current) {\n        slidClickRef.current = false\n        return\n      }\n      if (isHold) return holdClick()\n      if (repeatRef.current) return\n      if (state === \"undo\") cancel()\n      else if (state === \"armed\") confirm()\n      else if (state === \"idle\" && gesture === \"click\") confirm()\n      else if (state === \"idle\") armNow()\n    },\n    onBlur() {\n      resumeUndo(\"focus\")\n      const sliding = slideRef.current\n      slideRef.current = null\n      if (isHolding) release(sliding?.progress)\n      else if (state === \"armed\") cancel()\n    },\n    onFocus() {\n      pauseUndo(\"focus\")\n    },\n    onPointerEnter() {\n      pauseUndo(\"hover\")\n    },\n    onPointerLeave() {\n      resumeUndo(\"hover\")\n      if (isHolding && !isSlide) release()\n    },\n    onPointerDown(event) {\n      selectedRef.current = hasSelection()\n      slidClickRef.current = false\n      if (isSlide) {\n        pressRef.current = isVirtualPress(event) ? \"virtual\" : \"pointer\"\n        if (event.button !== 0 || quietRef.current || state !== \"idle\") return\n        if (pressRef.current === \"virtual\") return\n        try {\n          event.currentTarget.setPointerCapture?.(event.pointerId)\n        } catch {}\n        slideRef.current = {\n          id: event.pointerId,\n          startX: event.clientX,\n          width: event.currentTarget.getBoundingClientRect().width,\n          progress: 0,\n          moved: false,\n        }\n        return\n      }\n      if (!isHold || event.button !== 0 || quietRef.current) return\n      pressRef.current = isVirtualPress(event) ? \"virtual\" : \"pointer\"\n      undoPressRef.current = state === \"undo\"\n      if (state !== \"idle\") return\n      const target = event.currentTarget\n      if (target.hasPointerCapture?.(event.pointerId))\n        target.releasePointerCapture(event.pointerId)\n      hold(duration)\n    },\n    onPointerMove(event) {\n      const current = slideRef.current\n      if (!current || current.id !== event.pointerId) return\n      const distance = event.clientX - current.startX\n      if (!current.moved && Math.abs(distance) < 4) return\n      current.moved = true\n      current.progress = Math.min(\n        Math.max(distance / (current.width * 0.85), 0),\n        1\n      )\n      slide(current.progress)\n    },\n    onPointerUp(event) {\n      if (event.pointerType === \"touch\" && !selectedRef.current) {\n        requestAnimationFrame(clearSelection)\n      }\n      if (isSlide) return endSlide(event.currentTarget)\n      if (state !== \"holding\") return\n      if (fallback && pressRef.current === \"virtual\") reset()\n      else release()\n    },\n    onPointerCancel() {\n      if (isSlide) {\n        const current = slideRef.current\n        slideRef.current = null\n        if (current?.moved) release(current.progress)\n        return\n      }\n      if (isHolding) release()\n    },\n    onKeyDown(event) {\n      if (!isHold) {\n        repeatRef.current = event.repeat\n        return\n      }\n      if (event.key === \"Escape\" && fallbackArmed) return cancel()\n      if (!isPressKey(event)) return\n      event.preventDefault()\n      if (event.repeat || quietRef.current) return\n      pressRef.current = \"key\"\n      undoPressRef.current = state === \"undo\"\n      if (state === \"idle\") hold(duration)\n    },\n    onKeyUp(event) {\n      if (!isHold) {\n        repeatRef.current = false\n        return\n      }\n      if (!isPressKey(event)) return\n      const pressed = pressRef.current === \"key\"\n      pressRef.current = \"none\"\n      if (state === \"holding\") release()\n      else if (fallbackArmed && pressed) confirm()\n      else undoFromPress()\n    },\n    onMouseDown(event) {\n      if (event.detail > 1) event.preventDefault()\n    },\n    onContextMenu(event) {\n      if (isHold) event.preventDefault()\n    },\n  }\n\n  function getTriggerProps<P extends TriggerProps<T>>(props: P) {\n    const composed = { ...props }\n    for (const name of Object.keys(handlers) as (keyof typeof handlers)[]) {\n      const handler = handlers[name] as (event: unknown) => void\n      const theirs = props[name] as ((event: unknown) => void) | undefined\n      const ours = (event: { currentTarget: T }) => {\n        triggerRef.current = event.currentTarget\n        handler(event)\n      }\n      Object.assign(composed, { [name]: composeHandlers(theirs, ours) })\n    }\n    return {\n      ...composed,\n      disabled:\n        (disabled && state !== \"undo\") || state === \"pending\" || waiting > 0,\n    }\n  }\n\n  return { state, failed, waiting, undoSeconds, fillRef, getTriggerProps }\n}\n\ntype ConfirmationAnnouncements = {\n  hold?: string\n  armed?: string\n  fallback?: string\n  undo?: string\n  error?: string\n  wait?: string\n  slide?: string\n  success?: string\n}\n\nconst successMs = 1500\n\ninterface ConfirmationLabelOptions {\n  state: ConfirmationState\n  failed: boolean\n  gesture: NonNullable<GestureOptions[\"gesture\"]>\n  holdFallback: NonNullable<GestureOptions[\"holdFallback\"]>\n  undo: ConfirmationOptions[\"undo\"]\n  label: React.ReactNode\n  confirmLabel?: React.ReactNode\n  undoLabel?: React.ReactNode\n  errorLabel?: React.ReactNode\n  wait?: number\n  waiting?: number\n  waitLabel?: (seconds: number) => React.ReactNode\n  pendingLabel?: React.ReactNode\n  pendingDelay?: number\n  successLabel?: React.ReactNode\n  announcements?: ConfirmationAnnouncements\n  ariaLabel?: string\n  describedBy?: string\n}\n\nfunction waitSeconds(wait: number) {\n  return Math.ceil(toMs(wait, 0, 0) / 1000)\n}\n\nfunction text(node: React.ReactNode, fallback: string) {\n  return typeof node === \"string\" ? node : fallback\n}\n\nfunction useConfirmationLabels(options: ConfirmationLabelOptions) {\n  const {\n    state,\n    failed,\n    gesture,\n    holdFallback,\n    undo,\n    label,\n    confirmLabel,\n    undoLabel = \"Undo\",\n    errorLabel,\n    wait = 0,\n    waiting = 0,\n    waitLabel = (seconds: number) => `Wait ${seconds}s`,\n    pendingLabel,\n    pendingDelay = 0,\n    successLabel,\n    announcements,\n    ariaLabel,\n    describedBy,\n  } = options\n  const hintId = React.useId()\n  const [previous, setPrevious] = React.useState(state)\n  const [late, setLate] = React.useState(false)\n  const [succeeded, setSucceeded] = React.useState(false)\n  if (previous !== state) {\n    setPrevious(state)\n    setLate(false)\n    setSucceeded(\n      previous === \"pending\" &&\n        state === \"idle\" &&\n        !failed &&\n        successLabel != null\n    )\n  }\n\n  React.useEffect(() => {\n    if (state !== \"pending\") return\n    const id = setTimeout(() => setLate(true), Math.max(0, pendingDelay))\n    return () => clearTimeout(id)\n  }, [state, pendingDelay])\n\n  React.useEffect(() => {\n    if (!succeeded) return\n    const id = setTimeout(() => setSucceeded(false), successMs)\n    return () => clearTimeout(id)\n  }, [succeeded])\n\n  const waitTotal = waitSeconds(wait)\n  const isHold = gesture === \"hold\"\n  const isSlide = gesture === \"slide\"\n  const showError = failed && state === \"idle\" && errorLabel != null\n  const busy = state === \"pending\" && (late || pendingDelay <= 0)\n  const showPending = busy && pendingLabel != null\n  const showSuccess = succeeded && state === \"idle\"\n  const shown =\n    state === \"armed\" || state === \"undo\"\n      ? state\n      : waiting > 0\n        ? \"wait\"\n        : showPending\n          ? \"pending\"\n          : showSuccess\n            ? \"success\"\n            : showError\n              ? \"error\"\n              : \"idle\"\n  const labels: { state: string; node: React.ReactNode }[] = [\n    { state: \"idle\", node: label },\n  ]\n  if (\n    gesture === \"click-again\" ||\n    isSlide ||\n    (isHold && (confirmLabel != null || holdFallback !== \"none\"))\n  ) {\n    labels.push({\n      state: \"armed\",\n      node: confirmLabel ?? (isHold ? \"Confirm\" : \"Click again\"),\n    })\n  }\n  if (undo) labels.push({ state: \"undo\", node: undoLabel })\n  if (errorLabel != null) labels.push({ state: \"error\", node: errorLabel })\n  if (waitTotal > 0) {\n    labels.push({ state: \"wait\", node: waitLabel(waiting || waitTotal) })\n  }\n  if (pendingLabel != null)\n    labels.push({ state: \"pending\", node: pendingLabel })\n  if (successLabel != null)\n    labels.push({ state: \"success\", node: successLabel })\n\n  let announcement = \"\"\n  if (shown === \"wait\") {\n    announcement = announcements?.wait ?? `Available in ${waitTotal} seconds`\n  } else if (state === \"armed\" && isHold) {\n    announcement = announcements?.fallback ?? \"Activate again to confirm\"\n  } else if (state === \"armed\") {\n    announcement =\n      announcements?.armed ?? text(confirmLabel, \"Click again to confirm\")\n  } else if (state === \"undo\") {\n    announcement = announcements?.undo ?? \"Done. Undo is available.\"\n  } else if (showSuccess) {\n    announcement = announcements?.success ?? text(successLabel, \"Done\")\n  } else if (showError) {\n    announcement =\n      announcements?.error ??\n      text(errorLabel, \"Failed. Activate again to retry.\")\n  }\n\n  return {\n    shown,\n    busy,\n    labels,\n    ariaLabel:\n      ariaLabel && shown === \"undo\"\n        ? text(undoLabel, ariaLabel)\n        : ariaLabel && shown === \"error\"\n          ? text(errorLabel, ariaLabel)\n          : ariaLabel,\n    ariaDescribedBy:\n      isHold || isSlide\n        ? [hintId, describedBy].filter(Boolean).join(\" \")\n        : describedBy,\n    hint: isHold\n      ? {\n          id: hintId,\n          text:\n            announcements?.hold ??\n            (holdFallback === \"none\"\n              ? \"Press and hold to confirm\"\n              : \"Press and hold, or activate twice, to confirm\"),\n        }\n      : isSlide\n        ? {\n            id: hintId,\n            text:\n              announcements?.slide ??\n              \"Slide to the end, or activate twice, to confirm\",\n          }\n        : null,\n    announcement,\n  }\n}\n\nexport {\n  useConfirmation,\n  useConfirmationLabels,\n  composeHandlers,\n  isPromise,\n  playFill,\n  useFill,\n  startUndoWindow,\n  type ConfirmationState,\n  type ConfirmationAnnouncements,\n  type ConfirmationOptions,\n  type GestureOptions,\n  type Fill,\n  type UndoWindow,\n}\n",
      "type": "registry:lib",
      "target": "@ui/sureui/confirmation.ts"
    },
    {
      "path": "components/ui/sureui/undoable.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { useRender } from \"@base-ui/react/use-render\"\n\nimport { Button } from \"@/components/ui/button\"\nimport {\n  isPromise,\n  composeHandlers,\n  startUndoWindow,\n  useFill,\n  type ConfirmationOptions,\n  type Fill,\n  type UndoWindow,\n} from \"@/components/ui/sureui/confirmation\"\n\ntype UndoableState = \"idle\" | \"undo\" | \"pending\" | \"removed\"\n\ninterface UndoableRenderProps {\n  remove: () => void\n  state: UndoableState\n}\n\ninterface UndoableProps\n  extends\n    Omit<useRender.ComponentProps<\"div\", { state: UndoableState }>, \"children\">,\n    ConfirmationOptions {\n  children?: React.ReactNode | ((props: UndoableRenderProps) => React.ReactNode)\n  label?: React.ReactNode\n  undoLabel?: React.ReactNode\n  focusAfterRemove?: (row: HTMLElement) => HTMLElement | null\n  announcements?: {\n    undo?: string\n  }\n}\n\ntype HostProps = {\n  style?: React.CSSProperties\n  onPointerEnter?: React.PointerEventHandler<HTMLDivElement>\n  onPointerLeave?: React.PointerEventHandler<HTMLDivElement>\n  onFocus?: React.FocusEventHandler<HTMLDivElement>\n  onBlur?: React.FocusEventHandler<HTMLDivElement>\n}\n\ntype Collapsed = {\n  height: number\n  columns: number | null\n}\n\nconst focusable =\n  'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'\n\nfunction pathTo(root: Element, node: Element) {\n  const path: number[] = []\n  let current: Element | null = node\n  while (current && current !== root) {\n    const parent: Element | null = current.parentElement\n    if (!parent) return null\n    path.unshift(Array.prototype.indexOf.call(parent.children, current))\n    current = parent\n  }\n  return current === root ? path : null\n}\n\nfunction follow(root: Element, path: number[] | null) {\n  if (!path) return null\n  let current: Element | undefined = root\n  for (const index of path) current = current?.children[index]\n  return current instanceof HTMLElement && current.matches(focusable)\n    ? current\n    : null\n}\n\nfunction targetIn(row: Element, path: number[] | null) {\n  if (\n    row.getAttribute(\"data-slot\") === \"undoable\" &&\n    row.getAttribute(\"data-state\") !== \"idle\"\n  ) {\n    return null\n  }\n  return (\n    follow(row, path) ??\n    (row instanceof HTMLElement && row.matches(focusable)\n      ? row\n      : row.querySelector<HTMLElement>(focusable))\n  )\n}\n\nfunction nextFocus(row: HTMLElement, path: number[] | null) {\n  for (\n    let next = row.nextElementSibling;\n    next;\n    next = next.nextElementSibling\n  ) {\n    const target = targetIn(next, path)\n    if (target) return target\n  }\n  for (\n    let previous = row.previousElementSibling;\n    previous;\n    previous = previous.previousElementSibling\n  ) {\n    const target = targetIn(previous, path)\n    if (target) return target\n  }\n  const list = row.parentElement\n  if (!list || list === document.body) return null\n  if (!list.matches(focusable) && !list.hasAttribute(\"tabindex\")) {\n    list.tabIndex = -1\n  }\n  return list\n}\n\nfunction measure(host: HTMLElement): Collapsed {\n  return {\n    height: host.getBoundingClientRect().height,\n    columns:\n      host instanceof HTMLTableRowElement\n        ? Math.max(\n            1,\n            Array.from(host.cells).reduce((sum, cell) => sum + cell.colSpan, 0)\n          )\n        : null,\n  }\n}\n\nfunction announcer() {\n  let region = document.querySelector<HTMLElement>(\"[data-sureui-announcer]\")\n  if (!region) {\n    region = document.createElement(\"div\")\n    region.setAttribute(\"data-sureui-announcer\", \"\")\n    region.setAttribute(\"aria-live\", \"polite\")\n    region.className = \"sr-only\"\n    document.body.append(region)\n  }\n  return region\n}\n\nfunction useUndoable({\n  onConfirm,\n  onCancel,\n  onConfirmError,\n  undo = true,\n  pauseUndoOnHover = true,\n  pauseUndoOnFocus = true,\n  focusAfterRemove,\n  announcement,\n}: ConfirmationOptions &\n  Pick<UndoableProps, \"focusAfterRemove\"> & { announcement?: string }) {\n  const [state, setState] = React.useState<UndoableState>(\"idle\")\n  const [collapsed, setCollapsed] = React.useState<Collapsed | null>(null)\n  const [fill, setFill] = React.useState<Fill | null>(null)\n  const [paused, setPaused] = React.useState(false)\n  const [failed, setFailed] = React.useState(false)\n  const hostRef = React.useRef<HTMLDivElement>(null)\n  const labelRef = React.useRef<HTMLSpanElement>(null)\n  const undoRef = React.useRef<HTMLButtonElement>(null)\n  const fillRef = React.useRef<HTMLSpanElement>(null)\n  const windowRef = React.useRef<UndoWindow | null>(null)\n  const busyRef = React.useRef(false)\n  const hoverPausableRef = React.useRef(true)\n  const focusingRef = React.useRef(false)\n  const focusUndoRef = React.useRef(false)\n  const restoreFocusRef = React.useRef(false)\n  const triggerPathRef = React.useRef<number[] | null>(null)\n  const announcedRef = React.useRef(\"\")\n  const optionsRef = React.useRef({\n    onConfirm,\n    onCancel,\n    onConfirmError,\n    undo,\n    pauseUndoOnHover,\n    pauseUndoOnFocus,\n    focusAfterRemove,\n  })\n\n  useFill(fillRef, fill, paused)\n\n  React.useEffect(() => {\n    optionsRef.current = {\n      onConfirm,\n      onCancel,\n      onConfirmError,\n      undo,\n      pauseUndoOnHover,\n      pauseUndoOnFocus,\n      focusAfterRemove,\n    }\n  })\n\n  const clearAnnouncement = React.useCallback(() => {\n    const region = document.querySelector(\"[data-sureui-announcer]\")\n    if (announcedRef.current && region?.textContent === announcedRef.current) {\n      region.textContent = \"\"\n    }\n    announcedRef.current = \"\"\n  }, [])\n\n  React.useEffect(\n    () => () => {\n      windowRef.current?.cancel()\n      windowRef.current = null\n      clearAnnouncement()\n    },\n    [clearAnnouncement]\n  )\n\n  const restore = React.useCallback(() => {\n    windowRef.current?.cancel()\n    windowRef.current = null\n    busyRef.current = false\n    restoreFocusRef.current = true\n    setFill(null)\n    setPaused(false)\n    setCollapsed(null)\n    setState(\"idle\")\n  }, [])\n\n  const fail = React.useCallback(\n    (error: unknown) => {\n      restore()\n      setFailed(true)\n      const { onConfirmError } = optionsRef.current\n      if (!onConfirmError) throw error\n      onConfirmError(error)\n    },\n    [restore]\n  )\n\n  const removed = React.useCallback(() => {\n    const host = hostRef.current\n    const active = document.activeElement\n    if (host && active instanceof Element && host.contains(active)) {\n      const { focusAfterRemove } = optionsRef.current\n      const target = focusAfterRemove\n        ? focusAfterRemove(host)\n        : nextFocus(host, triggerPathRef.current)\n      target?.focus()\n    }\n    setState(\"removed\")\n  }, [])\n\n  const commit = React.useCallback(\n    (run: ConfirmationOptions[\"onConfirm\"]) => {\n      windowRef.current = null\n      setFill(null)\n      setPaused(false)\n      let result: ReturnType<ConfirmationOptions[\"onConfirm\"]>\n      try {\n        result = run()\n      } catch (error) {\n        return fail(error)\n      }\n      if (!isPromise(result)) return removed()\n      setState(\"pending\")\n      ;(async () => {\n        try {\n          await result\n        } catch (error) {\n          return fail(error)\n        }\n        removed()\n      })()\n    },\n    [fail, removed]\n  )\n\n  const remove = React.useCallback(() => {\n    const host = hostRef.current\n    if (!host || busyRef.current) return\n    busyRef.current = true\n    setFailed(false)\n    const { onConfirm: run, undo: duration } = optionsRef.current\n    const active = document.activeElement\n    const hadFocus = active instanceof Element && host.contains(active)\n    triggerPathRef.current = hadFocus ? pathTo(host, active) : null\n    focusUndoRef.current = hadFocus\n    hoverPausableRef.current = !host.matches(\":hover\")\n    setCollapsed(measure(host))\n    if (!duration) {\n      commit(run)\n      return\n    }\n    const undoWindow = startUndoWindow({\n      duration,\n      onExpire: () => commit(run),\n      onPauseChange: setPaused,\n      within: () => hostRef.current,\n    })\n    windowRef.current = undoWindow\n    setFill(\n      undoWindow.manual\n        ? null\n        : {\n            from: 1,\n            to: 0,\n            duration: undoWindow.duration,\n            startedAt: performance.now(),\n          }\n    )\n    setPaused(undoWindow.paused())\n    setState(\"undo\")\n  }, [commit])\n\n  const cancel = React.useCallback(() => {\n    if (!windowRef.current) return\n    restore()\n    optionsRef.current.onCancel?.()\n  }, [restore])\n\n  React.useLayoutEffect(() => {\n    if (state === \"undo\") {\n      if (focusUndoRef.current) {\n        focusUndoRef.current = false\n        focusingRef.current = true\n        undoRef.current?.focus()\n        focusingRef.current = false\n      }\n      const text = (labelRef.current?.textContent ?? \"\")\n        .trim()\n        .replace(/[.!?]$/, \"\")\n      const message = announcement ?? `${text || \"Deleted\"}. Undo is available.`\n      announcedRef.current = message\n      announcer().textContent = message\n      return\n    }\n    if (state !== \"idle\") return\n    clearAnnouncement()\n    if (!restoreFocusRef.current) return\n    restoreFocusRef.current = false\n    const host = hostRef.current\n    const active = document.activeElement\n    if (!host || (active && active !== document.body && active.isConnected)) {\n      return\n    }\n    const target =\n      follow(host, triggerPathRef.current) ??\n      host.querySelector<HTMLElement>(focusable)\n    target?.focus()\n  }, [state, announcement, clearAnnouncement])\n\n  function getHostProps<P extends HostProps>(props: P) {\n    return {\n      ...props,\n      style:\n        collapsed && collapsed.height > 0\n          ? {\n              ...props.style,\n              [collapsed.columns === null ? \"minHeight\" : \"height\"]:\n                collapsed.height,\n            }\n          : props.style,\n      onPointerEnter: composeHandlers(props.onPointerEnter, () => {\n        if (optionsRef.current.pauseUndoOnHover && hoverPausableRef.current) {\n          windowRef.current?.pause(\"hover\")\n        }\n      }),\n      onPointerLeave: composeHandlers(props.onPointerLeave, () => {\n        hoverPausableRef.current = true\n        windowRef.current?.resume(\"hover\")\n      }),\n      onFocus: composeHandlers(props.onFocus, () => {\n        if (optionsRef.current.pauseUndoOnFocus && !focusingRef.current) {\n          windowRef.current?.pause(\"focus\")\n        }\n      }),\n      onBlur: composeHandlers(\n        props.onBlur,\n        (event: React.FocusEvent<HTMLDivElement>) => {\n          const next = event.relatedTarget\n          if (next instanceof Node && event.currentTarget.contains(next)) {\n            return\n          }\n          windowRef.current?.resume(\"focus\")\n        }\n      ),\n    }\n  }\n\n  return {\n    state,\n    failed,\n    columns: collapsed?.columns ?? null,\n    remove,\n    cancel,\n    getHostProps,\n    hostRef,\n    labelRef,\n    undoRef,\n    fillRef,\n  }\n}\n\nfunction Undoable(props: UndoableProps) {\n  const {\n    onConfirm,\n    onCancel,\n    onConfirmError,\n    undo,\n    pauseUndoOnHover,\n    pauseUndoOnFocus,\n    label = \"Deleted\",\n    undoLabel = \"Undo\",\n    focusAfterRemove,\n    announcements,\n    render,\n    ref,\n    children,\n    ...rest\n  } = props\n  const {\n    state,\n    failed,\n    columns,\n    remove,\n    cancel,\n    getHostProps,\n    hostRef,\n    labelRef,\n    undoRef,\n    fillRef,\n  } = useUndoable({\n    onConfirm,\n    onCancel,\n    onConfirmError,\n    undo,\n    pauseUndoOnHover,\n    pauseUndoOnFocus,\n    focusAfterRemove,\n    announcement: announcements?.undo,\n  })\n  const labelId = React.useId()\n\n  const strip = (\n    <span className=\"flex w-full min-w-0 items-center gap-2\">\n      <span\n        ref={labelRef}\n        id={labelId}\n        className=\"min-w-0 truncate text-muted-foreground\"\n      >\n        {label}\n      </span>\n      {(state === \"undo\" || state === \"pending\") && (\n        <Button\n          ref={undoRef}\n          variant=\"outline\"\n          size=\"sm\"\n          aria-describedby={labelId}\n          disabled={state === \"pending\"}\n          focusableWhenDisabled\n          onClick={cancel}\n          className=\"relative ml-auto overflow-hidden motion-safe:aria-disabled:animate-pulse motion-reduce:aria-disabled:opacity-50\"\n        >\n          <span\n            ref={fillRef}\n            aria-hidden\n            className=\"pointer-events-none absolute inset-0 origin-left scale-x-0 bg-current opacity-20\"\n          />\n          {undoLabel}\n        </Button>\n      )}\n    </span>\n  )\n\n  let content: React.ReactNode\n  if (state === \"idle\") {\n    content =\n      typeof children === \"function\" ? children({ remove, state }) : children\n  } else if (columns !== null) {\n    content = (\n      <td\n        data-slot=\"undoable-strip\"\n        colSpan={columns}\n        className=\"p-2 align-middle\"\n      >\n        {strip}\n      </td>\n    )\n  } else {\n    content = (\n      <span data-slot=\"undoable-strip\" className=\"col-span-full flex w-full\">\n        {strip}\n      </span>\n    )\n  }\n\n  return useRender({\n    defaultTagName: \"div\",\n    render,\n    ref: ref ? [ref, hostRef] : hostRef,\n    state: { state },\n    props: {\n      ...getHostProps(rest),\n      \"data-slot\": \"undoable\",\n      \"data-error\": failed || undefined,\n      children: content,\n    },\n  })\n}\n\nexport { Undoable, type UndoableProps, type UndoableState }\n",
      "type": "registry:ui",
      "target": "@ui/sureui/undoable.tsx"
    }
  ],
  "categories": [
    "confirmation",
    "list",
    "table"
  ],
  "type": "registry:ui"
}