Edit text alongside atomic tokens for mentions, files, and other references.
Default
Type @ to mention a teammate.
Sizes
Variants
Grouped suggestions
Token deletion
Form and custom tokens
States
Purpose
A token input lets people write text and insert distinct items, such as mentions, files, or commands, into the same editable field.
Parts & Composition
TokenInput owns the ordered text-and-token value. Put TokenInputEditor and, when suggestions are needed, TriggerMenu inside it. The SDK connects the menu to the editor caret. TriggerMenuContent, TriggerMenuList, and TriggerMenuItem render the suggestion surface. renderToken customizes each inserted token; use TokenInputToken and TokenInputTokenRemove to retain the built-in selection and removal behavior.
API & Props
| Part / Prop | Purpose |
|---|---|
TokenInput.value / defaultValue / onValueChange | Controlled, initial, or change-tracked ordered arrays of text and token objects. Change details include the reason and removed tokens; details.cancel() can reject an edit. |
onSubmit / submitShortcut | Optional submit callback and shortcut: enter or mod+enter. An open menu or active input method keeps Enter available to that interaction. |
tokenDeletion | whole removes a token immediately; select selects then removes it; revert turns it back into editable text. Defaults to whole. |
copy / codec / getTokenDescription | Set clipboard output, token text serialization, and the extra screen-reader description for each token. |
name / form / required / disabled / readOnly | Native form submission and standard form/editability behavior. A named field submits the codec's text representation. |
controller / history / debug | Programmatic read, edit, focus, clear, and undo history. debug logs state changes in development. |
renderToken | Return custom token content. The default renderer uses TokenInputToken and TokenInputTokenRemove; getTokenIcon supplies an optional icon to it. |
TokenInputEditor.variant / size | filled, outline, ghost, or underline; and xs, sm, md, or lg. Defaults to filled and md. Size sets minimum height, padding, and text scale while the editor can grow for wrapped content. |
TokenInputEditor.placeholder / render | Empty-state hint and SDK rendering override. Show the placeholder with the editor's data-empty state. |
TokenInputToken.icon / TokenInputTokenRemove | Optional decorative icon and built-in token removal control. The remove control is revealed on hover or keyboard focus and stays available on touch devices. |
TriggerMenu / TriggerMenuContent / TriggerMenuList / TriggerMenuItem | Supply trigger definitions and compose the suggestion surface. TriggerMenuItem accepts value, label, disabled, and an optional decorative icon. |
createTokenInputController, defaultCodec, fromText, toLabel, toText | Create a controller and encode, decode, or extract display text from token input values. |
TriggerMenu also supports filtered or asynchronous item sources, groups, empty/loading states, command arguments, and controlled state. See the upstream reference for its full API. Native attributes, event handlers, refs, and rendering props pass through on their corresponding SDK parts. className on TokenInputEditor styles the editable region; className on TriggerMenuContent styles the popup.
Theming, Layout & Responsiveness
The editor uses the same semantic surfaces and focus treatment as Input. Its four sizes use shared minimum-height and text-scale tokens, with content-driven height for multiple lines. The underline variant uses the shared text-field underline treatment. TriggerMenuContent uses the popover theme tokens, and its active suggestion moves the shared sliding highlight. Token chips retain their subtle primary-tinted bevel; pending and unresolved states use SDK data attributes and semantic tokens.
The editor exposes data-size, data-variant, data-empty, data-disabled, and data-readonly. Tokens expose data-token-type, data-pending, data-unresolved, and data-selected. The suggestion menu uses the SDK's caret anchor and collision handling.
Motion & Accessibility
The SDK editor handles caret movement, selection, clipboard operations, undo/redo, token navigation, and trigger-menu keyboard interaction. Backspace and Delete follow tokenDeletion; arrow keys move through suggestions and Enter chooses the highlighted item. Token appearance, suggestion popup, and highlight motion respect reduced-motion preferences.
Give the editor an accessible name with aria-label or a UI SDK Field and FieldLabel. The remove part is hidden from assistive technology because keyboard deletion is the accessible path. Keep token labels understandable without icons, and use getTokenDescription when a token needs more spoken context. Add name when the value should be submitted with a form.
Guidance for Coding Agents
Install @ui-sdk/react and @ui-sdk/core if they are not already dependencies. Read this Info page and the upstream UI SDK Token Input reference and Trigger Menu reference before implementing advanced behavior. Build on the SDK TokenInput → TokenInputEditor composition, add TriggerMenu only for suggestions, and use the library's wrapped parts for the themed editor, chips, popup, and menu items.
Represent content as ordered strings and token objects with stable type and value fields. Choose controlled state only when the app must own each update; otherwise use defaultValue. Use renderToken for custom chip markup, preserving TokenInputToken and TokenInputTokenRemove when the built-in selection and removal behavior is desired. Use getTokenIcon for a simple icon lookup in the default renderer. Keep filtering data, persistence, permissions, and submission effects in the application.
Set name for native form submission and select tokenDeletion to match the editing experience. Give each editor an accessible name, keep icons decorative, and use the closest Preview example as the starting point. Check both upstream references for inherited props, event details, data sources, keyboard behavior, and rendering options rather than recreating those behaviors in the wrapper.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/token-input'use client';
import type { Token as SDKToken, TokenCodec, TokenInputOptions } from '@ui-sdk/core/token-input';
import { mergeProps } from '@ui-sdk/react/primitive';
import {
createTokenInputController,
defaultCodec,
fromText,
TokenInput as SDKTokenInput,
TokenInputEditor as SDKTokenInputEditor,
TokenInputToken as SDKTokenInputToken,
TokenInputTokenRemove as SDKTokenInputTokenRemove,
toLabel,
toText,
} from '@ui-sdk/react/token-input';
import {
TriggerMenuContent as SDKTriggerMenuContent,
TriggerMenuEmpty as SDKTriggerMenuEmpty,
TriggerMenuGroup as SDKTriggerMenuGroup,
TriggerMenuGroupLabel as SDKTriggerMenuGroupLabel,
TriggerMenuHint as SDKTriggerMenuHint,
TriggerMenuItem as SDKTriggerMenuItem,
TriggerMenuList as SDKTriggerMenuList,
TriggerMenuSeparator as SDKTriggerMenuSeparator,
TriggerMenuStatus as SDKTriggerMenuStatus,
TriggerMenu,
type TriggerMenuDataItem,
TriggerMenuItemIcon,
} from '@ui-sdk/react/trigger-menu';
import { cva, type VariantProps } from 'class-variance-authority';
import { X } from 'lucide-react';
import { type ComponentProps, createContext, type ReactNode, useContext } from 'react';
import { type BadgeProps, badgeVariants } from '@/components/devvarena-ui/badge';
import { Separator } from '@/components/devvarena-ui/separator';
import { useSlidingHighlight } from '@/hooks/use-sliding-highlight';
import {
concentricRadius,
controlMinHeights,
controlTextSizes,
focusRing,
partClass,
type StandardControlSize,
slidingHighlight,
textFieldSurfaces,
textFieldUnderlineMotion,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
type Token = SDKToken & { icon?: ReactNode };
type TokenInputValue = (string | Token)[];
const tokenInputEditorVariants = cva(
`block h-auto w-full min-w-0 whitespace-pre-wrap wrap-anywhere rounded-lg border shadow-sm transition-[border-color,background-color,box-shadow,filter] duration-200 ${focusRing} data-empty:before:pointer-events-none data-empty:before:text-muted-foreground data-empty:before:content-[attr(aria-placeholder)] motion-reduce:transition-none`,
{
variants: {
size: {
xs: `${controlMinHeights.xs} px-2 py-1 ${controlTextSizes.xs}`,
sm: `${controlMinHeights.sm} px-2.5 py-1.5 ${controlTextSizes.sm}`,
md: `${controlMinHeights.md} px-3 py-2 ${controlTextSizes.md}`,
lg: `${controlMinHeights.lg} px-4 py-2.5 ${controlTextSizes.lg}`,
},
},
defaultVariants: { size: 'md' },
},
);
const TokenInputSizeContext = createContext<StandardControlSize>('md');
type TokenInputProps = Omit<
ComponentProps<typeof SDKTokenInput>,
'value' | 'defaultValue' | 'renderToken'
> & {
size?: StandardControlSize;
value?: TokenInputValue;
defaultValue?: TokenInputValue;
renderToken?: (token: Token) => ReactNode;
getTokenIcon?: (token: Token) => ReactNode;
};
function TokenInput({
size = 'md',
getTokenIcon,
renderToken = (token) => (
<TokenInputToken icon={token.icon ?? getTokenIcon?.(token)}>
{token.label}
<TokenInputTokenRemove />
</TokenInputToken>
),
...props
}: TokenInputProps) {
return (
<TokenInputSizeContext value={size}>
<SDKTokenInput {...props} renderToken={renderToken} />
</TokenInputSizeContext>
);
}
type TokenInputEditorProps = ComponentProps<typeof SDKTokenInputEditor> &
VariantProps<typeof tokenInputEditorVariants> & {
variant?: keyof typeof textFieldSurfaces;
size?: StandardControlSize;
};
function TokenInputEditor({
variant = 'filled',
size,
className,
...props
}: TokenInputEditorProps) {
const contextSize = useContext(TokenInputSizeContext);
const resolvedSize = size ?? contextSize;
return (
<SDKTokenInputEditor
{...props}
data-variant={variant}
data-size={resolvedSize}
className={partClass(
tokenInputEditorVariants({ size: resolvedSize }),
textFieldSurfaces[variant],
variant === 'underline' && textFieldUnderlineMotion,
className,
)}
/>
);
}
type TokenInputTokenProps = ComponentProps<typeof SDKTokenInputToken> &
Pick<BadgeProps, 'variant' | 'status'> & {
icon?: ReactNode;
};
function TokenInputToken({
variant = 'solid',
status = 'neutral',
className,
children,
icon,
...props
}: TokenInputTokenProps) {
const size = useContext(TokenInputSizeContext);
return (
<SDKTokenInputToken
{...props}
data-variant={variant}
data-status={status}
data-size={size}
className={partClass(
badgeVariants({ status, variant, size }),
'group/token-chip relative m-px overflow-visible align-baseline [@media(hover:none)]:pe-5 data-pending:opacity-60 data-unresolved:border-destructive/50 motion-safe:animate-in motion-safe:fade-in motion-safe:blur-in-[3px] motion-safe:zoom-in-95 motion-safe:duration-180 motion-safe:ease-out',
className,
)}
>
{icon == null
? children
: (state) => (
<>
<span
aria-hidden="true"
className="inline-flex size-[1em] shrink-0 items-center justify-center [&>svg]:size-full"
>
{icon}
</span>
{typeof children === 'function' ? children(state) : children}
</>
)}
</SDKTokenInputToken>
);
}
function TokenInputTokenRemove({
className,
children,
'aria-label': ariaLabel,
...props
}: ComponentProps<typeof SDKTokenInputTokenRemove>) {
return (
<SDKTokenInputTokenRemove
{...props}
aria-label={ariaLabel ?? (children == null ? 'Remove token' : undefined)}
className={partClass(
`pointer-events-none active:scale-90 absolute inset-e-0.5 z-10 inline-grid size-4 cursor-pointer place-items-center rounded-sm border border-border bg-background text-foreground opacity-0 transition-opacity duration-150 group-hover/token-chip:pointer-events-auto group-hover/token-chip:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100 data-disabled:hidden data-readonly:hidden motion-reduce:transition-none ${focusRing}`,
className,
)}
>
{children ?? <X aria-hidden="true" className="size-2.5" />}
</SDKTokenInputTokenRemove>
);
}
function TriggerMenuContent({
children,
className,
ref,
...props
}: ComponentProps<typeof SDKTriggerMenuContent>) {
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector: '[data-slot="trigger-menu-item"]:not([data-disabled])',
activeAttribute: 'data-highlighted',
});
const contentRef = mergeProps({ ref: containerRef }, { ref }).ref;
return (
<SDKTriggerMenuContent
{...props}
ref={contentRef}
className={partClass(
'relative isolate z-50 min-w-44 origin-(--transform-origin) overflow-y-auto overscroll-contain rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-sm [scrollbar-width:thin] [scrollbar-color:var(--border)_transparent] transition-[opacity,scale,filter] duration-200 ease-out data-starting-style:opacity-0 data-ending-style:opacity-0 motion-safe:data-starting-style:scale-95 motion-safe:data-starting-style:blur-[3px] motion-safe:data-ending-style:scale-[0.98] motion-safe:data-ending-style:blur-[3px] motion-reduce:transition-none [&_[data-slot=trigger-menu-item]]:relative [&_[data-slot=trigger-menu-item]]:z-10',
className,
)}
>
{(state) => (
<>
<span
aria-hidden="true"
data-slot="token-input-suggestion-highlight"
className={slidingHighlight}
style={highlightStyle}
/>
{typeof children === 'function' ? children(state) : children}
</>
)}
</SDKTriggerMenuContent>
);
}
function TriggerMenuList({ className, ...props }: ComponentProps<typeof SDKTriggerMenuList>) {
return (
<SDKTriggerMenuList
{...props}
className={partClass(
'scroll-fade grid max-h-60 min-w-0 gap-1 overflow-y-auto overscroll-contain [scrollbar-width:thin] [scrollbar-color:var(--border)_transparent]',
className,
)}
/>
);
}
function TriggerMenuEmpty({ className, ...props }: ComponentProps<typeof SDKTriggerMenuEmpty>) {
return (
<SDKTriggerMenuEmpty
{...props}
className={partClass('px-3 py-2 text-center text-sm text-muted-foreground', className)}
/>
);
}
function TriggerMenuGroup({ className, ...props }: ComponentProps<typeof SDKTriggerMenuGroup>) {
return <SDKTriggerMenuGroup {...props} className={partClass('grid gap-1', className)} />;
}
function TriggerMenuGroupLabel({
className,
...props
}: ComponentProps<typeof SDKTriggerMenuGroupLabel>) {
return (
<SDKTriggerMenuGroupLabel
{...props}
className={partClass('px-2 py-1 text-sm font-medium text-muted-foreground', className)}
/>
);
}
function TriggerMenuHint({ className, ...props }: ComponentProps<typeof SDKTriggerMenuHint>) {
return (
<SDKTriggerMenuHint
{...props}
className={partClass('pointer-events-none text-muted-foreground', className)}
/>
);
}
function TriggerMenuSeparator({
className,
...props
}: ComponentProps<typeof SDKTriggerMenuSeparator>) {
return (
<SDKTriggerMenuSeparator {...props} render={<Separator className={cn('my-1', className)} />} />
);
}
function TriggerMenuStatus({ className, ...props }: ComponentProps<typeof SDKTriggerMenuStatus>) {
return <SDKTriggerMenuStatus {...props} className={cn('sr-only', className)} />;
}
type TriggerMenuItemProps<T = string> = ComponentProps<typeof SDKTriggerMenuItem<T>> & {
icon?: ReactNode;
};
function TriggerMenuItem<T = string>({
children,
icon,
className,
...props
}: TriggerMenuItemProps<T>) {
return (
<SDKTriggerMenuItem<T>
{...props}
className={partClass(
`flex cursor-pointer touch-manipulation items-center gap-2 ${concentricRadius} px-2 py-1.5 ${controlTextSizes.md} [@media(pointer:coarse)]:min-h-11 data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:cursor-default data-disabled:opacity-50`,
className,
)}
>
{(state) => (
<>
{icon != null && (
<TriggerMenuItemIcon className="size-4 shrink-0 [&>svg]:size-full">
{icon}
</TriggerMenuItemIcon>
)}
{typeof children === 'function' ? children(state) : (children ?? props.label)}
</>
)}
</SDKTriggerMenuItem>
);
}
export {
createTokenInputController,
defaultCodec,
fromText,
type Token,
type TokenCodec,
TokenInput,
TokenInputEditor,
type TokenInputEditorProps,
type TokenInputOptions,
type TokenInputProps,
TokenInputToken,
TokenInputTokenRemove,
type TokenInputValue,
TriggerMenu,
TriggerMenuContent,
type TriggerMenuDataItem,
TriggerMenuEmpty,
TriggerMenuGroup,
TriggerMenuGroupLabel,
TriggerMenuHint,
TriggerMenuItem,
TriggerMenuItemIcon,
TriggerMenuList,
TriggerMenuSeparator,
TriggerMenuStatus,
toLabel,
toText,
};
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 { Separator as SDKSeparator } from '@ui-sdk/react/separator';
import type { ComponentProps } from 'react';
import { partClass } from '@/lib/devvarena-ui';
type SeparatorProps = ComponentProps<typeof SDKSeparator> & { variant?: 'fade' | 'solid' };
/** Theme-derived fading rule built on `@ui-sdk/react/separator`. */
function Separator({
orientation = 'horizontal',
decorative = true,
variant = 'fade',
className,
...props
}: SeparatorProps) {
return (
<SDKSeparator
{...props}
orientation={orientation}
decorative={decorative}
data-variant={variant}
className={partClass(
'pointer-events-none shrink-0',
orientation === 'horizontal' ? 'h-px w-full' : 'w-px self-stretch',
variant === 'solid'
? 'bg-[var(--separator-color,var(--border))]'
: orientation === 'horizontal'
? 'bg-[linear-gradient(to_right,transparent,var(--separator-color,var(--border))_18%,var(--separator-color,var(--border))_82%,transparent)]'
: 'bg-[linear-gradient(to_bottom,transparent,var(--separator-color,var(--border))_18%,var(--separator-color,var(--border))_82%,transparent)]',
className,
)}
/>
);
}
export type { SeparatorProps };
export { Separator };
'use client';
import { type CSSProperties, useCallback, useMemo } from 'react';
export type UseSlidingHighlightOptions = {
/** Mark eligible descendants with this selector. */
itemSelector?: string;
/** Resolve a row when the primitive focuses its parent instead of the row itself. */
focusItemSelector?: string;
disabled?: boolean;
/** Follow a primitive-owned state attribute on eligible items. */
activeAttribute?: string;
};
function highlightProperties(activeAttribute?: string) {
const prefix = activeAttribute ? `--sliding-highlight-${activeAttribute}` : '--sliding-highlight';
return {
left: `${prefix}-left`,
top: `${prefix}-top`,
width: `${prefix}-width`,
height: `${prefix}-height`,
opacity: `${prefix}-opacity`,
};
}
type Clipper = { el: Element; x: boolean; y: boolean };
/** Decorative hover/focus feedback; zero React state or useEffect. */
export function useSlidingHighlight({
itemSelector = '[data-highlight-item]',
focusItemSelector,
disabled = false,
activeAttribute,
}: UseSlidingHighlightOptions = {}) {
const properties = useMemo(() => highlightProperties(activeAttribute), [activeAttribute]);
const highlightStyle = useMemo<CSSProperties>(
() => ({
position: 'absolute',
top: 0,
left: 0,
width: `var(${properties.width}, 0px)`,
height: `var(${properties.height}, 0px)`,
transform: `translate3d(var(${properties.left}, 0px), var(${properties.top}, 0px), 0)`,
opacity: `var(${properties.opacity}, 0)`,
pointerEvents: 'none',
}),
[properties],
);
const containerRef = useCallback(
(container: HTMLElement | null) => {
if (!container || disabled) return;
const activeSelector = activeAttribute ? `${itemSelector}[${activeAttribute}]` : null;
const style = container.style;
let hovered: HTMLElement | null = null;
let focused: HTMLElement | null = null;
let observed: HTMLElement | null = null;
let clippers: Clipper[] = [];
let visible: boolean | null = null;
let pLeft = NaN;
let pTop = NaN;
let pWidth = NaN;
let pHeight = NaN;
const findItem = (target: EventTarget | null) => {
const item = target instanceof Element ? target.closest<HTMLElement>(itemSelector) : null;
return item && item !== container && container.contains(item) ? item : null;
};
// Programmatic/pointer focus must not pin a popover's initially focused row.
const findFocusedItem = (target: EventTarget | null) => {
if (!(target instanceof Element) || !target.matches(':focus-visible')) return null;
const inner = focusItemSelector ? target.querySelector(focusItemSelector) : null;
return findItem(inner ?? target);
};
const setVisible = (next: boolean) => {
if (visible === next) return;
visible = next;
style.setProperty(properties.opacity, next ? '1' : '0');
};
// Runs only when the tracked item changes, so getComputedStyle is not called per frame.
const track = (item: HTMLElement | null) => {
if (observed === item) return;
if (observed) resize?.unobserve(observed);
if (item) resize?.observe(item);
observed = item;
clippers = [];
for (let el = item?.parentElement; el && el !== container; el = el.parentElement) {
const { overflowX, overflowY } = getComputedStyle(el);
const x = overflowX !== 'visible';
const y = overflowY !== 'visible';
if (x || y) clippers.push({ el, x, y });
}
};
const measure = () => {
const item = activeSelector
? container.querySelector<HTMLElement>(activeSelector)
: focused?.matches(itemSelector) && container.contains(focused)
? focused
: hovered;
const valid = item && container.contains(item) && item.matches(itemSelector);
track(valid ? item : null);
if (!valid) return setVisible(false);
const outer = container.getBoundingClientRect();
const inner = item.getBoundingClientRect();
if (!outer.width || !outer.height || !inner.width || !inner.height) {
return setVisible(false);
}
let { left: cLeft, top: cTop, right: cRight, bottom: cBottom } = inner;
for (const { el, x, y } of clippers) {
const r = el.getBoundingClientRect();
if (x) {
cLeft = Math.max(cLeft, r.left);
cRight = Math.min(cRight, r.right);
}
if (y) {
cTop = Math.max(cTop, r.top);
cBottom = Math.min(cBottom, r.bottom);
}
}
if (cRight <= cLeft || cBottom <= cTop) return setVisible(false);
const scaleX = container.offsetWidth / outer.width;
const scaleY = container.offsetHeight / outer.height;
const left = (cLeft - outer.left) * scaleX - container.clientLeft + container.scrollLeft;
const top = (cTop - outer.top) * scaleY - container.clientTop + container.scrollTop;
const width = (cRight - cLeft) * scaleX;
const height = (cBottom - cTop) * scaleY;
if (left !== pLeft) {
pLeft = left;
style.setProperty(properties.left, `${left}px`);
}
if (top !== pTop) {
pTop = top;
style.setProperty(properties.top, `${top}px`);
}
if (width !== pWidth) {
pWidth = width;
style.setProperty(properties.width, `${width}px`);
}
if (height !== pHeight) {
pHeight = height;
style.setProperty(properties.height, `${height}px`);
}
setVisible(true);
};
const resize = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
const mutation = new MutationObserver(measure);
const onPointer = (e: PointerEvent) => {
if (e.pointerType === 'touch') return;
const next = findItem(e.type === 'pointerout' ? e.relatedTarget : e.target);
if (next === hovered) return;
hovered = next;
measure();
};
const onPointerLeave = (e: PointerEvent) => {
if (e.pointerType === 'touch') return;
hovered = null;
measure();
};
const onFocus = (e: FocusEvent) => {
focused = findFocusedItem(e.type === 'focusin' ? e.target : e.relatedTarget);
measure();
};
resize?.observe(container);
mutation.observe(container, {
childList: true,
subtree: true,
...(activeAttribute && {
attributeFilter: [activeAttribute, 'data-disabled', 'aria-disabled'],
}),
});
container.addEventListener('scroll', measure, { capture: true, passive: true });
if (!activeSelector) {
focused = findFocusedItem(document.activeElement);
container.addEventListener('pointerover', onPointer);
container.addEventListener('pointermove', onPointer);
container.addEventListener('pointerout', onPointer);
container.addEventListener('pointerleave', onPointerLeave);
container.addEventListener('pointercancel', onPointerLeave);
container.addEventListener('focusin', onFocus);
container.addEventListener('focusout', onFocus);
}
measure();
return () => {
resize?.disconnect();
mutation.disconnect();
container.removeEventListener('scroll', measure, true);
if (!activeSelector) {
container.removeEventListener('pointerover', onPointer);
container.removeEventListener('pointermove', onPointer);
container.removeEventListener('pointerout', onPointer);
container.removeEventListener('pointerleave', onPointerLeave);
container.removeEventListener('pointercancel', onPointerLeave);
container.removeEventListener('focusin', onFocus);
container.removeEventListener('focusout', onFocus);
}
for (const v of Object.values(properties)) style.removeProperty(v);
};
},
[itemSelector, focusItemSelector, disabled, activeAttribute, properties],
);
return { containerRef, highlightStyle };
}
import { cn } from '@/lib/utils';
type ClassValue = string | false | null | undefined;
type PartClassValue<State> = ClassValue | ((state: State) => ClassValue);
/** Composes static class names and UI-SDK state class functions into a single `className` prop. */
export function partClass<State>(...parts: PartClassValue<State>[]) {
if (parts.some((part) => typeof part === 'function')) {
return (state: State) =>
cn(...parts.map((part) => (typeof part === 'function' ? part(state) : part)));
}
return cn(...(parts as ClassValue[]));
}
export const surfacePadding = 'p-1 [--surface-padding:1.5rem] [--concentric-inset:0.25rem]';
export const surfaceRegionInset = 'p-[calc(var(--surface-padding,1rem)-0.5rem)]';
export const surfaceHeaderRadius = 'rounded-t-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
export const surfaceFooterRadius = 'rounded-b-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
/** Concentric inner radius (`outer - inset`); set `[--concentric-inset:0.125rem]` on `p-0.5` rails (defaults to `0.25rem` for `p-1`). */
export const concentricRadius =
'rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))]';
export const surfaceBodyPadding =
'py-[max(0px,calc(var(--surface-padding,1rem)-1rem))] has-[>[data-slot=list]:not([data-variant=plain])]:p-0 has-[>[data-slot=list-items-container]]:p-0';
export type StandardControlSize = 'xs' | 'sm' | 'md' | 'lg';
/** Standard control heights (`28px / 32px / 40px / 48px`) for buttons, inputs, selects, tabs, and sliders. */
export const controlHeights = {
xs: 'h-7',
sm: 'h-8',
md: 'h-10',
lg: 'h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard minimum control heights (`28px / 32px / 40px / 48px`) for expandable controls and menu items. */
export const controlMinHeights = {
xs: 'min-h-7',
sm: 'min-h-8',
md: 'min-h-10',
lg: 'min-h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard control text sizes (`xs / xs / sm / base`) paired with `StandardControlSize`. */
export const controlTextSizes = {
xs: 'text-xs',
sm: 'text-xs',
md: 'text-sm',
lg: 'text-base',
} as const satisfies Record<StandardControlSize, string>;
/** Compact control heights (`1.25rem / 1.3rem / 1.625rem / 1.75rem`), one step smaller than standard, for switches and compact controls. */
export const compactControlHeights = {
xs: 'h-[1.3rem]',
sm: 'h-[1.4rem]',
md: 'h-[1.5rem]',
lg: 'h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Compact minimum control heights (`1rem / 1.25rem / 1.5rem / 1.75rem`) for badges and tooltips. */
export const compactControlMinHeights = {
xs: 'min-h-[1.3rem]',
sm: 'min-h-[1.4rem]',
md: 'min-h-[1.5rem]',
lg: 'min-h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Universal keyboard focus + invalid ring/border styles shared across controls. */
export const focusRing =
'touch-manipulation outline-none focus-visible:border-ring/30 transition-ring focus-visible:ring-3 focus-visible:ring-ring/15 focus-visible:brightness-[0.97] dark:focus-visible:brightness-[1.15] has-[:focus-visible]:border-ring/30 has-[:focus-visible]:ring-3 has-[:focus-visible]:ring-ring/15 has-[:focus-visible]:brightness-[0.97] dark:has-[:focus-visible]:brightness-[1.15] data-active:border-ring/30 data-active:ring-3 data-active:ring-ring/15 data-active:brightness-[0.97] dark:data-active:brightness-[1.15] data-open:border-ring/30 data-open:ring-3 data-open:ring-ring/15 data-open:brightness-[0.97] dark:data-open:brightness-[1.15] data-disabled:cursor-not-allowed data-disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/25 data-invalid:border-destructive data-invalid:ring-3 data-invalid:ring-destructive/25 has-[[data-invalid]]:border-destructive has-[[data-invalid]]:ring-3 has-[[data-invalid]]:ring-destructive/25 group-aria-invalid/control:border-destructive group-aria-invalid/control:ring-3 group-aria-invalid/control:ring-destructive/25 group-data-invalid/control:border-destructive group-data-invalid/control:ring-3 group-data-invalid/control:ring-destructive/25 group-has-[input[aria-invalid=true]]/control:border-destructive group-has-[input[aria-invalid=true]]/control:ring-3 group-has-[input[aria-invalid=true]]/control:ring-destructive/25 hover:brightness-[0.97] dark:hover:brightness-[1.15]';
/** Shared sliding highlight indicator base (pointer-safe, concentric inner radius inside rounded-lg containers, 200ms transition). */
export const slidingHighlight =
'pointer-events-none -z-10 rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))] bg-primary/10 [clip-path:inset(0px_round_max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem))))] transition-[transform,width,height,opacity] duration-200 ease-out motion-reduce:transition-none';
export const textFieldSurfaces = {
filled: 'border-input bg-card text-card-foreground',
outline: 'border-input bg-transparent text-foreground dark:bg-transparent',
ghost: 'border-transparent bg-muted text-foreground shadow-none',
underline:
'rounded-none border-0 border-b-2 border-input bg-transparent px-0 text-foreground shadow-none focus-visible:border-ring focus-visible:ring-0 aria-invalid:ring-0 data-invalid:ring-0 dark:bg-transparent',
} as const;
export const textFieldUnderlineMotion =
'border-transparent! bg-origin-border bg-bottom bg-no-repeat [--underline-color:var(--primary)] [background-image:linear-gradient(var(--underline-color),var(--underline-color)),linear-gradient(var(--input),var(--input))] [background-size:0%_2px,100%_2px] focus:[background-size:100%_2px,100%_2px] aria-invalid:[--underline-color:var(--destructive)] data-invalid:[--underline-color:var(--destructive)] transition-[border-color,background-color,box-shadow,filter,background-size] duration-200 motion-reduce:transition-none';
/** Generic balanced icon & floating-label layout tokens shared across all text-field sizes. */
export const textFieldLayout = {
icon: 'size-4',
iconStart: 'start-3',
iconEnd: 'end-3',
padStart: 'ps-9',
padEnd: 'pe-9',
underlinePadStart: 'ps-7',
underlinePadEnd: 'pe-7',
floatingStart: 'start-2.5',
floatingWithIcon: 'start-8',
floatingUnderlineIcon: 'start-6',
} as const;
export const textFieldLabelSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
/** Clamps per-grapheme wave delay (ms) so total staggering stays within 300ms. */
export function clampWaveDelay(waveDelay: number, count: number): number {
return Math.max(
0,
Math.min(Number.isFinite(waveDelay) ? waveDelay : 24, 80, 300 / Math.max(1, count - 1)),
);
}
/** Shared scale/color transition for floating labels inside a `group/field` wrapper. */
export const textFieldLabelMotion =
'inline-block origin-left backdrop-blur-xs transition-[scale,color] duration-200 ease-out group-has-[input:focus]/field:scale-85 group-has-[input:not(:placeholder-shown)]/field:scale-85 rtl:origin-right motion-reduce:transition-none';
/** Resolves start/end padding for a text field when a leading or trailing icon is present. */
export function getTextFieldIconPadding(iconPosition: 'start' | 'end', underline: boolean): string {
if (iconPosition === 'start') {
return underline ? textFieldLayout.underlinePadStart : textFieldLayout.padStart;
}
return underline ? textFieldLayout.underlinePadEnd : textFieldLayout.padEnd;
}
/** Shared per-grapheme ripple transition for wave labels inside a `group/field` wrapper. */
export const textFieldWaveMotion =
'inline-block origin-left backdrop-blur-xs transition-[translate,scale,color] duration-200 ease-out group-has-[input:focus]/field:-translate-y-5 group-has-[input:focus]/field:scale-85 group-has-[input:focus]/field:text-primary group-has-[input:not(:placeholder-shown)]/field:-translate-y-5 group-has-[input:not(:placeholder-shown)]/field:scale-85 group-has-[input[aria-invalid=true]]/field:text-destructive rtl:origin-right motion-reduce:transition-none';