{ "$schema": "https://ui.shadcn.com/schema/registry-item.json", "name": "undo-action", "type": "registry:ui", "title": "Undo action", "description": "Destructive actions with a burning undo window, an undo toast, and hold-to-confirm for what cannot be undone.", "dependencies": [ "@fungi.computer/stipe", "cn", "class-variance-authority", "react", "sonner" ], "registryDependencies": [ "@shiit/button", "@shiit/alert", "@shiit/visually-hidden" ], "files": [ { "path": "../src/components/undo-action.tsx", "type": "registry:ui", "target": "@ui/undo-action.tsx", "content": "import {\n forwardRef,\n useEffect,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\n\nimport { cn } from \"@/lib/cn\";\nimport { canAnimate, motionEasing, readMotion } from \"@/lib/motion\";\nimport { Button, type ButtonProps } from \"./button.js\";\nimport { VisuallyHidden } from \"./visually-hidden.js\";\n\n/** Props accepted by Fuse. */\nexport type FuseProps = {\n /** How long the fuse burns, in milliseconds: a decision window, not motion. */\n duration: number;\n /** Hold the burn, for example while the pointer rests on the action. */\n paused?: boolean;\n /** Called once when the fuse has burnt down. */\n onBurnt: () => void;\n className?: string;\n};\n\n/**\n * A hairline that burns down over its duration, then calls `onBurnt`. Its\n * thickness is the theme's `--stipe-motion-fuse` (0 hides it but the window\n * still runs). Under reduced motion it ticks down once a second instead of\n * burning smoothly.\n */\nexport function Fuse({\n duration,\n paused = false,\n onBurnt,\n className,\n}: FuseProps) {\n const node = useRef(null);\n const burn = useRef(null);\n const burnt = useRef(onBurnt);\n useEffect(() => {\n burnt.current = onBurnt;\n }, [onBurnt]);\n\n useLayoutEffect(() => {\n const element = node.current;\n if (!element) return;\n if (!canAnimate(element)) {\n const timer = setTimeout(() => {\n burnt.current();\n }, duration);\n return () => {\n clearTimeout(timer);\n };\n }\n const motion = readMotion(element);\n const seconds = Math.max(1, Math.round(duration / 1000));\n const animation = element.animate(\n [{ transform: \"scaleX(1)\" }, { transform: \"scaleX(0)\" }],\n {\n duration,\n easing: motion.reduced\n ? `steps(${String(seconds)}, end)`\n : motionEasing(motion, \"linear\"),\n fill: \"forwards\",\n },\n );\n animation.addEventListener(\"finish\", () => {\n burnt.current();\n });\n burn.current = animation;\n return () => {\n animation.cancel();\n burn.current = null;\n };\n }, [duration]);\n\n useEffect(() => {\n const animation = burn.current;\n if (!animation) return;\n if (paused) animation.pause();\n else if (animation.playState === \"paused\") animation.play();\n }, [paused]);\n\n return (\n \n );\n}\n\n/** Props accepted by UndoAction. */\nexport type UndoActionProps = {\n /** The action's label, such as \"Stop\". */\n children: ReactNode;\n /** Runs when the undo window closes without an undo: the action happens then. */\n onCommit: () => void;\n /** Spoken when the action is armed, such as \"Port 5173 stops in 5 seconds\". */\n armedAnnouncement: string;\n /** Spoken after an undo, such as \"Port 5173 kept open\". */\n undoneAnnouncement: string;\n undoLabel?: ReactNode;\n /** The undo window in milliseconds. */\n undoMs?: number;\n} & Omit;\n\n/**\n * A destructive action that waits for its undo window instead of asking\n * first. Pressing it turns the same button into Undo with a fuse burning along\n * its edge; Undo or Escape cancels, and the action commits when the fuse runs\n * out. Resting the pointer on it holds the fuse.\n */\nexport const UndoAction = forwardRef(\n function UndoAction(\n {\n children,\n onCommit,\n armedAnnouncement,\n undoneAnnouncement,\n undoLabel = \"Undo\",\n undoMs = 5000,\n className,\n onKeyDown,\n onPointerEnter,\n onPointerLeave,\n ...props\n },\n ref,\n ) {\n const [armed, setArmed] = useState(false);\n const [held, setHeld] = useState(false);\n const [spoken, setSpoken] = useState(\"\");\n const hint = useId();\n const undo = () => {\n setArmed(false);\n setSpoken(undoneAnnouncement);\n };\n return (\n <>\n {\n if (armed) {\n undo();\n return;\n }\n setArmed(true);\n setSpoken(armedAnnouncement);\n }}\n onKeyDown={(event) => {\n onKeyDown?.(event);\n if (armed && event.key === \"Escape\") {\n event.preventDefault();\n undo();\n }\n }}\n onPointerEnter={(event) => {\n onPointerEnter?.(event);\n setHeld(true);\n }}\n onPointerLeave={(event) => {\n onPointerLeave?.(event);\n setHeld(false);\n }}\n >\n {armed ? undoLabel : children}\n {armed ? (\n {\n setArmed(false);\n setSpoken(\"\");\n onCommit();\n }}\n />\n ) : null}\n \n Press Escape to undo.\n {spoken}\n \n );\n },\n);\n" }, { "path": "../src/components/hold-button.tsx", "type": "registry:ui", "target": "@ui/hold-button.tsx", "content": "import {\n forwardRef,\n useEffect,\n useId,\n useRef,\n type KeyboardEvent,\n type PointerEvent,\n type ReactNode,\n} from \"react\";\n\nimport { cn } from \"@/lib/cn\";\nimport { canAnimate, motionEasing, readMotion } from \"@/lib/motion\";\nimport { Button, type ButtonProps } from \"./button.js\";\nimport { VisuallyHidden } from \"./visually-hidden.js\";\n\n/** Props accepted by HoldButton. */\nexport type HoldButtonProps = {\n children: ReactNode;\n /** Runs once the button has been held for `holdMs`. */\n onConfirm: () => void;\n /** How long to hold, in milliseconds: a deliberate pause, not motion. */\n holdMs?: number;\n /** Spoken description of the gesture. */\n holdHint?: string;\n} & Omit;\n\nconst confirmKeys = new Set([\"Enter\", \" \"]);\n\n/** What is holding the button: the confirm key, or one pointer by id. */\ntype Holder = \"key\" | number;\n\n/**\n * For an action nothing can undo: press and hold (pointer, Space or Enter)\n * while a fill rises; let go early and it drops back; hold to the top and the\n * action runs. Under reduced motion the fill rises in three steps.\n */\nexport const HoldButton = forwardRef(\n function HoldButton(\n {\n children,\n onConfirm,\n holdMs = 900,\n holdHint = \"Press and hold to confirm.\",\n className,\n disabled,\n loading = false,\n result,\n resultLabel,\n onBlur,\n onKeyDown,\n onKeyUp,\n onPointerDown,\n onPointerUp,\n onPointerLeave,\n onPointerCancel,\n ...props\n },\n ref,\n ) {\n const fill = useRef(null);\n const rising = useRef(null);\n const timer = useRef | null>(null);\n const holder = useRef(null);\n const confirm = useRef(onConfirm);\n const hint = useId();\n useEffect(() => {\n confirm.current = onConfirm;\n }, [onConfirm]);\n useEffect(\n () => () => {\n rising.current?.cancel();\n if (timer.current !== null) clearTimeout(timer.current);\n },\n [],\n );\n\n const finish = () => {\n rising.current = null;\n timer.current = null;\n holder.current = null;\n confirm.current();\n const element = fill.current;\n if (!element || !canAnimate(element)) return;\n const motion = readMotion(element);\n element.animate([{ opacity: 1 }, { opacity: 0 }], {\n duration: motion.normal,\n easing: motionEasing(motion, motion.easeExit),\n });\n };\n\n const start = (by: Holder) => {\n const element = fill.current;\n if (\n disabled === true ||\n loading ||\n !element ||\n rising.current ||\n timer.current\n )\n return;\n holder.current = by;\n if (!canAnimate(element)) {\n timer.current = setTimeout(finish, holdMs);\n return;\n }\n const motion = readMotion(element);\n const animation = element.animate(\n [{ transform: \"scaleY(0)\" }, { transform: \"scaleY(1)\" }],\n {\n duration: holdMs,\n easing: motion.reduced\n ? \"steps(3, end)\"\n : motionEasing(motion, \"cubic-bezier(0.3, 0, 0.7, 1)\"),\n },\n );\n animation.addEventListener(\"finish\", finish);\n rising.current = animation;\n };\n\n // Each input ends only the hold it started: a mouse leaving the button\n // (or the button moving away from a resting mouse) never cancels a held\n // key. Blur and Escape end any hold.\n const release = (by?: Holder) => {\n if (by !== undefined && holder.current !== by) return;\n holder.current = null;\n if (timer.current !== null) {\n clearTimeout(timer.current);\n timer.current = null;\n }\n const animation = rising.current;\n const element = fill.current;\n if (!animation || !element) return;\n rising.current = null;\n // Drop back from wherever the fill had reached.\n const reached = getComputedStyle(element).transform;\n animation.cancel();\n const motion = readMotion(element);\n element.animate(\n [\n { transform: reached === \"none\" ? \"scaleY(0)\" : reached },\n { transform: \"scaleY(0)\" },\n ],\n { duration: motion.fast, easing: motionEasing(motion, motion.ease) },\n );\n };\n\n return (\n <>\n {\n release();\n onBlur?.(event);\n }}\n onPointerDown={(event: PointerEvent) => {\n onPointerDown?.(event);\n if (event.button === 0) start(event.pointerId);\n }}\n onPointerUp={(event: PointerEvent) => {\n onPointerUp?.(event);\n release(event.pointerId);\n }}\n onPointerLeave={(event: PointerEvent) => {\n onPointerLeave?.(event);\n release(event.pointerId);\n }}\n onPointerCancel={(event: PointerEvent) => {\n onPointerCancel?.(event);\n release(event.pointerId);\n }}\n onKeyDown={(event: KeyboardEvent) => {\n onKeyDown?.(event);\n if (event.key === \"Escape\") release();\n if (!confirmKeys.has(event.key)) return;\n event.preventDefault();\n if (!event.repeat) start(\"key\");\n }}\n onKeyUp={(event: KeyboardEvent) => {\n onKeyUp?.(event);\n if (!confirmKeys.has(event.key)) return;\n event.preventDefault();\n release(\"key\");\n }}\n >\n \n {children}\n \n {holdHint}\n \n );\n },\n);\n" }, { "path": "../src/components/undo-toast.tsx", "type": "registry:ui", "target": "@ui/undo-toast.tsx", "content": "import { useEffect, useState, type ReactNode } from \"react\";\nimport { toast } from \"sonner\";\n\nimport { Alert } from \"./alert.js\";\nimport { Button } from \"./button.js\";\nimport { Fuse } from \"./undo-action.js\";\n\n/** What an undo toast says and does. */\nexport type UndoToastOptions = Readonly<{\n title: ReactNode;\n description?: ReactNode;\n /** Runs when the toast's fuse burns out: the action happens then. */\n onCommit: () => void;\n /** Runs when the person undoes, by the button or Escape. */\n onUndo?: () => void;\n undoLabel?: string;\n /** The undo window in milliseconds. */\n undoMs?: number;\n /** The Toaster to show it on, when a page has more than one. */\n toasterId?: string;\n}>;\n\nfunction UndoToast({\n dismiss,\n options,\n}: {\n dismiss: () => void;\n options: UndoToastOptions;\n}) {\n const [held, setHeld] = useState(false);\n const [settled, setSettled] = useState(false);\n const undo = () => {\n if (settled) return;\n setSettled(true);\n options.onUndo?.();\n dismiss();\n };\n useEffect(() => {\n const onKey = (event: KeyboardEvent) => {\n if (event.key !== \"Escape\" || settled) return;\n setSettled(true);\n options.onUndo?.();\n dismiss();\n };\n globalThis.addEventListener(\"keydown\", onKey);\n return () => {\n globalThis.removeEventListener(\"keydown\", onKey);\n };\n }, [settled, options, dismiss]);\n return (\n {\n setHeld(true);\n }}\n onPointerLeave={() => {\n setHeld(false);\n }}\n onFocus={() => {\n setHeld(true);\n }}\n onBlur={() => {\n setHeld(false);\n }}\n >\n \n {options.undoLabel ?? \"Undo\"}\n \n }\n />\n {\n if (settled) return;\n setSettled(true);\n options.onCommit();\n dismiss();\n }}\n />\n \n );\n}\n\n/**\n * Show a done-and-undoable toast: the action is deferred while a fuse burns\n * along the toast's edge, Undo or Escape cancels it, and resting on the toast\n * holds the fuse. Returns the toast id.\n */\nexport function toastUndo(options: UndoToastOptions): string | number {\n const settings: Parameters[1] = { duration: Infinity };\n if (options.toasterId !== undefined) settings.toasterId = options.toasterId;\n return toast.custom(\n (id) => (\n {\n toast.dismiss(id);\n }}\n />\n ),\n settings,\n );\n}\n" }, { "path": "../src/lib/motion.ts", "type": "registry:lib", "target": "@lib/motion.ts", "content": "import {\n useLayoutEffect,\n useState,\n useSyncExternalStore,\n type RefObject,\n} from \"react\";\n\n/** Resolved, element-scoped motion. Times are milliseconds and distances pixels. */\nexport type Motion = Readonly<{\n reduced: boolean;\n squish: number;\n fast: number;\n normal: number;\n slow: number;\n springDuration: number;\n bounce: number;\n stretch: number;\n distance: number;\n stagger: number;\n blur: number;\n shake: number;\n steps: number;\n fuse: number;\n pressDepth: number;\n pressScale: number;\n ease: string;\n easeExit: string;\n}>;\n\nconst defaults: Motion = Object.freeze({\n reduced: false,\n squish: 90,\n fast: 120,\n normal: 180,\n slow: 280,\n springDuration: 320,\n bounce: 0.3,\n stretch: 0.28,\n distance: 4,\n stagger: 24,\n blur: 0,\n shake: 3,\n steps: 0,\n fuse: 1,\n pressDepth: 0.5,\n pressScale: 1,\n ease: \"cubic-bezier(0.2, 0, 0, 1)\",\n easeExit: \"cubic-bezier(0.4, 0, 1, 1)\",\n});\n\nconst preference = \"(prefers-reduced-motion: reduce)\";\n\n/** Read at an event boundary; no root-theme lookup, so nested tokens win. */\nexport function readMotion(element: Element): Motion {\n const view = element.ownerDocument.defaultView;\n if (!view) return defaults;\n const style = view.getComputedStyle(element);\n const number = (name: string, fallback: number) => {\n const value = style.getPropertyValue(name).trim();\n const parsed = Number.parseFloat(value);\n return Number.isFinite(parsed) ? Math.max(0, parsed) : fallback;\n };\n const time = (name: string, fallback: number) => {\n const value = style.getPropertyValue(name).trim();\n return (\n number(name, fallback) *\n (value.endsWith(\"s\") && !value.endsWith(\"ms\") ? 1000 : 1)\n );\n };\n const browser: Partial> = view;\n const reduced = browser.matchMedia?.(preference).matches ?? false;\n const duration = (name: string, fallback: number) =>\n reduced ? 120 : time(`--stipe-motion-${name}`, fallback);\n const amount = (name: string, fallback: number) =>\n reduced ? 0 : number(`--stipe-motion-${name}`, fallback);\n return {\n reduced,\n squish: duration(\"squish\", defaults.squish),\n fast: duration(\"fast\", defaults.fast),\n normal: duration(\"normal\", defaults.normal),\n slow: duration(\"slow\", defaults.slow),\n springDuration: duration(\"spring-duration\", defaults.springDuration),\n bounce: Math.min(1, amount(\"bounce\", defaults.bounce)),\n stretch: amount(\"stretch\", defaults.stretch),\n distance: amount(\"distance\", defaults.distance),\n stagger: reduced ? 0 : time(\"--stipe-motion-stagger\", defaults.stagger),\n blur: amount(\"blur\", defaults.blur),\n shake: amount(\"shake\", defaults.shake),\n steps: Math.floor(amount(\"steps\", defaults.steps)),\n fuse: number(\"--stipe-motion-fuse\", defaults.fuse),\n pressDepth: reduced\n ? 0\n : number(\"--stipe-press-depth\", defaults.pressDepth),\n pressScale: reduced\n ? 1\n : number(\"--stipe-press-scale\", defaults.pressScale),\n ease: style.getPropertyValue(\"--stipe-motion-ease\").trim() || defaults.ease,\n easeExit:\n style.getPropertyValue(\"--stipe-motion-ease-exit\").trim() ||\n defaults.easeExit,\n };\n}\n\n/** Live motion tokens for a mounted ref, including nested theme and OS changes. */\nexport function useMotion(ref: RefObject): Motion {\n const [motion, setMotion] = useState(() => ({\n ...defaults,\n reduced: true,\n }));\n useLayoutEffect(() => {\n const element = ref.current;\n const view = element?.ownerDocument.defaultView;\n if (!element || !view) return;\n const update = () => {\n const next = readMotion(element);\n setMotion((previous) =>\n JSON.stringify(previous) === JSON.stringify(next) ? previous : next,\n );\n };\n update();\n const observer = new view.MutationObserver(update);\n // Observe ancestors only: animation writes to descendants must not trigger reads.\n for (\n let parent: Element | null = element;\n parent;\n parent = parent.parentElement\n ) {\n observer.observe(parent, {\n attributes: true,\n attributeFilter: [\"data-theme\", \"class\", \"style\"],\n });\n }\n const browser: Partial> = view;\n const media = browser.matchMedia?.(preference);\n media?.addEventListener(\"change\", update);\n return () => {\n observer.disconnect();\n media?.removeEventListener(\"change\", update);\n };\n }, [ref]);\n return motion;\n}\n\n/** Today's feel: the defaults that components' authored timings are written against. */\nexport const motionDefaults: Motion = defaults;\n\n/**\n * Scale one of a component's authored durations by the theme's tempo\n * (`--stipe-motion-normal` against its 180ms default). Today's themes return\n * the authored value unchanged; reduced motion returns 0 (nothing travels).\n */\nexport function motionTime(motion: Motion, authored: number): number {\n if (motion.reduced) return 0;\n return Math.round((authored * motion.normal) / defaults.normal);\n}\n\n/**\n * Scale one of a component's authored spring bounces by the theme's bounce\n * (`--stipe-motion-bounce` against its 0.3 default), so a lively control stays\n * livelier than a calm one inside every theme. A 0 theme is critically damped.\n */\nexport function motionBounce(motion: Motion, authored: number): number {\n if (motion.reduced) return 0;\n const scaled = (authored * motion.bounce) / defaults.bounce;\n return Math.min(0.9, Math.max(0, scaled));\n}\n\n/** Scale an authored spring settle time by `--stipe-motion-spring-duration`. */\nexport function motionSpringTime(motion: Motion, authored: number): number {\n if (motion.reduced) return 0;\n return Math.round(\n (authored * motion.springDuration) / defaults.springDuration,\n );\n}\n\n/** A CSS easing for a Web Animation, stepped when the theme asks for it. */\nexport function motionEasing(motion: Motion, ease: string): string {\n return motion.steps > 0 ? `steps(${String(motion.steps)}, end)` : ease;\n}\n\n/** Whether the element can run Web Animations (not in jsdom or old engines). */\nexport function canAnimate(element: Element): boolean {\n return \"animate\" in element;\n}\n\nconst globalWindow: Partial> = globalThis;\n\nfunction prefersReducedMotion(): boolean {\n return globalWindow.matchMedia?.(preference).matches ?? false;\n}\n\nfunction subscribeReducedMotion(update: () => void) {\n const media = globalWindow.matchMedia?.(preference);\n media?.addEventListener(\"change\", update);\n return () => {\n media?.removeEventListener(\"change\", update);\n };\n}\n\n/** Server renders assume reduced motion, so hydration never starts mid-move. */\nfunction serverReducedMotion() {\n return true;\n}\n\n/**\n * The live reduced-motion preference alone, for controls that only need to\n * know whether to move (their timing comes from `readMotion` when they do).\n */\nexport function useReducedMotion(): boolean {\n return useSyncExternalStore(\n subscribeReducedMotion,\n prefersReducedMotion,\n serverReducedMotion,\n );\n}\n" }, { "path": "../src/lib/cn.ts", "type": "registry:lib", "target": "@lib/cn.ts", "content": "import { STIPE_SPACING_NAMES } from \"@fungi.computer/stipe\";\nimport { cva } from \"class-variance-authority\";\nimport { createCn } from \"cn/config\";\n\n/** A conditional class value accepted by cn. */\nexport type { ClassValue } from \"cn\";\nexport { cva };\n\n/** Merge conditional classes with Tailwind rules and Stipe's named spacing. */\nexport const cn = createCn({\n extend: { theme: { spacing: [...STIPE_SPACING_NAMES] } },\n});\n\n/** Resolve a typed React class-name prop before merging its classes. */\nexport function resolveClassName(\n className: string | ((state: State) => string | undefined) | undefined,\n state: State,\n): string | undefined {\n return typeof className === \"function\" ? className(state) : className;\n}\n" } ], "css": { "@import \"@fungi.computer/stipe/styles.css\"": {}, "@plugin \"@tailwindcss/typography\"": {}, "@layer utilities": { ".caps-fuse": { "color": "var(--caps-fuse-color, inherit)", "position": "absolute", "insetInline": "0", "bottom": "0", "height": "var(--stipe-motion-fuse, 1px)", "background": "linear-gradient(\n to right,\n color-mix(in oklab, currentColor 55%, transparent),\n currentColor\n )", "transformOrigin": "left center", "pointerEvents": "none" }, ".caps-undo-action": { "position": "relative" }, ".caps-undo-toast": { "--caps-fuse-color": "var(--color-base-content)", "position": "relative" }, ".caps-undo-toast > .caps-fuse": { "insetInline": "var(--spacing-md)", "bottom": "var(--spacing-xs)" }, ".caps-hold-button": { "position": "relative", "isolation": "isolate", "overflow": "clip" }, ".caps-hold-fill": { "position": "absolute", "inset": "0", "zIndex": -1, "background": "color-mix(in oklab, currentColor 36%, transparent)", "transform": "scaleY(0)", "transformOrigin": "bottom center", "pointerEvents": "none" } }, "@property --caps-game-host-ink": { "syntax": "\"\"", "inherits": "true", "initialValue": "black" } } }