Browse folders, pages, and other nested items in an expandable list.
Project files
Sizes
From file paths
Multiple selection
0 selected
Cascading checkboxes
Navigation links
Purpose
A tree shows related items in branches people can expand and collapse, like folders in a file browser or sections in a sidebar.
Parts & Composition
Put each TreeItemLabel inside its TreeItem. Add a TreeGroup after the label to make a branch, and place optional indicators and checkboxes inside the label. For a data-driven tree, pass items or paths and let UI SDK render the rows.
| Part | Role |
|---|---|
Tree | Named root that manages navigation, selection, and expanded branches. |
TreeItem | Leaf or branch identified by a unique value. |
TreeItemLabel | Visible row and accessible text. Use render to make it a link. |
TreeItemIndicator | Branch toggle with a default chevron. |
TreeItemCheckbox | Uses the library Checkbox’s surface and mark while UI SDK Tree owns checking and mixed state. |
TreeGroup | Nested items under a branch. |
TreeItems | SDK renderer for a collection of items. |
API & Props
| Prop / part | Purpose |
|---|---|
items / paths | Supply the full hierarchy or a list of file paths. Keep the collection available when rendering your own rows. |
mode / value / defaultValue / onValueChange | Choose none, single, or multiple selection. Single uses a string or null. Multiple uses an array of strings. |
activation / expandOnPress | Choose when focus selects an item. Clicking a branch row or its chevron toggles expansion. Set expandOnPress={false} to make row clicks select without toggling the branch. |
expanded / defaultExpanded / onExpandedChange | Control or initialize branch expansion independently of selection. |
checkable / checked / defaultChecked / onCheckedChange | Enable and manage checkbox state separately from selected rows. |
checkStrategy | Report checked leaves, outermost fully checked branches, every fully checked item, or independent checks. |
current | Identifies the active page and opens its ancestor branches. |
onAction / pendingAnnouncement | Handle item activation. A returned Promise gives the item a pending state. |
loadChildren / onHighlight | Load branches on demand or integrate externally managed scrolling for a virtual list. |
disabled / focusableWhenDisabled | Disable operations and choose whether disabled rows can receive focus. |
keepMounted / hiddenUntilFound | Preserve collapsed markup or let browser Find reveal a group. Also configurable per group. |
size | the library row density: xs / sm / md / lg. |
slidingHighlight | Defaults to true. Set false for a static hover and keyboard focus highlight. |
TreeItem.value / branch / label / disabled | Unique item ID, explicit branch flag, optional search label, and per-item availability. |
controller | Use createTreeController() for programmatic expansion, selection, checking, and focus. |
Expansion, selection, and checkboxes are independent. Choose controlled or uncontrolled state for each. UI SDK handles cascading checks and mixed state. If selected or checked values belong in a form, serialize them in the app.
Theming, Layout & Responsiveness
Rows use the library’s muted and accent tokens for selected and focused states. Style visible rows through tree-label, so styling a parent does not also highlight its descendants.
Indentation uses the SDK’s depth variable, --tree-level, and follows the reading direction. Rows use the the library minimum height scale of 28, 32, 40, or 48px and can grow for wrapped labels.
Motion & Accessibility
The shared highlight follows hover and keyboard focus. The branch indicator rotates and groups expand or collapse using the SDK’s measured height. Both respect reduced motion.
Give the tree an accessible name and each row a clear label. UI SDK provides the tree roles, a single Tab stop, arrow navigation, typeahead, and the expanded and checked states. Enter activates a row or follows its link. Space checks the focused item in checkable mode.
Guidance for Coding Agents
Install this component using the command in the Install tab, then read this Info page before composing it.
Start from the closest Preview → Usage example. Use items or paths for a known collection, or compose the SDK parts for custom rows. Give each item a stable value unique across the tree. Keep expansion, selected rows, checked values, and the current route separate.
Use the UI SDK Tree reference for controller methods, keyboard details, lazy loading, virtualization, rendering, and change callbacks. Keep fetching, authorization, and persistence in the app.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/tree'use client';
import {
Tree as SDKTree,
TreeItemCheckbox as SDKTreeItemCheckbox,
TreeItemIndicator as SDKTreeItemIndicator,
TreeItemLabel as SDKTreeItemLabel,
type TreeProps as SDKTreeProps,
TreeGroup,
TreeItem,
type TreeItemData,
type TreeMode,
treeFromPaths,
} from '@ui-sdk/react/tree';
import { cva } from 'class-variance-authority';
import { ChevronRight } from 'lucide-react';
import { type ComponentProps, createContext, useContext, useMemo } from 'react';
import { CheckboxMark, checkboxSurface } from '@/components/devvarena-ui/checkbox';
import { useSlidingHighlight } from '@/hooks/use-sliding-highlight';
import {
compactControlHeights,
concentricRadius,
controlMinHeights,
controlTextSizes,
partClass,
type StandardControlSize,
slidingHighlight,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
const TreeContext = createContext<{ size: StandardControlSize; checkable: boolean }>({
size: 'md',
checkable: false,
});
const treeLabelVariants = cva('', {
variants: {
size: {
xs: `${controlMinHeights.xs} ${controlTextSizes.xs}`,
sm: `${controlMinHeights.sm} ${controlTextSizes.sm}`,
md: `${controlMinHeights.md} ${controlTextSizes.md}`,
lg: `${controlMinHeights.lg} ${controlTextSizes.lg}`,
} satisfies Record<StandardControlSize, string>,
},
});
const rowStates =
'[&_[data-slot=tree-item]]:outline-none [&_[data-slot=tree-label]:not([data-disabled])]:cursor-pointer [&_[data-slot=tree-label][data-disabled]]:cursor-not-allowed [&_[data-slot=tree-label][data-disabled]]:opacity-50 [&_[data-slot=tree-label]:is([data-selected],[data-current])]:bg-muted/45 [&_[data-slot=tree-label]:is([data-selected],[data-current])]:font-medium [&_[data-slot=tree-item]:focus-visible>[data-slot=tree-label]]:text-accent-foreground [&_[data-slot=tree-item]:focus-visible>[data-slot=tree-label]]:ring-2 [&_[data-slot=tree-item]:focus-visible>[data-slot=tree-label]]:ring-ring/30 [&_[data-slot=tree-item]:focus-visible>[data-slot=tree-label]]:ring-inset [&_[data-slot=tree-label][data-pending]]:opacity-65';
const groups =
'[&_[data-slot=tree-group]]:h-(--tree-group-height) [&_[data-slot=tree-group]]:overflow-hidden [&_[data-slot=tree-group]]:transition-[height] [&_[data-slot=tree-group]]:duration-150 [&_[data-slot=tree-group]]:ease-out [&_[data-slot=tree-group]:is([data-starting-style],[data-ending-style])]:h-0 motion-reduce:[&_[data-slot=tree-group]]:transition-none';
type TreeProps<Mode extends TreeMode = 'single'> = SDKTreeProps<Mode> & {
size?: StandardControlSize;
slidingHighlight?: boolean;
};
function Tree<Mode extends TreeMode = 'single'>({
size = 'md',
slidingHighlight: animatedHighlight = true,
className,
children,
...props
}: TreeProps<Mode>) {
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector:
'[data-slot="tree-label"]:not([data-disabled], :has([data-slot="tree-indicator"]:hover))',
focusItemSelector: ':scope > [data-slot="tree-label"]',
disabled: !animatedHighlight,
});
const checkable = Boolean(props.checkable);
const contextValue = useMemo(() => ({ size, checkable }), [size, checkable]);
const resolvedItems = useMemo(() => {
if (children != null) return undefined;
return props.items ?? (props.paths ? treeFromPaths(props.paths) : undefined);
}, [children, props.items, props.paths]);
return (
<TreeContext value={contextValue}>
<div
ref={containerRef}
className={cn(
'relative isolate w-full min-w-0',
typeof className === 'string' && className,
)}
>
{animatedHighlight && (
<span aria-hidden="true" style={highlightStyle} className={cn(slidingHighlight, 'z-0')} />
)}
<SDKTree<Mode>
{...props}
data-size={size}
className={partClass(
'w-full min-w-0 text-foreground',
rowStates,
animatedHighlight
? '[&_[data-slot=tree-label]]:relative [&_[data-slot=tree-label]]:z-10'
: '[&_[data-slot=tree-label]:not([data-disabled],:has([data-slot=tree-indicator]:hover)):hover]:bg-accent [&_[data-slot=tree-item]:focus-visible>[data-slot=tree-label]]:bg-accent',
groups,
typeof className === 'function' ? className : undefined,
)}
>
{children ?? (resolvedItems ? <TreeItems items={resolvedItems} /> : undefined)}
</SDKTree>
</div>
</TreeContext>
);
}
function TreeItemLabel({ className, ...props }: ComponentProps<typeof SDKTreeItemLabel>) {
const { size } = useContext(TreeContext);
return (
<SDKTreeItemLabel
{...props}
data-size={size}
className={partClass(
`flex min-w-0 touch-manipulation items-center gap-2 ${concentricRadius} py-1 pe-2 ps-[calc(0.5rem+(var(--tree-level,1)-1)*1rem)] transition-colors wrap-anywhere motion-reduce:transition-none [&:not([data-branch])]:ps-[calc(2rem+(var(--tree-level,1)-1)*1rem)] [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-muted-foreground`,
treeLabelVariants({ size }),
className,
)}
/>
);
}
function TreeItems({ items }: { items: TreeItemData[] }) {
const { checkable } = useContext(TreeContext);
return items.map((item) => (
<TreeItem
key={item.value}
value={item.value}
branch={item.children !== undefined}
disabled={item.disabled}
>
<TreeItemLabel
// biome-ignore lint/a11y/useAnchorContent: children are injected by TreeItemLabel's render prop
render={item.href ? <a href={item.href} /> : undefined}
>
{item.children !== undefined && <TreeItemIndicator />}
{checkable && <TreeItemCheckbox />}
{item.label}
</TreeItemLabel>
{item.children && (
<TreeGroup>
<TreeItems items={item.children} />
</TreeGroup>
)}
</TreeItem>
));
}
function TreeItemIndicator({
children,
className,
...props
}: ComponentProps<typeof SDKTreeItemIndicator>) {
return (
<SDKTreeItemIndicator
{...props}
className={partClass(
'pointer-events-auto grid size-4 shrink-0 place-items-center rounded-sm text-muted-foreground hover:not-data-disabled:bg-accent hover:not-data-disabled:text-accent-foreground [&>svg]:pointer-events-none [&>svg]:size-3.5 [&>svg]:transition-transform [&>svg]:duration-150 motion-reduce:[&>svg]:transition-none data-expanded:[&>svg]:rotate-90 rtl:not-data-expanded:[&>svg]:rotate-180',
className,
)}
>
{children ?? <ChevronRight aria-hidden="true" />}
</SDKTreeItemIndicator>
);
}
function TreeItemCheckbox({
children,
className,
...props
}: ComponentProps<typeof SDKTreeItemCheckbox>) {
return (
<SDKTreeItemCheckbox
{...props}
className={(state) =>
cn(
'group/checkbox-indicator inline-grid shrink-0 place-items-center rounded-sm border bg-clip-padding [&>svg]:size-3.5',
compactControlHeights.xs,
'aspect-square',
checkboxSurface(state.checked !== false),
typeof className === 'function' ? className(state) : className,
)
}
>
{(state) => {
if (typeof children === 'function') return children(state);
if (children != null) return children;
return state.checked === false ? null : (
<CheckboxMark mixed={state.checked === 'indeterminate'} />
);
}}
</SDKTreeItemCheckbox>
);
}
export type {
TreeActionDetails,
TreeCheckStrategy,
TreeController,
TreeItemData,
TreeMode,
TreeOptions,
TreeRow,
TreeValue,
} from '@ui-sdk/react/tree';
export {
createTreeController,
TreeGroup,
TreeItem,
toggleTreeChecked,
treeCheckedStates,
treeFromPaths,
visibleTreeRows,
} from '@ui-sdk/react/tree';
export type { TreeProps };
export { Tree, TreeItemCheckbox, TreeItemIndicator, TreeItemLabel, TreeItems };
'use client';
import type {
CheckboxChangeOptions,
CheckboxCheckedChangeReason,
CheckboxController,
CheckboxGroupChangeOptions,
CheckboxGroupController,
CheckboxGroupOptions,
CheckboxGroupState,
CheckboxGroupValueChangeReason,
CheckboxIndicatorState,
CheckboxOptions,
CheckboxState,
CheckedState,
} from '@ui-sdk/core/checkbox';
import {
createCheckboxController,
createCheckboxGroupController,
Checkbox as SDKCheckbox,
CheckboxGroup as SDKCheckboxGroup,
CheckboxIndicator as SDKCheckboxIndicator,
} from '@ui-sdk/react/checkbox';
import { cva } from 'class-variance-authority';
import type { ComponentProps } from 'react';
import { buttonSurfaces } from '@/components/devvarena-ui/button';
import {
compactControlHeights,
focusRing,
partClass,
type StandardControlSize,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
function checkboxSurface(checked: boolean) {
return checked ? buttonSurfaces.primary : cn(buttonSurfaces.secondary, 'border-ring/40');
}
function CheckboxMark({ mixed, animated = true }: { mixed?: boolean; animated?: boolean }) {
if (mixed) return <span className="h-0.5 w-2/3 rounded-full bg-current" />;
return (
<svg aria-hidden="true" width="1em" height="1em" viewBox="0 0 24 24">
<path
fill="none"
stroke="currentColor"
strokeDasharray={24}
strokeDashoffset={0}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2.9}
d="M5 11L11 17L21 7"
className={cn(
animated &&
'motion-safe:transition-[stroke-dashoffset] motion-safe:duration-300 motion-safe:group-data-unchecked/checkbox-indicator:[stroke-dashoffset:24] motion-safe:starting:[stroke-dashoffset:24]',
)}
/>
</svg>
);
}
const checkboxStyles = cva(
'relative inline-grid aspect-square shrink-0 cursor-pointer place-items-center rounded-sm border bg-clip-padding align-middle transition-[background-color,border-color,box-shadow,filter,scale] duration-150 [@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 data-disabled:cursor-not-allowed data-disabled:opacity-50 data-readonly:cursor-default motion-safe:active:not-data-disabled:not-data-readonly:scale-95 motion-reduce:transition-none',
{
variants: {
size: {
xs: [compactControlHeights.xs, '[--checkbox-icon-size:0.8125rem]'],
sm: [compactControlHeights.sm, '[--checkbox-icon-size:0.9375rem]'],
md: [compactControlHeights.md, '[--checkbox-icon-size:1.0625rem]'],
lg: [compactControlHeights.lg, '[--checkbox-icon-size:1.25rem]'],
},
},
},
);
type CheckboxGroupProps<T extends string = string> = ComponentProps<typeof SDKCheckboxGroup<T>>;
function CheckboxGroup<T extends string = string>({ className, ...props }: CheckboxGroupProps<T>) {
return <SDKCheckboxGroup<T> {...props} className={partClass('group/control', className)} />;
}
type CheckboxProps = ComponentProps<typeof SDKCheckbox> & {
size?: StandardControlSize;
};
function Checkbox({ size = 'md', className, children, ...props }: CheckboxProps) {
const hasRender = props.render !== undefined;
return (
<SDKCheckbox
{...props}
data-size={size}
className={partClass(
!hasRender && checkboxStyles({ size }),
!hasRender && focusRing,
hasRender
? undefined
: (state: CheckboxState) => checkboxSurface(state.checked || state.indeterminate),
className,
)}
>
{children === undefined && !hasRender ? defaultIndicator : children}
</SDKCheckbox>
);
}
type CheckboxIndicatorProps = ComponentProps<typeof SDKCheckboxIndicator> & {
animated?: boolean;
};
function CheckboxIndicator({
animated = true,
children,
className,
...props
}: CheckboxIndicatorProps) {
return (
<SDKCheckboxIndicator
aria-hidden="true"
{...props}
className={partClass(
'group/checkbox-indicator pointer-events-none grid size-[var(--checkbox-icon-size,1.0625rem)] place-items-center data-unchecked:opacity-0 [&>svg]:size-full',
animated &&
'transition-[opacity,scale] duration-150 data-starting-style:scale-75 data-starting-style:opacity-0 data-ending-style:scale-75 data-ending-style:opacity-0 motion-reduce:transition-none',
className,
)}
>
{(state) => {
if (typeof children === 'function') return children(state);
if (children != null) return children;
return <CheckboxMark mixed={state.indeterminate} animated={animated} />;
}}
</SDKCheckboxIndicator>
);
}
const defaultIndicator = <CheckboxIndicator />;
export {
Checkbox,
type CheckboxChangeOptions,
type CheckboxCheckedChangeReason,
type CheckboxController,
CheckboxGroup,
type CheckboxGroupChangeOptions,
type CheckboxGroupController,
type CheckboxGroupOptions,
type CheckboxGroupState,
type CheckboxGroupValueChangeReason,
CheckboxIndicator,
type CheckboxIndicatorState,
CheckboxMark,
type CheckboxOptions,
type CheckboxState,
type CheckedState,
checkboxSurface,
createCheckboxController,
createCheckboxGroupController,
};
'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';