A stepped slider with tactile thumb motion, a chromatic fill, and a color-matched pixel flow.
Default
Sizes
Custom Steps
A custom three-step scale with a consistent mint palette.
Form
States
Managed by workspace policy while battery saver is active.
Focusable for inspection, but value cannot be modified.
Purpose
An energy slider lets people adjust a value along a range and see visual feedback as it changes.
Parts & Composition
EnergySlider → header (label, value) → control → track (indicator and single thumb). Optional EnergySliderScale and EnergySliderDescription; wire description id to thumb aria-describedby.
API & Props
| Prop / part | Purpose |
|---|---|
steps | ≥2 { label, color? }; values are zero-based indices |
size | xs, sm, md (default), lg — scales control row, track, thumb, header, and scale (28 / 32 / 40 / 48px control scale) |
value, defaultValue, onValueChange, onValueCommit | Controlled / uncontrolled index |
name, form, disabled, readOnly | Native form integration |
| Thumb children | Decorative icon in thumb |
Missing step color | Falls back to primary |
State & forms
Submitted value is the step index. Use format for custom spoken values and largeStep to set the Page Up and Page Down increment. A controller created with createEnergySliderController<number>() can focus the thumb or move it programmatically. Keep indices valid when steps changes.
Theming, Layout & Responsiveness
Per-step color accepts CSS values or variables. Fill and thumb positions follow the primitive (no lag on fast drags).
Control row follows size (h-7 … h-12); thumb hit slop scales with the thumb. Avoid crowded step counts; long labels wrap in narrow parents.
Motion & Accessibility
Decorative particles while dragging (effort-scaled); fades ~1s after release. Uses tw-animate-css utilities—import in global CSS like this project. Reduced motion hides particles and label/thumb transitions.
Label supplies the name; thumb announces the selected step label. Scale text is decorative. Set dir="rtl" or inherit the document direction.
Guidance for Coding Agents
Use the Energy Slider when the value benefits from its visual feedback. Supply meaningful bounds, units, and an accessible name. Use live changes for immediate feedback and commits for expensive work that only needs the settled value.
Pair EnergySliderLabel with EnergySlider so the thumb inherits an accessible name, and use onValueCommit for final-value side effects. Include tw-animate-css when using the particle motion.
Start from the closest Preview → Usage example and use this page’s API table for component parts and options. For inherited props, callbacks, keyboard behavior, and rendering options, consult UI SDK Slider.
Registry
UI SDK React and Core. Add EnergySliderIndicator inside the track for the colored fill. Existing consumers should rename onValueCommitted to onValueCommit and read { value } in custom EnergySliderValue callbacks. Import tw-animate-css in global CSS for particle motion (as in this project).
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/energy-slider'use client';
import {
Slider,
SliderControl,
SliderIndicator,
SliderThumb,
SliderTrack,
SliderValue,
} from '@ui-sdk/react/slider';
import { cva, type VariantProps } from 'class-variance-authority';
import { Zap } from 'lucide-react';
import {
type ComponentProps,
type CSSProperties,
createContext,
useContext,
useId,
useMemo,
} from 'react';
import { ValueTransition } from '@/hooks/use-value-transition';
import { focusRing, partClass, type StandardControlSize } from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
type EnergySliderStep = { label: string; color?: string };
const EnergySliderContext = createContext<{
steps: readonly EnergySliderStep[];
labelId: string;
} | null>(null);
function stepIndex(value: number | number[], steps: readonly EnergySliderStep[]) {
return Math.min(steps.length - 1, Math.max(0, Math.round(Number(value))));
}
function useEnergySlider() {
const context = useContext(EnergySliderContext);
if (!context) throw new Error('EnergySlider parts require an EnergySlider.');
return context;
}
const energySliderSizeVariants = cva('group/energy w-full min-w-0 data-disabled:opacity-45', {
variants: {
size: {
xs: [
'[&_[data-slot=energy-slider-header]]:mb-4 [&_[data-slot=energy-slider-header]]:gap-1.5 [&_[data-slot=energy-slider-header]]:text-xs',
'[&_[data-slot=energy-slider-scale]]:mb-0.5 [&_[data-slot=energy-slider-scale]]:text-[0.6875rem]',
'[&_[data-slot=energy-slider-description]]:text-[0.6875rem]',
'[&_[data-slot=slider-control]]:h-7 [&_[data-slot=slider-control]]:px-4',
'[&_[data-slot=slider-track]]:h-5 [&_[data-slot=slider-track]>span]:px-3 [&_[data-slot=slider-track]>span_span]:size-0.5',
'[&_[data-slot=slider-thumb]]:h-6 [&_[data-slot=slider-thumb]]:w-8 [&_[data-slot=slider-thumb]]:before:-inset-1',
'[&_[data-slot=slider-thumb]>[data-energy-thumb]]:h-6 [&_[data-slot=slider-thumb]>[data-energy-thumb]]:w-8 [&_[data-slot=slider-thumb]>[data-energy-thumb]]:[&>svg]:size-4',
].join(' '),
sm: [
'[&_[data-slot=energy-slider-header]]:mb-5 [&_[data-slot=energy-slider-header]]:gap-1.5 [&_[data-slot=energy-slider-header]]:text-xs',
'[&_[data-slot=energy-slider-scale]]:mb-1 [&_[data-slot=energy-slider-scale]]:text-xs',
'[&_[data-slot=energy-slider-description]]:text-xs',
'[&_[data-slot=slider-control]]:h-8 [&_[data-slot=slider-control]]:px-4.5',
'[&_[data-slot=slider-track]]:h-6 [&_[data-slot=slider-track]>span]:px-3.5',
'[&_[data-slot=slider-thumb]]:h-7 [&_[data-slot=slider-thumb]]:w-9 [&_[data-slot=slider-thumb]]:before:-inset-1',
'[&_[data-slot=slider-thumb]>[data-energy-thumb]]:h-7 [&_[data-slot=slider-thumb]>[data-energy-thumb]]:w-9 [&_[data-slot=slider-thumb]>[data-energy-thumb]]:[&>svg]:size-4',
].join(' '),
md: [
'[&_[data-slot=energy-slider-header]]:mb-6 [&_[data-slot=energy-slider-header]]:gap-2 [&_[data-slot=energy-slider-header]]:text-sm',
'[&_[data-slot=energy-slider-scale]]:mb-1 [&_[data-slot=energy-slider-scale]]:text-xs',
'[&_[data-slot=energy-slider-description]]:text-xs',
'[&_[data-slot=slider-control]]:h-10 [&_[data-slot=slider-control]]:px-5',
'[&_[data-slot=slider-track]]:h-7 [&_[data-slot=slider-track]>span]:px-4',
'[&_[data-slot=slider-thumb]]:h-8 [&_[data-slot=slider-thumb]]:w-10 [&_[data-slot=slider-thumb]]:before:-inset-1.5',
'[&_[data-slot=slider-thumb]>[data-energy-thumb]]:h-8 [&_[data-slot=slider-thumb]>[data-energy-thumb]]:w-10 [&_[data-slot=slider-thumb]>[data-energy-thumb]]:[&>svg]:size-5',
].join(' '),
lg: [
'[&_[data-slot=energy-slider-header]]:mb-7 [&_[data-slot=energy-slider-header]]:gap-2.5 [&_[data-slot=energy-slider-header]]:text-base',
'[&_[data-slot=energy-slider-scale]]:mb-1.5 [&_[data-slot=energy-slider-scale]]:text-sm',
'[&_[data-slot=energy-slider-description]]:text-sm',
'[&_[data-slot=slider-control]]:h-12 [&_[data-slot=slider-control]]:px-6',
'[&_[data-slot=slider-track]]:h-9 [&_[data-slot=slider-track]>span]:px-5 [&_[data-slot=slider-track]>span_span]:size-1.5',
'[&_[data-slot=slider-thumb]]:h-10 [&_[data-slot=slider-thumb]]:w-12 [&_[data-slot=slider-thumb]]:before:-inset-2',
'[&_[data-slot=slider-thumb]>[data-energy-thumb]]:h-10 [&_[data-slot=slider-thumb]>[data-energy-thumb]]:w-12 [&_[data-slot=slider-thumb]>[data-energy-thumb]]:[&>svg]:size-6',
].join(' '),
} satisfies Record<StandardControlSize, string>,
},
defaultVariants: { size: 'md' },
});
type EnergySliderSize = StandardControlSize;
type EnergySliderProps = Omit<
ComponentProps<typeof Slider<number>>,
'min' | 'max' | 'step' | 'orientation' | 'minStepsBetweenThumbs'
> &
VariantProps<typeof energySliderSizeVariants> & {
steps: readonly EnergySliderStep[];
};
function EnergySlider({
steps,
size = 'md',
className,
style,
defaultValue = 0,
largeStep = 1,
format = (value) => steps[stepIndex(value, steps)].label,
...props
}: EnergySliderProps) {
const labelId = useId();
if (steps.length < 2) throw new Error('EnergySlider requires at least two steps.');
const contextValue = useMemo(() => ({ steps, labelId }), [steps, labelId]);
return (
<EnergySliderContext value={contextValue}>
<Slider<number>
{...props}
defaultValue={defaultValue}
min={0}
max={steps.length - 1}
step={1}
largeStep={largeStep}
format={format}
orientation="horizontal"
data-size={size ?? 'md'}
className={partClass(energySliderSizeVariants({ size }), className)}
style={(state) => {
const index = stepIndex(state.value, steps);
const effort = index / (steps.length - 1);
return {
'--energy-speed': `${4.5 - effort * 3.3}s`,
'--energy-intensity': 0.2 + effort * 0.55,
'--energy-color': steps[index].color || 'var(--primary)',
...(typeof style === 'function' ? style(state) : style),
} as CSSProperties;
}}
/>
</EnergySliderContext>
);
}
function EnergySliderHeader({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="energy-slider-header"
className={cn(
'flex min-w-0 flex-wrap items-center font-medium text-muted-foreground',
className,
)}
/>
);
}
function EnergySliderLabel({ className, id, ...props }: ComponentProps<'span'>) {
const { labelId } = useEnergySlider();
return (
<span
{...props}
id={id ?? labelId}
data-slot="energy-slider-label"
className={cn('font-medium text-muted-foreground', className)}
/>
);
}
function EnergySliderValue({
animated = true,
className,
children,
...props
}: ComponentProps<typeof SliderValue> & { animated?: boolean }) {
const { steps } = useEnergySlider();
return (
<SliderValue
{...props}
className={partClass(
'font-medium text-[color:var(--energy-color)] transition-colors duration-300 motion-reduce:transition-none',
className,
)}
>
{children ??
(({ value }) => (
<ValueTransition value={steps[stepIndex(value, steps)]?.label ?? ''} enabled={animated} />
))}
</SliderValue>
);
}
function EnergySliderControl({ className, ...props }: ComponentProps<typeof SliderControl>) {
return (
<SliderControl
{...props}
className={partClass(
'relative flex w-full touch-pan-y items-center select-none data-disabled:cursor-not-allowed',
className,
)}
/>
);
}
function EnergySliderTrack({ className, children, ...props }: ComponentProps<typeof SliderTrack>) {
const { steps } = useEnergySlider();
return (
<SliderTrack
{...props}
className={partClass(
'relative h-full w-full rounded-lg bg-muted shadow-[inset_0_1px_3px_rgb(0_0_0/0.12)]',
className,
)}
>
{(state) => (
<>
{typeof children === 'function' ? children(state) : children}
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-1 flex items-center justify-between"
>
{steps.map((entry) => (
<span key={entry.label} className="size-1 rounded-full bg-foreground/25" />
))}
</span>
</>
)}
</SliderTrack>
);
}
const energyParticles = Array.from({ length: 84 }, (_, index) => {
const column = index % 12;
const row = Math.floor(index / 12);
const shades = [
'var(--energy-color)',
'color-mix(in oklch,var(--energy-color),white 65%)',
'color-mix(in oklch,var(--energy-color),white 25%)',
'color-mix(in oklch,var(--energy-color),black 30%)',
'color-mix(in oklch,var(--energy-color),#fb7185 28%)',
];
return (
<rect
key={`${column}-${row}`}
x={column * 4 + ((row * 7) % 3) * 0.4}
y={row * 4 + 0.3}
width={1.7 + ((column * 7 + row * 3) % 4) * 0.5}
height={1.6 + ((column * 3 + row) % 3) * 0.35}
rx="0.25"
fill={shades[(column * 7 + row * 3) % shades.length]}
opacity={0.15 + ((column * 13 + row * 7) % 9) * 0.1}
/>
);
});
function EnergySliderIndicator({
className,
children,
...props
}: ComponentProps<typeof SliderIndicator>) {
const glitterId = useId();
return (
<SliderIndicator
{...props}
className={partClass(
'pointer-events-none absolute h-full rounded-[inherit] bg-[linear-gradient(90deg,color-mix(in_oklab,var(--energy-color)_12%,transparent),var(--energy-color))] rtl:bg-[linear-gradient(270deg,color-mix(in_oklab,var(--energy-color)_12%,transparent),var(--energy-color))] transition-colors duration-200 ease-out motion-reduce:transition-none overflow-hidden',
className,
)}
>
{(state) => (
<>
{typeof children === 'function' ? children(state) : children}
<svg
aria-hidden="true"
className="absolute inset-0 size-full invisible opacity-0 [transition:opacity_200ms_ease_1s,visibility_0s_linear_1.2s] group-data-dragging/energy:visible group-data-dragging/energy:opacity-[var(--energy-intensity)] group-data-dragging/energy:[transition:opacity_120ms_ease] [mask-image:linear-gradient(to_right,transparent,black_90%)] rtl:[mask-image:linear-gradient(to_left,transparent,black_90%)] motion-reduce:hidden"
>
<defs>
<pattern id={glitterId} width="48" height="28" patternUnits="userSpaceOnUse">
{energyParticles}
</pattern>
</defs>
<g className="animate-out slide-out-to-right-12 repeat-infinite ease-linear [--tw-animation-duration:calc(var(--energy-speed,4.5s)*0.5)] motion-reduce:animate-none">
<rect x="-48" width="calc(100% + 48px)" height="100%" fill={`url(#${glitterId})`} />
</g>
</svg>
</>
)}
</SliderIndicator>
);
}
function EnergySliderThumb({
className,
children,
'aria-label': label,
'aria-labelledby': labelledBy,
...props
}: Omit<ComponentProps<typeof SliderThumb>, 'index'>) {
const { labelId } = useEnergySlider();
return (
<SliderThumb
{...props}
aria-label={label ?? 'Energy level'}
aria-labelledby={labelledBy ?? (label ? undefined : labelId)}
className={partClass(
cn(
'group/energy-thumb z-10 flex items-center justify-center rounded-lg border border-transparent bg-transparent shadow-none text-[color:var(--energy-color)] transition-[color,border-color,box-shadow] duration-200 ease-out before:absolute motion-reduce:transition-none',
focusRing,
),
className,
)}
>
{(state) => (
<span
data-energy-thumb=""
aria-hidden="true"
className="pointer-events-none inline-flex items-center justify-center rounded-lg border border-[color-mix(in_oklch,var(--energy-color),white_30%)] bg-foreground text-[color:color-mix(in_oklch,var(--energy-color),var(--background)_75%)] shadow-[inset_0_1.5px_0_rgb(255_255_255/0.22),inset_0_-1px_0_rgb(0_0_0/0.12)] transition-[scale,background-color,border-color] duration-300 ease-[cubic-bezier(0.22,1.4,0.36,1)] group-hover/energy-thumb:scale-110 group-data-dragging/energy-thumb:scale-125 motion-reduce:transition-none motion-reduce:scale-100 [&>svg]:drop-shadow-[0_0_4px_color-mix(in_srgb,var(--energy-color),transparent_45%)]"
>
{(typeof children === 'function' ? children(state) : children) ?? (
<Zap aria-hidden="true" fill="currentColor" stroke="currentColor" strokeWidth={1.25} />
)}
</span>
)}
</SliderThumb>
);
}
function EnergySliderScale({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
aria-hidden="true"
data-slot="energy-slider-scale"
className={cn('flex justify-between gap-2 text-muted-foreground', className)}
/>
);
}
function EnergySliderDescription({ className, ...props }: ComponentProps<'p'>) {
return (
<p
{...props}
data-slot="energy-slider-description"
className={cn('m-0 mt-1 leading-relaxed text-muted-foreground', className)}
/>
);
}
export type { SliderOptions } from '@ui-sdk/core/slider';
export { createSliderController as createEnergySliderController } from '@ui-sdk/react/slider';
export {
EnergySlider,
EnergySliderControl,
EnergySliderDescription,
EnergySliderHeader,
EnergySliderIndicator,
EnergySliderLabel,
EnergySliderScale,
type EnergySliderSize,
type EnergySliderStep,
EnergySliderThumb,
EnergySliderTrack,
EnergySliderValue,
};
'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';