Search a set of options and choose one or several values.
Default
Creatable Tags & Chips
Grouped Object Values & Form
Search by name or email, then submit the form.
Async Search
Purpose
Search a set of options and choose one or several values.
Parts & Composition
Place ComboboxInput and optionally ComboboxLabel in the root. Put ComboboxItem rows in ComboboxList inside ComboboxContent. Place empty and status messages outside the list. Use the chip parts when displaying multiple selected values.
API & Props
| Prop or part | Purpose |
|---|---|
value, defaultValue, onValueChange | Control or initialize the selection. With multiple, pass an array. |
query, defaultQuery, onQueryChange | Control or observe search text independently of selection. |
items, filter, onLoadMore | SDK data, filtering, and pagination options. Explicit items let you compose styled rows. |
presentation | Defaults to "auto". Supports "popover" and "sheet". |
Combobox.size / ComboboxInput.variant | xs, sm, md (default), or lg scales input, items, create/select-all rows, and group labels together; variant selects shared text field surfaces. |
ComboboxList.slidingHighlight | Glides the shared sliding highlight across item, create, and select-all rows (true by default; false falls back to bg-accent) with scroll-fade. |
ComboboxContent.mobileTitle | Optional heading rendered when the combobox opens as a bottom sheet on small touch screens. |
Theming, Layout & Responsiveness
The input uses shared text field tokens. The popup matches the anchor width on desktop and can open as a sheet on small touch screens.
Motion & Accessibility
The shared highlight follows the SDK active option. The SDK owns focus and selection, and popup transitions respect reduced motion.
Guidance for Coding Agents
Install Combobox using the command in the Install tab and read this Info page. Begin with the closest Preview example, then consult the UI SDK Combobox reference for inherited props, state callbacks, and custom rendering.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/combobox'use client';
import {
Combobox as SDKCombobox,
ComboboxArrow as SDKComboboxArrow,
ComboboxChip as SDKComboboxChip,
ComboboxChipRemove as SDKComboboxChipRemove,
ComboboxChips as SDKComboboxChips,
ComboboxChipsOverflow as SDKComboboxChipsOverflow,
ComboboxClear as SDKComboboxClear,
ComboboxContent as SDKComboboxContent,
ComboboxCreate as SDKComboboxCreate,
ComboboxEmpty as SDKComboboxEmpty,
ComboboxGroup as SDKComboboxGroup,
ComboboxGroupLabel as SDKComboboxGroupLabel,
ComboboxInput as SDKComboboxInput,
ComboboxItem as SDKComboboxItem,
ComboboxItemIcon as SDKComboboxItemIcon,
ComboboxItemIndicator as SDKComboboxItemIndicator,
ComboboxItemText as SDKComboboxItemText,
ComboboxLabel as SDKComboboxLabel,
ComboboxList as SDKComboboxList,
type ComboboxProps as SDKComboboxProps,
ComboboxSelectAll as SDKComboboxSelectAll,
ComboboxSeparator as SDKComboboxSeparator,
ComboboxStatus as SDKComboboxStatus,
ComboboxTrigger as SDKComboboxTrigger,
} from '@ui-sdk/react/combobox';
import { cva } from 'class-variance-authority';
import { Check, ChevronDown, X } from 'lucide-react';
import { type ComponentProps, createContext, type ReactNode, useContext } from 'react';
import { type BadgeProps, badgeVariants } from '@/components/devvarena-ui/badge';
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 { ValueTransition } from '@/hooks/use-value-transition';
import {
concentricRadius,
controlMinHeights,
controlTextSizes,
partClass,
type StandardControlSize,
slidingHighlight as slidingHighlightClass,
type textFieldSurfaces,
} from '@/lib/devvarena-ui';
const ComboboxSizeContext = createContext<StandardControlSize>('md');
const comboboxRowStyles = cva(
`relative flex min-w-0 cursor-pointer touch-manipulation select-none items-center ${concentricRadius} text-start outline-none [@media(pointer:coarse)]:min-h-11 data-highlighted:text-accent-foreground group-not-data-sliding-highlight/combobox-list:data-highlighted:bg-accent data-disabled:pointer-events-none data-disabled:opacity-50 data-pending:cursor-progress data-pending:opacity-60 data-selected:font-medium`,
{
variants: {
size: {
xs: `${controlMinHeights.xs} gap-1.5 px-2 ${controlTextSizes.xs}`,
sm: `${controlMinHeights.sm} gap-2 px-2.5 ${controlTextSizes.sm}`,
md: `${controlMinHeights.md} gap-2.5 px-2.5 ${controlTextSizes.md}`,
lg: `${controlMinHeights.lg} gap-2.5 px-3 ${controlTextSizes.lg}`,
} satisfies Record<StandardControlSize, string>,
},
defaultVariants: { size: 'md' },
},
);
const comboboxGroupLabelStyles = cva('font-medium text-muted-foreground', {
variants: {
size: {
xs: 'px-2 py-1 text-xs',
sm: 'px-2.5 py-1 text-xs',
md: 'px-2.5 py-1.5 text-xs',
lg: 'px-3 py-2 text-sm',
} satisfies Record<StandardControlSize, string>,
},
defaultVariants: { size: 'md' },
});
const HIGHLIGHT_SELECTOR =
':is([data-slot="combobox-item"],[data-slot="combobox-create"],[data-slot="combobox-select-all"]):not([data-disabled])';
const chevron = (
<ChevronDown
aria-hidden="true"
className="transition-transform in-data-open:rotate-180 motion-reduce:transition-none"
/>
);
const close = <X aria-hidden="true" />;
const check = <Check aria-hidden="true" />;
type ComboboxProps<T = string, Multiple extends boolean | undefined = false> = SDKComboboxProps<
T,
Multiple
> & {
size?: StandardControlSize;
};
function Combobox<T = string, Multiple extends boolean | undefined = false>({
presentation = 'auto',
size = 'md',
...props
}: ComboboxProps<T, Multiple>) {
return (
<ComboboxSizeContext value={size}>
<SDKCombobox<T, Multiple>
{...(props as SDKComboboxProps<T, Multiple>)}
presentation={presentation}
/>
</ComboboxSizeContext>
);
}
function ComboboxItemIndicator({
className,
children,
...props
}: ComponentProps<typeof SDKComboboxItemIndicator>) {
return (
<SDKComboboxItemIndicator
{...props}
className={partClass(
'ms-auto inline-grid size-4 shrink-0 place-items-center text-primary [&>svg]:size-full',
className,
)}
>
{children ?? check}
</SDKComboboxItemIndicator>
);
}
function ComboboxSeparator({ className, ...props }: ComponentProps<typeof SDKComboboxSeparator>) {
return (
<SDKComboboxSeparator
{...props}
render={<Separator />}
className={partClass('my-1', className)}
/>
);
}
type ComboboxInputProps = Omit<ComponentProps<typeof SDKComboboxInput>, 'size'> & {
size?: StandardControlSize;
variant?: keyof typeof textFieldSurfaces;
htmlSize?: number;
};
function ComboboxInput({
size,
variant = 'filled',
htmlSize,
className,
...props
}: ComboboxInputProps) {
const contextSize = useContext(ComboboxSizeContext);
const inputSize = size ?? contextSize;
return (
<SDKComboboxInput
{...props}
size={htmlSize}
data-size={inputSize}
data-variant={variant}
className={partClass(inputVariants({ size: inputSize, variant }), className)}
/>
);
}
type ComboboxListProps = ComponentProps<typeof SDKComboboxList> & {
slidingHighlight?: boolean;
};
function ComboboxList({
slidingHighlight = true,
className,
children,
...props
}: ComboboxListProps) {
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector: HIGHLIGHT_SELECTOR,
activeAttribute: 'data-highlighted',
disabled: !slidingHighlight,
});
return (
<div
data-sliding-highlight={slidingHighlight ? '' : undefined}
className="group/combobox-list scroll-fade min-h-0 overflow-y-auto overscroll-contain [scrollbar-width:thin] [scrollbar-color:var(--border)_transparent]"
>
<div ref={containerRef} className="relative isolate">
{slidingHighlight && (
<span aria-hidden="true" style={highlightStyle} className={slidingHighlightClass} />
)}
<SDKComboboxList
{...props}
className={partClass('relative grid min-w-0 gap-0.5 p-1', className)}
>
{children}
</SDKComboboxList>
</div>
</div>
);
}
type ComboboxTriggerProps = ComponentProps<typeof SDKComboboxTrigger> &
Pick<ButtonProps, 'size' | 'variant'>;
function ComboboxTrigger({
size = 'icon-sm',
variant = 'ghost',
className,
children,
...props
}: ComboboxTriggerProps) {
return (
<SDKComboboxTrigger
{...props}
data-size={size}
data-variant={variant}
className={partClass(buttonVariants({ size, variant }), className)}
>
{children ?? chevron}
</SDKComboboxTrigger>
);
}
type ComboboxClearProps = ComponentProps<typeof SDKComboboxClear> &
Pick<ButtonProps, 'size' | 'variant'>;
function ComboboxClear({
size = 'icon-sm',
variant = 'ghost',
className,
children,
...props
}: ComboboxClearProps) {
return (
<SDKComboboxClear
{...props}
data-size={size}
data-variant={variant}
className={partClass(buttonVariants({ size, variant }), className)}
>
{children ?? close}
</SDKComboboxClear>
);
}
function ComboboxChipRemove({
className,
children,
...props
}: ComponentProps<typeof SDKComboboxChipRemove>) {
return (
<SDKComboboxChipRemove
{...props}
className={partClass(
'inline-grid size-4 shrink-0 cursor-pointer place-items-center rounded-sm text-current/65 transition-[background-color,color,opacity] duration-150 hover:bg-foreground/10 hover:text-current focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 [&>svg]:size-3',
className,
)}
>
{children ?? close}
</SDKComboboxChipRemove>
);
}
function ComboboxLabel({ className, ...props }: ComponentProps<typeof SDKComboboxLabel>) {
return (
<SDKComboboxLabel
{...props}
className={partClass('block text-sm font-medium data-disabled:opacity-50', className)}
/>
);
}
type ComboboxContentProps = ComponentProps<typeof SDKComboboxContent> & {
mobileTitle?: ReactNode;
};
function ComboboxContent({
sideOffset = 4,
mobileTitle,
className,
children,
...props
}: ComboboxContentProps) {
const size = useContext(ComboboxSizeContext);
return (
<SDKComboboxContent
{...props}
sideOffset={sideOffset}
data-size={size}
className={partClass(
'group/combobox-content not-prose flex max-h-(--available-height,22rem) min-w-0 flex-col overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-sm data-[presentation=popover]:w-(--anchor-width) data-[presentation=sheet]:h-[min(32rem,80dvh)] data-[presentation=sheet]:max-h-none data-[presentation=sheet]:w-full data-[presentation=sheet]:rounded-b-none data-[presentation=sheet]:border-x-0 data-[presentation=sheet]:border-b-0 data-[presentation=sheet]:pb-[max(0.5rem,env(safe-area-inset-bottom))] origin-(--transform-origin) 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-ending-style:scale-[0.98] 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',
className,
)}
>
{(state) => (
<>
{mobileTitle != null && (
<div className="relative mx-1 mt-1 hidden shrink-0 px-3 py-3 group-data-[presentation=sheet]/combobox-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>
)}
{typeof children === 'function' ? children(state) : children}
</>
)}
</SDKComboboxContent>
);
}
function ComboboxItem<T = string>({
className,
...props
}: ComponentProps<typeof SDKComboboxItem<T>>) {
const size = useContext(ComboboxSizeContext);
return (
<SDKComboboxItem<T>
{...props}
data-size={size}
className={partClass(comboboxRowStyles({ size }), className)}
/>
);
}
function ComboboxGroup({ className, ...props }: ComponentProps<typeof SDKComboboxGroup>) {
return <SDKComboboxGroup {...props} className={partClass('grid gap-0.5', className)} />;
}
function ComboboxGroupLabel({ className, ...props }: ComponentProps<typeof SDKComboboxGroupLabel>) {
const size = useContext(ComboboxSizeContext);
return (
<SDKComboboxGroupLabel
{...props}
className={partClass(comboboxGroupLabelStyles({ size }), className)}
/>
);
}
function ComboboxEmpty({ className, ...props }: ComponentProps<typeof SDKComboboxEmpty>) {
return (
<SDKComboboxEmpty
{...props}
className={partClass(
'px-3 py-4 text-center text-sm text-muted-foreground empty:hidden',
className,
)}
/>
);
}
function ComboboxStatus({ className, ...props }: ComponentProps<typeof SDKComboboxStatus>) {
return (
<SDKComboboxStatus
{...props}
className={partClass('px-3 py-2 text-xs text-muted-foreground empty:hidden', className)}
/>
);
}
function ComboboxItemIcon({ className, ...props }: ComponentProps<typeof SDKComboboxItemIcon>) {
return (
<SDKComboboxItemIcon
{...props}
className={partClass(
'inline-flex size-4 shrink-0 items-center justify-center text-muted-foreground [&>svg]:size-full',
className,
)}
/>
);
}
function ComboboxItemText({ className, ...props }: ComponentProps<typeof SDKComboboxItemText>) {
return (
<SDKComboboxItemText
{...props}
className={partClass(
'min-w-0 flex-1 truncate [&_mark]:bg-transparent [&_mark]:font-semibold [&_mark]:text-foreground',
className,
)}
/>
);
}
function ComboboxChips({ className, ...props }: ComponentProps<typeof SDKComboboxChips>) {
return (
<SDKComboboxChips
{...props}
className={partClass('flex min-w-0 flex-wrap items-center gap-1.5', className)}
/>
);
}
type ComboboxChipProps<T = string> = ComponentProps<typeof SDKComboboxChip<T>> &
Pick<BadgeProps, 'variant' | 'size'>;
function ComboboxChip<T = string>({
className,
variant = 'solid',
size,
...props
}: ComboboxChipProps<T>) {
const contextSize = useContext(ComboboxSizeContext);
const chipSize = size ?? contextSize;
return (
<SDKComboboxChip<T>
{...props}
data-variant={variant}
data-size={chipSize}
className={partClass(badgeVariants({ variant, size: chipSize }), 'gap-1 pe-1', className)}
/>
);
}
function ComboboxCreate({ className, ...props }: ComponentProps<typeof SDKComboboxCreate>) {
const size = useContext(ComboboxSizeContext);
return (
<SDKComboboxCreate
{...props}
data-size={size}
className={partClass(comboboxRowStyles({ size }), className)}
/>
);
}
function ComboboxSelectAll({ className, ...props }: ComponentProps<typeof SDKComboboxSelectAll>) {
const size = useContext(ComboboxSizeContext);
return (
<SDKComboboxSelectAll
{...props}
data-size={size}
className={partClass(comboboxRowStyles({ size }), className)}
/>
);
}
type ComboboxChipsOverflowProps = ComponentProps<typeof SDKComboboxChipsOverflow> &
Pick<BadgeProps, 'variant' | 'size'>;
function ComboboxChipsOverflow({
className,
variant = 'soft',
size,
children,
...props
}: ComboboxChipsOverflowProps) {
const contextSize = useContext(ComboboxSizeContext);
const chipSize = size ?? contextSize;
return (
<SDKComboboxChipsOverflow
{...props}
data-variant={variant}
data-size={chipSize}
className={partClass(badgeVariants({ variant, size: chipSize }), className)}
>
{children ?? (({ count }) => <ValueTransition value={`+${count}`} />)}
</SDKComboboxChipsOverflow>
);
}
function ComboboxArrow({ className, ...props }: ComponentProps<typeof SDKComboboxArrow>) {
return (
<SDKComboboxArrow
{...props}
className={partClass('size-2 rotate-45 border border-border bg-popover', className)}
/>
);
}
export {
ComboboxItems,
ComboboxValue,
ComboboxValueIcon,
createComboboxController,
} from '@ui-sdk/react/combobox';
export {
Combobox,
ComboboxArrow,
ComboboxChip,
ComboboxChipRemove,
ComboboxChips,
ComboboxChipsOverflow,
ComboboxClear,
ComboboxContent,
type ComboboxContentProps,
ComboboxCreate,
ComboboxEmpty,
ComboboxGroup,
ComboboxGroupLabel,
ComboboxInput,
type ComboboxInputProps,
ComboboxItem,
ComboboxItemIcon,
ComboboxItemIndicator,
ComboboxItemText,
ComboboxLabel,
ComboboxList,
type ComboboxListProps,
type ComboboxProps,
ComboboxSelectAll,
ComboboxSeparator,
ComboboxStatus,
ComboboxTrigger,
};
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';