Enter, step, scrub, and format numeric values with native form support.
Default
Choose 1 to 12 items.
Sizes
Button Positions
Formatting and Scrubbing
Form and Validation
Custom Button Rendering
States
Purpose
A number input lets people type a number or adjust it with plus and minus buttons. It’s useful for quantities and other settings with clear limits.
Parts & Composition
Place NumberInputControl and optional step buttons inside NumberInputGroup. Wrap those parts in NumberInput so they share the same value. Use a label for the control.
API & Props
The standard step buttons are flat and share the group’s sliding highlight. Use the SDK render prop to give a step button the Button appearance.
| Part / Prop | Purpose |
|---|---|
NumberInput | Root (size: xs | sm | md | lg, animated default true, value, defaultValue, onValueChange, onValueCommit, min, max, step, largeStep, smallStep, format, locale, wheel, disabled, readOnly, required, name, form, controller, debug) |
NumberInputGroup | Input & button bar (buttonPosition: 'split' default, 'end', or 'bottom') |
NumberInputControl | Text field displaying the formatted number and mirrored rolling digits |
NumberInputDecrement, NumberInputIncrement | Step buttons (repeat while held; Shift uses largeStep) |
NumberInputScrubArea, NumberInputScrubAreaCursor | Pointer-locked drag scrubber (orientation, pixelsPerStep, controller) |
size | xs (28px), sm (32px), md (40px), lg (48px) via controlHeights |
createNumberInputController() | Programmatic getValue(), setValue(), increment(), decrement(), and focus() |
Common props in detail
| Prop | Purpose |
|---|---|
value / defaultValue | Use a number or null for an empty input. |
onValueChange | Reports valid numeric changes during editing. |
onValueCommit | Runs after an edit is committed, a step key or button is released, or scrubbing ends. |
State & forms
An empty field has value null. When name is set, the hidden input submits the unformatted number while NumberInputControl displays the Intl.NumberFormat (format / locale) string. Enter or blur commits typed text, clamps to min/max, and snaps to step.
Interaction states
| State | Behavior |
|---|---|
| Rest | NumberInputGroup renders with border-input bg-popover text-foreground shadow-sm dark:bg-popover. |
| Step / scrub | When animated is true, stepped or scrubbed digits roll vertically (300ms). The shared sliding highlight follows enabled step buttons. |
| Focus | Keyboard or input focus applies focusRing (has-[:focus-visible]:ring-3 has-[:focus-visible]:border-border has-[:focus-visible]:ring-border/50) on NumberInputGroup. |
| Invalid | aria-invalid="true" applies border-destructive and ring-3 ring-destructive/25 via focusRing. |
| Disabled / Read-only | data-disabled dims the group (opacity-50) and disables step buttons; at min/max bounds, the corresponding step button disables (opacity-40). |
Theming, Layout & Responsiveness
Uses shadcn semantic tokens (input, secondary, foreground, muted, muted-foreground, border, ring, destructive) via focusRing, compatible with light, dark, and custom themes.
| Attribute | Meaning |
|---|---|
data-slot="number-input" / number-input-group / number-input-control / number-input-decrement / number-input-increment / number-input-scrub-area | Stable slot selectors on each part. |
data-size, data-button-position | Reflects xs–lg and 'split' | 'end'. |
data-disabled, data-readonly, data-scrubbing | Propagated state attributes across parts. |
NumberInputGroup uses controlHeights[size] (h-7–h-12) and aspect-square h-full step buttons with touch-manipulation.
Motion & Accessibility
Follows the WAI-ARIA spinbutton pattern (ArrowUp/ArrowDown step, PageUp/PageDown or Shift+Arrow use largeStep, Alt+Arrow uses smallStep). Always provide a FieldLabel or aria-label.
Guidance for Coding Agents
Install using the command in the Install tab. Read this Info page before implementing.
Set bounds, step, locale, and formatting at the root. Compose the control, increment, and decrement parts and use the grouped layout option for button placement. Handle interim edits and committed values through their respective callbacks.
Place NumberInputControl and optional step buttons inside NumberInputGroup, and use format / locale for currency, units, or percentages. Keep value numeric or null and format it with the component props.
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 Number Input.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/number-input'use client';
import type {
NumberInputButtonState,
NumberInputChangeOptions,
NumberInputController,
NumberInputOptions,
NumberInputState,
NumberInputValueChangeReason,
} from '@ui-sdk/core/number-input';
import {
createNumberInputController,
NumberInput as SDKNumberInput,
NumberInputControl as SDKNumberInputControl,
NumberInputDecrement as SDKNumberInputDecrement,
NumberInputGroup as SDKNumberInputGroup,
NumberInputIncrement as SDKNumberInputIncrement,
NumberInputScrubArea as SDKNumberInputScrubArea,
NumberInputScrubAreaCursor as SDKNumberInputScrubAreaCursor,
} from '@ui-sdk/react/number-input';
import { mergeProps } from '@ui-sdk/react/primitive';
import {
type ComponentProps,
createContext,
useCallback,
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Separator } from '@/components/devvarena-ui/separator';
import { useSlidingHighlight } from '@/hooks/use-sliding-highlight';
import {
controlHeights,
controlTextSizes,
focusRing,
partClass,
type StandardControlSize,
slidingHighlight,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
type NumberInputProps = ComponentProps<typeof SDKNumberInput> & {
size?: StandardControlSize;
animated?: boolean;
};
/* Rolling digits: the real <input> keeps editing/a11y (its text is made
* transparent); an aria-hidden layer mirrors it. Only digits that changed
* remount, and Tailwind `starting:` transitions animate them (CSS only). */
const rollReasons = new Set(['step-key', 'increment-press', 'decrement-press', 'wheel', 'scrub']);
const CONTROL = '[data-slot="number-input-control"]';
type Roll = { text: string; prev: string; dir: 1 | -1 | 0 };
const NumberInputContext = createContext<{ roll: Roll | null; size: StandardControlSize }>({
roll: null,
size: 'md',
});
function NumberInput({
animated = true,
size = 'md',
className,
onValueChange,
onInput,
ref,
...props
}: NumberInputProps) {
const root = useRef<HTMLDivElement | null>(null);
const last = useRef<number | null>(props.value ?? props.defaultValue ?? null);
const dir = useRef<Roll['dir']>(0);
const [roll, setRoll] = useState<Roll>({ text: '', prev: '', dir: 0 });
const attachRoot = useMemo(() => (ref ? mergeProps({ ref: root }, { ref }).ref : root), [ref]);
// Mirror the input's displayed text so locale/formatting is respected.
const sync = useCallback(() => {
const text = root.current?.querySelector<HTMLInputElement>(CONTROL)?.value ?? '';
setRoll((r) => (r.text === text ? r : { text, prev: r.text, dir: dir.current }));
dir.current = 0;
}, []);
useLayoutEffect(() => {
void props.value;
if (animated) sync();
}, [animated, props.value, sync]); // initial + externally controlled values
const contextValue = useMemo(
() => ({ roll: animated ? roll : null, size }),
[animated, roll, size],
);
return (
<NumberInputContext value={contextValue}>
<SDKNumberInput
{...props}
ref={attachRoot}
onInput={(event) => {
onInput?.(event);
if (animated) sync();
}}
onValueChange={(value, details) => {
onValueChange?.(value, details);
if (details.canceled) return;
if (
animated &&
value !== null &&
last.current !== null &&
value !== last.current &&
rollReasons.has(details.reason)
) {
dir.current = value > last.current ? 1 : -1;
}
last.current = value;
if (animated) requestAnimationFrame(sync); // the input has updated by next frame
}}
data-size={size}
className={partClass(
cn('group/control grid min-w-0 gap-2', controlTextSizes[size]),
className,
)}
/>
</NumberInputContext>
);
}
const charClass = 'relative inline-block whitespace-pre leading-normal';
const motion =
'transition-[translate,opacity] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none';
function RollingText({ text, prev, dir }: Roll) {
const chars = [...text];
const old = [...prev];
const shift = old.length - chars.length; // align digits from the right
return (
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 flex items-center justify-center overflow-hidden tabular-nums [mask-image:linear-gradient(to_bottom,transparent,#000_28%,#000_72%,transparent)]"
>
{chars.map((ch, i) => {
const before = old[i + shift];
const key = `${chars.length - i}-${ch}`;
return dir && before !== undefined && before !== ch ? (
<span key={key} className={cn(charClass, dir > 0 ? '[--d:1]' : '[--d:-1]')}>
<span
className={cn(
'inline-block starting:translate-y-[calc(var(--d)*100%)] starting:opacity-0',
motion,
)}
>
{ch}
</span>
<span
className={cn(
'absolute inset-0 translate-y-[calc(var(--d)*-100%)] opacity-0 starting:translate-y-0 starting:opacity-100 motion-reduce:hidden',
motion,
)}
>
{before}
</span>
</span>
) : (
<span key={key} className={charClass}>
{ch}
</span>
);
})}
</span>
);
}
const buttonPositions = {
split: '',
end: '[&>[data-slot=number-input-field]]:order-[-2] [&>[data-step-separator=decrement]]:-order-1 [&>[data-slot=number-input-decrement]]:rounded-none',
bottom:
'grid grid-cols-[1fr_auto_1fr] [&>[data-slot=number-input-field]]:col-span-full [&>[data-slot=number-input-field]]:row-start-1 [&>[data-slot=number-input-field]]:min-h-10 [&>[data-slot=number-input-field]]:border-b [&>[data-slot=number-input-field]]:border-border [&>[data-slot=number-input-decrement]]:col-start-1 [&>[data-slot=number-input-decrement]]:row-start-2 [&>[data-slot=number-input-decrement]]:aspect-auto [&>[data-slot=number-input-decrement]]:min-h-9 [&>[data-slot=number-input-decrement]]:w-full [&>[data-slot=number-input-decrement]]:rounded-none [&>[data-slot=number-input-decrement]]:rounded-es-[inherit] [&>[data-step-separator=decrement]]:col-start-2 [&>[data-step-separator=decrement]]:row-start-2 [&>[data-step-separator=increment]]:hidden [&>[data-slot=number-input-increment]]:col-start-3 [&>[data-slot=number-input-increment]]:row-start-2 [&>[data-slot=number-input-increment]]:aspect-auto [&>[data-slot=number-input-increment]]:min-h-9 [&>[data-slot=number-input-increment]]:w-full [&>[data-slot=number-input-increment]]:rounded-none [&>[data-slot=number-input-increment]]:rounded-ee-[inherit]',
} as const;
type NumberInputGroupProps = ComponentProps<typeof SDKNumberInputGroup> & {
buttonPosition?: keyof typeof buttonPositions;
};
function NumberInputGroup({
buttonPosition = 'split',
className,
children,
ref,
...props
}: NumberInputGroupProps) {
const { size } = useContext(NumberInputContext);
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector:
'[data-slot=number-input-decrement]:not(:disabled):not([aria-disabled=true]),[data-slot=number-input-increment]:not(:disabled):not([aria-disabled=true])',
});
const groupRef = useMemo(
() => (ref ? mergeProps({ ref: containerRef }, { ref }).ref : containerRef),
[containerRef, ref],
);
return (
<SDKNumberInputGroup
{...props}
ref={groupRef}
data-size={size}
data-button-position={buttonPosition}
className={partClass(
cn(
'relative isolate flex min-w-0 items-stretch overflow-hidden rounded-lg border border-input bg-popover text-foreground shadow-sm transition-[border-color,box-shadow] data-disabled:opacity-50 motion-reduce:transition-none dark:bg-popover',
buttonPosition !== 'bottom' && controlHeights[size],
focusRing,
buttonPositions[buttonPosition],
),
className,
)}
>
{(state) => (
<>
<span
aria-hidden="true"
data-slot="number-input-highlight"
className={cn(
slidingHighlight,
'[clip-path:inset(2px_round_max(0px,calc(var(--radius-lg,0.5rem)-2px)))]',
)}
style={highlightStyle}
/>
{typeof children === 'function' ? children(state) : children}
</>
)}
</SDKNumberInputGroup>
);
}
function NumberInputControl({ className, ...props }: ComponentProps<typeof SDKNumberInputControl>) {
const { roll } = useContext(NumberInputContext);
const mirrored = roll !== null && roll.text !== '';
return (
<span data-slot="number-input-field" className="relative flex min-w-0 flex-1">
<SDKNumberInputControl
{...props}
className={partClass(
cn(
'w-full min-w-0 flex-1 rounded-[inherit] bg-transparent px-2.5 text-center tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed',
mirrored && 'text-transparent caret-foreground selection:bg-primary/25',
),
className,
)}
/>
{mirrored && <RollingText {...roll} />}
</span>
);
}
const stepButtonClass = cn(
'grid aspect-square h-full shrink-0 cursor-pointer touch-manipulation place-items-center bg-clip-padding text-base leading-none transition-[background-color,box-shadow,filter] focus-visible:ring-inset disabled:pointer-events-none disabled:opacity-40 aria-disabled:pointer-events-none aria-disabled:opacity-40 motion-reduce:transition-none',
focusRing,
);
const defaultDecrementIcon = <span aria-hidden="true">−</span>;
const defaultIncrementIcon = <span aria-hidden="true">+</span>;
function NumberInputDecrement({
className,
children = defaultDecrementIcon,
...props
}: ComponentProps<typeof SDKNumberInputDecrement>) {
const hasRender = props.render !== undefined;
return (
<>
<SDKNumberInputDecrement
aria-label="Decrease"
{...props}
className={partClass(
hasRender ? '' : cn(stepButtonClass, 'rounded-s-[inherit]'),
className,
)}
>
{children}
</SDKNumberInputDecrement>
{!hasRender && <Separator orientation="vertical" data-step-separator="decrement" />}
</>
);
}
function NumberInputIncrement({
className,
children = defaultIncrementIcon,
...props
}: ComponentProps<typeof SDKNumberInputIncrement>) {
const hasRender = props.render !== undefined;
return (
<>
{!hasRender && <Separator orientation="vertical" data-step-separator="increment" />}
<SDKNumberInputIncrement
aria-label="Increase"
{...props}
className={partClass(
hasRender ? '' : cn(stepButtonClass, 'rounded-e-[inherit]'),
className,
)}
>
{children}
</SDKNumberInputIncrement>
</>
);
}
function NumberInputScrubArea({
className,
orientation = 'horizontal',
...props
}: ComponentProps<typeof SDKNumberInputScrubArea>) {
return (
<SDKNumberInputScrubArea
{...props}
orientation={orientation}
className={partClass(
cn(
'w-fit select-none data-disabled:cursor-not-allowed data-readonly:cursor-default',
orientation === 'vertical' ? 'cursor-ns-resize' : 'cursor-ew-resize',
),
className,
)}
/>
);
}
function NumberInputScrubAreaCursor({
className,
children = '↔',
...props
}: ComponentProps<typeof SDKNumberInputScrubAreaCursor>) {
return (
<SDKNumberInputScrubAreaCursor
aria-hidden="true"
{...props}
className={partClass(
'pointer-events-none z-50 inline-grid size-6 place-items-center rounded-full border border-border bg-background text-sm text-foreground shadow-sm',
className,
)}
>
{children}
</SDKNumberInputScrubAreaCursor>
);
}
export {
createNumberInputController,
NumberInput,
type NumberInputButtonState,
type NumberInputChangeOptions,
NumberInputControl,
type NumberInputController,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
type NumberInputOptions,
NumberInputScrubArea,
NumberInputScrubAreaCursor,
type NumberInputState,
type NumberInputValueChangeReason,
};
import { Separator as SDKSeparator } from '@ui-sdk/react/separator';
import type { ComponentProps } from 'react';
import { partClass } from '@/lib/devvarena-ui';
type SeparatorProps = ComponentProps<typeof SDKSeparator> & { variant?: 'fade' | 'solid' };
/** Theme-derived fading rule built on `@ui-sdk/react/separator`. */
function Separator({
orientation = 'horizontal',
decorative = true,
variant = 'fade',
className,
...props
}: SeparatorProps) {
return (
<SDKSeparator
{...props}
orientation={orientation}
decorative={decorative}
data-variant={variant}
className={partClass(
'pointer-events-none shrink-0',
orientation === 'horizontal' ? 'h-px w-full' : 'w-px self-stretch',
variant === 'solid'
? 'bg-[var(--separator-color,var(--border))]'
: orientation === 'horizontal'
? 'bg-[linear-gradient(to_right,transparent,var(--separator-color,var(--border))_18%,var(--separator-color,var(--border))_82%,transparent)]'
: 'bg-[linear-gradient(to_bottom,transparent,var(--separator-color,var(--border))_18%,var(--separator-color,var(--border))_82%,transparent)]',
className,
)}
/>
);
}
export type { SeparatorProps };
export { Separator };
'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 };
}
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';