All components
Date Input
Segmented date field with keyboard-editable month, day and year in locale order.
Start date
03182026
12345678910111213141516171819202122232425import { DateInput } from "#components/ui/base-ui/date-input.tsx";import { indigoPalette } from "@stylexblocks/ui/themes/palettes.ts";
export function Example() { return ( // Base UI has no date-input primitive: Root owns the fields and takes a // plain Date; segments are role="spinbutton" in locale order <DateInput.Root locale="en-US" defaultValue={new Date(2026, 2, 18)} variant="outline" size="md" palette={indigoPalette} name="start" > <DateInput.Label>Start date</DateInput.Label> <DateInput.Control> <DateInput.SegmentGroup /> </DateInput.Control> <DateInput.HiddenInput /> </DateInput.Root> );}
// controlled: <DateInput.Root value={date} onValueChange={(d) => setDate(d.value)}>Variants
Start date
outline03182026
Start date
subtle03182026
Start date
flushed03182026
Sizes
Start date
xs03182026
Start date
sm03182026
Start date
md03182026
Start date
lg03182026
Start date
xl03182026
Controlled
onValueChange fires with a Date once every segment is filled, and with null when one is cleared. Tab or ArrowLeft/Right moves between segments, ArrowUp/Down steps the focused one, typed digits fill it and jump ahead, Backspace clears.
Due date
Value: incompletemmddyyyy
Locale order
Segment order and separators come from Intl.DateTimeFormat: German shows day, month, year separated by dots.
Startdatum
18032026
Install
1npx stylexblocks add date-inputSource
components/ui/base-ui/date-input.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732import { createContext, useContext, useEffect, useId, useMemo, useRef, useState,} from "react";import { mergeProps } from "@base-ui/react/merge-props";import { useRender } from "@base-ui/react/use-render";import { createSlotRecipeContext } from "#lib/base-ui/create-slot-recipe-context.tsx";import { defineSlotRecipe } from "#lib/recipe-props.ts";import * as stylex from "@stylexjs/stylex";import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
const dateInputRoot = stylex.create({ base: { display: 'flex', flexDirection: 'column', gap: spacing._1_5, width: '100%', },})
const dateInputLabel = stylex.create({ base: { fontSize: fontSizes.sm, lineHeight: lineHeights.sm, fontWeight: fontWeights.medium, alignSelf: 'flex-start', userSelect: 'none', opacity: { default: null, ':is([data-disabled])': 0.5, }, },})
/** The input-shaped box the segments sit in; mirrors the `input` recipe. */const dateInputControl = stylex.create({ base: { display: 'flex', alignItems: 'center', width: '100%', minWidth: 0, position: 'relative', height: 'var(--input-height)', cursor: { default: 'text', ':is([data-disabled])': 'not-allowed', }, color: semanticColors.fg, opacity: { default: null, ':is([data-disabled])': 0.5, }, '--focus-color': colorPalette.focusRing, '--error-color': semanticColors.borderError, borderColor: { default: null, ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)', }, },})
const dateInputControlSizes = stylex.create({ xs: { borderRadius: semanticRadii.control, paddingInline: spacing._2, '--input-height': sizes.controlXs, fontSize: fontSizes.xs, lineHeight: lineHeights.xs, }, sm: { borderRadius: semanticRadii.control, paddingInline: spacing._2_5, '--input-height': sizes.controlSm, fontSize: fontSizes.sm, lineHeight: lineHeights.sm, }, md: { borderRadius: semanticRadii.control, paddingInline: spacing._3, '--input-height': sizes.controlMd, fontSize: fontSizes.sm, lineHeight: lineHeights.sm, }, lg: { borderRadius: semanticRadii.control, paddingInline: spacing._4_5, '--input-height': sizes.controlLg, fontSize: fontSizes.md, lineHeight: lineHeights.md, }, xl: { borderRadius: semanticRadii.control, paddingInline: spacing._6, '--input-height': sizes.controlXl, fontSize: fontSizes.md, lineHeight: lineHeights.md, },})
const dateInputControlVariants = stylex.create({ outline: { backgroundColor: semanticColors.bg, borderWidth: '1px', borderStyle: 'solid', borderColor: { default: semanticColors.border, ':hover': semanticColors.borderEmphasized, ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)', }, outlineWidth: { default: null, ':focus-within': 'var(--focus-ring-width, 1px)', }, outlineOffset: { default: null, ':focus-within': '0px', }, outlineStyle: { default: null, ':focus-within': 'solid', }, outlineColor: { default: null, ':focus-within': 'var(--focus-color)', }, }, subtle: { backgroundColor: semanticColors.bgMuted, borderWidth: '1px', borderStyle: 'solid', borderColor: { default: 'transparent', ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)', }, outlineWidth: { default: null, ':focus-within': 'var(--focus-ring-width, 1px)', }, outlineOffset: { default: null, ':focus-within': '0px', }, outlineStyle: { default: null, ':focus-within': 'solid', }, outlineColor: { default: null, ':focus-within': 'var(--focus-color)', }, }, flushed: { backgroundColor: 'transparent', borderRadius: 0, paddingInline: 0, borderBottomWidth: '1px', borderBottomStyle: 'solid', borderBottomColor: { default: semanticColors.border, ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)', ':focus-within': 'var(--focus-color)', }, boxShadow: { default: null, ':focus-within': '0px 1px 0px 0px var(--focus-color)', }, },})
const dateInputSegmentGroup = stylex.create({ base: { display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums', },})
const dateInputSegment = stylex.create({ base: { display: 'inline-block', paddingInline: '1px', borderRadius: semanticRadii.l1, outline: 'none', textAlign: 'end', caretColor: 'transparent', userSelect: 'none', fontVariantNumeric: 'tabular-nums', color: { default: semanticColors.fg, ':is([data-placeholder-shown]):not(:focus)': semanticColors.fgMuted, ':is([data-type="literal"])': semanticColors.fgMuted, ':focus': colorPalette.contrast, }, backgroundColor: { default: null, ':focus': colorPalette.solid, }, },})
export type DateInputSize = keyof typeof dateInputControlSizes
export type DateInputVariant = keyof typeof dateInputControlVariants
const dateInputRecipe = defineSlotRecipe({ slots: { root: { styles: dateInputRoot }, label: { styles: dateInputLabel }, control: { styles: dateInputControl, sizes: dateInputControlSizes, variants: dateInputControlVariants, }, segmentGroup: { styles: dateInputSegmentGroup }, segment: { styles: dateInputSegment }, }, defaultVariants: { size: "md", variant: "outline" },});
export type DateSegmentType = "year" | "month" | "day";
export interface DateSegment { type: DateSegmentType | "literal"; /** Displayed text: the padded value, the typed digits, or the placeholder. */ text: string; value?: number; minValue?: number; maxValue?: number; isPlaceholder: boolean; placeholder: string; isEditable: boolean;}
type Fields = Record<DateSegmentType, number | null>;
const EMPTY: Fields = { year: null, month: null, day: null };const PLACEHOLDER: Record<DateSegmentType, string> = { year: "yyyy", month: "mm", day: "dd" };const LABEL: Record<DateSegmentType, string> = { year: "year", month: "month", day: "day" };const DIGITS: Record<DateSegmentType, number> = { year: 4, month: 2, day: 2 };
const daysInMonth = (year: number | null, month: number | null) => month == null ? 31 : new Date(year ?? 2000, month, 0).getDate();
function range(type: DateSegmentType, f: Fields): [number, number] { if (type === "year") return [1, 9999]; if (type === "month") return [1, 12]; return [1, daysInMonth(f.year, f.month)];}
const fieldsFromDate = (date: Date | null | undefined): Fields => date ? { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate() } : EMPTY;
function dateFromFields(f: Fields): Date | null { if (f.year == null || f.month == null || f.day == null) return null; const date = new Date(f.year, f.month - 1, Math.min(f.day, daysInMonth(f.year, f.month))); date.setFullYear(f.year); // years < 100 would otherwise map to 19xx return date;}
const sameDate = (a: Date | null | undefined, b: Date | null | undefined) => a == null || b == null ? a == b : a.getTime() === b.getTime();
type LayoutPart = { type: DateSegmentType } | { type: "literal"; text: string };
/** Segment order and literals for the locale, e.g. `mm/dd/yyyy` or `dd.mm.yyyy`. */function localeLayout(locale: string): LayoutPart[] { const parts = new Intl.DateTimeFormat(locale, { year: "numeric", month: "2-digit", day: "2-digit", }).formatToParts(new Date(2000, 0, 1)); return parts.flatMap((part): LayoutPart[] => part.type === "year" || part.type === "month" || part.type === "day" ? [{ type: part.type as DateSegmentType }] : part.type === "literal" ? [{ type: "literal" as const, text: part.value }] : [], );}
const toIso = (date: Date | null) => date ? `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}` : "";
const dataAttr = (on: boolean | undefined) => (on ? "" : undefined);
export interface DateInputValueChangeDetails { value: Date | null;}
interface DateInputState { segments: DateSegment[]; disabled: boolean; readOnly: boolean; invalid: boolean; labelId: string; groupId: string; value: Date | null; name?: string; setField: (type: DateSegmentType, value: number | null) => void; typed: { type: DateSegmentType; text: string } | null; setTyped: (typed: { type: DateSegmentType; text: string } | null) => void; fields: Fields;}
const DateInputContext = createContext<DateInputState | null>(null);
function useDateInput() { const ctx = useContext(DateInputContext); if (!ctx) throw new Error("DateInput parts must be rendered inside <DateInput.Root>"); return ctx;}
export type DateInputRootOwnProps = { /** Controlled date (null when incomplete or cleared). */ value?: Date | null; /** Initial date when uncontrolled. */ defaultValue?: Date | null; /** Fires with a Date once every segment is filled, and with null when one is cleared. */ onValueChange?: (details: DateInputValueChangeDetails) => void; /** BCP 47 locale driving segment order and separators. */ locale?: string; disabled?: boolean; readOnly?: boolean; invalid?: boolean; /** Form field name; the hidden input carries an ISO `yyyy-mm-dd` value. */ name?: string;};
function RootNode({ render, value, defaultValue = null, onValueChange, locale = "en-US", disabled = false, readOnly = false, invalid = false, name, ...rest}: Omit<useRender.ComponentProps<"div">, "defaultValue"> & DateInputRootOwnProps) { const [fields, setFields] = useState<Fields>(() => fieldsFromDate(value !== undefined ? value : defaultValue), ); const [typed, setTyped] = useState<DateInputState["typed"]>(null); const emitted = useRef<Date | null>(value !== undefined ? value : defaultValue); const onChange = useRef(onValueChange); onChange.current = onValueChange;
// controlled: adopt outside changes, but keep partially typed fields when // the parent just echoes back the null we emitted useEffect(() => { if (value === undefined || sameDate(value, emitted.current)) return; emitted.current = value; setFields(fieldsFromDate(value)); }, [value]);
const uid = useId(); const layout = useMemo(() => localeLayout(locale), [locale]);
const ctx = useMemo<DateInputState>(() => { const segments: DateSegment[] = layout.map((part) => { if (part.type === "literal") { return { type: "literal", text: part.text, isPlaceholder: false, placeholder: part.text, isEditable: false, }; } const current = fields[part.type]; const [minValue, maxValue] = range(part.type, fields); const typing = typed?.type === part.type ? typed.text : null; const text = typing ?? (current == null ? PLACEHOLDER[part.type] : String(current).padStart(DIGITS[part.type], "0")); return { type: part.type, text, value: current ?? undefined, minValue, maxValue, isPlaceholder: current == null && typing == null, placeholder: PLACEHOLDER[part.type], isEditable: !disabled && !readOnly, }; }); return { segments, disabled, readOnly, invalid, labelId: `${uid}-label`, groupId: `${uid}-group`, value: dateFromFields(fields), name, typed, setTyped, fields, setField: (type, next) => { const merged = { ...fields, [type]: next }; // keep the day inside the (possibly shorter) month if (merged.day != null) { merged.day = Math.min(merged.day, daysInMonth(merged.year, merged.month)); } setFields(merged); const date = dateFromFields(merged); if (!sameDate(date, emitted.current)) { emitted.current = date; onChange.current?.({ value: date }); } }, }; }, [layout, fields, typed, disabled, readOnly, invalid, uid, name]);
const element = useRender({ defaultTagName: "div", render: render as useRender.RenderProp, props: mergeProps( { "data-disabled": dataAttr(disabled), "data-readonly": dataAttr(readOnly), "data-invalid": dataAttr(invalid), }, rest, ), }); return <DateInputContext.Provider value={ctx}>{element}</DateInputContext.Provider>;}
function segmentEls(from: Element) { const group = from.closest("[data-date-input-group]"); return group ? Array.from(group.querySelectorAll<HTMLElement>('[role="spinbutton"]')) : [];}
function focusSibling(from: HTMLElement, delta: number) { const els = segmentEls(from); els[els.indexOf(from) + delta]?.focus();}
function LabelNode({ render, ...rest }: useRender.ComponentProps<"span">) { const ctx = useDateInput(); return useRender({ defaultTagName: "span", render: render as useRender.RenderProp, props: mergeProps( { id: ctx.labelId, "data-disabled": dataAttr(ctx.disabled), "data-invalid": dataAttr(ctx.invalid), onClick: () => { if (ctx.disabled) return; const group = document.getElementById(ctx.groupId); group?.querySelector<HTMLElement>('[role="spinbutton"]')?.focus(); }, }, rest, ), });}
function ControlNode({ render, ...rest }: useRender.ComponentProps<"div">) { const ctx = useDateInput(); return useRender({ defaultTagName: "div", render: render as useRender.RenderProp, props: mergeProps( { "data-disabled": dataAttr(ctx.disabled), "data-readonly": dataAttr(ctx.readOnly), "data-invalid": dataAttr(ctx.invalid), // clicking the box (not a segment) focuses the first empty segment onMouseDown: (event: React.MouseEvent<HTMLDivElement>) => { if (ctx.disabled || event.target !== event.currentTarget) return; event.preventDefault(); const els = Array.from( event.currentTarget.querySelectorAll<HTMLElement>('[role="spinbutton"]'), ); (els.find((el) => el.hasAttribute("data-placeholder-shown")) ?? els[0])?.focus(); }, }, rest, ), });}
function SegmentNode({ render, ref, segment, ...rest}: useRender.ComponentProps<"span"> & { segment: DateSegment }) { const ctx = useDateInput(); const localRef = useRef<HTMLSpanElement>(null); const type = segment.type; const editable = type !== "literal" && segment.isEditable;
const typeDigit = (digit: string) => { if (type === "literal") return; const [min, max] = range(type, ctx.fields); let text = (ctx.typed?.type === type ? ctx.typed.text : "") + digit; if (Number(text) > max) text = digit; const num = Number(text); const done = text.length >= DIGITS[type] || num * 10 > max; ctx.setField(type, num >= min ? num : null); if (done) { ctx.setTyped(null); if (localRef.current) focusSibling(localRef.current, 1); } else { ctx.setTyped({ type, text }); } };
// Mobile keyboards send text through `beforeinput` (keydown reports // "Unidentified"); the segment is contentEditable only to summon them, so // every native edit is cancelled and digits are fed to the typing logic. const typeRef = useRef(typeDigit); typeRef.current = typeDigit; useEffect(() => { const el = localRef.current; if (!el || !editable) return; const onBeforeInput = (event: InputEvent) => { event.preventDefault(); for (const ch of event.data ?? "") if (/\d/.test(ch)) typeRef.current(ch); }; el.addEventListener("beforeinput", onBeforeInput); return () => el.removeEventListener("beforeinput", onBeforeInput); }, [editable]);
const step = (delta: number) => { if (type === "literal") return; const [min, max] = range(type, ctx.fields); const today = new Date(); const fallback = type === "year" ? today.getFullYear() : type === "month" ? today.getMonth() + 1 : today.getDate(); const current = ctx.fields[type]; const next = current == null ? Math.min(fallback, max) : ((current - min + delta + (max - min + 1)) % (max - min + 1)) + min; ctx.setTyped(null); ctx.setField(type, next); };
const internal = type === "literal" ? { "aria-hidden": true, "data-type": "literal", children: segment.text } : { role: "spinbutton", tabIndex: ctx.disabled ? undefined : 0, contentEditable: editable, suppressContentEditableWarning: true, spellCheck: false, autoCorrect: "off", autoComplete: "off", inputMode: editable ? ("numeric" as const) : undefined, enterKeyHint: "next" as const, "aria-label": LABEL[type], "aria-valuenow": segment.value, "aria-valuemin": segment.minValue, "aria-valuemax": segment.maxValue, "aria-valuetext": segment.isPlaceholder ? "Empty" : segment.text, "aria-disabled": ctx.disabled || undefined, "aria-readonly": ctx.readOnly || undefined, "aria-invalid": ctx.invalid || undefined, "data-type": type, "data-value": segment.value, "data-placeholder-shown": dataAttr(segment.isPlaceholder), "data-disabled": dataAttr(ctx.disabled), "data-readonly": dataAttr(ctx.readOnly), "data-editable": dataAttr(editable), children: segment.text, onBlur: () => { if (ctx.typed?.type === type) ctx.setTyped(null); }, onPaste: (event: React.ClipboardEvent) => event.preventDefault(), onDrop: (event: React.DragEvent) => event.preventDefault(), onKeyDown: (event: React.KeyboardEvent<HTMLSpanElement>) => { if (event.ctrlKey || event.metaKey || event.altKey) return; const el = event.currentTarget; switch (event.key) { case "ArrowLeft": event.preventDefault(); focusSibling(el, -1); return; case "ArrowRight": event.preventDefault(); focusSibling(el, 1); return; case "Tab": case "Enter": return; } if (!editable) return; switch (event.key) { case "ArrowUp": event.preventDefault(); step(1); return; case "ArrowDown": event.preventDefault(); step(-1); return; case "PageUp": event.preventDefault(); step(type === "year" ? 10 : type === "month" ? 3 : 7); return; case "PageDown": event.preventDefault(); step(type === "year" ? -10 : type === "month" ? -3 : -7); return; case "Backspace": case "Delete": { event.preventDefault(); const typing = ctx.typed?.type === type ? ctx.typed.text : null; if (typing && typing.length > 1) { const text = typing.slice(0, -1); ctx.setTyped({ type, text }); ctx.setField(type, Number(text) >= range(type, ctx.fields)[0] ? Number(text) : null); } else if (ctx.fields[type] != null || typing) { ctx.setTyped(null); ctx.setField(type, null); } else if (event.key === "Backspace") { focusSibling(el, -1); } return; } } if (/^\d$/.test(event.key)) { event.preventDefault(); typeDigit(event.key); } else if (event.key.length === 1) { event.preventDefault(); } }, };
return useRender({ defaultTagName: "span", render: render as useRender.RenderProp, ref: ref ? [ref, localRef] : localRef, props: mergeProps(internal, rest), });}
const { withProvider, withContext } = createSlotRecipeContext(dateInputRecipe);
const Segment = withContext(SegmentNode, "segment", "DateInputSegment");
function SegmentGroupNode({ render, children, ...rest }: useRender.ComponentProps<"div">) { const ctx = useDateInput(); return useRender({ defaultTagName: "div", render: render as useRender.RenderProp, props: mergeProps( { id: ctx.groupId, role: "group", "aria-labelledby": ctx.labelId, "data-date-input-group": "", "data-disabled": dataAttr(ctx.disabled), "data-invalid": dataAttr(ctx.invalid), style: { unicodeBidi: "isolate" }, children: children ?? ctx.segments.map((segment, i) => <Segment key={i} segment={segment} />), }, rest, ), });}
function HiddenInputNode(props: Omit<React.ComponentProps<"input">, "type" | "value">) { const ctx = useDateInput(); return ( <input type="hidden" name={ctx.name} value={toIso(ctx.value)} {...props} /> );}
/** Render-prop access to the segments and value, like Ark's `DateInput.Context`. */function DateInputContextConsumer({ children,}: { children: (api: { segments: DateSegment[]; value: Date | null }) => React.ReactNode;}) { const ctx = useDateInput(); return <>{children({ segments: ctx.segments, value: ctx.value })}</>;}
/** * DateInput — a segmented date field. Base UI ships no date-input * primitive, so Root owns the month / day / year fields (controlled via * `value`/`onValueChange` with a `Date`, or uncontrolled via * `defaultValue`) and lays the segments out in `locale` order via * `Intl.DateTimeFormat#formatToParts`. Each segment is a * `role="spinbutton"`: ArrowUp/Down step (wrapping), digits type in and * auto-advance, Backspace clears, ArrowLeft/Right move between segments. * `<DateInput.Root variant size>` resolves the recipe once; every part * inherits it through context. SegmentGroup renders the segments by * default. Composition per part via `render`. */export const DateInput = { Root: withProvider(RootNode, "root", "DateInputRoot"), Label: withContext(LabelNode, "label", "DateInputLabel"), Control: withContext(ControlNode, "control", "DateInputControl"), SegmentGroup: withContext(SegmentGroupNode, "segmentGroup", "DateInputSegmentGroup"), Segment, HiddenInput: HiddenInputNode, Context: DateInputContextConsumer,};
export type DateInputRootProps = React.ComponentProps<typeof DateInput.Root>;export type DateInputControlProps = React.ComponentProps<typeof DateInput.Control>;export type DateInputSegmentProps = React.ComponentProps<typeof DateInput.Segment>;