Elements
TimeField
A time field edits a time of day, a segment at a time: the hour, the minute, with precision="second" the second,
and with hourCycle="h12" AM or PM. A reminder’s time, a meeting’s start, the hours a shop opens. It is the time
under DatePicker’s calendar with timePrecision, on its own in the page.
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);The field owns the behavior: the time (the app’s, or its own), which segment the keys edit, typing and stepping
digits, and what screen readers hear. The look is the app’s: it styles the segments and the : between them, or
draws the segments itself.
use chrono::NaiveTime;
use nsh_base::{HourCycle, TimeFieldSegmentEntry, TimeOfDay, time_field};
use nsh_core::prelude::*;
fn reminder_time() -> impl IntoElement {
let at = signal(TimeOfDay(NaiveTime::from_hms_opt(9, 30, 0).unwrap()));
time_field()
.value(move || Some(at.get()))
.on_change(move |next: &TimeOfDay| at.set(*next))
.hour_cycle(HourCycle::H12)
.accessibility_label("Reminder time")
.segment_class("rounded-sm focus:bg-accent disabled:opacity-50")
.render_segment(|segment: &TimeFieldSegmentEntry| view().px_1().child(text(segment.label.clone())))
}import { mount, signal } from "nsh";
import { TimeField } from "nsh/base";
function App() {
const at = signal("09:30");
return (
<TimeField
value={at()}
onChange={({ value }) => at.set(value)}
hourCycle="h12"
accessibilityLabel="Reminder time"
class="h-9 w-32 flex-row items-center rounded-md border border-input px-2"
segmentClass="rounded-sm px-0.5 text-sm tabular-nums focus:bg-accent focus:text-accent-foreground"
separatorClass="text-sm text-muted-foreground"
/>
);
}
mount(App);TimeField comes from nsh/base, the nsh-base crate in Rust. In Rust, time_field()
makes one with a setter per prop (.value(..), .precision(..), .hour_cycle(..)) and a listener per event
(.on_change(..)). Its time is a TimeOfDay, a chrono::NaiveTime.
#Value
The value is a time of day on a 24-hour clock, as an HTML <input type="time">’s: "HH:MM", or "HH:MM:SS" with
precision="second", whatever hourCycle the field shows. With value, the app owns it: the field shows it and
reports each edit with onChange({ value }); the app sets value to follow it. Left out, the field keeps its own
time, from defaultValue at first (default 00:00).
precision is the smallest unit the field edits, "minute" (the default) or "second". hourCycle is how it counts
the hours: "h23" (the default) from 00 to 23, "h12" from 12 to 11 with an AM/PM segment after the numbers. The
user’s is "h12" where localeSettings().hourCycle is "h11" or "h12", else "h23"
(Regional preferences).
#Editing
One segment is selected; the keys edit it, as gpui-base’s time field:
- Up and Down step the segment by one and wrap around (59 to 00) without carrying into the next segment.
- Digits type into it, two at a time: a digit that cannot start a longer value (a
7in the hour) completes the segment and moves to the next. aandpset AM and PM.- Backspace and Delete reset the segment.
A press on a segment selects it. A press on the selected AM/PM segment switches it, since phones have no a and p
keys. The keys go to one native text field behind the segments, transparent, as an OtpInput’s: on
phones and tablets it brings up the number pad.
#Props
| Prop | Rust | Type | Default | Description |
|---|---|---|---|---|
value |
.value(..) |
string |
none | The time, owned by the app. |
defaultValue |
.default_value(..) |
string |
"00:00" |
The time at first, without value. |
precision |
.precision(..) |
"minute" | "second" |
"minute" |
The smallest unit it edits. |
hourCycle |
.hour_cycle(..) |
"h23" | "h12" |
"h23" |
How it counts the hours; "h12" adds an AM/PM segment. |
disabled |
.disabled(..) |
boolean |
false |
No focus and no editing; disabled: styles apply to the field and its segments. |
accessibilityLabel |
.accessibility_label(..) |
string |
none | What screen readers call the field. |
segmentClass, segmentStyle |
.segment_class(..), .segment_style(..) |
string, StyleProp<TextStyle> |
none | Each segment: focus: on the selected one while the field has the focus, disabled: with the field; with group, its content follows them (group-focus:, group-disabled:). |
separatorClass, separatorStyle |
.separator_class(..), .separator_style(..) |
string, StyleProp<TextStyle> |
none | Each : between the numbers. |
renderSegment |
.render_segment(..) |
(segment: TimeFieldSegmentEntry) => JSX.Element |
none | A segment’s content, drawn by the app from what it shows; its label otherwise. |
class, style |
style methods | string, StyleProp<ViewStyle> |
none | The field, around its segments (a row). |
renderSegment gets a TimeFieldSegmentEntry: segment ("hour", "minute", "second" or "period"), value
(the hour on the field’s clock, the minute or the second; 0 for AM and 1 for PM) and label (two digits, or AM /
PM). It never gets the segment’s state: the segment is focus: while the keys edit it and disabled: with the
field, and with group in segmentClass its content follows with group-focus: and group-disabled:. So a segment
is drawn again only when its value changes; moving between the segments and the focus coming and going draw nothing:
<TimeField
segmentClass="group rounded-sm px-0.5 focus:bg-primary"
renderSegment={(segment) => <Text class="text-sm tabular-nums text-foreground group-focus:text-primary-foreground">{segment.label}</Text>}
/>
#Events
| Event | Rust | Description |
|---|---|---|
onChange |
.on_change(|value| ..) |
The user changed the time: { value }. Set value to follow it. A value the app passes is never reported. |
#Parts
| Part | Where | Styled with |
|---|---|---|
| The field | the root, a row | class, style |
| A segment | the field: hour, minute, second, AM/PM | segmentClass, segmentStyle, renderSegment (group-focus:, group-disabled: inside, under group in segmentClass) |
| A separator | the field, between two numbers | separatorClass, separatorStyle |
#Keyboard
Tab reaches the field with its selected segment. Then:
| Key | Action |
|---|---|
| Left / Right | The segment before or after. |
| Tab / Shift+Tab | The segment after or before; Tab from the last one and Shift+Tab from the first leave the field. |
| Up / Down | Steps the segment by one, wrapping around. |
| 0 to 9 | Types into the segment. |
| A / P | AM or PM. |
| Backspace, Delete | Resets the segment. |
#Accessibility
- The field is a text field named by
accessibilityLabel; screen readers read the time it shows.disableddims it. - Phones and tablets show the number pad.
See Accessibility for labels, roles and announcements in general.