Elements
DatePicker
A date picker sets a date from a Calendar that opens from the app’s trigger: a due date, a birthday,
with range the days of a trip, with timePrecision a date and a time of day. Like Select, it opens as
each device expects:
import { type JSX, mount, signal, Text, View } from "nsh";
import { DatePicker, type DatePickerValue, type DateRangePreset, type HourCycle, type OpenChangeReason } from "nsh/base";
import { desktop, Log, Panel, Segmented, size, Split, ui, wide, sectionSurface, controlSize, clearButtonLook, datePickerLook, DateTrigger } from "./palette";
// Three date pickers in a card: a due date (weekends disabled, presets
// beside the calendar, a clear button), a stay picked as a range over two
// months in a wide window, and a meeting's date and time with the hours
// on the clock the inspector picks. The look is the shared listbox look,
// after shadcn/ui's date picker: the trigger (`DateTrigger`) led by a
// calendar, the value or a muted placeholder, and `datePickerLook` for the
// rest: the popup at the trigger (a sheet on a touch screen), the items
// (`CalendarItem`: the month and year, two-letter weekdays, today on a quiet
// fill, the selected days on `primary`, a range's band), the presets, and
// the time's row, segments and well.
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
/** A day's ISO date (`"2026-10-28"`), in local time as the calendar's days are. */
const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
const addDays = (d: Date, days: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + days);
/** An ISO date's month and day: `Oct 28`. */
const monthDay = (value: string) => `${MONTHS[Number(value.slice(5, 7)) - 1].slice(0, 3)} ${Number(value.slice(8, 10))}`;
/** A time `"HH:MM"` on the picked clock: `14:30`, or `2:30 PM`. */
function clock(time: string, cycle: HourCycle) {
if (cycle === "h23") return time;
const hour = Number(time.slice(0, 2));
return `${hour % 12 === 0 ? 12 : hour % 12}:${time.slice(3, 5)} ${hour < 12 ? "AM" : "PM"}`;
}
/** A trigger's width: set with a pointer, the field's on a touch screen. */
const trigger = desktop ? { width: 260 } : undefined;
/** A label over its control, a quieter line under the label. */
function Field(props: { label: string; detail: string; children: JSX.Element }) {
return (
<View style={{ gap: 8 }}>
<View style={{ gap: 2 }}>
<Text style={{ fontSize: size.label, fontWeight: "500", color: ui().text }}>{props.label}</Text>
<Text style={{ fontSize: size.detail, color: ui().muted }}>{props.detail}</Text>
</View>
{props.children}
</View>
);
}
function App() {
const due = signal<string | null>(null);
const stay = signal<DatePickerValue>(null);
const meeting = signal<string | null>(null);
const cycle = signal<HourCycle>("h12");
const dueOpen = signal(false);
const stayOpen = signal(false);
const meetingOpen = signal(false);
const events = signal<string[]>([]);
const log = (line: string) => events.set([line, ...events()].slice(0, 8));
const opened = (open: (next: boolean) => void) => ({ open: next }: { open: boolean; reason: OpenChangeReason }) => open(next);
// The presets from today.
const today = new Date();
const monday = addDays(today, ((8 - today.getDay()) % 7) || 7);
const dues: DateRangePreset[] = [
{ label: "Today", value: iso(today) },
{ label: "Tomorrow", value: iso(addDays(today, 1)) },
{ label: "Next Monday", value: iso(monday) },
];
const stays: DateRangePreset[] = [
{ label: "This week", value: [iso(today), iso(addDays(today, (7 - today.getDay()) % 7))] },
{ label: "Next 7 nights", value: [iso(today), iso(addDays(today, 7))] },
];
const stayTitle = () => {
const r = stay();
return Array.isArray(r) && r[0] && r[1] ? `${monthDay(r[0])} – ${monthDay(r[1])}, ${r[1].slice(0, 4)}` : undefined;
};
const meetingTitle = () => {
const v = meeting();
return v ? `${monthDay(v)}, ${v.slice(0, 4)} · ${clock(v.slice(11, 16), cycle())}` : undefined;
};
return (
<View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
<Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>date-picker</Text>
<Text style={{ color: ui().muted }}>
{desktop ? "Arrows move between days, Return picks; the trigger takes Delete to clear" : "Tap a day; the meeting's time takes digits"}
</Text>
<Split
gap={14}
inspector={
<>
<Panel title="value">
<Text style={{ fontSize: 13, color: ui().text }}>{`due ${JSON.stringify(due())}`}</Text>
<Text style={{ fontSize: 13, color: ui().text }}>{`stay ${JSON.stringify(stay())}`}</Text>
<Text style={{ fontSize: 13, color: ui().text }}>{`meeting ${JSON.stringify(meeting())}`}</Text>
</Panel>
<Segmented label="hourCycle" options={["h12", "h23"] as const} value={cycle()} onChange={(v) => cycle.set(v)} />
<Log title="onChange" lines={events()} minHeight={120} />
</>
}
>
<View style={{ ...sectionSurface({ padded: true }), gap: 20 }}>
<Field label="Due" detail="Weekdays only, presets beside the calendar, a clear button">
<DatePicker
value={due()}
onChange={({ value }) => {
due.set(typeof value === "string" ? value : null);
log(`Due → ${JSON.stringify(value)}`);
}}
onOpenChange={opened((next) => dueOpen.set(next))}
accessibilityLabel="Due"
disabledMatcher={[0, 6]}
presets={dues}
{...datePickerLook()}
style={trigger}
cleanable
clearButtonAccessibilityLabel="Clear the due date"
{...clearButtonLook({ over: true })}
trigger={<DateTrigger title={due() ? `${monthDay(due()!)}, ${due()!.slice(0, 4)}` : "No due date"} placeholder={!due()} open={dueOpen()} clearable={due() !== null} style={trigger} />}
/>
</Field>
<Field label="Stay" detail={wide() ? "A range over two months: the first press starts it" : "A range: the first press starts it, the second ends it"}>
<DatePicker
range
value={stay()}
onChange={({ value }) => {
stay.set(value);
log(`Stay → ${JSON.stringify(value)}`);
}}
onOpenChange={opened((next) => stayOpen.set(next))}
accessibilityLabel="Stay"
numberOfMonths={wide() ? 2 : 1}
firstDayOfWeek={1}
presets={stays}
{...datePickerLook({ months: () => (wide() ? 2 : 1), firstDayOfWeek: 1 })}
trigger={<DateTrigger title={stayTitle() ?? "Check-in – check-out"} placeholder={!stayTitle()} open={stayOpen()} style={trigger} />}
/>
</Field>
<Field label="Meeting" detail={desktop ? "A day, then its time; the day again closes the calendar" : "A tap picks the day; open it again for the time"}>
<DatePicker
value={meeting()}
onChange={({ value }) => {
meeting.set(typeof value === "string" ? value : null);
log(`Meeting → ${JSON.stringify(value)}`);
}}
onOpenChange={opened((next) => meetingOpen.set(next))}
accessibilityLabel="Meeting"
timePrecision="minute"
hourCycle={cycle()}
defaultTime="09:00"
{...datePickerLook()}
timeLabel={<Text style={{ fontSize: controlSize.label, color: ui().muted }}>Time</Text>}
timeAccessibilityLabel="Meeting time"
trigger={<DateTrigger title={meetingTitle() ?? "Not scheduled"} placeholder={!meetingTitle()} open={meetingOpen()} style={trigger} />}
/>
</Field>
</View>
</Split>
</View>
);
}
mount(App);- On the desktops and in desktop browsers, a popup at the trigger; opening it puts the keyboard on the days.
- On phones and tablets, a sheet at the bottom of the screen over a backdrop.
The picker owns the behavior: the value (the app’s, or its own), the open state, the calendar, the time, the presets, the keyboard and what screen readers hear. The look is the app’s: it draws the trigger (with the value, a placeholder, an icon) and styles the popup, the calendar’s parts, the presets and the time field.
use chrono::NaiveDate;
use nsh_base::{DateRangePreset, DateTime, PickedDate, date_picker, theme};
use nsh_core::prelude::*;
fn trip_dates() -> impl IntoElement {
let trip = signal(DateTime::Range(None, None));
let title = move || {
trip.get()
.format("%b %-d")
.map(|s| s.to_string())
.unwrap_or_else(|| "Pick dates".to_string())
};
let day = |m, d| NaiveDate::from_ymd_opt(2026, m, d).unwrap();
date_picker()
.range(true)
.number_of_months(2)
.value(move || trip.get())
.on_change(move |next: &PickedDate| trip.set(next.value))
.presets(vec![
DateRangePreset::range("This week", day(10, 25), day(10, 31)),
DateRangePreset::range("Next week", day(11, 1), day(11, 7)),
])
.accessibility_label("Trip")
.offset(px(4.0))
.popup_style(|s| {
s.p_3()
.rounded_lg()
.border_1()
.border_color(move || theme().border)
.bg(move || theme().popover)
.shadow_md()
})
.trigger(
view()
.h_9()
.w_56()
.px_3()
.justify_center()
.rounded_md()
.border_1()
.border_color(move || theme().input)
.child(text(title)),
)
}import { mount, signal, Text, View } from "nsh";
import { DatePicker, type DatePickerValue } from "nsh/base";
function App() {
const due = signal<DatePickerValue>(null);
return (
<DatePicker
value={due()}
onChange={({ value }) => due.set(value)}
timePrecision="minute"
cleanable
clearButton={<Text>×</Text>}
clearButtonAccessibilityLabel="Clear the due date"
presets={[{ label: "Tomorrow 9:00", value: "2026-10-29T09:00" }]}
accessibilityLabel="Due"
offset={4}
popupClass="rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-md"
backdropClass="bg-black/40"
contentClass="flex-row gap-3"
presetClass="rounded-md px-2 py-1.5 text-sm hover:bg-accent"
headerClass="flex-row items-center justify-between"
rowClass="flex-row justify-between"
itemClass="h-8 min-w-8 items-center justify-center rounded-md text-sm focus-visible:ring-2 focus-visible:ring-ring selected:bg-primary selected:text-primary-foreground disabled:opacity-50"
timeClass="mt-2 gap-3"
timeLabel={<Text class="text-sm">Time</Text>}
timeAccessibilityLabel="Due time"
timeFieldClass="flex-row rounded-md border border-input px-2 py-1"
segmentClass="text-sm tabular-nums focus:bg-accent"
trigger={
<View class="h-9 w-56 justify-center rounded-md border border-input px-3 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring">
<Text>{typeof due() === "string" ? (due() as string).replace("T", " ") : "Pick a date"}</Text>
</View>
}
/>
);
}
mount(App);DatePicker comes from nsh/base, the nsh-base crate in Rust. In Rust, date_picker()
makes one with a setter per prop (.value(..), .range(..), .time_precision(..)) and a listener per event
(.on_change(..)). Its value is a DateTime (DateTime::Single, DateTime::Range, from chrono dates or dates and
times); onChange gives a PickedDate, the value with the picker’s time precision.
#Value
The value is in the forms of the HTML inputs: an ISO date, "2026-10-28", as <input type="date">’s; with range
[start, end]; with timePrecision a date and time, "2026-10-28T09:30" ("2026-10-28T09:30:15" at seconds), as
<input type="datetime-local">’s; null is none. With value, the app owns it: the picker shows it and reports each
change with onChange({ value }); the app sets value to follow it. Left out, the picker keeps its own value, from
defaultValue at first.
- A single date: a press on a day sets the value and closes the popup.
- With
range, the first press starts the range and the second ends it, as a calendar’s; the complete range sets the value and closes the popup. - With
timePrecision(a single date only), a time field shows under the calendar and every edit of the time is reported. On the desktops, picking a day keeps the popup open for the time and reports the date with its time; a press on the selected day again closes the popup. On phones and tablets, a tap on a day picks it at its time and closes the sheet, as a single date does; the sheet opens again for the time. A day picked before any time getsdefaultTime(default00:00).hourCycleis how the field counts the hours, as TimeField’s, the user’s included.
cleanable adds a clear button while there is a value: a press clears it (onChange({ value: null })). It comes
after the trigger, not inside it, so a press on it never opens the popup; the app places it and fills it
(clearButton), as a select’s clear button.
#Presets
presets are buttons beside the calendar that set the value: “Today”, “Last 7 days”, “Tomorrow at 9”. Each is
{ label, value }, value a date, a range or dates and times, kept as given; a press sets it and closes the popup.
contentClass lays out the presets’ column and the calendar with the time (a row, flex-row); presetsClass styles
the column, presetClass each button.
#The calendar
Every prop of Calendar but its value passes on to the picker’s: numberOfMonths, firstDayOfWeek,
disabledMatcher, yearRange, previousAccessibilityLabel, nextAccessibilityLabel, the parts (headerClass to
itemStyle) and renderItem. calendarClass and calendarStyle style the calendar itself. Its views and keys are a
calendar’s.
The time row (timeClass, timeStyle) holds timeLabel, the app’s words for it (“Time”), at its start and the time
field (timeFieldClass, timeFieldStyle, timeAccessibilityLabel) at its end: a row with its items centered and
spread apart (flex-row items-center justify-between, as gpui-component’s). The field’s segments are a
TimeField’s (segmentClass, separatorClass, renderSegment).
#Entrance and exit
On the desktops the popup comes and goes with your transitions, as a Popover’s:
popupStartingClass is its look in its first frame, and the transition-* classes of popupClass carry it to its own
look; popupEndingClass is its look once closed, which it keeps, taking no presses, while those transitions run, and
onClose follows. The keyboard focus is back on the trigger as it closes, unless the choice’s onChange focused
another view (the next field of a form), which keeps it. Opened again on its way out, it returns to its look from where
it is. popupStartingStyle and popupEndingStyle do the same with inline styles. When the user asks for less motion it
appears and goes at once; the sheet of touch screens slides in and out on its own.
<DatePicker
popupClass="rounded-lg bg-popover p-3 shadow-md transition-all duration-150 ease-out"
popupStartingClass="opacity-0 -translate-y-1"
popupEndingClass="opacity-0"
trigger={<DateTrigger />}
/>
#Props
| Prop | Rust | Type | Default | Description |
|---|---|---|---|---|
value |
.value(..) |
DatePickerValue |
none | The value, owned by the app. |
defaultValue |
.default_value(..) |
DatePickerValue |
null |
The value at first, without value. |
range |
.range(..) |
boolean |
false |
Pick a range of dates. |
open, defaultOpen |
.open(..), .default_open(..) |
boolean |
false |
The open state, the app’s or the picker’s own. |
disabled |
.disabled(..) |
boolean |
false |
It stays closed and takes no presses or keyboard focus. |
accessibilityLabel |
.accessibility_label(..) |
string |
none | What screen readers call it. |
dateFormat |
.date_format(..) |
string |
"%Y/%m/%d" and the time |
How screen readers hear the value, in chrono’s format. |
timePrecision |
.time_precision(..) |
"minute" | "second" |
none | Edit the time of day too, down to this. |
hourCycle |
.hour_cycle(..) |
"h23" | "h12" |
"h23" |
How the time field counts the hours. |
defaultTime |
.default_time(..) |
string |
"00:00" |
The time a date gets before the user sets one. |
cleanable |
.cleanable(..) |
boolean |
false |
A clear button while there is a value. |
presets |
.presets(..) |
DateRangePreset[] |
[] |
Buttons in the popup that set the value. |
numberOfMonths, firstDayOfWeek, disabledMatcher, yearRange |
as Calendar’s |
as Calendar’s |
as Calendar’s |
The calendar’s months, weeks, disabled dates and years. |
previousAccessibilityLabel, nextAccessibilityLabel |
as Calendar’s |
string |
none | What screen readers say for the calendar’s Previous and Next. |
placement, align, offset, margin |
.placement(..), … |
as Select’s |
"bottom", "start", 0, 0 |
Desktops: where the popup goes against the trigger. |
popupClass, popupStyle |
.popup_class(..), .popup_style(..) |
string, StyleProp<ViewStyle> |
none | The popup (desktops) or the sheet (touch screens). |
popupStartingClass, popupStartingStyle |
.popup_starting_class(..), .popup_starting_style(..) |
string, StyleProp<ViewStyle> |
none | Desktops: the popup’s look in its first frame, over its own: its transitions run from it. |
popupEndingClass, popupEndingStyle |
.popup_ending_class(..), .popup_ending_style(..) |
string, StyleProp<ViewStyle> |
none | Desktops: the popup’s look once closed, over its own: it stays while its transitions run. |
backdropClass, backdropStyle |
.backdrop_class(..), .backdrop_style(..) |
string, StyleProp<ViewStyle> |
none | The backdrop behind the sheet. |
contentClass, contentStyle |
.content_class(..), .content_style(..) |
string, StyleProp<ViewStyle> |
none | The popup’s content: the presets beside the calendar and the time. |
presetsClass, presetsStyle |
.presets_class(..), .presets_style(..) |
string, StyleProp<ViewStyle> |
none | The presets’ column. |
presetClass, presetStyle |
.preset_class(..), .preset_style(..) |
string, StyleProp<TextStyle> |
none | Each preset’s button. |
calendarClass, calendarStyle |
.calendar_class(..), .calendar_style(..) |
string, StyleProp<ViewStyle> |
none | The calendar. |
headerClass … itemStyle |
as Calendar’s |
as Calendar’s |
none | The calendar’s header, body, months, rows and items. |
renderItem |
.render_item(..) |
(item: CalendarEntry) => JSX.Element |
none | Each item of the calendar, drawn by the app from what it is; its states are the items’ classes, as Calendar’s. |
timeClass, timeStyle |
.time_class(..), .time_style(..) |
string, StyleProp<ViewStyle> |
none | The time’s row: its label at the start, the field at the end. |
timeLabel |
.time_label(..) |
JSX.Element |
none | What the time’s row shows before the field. |
timeFieldClass, timeFieldStyle |
.time_field_class(..), .time_field_style(..) |
string, StyleProp<ViewStyle> |
none | The time field. |
timeAccessibilityLabel |
.time_accessibility_label(..) |
string |
none | What screen readers call the time field. |
segmentClass, segmentStyle, separatorClass, separatorStyle, renderSegment |
as TimeField’s |
as TimeField’s |
none | The time field’s segments and :. |
clearButtonClass, clearButtonStyle |
.clear_button_class(..), .clear_button_style(..) |
string, StyleProp<ViewStyle> |
none | The clear button (cleanable). |
clearButton |
.clear_button(..) |
JSX.Element |
none | The content of the clear button. |
clearButtonAccessibilityLabel |
.clear_button_accessibility_label(..) |
string |
none | What screen readers call the clear button. |
trigger |
.trigger(..) |
JSX.Element |
none | What opens the popup when pressed; the popup is placed against it. |
class, style |
style methods | string, StyleProp<ViewStyle> |
none | The view around the trigger. |
#Events
| Event | Rust | Description |
|---|---|---|
onChange |
.on_change(|value| ..) |
The value changed (a day, a range’s end, a preset, the time, the clear button): { value }. Set value to follow it. |
onOpenChange |
.on_open_change(|e| ..) |
The popup opened or closed, with why ({ open, reason }). Set open to follow it. |
onOpen, onClose |
.on_open(..), .on_close(..) |
The popup is shown, or gone. |
onCancel |
.on_cancel(..) |
The user closed the popup without a choice (Escape or back, a press outside or on the backdrop). |
#Parts
| Part | Where | Styled with |
|---|---|---|
| The trigger | the picker’s view | the app’s own element (trigger) |
| The clear button | the picker’s view, after the trigger (cleanable, while there is a value) |
clearButtonClass, clearButtonStyle; its content clearButton |
| The popup or sheet | over everything, at the trigger (desktops) or at the bottom (touch screens) | popupClass, popupStyle |
| The backdrop | behind the sheet (touch screens) | backdropClass, backdropStyle |
| The content | the popup | contentClass, contentStyle |
| The presets | the content, first (presets) |
presetsClass, presetsStyle; each presetClass, presetStyle |
| The calendar | the content | calendarClass, calendarStyle, and Calendar’s parts |
| The time’s row | under the calendar (timePrecision) |
timeClass, timeStyle; its label timeLabel |
| The time field | the time’s row | timeFieldClass, timeFieldStyle, and TimeField’s parts |
#Keyboard
| Key | Action |
|---|---|
| Return (on the trigger) | Opens the popup, or closes it. |
| Delete, Backspace (on the trigger) | Clears the value while the popup is closed. |
| Escape | Closes the popup without a choice. |
In the popup, the calendar’s keys move between days and pick one (see Keyboard) and the time field’s edit the time (see Keyboard).
#Accessibility
- The trigger is a combobox for screen readers: its label is
accessibilityLabel, its value the date asdateFormatwrites it (by default2026/10/28, with the time attimePrecision), and it says whether the popup is expanded.disableddims it. - The calendar’s days are buttons named by their ISO dates (see Accessibility); the
presets are buttons named by their labels; the time field is named by
timeAccessibilityLabel. - The clear button is a button named by
clearButtonAccessibilityLabel.
See Accessibility for labels, roles and announcements in general.