{ "$schema": "https://ui.shadcn.com/schema/registry-item.json", "name": "code-input", "type": "registry:ui", "title": "Code input", "description": "A one-time code as slots over one native input, with landing, refusal and acceptance motion.", "dependencies": [ "@fungi.computer/stipe", "cn", "class-variance-authority", "react" ], "registryDependencies": ["@shiit/input"], "files": [ { "path": "../src/components/code-input.tsx", "type": "registry:ui", "target": "@ui/code-input.tsx", "content": "import {\n forwardRef,\n useImperativeHandle,\n useLayoutEffect,\n useRef,\n useState,\n type InputHTMLAttributes,\n} from \"react\";\n\nimport { cn } from \"@/lib/cn\";\nimport {\n canAnimate,\n motionEasing,\n readMotion,\n type Motion,\n} from \"@/lib/motion\";\n\nconst graphemes = new Intl.Segmenter();\n\n/** What the caller has learned about the entered code. */\nexport type CodeInputStatus = \"idle\" | \"invalid\" | \"accepted\";\n\n/** Props accepted by CodeInput. */\nexport type CodeInputProps = {\n /** How many characters the code has. */\n length?: number;\n /** The current code. */\n value: string;\n /** Receives the code after a native edit or a normalized paste. */\n onValueChange: (value: string) => void;\n /**\n * `invalid` shakes the slots in a cascade and marks them; `accepted` lifts\n * them in a wave. Say what was wrong next to the field, as with any error.\n */\n status?: CodeInputStatus;\n} & Omit<\n InputHTMLAttributes,\n \"value\" | \"defaultValue\" | \"onChange\" | \"maxLength\" | \"size\"\n>;\n\nfunction land(slot: HTMLElement, motion: Motion) {\n // A character drops into its slot: a small press, then a settle sized by\n // the theme's bounce. Reduced motion only fades the character in.\n if (motion.reduced)\n return slot.animate([{ color: \"transparent\" }, {}], {\n duration: motion.fast,\n });\n const give = 0.06 * Math.min(1.5, motion.bounce / 0.3);\n return slot.animate(\n [\n { transform: `translateY(${String(motion.distance / 2)}px) scale(0.94)` },\n { transform: `scale(${String(1 + give)})`, offset: 0.55 },\n { transform: \"none\" },\n ],\n {\n duration: motion.springDuration,\n easing: motionEasing(motion, motion.ease),\n },\n );\n}\n\nfunction refuse(slot: HTMLElement, index: number, motion: Motion) {\n const x = motion.shake;\n return slot.animate(\n [\n { transform: \"none\" },\n { transform: `translateX(${String(-x)}px)` },\n { transform: `translateX(${String(x)}px)` },\n { transform: `translateX(${String(-x / 2)}px)` },\n { transform: \"none\" },\n ],\n {\n duration: motion.slow,\n delay: index * motion.stagger,\n easing: motionEasing(motion, \"linear\"),\n },\n );\n}\n\nfunction accept(slot: HTMLElement, index: number, motion: Motion) {\n return slot.animate(\n [\n { transform: \"none\" },\n { transform: `translateY(${String(-motion.distance)}px)`, offset: 0.4 },\n { transform: \"none\" },\n ],\n {\n duration: motion.slow,\n delay: index * motion.stagger,\n easing: motionEasing(motion, motion.ease),\n },\n );\n}\n\n/**\n * A short code (a sign-in or pairing code) shown as one slot per character.\n * It is a single native input underneath, so typing, pasting, one-time-code\n * autofill and screen readers behave as they do on any text field.\n */\nexport const CodeInput = forwardRef(\n function CodeInput(\n {\n length = 6,\n value,\n onValueChange,\n status = \"idle\",\n className,\n onFocus,\n onBlur,\n onSelect,\n onPaste,\n ...props\n },\n ref,\n ) {\n const input = useRef(null);\n const slots = useRef(null);\n useImperativeHandle(\n ref,\n () => input.current,\n );\n const [focused, setFocused] = useState(false);\n const [cursor, setCursor] = useState(value.length);\n const characters = Array.from(\n graphemes.segment(value),\n (part) => part.segment,\n ).slice(0, length);\n const active = Math.min(\n Array.from(graphemes.segment(value.slice(0, cursor))).length,\n length - 1,\n );\n const filled = useRef(characters.length);\n\n useLayoutEffect(() => {\n const root = slots.current;\n const before = filled.current;\n filled.current = characters.length;\n if (!root || !canAnimate(root) || characters.length <= before) return;\n const slot = root.children.item(characters.length - 1);\n if (!(slot instanceof HTMLElement)) return;\n const animation = land(slot, readMotion(root));\n return () => {\n animation.cancel();\n };\n }, [characters.length]);\n\n useLayoutEffect(() => {\n const root = slots.current;\n if (!root || !canAnimate(root) || status === \"idle\") return;\n const motion = readMotion(root);\n if (motion.reduced) return;\n const animations = [...root.children].flatMap((slot, index) =>\n slot instanceof HTMLElement\n ? [\n status === \"invalid\"\n ? refuse(slot, index, motion)\n : accept(slot, index, motion),\n ]\n : [],\n );\n return () => {\n for (const animation of animations) animation.cancel();\n };\n }, [status]);\n\n return (\n
\n {\n setFocused(false);\n onBlur?.(event);\n }}\n onChange={(event) => {\n onValueChange(event.target.value.replace(/\\s/gu, \"\"));\n }}\n onPaste={(event) => {\n onPaste?.(event);\n if (event.defaultPrevented || event.currentTarget.readOnly) return;\n const pasted = event.clipboardData.getData(\"text\");\n const normalized = pasted.replace(/\\s/gu, \"\");\n if (normalized === pasted) return;\n event.preventDefault();\n const field = event.currentTarget;\n const start = field.selectionStart ?? 0;\n const end = field.selectionEnd ?? start;\n // Native maxlength still owns ordinary edits. Formatted paste is\n // normalized before applying that same remaining input capacity.\n const available = Math.max(\n 0,\n length - field.value.length + end - start,\n );\n field.setRangeText(\n normalized.slice(0, available),\n start,\n end,\n \"end\",\n );\n setCursor(field.selectionStart ?? field.value.length);\n onValueChange(field.value);\n }}\n onFocus={(event) => {\n setFocused(true);\n setCursor(event.currentTarget.selectionStart ?? value.length);\n onFocus?.(event);\n }}\n onSelect={(event) => {\n setCursor(event.currentTarget.selectionStart ?? value.length);\n onSelect?.(event);\n }}\n ref={input}\n value={characters.join(\"\")}\n />\n
\n {Array.from({ length }, (_, index) => (\n \n {characters[index] ?? \"\"}\n {focused && index === active && characters.length < length ? (\n \n ) : null}\n \n ))}\n
\n
\n );\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-code-input": { "position": "relative", "display": "inline-grid", "justifySelf": "start", "width": "max-content" }, ".caps-code-field": { "position": "absolute", "inset": "0", "zIndex": 1, "width": "100%", "height": "100%", "border": "0", "background": "transparent", "color": "transparent", "caretColor": "transparent", "fontSize": "1rem", "opacity": 0, "cursor": "text" }, ".caps-code-slots": { "display": "grid", "gridAutoColumns": "max-content", "gridAutoFlow": "column", "gap": "var(--spacing-xs)" }, ".caps-code-slot": { "position": "relative", "width": "var(--size)", "justifyContent": "center", "paddingInline": "0", "fontFamily": "var(--font-numeric, var(--font-mono))", "fontSize": "1.125rem", "fontWeight": 600 }, ".caps-code-slot[data-active=\"true\"]": { "--caps-input-edge": "var(--color-info)", "--caps-input-edge-width": "2px" }, ".caps-code-input[data-status=\"invalid\"] .caps-code-slot": { "--caps-input-edge": "var(--color-error)", "--caps-input-edge-width": "1px" }, ".caps-code-input[data-status=\"accepted\"] .caps-code-slot": { "--caps-input-edge": "var(--color-success)", "--caps-input-edge-width": "1px" }, ".caps-code-input .caps-code-slot[data-active=\"true\"]": { "--caps-input-edge-width": "2px" }, ".caps-code-caret": { "width": "2px", "height": "1.1em", "borderRadius": "var(--radius-selector)", "background": "currentColor", "animation": "caps-code-caret calc(var(--stipe-motion-slow) * 4)\n steps(2, jump-none) infinite" }, "@media (forced-colors: active)": { ".caps-code-slot[data-active=\"true\"]": { "outline": "2px solid Highlight", "outlineOffset": "2px" } } }, "@property --caps-game-host-ink": { "syntax": "\"\"", "inherits": "true", "initialValue": "black" } } }