Enter, paste, or autofill a verification code with native form support.
Default
Enter or paste the six-digit code.
Sizes
Form and Completion
Sizes and States
Purpose
A one-time code input gives each character its own slot and lets people type or paste the whole code.
Parts & Composition
Wrap the visible slots in OTPInputGroup inside OTPInput. Give each slot its index. Use the separator part between groups when the code has a visual break.
API & Props
| Part / Prop | Purpose |
|---|---|
OTPInput | Root container & hidden input (maxLength, pattern: 'digits' | 'alphanumeric' | 'letters' | RegExp, value, defaultValue, onValueChange, onValueCommit, inputMode, autoComplete, textAlign, disabled, readOnly, required, name, form, controller, size, success) |
OTPInputGroup | Flex run of adjacent slots |
OTPInputSlot | Indexed character cell (index zero-based, animated default true, or custom ({ char, active, hasFakeCaret }) => ReactNode) |
OTPInputSeparator | Decorative divider between groups (defaults to '–', aria-hidden="true") |
size | xs (28px), sm (32px), md (40px), lg (48px) via controlHeights (h-7–h-12 + aspect-square slots) |
success | Applies verified emerald border (border-emerald-500) and active ring (ring-emerald-500/25) |
createOTPInputController() | Programmatic getValue(), setValue(), clear(), focus(), and select() |
Common props in detail
| Prop | Purpose |
|---|---|
value / defaultValue | Use a string so leading zeroes are preserved. |
onValueCommit | Runs when a change fills the code, including paste and autofill. Changing an already full code runs it again. |
success | Set from the app’s verification result. A full input does not imply success. |
State & forms
The value is always a string (preserving leading zeros). onValueCommit fires once all maxLength slots are filled. Passing name and required participates in native form submission and reset.
Interaction states
| State | Behavior |
|---|---|
| Rest | Slots render with border-input bg-card text-foreground shadow-sm. |
| Hover / Active slot | useSlidingHighlight tracks the hovered or data-active slot (slidingHighlight); the active slot gets focusRing (border-ring/30 ring-3 ring-ring/15) and an animated data-fake-caret pulse when empty. |
| Character entry | When animated is true, newly entered characters slide/fade/blur in (duration-180). |
| Invalid | aria-invalid="true" applies border-destructive, data-active:ring-destructive/25, and a 280ms horizontal wobble (otp-wobble). |
| Success | success (data-success) applies border-emerald-500 and data-active:ring-emerald-500/25. |
| Disabled / Read-only | data-disabled sets opacity-50 and cursor-not-allowed; readOnly keeps slots readable/copyable with cursor-default. |
Theming, Layout & Responsiveness
Uses shadcn semantic tokens (input, secondary, foreground, muted-foreground, ring, destructive) plus emerald-500 for success, compatible with light, dark, and custom themes.
| Attribute / CSS Var | Meaning |
|---|---|
data-slot="otp-input" / otp-input-group / otp-input-slot / otp-input-separator / otp-input-highlight | Stable slot selectors on each part. |
data-size, data-success, data-disabled | Root size (xs–lg), verified state, and disabled state. |
data-active, data-filled, data-fake-caret | Present on the active slot, filled slots, and empty focused slot displaying a synthetic caret. |
OTPInput uses inline-flex max-w-full touch-manipulation items-center gap-2 with tabular-nums on every slot so digits never shift width.
Motion & Accessibility
id, autoFocus, aria-label, aria-labelledby, aria-describedby, and aria-invalid forward directly to the underlying native <input>. Pair with Field + FieldLabel or provide aria-label.
Guidance for Coding Agents
Install using the command in the Install tab. Read this Info page before implementing.
Set the code length and pattern, then compose indexed slots in order. Keep the code as a string and verify it in the app. Set success or invalid feedback only after verification, and keep codes out of logs.
Render OTPInputSlot with zero-based index from 0 to maxLength - 1.
Start from the closest Preview → Usage example and use this page’s API table for component parts and options. For inherited props, callbacks, keyboard behavior, and rendering options, consult UI SDK Otp Input.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/otp-input'use client';
import type { OTPInputController, OTPInputOptions, OTPInputPattern } from '@ui-sdk/core/otp-input';
import {
createOTPInputController,
OTPInput as SDKOTPInput,
OTPInputGroup as SDKOTPInputGroup,
OTPInputSeparator as SDKOTPInputSeparator,
OTPInputSlot as SDKOTPInputSlot,
} from '@ui-sdk/react/otp-input';
import { mergeProps } from '@ui-sdk/react/primitive';
import { type ComponentProps, createContext, useContext, useMemo } from 'react';
import { buttonSurfaces } from '@/components/devvarena-ui/button';
import { useSlidingHighlight } from '@/hooks/use-sliding-highlight';
import { ValueTransition } from '@/hooks/use-value-transition';
import {
controlHeights,
controlTextSizes,
focusRing,
partClass,
type StandardControlSize,
slidingHighlight,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
type OTPInputSize = StandardControlSize;
const OTPSizeContext = createContext<OTPInputSize>('md');
type OTPInputProps = ComponentProps<typeof SDKOTPInput> & {
size?: OTPInputSize;
success?: boolean;
};
function OTPInput({
size = 'md',
success = false,
className,
children,
ref,
...props
}: OTPInputProps) {
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector: '[data-slot="otp-input-slot"]:not([data-disabled])',
activeAttribute: 'data-active',
disabled: props.disabled || props.readOnly,
});
const rootRef = useMemo(
() => (ref ? mergeProps({ ref: containerRef }, { ref }).ref : containerRef),
[containerRef, ref],
);
return (
<OTPSizeContext value={size}>
<SDKOTPInput
{...props}
ref={rootRef}
data-size={size}
data-success={success || undefined}
className={partClass(
cn(
'group/otp group/control relative isolate inline-flex max-w-full touch-manipulation items-center gap-2 [--concentric-inset:0px] data-disabled:opacity-50 motion-safe:has-[input[aria-invalid=true]]:animate-[otp-wobble_280ms_ease-out]',
controlTextSizes[size],
),
className,
)}
>
{(state) => (
<>
<style href="otp-feedback" precedence="components">
{
'@keyframes otp-wobble{0%,100%{translate:0}20%,60%{translate:-4px}40%,80%{translate:4px}}'
}
</style>
<span
aria-hidden="true"
data-slot="otp-input-highlight"
className={cn(slidingHighlight, 'z-10')}
style={highlightStyle}
/>
{typeof children === 'function' ? children(state) : children}
</>
)}
</SDKOTPInput>
</OTPSizeContext>
);
}
function OTPInputGroup({ className, ...props }: ComponentProps<typeof SDKOTPInputGroup>) {
return <SDKOTPInputGroup {...props} className={partClass('flex min-w-0 gap-1', className)} />;
}
type OTPInputSlotProps = ComponentProps<typeof SDKOTPInputSlot> & {
animated?: boolean;
};
function OTPInputSlot({ animated = true, className, children, ...props }: OTPInputSlotProps) {
const size = useContext(OTPSizeContext);
return (
<SDKOTPInputSlot
{...props}
data-size={size}
className={partClass(
cn(
'relative grid aspect-square min-w-0 place-items-center rounded-lg border font-medium tabular-nums transition-[border-color,box-shadow,filter] data-readonly:cursor-default group-data-success/otp:border-[var(--status-success,var(--color-emerald-500))] group-data-success/otp:data-active:ring-[color-mix(in_oklab,var(--status-success,var(--color-emerald-500))_25%,transparent)] data-fake-caret:after:pointer-events-none data-fake-caret:after:absolute data-fake-caret:after:h-1/2 data-fake-caret:after:w-px data-fake-caret:after:bg-current motion-safe:data-fake-caret:after:animate-pulse motion-reduce:transition-none',
buttonSurfaces.secondary,
controlHeights[size],
focusRing,
),
className,
)}
>
{children ?? (({ char }) => <ValueTransition value={char ?? ''} enabled={animated} />)}
</SDKOTPInputSlot>
);
}
function OTPInputSeparator({
children = '–',
className,
...props
}: ComponentProps<typeof SDKOTPInputSeparator>) {
return (
<SDKOTPInputSeparator
aria-hidden="true"
{...props}
className={partClass('shrink-0 text-muted-foreground', className)}
>
{children}
</SDKOTPInputSeparator>
);
}
export {
createOTPInputController,
OTPInput,
type OTPInputController,
OTPInputGroup,
type OTPInputOptions,
type OTPInputPattern,
OTPInputSeparator,
type OTPInputSize,
OTPInputSlot,
};
import type { ButtonOptions } from '@ui-sdk/core/button';
import { Button as ButtonPrimitive } from '@ui-sdk/react/button';
import { cva, type VariantProps } from 'class-variance-authority';
import { Loader2 } from 'lucide-react';
import type { ComponentProps, ReactNode } from 'react';
import { controlHeights, controlTextSizes, focusRing } from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
/*
* Clean tactile button surfaces with a subtle top highlight, contact shadow,
* and 2% press scale using pure Tailwind/theme tokens.
*/
const flatPress = 'motion-safe:not-data-disabled:not-data-pending:active:scale-[0.985]';
const activeInsetShadow =
'active:shadow-[inset_0_1px_3px_rgb(0_0_0/0.12),0_1px_2px_rgb(0_0_0/0.06)] dark:active:shadow-[inset_0_1px_3px_rgb(0_0_0/0.18),0_1px_2px_rgb(0_0_0/0.1)]';
const tactileFilled =
'bg-[linear-gradient(180deg,rgb(255_255_255/0.16),rgb(255_255_255/0)_75%)] shadow-[inset_0_1.5px_0_rgb(255_255_255/0.22),inset_0_-1px_0_rgb(0_0_0/0.12),0_1px_3px_0_rgb(0_0_0/0.1),0_1px_2px_-1px_rgb(0_0_0/0.1)] active:shadow-[inset_0_1px_3px_rgb(0_0_0/0.18),0_1px_2px_rgb(0_0_0/0.1)]';
const tactileNeutral = `bg-[linear-gradient(180deg,rgb(255_255_255/0.35),transparent_48%,rgb(0_0_0/0.025)_100%)] shadow-[inset_0_1px_0_rgb(255_255_255/0.65),inset_0_-1px_0_rgb(0_0_0/0.06),0_1px_3px_0_rgb(0_0_0/0.1),0_1px_2px_-1px_rgb(0_0_0/0.1)] dark:bg-[linear-gradient(180deg,rgb(255_255_255/0.06),transparent_48%,rgb(0_0_0/0.12)_100%)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.1),inset_0_-1px_0_rgb(0_0_0/0.12),0_1px_3px_0_rgb(0_0_0/0.1),0_1px_2px_-1px_rgb(0_0_0/0.1)] ${activeInsetShadow}`;
/** Surface map for button variants, shared with Toggle, Tabs, Radio, Checkbox, and Switch. */
const buttonSurfaces = {
primary: `border-[color-mix(in_oklch,var(--primary),black_8%)] bg-primary text-primary-foreground ${tactileFilled} ${flatPress}`,
secondary: ` bg-popover text-popover-foreground border-[color-mix(in_oklch,var(--muted),black_5%)] ${tactileNeutral} ${flatPress}`,
outline: `border-input bg-accent/10 text-foreground shadow-sm hover:text-accent-foreground ${activeInsetShadow} ${flatPress}`,
ghost: `border-transparent text-foreground hover:bg-muted ${activeInsetShadow} ${flatPress}`,
destructive: `border-[color-mix(in_oklch,var(--destructive),black_8%)] bg-destructive text-[color:var(--destructive-foreground,white)] ${tactileFilled} ${flatPress}`,
tertiary: `border-transparent bg-accent text-accent-foreground ${activeInsetShadow} ${flatPress}`,
'destructive-soft': `border-transparent bg-destructive/10 text-destructive dark:bg-destructive/20 ${activeInsetShadow} ${flatPress}`,
link: 'border-transparent text-primary underline-offset-4 hover:underline',
} as const;
type ButtonVariant = keyof typeof buttonSurfaces;
const buttonBase = cva(
[
// layout
'group/button relative isolate inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-lg border text-sm font-medium',
// interaction
'cursor-pointer select-none touch-manipulation',
'transition-[background-color,border-color,box-shadow,translate,scale,filter] duration-150 ease-out motion-reduce:transition-none',
focusRing,
// 44px touch target on coarse pointers without changing the visual size
'[@media(pointer:coarse)]:after:absolute [@media(pointer:coarse)]:after:inset-1/2 [@media(pointer:coarse)]:after:min-h-11 [@media(pointer:coarse)]:after:min-w-11 [@media(pointer:coarse)]:after:-translate-1/2',
// states
'disabled:cursor-not-allowed aria-disabled:opacity-50 data-disabled:cursor-not-allowed data-disabled:opacity-50 data-pending:cursor-wait',
// icons
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-(--icon-size,1rem) [&>span:has(>svg):not([class*='size-'])]:size-(--icon-size,1rem)",
],
{
variants: {
size: {
md: `${controlHeights.md} ${controlTextSizes.md} gap-2 px-4 [--icon-size:1.2rem]`,
xs: `${controlHeights.xs} ${controlTextSizes.xs} gap-1 px-2.5 [--icon-size:0.875rem]`,
sm: `${controlHeights.sm} ${controlTextSizes.sm} gap-1.5 px-3 [--icon-size:1rem]`,
lg: `${controlHeights.lg} ${controlTextSizes.lg} gap-2 px-6 [--icon-size:1.25rem]`,
icon: `${controlHeights.md} aspect-square [--icon-size:1.2rem]`,
'icon-xs': `${controlHeights.xs} aspect-square [--icon-size:0.875rem]`,
'icon-sm': `${controlHeights.sm} aspect-square [--icon-size:1rem]`,
'icon-lg': `${controlHeights.lg} aspect-square [--icon-size:1.25rem]`,
},
},
defaultVariants: { size: 'md' },
},
);
type ButtonVariantProps = VariantProps<typeof buttonBase> & {
variant?: ButtonVariant;
};
function buttonVariants({
variant = 'primary',
size,
className,
}: ButtonVariantProps & { className?: string } = {}) {
return cn(buttonBase({ size }), buttonSurfaces[variant], className);
}
type ButtonProps = Omit<
ComponentProps<typeof ButtonPrimitive>,
keyof ButtonOptions | 'className' | 'children'
> &
ButtonOptions &
ButtonVariantProps & {
children?: ReactNode;
className?: string;
/** Prevent repeated activation and display an inline spinner without replacing the label. */
loading?: boolean;
};
const spinner = (
<Loader2
aria-hidden="true"
data-slot="spinner"
className="hidden size-(--icon-size,1rem) animate-spin in-data-pending:inline-block in-data-loading:inline-block motion-reduce:animate-none"
/>
);
function Button({
className,
variant = 'primary',
size = 'md',
loading = false,
disabled,
children,
'aria-busy': ariaBusy,
...props
}: ButtonProps) {
return (
<ButtonPrimitive
{...props}
className={buttonVariants({ variant, size, className })}
data-size={size}
data-variant={variant}
data-loading={loading || undefined}
disabled={disabled || loading}
aria-busy={loading || ariaBusy}
>
{spinner}
{children}
</ButtonPrimitive>
);
}
export { Button, type ButtonProps, type ButtonVariant, buttonSurfaces, buttonVariants };
'use client';
import { type CSSProperties, useCallback, useMemo } from 'react';
export type UseSlidingHighlightOptions = {
/** Mark eligible descendants with this selector. */
itemSelector?: string;
/** Resolve a row when the primitive focuses its parent instead of the row itself. */
focusItemSelector?: string;
disabled?: boolean;
/** Follow a primitive-owned state attribute on eligible items. */
activeAttribute?: string;
};
function highlightProperties(activeAttribute?: string) {
const prefix = activeAttribute ? `--sliding-highlight-${activeAttribute}` : '--sliding-highlight';
return {
left: `${prefix}-left`,
top: `${prefix}-top`,
width: `${prefix}-width`,
height: `${prefix}-height`,
opacity: `${prefix}-opacity`,
};
}
type Clipper = { el: Element; x: boolean; y: boolean };
/** Decorative hover/focus feedback; zero React state or useEffect. */
export function useSlidingHighlight({
itemSelector = '[data-highlight-item]',
focusItemSelector,
disabled = false,
activeAttribute,
}: UseSlidingHighlightOptions = {}) {
const properties = useMemo(() => highlightProperties(activeAttribute), [activeAttribute]);
const highlightStyle = useMemo<CSSProperties>(
() => ({
position: 'absolute',
top: 0,
left: 0,
width: `var(${properties.width}, 0px)`,
height: `var(${properties.height}, 0px)`,
transform: `translate3d(var(${properties.left}, 0px), var(${properties.top}, 0px), 0)`,
opacity: `var(${properties.opacity}, 0)`,
pointerEvents: 'none',
}),
[properties],
);
const containerRef = useCallback(
(container: HTMLElement | null) => {
if (!container || disabled) return;
const activeSelector = activeAttribute ? `${itemSelector}[${activeAttribute}]` : null;
const style = container.style;
let hovered: HTMLElement | null = null;
let focused: HTMLElement | null = null;
let observed: HTMLElement | null = null;
let clippers: Clipper[] = [];
let visible: boolean | null = null;
let pLeft = NaN;
let pTop = NaN;
let pWidth = NaN;
let pHeight = NaN;
const findItem = (target: EventTarget | null) => {
const item = target instanceof Element ? target.closest<HTMLElement>(itemSelector) : null;
return item && item !== container && container.contains(item) ? item : null;
};
// Programmatic/pointer focus must not pin a popover's initially focused row.
const findFocusedItem = (target: EventTarget | null) => {
if (!(target instanceof Element) || !target.matches(':focus-visible')) return null;
const inner = focusItemSelector ? target.querySelector(focusItemSelector) : null;
return findItem(inner ?? target);
};
const setVisible = (next: boolean) => {
if (visible === next) return;
visible = next;
style.setProperty(properties.opacity, next ? '1' : '0');
};
// Runs only when the tracked item changes, so getComputedStyle is not called per frame.
const track = (item: HTMLElement | null) => {
if (observed === item) return;
if (observed) resize?.unobserve(observed);
if (item) resize?.observe(item);
observed = item;
clippers = [];
for (let el = item?.parentElement; el && el !== container; el = el.parentElement) {
const { overflowX, overflowY } = getComputedStyle(el);
const x = overflowX !== 'visible';
const y = overflowY !== 'visible';
if (x || y) clippers.push({ el, x, y });
}
};
const measure = () => {
const item = activeSelector
? container.querySelector<HTMLElement>(activeSelector)
: focused?.matches(itemSelector) && container.contains(focused)
? focused
: hovered;
const valid = item && container.contains(item) && item.matches(itemSelector);
track(valid ? item : null);
if (!valid) return setVisible(false);
const outer = container.getBoundingClientRect();
const inner = item.getBoundingClientRect();
if (!outer.width || !outer.height || !inner.width || !inner.height) {
return setVisible(false);
}
let { left: cLeft, top: cTop, right: cRight, bottom: cBottom } = inner;
for (const { el, x, y } of clippers) {
const r = el.getBoundingClientRect();
if (x) {
cLeft = Math.max(cLeft, r.left);
cRight = Math.min(cRight, r.right);
}
if (y) {
cTop = Math.max(cTop, r.top);
cBottom = Math.min(cBottom, r.bottom);
}
}
if (cRight <= cLeft || cBottom <= cTop) return setVisible(false);
const scaleX = container.offsetWidth / outer.width;
const scaleY = container.offsetHeight / outer.height;
const left = (cLeft - outer.left) * scaleX - container.clientLeft + container.scrollLeft;
const top = (cTop - outer.top) * scaleY - container.clientTop + container.scrollTop;
const width = (cRight - cLeft) * scaleX;
const height = (cBottom - cTop) * scaleY;
if (left !== pLeft) {
pLeft = left;
style.setProperty(properties.left, `${left}px`);
}
if (top !== pTop) {
pTop = top;
style.setProperty(properties.top, `${top}px`);
}
if (width !== pWidth) {
pWidth = width;
style.setProperty(properties.width, `${width}px`);
}
if (height !== pHeight) {
pHeight = height;
style.setProperty(properties.height, `${height}px`);
}
setVisible(true);
};
const resize = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
const mutation = new MutationObserver(measure);
const onPointer = (e: PointerEvent) => {
if (e.pointerType === 'touch') return;
const next = findItem(e.type === 'pointerout' ? e.relatedTarget : e.target);
if (next === hovered) return;
hovered = next;
measure();
};
const onPointerLeave = (e: PointerEvent) => {
if (e.pointerType === 'touch') return;
hovered = null;
measure();
};
const onFocus = (e: FocusEvent) => {
focused = findFocusedItem(e.type === 'focusin' ? e.target : e.relatedTarget);
measure();
};
resize?.observe(container);
mutation.observe(container, {
childList: true,
subtree: true,
...(activeAttribute && {
attributeFilter: [activeAttribute, 'data-disabled', 'aria-disabled'],
}),
});
container.addEventListener('scroll', measure, { capture: true, passive: true });
if (!activeSelector) {
focused = findFocusedItem(document.activeElement);
container.addEventListener('pointerover', onPointer);
container.addEventListener('pointermove', onPointer);
container.addEventListener('pointerout', onPointer);
container.addEventListener('pointerleave', onPointerLeave);
container.addEventListener('pointercancel', onPointerLeave);
container.addEventListener('focusin', onFocus);
container.addEventListener('focusout', onFocus);
}
measure();
return () => {
resize?.disconnect();
mutation.disconnect();
container.removeEventListener('scroll', measure, true);
if (!activeSelector) {
container.removeEventListener('pointerover', onPointer);
container.removeEventListener('pointermove', onPointer);
container.removeEventListener('pointerout', onPointer);
container.removeEventListener('pointerleave', onPointerLeave);
container.removeEventListener('pointercancel', onPointerLeave);
container.removeEventListener('focusin', onFocus);
container.removeEventListener('focusout', onFocus);
}
for (const v of Object.values(properties)) style.removeProperty(v);
};
},
[itemSelector, focusItemSelector, disabled, activeAttribute, properties],
);
return { containerRef, highlightStyle };
}
'use client';
import { type ComponentProps, useState } from 'react';
import { cn } from '@/lib/utils';
export type UseValueTransitionOptions = {
/** Whether characters animate when the value changes. Defaults to `true`. */
enabled?: boolean;
/** Roll direction. `auto` rolls up when a number grows (or for text), down when it shrinks. */
direction?: 'auto' | 'up' | 'down';
/** Delay in ms between consecutive changed characters. Defaults to `28`. */
stagger?: number;
/**
* Animation granularity:
* - `auto` (default): per-character for numeric values, whole-string for text.
* - `char`: always animate per-character.
* - `whole`: always animate the entire value as one unit.
*/
mode?: 'auto' | 'char' | 'whole';
};
export type TransitionChar = {
key: string;
char: string;
/** The character being replaced. Only set when this character should roll. */
prev?: string;
/** Transition delay in ms. */
delay: number;
};
const MAX_DELAY = 140;
const hasDigit = (text: string) => /\d/.test(text);
const isNumeric = (text: string) => hasDigit(text) && !/[a-zA-Z]/.test(text);
const toNumber = (text: string) => Number.parseFloat(text.replace(/[^\d.-]/g, ''));
/**
* Diffs `value` against its previous value and returns per-character data, so
* only the characters that actually changed roll, one after another.
*
* - Numbers align from the right (the ones digit stays the ones digit),
* text aligns from the left.
* - Pure derivation from state, with no effects or DOM reads, so it works for
* any value: numbers, formatted numbers, labels, statuses.
*/
export function useValueTransition(
value: string | number | null | undefined,
{
enabled = true,
direction = 'auto',
stagger = 28,
mode = 'auto',
}: UseValueTransitionOptions = {},
) {
const text = value == null ? '' : String(value);
const [state, setState] = useState({ text, prev: text });
if (state.text !== text) setState({ text, prev: state.text });
const numeric = isNumeric(state.text);
const perChar = mode === 'char' || (mode === 'auto' && numeric);
const dir: 1 | -1 =
direction === 'up'
? 1
: direction === 'down'
? -1
: numeric && hasDigit(state.prev) && toNumber(state.text) < toNumber(state.prev)
? -1
: 1;
if (!perChar) {
const changed = enabled && state.prev !== state.text;
const chars: TransitionChar[] = state.text
? [
{
key: `whole-${state.text}`,
char: state.text,
prev: changed ? state.prev : undefined,
delay: 0,
},
]
: [];
return { text: state.text, chars, dir };
}
const next = [...state.text];
const old = [...state.prev];
const offset = numeric ? old.length - next.length : 0;
const fromEmpty = state.prev === '' && state.text !== '';
// Stagger starts at the least significant end: ones digit first for numbers.
let rank = 0;
const chars: TransitionChar[] = new Array(next.length);
for (let step = 0; step < next.length; step++) {
const i = numeric ? next.length - 1 - step : step;
const char = next[i];
const prevChar = old[i + offset];
const shouldRoll = enabled && (fromEmpty || (prevChar !== undefined && prevChar !== char));
chars[i] = {
// Keyed by position + char: a changed character remounts (replaying the
// animation, even on rapid changes) while untouched ones stay mounted.
key: `${numeric ? next.length - i : i}-${char}`,
char,
prev: shouldRoll ? (prevChar ?? '') : undefined,
delay: shouldRoll ? Math.min(rank++ * stagger, MAX_DELAY) : 0,
};
}
return { text: state.text, chars, dir };
}
const motion =
'transition-[translate,opacity,filter] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none';
export type ValueTransitionProps = Omit<ComponentProps<'span'>, 'children'> &
UseValueTransitionOptions & {
value: string | number | null | undefined;
/** Whether to apply a subtle blur during the transition. Defaults to `true`. */
blur?: boolean;
};
/**
* Drop-in display for any value: `<ValueTransition value={count} />`.
* Inherits font, size and color from its parent.
*/
export function ValueTransition({
value,
enabled,
direction,
stagger,
mode,
blur = true,
className,
...props
}: ValueTransitionProps) {
const { text, chars, dir } = useValueTransition(value, { enabled, direction, stagger, mode });
return (
<span
{...props}
className={cn(
'inline-flex overflow-hidden tabular-nums [mask-image:linear-gradient(to_bottom,transparent,#000_14%,#000_88%,transparent)]',
className,
)}
>
<span className="sr-only"> {text} </span>
<span aria-hidden="true" className="inline-flex">
{chars.map(({ key, char, prev, delay }) => (
<span
key={key}
className={cn(
'relative inline-block whitespace-pre leading-normal',
dir > 0 ? '[--d:1]' : '[--d:-1]',
)}
>
{prev === undefined ? (
char
) : (
<>
<span
style={{ transitionDelay: `${delay}ms` }}
className={cn(
'inline-block starting:translate-y-[calc(var(--d)*100%)] starting:opacity-0',
blur && 'starting:blur-[2px]',
motion,
)}
>
{char}
</span>
<span
aria-hidden="true"
style={{ transitionDelay: `${delay}ms` }}
className={cn(
'absolute inset-0 translate-y-[calc(var(--d)*-100%)] opacity-0 starting:translate-y-0 starting:opacity-100 motion-reduce:hidden',
blur && 'blur-[2px] starting:blur-none',
motion,
)}
>
{prev}
</span>
</>
)}
</span>
))}
</span>
</span>
);
}
import { cn } from '@/lib/utils';
type ClassValue = string | false | null | undefined;
type PartClassValue<State> = ClassValue | ((state: State) => ClassValue);
/** Composes static class names and UI-SDK state class functions into a single `className` prop. */
export function partClass<State>(...parts: PartClassValue<State>[]) {
if (parts.some((part) => typeof part === 'function')) {
return (state: State) =>
cn(...parts.map((part) => (typeof part === 'function' ? part(state) : part)));
}
return cn(...(parts as ClassValue[]));
}
export const surfacePadding = 'p-1 [--surface-padding:1.5rem] [--concentric-inset:0.25rem]';
export const surfaceRegionInset = 'p-[calc(var(--surface-padding,1rem)-0.5rem)]';
export const surfaceHeaderRadius = 'rounded-t-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
export const surfaceFooterRadius = 'rounded-b-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
/** Concentric inner radius (`outer - inset`); set `[--concentric-inset:0.125rem]` on `p-0.5` rails (defaults to `0.25rem` for `p-1`). */
export const concentricRadius =
'rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))]';
export const surfaceBodyPadding =
'py-[max(0px,calc(var(--surface-padding,1rem)-1rem))] has-[>[data-slot=list]:not([data-variant=plain])]:p-0 has-[>[data-slot=list-items-container]]:p-0';
export type StandardControlSize = 'xs' | 'sm' | 'md' | 'lg';
/** Standard control heights (`28px / 32px / 40px / 48px`) for buttons, inputs, selects, tabs, and sliders. */
export const controlHeights = {
xs: 'h-7',
sm: 'h-8',
md: 'h-10',
lg: 'h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard minimum control heights (`28px / 32px / 40px / 48px`) for expandable controls and menu items. */
export const controlMinHeights = {
xs: 'min-h-7',
sm: 'min-h-8',
md: 'min-h-10',
lg: 'min-h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard control text sizes (`xs / xs / sm / base`) paired with `StandardControlSize`. */
export const controlTextSizes = {
xs: 'text-xs',
sm: 'text-xs',
md: 'text-sm',
lg: 'text-base',
} as const satisfies Record<StandardControlSize, string>;
/** Compact control heights (`1.25rem / 1.3rem / 1.625rem / 1.75rem`), one step smaller than standard, for switches and compact controls. */
export const compactControlHeights = {
xs: 'h-[1.3rem]',
sm: 'h-[1.4rem]',
md: 'h-[1.5rem]',
lg: 'h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Compact minimum control heights (`1rem / 1.25rem / 1.5rem / 1.75rem`) for badges and tooltips. */
export const compactControlMinHeights = {
xs: 'min-h-[1.3rem]',
sm: 'min-h-[1.4rem]',
md: 'min-h-[1.5rem]',
lg: 'min-h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Universal keyboard focus + invalid ring/border styles shared across controls. */
export const focusRing =
'touch-manipulation outline-none focus-visible:border-ring/30 transition-ring focus-visible:ring-3 focus-visible:ring-ring/15 focus-visible:brightness-[0.97] dark:focus-visible:brightness-[1.15] has-[:focus-visible]:border-ring/30 has-[:focus-visible]:ring-3 has-[:focus-visible]:ring-ring/15 has-[:focus-visible]:brightness-[0.97] dark:has-[:focus-visible]:brightness-[1.15] data-active:border-ring/30 data-active:ring-3 data-active:ring-ring/15 data-active:brightness-[0.97] dark:data-active:brightness-[1.15] data-open:border-ring/30 data-open:ring-3 data-open:ring-ring/15 data-open:brightness-[0.97] dark:data-open:brightness-[1.15] data-disabled:cursor-not-allowed data-disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/25 data-invalid:border-destructive data-invalid:ring-3 data-invalid:ring-destructive/25 has-[[data-invalid]]:border-destructive has-[[data-invalid]]:ring-3 has-[[data-invalid]]:ring-destructive/25 group-aria-invalid/control:border-destructive group-aria-invalid/control:ring-3 group-aria-invalid/control:ring-destructive/25 group-data-invalid/control:border-destructive group-data-invalid/control:ring-3 group-data-invalid/control:ring-destructive/25 group-has-[input[aria-invalid=true]]/control:border-destructive group-has-[input[aria-invalid=true]]/control:ring-3 group-has-[input[aria-invalid=true]]/control:ring-destructive/25 hover:brightness-[0.97] dark:hover:brightness-[1.15]';
/** Shared sliding highlight indicator base (pointer-safe, concentric inner radius inside rounded-lg containers, 200ms transition). */
export const slidingHighlight =
'pointer-events-none -z-10 rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))] bg-primary/10 [clip-path:inset(0px_round_max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem))))] transition-[transform,width,height,opacity] duration-200 ease-out motion-reduce:transition-none';
export const textFieldSurfaces = {
filled: 'border-input bg-card text-card-foreground',
outline: 'border-input bg-transparent text-foreground dark:bg-transparent',
ghost: 'border-transparent bg-muted text-foreground shadow-none',
underline:
'rounded-none border-0 border-b-2 border-input bg-transparent px-0 text-foreground shadow-none focus-visible:border-ring focus-visible:ring-0 aria-invalid:ring-0 data-invalid:ring-0 dark:bg-transparent',
} as const;
export const textFieldUnderlineMotion =
'border-transparent! bg-origin-border bg-bottom bg-no-repeat [--underline-color:var(--primary)] [background-image:linear-gradient(var(--underline-color),var(--underline-color)),linear-gradient(var(--input),var(--input))] [background-size:0%_2px,100%_2px] focus:[background-size:100%_2px,100%_2px] aria-invalid:[--underline-color:var(--destructive)] data-invalid:[--underline-color:var(--destructive)] transition-[border-color,background-color,box-shadow,filter,background-size] duration-200 motion-reduce:transition-none';
/** Generic balanced icon & floating-label layout tokens shared across all text-field sizes. */
export const textFieldLayout = {
icon: 'size-4',
iconStart: 'start-3',
iconEnd: 'end-3',
padStart: 'ps-9',
padEnd: 'pe-9',
underlinePadStart: 'ps-7',
underlinePadEnd: 'pe-7',
floatingStart: 'start-2.5',
floatingWithIcon: 'start-8',
floatingUnderlineIcon: 'start-6',
} as const;
export const textFieldLabelSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
/** Clamps per-grapheme wave delay (ms) so total staggering stays within 300ms. */
export function clampWaveDelay(waveDelay: number, count: number): number {
return Math.max(
0,
Math.min(Number.isFinite(waveDelay) ? waveDelay : 24, 80, 300 / Math.max(1, count - 1)),
);
}
/** Shared scale/color transition for floating labels inside a `group/field` wrapper. */
export const textFieldLabelMotion =
'inline-block origin-left backdrop-blur-xs transition-[scale,color] duration-200 ease-out group-has-[input:focus]/field:scale-85 group-has-[input:not(:placeholder-shown)]/field:scale-85 rtl:origin-right motion-reduce:transition-none';
/** Resolves start/end padding for a text field when a leading or trailing icon is present. */
export function getTextFieldIconPadding(iconPosition: 'start' | 'end', underline: boolean): string {
if (iconPosition === 'start') {
return underline ? textFieldLayout.underlinePadStart : textFieldLayout.padStart;
}
return underline ? textFieldLayout.underlinePadEnd : textFieldLayout.padEnd;
}
/** Shared per-grapheme ripple transition for wave labels inside a `group/field` wrapper. */
export const textFieldWaveMotion =
'inline-block origin-left backdrop-blur-xs transition-[translate,scale,color] duration-200 ease-out group-has-[input:focus]/field:-translate-y-5 group-has-[input:focus]/field:scale-85 group-has-[input:focus]/field:text-primary group-has-[input:not(:placeholder-shown)]/field:-translate-y-5 group-has-[input:not(:placeholder-shown)]/field:scale-85 group-has-[input[aria-invalid=true]]/field:text-destructive rtl:origin-right motion-reduce:transition-none';