Compound UI SDK select parts with flexible labels, groups, joined or floating menus, and rich options.
Default
Sizes
Labels
Custom indicator
Scroll
Type a city name while the menu is focused to jump to it.
Icons and clear
Multiple selection
Grouped search and multiple selection
Custom Rendering
States
Choose a tool before continuing.
Async Search
Object Values & Form
Submit the form to inspect FormData values. Reset restores defaults.
Purpose
A select lets people choose one or more options from a list. It can group options or let people search when the list is long.
Parts & Composition
Place the label, trigger with its value, and popup content inside Select. Use SelectField for field layout. Compose item parts for rich options or pass item data. Put SelectInput alongside SelectList inside the popup to keep search outside the scrolling options.
API & Props
| Part / Prop | Purpose |
|---|---|
Select | Root provider (value, defaultValue, onValueChange, multiple, items, name, form, disabled, readOnly, required, size: xs | sm | md | lg, popupStyle: floating | joined, presentation: auto | popover | sheet, controller) |
SelectField | Optional layout wrapper (data-slot="select", group/control relative w-full min-w-0 max-w-sm) |
SelectLabel | Field label (placement: above | floating | inset); turns text-destructive when invalid |
SelectTrigger | Button-style trigger (variant defaults to secondary, size inherits from Select, inset supports embedded labels) |
SelectValue | Selected label(s) (maxLabels shows a +N Badge; render and getMoreLabel take precedence) |
SelectContent | Top-layer popup/sheet (slidingHighlight default true, mobileTitle, side, align, sideOffset, alignItemWithTrigger, container, keepMounted) |
SelectItem | Option (value, disabled, icon, description) with SelectItemText, SelectItemIcon, SelectItemIndicator (default checkmark) |
SelectList, SelectItems, SelectGroup, SelectGroupLabel, SelectSeparator, SelectArrow | Scrollable list (for pairing with SelectInput), data renderer, option groups, divider, and popup arrow |
SelectInput, SelectEmpty, SelectStatus, SelectClear, SelectSelectAll, SelectDescription | Search input (Input), empty/status messages, clear/select-all actions (SelectClear accepts Button variant and size), and helper/error copy (invalid) |
createSelectController() | Programmatic open, close, value, and highlight control |
Common props in detail
| Prop / part | Purpose |
|---|---|
value / defaultValue | Use one value in single mode or an array in multiple mode. Choose controlled or initial state. |
onValueChange | Receives the next selection and SDK details. Keep controlled state in sync with the callback. |
open / defaultOpen / onOpenChange | Control or initialize menu visibility separately from selection. |
name / form | Identify and associate the field when including its selected values in a form. |
Interaction states
| State | Behavior |
|---|---|
| Rest | SelectTrigger uses the shared secondary Button surface; placeholder text uses text-muted-foreground. |
| Hover / Highlight | Inside SelectContent, useSlidingHighlight glides the shared slidingHighlight (bg-primary/10) across enabled [data-highlighted] options. |
| Open | data-open rotates the trigger chevron 180deg, applies border-ring ring-3 ring-ring/10, and flattens touching corners when popupStyle="joined". |
| Selected | data-selected highlights the option (bg-accent text-accent-foreground font-medium) and reveals SelectItemIndicator. |
| Focus | Keyboard focus applies focusRing (focus-visible:ring-3 focus-visible:ring-ring/30 focus-visible:border-ring) on triggers, SelectClear, and SelectSelectAll. |
| Invalid | aria-invalid / data-invalid applies border-destructive ring-3 ring-destructive/25 on the trigger and text-destructive on SelectLabel and SelectDescription invalid. |
| Disabled | data-disabled sets opacity-50 and cursor-not-allowed on triggers (opacity-40 and pointer-events-none on disabled items). |
Theming, Layout & Responsiveness
Uses shadcn semantic tokens (background, foreground, input, ring, popover, popover-foreground, accent, accent-foreground, muted-foreground, destructive, border) across light, dark, and custom themes.
| Attribute | Meaning |
|---|---|
data-slot="select" | Root SelectField wrapper (select-item, select-item-text, select-item-icon, select-item-indicator, select-item-description, select-description on subparts). |
data-size | Reflects xs | sm | md | lg to scale trigger, items, indicators, and group labels together. |
data-open, data-placeholder, data-highlighted, data-selected, data-disabled | UI SDK state attributes driving chevron rotation, placeholder styling, highlight pill, selected state, and disabled styling. |
data-presentation="popover" | "sheet" | Switches between anchored desktop popover (max-h-[min(18rem,var(--available-height))]) and mobile bottom sheet (max-h-[85dvh], safe-area bottom padding, mobileTitle header). |
data-sliding-highlight | Present on SelectContent when the sliding highlight overlay is active. |
Trigger and item heights follow controlHeights (xs 28px, sm 32px, md 40px, lg 48px) at every breakpoint. SelectTrigger, SelectItem, SelectClear, and SelectSelectAll set touch-manipulation, and SelectItem enforces min-h-11 (44px) on @media(pointer:coarse) touch devices. Long option text wraps with [overflow-wrap:anywhere]. presentation defaults to "auto": opens a bottom sheet on small touch screens and an anchored popover on desktop.
Motion & Accessibility
SelectLabel associates with SelectTrigger (pointer-events-none on floating and inset placements so clicks pass straight to the trigger). Pair SelectDescription id with aria-describedby on SelectTrigger, and pass aria-invalid on SelectTrigger for error states. Give icon-only triggers or options an explicit aria-label. Popup portals stay in their DOM ancestry by default so theme tokens and dir="rtl" inherit automatically.
Guidance for Coding Agents
Install Select with the command on the Install tab. Read this Info page and the linked UI SDK reference before implementing.
Use matching option values across the root, trigger value, and items. Choose scalar or array state based on multiple mode, and provide labels or item data so the closed trigger can resolve the selection. Keep search and list parts in the documented tree.
Keep items in sync with custom SelectItem children so SelectValue and typeahead work before the popup opens; place SelectList inside SelectContent when combining a fixed SelectInput search bar with a scrollable list. Set presentation on Select and associate any external description with the trigger using aria-describedby.
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 Select.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/select'use client';
import { createAutoScroll } from '@ui-sdk/core';
import type { SelectOptions } from '@ui-sdk/core/select';
import { mergeProps } from '@ui-sdk/react/primitive';
import {
createSelectController,
type ListData,
Select as SDKSelect,
SelectArrow as SDKSelectArrow,
SelectClear as SDKSelectClear,
SelectContent as SDKSelectContent,
SelectEmpty as SDKSelectEmpty,
SelectGroup as SDKSelectGroup,
SelectGroupLabel as SDKSelectGroupLabel,
SelectInput as SDKSelectInput,
SelectItem as SDKSelectItem,
SelectItemIcon as SDKSelectItemIcon,
SelectItemIndicator as SDKSelectItemIndicator,
SelectItemText as SDKSelectItemText,
SelectLabel as SDKSelectLabel,
SelectList as SDKSelectList,
SelectSelectAll as SDKSelectSelectAll,
SelectSeparator as SDKSelectSeparator,
SelectStatus as SDKSelectStatus,
SelectTrigger as SDKSelectTrigger,
SelectValue as SDKSelectValue,
SelectValueIcon as SDKSelectValueIcon,
type SelectController,
SelectItems,
type SelectOpenChangeReason,
type SelectValueChangeReason,
} from '@ui-sdk/react/select';
import { cva } from 'class-variance-authority';
import { ChevronDown, X } from 'lucide-react';
import {
type ComponentProps,
createContext,
type ReactNode,
type Ref,
useContext,
useId,
useMemo,
} from 'react';
import { Badge } from '@/components/devvarena-ui/badge';
import { type ButtonProps, buttonVariants } from '@/components/devvarena-ui/button';
import { Input } from '@/components/devvarena-ui/input';
import { Separator } from '@/components/devvarena-ui/separator';
import { useSlidingHighlight } from '@/hooks/use-sliding-highlight';
import { ValueTransition } from '@/hooks/use-value-transition';
import {
concentricRadius,
controlMinHeights,
controlTextSizes,
focusRing,
partClass,
type StandardControlSize,
slidingHighlight as slidingHighlightClass,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
type SelectMenuSize = StandardControlSize;
const selectItemDescriptionStyles =
'[&:has([data-slot=select-item-description])]:min-h-0 [&:has([data-slot=select-item-description])]:items-start [&:has([data-slot=select-item-description])]:gap-x-2 [&:has([data-slot=select-item-description])]:gap-y-0 [&:has([data-slot=select-item-description])_[data-slot=select-item-icon]]:self-start [&:has([data-slot=select-item-description])_[data-slot=select-item-description]]:leading-snug [&:has([data-slot=select-item-description])_[data-slot=select-item-indicator]]:translate-y-0';
const selectItemVariants = cva(
`relative flex w-full min-w-0 cursor-default touch-manipulation items-center ${concentricRadius} outline-none select-none [@media(pointer:coarse)]:min-h-11 [&[data-selected]]:bg-accent [&[data-selected]]:text-accent-foreground [&[data-selected]]:font-medium group-not-data-sliding-highlight/select-list:data-highlighted:not-data-selected:bg-accent [&[data-highlighted]:not([data-selected])]:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-40`,
{
variants: {
size: {
xs: `${controlMinHeights.xs} gap-1.5 px-2 ${controlTextSizes.xs} pe-7 [&_[data-slot=select-item-text]]:leading-4 [&:has([data-slot=select-item-icon])]:grid-cols-[1rem_minmax(0,1fr)] [&_[data-slot=select-item-icon]]:size-4 [&_[data-slot=select-item-icon]_svg]:size-3.5 [&_[data-slot=select-item-description]]:text-xs [&:has([data-slot=select-item-description])]:py-1 [&:has([data-slot=select-item-description])_[data-slot=select-item-indicator]]:top-2.5 ${selectItemDescriptionStyles}`,
sm: `${controlMinHeights.sm} gap-2 px-2.5 ${controlTextSizes.sm} pe-8 [&_[data-slot=select-item-text]]:leading-4 [&:has([data-slot=select-item-icon])]:grid-cols-[1rem_minmax(0,1fr)] [&_[data-slot=select-item-icon]]:size-4 [&_[data-slot=select-item-icon]_svg]:size-3.5 [&_[data-slot=select-item-description]]:text-xs [&:has([data-slot=select-item-description])]:py-1 [&:has([data-slot=select-item-description])_[data-slot=select-item-indicator]]:top-2.5 ${selectItemDescriptionStyles}`,
md: `${controlMinHeights.md} gap-2 px-2.5 ${controlTextSizes.md} pe-9 [&_[data-slot=select-item-text]]:leading-5 [&:has([data-slot=select-item-icon])]:grid-cols-[1.125rem_minmax(0,1fr)] [&_[data-slot=select-item-icon]]:size-[1.125rem] [&_[data-slot=select-item-icon]_svg]:size-4 [&_[data-slot=select-item-description]]:text-xs [&:has([data-slot=select-item-description])]:py-1.5 [&:has([data-slot=select-item-description])_[data-slot=select-item-indicator]]:top-3 ${selectItemDescriptionStyles}`,
lg: `${controlMinHeights.lg} gap-2.5 px-3 ${controlTextSizes.lg} pe-10 [&_[data-slot=select-item-text]]:leading-6 [&:has([data-slot=select-item-icon])]:grid-cols-[1.25rem_minmax(0,1fr)] [&_[data-slot=select-item-icon]]:size-5 [&_[data-slot=select-item-icon]_svg]:size-4 [&_[data-slot=select-item-description]]:text-sm [&:has([data-slot=select-item-description])]:py-2 [&:has([data-slot=select-item-description])_[data-slot=select-item-indicator]]:top-3.5 ${selectItemDescriptionStyles}`,
},
},
defaultVariants: { size: 'md' },
},
);
const selectItemIndicatorVariants = cva(
'group/select-item-indicator pointer-events-none absolute top-1/2 flex -translate-y-1/2 items-center justify-center text-primary',
{
variants: {
size: {
xs: 'end-2 size-3.5 [&_svg]:size-3.5',
sm: 'end-2 size-3.5 [&_svg]:size-3.5',
md: 'end-2.5 size-4 [&_svg]:size-4',
lg: 'end-3 size-[1.125rem] [&_svg]:size-[1.125rem]',
},
},
defaultVariants: { size: 'md' },
},
);
const selectGroupLabelVariants = cva('font-medium text-muted-foreground', {
variants: {
size: {
xs: 'px-2 py-1 text-xs',
sm: 'px-2 py-1 text-xs',
md: 'px-2.5 py-1.5 text-xs',
lg: 'px-3 py-2 text-sm',
},
},
defaultVariants: { size: 'md' },
});
const TRIGGER_CHEVRON = (
<ChevronDown
aria-hidden="true"
className="ms-auto shrink-0 text-muted-foreground transition-transform duration-150 group-data-open/select:rotate-180 motion-reduce:transition-none"
/>
);
const CHECK_INDICATOR = (
<svg
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="1em"
height="1em"
viewBox="0 0 24 24"
>
<path
fill="none"
stroke="currentColor"
strokeDasharray={24}
strokeDashoffset={0}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2.9}
d="M5 11L11 17L21 7"
className="motion-safe:transition-[stroke-dashoffset] motion-safe:duration-300 motion-safe:group-[:not([data-selected])]/select-item-indicator:[stroke-dashoffset:24] motion-safe:starting:[stroke-dashoffset:24]"
/>
</svg>
);
const HIGHLIGHT_SELECTOR =
':is([data-slot="select-item"],[data-slot="select-select-all"]):not([data-disabled]):not([aria-disabled="true"])';
const hoverScrollEdge = 24;
function bindSelectHoverScroll(content: HTMLDivElement | null) {
if (!content) return;
let viewport: HTMLElement | null = null;
let dir = 0;
const canScroll = () => {
if (
!viewport ||
!dir ||
!('open' in content.dataset) ||
content.dataset.presentation !== 'popover'
) {
return false;
}
const { scrollTop, scrollHeight, clientHeight } = viewport;
return dir < 0 ? scrollTop > 1 : scrollTop + clientHeight < scrollHeight - 1;
};
const scroll = createAutoScroll({
edge: hoverScrollEdge,
onScroll: () => !canScroll() && scroll.stop(),
});
const events = new AbortController();
const { signal } = events;
content.addEventListener(
'pointermove',
({ pointerType, clientX, clientY }) => {
if (pointerType !== 'mouse') return;
viewport = content.querySelector<HTMLElement>('[data-slot=select-list]') ?? content;
const { top, bottom } = viewport.getBoundingClientRect();
const up = clientY >= top && clientY - top < hoverScrollEdge;
const down = clientY <= bottom && bottom - clientY < hoverScrollEdge;
dir = up ? -1 : down ? 1 : 0;
if (!canScroll()) return scroll.stop();
scroll.update(clientX, clientY);
},
{ signal },
);
content.addEventListener('pointerleave', scroll.stop, { signal });
content.addEventListener('pointercancel', scroll.stop, { signal });
return () => {
events.abort();
scroll.stop();
};
}
const PopupStyleContext = createContext<'floating' | 'joined'>('floating');
const SelectSizeContext = createContext<SelectMenuSize>('md');
type SelectProps<Value = string, Multiple extends boolean | undefined = false> = SelectOptions<
Value,
Multiple
> & {
children?: ReactNode;
popupStyle?: 'floating' | 'joined';
/** Uses an adaptive sheet on small touch screens unless presentation is set explicitly. */
/** Scales the trigger and list at every breakpoint (Button heights). */
size?: SelectMenuSize;
};
function Select<Value = string, Multiple extends boolean | undefined = false>({
popupStyle = 'floating',
size = 'md',
presentation = 'auto',
...props
}: SelectProps<Value, Multiple>) {
// Removing wrapper props through rest destructuring loses the SDK's conditional multiple type.
const selectOptions = { ...props, presentation } as SelectOptions<Value, Multiple>;
return (
<PopupStyleContext.Provider value={popupStyle}>
<SelectSizeContext.Provider value={size}>
<SDKSelect<Value, Multiple> {...selectOptions} />
</SelectSizeContext.Provider>
</PopupStyleContext.Provider>
);
}
function SelectField({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="select"
className={cn('group/control relative w-full min-w-0 max-w-sm', className)}
/>
);
}
type SelectLabelProps = ComponentProps<typeof SDKSelectLabel> & {
placement?: 'above' | 'floating' | 'inset';
};
function SelectLabel({ className, placement = 'above', ...props }: SelectLabelProps) {
return (
<SDKSelectLabel
{...props}
className={partClass(
'block w-fit max-w-full break-words text-sm font-medium leading-5 text-foreground group-has-[[aria-invalid=true]]/control:text-destructive group-has-[[data-invalid]]/control:text-destructive',
placement === 'above' && 'mb-2',
placement === 'floating' &&
'pointer-events-none absolute start-3 top-0 z-10 -translate-y-1/2 backdrop-blur-xs px-1 text-xs leading-4 text-muted-foreground',
placement === 'inset' &&
'pointer-events-none absolute start-3 top-2 z-10 max-w-[calc(100%-3rem)] text-xs leading-4 text-muted-foreground',
className,
)}
/>
);
}
type SelectTriggerProps = Omit<ComponentProps<typeof SDKSelectTrigger>, 'children'> & {
children?: ReactNode;
variant?: ButtonProps['variant'];
size?: StandardControlSize;
/** Taller trigger for an inset field label; list density follows `Select` `size`. */
inset?: boolean;
};
function SelectTrigger({
className,
children,
inset = false,
size,
variant = 'secondary',
...props
}: SelectTriggerProps) {
const popupStyle = useContext(PopupStyleContext);
const menuSize = useContext(SelectSizeContext);
const triggerSize = size ?? menuSize;
return (
<SDKSelectTrigger
{...props}
data-size={triggerSize}
data-variant={variant}
data-inset={inset || undefined}
className={partClass(
buttonVariants({ variant, size: triggerSize }),
'group/select w-full min-w-0 justify-start text-start',
inset && 'h-auto min-h-14 pt-6 pb-2',
popupStyle === 'joined' &&
'data-open:[&:has(+[data-presentation=popover][data-side=bottom])]:rounded-b-none data-open:[&:has(+[data-presentation=popover][data-side=top])]:rounded-t-none',
className,
)}
>
{children}
{TRIGGER_CHEVRON}
</SDKSelectTrigger>
);
}
function SelectValue({
animated = true,
className,
maxLabels,
getMoreLabel,
render,
children,
...props
}: ComponentProps<typeof SDKSelectValue> & { animated?: boolean }) {
const useDefaultRender = children == null && !render && !getMoreLabel;
const useBadge = maxLabels != null && useDefaultRender;
const limit = Math.max(0, Math.floor(maxLabels ?? 0));
return (
<SDKSelectValue
{...props}
maxLabels={maxLabels}
getMoreLabel={getMoreLabel}
className={partClass(
'flex min-w-0 flex-1 break-words text-start [overflow-wrap:anywhere] data-placeholder:text-muted-foreground',
className,
)}
render={
useDefaultRender
? ({ children: label, className: valueClassName, ...valueProps }, { labels }) => {
if (useBadge) {
const remaining = labels.length - limit;
if (remaining > 0) {
const visible = labels.slice(0, limit).join(', ');
return (
<span {...valueProps} className={cn('items-center gap-1.5', valueClassName)}>
{visible && (
<span className="min-w-0 truncate">
<ValueTransition value={visible} enabled={animated} />
</span>
)}
<Badge aria-hidden="true" size="sm" className="shrink-0">
<ValueTransition value={`+${remaining}`} enabled={animated} />
</Badge>
<span className="sr-only">
{visible ? ` and ${remaining} more selected` : `${remaining} selected`}
</span>
</span>
);
}
}
return (
<span {...valueProps} className={valueClassName}>
{typeof label === 'string' || typeof label === 'number' ? (
<ValueTransition value={label} enabled={animated} />
) : (
label
)}
</span>
);
}
: render
}
>
{children}
</SDKSelectValue>
);
}
type SelectContentProps = Omit<ComponentProps<typeof SDKSelectContent>, 'children'> & {
children?: ReactNode;
slidingHighlight?: boolean;
mobileTitle?: ReactNode;
};
function SelectContent({
className,
children,
slidingHighlight = true,
mobileTitle = 'Choose an option',
side = 'bottom',
align = 'center',
sideOffset,
alignItemWithTrigger = false,
ref,
...props
}: SelectContentProps) {
const popupStyle = useContext(PopupStyleContext);
const menuSize = useContext(SelectSizeContext);
const animateDropdown = !alignItemWithTrigger;
const highlight = slidingHighlight;
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector: HIGHLIGHT_SELECTOR,
activeAttribute: 'data-highlighted',
disabled: !highlight,
});
const contentRef = useMemo<Ref<HTMLDivElement>>(
() =>
mergeProps(
{ ref: bindSelectHoverScroll },
highlight ? { ref: containerRef } : {},
ref ? { ref } : {},
).ref,
[containerRef, highlight, ref],
);
const scroller =
'group/select-list relative isolate min-h-0 overflow-y-auto overscroll-contain p-1 [scrollbar-width:thin] [scrollbar-color:var(--border)_transparent] gap-px';
return (
<SDKSelectContent
{...props}
ref={contentRef}
data-size={menuSize}
data-variant={popupStyle}
data-sliding-highlight={highlight ? '' : undefined}
side={side}
align={align}
sideOffset={sideOffset ?? (popupStyle === 'joined' ? 0 : 4)}
alignItemWithTrigger={alignItemWithTrigger}
className={partClass(
'group/select-content not-prose isolate m-0 flex flex-col max-h-[min(18rem,var(--available-height,18rem))] w-(--anchor-width) max-w-(--available-width) origin-(--transform-origin) rounded-lg border border-border bg-popover text-popover-foreground shadow-sm outline-none',
scroller,
'has-[[data-slot=select-list]]:overflow-hidden data-[presentation=sheet]:pb-[max(0.5rem,env(safe-area-inset-bottom))]',
'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',
animateDropdown &&
'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:blur-[3px] motion-safe:data-[presentation=popover]:data-ending-style:blur-[3px] motion-reduce:data-[presentation=popover]:transition-none',
animateDropdown &&
popupStyle === 'floating' &&
'motion-safe:data-[presentation=popover]:data-starting-style:scale-95 motion-safe:data-[presentation=popover]:data-ending-style:scale-[0.98]',
popupStyle === 'joined' &&
'data-[presentation=popover]:data-[side=bottom]:rounded-t-none data-[presentation=popover]:data-[side=top]:rounded-b-none',
className,
)}
>
<div className="relative mx-1 mt-1 hidden shrink-0 px-3 py-3 group-data-[presentation=sheet]/select-content:block">
<p className="m-0 break-words text-base font-semibold leading-6">{mobileTitle}</p>
<Separator className="absolute inset-x-1 bottom-0 w-auto" />
</div>
{highlight && (
<span aria-hidden="true" style={highlightStyle} className={slidingHighlightClass} />
)}
{children ?? <SelectList />}
</SDKSelectContent>
);
}
function SelectGroup({ className, ...props }: ComponentProps<typeof SDKSelectGroup>) {
return <SDKSelectGroup {...props} className={partClass('scroll-my-1 p-1', className)} />;
}
type SelectGroupLabelProps = ComponentProps<typeof SDKSelectGroupLabel>;
function SelectGroupLabel({ className, ...props }: SelectGroupLabelProps) {
const menuSize = useContext(SelectSizeContext);
return (
<SDKSelectGroupLabel
{...props}
className={partClass(selectGroupLabelVariants({ size: menuSize }), className)}
/>
);
}
type SelectItemProps<Value = string> = Omit<
ComponentProps<typeof SDKSelectItem<Value>>,
'children'
> & {
children?: ReactNode;
icon?: ReactNode;
description?: ReactNode;
};
function SelectItemWithDescription<Value>({
description,
describedBy,
children,
...props
}: SelectItemProps<Value> & { describedBy?: string }) {
const id = useId();
const descId = `${id}-description`;
return (
<SelectItemBase
{...props}
aria-describedby={describedBy ? `${describedBy} ${descId}` : descId}
descriptionNode={
<span
id={descId}
data-slot="select-item-description"
className="block min-w-0 break-words leading-relaxed text-muted-foreground"
>
{description}
</span>
}
>
{children}
</SelectItemBase>
);
}
function SelectItemBase<Value>({
className,
children,
icon,
descriptionNode,
...props
}: Omit<SelectItemProps<Value>, 'description'> & { descriptionNode?: ReactNode }) {
const menuSize = useContext(SelectSizeContext);
const hasDescription = descriptionNode != null;
return (
<SDKSelectItem
{...props}
data-size={menuSize}
className={partClass(
selectItemVariants({ size: menuSize }),
hasDescription && 'grid',
hasDescription && 'not-has-[[data-slot=select-item-icon]]:grid-cols-1',
className,
)}
>
{icon != null && (
<SelectItemIcon
aria-hidden="true"
className={cn(
'flex shrink-0 items-center justify-center text-muted-foreground',
hasDescription && 'row-span-2',
)}
>
{icon}
</SelectItemIcon>
)}
{children}
{descriptionNode}
</SDKSelectItem>
);
}
function SelectItem<Value = string>({
description,
'aria-describedby': describedBy,
...props
}: SelectItemProps<Value>) {
if (description != null && description !== false) {
return (
<SelectItemWithDescription {...props} description={description} describedBy={describedBy} />
);
}
return <SelectItemBase {...props} aria-describedby={describedBy} />;
}
type SelectItemIndicatorProps = ComponentProps<typeof SDKSelectItemIndicator>;
/** Visual selected marker; the primitive controls visibility and option semantics. */
function SelectItemIndicator({ className, children, ...props }: SelectItemIndicatorProps) {
const menuSize = useContext(SelectSizeContext);
return (
<SDKSelectItemIndicator
{...props}
aria-hidden="true"
className={partClass(selectItemIndicatorVariants({ size: menuSize }), className)}
>
{children ?? CHECK_INDICATOR}
</SDKSelectItemIndicator>
);
}
function SelectDescription({
className,
invalid = false,
...props
}: ComponentProps<'p'> & { invalid?: boolean }) {
return (
<p
{...props}
data-slot="select-description"
className={cn(
'm-0 mt-1 break-words text-xs leading-relaxed',
invalid ? 'text-destructive' : 'text-muted-foreground',
className,
)}
/>
);
}
const SelectValueIcon = SDKSelectValueIcon;
function SelectInput({
render = <Input variant="outline" containerProps={{ className: 'p-2 shrink-0' }} />,
...props
}: ComponentProps<typeof SDKSelectInput>) {
return <SDKSelectInput {...props} render={render} />;
}
const selectMessage = 'shrink-0 px-3 py-2 text-xs text-muted-foreground';
function SelectEmpty({ className, ...props }: ComponentProps<typeof SDKSelectEmpty>) {
return <SDKSelectEmpty {...props} className={partClass(selectMessage, 'empty:p-0', className)} />;
}
function SelectStatus({ className, ...props }: ComponentProps<typeof SDKSelectStatus>) {
return <SDKSelectStatus {...props} className={partClass(selectMessage, className)} />;
}
type SelectClearProps = ComponentProps<typeof SDKSelectClear> & {
variant?: ButtonProps['variant'];
size?: ButtonProps['size'];
};
const clearIcon = <X aria-hidden="true" />;
function SelectClear({
variant = 'ghost',
size = 'icon-xs',
children,
'aria-label': label = children == null ? 'Clear selection' : undefined,
className,
...props
}: SelectClearProps) {
return (
<SDKSelectClear
{...props}
aria-label={label}
data-size={size}
data-variant={variant}
className={partClass(buttonVariants({ variant, size: size }), className)}
>
{children ?? clearIcon}
</SDKSelectClear>
);
}
function SelectSelectAll({ className, ...props }: ComponentProps<typeof SDKSelectSelectAll>) {
return (
<SDKSelectSelectAll
{...props}
className={partClass(
`relative flex min-h-9 cursor-default select-none items-center ${concentricRadius} px-2.5 text-sm group-not-data-sliding-highlight/select-list:data-highlighted:bg-accent data-disabled:opacity-40 data-checked:font-semibold ${focusRing}`,
className,
)}
/>
);
}
function SelectList({ className, ...props }: ComponentProps<typeof SDKSelectList>) {
return (
<SDKSelectList
{...props}
className={partClass(
'scroll-fade min-h-0 overflow-y-auto overscroll-contain p-1 [scrollbar-width:thin] [scrollbar-color:var(--border)_transparent] group-data-[presentation=sheet]/select-content:px-2',
'[&_[data-slot=select-item]:not([data-size])]:relative [&_[data-slot=select-item]:not([data-size])]:z-10 [&_[data-slot=select-item]:not([data-size])]:rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))] [&_[data-slot=select-item]:not([data-size])]:px-2.5 [&_[data-slot=select-item]:not([data-size])]:py-2 [&_[data-slot=select-item]:not([data-size])]:text-sm [&_[data-slot=select-item]:not([data-size])[data-selected]]:bg-accent [&_[data-slot=select-item]:not([data-size])[data-selected]]:font-medium [&_[data-slot=select-item]:not([data-size])[data-selected]]:text-accent-foreground group-not-data-sliding-highlight/select-list:[&_[data-slot=select-item]:not([data-size])[data-highlighted]:not([data-selected])]:bg-accent [&_[data-slot=select-item]:not([data-size])[data-highlighted]]:text-accent-foreground [&_[data-slot=select-item][data-disabled]]:opacity-40',
className,
)}
/>
);
}
function SelectItemText({ className, ...props }: ComponentProps<typeof SDKSelectItemText>) {
return (
<SDKSelectItemText
{...props}
className={partClass('min-w-0 flex-1 break-words [overflow-wrap:anywhere]', className)}
/>
);
}
function SelectItemIcon({ className, ...props }: ComponentProps<typeof SDKSelectItemIcon>) {
return (
<SDKSelectItemIcon
{...props}
className={partClass(
'flex shrink-0 items-center justify-center text-muted-foreground',
className,
)}
/>
);
}
function SelectSeparator({
className,
render = <Separator />,
...props
}: ComponentProps<typeof SDKSelectSeparator>) {
return <SDKSelectSeparator {...props} render={render} className={partClass('my-1', className)} />;
}
function SelectArrow({ className, ...props }: ComponentProps<typeof SDKSelectArrow>) {
return (
<SDKSelectArrow
{...props}
className={partClass(
'pointer-events-none size-2 rotate-45 border border-border bg-popover',
className,
)}
/>
);
}
export {
createSelectController,
type ListData,
Select,
SelectArrow,
SelectClear,
SelectContent,
type SelectController,
SelectDescription,
SelectEmpty,
SelectField,
SelectGroup,
SelectGroupLabel,
SelectInput,
SelectItem,
SelectItemIcon,
SelectItemIndicator,
SelectItems,
SelectItemText,
SelectLabel,
SelectList,
type SelectMenuSize,
type SelectOpenChangeReason,
SelectSelectAll,
SelectSeparator,
SelectStatus,
SelectTrigger,
SelectValue,
type SelectValueChangeReason,
SelectValueIcon,
};
import { mergeProps, type RenderProp, renderElement } from '@ui-sdk/react/primitive';
import { cva, type VariantProps } from 'class-variance-authority';
import { Bell, CircleCheck, CircleDashed, CircleX, TriangleAlert } from 'lucide-react';
import type { ComponentProps, ReactNode } from 'react';
import { ValueTransition } from '@/hooks/use-value-transition';
import { compactControlMinHeights, controlTextSizes } from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
/** Label (`--badge-color`), fill, and ink align with Alert tone tokens. */
const statuses = {
neutral: {
label: 'Status',
className:
'[--badge-color:var(--muted-foreground)] [--badge-fill:var(--muted-foreground)] [--badge-ink:white]',
},
info: {
label: 'Info',
icon: Bell,
className:
'[--badge-color:var(--status-info,var(--color-blue-600))] dark:[--badge-color:var(--status-info,var(--color-blue-400))] [--badge-fill:var(--status-info,var(--color-blue-500))] [--badge-ink:white]',
},
progress: {
label: 'In progress',
icon: CircleDashed,
className:
'[--badge-color:var(--status-progress,var(--color-violet-600))] dark:[--badge-color:var(--status-progress,var(--color-violet-400))] [--badge-fill:var(--status-progress,var(--color-violet-500))] [--badge-ink:white]',
},
warning: {
label: 'Warning',
icon: TriangleAlert,
className:
'[--badge-color:var(--status-warning,var(--status-pending,var(--color-yellow-800)))] dark:[--badge-color:var(--status-warning,var(--status-pending,var(--color-yellow-300)))] [--badge-fill:var(--status-warning,var(--status-pending,var(--color-yellow-500)))] [--badge-ink:white]',
},
success: {
label: 'Success',
icon: CircleCheck,
className:
'[--badge-color:var(--status-success,var(--color-green-700))] dark:[--badge-color:var(--status-success,var(--color-green-400))] [--badge-fill:var(--status-success,var(--color-green-500))] [--badge-ink:white]',
},
error: {
label: 'Error',
icon: CircleX,
className:
'[--badge-color:var(--status-error,var(--color-red-600))] dark:[--badge-color:var(--status-error,var(--color-red-400))] [--badge-fill:var(--status-error,var(--color-red-500))] [--badge-ink:white]',
},
} as const;
const badgeShadow =
'shadow-[inset_0_1px_0_rgb(255_255_255/0.45),0_1px_1.5px_rgb(0_0_0/0.14)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.22),0_1px_2px_rgb(0_0_0/0.4)]';
const badgeVariants = cva(
'group/badge inline-flex w-fit max-w-full min-w-0 items-center justify-center rounded-sm border border-transparent font-medium tracking-normal whitespace-normal select-none transition-[background-color,border-color,box-shadow,filter,translate] duration-150 ease-out [a&,button&]:cursor-pointer [a&,button&]:touch-manipulation motion-safe:[a&,button&]:active:translate-y-px motion-reduce:transition-none',
{
variants: {
status: {
neutral: statuses.neutral.className,
info: statuses.info.className,
progress: statuses.progress.className,
warning: statuses.warning.className,
success: statuses.success.className,
error: statuses.error.className,
},
variant: {
soft: '[--badge-tone:var(--badge-fill,var(--badge-color))] bg-[color-mix(in_oklab,var(--badge-tone)_10%,transparent)] dark:bg-[color-mix(in_oklab,var(--badge-tone)_16%,transparent)] text-[color:var(--badge-color)]',
outline:
'[--badge-tone:var(--badge-fill,var(--badge-color))] border-[color-mix(in_oklab,var(--badge-tone)_32%,var(--border))] bg-transparent text-[color:var(--badge-color)]',
solid: `[--badge-tone:var(--badge-fill,var(--badge-color))] border-[color-mix(in_oklab,var(--badge-tone),black_12%)] bg-[var(--badge-tone)] text-[color:var(--badge-ink,white)] ${badgeShadow}`,
},
size: {
xs: `${compactControlMinHeights.xs} ${controlTextSizes.xs} gap-1 px-1.5 leading-none [&_[data-slot=badge-icon]]:size-2.5`,
sm: `${compactControlMinHeights.sm} ${controlTextSizes.sm} gap-1 px-2 py-0.5 leading-none [&_[data-slot=badge-icon]]:size-3`,
md: `${compactControlMinHeights.md} text-xs gap-1.5 px-2 py-0.5 leading-none [&_[data-slot=badge-icon]]:size-3.5`,
lg: `${compactControlMinHeights.lg} ${controlTextSizes.lg} gap-2 px-3 py-1 leading-snug [&_[data-slot=badge-icon]]:size-4`,
},
},
compoundVariants: [
{
status: 'neutral',
variant: 'solid',
className: 'border-border bg-muted text-muted-foreground',
},
],
defaultVariants: { status: 'neutral', variant: 'soft', size: 'md' },
},
);
type BadgeStatus = keyof typeof statuses;
type BadgeSize = NonNullable<VariantProps<typeof badgeVariants>['size']>;
type BadgeVariant = NonNullable<VariantProps<typeof badgeVariants>['variant']>;
type BadgeState = { slot: 'badge'; status: BadgeStatus; variant: BadgeVariant; size: BadgeSize };
type BadgeProps = ComponentProps<'span'> &
Omit<VariantProps<typeof badgeVariants>, 'status' | 'size' | 'variant'> & {
/** Semantic status preset for its label, icon, and theme color. */
status?: BadgeStatus;
/** Override the preset icon. Pass null or false to omit it. */
icon?: ReactNode;
/** Place the icon before or after the label. */
iconPosition?: 'start' | 'end';
/** Rotate the preset icon, typically for the progress status. */
animated?: boolean;
size?: BadgeSize;
variant?: BadgeVariant;
/** Render the badge as another element, such as an anchor or button. */
render?: RenderProp<BadgeState>;
};
function Badge({
status = 'neutral',
variant = 'soft',
size = 'md',
icon,
iconPosition = 'start',
animated = false,
children,
className,
render,
...props
}: BadgeProps) {
const preset = statuses[status];
const DefaultIcon = 'icon' in preset ? preset.icon : null;
const content = icon !== undefined ? icon : DefaultIcon ? <DefaultIcon /> : null;
const label = children ?? preset.label;
const displayedLabel =
typeof label === 'string' || typeof label === 'number' ? (
<ValueTransition
value={label}
className="min-w-0 max-w-full flex-wrap [overflow-wrap:anywhere]"
/>
) : (
label
);
const indicator =
content === null || content === false ? null : (
<span
aria-hidden="true"
data-slot="badge-icon"
className={cn(
'inline-flex shrink-0 items-center justify-center [&>svg]:size-full [&>svg]:stroke-[1.75]',
animated &&
icon === undefined &&
DefaultIcon &&
'motion-safe:animate-spin motion-safe:[animation-duration:1.6s]',
)}
>
{content}
</span>
);
const state: BadgeState = { slot: 'badge', status, variant, size };
return renderElement(
'span',
mergeProps(props, {
'data-slot': 'badge',
'data-status': status,
'data-variant': variant,
'data-size': size,
className: cn(badgeVariants({ status, variant, size }), className),
children: (
<>
{iconPosition === 'start' && indicator}
<span data-slot="badge-label" className="min-w-0 [overflow-wrap:anywhere]">
{displayedLabel}
</span>
{iconPosition === 'end' && indicator}
</>
),
}),
render,
state,
);
}
export { Badge, type BadgeProps, type BadgeSize, type BadgeStatus, badgeVariants };
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 };
}
'use client';
import { type ComponentProps, useState } from 'react';
import { cn } from '@/lib/utils';
export type UseValueTransitionOptions = {
/** Whether characters animate when the value changes. Defaults to `true`. */
enabled?: boolean;
/** Roll direction. `auto` rolls up when a number grows (or for text), down when it shrinks. */
direction?: 'auto' | 'up' | 'down';
/** Delay in ms between consecutive changed characters. Defaults to `28`. */
stagger?: number;
/**
* Animation granularity:
* - `auto` (default): per-character for numeric values, whole-string for text.
* - `char`: always animate per-character.
* - `whole`: always animate the entire value as one unit.
*/
mode?: 'auto' | 'char' | 'whole';
};
export type TransitionChar = {
key: string;
char: string;
/** The character being replaced. Only set when this character should roll. */
prev?: string;
/** Transition delay in ms. */
delay: number;
};
const MAX_DELAY = 140;
const hasDigit = (text: string) => /\d/.test(text);
const isNumeric = (text: string) => hasDigit(text) && !/[a-zA-Z]/.test(text);
const toNumber = (text: string) => Number.parseFloat(text.replace(/[^\d.-]/g, ''));
/**
* Diffs `value` against its previous value and returns per-character data, so
* only the characters that actually changed roll, one after another.
*
* - Numbers align from the right (the ones digit stays the ones digit),
* text aligns from the left.
* - Pure derivation from state, with no effects or DOM reads, so it works for
* any value: numbers, formatted numbers, labels, statuses.
*/
export function useValueTransition(
value: string | number | null | undefined,
{
enabled = true,
direction = 'auto',
stagger = 28,
mode = 'auto',
}: UseValueTransitionOptions = {},
) {
const text = value == null ? '' : String(value);
const [state, setState] = useState({ text, prev: text });
if (state.text !== text) setState({ text, prev: state.text });
const numeric = isNumeric(state.text);
const perChar = mode === 'char' || (mode === 'auto' && numeric);
const dir: 1 | -1 =
direction === 'up'
? 1
: direction === 'down'
? -1
: numeric && hasDigit(state.prev) && toNumber(state.text) < toNumber(state.prev)
? -1
: 1;
if (!perChar) {
const changed = enabled && state.prev !== state.text;
const chars: TransitionChar[] = state.text
? [
{
key: `whole-${state.text}`,
char: state.text,
prev: changed ? state.prev : undefined,
delay: 0,
},
]
: [];
return { text: state.text, chars, dir };
}
const next = [...state.text];
const old = [...state.prev];
const offset = numeric ? old.length - next.length : 0;
const fromEmpty = state.prev === '' && state.text !== '';
// Stagger starts at the least significant end: ones digit first for numbers.
let rank = 0;
const chars: TransitionChar[] = new Array(next.length);
for (let step = 0; step < next.length; step++) {
const i = numeric ? next.length - 1 - step : step;
const char = next[i];
const prevChar = old[i + offset];
const shouldRoll = enabled && (fromEmpty || (prevChar !== undefined && prevChar !== char));
chars[i] = {
// Keyed by position + char: a changed character remounts (replaying the
// animation, even on rapid changes) while untouched ones stay mounted.
key: `${numeric ? next.length - i : i}-${char}`,
char,
prev: shouldRoll ? (prevChar ?? '') : undefined,
delay: shouldRoll ? Math.min(rank++ * stagger, MAX_DELAY) : 0,
};
}
return { text: state.text, chars, dir };
}
const motion =
'transition-[translate,opacity,filter] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none';
export type ValueTransitionProps = Omit<ComponentProps<'span'>, 'children'> &
UseValueTransitionOptions & {
value: string | number | null | undefined;
/** Whether to apply a subtle blur during the transition. Defaults to `true`. */
blur?: boolean;
};
/**
* Drop-in display for any value: `<ValueTransition value={count} />`.
* Inherits font, size and color from its parent.
*/
export function ValueTransition({
value,
enabled,
direction,
stagger,
mode,
blur = true,
className,
...props
}: ValueTransitionProps) {
const { text, chars, dir } = useValueTransition(value, { enabled, direction, stagger, mode });
return (
<span
{...props}
className={cn(
'inline-flex overflow-hidden tabular-nums [mask-image:linear-gradient(to_bottom,transparent,#000_14%,#000_88%,transparent)]',
className,
)}
>
<span className="sr-only"> {text} </span>
<span aria-hidden="true" className="inline-flex">
{chars.map(({ key, char, prev, delay }) => (
<span
key={key}
className={cn(
'relative inline-block whitespace-pre leading-normal',
dir > 0 ? '[--d:1]' : '[--d:-1]',
)}
>
{prev === undefined ? (
char
) : (
<>
<span
style={{ transitionDelay: `${delay}ms` }}
className={cn(
'inline-block starting:translate-y-[calc(var(--d)*100%)] starting:opacity-0',
blur && 'starting:blur-[2px]',
motion,
)}
>
{char}
</span>
<span
aria-hidden="true"
style={{ transitionDelay: `${delay}ms` }}
className={cn(
'absolute inset-0 translate-y-[calc(var(--d)*-100%)] opacity-0 starting:translate-y-0 starting:opacity-100 motion-reduce:hidden',
blur && 'blur-[2px] starting:blur-none',
motion,
)}
>
{prev}
</span>
</>
)}
</span>
))}
</span>
</span>
);
}
import { cn } from '@/lib/utils';
type ClassValue = string | false | null | undefined;
type PartClassValue<State> = ClassValue | ((state: State) => ClassValue);
/** Composes static class names and UI-SDK state class functions into a single `className` prop. */
export function partClass<State>(...parts: PartClassValue<State>[]) {
if (parts.some((part) => typeof part === 'function')) {
return (state: State) =>
cn(...parts.map((part) => (typeof part === 'function' ? part(state) : part)));
}
return cn(...(parts as ClassValue[]));
}
export const surfacePadding = 'p-1 [--surface-padding:1.5rem] [--concentric-inset:0.25rem]';
export const surfaceRegionInset = 'p-[calc(var(--surface-padding,1rem)-0.5rem)]';
export const surfaceHeaderRadius = 'rounded-t-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
export const surfaceFooterRadius = 'rounded-b-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
/** Concentric inner radius (`outer - inset`); set `[--concentric-inset:0.125rem]` on `p-0.5` rails (defaults to `0.25rem` for `p-1`). */
export const concentricRadius =
'rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))]';
export const surfaceBodyPadding =
'py-[max(0px,calc(var(--surface-padding,1rem)-1rem))] has-[>[data-slot=list]:not([data-variant=plain])]:p-0 has-[>[data-slot=list-items-container]]:p-0';
export type StandardControlSize = 'xs' | 'sm' | 'md' | 'lg';
/** Standard control heights (`28px / 32px / 40px / 48px`) for buttons, inputs, selects, tabs, and sliders. */
export const controlHeights = {
xs: 'h-7',
sm: 'h-8',
md: 'h-10',
lg: 'h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard minimum control heights (`28px / 32px / 40px / 48px`) for expandable controls and menu items. */
export const controlMinHeights = {
xs: 'min-h-7',
sm: 'min-h-8',
md: 'min-h-10',
lg: 'min-h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard control text sizes (`xs / xs / sm / base`) paired with `StandardControlSize`. */
export const controlTextSizes = {
xs: 'text-xs',
sm: 'text-xs',
md: 'text-sm',
lg: 'text-base',
} as const satisfies Record<StandardControlSize, string>;
/** Compact control heights (`1.25rem / 1.3rem / 1.625rem / 1.75rem`), one step smaller than standard, for switches and compact controls. */
export const compactControlHeights = {
xs: 'h-[1.3rem]',
sm: 'h-[1.4rem]',
md: 'h-[1.5rem]',
lg: 'h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Compact minimum control heights (`1rem / 1.25rem / 1.5rem / 1.75rem`) for badges and tooltips. */
export const compactControlMinHeights = {
xs: 'min-h-[1.3rem]',
sm: 'min-h-[1.4rem]',
md: 'min-h-[1.5rem]',
lg: 'min-h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Universal keyboard focus + invalid ring/border styles shared across controls. */
export const focusRing =
'touch-manipulation outline-none focus-visible:border-ring/30 transition-ring focus-visible:ring-3 focus-visible:ring-ring/15 focus-visible:brightness-[0.97] dark:focus-visible:brightness-[1.15] has-[:focus-visible]:border-ring/30 has-[:focus-visible]:ring-3 has-[:focus-visible]:ring-ring/15 has-[:focus-visible]:brightness-[0.97] dark:has-[:focus-visible]:brightness-[1.15] data-active:border-ring/30 data-active:ring-3 data-active:ring-ring/15 data-active:brightness-[0.97] dark:data-active:brightness-[1.15] data-open:border-ring/30 data-open:ring-3 data-open:ring-ring/15 data-open:brightness-[0.97] dark:data-open:brightness-[1.15] data-disabled:cursor-not-allowed data-disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/25 data-invalid:border-destructive data-invalid:ring-3 data-invalid:ring-destructive/25 has-[[data-invalid]]:border-destructive has-[[data-invalid]]:ring-3 has-[[data-invalid]]:ring-destructive/25 group-aria-invalid/control:border-destructive group-aria-invalid/control:ring-3 group-aria-invalid/control:ring-destructive/25 group-data-invalid/control:border-destructive group-data-invalid/control:ring-3 group-data-invalid/control:ring-destructive/25 group-has-[input[aria-invalid=true]]/control:border-destructive group-has-[input[aria-invalid=true]]/control:ring-3 group-has-[input[aria-invalid=true]]/control:ring-destructive/25 hover:brightness-[0.97] dark:hover:brightness-[1.15]';
/** Shared sliding highlight indicator base (pointer-safe, concentric inner radius inside rounded-lg containers, 200ms transition). */
export const slidingHighlight =
'pointer-events-none -z-10 rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))] bg-primary/10 [clip-path:inset(0px_round_max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem))))] transition-[transform,width,height,opacity] duration-200 ease-out motion-reduce:transition-none';
export const textFieldSurfaces = {
filled: 'border-input bg-card text-card-foreground',
outline: 'border-input bg-transparent text-foreground dark:bg-transparent',
ghost: 'border-transparent bg-muted text-foreground shadow-none',
underline:
'rounded-none border-0 border-b-2 border-input bg-transparent px-0 text-foreground shadow-none focus-visible:border-ring focus-visible:ring-0 aria-invalid:ring-0 data-invalid:ring-0 dark:bg-transparent',
} as const;
export const textFieldUnderlineMotion =
'border-transparent! bg-origin-border bg-bottom bg-no-repeat [--underline-color:var(--primary)] [background-image:linear-gradient(var(--underline-color),var(--underline-color)),linear-gradient(var(--input),var(--input))] [background-size:0%_2px,100%_2px] focus:[background-size:100%_2px,100%_2px] aria-invalid:[--underline-color:var(--destructive)] data-invalid:[--underline-color:var(--destructive)] transition-[border-color,background-color,box-shadow,filter,background-size] duration-200 motion-reduce:transition-none';
/** Generic balanced icon & floating-label layout tokens shared across all text-field sizes. */
export const textFieldLayout = {
icon: 'size-4',
iconStart: 'start-3',
iconEnd: 'end-3',
padStart: 'ps-9',
padEnd: 'pe-9',
underlinePadStart: 'ps-7',
underlinePadEnd: 'pe-7',
floatingStart: 'start-2.5',
floatingWithIcon: 'start-8',
floatingUnderlineIcon: 'start-6',
} as const;
export const textFieldLabelSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
/** Clamps per-grapheme wave delay (ms) so total staggering stays within 300ms. */
export function clampWaveDelay(waveDelay: number, count: number): number {
return Math.max(
0,
Math.min(Number.isFinite(waveDelay) ? waveDelay : 24, 80, 300 / Math.max(1, count - 1)),
);
}
/** Shared scale/color transition for floating labels inside a `group/field` wrapper. */
export const textFieldLabelMotion =
'inline-block origin-left backdrop-blur-xs transition-[scale,color] duration-200 ease-out group-has-[input:focus]/field:scale-85 group-has-[input:not(:placeholder-shown)]/field:scale-85 rtl:origin-right motion-reduce:transition-none';
/** Resolves start/end padding for a text field when a leading or trailing icon is present. */
export function getTextFieldIconPadding(iconPosition: 'start' | 'end', underline: boolean): string {
if (iconPosition === 'start') {
return underline ? textFieldLayout.underlinePadStart : textFieldLayout.padStart;
}
return underline ? textFieldLayout.underlinePadEnd : textFieldLayout.padEnd;
}
/** Shared per-grapheme ripple transition for wave labels inside a `group/field` wrapper. */
export const textFieldWaveMotion =
'inline-block origin-left backdrop-blur-xs transition-[translate,scale,color] duration-200 ease-out group-has-[input:focus]/field:-translate-y-5 group-has-[input:focus]/field:scale-85 group-has-[input:focus]/field:text-primary group-has-[input:not(:placeholder-shown)]/field:-translate-y-5 group-has-[input:not(:placeholder-shown)]/field:scale-85 group-has-[input[aria-invalid=true]]/field:text-destructive rtl:origin-right motion-reduce:transition-none';