A text field that suggests completions while you type.
Default
Sizes
Variants
Groups, icons, and floating label
Inline completion and wave label
Form search
States
Purpose
Autocomplete suggests possible answers as people type. They can pick a suggestion or keep the text they entered.
Parts & Composition
Place the label and input inside Autocomplete. Put suggestions in AutocompleteList inside AutocompleteContent. Use AutocompleteInputGroup around the input and any clear or trigger controls when they should share one field. Use items with an empty list part for data-driven suggestions, or compose item parts for custom content.
| Part | Role |
|---|---|
AutocompleteLabel, AutocompleteInput | Associated label and text field. |
AutocompleteInputGroup | Optional layout that places the clear and trigger controls inside the input edge. |
AutocompleteTrigger, AutocompleteClear | Optional controls to toggle suggestions and clear text. |
AutocompleteContent, AutocompleteArrow | Suggestions popup or bottom sheet and its optional arrow. |
AutocompleteList, AutocompleteItems | Scrollable listbox and SDK data renderer. |
AutocompleteItem, AutocompleteItemText, AutocompleteItemIcon | Composed suggestions with optional match highlighting and decorative icons. |
AutocompleteGroup, AutocompleteGroupLabel, AutocompleteSeparator | Group and label related suggestions and divide sections. |
AutocompleteEmpty, AutocompleteStatus | Empty-state copy and optional live result or loading message. |
API & Props
| Prop / part | Purpose |
|---|---|
value / defaultValue / onValueChange | Controlled text, initial text, and SDK change callback. Every value is a string. |
items / emptyItems / filter | Suggestions, optional suggestions before typing, and filtering strategy. Set filter={false} for results already filtered by the app. |
open / defaultOpen / onOpenChange | Control or initialize the popup separately from the text. |
openOnFocus / autoHighlight / inlineComplete | Open when focused, highlight the first match, or offer an inline suffix. |
onSubmit / submitOnSelect | Handle Enter on unhighlighted text and optionally submit after selection. |
name / form / required / readOnly / disabled | Form association and field behavior. Set these on the root. |
status / onLoadMore / onHighlight | Integrate loading, paging, or custom suggestion rendering. |
presentation | Defaults to "auto". Set "popover" for an anchored popup or "sheet" for a bottom sheet. |
AutocompleteLabel.labelVariant / waveDelay | Choose standard, floating, or wave. Place animated labels inside AutocompleteInputGroup. The wave delay defaults to 24 ms per character. |
AutocompleteInput.variant / size / htmlSize | Input surfaces (filled, outline, ghost, underline), control size (xs, sm, md, lg), and optional native input size in characters. |
AutocompleteItem.value / label / keywords / disabled | Stable identifier, text filled into the field, extra search terms, and availability. |
AutocompleteContent | Accepts SDK placement and mounting options, including side, align, anchor, container, and keepMounted. |
createAutocompleteController() | Read or set text, open or close suggestions, and focus the field from app code. |
loop / modal / dismissible | Configure wrapping keyboard navigation, popup modality, and dismissal. |
announcement / onOpenChangeComplete / onDismissAttempt | Customize the spoken result message, observe the end of popup motion, or respond to a blocked dismissal. |
Autocomplete submits the text typed or chosen under the root’s name. An uncontrolled field returns to its default on form reset. In a controlled field, update the next string from onValueChange. Use details.cancel() when a change should be refused.
Theming, Layout & Responsiveness
The input shares Input’s four surfaces and size scale. The popup uses the theme’s popover and accent colors. Style the SDK’s data-slot and data-highlighted attributes for custom option treatments.
The anchored popup follows the input width and scrolls within available space. On small touch devices, the default responsive presentation uses the SDK sheet. The SDK moves the input into the sheet header.
Motion & Accessibility
The anchored popup uses a short fade and scale transition and respects reduced motion. Sheet gestures and their transitions are SDK-owned.
Use AutocompleteLabel or supply an accessible input name. Keep each suggestion value unique. Arrow keys move through suggestions while focus stays in the field, Enter chooses the highlighted item, and Escape closes the popup. Give custom trigger and clear affordances clear names.
Guidance for Coding Agents
Install Autocomplete using the command in the Install tab. Read this Info page and the linked UI SDK reference before implementing. Start from the closest Preview → Usage example. Use Autocomplete when free text is valid. Put the text and open state at the root when the app needs to control them, and leave filtering, navigation, and input focus to the SDK. Use items for simple data, or compose the item parts when suggestions need icons or custom markup. Keep remote fetching and validation in the app.
Use the API table above for component styling and the UI SDK Autocomplete reference for inherited props, callbacks, filtering, controllers, and keyboard behavior.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/autocomplete'use client';
import {
AutocompleteList,
Autocomplete as SDKAutocomplete,
AutocompleteArrow as SDKAutocompleteArrow,
AutocompleteClear as SDKAutocompleteClear,
AutocompleteContent as SDKAutocompleteContent,
AutocompleteInput as SDKAutocompleteInput,
AutocompleteLabel as SDKAutocompleteLabel,
AutocompleteSeparator as SDKAutocompleteSeparator,
AutocompleteTrigger as SDKAutocompleteTrigger,
} from '@ui-sdk/react/autocomplete';
import { mergeProps } from '@ui-sdk/react/primitive';
import { ChevronDown, X } from 'lucide-react';
import { type ComponentProps, useMemo } from 'react';
import { type ButtonProps, buttonVariants } from '@/components/devvarena-ui/button';
import { inputVariants } from '@/components/devvarena-ui/input';
import { Separator } from '@/components/devvarena-ui/separator';
import { useSlidingHighlight } from '@/hooks/use-sliding-highlight';
import {
clampWaveDelay,
partClass,
type StandardControlSize,
slidingHighlight,
textFieldLabelMotion,
textFieldLabelSegmenter,
type textFieldSurfaces,
textFieldWaveMotion,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
type AutocompleteProps = ComponentProps<typeof SDKAutocomplete>;
function Autocomplete({ presentation = 'auto', ...props }: AutocompleteProps) {
return <SDKAutocomplete {...props} presentation={presentation} />;
}
const toggleIcon = (
<ChevronDown
aria-hidden="true"
className="transition-transform in-data-open:rotate-180 motion-reduce:transition-none"
/>
);
const clearIcon = <X aria-hidden="true" />;
type AutocompleteInputProps = Omit<ComponentProps<typeof SDKAutocompleteInput>, 'size'> & {
size?: StandardControlSize;
htmlSize?: number;
variant?: keyof typeof textFieldSurfaces;
};
function AutocompleteInput({
size = 'md',
variant = 'filled',
htmlSize,
placeholder,
className,
...props
}: AutocompleteInputProps) {
return (
<SDKAutocompleteInput
{...props}
size={htmlSize}
placeholder={placeholder || ' '}
data-size={size}
data-variant={variant}
className={partClass(inputVariants({ size, variant }), className)}
/>
);
}
type AutocompleteLabelProps = ComponentProps<typeof SDKAutocompleteLabel> & {
labelVariant?: 'standard' | 'floating' | 'wave';
waveDelay?: number;
};
function AutocompleteLabel({
labelVariant = 'standard',
waveDelay = 24,
children,
className,
...props
}: AutocompleteLabelProps) {
const floating = labelVariant === 'floating';
const wave = labelVariant === 'wave';
const animated = floating || wave;
const segments =
wave && typeof children === 'string' ? [...textFieldLabelSegmenter.segment(children)] : [];
const delay = clampWaveDelay(waveDelay, segments.length);
return (
<SDKAutocompleteLabel
{...props}
data-label-variant={labelVariant}
className={partClass(
'text-sm font-medium data-disabled:opacity-50',
animated
? cn(
'pointer-events-none absolute start-2 top-[calc(50%+0.25rem)] z-10 max-w-[calc(100%-4rem)] -translate-y-1/2 px-1 leading-5 text-muted-foreground motion-reduce:transition-none',
floating &&
'truncate transition-[top,color] duration-200 ease-out group-has-[input:focus]/field:top-2 group-has-[input:focus]/field:text-primary group-has-[input:not(:placeholder-shown)]/field:top-2 group-has-[input[aria-invalid=true]]/field:text-destructive',
)
: 'mb-2 block',
className,
)}
>
{(state) => {
const label = typeof children === 'function' ? children(state) : children;
if (!animated) return label;
if (!segments.length) {
return <span className={textFieldLabelMotion}>{label}</span>;
}
return (
<>
<span className="sr-only">{label}</span>
<span aria-hidden="true" className="inline-flex whitespace-pre">
{segments.map(({ index, segment }, position) => (
<span
key={index}
className={textFieldWaveMotion}
style={{ transitionDelay: `${position * delay}ms` }}
>
{segment === ' ' ? '\u00A0' : segment}
</span>
))}
</span>
</>
);
}}
</SDKAutocompleteLabel>
);
}
function AutocompleteInputGroup({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="autocomplete-input-group"
className={cn(
'group/field relative grid min-w-0 grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-x-1',
'[&>[data-slot=autocomplete-input]]:col-span-full [&>[data-slot=autocomplete-input]]:row-start-1',
'[&>[data-slot=autocomplete-clear]]:col-start-2 [&>[data-slot=autocomplete-trigger]]:col-start-3',
'[&>:is([data-slot=autocomplete-clear],[data-slot=autocomplete-trigger])]:relative [&>:is([data-slot=autocomplete-clear],[data-slot=autocomplete-trigger])]:row-start-1',
'[&>:is([data-slot=autocomplete-clear],[data-slot=autocomplete-trigger]):last-child]:me-1.5',
'[&:has(>:is([data-slot=autocomplete-clear],[data-slot=autocomplete-trigger]):not([hidden]))>[data-slot=autocomplete-input]]:pe-10',
'[&:has(>[data-slot=autocomplete-clear]:not([hidden])):has(>[data-slot=autocomplete-trigger]:not([hidden]))>[data-slot=autocomplete-input]]:pe-18',
'[&:not(:has(>[data-slot=autocomplete-input]))]:hidden',
'has-[>[data-label-variant=floating]]:pt-2 has-[>[data-label-variant=wave]]:pt-2',
'[&:has(>[data-label-variant]:not([data-label-variant=standard]))>input]:placeholder:text-transparent',
'[&:has(>[data-label-variant=standard])>[data-label-variant=standard]]:col-span-full [&:has(>[data-label-variant=standard])>[data-label-variant=standard]]:row-start-1',
'[&:has(>[data-label-variant=standard])>:is([data-slot=autocomplete-input],[data-slot=autocomplete-clear],[data-slot=autocomplete-trigger])]:row-start-2',
className,
)}
/>
);
}
type AutocompleteTriggerProps = ComponentProps<typeof SDKAutocompleteTrigger> & {
variant?: ButtonProps['variant'];
size?: ButtonProps['size'];
};
function AutocompleteTrigger({
children,
variant = 'ghost',
size = 'icon-xs',
className,
'aria-label': label = 'Toggle suggestions',
...props
}: AutocompleteTriggerProps) {
return (
<SDKAutocompleteTrigger
{...props}
aria-label={label}
data-size={size}
data-variant={variant}
className={partClass(buttonVariants({ variant, size }), className)}
>
{children ?? toggleIcon}
</SDKAutocompleteTrigger>
);
}
type AutocompleteClearProps = ComponentProps<typeof SDKAutocompleteClear> & {
variant?: ButtonProps['variant'];
size?: ButtonProps['size'];
};
function AutocompleteClear({
children,
variant = 'ghost',
size = 'icon-xs',
className,
'aria-label': label = 'Clear text',
...props
}: AutocompleteClearProps) {
return (
<SDKAutocompleteClear
{...props}
aria-label={label}
data-size={size}
data-variant={variant}
className={partClass(buttonVariants({ variant, size }), className)}
>
{children ?? clearIcon}
</SDKAutocompleteClear>
);
}
function AutocompleteContent({
sideOffset = 4,
className,
children,
ref,
...props
}: ComponentProps<typeof SDKAutocompleteContent>) {
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector: suggestionSelector,
activeAttribute: 'data-highlighted',
});
const contentRef = useMemo(
() => (ref ? mergeProps({ ref: containerRef }, { ref }).ref : containerRef),
[containerRef, ref],
);
return (
<SDKAutocompleteContent
{...props}
ref={contentRef}
sideOffset={sideOffset}
className={partClass(
'not-prose isolate m-0 flex overflow-hidden max-h-[min(18rem,var(--available-height,18rem))] w-(--anchor-width) max-w-(--available-width) origin-(--transform-origin) flex-col rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-sm outline-none',
'data-[presentation=sheet]:h-[min(24rem,85dvh)] data-[presentation=sheet]:max-h-[85dvh] data-[presentation=sheet]:w-full data-[presentation=sheet]:max-w-none data-[presentation=sheet]:rounded-b-none data-[presentation=sheet]:border-x-0 data-[presentation=sheet]:border-b-0 data-[presentation=sheet]:pb-[max(0.25rem,env(safe-area-inset-bottom))] [--sheet-backdrop:rgb(0_0_0/0.4)]',
'data-[presentation=popover]:transition-[opacity,scale,filter] data-[presentation=popover]:duration-200 data-[presentation=popover]:ease-out data-[presentation=popover]:data-starting-style:opacity-0 data-[presentation=popover]:data-ending-style:opacity-0 motion-safe:data-[presentation=popover]:data-starting-style:scale-95 motion-safe:data-[presentation=popover]:data-starting-style:blur-[3px] motion-safe:data-[presentation=popover]:data-ending-style:scale-[0.98] motion-safe:data-[presentation=popover]:data-ending-style:blur-[3px] motion-reduce:data-[presentation=popover]:transition-none',
'[&_[data-slot=autocomplete-empty]:empty]:hidden [&_[data-slot=autocomplete-empty]]:px-3 [&_[data-slot=autocomplete-empty]]:py-2 [&_[data-slot=autocomplete-empty]]:text-sm [&_[data-slot=autocomplete-empty]]:text-muted-foreground [&_[data-slot=autocomplete-status]:empty]:hidden [&_[data-slot=autocomplete-status]]:px-3 [&_[data-slot=autocomplete-status]]:text-xs [&_[data-slot=autocomplete-status]]:text-muted-foreground',
'[&_[data-slot=autocomplete-list]]:scroll-fade [&_[data-slot=autocomplete-list]]:min-h-0 [&_[data-slot=autocomplete-list]]:overflow-y-auto [&_[data-slot=autocomplete-list]]:overscroll-contain [&_[data-slot=autocomplete-list]]:[scrollbar-width:thin] [&_[data-slot=autocomplete-list]]:[scrollbar-color:var(--border)_transparent]',
'[&_[data-slot=autocomplete-item]]:flex [&_[data-slot=autocomplete-item]]:min-h-10 [&_[data-slot=autocomplete-item]]:cursor-default [&_[data-slot=autocomplete-item]]:items-center [&_[data-slot=autocomplete-item]]:gap-2 [&_[data-slot=autocomplete-item]]:rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))] [&_[data-slot=autocomplete-item]]:px-3 [&_[data-slot=autocomplete-item]]:py-2 [&_[data-slot=autocomplete-item]]:text-sm [&_[data-slot=autocomplete-item]]:[overflow-wrap:anywhere]',
'[&_[data-slot=autocomplete-item][data-highlighted]]:text-accent-foreground [&_[data-slot=autocomplete-item][data-disabled]]:opacity-50',
'[&_[data-slot=autocomplete-group-label]]:px-3 [&_[data-slot=autocomplete-group-label]]:py-2 [&_[data-slot=autocomplete-group-label]]:text-xs [&_[data-slot=autocomplete-group-label]]:font-medium [&_[data-slot=autocomplete-group-label]]:text-muted-foreground',
'[&_[data-slot=autocomplete-item-icon]]:size-4 [&_[data-slot=autocomplete-item-icon]]:shrink-0 [&_[data-slot=autocomplete-item-icon]>svg]:size-full [&_[data-slot=autocomplete-item-icon]]:text-muted-foreground',
'[&_mark]:bg-transparent [&_mark]:font-semibold [&_mark]:text-inherit',
className,
)}
>
{typeof children === 'function' ? (
(state) => (
<>
<span aria-hidden="true" className={slidingHighlight} style={highlightStyle} />
{children(state)}
</>
)
) : (
<>
<span aria-hidden="true" className={slidingHighlight} style={highlightStyle} />
{children ?? <AutocompleteList />}
</>
)}
</SDKAutocompleteContent>
);
}
const suggestionSelector =
'[data-slot="autocomplete-item"]:not([data-disabled]):not([aria-disabled="true"])';
function AutocompleteArrow({ className, ...props }: ComponentProps<typeof SDKAutocompleteArrow>) {
return (
<SDKAutocompleteArrow
{...props}
className={partClass(
'size-2 rotate-45 border-border bg-popover data-[side=bottom]:-top-1 data-[side=bottom]:border-s data-[side=bottom]:border-t data-[side=top]:-bottom-1 data-[side=top]:border-e data-[side=top]:border-b data-[side=left]:-right-1 data-[side=left]:border-e data-[side=left]:border-t data-[side=right]:-left-1 data-[side=right]:border-s data-[side=right]:border-b',
className,
)}
/>
);
}
const separatorSurface = <Separator decorative={false} className="my-1" />;
function AutocompleteSeparator(props: ComponentProps<typeof SDKAutocompleteSeparator>) {
return <SDKAutocompleteSeparator render={separatorSurface} {...props} />;
}
export type {
AutocompleteController,
AutocompleteOpenChangeReason,
AutocompleteOptions,
AutocompleteSubmitDetails,
AutocompleteValueChangeReason,
ListData,
SearchFilter,
} from '@ui-sdk/react/autocomplete';
export {
AutocompleteEmpty,
AutocompleteGroup,
AutocompleteGroupLabel,
AutocompleteItem,
AutocompleteItemIcon,
AutocompleteItems,
AutocompleteItemText,
AutocompleteStatus,
createAutocompleteController,
} from '@ui-sdk/react/autocomplete';
export {
Autocomplete,
AutocompleteArrow,
AutocompleteClear,
AutocompleteContent,
AutocompleteInput,
AutocompleteInputGroup,
type AutocompleteInputProps,
AutocompleteLabel,
type AutocompleteLabelProps,
AutocompleteList,
type AutocompleteProps,
AutocompleteSeparator,
AutocompleteTrigger,
};
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 {
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';