Thoughtful date and range selection with a responsive calendar popup.
Default
Sizes
Date and Time
Range
Locale
Disabled and Read-only
Purpose
A date picker lets people type a date or choose it from a calendar. It can also collect a date range, include a time field, and offer shortcuts for common dates.
Parts & Composition
Place the date field and picker content inside DatePicker. Use DatePickerField for the combined segmented input and calendar trigger. Compose the header, sidebar, calendar, and footer inside DatePickerContent when you need a structured date or range panel.
API & Props
| Part | Purpose |
|---|---|
DatePicker | Root (size: xs | sm | md | lg, mode, value, defaultValue, onValueChange, locale, timeZone, min, max, unavailable, closeOnSelect, presentation, controller). |
DatePickerField | Joined segmented DateInput and DatePickerTrigger (startLabel, endLabel, triggerLabel, timeInput). |
DatePickerContent | Popover or sheet container (size override, align, sideOffset, anchor, container). |
DatePickerHeader, DatePickerLayout, DatePickerSidebar, DatePickerFooter | Surface layout regions (separator default false on header, true on footer; showClose default true on header). |
DatePickerCalendar, DatePickerPreset, DatePickerClear, TimeInput | Calendar grid, preset buttons, clear action (variant / size via buttonVariants, defaults to ghost / icon-xs), and standalone/paired time input. |
See the UI SDK Date Picker reference for upstream options on SDK parts. Wrapper-specific props are listed above.
Common props in detail
| Prop | Purpose |
|---|---|
mode / value / defaultValue | Use an ISO date string in single mode, a pair of ISO dates in range mode, or null to clear. |
min / max / unavailable | Constrain which dates the calendar can select. Keep business validation in the app. |
onValueChange | Receives the next value and change details after a date is picked or typed and committed. A range updates after both ends are set. |
name / startName / endName / form | Submit ISO date values with one field name or separate names for range ends. Use form to associate an external form. |
locale / timeZone | Set the calendar language and the time zone used to determine today. |
Use ISO date strings (2026-11-16) for single dates, [start, end] for ranges, and null when empty. Submits ISO values under name (or startName and endName). presentation defaults to "auto" and switches to a bottom sheet on small touch screens; size scales controlHeights, calendar cells, and popup padding.
Theming, Layout & Responsiveness
The surface uses Card’s padding scale. The shared inset tokens derive region padding from --surface-padding at xs (1.3rem), sm (1.35rem), md (1.5rem), and lg (1.75rem).
DatePickerInput, DateInput, TimeInput, and DatePickerField range wrappers use bg-card, border-input, shadow-sm, and shared focusRing. DatePickerContent uses bg-popover, border-border, shadow-sm, and surfaceHeaderRadius / surfaceFooterRadius. DatePickerHeader defaults to separator={false} and DatePickerFooter defaults to separator={true}.
DatePickerField joins segmented inputs and DatePickerTrigger in a ButtonGroup. size (xs | sm | md | lg) scales controlHeights, calendar cells, and popup padding. presentation defaults to "auto" and switches to a bottom sheet on small touch screens, moving DatePickerSidebar above the calendar. Set presentation="popover" to keep the picker anchored.
Month transitions slide in the direction of navigation; popover open/close scales from 95% to 100%. All transitions disable under prefers-reduced-motion.
Motion & Accessibility
Segmented date/time fields support arrow-key stepping and numeric entry; DatePickerTrigger and DatePickerClose (end-2.5 top-2.5) expose accessible labels and keyboard focus rings (focusRing).
Guidance for Coding Agents
Install Date Picker using the command on the Install tab. Read this Info page and the linked UI SDK reference before implementing.
Choose single or range mode first and match the value shape. Use DatePickerField for the joined date entry and calendar trigger, then compose content regions as needed. Set locale and constraints at the root and keep timezone conversion or business validation in the app.
Pass ISO date strings (YYYY-MM-DD) or [start, end] tuples for range mode.
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 Date Picker.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/date-picker'use client';
import type { DatePickerController, DatePickerState } from '@ui-sdk/core/date-picker';
import { DateInput as SDKDateInput } from '@ui-sdk/react/date-input';
import {
CalendarWeekdays,
CalendarWeeks,
createDatePickerController,
CalendarDay as SDKCalendarDay,
CalendarGrid as SDKCalendarGrid,
CalendarHeading as SDKCalendarHeading,
CalendarNext as SDKCalendarNext,
CalendarPrevious as SDKCalendarPrevious,
CalendarWeekday as SDKCalendarWeekday,
DatePicker as SDKDatePicker,
DatePickerClear as SDKDatePickerClear,
DatePickerContent as SDKDatePickerContent,
DatePickerHint as SDKDatePickerHint,
DatePickerInput as SDKDatePickerInput,
DatePickerPreset as SDKDatePickerPreset,
DatePickerTrigger as SDKDatePickerTrigger,
} from '@ui-sdk/react/date-picker';
import { TimeInput as SDKTimeInput } from '@ui-sdk/react/time-input';
import { cva } from 'class-variance-authority';
import { Calendar, ChevronLeft, ChevronRight, X } from 'lucide-react';
import {
type ComponentProps,
createContext,
type ReactNode,
useContext,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Button, type ButtonProps, buttonVariants } from '@/components/devvarena-ui/button';
import { InputGroup, InputGroupItem } from '@/components/devvarena-ui/input-group';
import { Separator } from '@/components/devvarena-ui/separator';
import { useSlidingHighlight } from '@/hooks/use-sliding-highlight';
import {
concentricRadius,
controlHeights,
controlTextSizes,
focusRing,
partClass,
type StandardControlSize,
slidingHighlight as slidingHighlightClass,
surfaceBodyPadding,
surfaceFooterRadius,
surfaceHeaderRadius,
surfacePadding,
surfaceRegionInset,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
const segmentedInputSize = {
xs: `${controlHeights.xs} ${controlTextSizes.xs}`,
sm: `${controlHeights.sm} ${controlTextSizes.sm}`,
md: `${controlHeights.md} ${controlTextSizes.md}`,
lg: `${controlHeights.lg} ${controlTextSizes.lg}`,
} as const satisfies Record<StandardControlSize, string>;
const segmentedInputClasses = cn(
'inline-flex min-w-0 items-center rounded-lg border border-input bg-card px-2.5 text-foreground shadow-sm',
focusRing,
'[&_[data-slot=date-input-segment]]:rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))] [&_[data-slot=date-input-segment]]:text-center [&_[data-slot=date-input-segment]]:outline-none [&_[data-slot=date-input-segment]:focus]:bg-accent [&_[data-slot=date-input-segment]:focus]:text-accent-foreground [&_[data-slot=date-input-segment]]:selection:bg-accent [&_[data-slot=date-input-segment]]:selection:text-accent-foreground [&_[data-type=literal]]:text-muted-foreground [&_[data-empty]]:text-muted-foreground',
);
type DatePickerSize = StandardControlSize;
type DatePickerProps = ComponentProps<typeof SDKDatePicker> & {
size?: DatePickerSize;
};
const calendarDayFocus = cn(focusRing, 'focus-visible:ring-inset');
const SizeContext = createContext<DatePickerSize>('md');
const MonthsContext = createContext(1);
type DatePickerFieldOptions = Pick<
DatePickerProps,
'locale' | 'min' | 'max' | 'unavailable' | 'required' | 'form'
>;
type DatePickerFieldContext = {
state: DatePickerState;
options: DatePickerFieldOptions;
controller: DatePickerController;
fieldId: string;
};
const FieldContext = createContext<DatePickerFieldContext | null>(null);
function DatePickerFieldProvider({
state,
options,
controller,
fieldId,
children,
}: DatePickerFieldContext & { children: ReactNode }) {
const value = useMemo(
() => ({ state, options, controller, fieldId }),
[state, options, controller, fieldId],
);
return <FieldContext value={value}>{children}</FieldContext>;
}
const iconSize = { xs: 'icon-xs', sm: 'icon-sm', md: 'icon', lg: 'icon-lg' } as const;
const sizeStyles = cva('', {
variants: {
size: {
xs: [controlTextSizes.xs, '[--surface-padding:1.3rem] [--day-size:1.75rem]'],
sm: [controlTextSizes.sm, '[--surface-padding:1.35rem] [--day-size:2rem]'],
md: [controlTextSizes.md, '[--day-size:2.3rem]'],
lg: [controlTextSizes.lg, '[--day-size:2.5rem] [--surface-padding:1.75rem]'],
},
},
defaultVariants: { size: 'md' },
});
function DatePicker({
size = 'md',
months = 1,
presentation = 'auto',
controller: providedController,
children,
locale,
min,
max,
unavailable,
required,
form,
...props
}: DatePickerProps) {
const [localController] = useState(() => createDatePickerController());
const fieldId = useId();
const controller = providedController ?? localController;
const options = useMemo(
() => ({ locale, min, max, unavailable, required, form }),
[locale, min, max, unavailable, required, form],
);
return (
<SizeContext value={size}>
<MonthsContext value={months}>
<SDKDatePicker
{...props}
{...options}
months={months}
presentation={presentation}
controller={controller}
>
{(state) => (
<DatePickerFieldProvider
state={state}
options={options}
controller={controller}
fieldId={fieldId}
>
{typeof children === 'function'
? children(state)
: (children ?? (
<>
<DatePickerField />
<DatePickerContent />
</>
))}
</DatePickerFieldProvider>
)}
</SDKDatePicker>
</MonthsContext>
</SizeContext>
);
}
type DatePickerFieldProps = Omit<
ComponentProps<typeof InputGroup>,
'children' | 'ref' | 'orientation'
> & {
startLabel?: string;
endLabel?: string;
triggerLabel?: string;
timeInput?: ReactNode;
};
function DatePickerField({
startLabel,
endLabel = 'End date',
triggerLabel,
timeInput,
...props
}: DatePickerFieldProps) {
const size = useContext(SizeContext);
const field = useContext(FieldContext);
const [draft, setDraft] = useState<[string | null, string | null] | null>(null);
const hasCommittedRange = Array.isArray(field?.state.value);
useLayoutEffect(() => {
if (hasCommittedRange) setDraft(null);
}, [hasCommittedRange]);
if (!field) return null;
const { state, options, controller, fieldId } = field;
const isRange = state.mode === 'range';
const dates = Array.isArray(state.value) ? state.value : (draft ?? [null, null]);
const updateRange = (
index: 0 | 1,
value: string | null,
details: Parameters<NonNullable<ComponentProps<typeof SDKDateInput>['onValueChange']>>[1],
) => {
if (details.reason === 'reset') {
setDraft(null);
return;
}
const start = index === 0 ? value : dates[0];
const end = index === 1 ? value : dates[1];
if (start && end) {
if (start === dates[0] && end === dates[1] && state.value !== null) return;
if (controller.setValue([start, end], { reason: 'input-commit' })) setDraft(null);
else details.cancel();
} else if (state.value === null || controller.clear({ reason: 'input-commit' })) {
setDraft([start, end]);
} else {
details.cancel();
}
};
const startInput = (
<DateInput
{...options}
aria-label={startLabel ?? (isRange ? 'Start date' : 'Date')}
disabled={state.disabled}
readOnly={state.readOnly}
value={isRange ? dates[0] : typeof state.value === 'string' ? state.value : null}
onValueChange={(next, details) => {
if (isRange) updateRange(0, next, details);
else if (
details.reason !== 'reset' &&
next !== state.value &&
!controller.setValue(next, { reason: 'input-commit' })
)
details.cancel();
}}
className={
isRange
? 'h-full rounded-none! border-0 bg-transparent shadow-none ring-0! has-[:focus-visible]:ring-0! focus-visible:ring-0! hover:brightness-100!'
: 'rounded-e-none border-e-0'
}
/>
);
return (
<InputGroup
{...props}
data-date-picker-field={fieldId}
data-size={size}
className={cn('w-fit max-w-full', props.className)}
>
<InputGroupItem>
{isRange ? (
<div
data-slot="date-picker-range"
data-input-group-control=""
className={cn(
'flex min-w-0 items-center bg-transparent',
focusRing,
segmentedInputSize[size],
)}
>
{startInput}
<span aria-hidden="true" className="shrink-0 text-muted-foreground">
–
</span>
<DateInput
{...options}
aria-label={endLabel}
disabled={state.disabled}
readOnly={state.readOnly}
value={dates[1]}
onValueChange={(next, details) => updateRange(1, next, details)}
className="h-full rounded-none! border-0 bg-transparent shadow-none ring-0! has-[:focus-visible]:ring-0! focus-visible:ring-0! hover:brightness-100!"
/>
</div>
) : (
startInput
)}
</InputGroupItem>
{timeInput && <InputGroupItem>{timeInput}</InputGroupItem>}
<InputGroupItem>
<DatePickerTrigger aria-label={triggerLabel} variant="secondary" size={iconSize[size]}>
<Calendar aria-hidden="true" />
</DatePickerTrigger>
</InputGroupItem>
</InputGroup>
);
}
function DateInput({ className, ...props }: ComponentProps<typeof SDKDateInput>) {
const size = useContext(SizeContext);
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector: '[data-slot="date-input-segment"]:not([data-type="literal"])',
});
return (
<div ref={containerRef} className="relative isolate inline-flex min-w-0">
<span
aria-hidden="true"
data-slot="date-input-highlight"
className={cn(slidingHighlightClass, 'z-10')}
style={highlightStyle}
/>
<SDKDateInput
{...props}
className={partClass(
cn(
segmentedInputClasses,
'[&_[data-slot=date-input-segment]]:select-none [&_[data-slot=date-input-segment]:focus]:bg-transparent',
segmentedInputSize[size],
),
className,
)}
/>
</div>
);
}
type TimeInputProps = ComponentProps<typeof SDKTimeInput>;
function TimeInput({ className, ...props }: TimeInputProps) {
const rootSize = useContext(SizeContext);
return (
<SDKTimeInput
{...props}
className={partClass(cn(segmentedInputClasses, segmentedInputSize[rootSize]), className)}
/>
);
}
type DatePickerInputProps = Omit<ComponentProps<typeof SDKDatePickerInput>, 'size'> & {
size?: DatePickerSize | number;
};
function DatePickerInput({ size, className, ...props }: DatePickerInputProps) {
const rootSize = useContext(SizeContext);
const visualSize = typeof size === 'string' ? size : rootSize;
return (
<SDKDatePickerInput
{...props}
size={typeof size === 'number' ? size : undefined}
className={partClass(
cn(
'w-full min-w-0 rounded-lg border border-input bg-card px-3 text-foreground shadow-sm transition-[border-color,box-shadow,filter] duration-200 disabled:opacity-50',
focusRing,
segmentedInputSize[visualSize],
),
className,
)}
/>
);
}
type DatePickerTriggerProps = ComponentProps<typeof SDKDatePickerTrigger> & {
variant?: ButtonProps['variant'];
size?: ButtonProps['size'];
};
function DatePickerTrigger({
variant = 'secondary',
size,
className,
children,
...props
}: DatePickerTriggerProps) {
const contextSize = useContext(SizeContext);
return (
<SDKDatePickerTrigger
{...props}
data-size={size ?? contextSize}
data-variant={variant}
className={partClass(
cn(
buttonVariants({
variant,
size: size ?? contextSize,
}),
'shrink-0',
),
className,
)}
>
{children ?? (props.render == null ? <Calendar aria-hidden="true" /> : undefined)}
</SDKDatePickerTrigger>
);
}
type DatePickerContentProps = ComponentProps<typeof SDKDatePickerContent> & {
size?: DatePickerSize;
};
function DatePickerContent({
className,
children,
anchor,
align = 'start',
sideOffset = 6,
size,
...props
}: DatePickerContentProps) {
const rootSize = useContext(SizeContext);
const fieldId = useContext(FieldContext)?.fieldId;
const fieldAnchor = fieldId ? `[data-date-picker-field="${fieldId}"]` : undefined;
return (
<SDKDatePickerContent
{...props}
anchor={anchor === undefined ? fieldAnchor : anchor}
align={align}
data-size={size ?? rootSize}
sideOffset={sideOffset}
className={partClass(
cn(
'group/date-picker relative not-prose m-0 flex min-h-0 w-fit flex-col max-w-[min(var(--available-width,100vw),calc(100vw-1rem))] max-h-[var(--available-height,90dvh)] overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-sm outline-none origin-(--transform-origin)',
'data-[presentation=popover]:transition-[opacity,scale,filter] data-[presentation=popover]:duration-200 data-[presentation=popover]:ease-out data-[presentation=popover]:data-starting-style:opacity-0 data-[presentation=popover]:data-ending-style:opacity-0 motion-safe:data-[presentation=popover]:data-starting-style:scale-95 motion-safe:data-[presentation=popover]:data-starting-style:blur-[3px] motion-safe:data-[presentation=popover]:data-ending-style:scale-[0.98] motion-safe:data-[presentation=popover]:data-ending-style:blur-[3px] motion-reduce:data-[presentation=popover]:transition-none',
'data-[presentation=sheet]:w-full data-[presentation=sheet]:max-w-none data-[presentation=sheet]:max-h-[85dvh] data-[presentation=sheet]:rounded-b-none data-[presentation=sheet]:border-x-0 data-[presentation=sheet]:border-b-0 data-[presentation=sheet]:pb-[max(var(--surface-padding,1rem),env(safe-area-inset-bottom))]',
surfacePadding,
sizeStyles({ size: size ?? rootSize }),
),
className,
)}
>
{children ?? <DatePickerCalendar />}
</SDKDatePickerContent>
);
}
function DatePickerClose({
children,
onClick,
'aria-label': label,
...props
}: ComponentProps<typeof Button>) {
const controller = useContext(FieldContext)?.controller;
const iconOnly = children == null;
return (
<Button
variant="ghost"
size={iconOnly ? 'icon-xs' : 'sm'}
aria-label={label ?? (iconOnly ? 'Close calendar' : undefined)}
{...props}
onClick={(event, details) => {
const result = onClick?.(event, details);
if (!event.defaultPrevented)
controller?.close({ reason: 'close-press', event: event.nativeEvent });
return result;
}}
>
{children ?? <X aria-hidden="true" />}
</Button>
);
}
function DatePickerHeader({
children,
className,
showClose = true,
closeLabel,
separator = false,
...props
}: ComponentProps<'header'> & {
showClose?: boolean;
closeLabel?: string;
separator?: boolean;
}) {
return (
<header
{...props}
data-slot="date-picker-header"
className={cn(
'relative grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-2 gap-y-1',
surfaceHeaderRadius,
surfaceRegionInset,
className,
)}
>
{children}
{showClose && (
<DatePickerClose
aria-label={closeLabel}
className="absolute end-2.5 top-2.5 z-10 text-muted-foreground hover:text-foreground"
/>
)}
{separator ? <Separator className="absolute inset-x-0 bottom-0 w-auto" /> : null}
</header>
);
}
function DatePickerTitle({ className, ...props }: ComponentProps<'h2'>) {
return (
<h2 {...props} className={cn('m-0 flex items-center gap-2 text-sm font-semibold', className)} />
);
}
function DatePickerDescription({ className, ...props }: ComponentProps<'p'>) {
return (
<p {...props} className={cn('col-span-full m-0 text-sm text-muted-foreground', className)} />
);
}
function DatePickerLayout({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="date-picker-layout"
className={cn(
'flex min-h-0 min-w-0 flex-col gap-3 sm:flex-row group-data-[presentation=sheet]/date-picker:flex-col',
surfaceRegionInset,
surfaceBodyPadding,
className,
)}
/>
);
}
function DatePickerViewport({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="date-picker-calendar"
className={cn(
'min-h-0 min-w-0 overflow-auto overscroll-contain scroll-fade scroll-fade-3 px-px',
className,
)}
/>
);
}
function DatePickerSidebar({ children, className, ...props }: ComponentProps<'div'>) {
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector:
'[data-slot=date-picker-preset]:not(:disabled,[aria-disabled=true],[data-disabled],[data-selected])',
});
return (
<div
{...props}
data-slot="date-picker-sidebar"
className={cn(
'relative flex min-h-0 shrink-0 flex-col pe-0 sm:min-w-28 sm:pe-3 group-data-[presentation=sheet]/date-picker:max-h-28 group-data-[presentation=sheet]/date-picker:shrink group-data-[presentation=sheet]/date-picker:pe-0',
className,
)}
>
<div
ref={containerRef}
className="group/date-presets relative isolate flex min-h-0 flex-wrap gap-1 overflow-auto overscroll-contain scroll-fade scroll-fade-3 sm:flex-col sm:flex-nowrap group-data-[presentation=sheet]/date-picker:flex-row group-data-[presentation=sheet]/date-picker:flex-wrap"
>
<span aria-hidden="true" style={highlightStyle} className={slidingHighlightClass} />
{children}
</div>
<Separator
orientation="vertical"
className="absolute inset-y-0 end-0 hidden sm:block group-data-[presentation=sheet]/date-picker:hidden"
/>
</div>
);
}
function DatePickerFooter({
separator = true,
children,
className,
...props
}: ComponentProps<'footer'> & { separator?: boolean }) {
return (
<footer
{...props}
data-slot="date-picker-footer"
className={cn(
surfaceRegionInset,
surfaceFooterRadius,
'relative shrink-0 group-data-[presentation=sheet]/date-picker:rounded-b-none group-data-[presentation=sheet]/date-picker:pb-[max(0px,calc(env(safe-area-inset-bottom)-0.25rem))]',
className,
)}
>
{separator ? <Separator className="absolute inset-x-0 top-0 w-auto" /> : null}
<div className="flex flex-wrap items-center justify-end gap-2">{children}</div>
</footer>
);
}
function DatePickerHint({ className, ...props }: ComponentProps<typeof SDKDatePickerHint>) {
return (
<SDKDatePickerHint
{...props}
className={partClass('text-xs text-muted-foreground', className)}
/>
);
}
type DatePickerClearProps = ComponentProps<typeof SDKDatePickerClear> & {
variant?: ButtonProps['variant'];
size?: ButtonProps['size'];
};
function DatePickerClear({
children,
variant = 'ghost',
size = 'icon-xs',
className,
'aria-label': label,
...props
}: DatePickerClearProps) {
const iconOnly = children == null && props.render == null;
return (
<SDKDatePickerClear
{...props}
aria-label={label ?? (iconOnly ? 'Clear date' : undefined)}
data-size={size}
data-variant={variant}
className={partClass(buttonVariants({ variant, size }), className)}
>
{iconOnly ? <X aria-hidden="true" /> : children}
</SDKDatePickerClear>
);
}
function DatePickerPreset({ className, ...props }: ComponentProps<typeof SDKDatePickerPreset>) {
return (
<SDKDatePickerPreset
{...props}
className={partClass(
`${concentricRadius} px-3 py-1.5 text-start outline-none hover:bg-accent focus-visible:bg-accent group-hover/date-presets:[&:not([data-selected])]:hover:bg-transparent group-focus-within/date-presets:[&:not([data-selected])]:focus-visible:bg-transparent [&[data-selected]]:bg-accent [&[data-selected]]:font-medium disabled:opacity-50`,
className,
)}
/>
);
}
const navigationClass =
'inline-flex size-7 items-center justify-center rounded-lg text-muted-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent data-disabled:opacity-40 [&_svg]:size-4';
function CalendarPrevious({
className,
children,
...props
}: ComponentProps<typeof SDKCalendarPrevious>) {
return (
<SDKCalendarPrevious {...props} className={partClass(navigationClass, className)}>
{children ?? <ChevronLeft aria-hidden="true" className="rtl:rotate-180" />}
</SDKCalendarPrevious>
);
}
function CalendarNext({ className, children, ...props }: ComponentProps<typeof SDKCalendarNext>) {
return (
<SDKCalendarNext {...props} className={partClass(navigationClass, className)}>
{children ?? <ChevronRight aria-hidden="true" className="rtl:rotate-180" />}
</SDKCalendarNext>
);
}
function CalendarHeading({ className, ...props }: ComponentProps<typeof SDKCalendarHeading>) {
return (
<SDKCalendarHeading
{...props}
className={partClass('m-0 text-center text-sm font-semibold', className)}
/>
);
}
function CalendarWeekday({ className, ...props }: ComponentProps<typeof SDKCalendarWeekday>) {
return (
<SDKCalendarWeekday
{...props}
className={partClass('h-7 text-center text-xs font-medium text-muted-foreground', className)}
/>
);
}
function CalendarDay({ className, ...props }: ComponentProps<typeof SDKCalendarDay>) {
return (
<SDKCalendarDay
{...props}
className={partClass(
cn(
calendarDayFocus,
`h-(--day-size) w-(--day-size) cursor-default ${concentricRadius} text-center outline-none [&:not([data-selected])]:hover:bg-accent group-hover/date-grid:[&:not([data-selected],[data-today],[data-preview],[data-disabled],[data-unavailable])]:hover:bg-transparent [&[data-outside]]:text-muted-foreground [&[data-disabled]]:opacity-40 [&[data-unavailable]]:line-through [&[data-today]]:relative [&[data-today]]:isolate [&[data-today]]:font-semibold [&[data-today]]:before:pointer-events-none [&[data-today]]:before:absolute [&[data-today]]:before:inset-0 [&[data-today]]:before:-z-10 [&[data-today]]:before:rounded-[inherit] [&[data-today]:is(:not([data-selected]),[data-range-middle])]:before:bg-primary/20 [&[data-today]:is(:not([data-selected]),[data-range-middle])]:text-primary [&[data-selected]:not([data-range-middle])]:bg-primary [&[data-selected]:not([data-range-middle])]:text-primary-foreground [&[data-range-start]:not([data-range-end])]:rounded-e-none [&[data-range-end]:not([data-range-start])]:rounded-s-none [&[data-range-middle]]:rounded-none [&[data-range-middle]]:bg-primary/15 [&[data-range-middle]]:text-foreground [&[data-preview]:not([data-selected])]:bg-accent`,
),
className,
)}
/>
);
}
function CalendarMonthWeeks({ month, offset }: { month: string; offset: number }) {
const ref = useRef<HTMLTableSectionElement>(null);
const previousMonth = useRef(month);
useLayoutEffect(() => {
const previous = previousMonth.current;
previousMonth.current = month;
const weeks = ref.current;
const grids = weeks?.closest<HTMLElement>('[data-slot="date-picker-grids"]');
// Keep the shared highlight and day cells in the same moving coordinate space.
if (grids && offset !== 0) return;
const surface = grids ?? weeks;
if (
previous === month ||
!surface?.animate ||
matchMedia('(prefers-reduced-motion: reduce)').matches
)
return;
const forward = month > previous;
const rtl = getComputedStyle(surface).direction === 'rtl';
const distance = forward !== rtl ? 16 : -16;
const slide = surface.animate(
[
{ transform: `translateX(${distance}px)`, opacity: 0 },
{ transform: 'translateX(0)', opacity: 1 },
],
{ duration: 200, easing: 'ease-out' },
);
return () => slide.cancel();
}, [month, offset]);
return <CalendarWeeks ref={ref}>{(cell) => <CalendarDay value={cell.date} />}</CalendarWeeks>;
}
function CalendarGrid({
offset = 0,
className,
children,
...props
}: ComponentProps<typeof SDKCalendarGrid>) {
return (
<SDKCalendarGrid
{...props}
offset={offset}
className={partClass('mx-auto table-fixed border-separate border-spacing-0.5', className)}
>
{children ??
(({ month }) => (
<>
<CalendarWeekdays>{(index) => <CalendarWeekday index={index} />}</CalendarWeekdays>
<CalendarMonthWeeks month={month} offset={offset} />
</>
))}
</SDKCalendarGrid>
);
}
function DatePickerCalendar() {
const offsets = Array.from({ length: useContext(MonthsContext) }, (_, offset) => offset);
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector:
'[data-slot=calendar-day]:not([aria-disabled=true],[data-disabled],[data-unavailable],[data-selected],[data-today],[data-preview])',
});
return (
<DatePickerViewport className="space-y-2">
<div className="flex items-center justify-between gap-3">
<CalendarPrevious />
<CalendarHeading />
<CalendarNext />
</div>
<div
ref={containerRef}
data-slot="date-picker-grids"
className="group/date-grid relative isolate flex flex-wrap justify-center gap-3"
>
<span aria-hidden="true" style={highlightStyle} className={slidingHighlightClass} />
{offsets.map((offset) => (
<CalendarGrid key={offset} offset={offset} />
))}
</div>
</DatePickerViewport>
);
}
export type { DatePickerOptions } from '@ui-sdk/core/date-picker';
export type {
DatePickerController,
DatePickerMode,
DatePickerValue,
} from '@ui-sdk/react/date-picker';
export {
CalendarMonthSelect,
CalendarWeekdays,
CalendarWeeks,
CalendarYearSelect,
createDatePickerController,
} from '@ui-sdk/react/date-picker';
export { createTimeInputController, TimeInputSegment } from '@ui-sdk/react/time-input';
export {
CalendarDay,
CalendarGrid,
CalendarHeading,
CalendarNext,
CalendarPrevious,
CalendarWeekday,
DateInput,
DatePicker,
DatePickerCalendar,
DatePickerClear,
DatePickerClose,
DatePickerContent,
DatePickerDescription,
DatePickerField,
DatePickerFooter,
DatePickerHeader,
DatePickerHint,
DatePickerInput,
DatePickerLayout,
DatePickerPreset,
DatePickerSidebar,
type DatePickerSize,
DatePickerTitle,
DatePickerTrigger,
DatePickerViewport,
TimeInput,
};
import type { ButtonOptions } from '@ui-sdk/core/button';
import { Button as ButtonPrimitive } from '@ui-sdk/react/button';
import { cva, type VariantProps } from 'class-variance-authority';
import { Loader2 } from 'lucide-react';
import type { ComponentProps, ReactNode } from 'react';
import { controlHeights, controlTextSizes, focusRing } from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
/*
* Clean tactile button surfaces with a subtle top highlight, contact shadow,
* and 2% press scale using pure Tailwind/theme tokens.
*/
const flatPress = 'motion-safe:not-data-disabled:not-data-pending:active:scale-[0.985]';
const activeInsetShadow =
'active:shadow-[inset_0_1px_3px_rgb(0_0_0/0.12),0_1px_2px_rgb(0_0_0/0.06)] dark:active:shadow-[inset_0_1px_3px_rgb(0_0_0/0.18),0_1px_2px_rgb(0_0_0/0.1)]';
const tactileFilled =
'bg-[linear-gradient(180deg,rgb(255_255_255/0.16),rgb(255_255_255/0)_75%)] shadow-[inset_0_1.5px_0_rgb(255_255_255/0.22),inset_0_-1px_0_rgb(0_0_0/0.12),0_1px_3px_0_rgb(0_0_0/0.1),0_1px_2px_-1px_rgb(0_0_0/0.1)] active:shadow-[inset_0_1px_3px_rgb(0_0_0/0.18),0_1px_2px_rgb(0_0_0/0.1)]';
const tactileNeutral = `bg-[linear-gradient(180deg,rgb(255_255_255/0.35),transparent_48%,rgb(0_0_0/0.025)_100%)] shadow-[inset_0_1px_0_rgb(255_255_255/0.65),inset_0_-1px_0_rgb(0_0_0/0.06),0_1px_3px_0_rgb(0_0_0/0.1),0_1px_2px_-1px_rgb(0_0_0/0.1)] dark:bg-[linear-gradient(180deg,rgb(255_255_255/0.06),transparent_48%,rgb(0_0_0/0.12)_100%)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.1),inset_0_-1px_0_rgb(0_0_0/0.12),0_1px_3px_0_rgb(0_0_0/0.1),0_1px_2px_-1px_rgb(0_0_0/0.1)] ${activeInsetShadow}`;
/** Surface map for button variants, shared with Toggle, Tabs, Radio, Checkbox, and Switch. */
const buttonSurfaces = {
primary: `border-[color-mix(in_oklch,var(--primary),black_8%)] bg-primary text-primary-foreground ${tactileFilled} ${flatPress}`,
secondary: ` bg-popover text-popover-foreground border-[color-mix(in_oklch,var(--muted),black_5%)] ${tactileNeutral} ${flatPress}`,
outline: `border-input bg-accent/10 text-foreground shadow-sm hover:text-accent-foreground ${activeInsetShadow} ${flatPress}`,
ghost: `border-transparent text-foreground hover:bg-muted ${activeInsetShadow} ${flatPress}`,
destructive: `border-[color-mix(in_oklch,var(--destructive),black_8%)] bg-destructive text-[color:var(--destructive-foreground,white)] ${tactileFilled} ${flatPress}`,
tertiary: `border-transparent bg-accent text-accent-foreground ${activeInsetShadow} ${flatPress}`,
'destructive-soft': `border-transparent bg-destructive/10 text-destructive dark:bg-destructive/20 ${activeInsetShadow} ${flatPress}`,
link: 'border-transparent text-primary underline-offset-4 hover:underline',
} as const;
type ButtonVariant = keyof typeof buttonSurfaces;
const buttonBase = cva(
[
// layout
'group/button relative isolate inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-lg border text-sm font-medium',
// interaction
'cursor-pointer select-none touch-manipulation',
'transition-[background-color,border-color,box-shadow,translate,scale,filter] duration-150 ease-out motion-reduce:transition-none',
focusRing,
// 44px touch target on coarse pointers without changing the visual size
'[@media(pointer:coarse)]:after:absolute [@media(pointer:coarse)]:after:inset-1/2 [@media(pointer:coarse)]:after:min-h-11 [@media(pointer:coarse)]:after:min-w-11 [@media(pointer:coarse)]:after:-translate-1/2',
// states
'disabled:cursor-not-allowed aria-disabled:opacity-50 data-disabled:cursor-not-allowed data-disabled:opacity-50 data-pending:cursor-wait',
// icons
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-(--icon-size,1rem) [&>span:has(>svg):not([class*='size-'])]:size-(--icon-size,1rem)",
],
{
variants: {
size: {
md: `${controlHeights.md} ${controlTextSizes.md} gap-2 px-4 [--icon-size:1.2rem]`,
xs: `${controlHeights.xs} ${controlTextSizes.xs} gap-1 px-2.5 [--icon-size:0.875rem]`,
sm: `${controlHeights.sm} ${controlTextSizes.sm} gap-1.5 px-3 [--icon-size:1rem]`,
lg: `${controlHeights.lg} ${controlTextSizes.lg} gap-2 px-6 [--icon-size:1.25rem]`,
icon: `${controlHeights.md} aspect-square [--icon-size:1.2rem]`,
'icon-xs': `${controlHeights.xs} aspect-square [--icon-size:0.875rem]`,
'icon-sm': `${controlHeights.sm} aspect-square [--icon-size:1rem]`,
'icon-lg': `${controlHeights.lg} aspect-square [--icon-size:1.25rem]`,
},
},
defaultVariants: { size: 'md' },
},
);
type ButtonVariantProps = VariantProps<typeof buttonBase> & {
variant?: ButtonVariant;
};
function buttonVariants({
variant = 'primary',
size,
className,
}: ButtonVariantProps & { className?: string } = {}) {
return cn(buttonBase({ size }), buttonSurfaces[variant], className);
}
type ButtonProps = Omit<
ComponentProps<typeof ButtonPrimitive>,
keyof ButtonOptions | 'className' | 'children'
> &
ButtonOptions &
ButtonVariantProps & {
children?: ReactNode;
className?: string;
/** Prevent repeated activation and display an inline spinner without replacing the label. */
loading?: boolean;
};
const spinner = (
<Loader2
aria-hidden="true"
data-slot="spinner"
className="hidden size-(--icon-size,1rem) animate-spin in-data-pending:inline-block in-data-loading:inline-block motion-reduce:animate-none"
/>
);
function Button({
className,
variant = 'primary',
size = 'md',
loading = false,
disabled,
children,
'aria-busy': ariaBusy,
...props
}: ButtonProps) {
return (
<ButtonPrimitive
{...props}
className={buttonVariants({ variant, size, className })}
data-size={size}
data-variant={variant}
data-loading={loading || undefined}
disabled={disabled || loading}
aria-busy={loading || ariaBusy}
>
{spinner}
{children}
</ButtonPrimitive>
);
}
export { Button, type ButtonProps, type ButtonVariant, buttonSurfaces, buttonVariants };
import { cva } from 'class-variance-authority';
import type { ComponentProps } from 'react';
import { controlHeights, controlTextSizes, type StandardControlSize } from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
const inputGroupSizes = cva('', {
variants: {
size: {
xs: '[&_:is(button,a,input,[data-slot=input],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:h-7 [&_:is(button,a,input,textarea,[data-slot=input],[data-slot=textarea],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:text-xs',
sm: '[&_:is(button,a,input,[data-slot=input],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:h-8 [&_:is(button,a,input,textarea,[data-slot=input],[data-slot=textarea],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:text-xs',
md: '[&_:is(button,a,input,[data-slot=input],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:h-10 [&_:is(button,a,input,textarea,[data-slot=input],[data-slot=textarea],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:text-sm',
lg: '[&_:is(button,a,input,[data-slot=input],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:h-12 [&_:is(button,a,input,textarea,[data-slot=input],[data-slot=textarea],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:text-base',
} satisfies Record<StandardControlSize, string>,
},
});
const inputGroupTextSizes = cva('', {
variants: {
size: {
xs: `${controlHeights.xs} px-2.5 ${controlTextSizes.xs} [&_svg:not([class*='size-'])]:size-3.5`,
sm: `${controlHeights.sm} px-3 ${controlTextSizes.sm}`,
md: `${controlHeights.md} px-3.5 ${controlTextSizes.md}`,
lg: `${controlHeights.lg} px-4 ${controlTextSizes.lg}`,
} satisfies Record<StandardControlSize, string>,
},
});
type InputGroupProps = ComponentProps<'div'> & {
size?: StandardControlSize;
orientation?: 'horizontal' | 'vertical';
};
function InputGroup({ size, orientation = 'horizontal', className, ...props }: InputGroupProps) {
return (
// biome-ignore lint/a11y/useSemanticElements: InputGroup joins mixed controls into one bar; fieldset breaks flex alignment.
<div
{...props}
role="group"
data-slot="input-group"
data-size={size}
data-orientation={orientation}
className={cn(
'group/input-group isolate flex min-w-0 items-stretch rounded-lg border border-input bg-card text-card-foreground shadow-sm',
orientation === 'horizontal'
? [
'flex-row',
'[&>[data-slot=input-group-item]~[data-slot=input-group-item]]:border-s [&>[data-slot=input-group-item]~[data-slot=input-group-item]]:border-border',
'[&>[data-slot=input-group-item]~[data-slot=input-group-item]]:[--ig-tl:0px] [&>[data-slot=input-group-item]~[data-slot=input-group-item]]:[--ig-bl:0px]',
'[&>[data-slot=input-group-item]:has(~[data-slot=input-group-item])]:[--ig-tr:0px] [&>[data-slot=input-group-item]:has(~[data-slot=input-group-item])]:[--ig-br:0px]',
]
: [
'flex-col',
'[&>[data-slot=input-group-item]~[data-slot=input-group-item]]:border-t [&>[data-slot=input-group-item]~[data-slot=input-group-item]]:border-border',
'[&>[data-slot=input-group-item]~[data-slot=input-group-item]]:[--ig-tl:0px] [&>[data-slot=input-group-item]~[data-slot=input-group-item]]:[--ig-tr:0px]',
'[&>[data-slot=input-group-item]:has(~[data-slot=input-group-item])]:[--ig-bl:0px] [&>[data-slot=input-group-item]:has(~[data-slot=input-group-item])]:[--ig-br:0px]',
'[&>[data-slot=input-group-item]>*:not([popover]):not([data-slot$=-content])]:w-full',
],
inputGroupSizes({ size }),
className,
)}
/>
);
}
type InputGroupItemProps = ComponentProps<'div'> & {
grow?: boolean;
};
function InputGroupItem({ grow = false, className, ...props }: InputGroupItemProps) {
return (
<div
{...props}
data-slot="input-group-item"
className={cn(
'relative flex min-w-0 items-stretch focus-within:z-10 hover:z-10 has-[[data-open]]:z-10',
grow && 'flex-1 [&>*:not([popover]):not([data-slot$=-content])]:w-full',
'[&_:is(button,a,input,textarea,[data-slot=input],[data-slot=textarea],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:border-0',
'[&_:is(button,a,input,textarea,[data-slot=input],[data-slot=textarea],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:shadow-none',
'[&_:is(button,a,input,textarea,[data-slot=input],[data-slot=textarea],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:rounded-ss-[var(--ig-tl,calc(var(--radius-lg)-1px))]',
'[&_:is(button,a,input,textarea,[data-slot=input],[data-slot=textarea],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:rounded-se-[var(--ig-tr,calc(var(--radius-lg)-1px))]',
'[&_:is(button,a,input,textarea,[data-slot=input],[data-slot=textarea],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:rounded-es-[var(--ig-bl,calc(var(--radius-lg)-1px))]',
'[&_:is(button,a,input,textarea,[data-slot=input],[data-slot=textarea],[data-slot=autocomplete-input],[data-slot=select-trigger],[data-slot=number-input-group],[data-slot=time-input],[data-slot=date-input],[data-slot=date-picker-trigger],[data-slot=input-group-text],[data-input-group-control]):not(:where([data-slot=input-group-item]_:is([popover],[data-slot$=-content])_*))]:rounded-ee-[var(--ig-br,calc(var(--radius-lg)-1px))]',
className,
)}
/>
);
}
type InputGroupTextProps = ComponentProps<'div'> & {
size?: StandardControlSize;
};
function InputGroupText({ size = 'md', className, ...props }: InputGroupTextProps) {
return (
<div
{...props}
data-slot="input-group-text"
data-size={size}
className={cn(
"flex items-center gap-2 rounded-lg border border-input bg-muted font-medium text-muted-foreground shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
inputGroupTextSizes({ size }),
className,
)}
/>
);
}
export type { InputGroupItemProps, InputGroupProps, InputGroupTextProps };
export { InputGroup, InputGroupItem, InputGroupText };
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';