Find and run actions from a searchable list.
Default
Type to filter commands or try keywords like "invoices".
Variants
Dialog Palette (⌘K)
Press the button or ⌘K to open the palette.
Nested Pages
Choose a nested page, or press Backspace when empty to go back.
Async Search & Pending
Search async tasks and select one to see pending state.
Purpose
Find and run actions from a searchable list.
Parts & Composition
Use CommandInput and CommandList inside Command. Put CommandItem rows in the list and empty or status messages beside it. To build a palette, put Command inside the library Dialog and attach the opening shortcut to the dialog trigger.
API & Props
| Prop or part | Purpose |
|---|---|
onAction, pendingAnnouncement | Run an action. A returned Promise drives SDK pending state. |
query, onQueryChange, filter | Control the search text or change how rows match. |
pages, CommandPage, CommandItem.page | Compose nested choice lists. |
Command.size / CommandInput.variant | xs, sm, md (default), or lg scales input, items, and group labels together; variant selects shared text field surfaces. |
CommandList.slidingHighlight | Glides the shared sliding highlight across highlighted items (true by default; false falls back to bg-accent) with scroll-fade. |
CommandItem.shortcut, CommandShortcut | Bind the action on the item and display its the library keycap hint. |
Theming, Layout & Responsiveness
Command uses the same field tokens and list spacing as styled controls. Constrain the list or its surrounding surface for long result sets.
Motion & Accessibility
Arrow keys move the SDK highlight while focus remains in the input. The SDK manages filtering, activation, and pending state.
Guidance for Coding Agents
Install Command using the command in the Install tab and read this Info page. Begin with the closest Preview example, then consult the UI SDK Command reference for inherited props, state callbacks, and custom rendering.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/command'use client';
import {
Command as SDKCommand,
CommandEmpty as SDKCommandEmpty,
CommandGroup as SDKCommandGroup,
CommandGroupLabel as SDKCommandGroupLabel,
CommandInput as SDKCommandInput,
CommandItem as SDKCommandItem,
CommandItemIcon as SDKCommandItemIcon,
CommandItemText as SDKCommandItemText,
CommandList as SDKCommandList,
type CommandProps as SDKCommandProps,
CommandSeparator as SDKCommandSeparator,
CommandShortcut as SDKCommandShortcut,
CommandStatus as SDKCommandStatus,
} from '@ui-sdk/react/command';
import { cva } from 'class-variance-authority';
import { type ComponentProps, createContext, type ReactNode, useContext, useId } from 'react';
import { inputVariants } from '@/components/devvarena-ui/input';
import { Separator } from '@/components/devvarena-ui/separator';
import { useSlidingHighlight } from '@/hooks/use-sliding-highlight';
import {
clampWaveDelay,
compactControlMinHeights,
concentricRadius,
controlMinHeights,
controlTextSizes,
getTextFieldIconPadding,
partClass,
type StandardControlSize,
slidingHighlight as slidingHighlightClass,
textFieldLabelMotion,
textFieldLabelSegmenter,
textFieldLayout,
type textFieldSurfaces,
textFieldWaveMotion,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
const CommandSizeContext = createContext<StandardControlSize>('md');
const commandItemStyles = cva(
`relative flex min-w-0 cursor-pointer touch-manipulation select-none items-center ${concentricRadius} text-start outline-none [@media(pointer:coarse)]:min-h-11 data-highlighted:text-accent-foreground group-not-data-sliding-highlight/command-list:data-highlighted:bg-accent data-disabled:pointer-events-none data-disabled:opacity-50 data-pending:cursor-progress data-pending:opacity-60`,
{
variants: {
size: {
xs: `${controlMinHeights.xs} gap-1.5 px-2 ${controlTextSizes.xs}`,
sm: `${controlMinHeights.sm} gap-2 px-2.5 ${controlTextSizes.sm}`,
md: `${controlMinHeights.md} gap-2.5 px-2.5 ${controlTextSizes.md}`,
lg: `${controlMinHeights.lg} gap-2.5 px-3 ${controlTextSizes.lg}`,
} satisfies Record<StandardControlSize, string>,
},
defaultVariants: { size: 'md' },
},
);
const commandGroupLabelStyles = cva('font-medium text-muted-foreground', {
variants: {
size: {
xs: 'px-2 py-1 text-xs',
sm: 'px-2.5 py-1 text-xs',
md: 'px-2.5 py-1.5 text-xs',
lg: 'px-3 py-2 text-sm',
} satisfies Record<StandardControlSize, string>,
},
defaultVariants: { size: 'md' },
});
const HIGHLIGHT_SELECTOR = '[data-slot="command-item"]:not([data-disabled])';
type CommandProps = SDKCommandProps & { size?: StandardControlSize };
function Command({ size = 'md', className, ...props }: CommandProps) {
return (
<CommandSizeContext value={size}>
<SDKCommand
{...props}
data-size={size}
className={partClass('flex min-h-0 min-w-0 flex-col gap-2', className)}
/>
</CommandSizeContext>
);
}
type CommandInputVariant = keyof typeof textFieldSurfaces;
type CommandInputLabelVariant = 'standard' | 'floating' | 'wave';
type CommandInputProps = Omit<ComponentProps<typeof SDKCommandInput>, 'size'> & {
size?: StandardControlSize;
variant?: CommandInputVariant;
htmlSize?: number;
label?: string;
labelVariant?: CommandInputLabelVariant;
icon?: ReactNode;
iconPosition?: 'start' | 'end';
waveDelay?: number;
containerProps?: Omit<ComponentProps<'div'>, 'children'>;
};
function CommandInput({
size,
variant = 'filled',
htmlSize,
label,
labelVariant = 'standard',
icon,
iconPosition = 'start',
waveDelay = 24,
containerProps,
id,
placeholder,
className,
...props
}: CommandInputProps) {
const generatedId = useId();
const inputId = id ?? generatedId;
const contextSize = useContext(CommandSizeContext);
const inputSize = size ?? contextSize;
const animated = Boolean(label) && labelVariant !== 'standard';
const underline = variant === 'underline';
const graphemes =
animated && labelVariant === 'wave' && label
? Array.from(textFieldLabelSegmenter.segment(label), (part) => ({
text: part.segment,
offset: part.index,
}))
: [];
const delay = clampWaveDelay(waveDelay, graphemes.length);
const paddingForIcon = icon ? getTextFieldIconPadding(iconPosition, underline) : undefined;
const inputElement = (
<SDKCommandInput
{...props}
id={id ?? (label ? inputId : undefined)}
size={htmlSize}
placeholder={animated ? ' ' : placeholder}
data-size={inputSize}
data-variant={variant}
className={partClass(inputVariants({ size: inputSize, variant }), paddingForIcon, className)}
/>
);
if (!label && !icon && !containerProps) {
return inputElement;
}
return (
<div
{...containerProps}
data-slot="command-input-container"
data-disabled={props.disabled ? '' : undefined}
className={cn('w-full min-w-0', containerProps?.className)}
>
{label && !animated && (
<label
htmlFor={inputId}
data-slot="command-input-label"
className={cn(
'mb-2 block font-medium leading-5 text-foreground',
controlTextSizes[inputSize],
props.disabled && 'opacity-50',
)}
>
{label}
</label>
)}
<div
data-slot="command-input-control"
data-variant={variant}
data-size={inputSize}
className="group/field relative"
>
{inputElement}
{animated && label && (
<label
htmlFor={inputId}
data-slot="command-input-label"
className={cn(
'pointer-events-none absolute top-1/2 -translate-y-1/2 leading-5 text-muted-foreground motion-reduce:transition-none',
labelVariant === 'floating' &&
'transition-[top,color] duration-200 ease-out group-has-[input:focus]/field:top-0 group-has-[input:focus]/field:text-primary group-has-[input:not(:placeholder-shown)]/field:top-0',
'max-w-[calc(100%-1.5rem)]',
controlTextSizes[inputSize],
icon && iconPosition === 'start'
? underline
? textFieldLayout.floatingUnderlineIcon
: textFieldLayout.floatingWithIcon
: underline
? '-start-1'
: textFieldLayout.floatingStart,
icon && 'max-w-[calc(100%-3.25rem)]',
props.disabled && 'opacity-50',
)}
>
<span className="sr-only">{label}</span>
<span
aria-hidden="true"
className="-my-6 block overflow-hidden text-ellipsis whitespace-pre px-1 py-6"
>
{labelVariant === 'wave' ? (
graphemes.map(({ text, offset }, index) => (
<span
key={`${label}-${offset}`}
className={textFieldWaveMotion}
style={{ transitionDelay: `${index * delay}ms` }}
>
{text === ' ' ? '\u00A0' : text}
</span>
))
) : (
<span className={textFieldLabelMotion}>{label}</span>
)}
</span>
</label>
)}
{icon && (
<span
aria-hidden="true"
className={cn(
'pointer-events-none absolute top-1/2 inline-flex -translate-y-1/2 items-center justify-center text-muted-foreground transition-colors duration-200 group-has-[input:focus]/field:text-primary motion-reduce:transition-none [&>svg]:size-full',
textFieldLayout.icon,
iconPosition === 'start'
? underline
? 'start-0'
: textFieldLayout.iconStart
: underline
? 'end-0'
: textFieldLayout.iconEnd,
props.disabled && 'opacity-50',
)}
>
{icon}
</span>
)}
</div>
</div>
);
}
type CommandListProps = ComponentProps<typeof SDKCommandList> & {
slidingHighlight?: boolean;
};
function CommandList({ slidingHighlight = true, className, children, ...props }: CommandListProps) {
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector: HIGHLIGHT_SELECTOR,
activeAttribute: 'data-highlighted',
disabled: !slidingHighlight,
});
return (
<div
data-sliding-highlight={slidingHighlight ? '' : undefined}
className="group/command-list scroll-fade max-h-72 min-h-0 overflow-y-auto overscroll-contain [scrollbar-width:thin] [scrollbar-color:var(--border)_transparent]"
>
<div ref={containerRef} className="relative isolate">
{slidingHighlight && (
<span aria-hidden="true" style={highlightStyle} className={slidingHighlightClass} />
)}
<SDKCommandList
{...props}
className={partClass('relative grid min-w-0 gap-0.5 p-1', className)}
>
{children}
</SDKCommandList>
</div>
</div>
);
}
function CommandSeparator({ className, ...props }: ComponentProps<typeof SDKCommandSeparator>) {
return (
<SDKCommandSeparator
{...props}
render={<Separator />}
className={partClass('my-1', className)}
/>
);
}
function CommandItem({ className, ...props }: ComponentProps<typeof SDKCommandItem>) {
const size = useContext(CommandSizeContext);
return (
<SDKCommandItem
{...props}
data-size={size}
className={partClass(commandItemStyles({ size }), className)}
/>
);
}
function CommandItemText({ className, ...props }: ComponentProps<typeof SDKCommandItemText>) {
return (
<SDKCommandItemText
{...props}
className={partClass(
'min-w-0 flex-1 truncate [&_mark]:bg-transparent [&_mark]:font-semibold [&_mark]:text-foreground',
className,
)}
/>
);
}
function CommandItemIcon({ className, ...props }: ComponentProps<typeof SDKCommandItemIcon>) {
return (
<SDKCommandItemIcon
{...props}
className={partClass(
'inline-flex size-4 shrink-0 items-center justify-center text-muted-foreground [&>svg]:size-full',
className,
)}
/>
);
}
function CommandGroup({ className, ...props }: ComponentProps<typeof SDKCommandGroup>) {
return <SDKCommandGroup {...props} className={partClass('grid gap-0.5', className)} />;
}
function CommandGroupLabel({ className, ...props }: ComponentProps<typeof SDKCommandGroupLabel>) {
const size = useContext(CommandSizeContext);
return (
<SDKCommandGroupLabel
{...props}
className={partClass(commandGroupLabelStyles({ size }), className)}
/>
);
}
function CommandEmpty({ className, ...props }: ComponentProps<typeof SDKCommandEmpty>) {
return (
<SDKCommandEmpty
{...props}
className={partClass(
'px-3 py-6 text-center text-sm text-muted-foreground empty:hidden',
className,
)}
/>
);
}
function CommandStatus({ className, ...props }: ComponentProps<typeof SDKCommandStatus>) {
return (
<SDKCommandStatus
{...props}
className={partClass('px-3 py-2 text-xs text-muted-foreground empty:hidden', className)}
/>
);
}
function CommandShortcut({ className, ...props }: ComponentProps<typeof SDKCommandShortcut>) {
return (
<SDKCommandShortcut
{...props}
className={partClass(
cn(
compactControlMinHeights.sm,
'ms-auto inline-flex min-w-6 items-center justify-center rounded-lg border border-border/60 bg-muted/60 px-1.5 font-sans text-xs text-muted-foreground',
),
className,
)}
/>
);
}
export {
CommandItems,
CommandPage,
createCommandController,
} from '@ui-sdk/react/command';
export {
Command,
CommandEmpty,
CommandGroup,
CommandGroupLabel,
CommandInput,
type CommandInputLabelVariant,
type CommandInputProps,
type CommandInputVariant,
CommandItem,
CommandItemIcon,
CommandItemText,
CommandList,
type CommandListProps,
type CommandProps,
CommandSeparator,
CommandShortcut,
CommandStatus,
};
'use client';
import {
createInputController,
type InputController,
type InputState,
type InputValueChangeReason,
Input as SDKInput,
InputClear as SDKInputClear,
InputGroup as SDKInputGroup,
} from '@ui-sdk/react/input';
import { cva, type VariantProps } from 'class-variance-authority';
import { X } from 'lucide-react';
import { type ComponentProps, type ReactNode, useId } from 'react';
import { type ButtonProps, buttonVariants } from '@/components/devvarena-ui/button';
import {
clampWaveDelay,
controlHeights,
controlTextSizes,
focusRing,
getTextFieldIconPadding,
partClass,
type StandardControlSize,
textFieldLabelSegmenter,
textFieldLayout,
textFieldSurfaces,
textFieldUnderlineMotion,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
const inputVariants = cva(
`w-full min-w-0 rounded-lg border py-2 shadow-sm transition-[border-color,background-color,box-shadow,filter] duration-200 ${focusRing} disabled:cursor-not-allowed disabled:opacity-50 read-only:cursor-default motion-reduce:transition-none`,
{
variants: {
variant: {
...textFieldSurfaces,
underline: `${textFieldSurfaces.underline} ${textFieldUnderlineMotion}`,
},
size: {
xs: `${controlHeights.xs} px-2 text-xs`,
sm: `${controlHeights.sm} px-2.5 text-xs`,
md: `${controlHeights.md} px-3 text-sm`,
lg: `${controlHeights.lg} px-4 text-base`,
},
},
defaultVariants: { variant: 'filled', size: 'md' },
},
);
type InputSize = StandardControlSize;
type NativeInputProps = Omit<ComponentProps<typeof SDKInput>, 'children' | 'size'>;
type InputProps = NativeInputProps &
VariantProps<typeof inputVariants> & {
/** Native input size attribute, in characters. */
htmlSize?: number;
label?: string;
labelVariant?: 'standard' | 'floating' | 'wave';
icon?: ReactNode;
iconPosition?: 'start' | 'end';
/** Per-grapheme delay in milliseconds; total staggering is capped at 300ms. */
waveDelay?: number;
description?: ReactNode;
/** Native props/ref for the outer layout; className/ref target the input itself. */
containerProps?: Omit<ComponentProps<'div'>, 'children'>;
};
const animatedLabelTypes = new Set(['text', 'email', 'password', 'search', 'tel', 'url', 'number']);
const labelActive =
'has-[input:focus]:[--field-label-scale:0.85] has-[input:not(:placeholder-shown)]:[--field-label-scale:0.85]';
const labelPatch =
'group-has-[input:focus]/input:bg-[linear-gradient(to_bottom,transparent_20%,var(--background)_40%,var(--background)_65%,transparent_85%)] group-has-[input:not(:placeholder-shown)]/input:bg-[linear-gradient(to_bottom,transparent_20%,var(--background)_40%,var(--background)_65%,transparent_85%)]';
const labelMotion =
'inline-block origin-left scale-[var(--field-label-scale,1)] transition-[scale,color] duration-200 ease-out group-has-[input:focus]/input:text-primary group-data-invalid/input:text-destructive motion-reduce:transition-none rtl:origin-right';
function InputLabel({ className, ...props }: ComponentProps<'label'>) {
// biome-ignore lint/a11y/noLabelWithoutControl: htmlFor and label children are supplied by callers via props.
return <label {...props} data-slot="input-label" className={className} />;
}
function InputDescription({ className, ...props }: ComponentProps<'p'>) {
return <p {...props} data-slot="input-description" className={cn('m-0 mt-1', className)} />;
}
/** Chrome wrapper for icons, floating labels, and underline affordances. */
function InputControlShell({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="input-control" className={className} {...props} />;
}
/** One native input contract; label position comes from CSS, including autofilled values. */
function Input({
label,
labelVariant = 'standard',
variant = 'filled',
size = 'md',
htmlSize,
icon,
iconPosition = 'start',
waveDelay = 24,
description,
containerProps,
id,
type = 'text',
placeholder,
className,
'aria-describedby': describedBy,
...props
}: InputProps) {
const generatedId = useId();
const inputId = id ?? generatedId;
const descriptionId = `${inputId}-description`;
const animated = Boolean(label) && labelVariant !== 'standard' && animatedLabelTypes.has(type);
const hasDescription = description !== undefined && description !== null && description !== false;
const invalid = Boolean(props['aria-invalid']) && props['aria-invalid'] !== 'false';
const graphemes =
animated && labelVariant === 'wave' && label
? Array.from(textFieldLabelSegmenter.segment(label), (part) => ({
text: part.segment,
offset: part.index,
}))
: [];
const delay = clampWaveDelay(waveDelay, graphemes.length);
const underline = variant === 'underline';
const resolvedSize: InputSize = size ?? 'md';
const paddingForIcon = icon ? getTextFieldIconPadding(iconPosition, underline) : undefined;
return (
<div
{...containerProps}
data-slot="input-container"
data-disabled={props.disabled ? '' : undefined}
data-invalid={invalid || undefined}
className={cn('w-full min-w-0', animated && 'pt-2', containerProps?.className)}
>
{label && !animated && (
<InputLabel
htmlFor={inputId}
className={cn(
'mb-2 block font-medium leading-5',
controlTextSizes[resolvedSize],
invalid && 'text-destructive',
props.disabled && 'opacity-50',
)}
>
{label}
</InputLabel>
)}
<InputControlShell
data-variant={variant}
data-size={resolvedSize}
data-invalid={invalid || undefined}
className={cn('group/input relative', animated && labelActive)}
>
<SDKInput
{...props}
id={id ?? (label ? inputId : undefined)}
type={type}
size={htmlSize}
placeholder={animated ? ' ' : placeholder}
aria-describedby={
[describedBy, hasDescription ? descriptionId : undefined].filter(Boolean).join(' ') ||
undefined
}
className={(state) =>
cn(
inputVariants({ variant, size: resolvedSize }),
paddingForIcon,
typeof className === 'function' ? className(state) : className,
)
}
/>
{animated && label && (
<InputLabel
htmlFor={inputId}
className={cn(
'pointer-events-none absolute top-1/2 -translate-y-1/2 leading-5 text-muted-foreground transition-[top] duration-200 ease-out group-has-[input:focus]/input:top-0 group-has-[input:not(:placeholder-shown)]/input:top-0 motion-reduce:transition-none',
'max-w-[calc(100%-1.5rem)]',
controlTextSizes[resolvedSize],
icon && iconPosition === 'start'
? underline
? textFieldLayout.floatingUnderlineIcon
: textFieldLayout.floatingWithIcon
: underline
? '-start-1'
: textFieldLayout.floatingStart,
icon && 'max-w-[calc(100%-3.25rem)]',
props.disabled && 'opacity-50',
)}
>
<span className="sr-only">{label}</span>
<span
aria-hidden="true"
className="-my-6 block overflow-hidden text-ellipsis whitespace-pre px-1 py-6"
>
{labelVariant === 'wave' ? (
graphemes.map(({ text, offset }, index) => (
<span
key={`${label}-${offset}`}
className={cn(labelMotion, labelPatch)}
style={{ transitionDelay: `${index * delay}ms` }}
>
{text}
</span>
))
) : (
<span className={cn(labelMotion, labelPatch)}>{label}</span>
)}
</span>
</InputLabel>
)}
{icon && (
<span
aria-hidden="true"
className={cn(
'pointer-events-none absolute top-1/2 inline-flex -translate-y-1/2 items-center justify-center text-muted-foreground transition-colors duration-200 group-has-[input:focus]/input:text-primary group-data-invalid/input:text-destructive motion-reduce:transition-none [&>svg]:size-full',
textFieldLayout.icon,
iconPosition === 'start'
? underline
? 'start-0'
: textFieldLayout.iconStart
: underline
? 'end-0'
: textFieldLayout.iconEnd,
props.disabled && 'opacity-50',
)}
>
{icon}
</span>
)}
</InputControlShell>
{hasDescription && (
<InputDescription
id={descriptionId}
className={cn(
'mt-1 text-xs leading-relaxed',
invalid ? 'text-destructive' : 'text-muted-foreground',
)}
>
{description}
</InputDescription>
)}
</div>
);
}
function InputGroup({ className, ...props }: ComponentProps<typeof SDKInputGroup>) {
return (
<SDKInputGroup
{...props}
data-slot="input-group"
className={(state) =>
cn(
'group/control relative flex min-w-0 items-center gap-2 [&>[data-slot=input]]:min-w-0 [&>[data-slot=input]]:flex-1',
typeof className === 'function' ? className(state) : className,
)
}
/>
);
}
type InputClearProps = ComponentProps<typeof SDKInputClear> & {
variant?: ButtonProps['variant'];
size?: ButtonProps['size'];
};
function InputClear({
children,
variant = 'ghost',
size = 'icon-sm',
className,
...props
}: InputClearProps) {
return (
<SDKInputClear
aria-label="Clear input"
{...props}
className={partClass(buttonVariants({ variant, size }), className)}
>
{children ?? <X aria-hidden="true" />}
</SDKInputClear>
);
}
export {
createInputController,
Input,
InputClear,
type InputController,
InputControlShell,
InputDescription,
InputGroup,
InputLabel,
type InputProps,
type InputSize,
type InputState,
type InputValueChangeReason,
inputVariants,
};
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';