元素
DatePicker
日期選擇器讓使用者從Calendar設定日期,日曆由應用程式的觸發元件開啟:截止日期、生日;加上 range 可選取旅程的日期範圍;加上 timePrecision 可選取日期與時間。與 Select 一樣,它會按各種裝置的慣例開啟:
import { type JSX, mount, signal, Text, View, windowSize } from "nsh";
import { type CalendarEntry, DatePicker, type DatePickerValue, type DateRangePreset, type HourCycle, type OpenChangeReason, type TimeFieldSegmentEntry } from "nsh/base";
import { button, desktop, Icon, Log, Panel, Segmented, size, Split, ui, wide } 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 trigger is the shared button look
// with the value and a chevron that turns while the calendar is open; the
// calendar is a popup at the trigger, a sheet on a touch screen. Every
// item is drawn by `renderItem` (month names, weekday initials, today on a
// quiet fill, the selected days filled, a range's band) and every segment
// of the time by `renderSegment`; the time's label starts its row and the
// field, a well as the number inputs', ends it.
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const WEEKDAYS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
/** 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"}`;
}
/** The text of a control: 13 with a pointer, the touch label size otherwise. */
const controlText = desktop ? 13 : size.label;
/** A day's cell: seven across the popup with a pointer, across a phone's sheet otherwise. */
const cell = desktop ? 32 : 42;
/** The gap between the months of a calendar of two. */
const monthGap = 16;
/**
* On a touch screen the calendar spans the sheet (the window less the sheet's padding), its columns sharing it: the
* header's titles split what Previous and Next leave, so the month and the year meet in the middle, and each month's
* title of two is over its month.
*/
const toggleWidth = () => Math.floor((windowSize().width - 2 * 10) / 2 - cell);
/** A popup at the trigger with a pointer, a sheet at the bottom on a touch screen. */
const surface = () =>
desktop
? { ...ui().card, borderRadius: 12, padding: 8 }
: { ...ui().card, borderTopLeftRadius: 20, borderTopRightRadius: 20, paddingHorizontal: 10, paddingTop: 14, paddingBottom: 30 };
const backdrop = { backgroundColor: "rgba(0,0,0,0.45)" };
/** The popup's layout: presets in a column beside the calendar with a pointer, a row of chips above it on a phone. */
const content = desktop ? { flexDirection: "row" as const, gap: 10 } : { gap: 12 };
const presets = () =>
desktop
? { gap: 2, minWidth: 104, paddingRight: 10, borderRightWidth: 1, borderColor: ui().border }
: { flexDirection: "row" as const, flexWrap: "wrap" as const, gap: 6 };
const preset = () =>
desktop
? { height: 28, paddingHorizontal: 8, borderRadius: 6, justifyContent: "center" as const, fontSize: 13, color: ui().text }
: { height: 34, paddingHorizontal: 12, borderRadius: 17, borderWidth: 1, borderColor: ui().border, justifyContent: "center" as const, fontSize: 14, color: ui().text };
/** The calendar: in the popup with a pointer; across the sheet on a touch screen, as the time's row under it. */
const calendar = desktop ? { padding: 2 } : {};
/** The time's row under a hairline, its label at the start and the field at the end, on the calendar's edges. */
const time = () => ({
gap: 10,
marginTop: 8,
paddingTop: 8,
borderTopWidth: 1,
borderColor: ui().border,
...(desktop ? { paddingHorizontal: 2 } : {}),
});
/** The time's field: a recessed well as the number inputs', with their hover and the keyboard's ring while it edits. */
const timeField = [
desktop ? "h-8 rounded-lg px-2" : "h-11 rounded-xl px-3",
"items-center border border-input bg-field",
"enabled:hover:border-faint focus-within:outline-2 focus-within:outline-info",
].join(" ");
/** The trigger: the shared button's look, the value at the start and a chevron in a lane as wide as it. */
function Trigger(props: { title?: string; placeholder: string; open: boolean; clearable?: boolean }) {
const look = button("secondary", {
style: () => ({
flexDirection: "row",
justifyContent: "space-between",
gap: 8,
...(desktop ? { width: 260 } : {}),
...(props.open ? { borderColor: ui().faint } : {}),
}),
});
return (
<View {...look}>
<Text style={{ numberOfLines: 1, flex: 1, fontSize: controlText, color: props.title ? ui().text : ui().muted }}>
{props.title ?? props.placeholder}
</Text>
{/* With a clear button over the end (`cleanable`), an empty lane as wide as the button in place of the chevron. */}
<View
class="transition-transform duration-150 motion-reduce:transition-none"
style={{
width: props.clearable ? 20 : 10,
height: 20,
alignItems: "center",
justifyContent: "center",
opacity: props.clearable ? 0 : 1,
transform: [{ rotate: props.open ? "270deg" : "90deg" }],
}}
>
<Text style={{ fontSize: 18, color: ui().muted }}>›</Text>
</View>
</View>
);
}
/**
* The calendar's items (`itemClass`): pressed at 70%; `group`, so the
* drawing inside follows the item's states.
*/
const itemClass = "group active:opacity-70";
/**
* An item of the calendar, drawn once from what it is, its states the
* item's classes: Previous and Next as arrows (faint while they take no
* press), the month and year toggles (or each month's title, with `months`
* over one) by name, the open view's toggle in the accent, the weekdays'
* initials, and the days: today on the theme's quiet `accent` fill
* (gpui-component's), the selected date and a range's ends filled, the days
* of a complete range on a band from end to end (`data-range-*`), the other
* months' days and the disabled ones faint, the keyboard's day ringed.
*/
function Item(props: { item: CalendarEntry; months?: number }) {
const kind = props.item.kind;
if (kind === "previous" || kind === "next") {
return (
<View class="group-disabled:opacity-30" style={{ width: cell, height: cell, alignItems: "center", justifyContent: "center" }}>
<Text style={{ fontSize: 20, color: ui().muted }}>{kind === "previous" ? "‹" : "›"}</Text>
</View>
);
}
if (kind === "monthToggle" || kind === "yearToggle") {
// A month's title in a calendar of several takes no press: the month and its year, over the month.
const title = kind === "monthToggle" && (props.months ?? 1) > 1;
return (
<Text
class="text-foreground group-selected:text-brand"
style={{
width: !desktop ? toggleWidth() : title ? 6 * cell + monthGap / 2 : kind === "monthToggle" ? 3 * cell : 2 * cell,
paddingHorizontal: 3,
textAlign: title ? "center" : kind === "monthToggle" ? "right" : "left",
fontSize: size.label,
fontWeight: "600",
}}
>
{title ? `${MONTHS[props.item.value - 1]} ${props.item.year}` : kind === "monthToggle" ? MONTHS[props.item.value - 1] : String(props.item.value)}
</Text>
);
}
if (kind === "weekday") {
return <Text style={{ minWidth: cell, paddingVertical: 4, textAlign: "center", fontSize: 11, color: ui().faint }}>{WEEKDAYS[props.item.value]}</Text>;
}
if (kind === "month" || kind === "year") {
// The month view's months (rows of 3) and the year view's years (rows of 5), as wide as a month; the shown one
// filled.
return (
<View
class="rounded-lg group-selected:bg-brand-fill"
style={{ minWidth: (7 * cell) / (kind === "month" ? 3 : 5), height: cell + 6, alignItems: "center", justifyContent: "center" }}
>
<Text class="text-foreground group-selected:text-on-brand" style={{ fontSize: controlText }}>
{kind === "month" ? MONTHS[props.item.value - 1].slice(0, 3) : String(props.item.value)}
</Text>
</View>
);
}
// A day, as wide as its column (the calendar's columns share its width). The band spans a range's middle days and
// reaches from its ends' middles; a range of one day has none. The circle fills for the selected date and a
// range's ends (not its middle days), else for today.
const own = props.item.outside ? "text-faint" : "text-foreground";
return (
<View style={{ minWidth: cell, height: cell, alignItems: "center", justifyContent: "center" }}>
<View
class={
"absolute inset-y-0.5 left-0 right-0 hidden bg-brand-tint group-data-range-middle:flex group-data-range-start:flex " +
"group-data-range-start:left-1/2 group-data-range-end:flex group-data-range-end:right-1/2 group-data-range-start:group-data-range-end:hidden"
}
/>
<View
class={
`${props.item.today ? "bg-accent" : ""} border-[1.5px] border-transparent group-focus:border-info ` +
"group-selected:bg-brand-fill group-data-range-middle:bg-transparent"
}
style={{ width: cell - 4, height: cell - 4, borderRadius: (cell - 4) / 2, alignItems: "center", justifyContent: "center" }}
>
<Text
class={
`${own} ${props.item.today ? "font-semibold" : "font-normal"} group-selected:font-semibold group-selected:text-on-brand ` +
`group-data-range-middle:${own} group-disabled:text-faint group-disabled:opacity-50`
}
style={{ fontSize: controlText, fontVariant: ["tabular-nums"] }}
>
{String(props.item.value)}
</Text>
</View>
</View>
);
}
/**
* A segment of the time: filled while it has the keys (`focus:` on the
* segment, `segmentClass`), its digits or AM / PM in the color on the fill
* (`group-focus:`), so moving between the segments draws nothing.
*/
const segmentClass = "group rounded active:opacity-70 focus:bg-brand-fill";
function Segment(props: { segment: TimeFieldSegmentEntry }) {
return (
<Text class="text-foreground group-focus:text-on-brand" style={{ paddingHorizontal: 3, fontSize: controlText, fontVariant: ["tabular-nums"] }}>
{props.segment.label}
</Text>
);
}
/** 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={{ ...ui().card, borderRadius: 16, padding: 16, 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}
offset={4}
margin={8}
popupStyle={surface()}
backdropStyle={backdrop}
contentStyle={content}
presetsStyle={presets()}
presetStyle={preset()}
presetClass="active:opacity-70"
calendarStyle={calendar}
headerStyle={{ marginBottom: 4 }}
itemClass={itemClass}
renderItem={(item) => <Item item={item} />}
style={desktop ? { width: 260 } : undefined}
cleanable
clearButtonAccessibilityLabel="Clear the due date"
clearButtonClass="absolute items-center justify-center rounded-full enabled:hover:opacity-70"
clearButtonStyle={{ top: (size.control - 20) / 2, right: 10, width: 20, height: 20 }}
clearButton={<Icon name="close" size={14} tint={ui().muted} />}
trigger={<Trigger title={due() ? `${monthDay(due()!)}, ${due()!.slice(0, 4)}` : undefined} placeholder="No due date" open={dueOpen()} clearable={due() !== null} />}
/>
</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}
offset={4}
margin={8}
popupStyle={surface()}
backdropStyle={backdrop}
contentStyle={content}
presetsStyle={presets()}
presetStyle={preset()}
presetClass="active:opacity-70"
calendarStyle={calendar}
headerStyle={{ marginBottom: 4 }}
bodyStyle={{ gap: monthGap }}
itemClass={itemClass}
renderItem={(item) => <Item item={item} months={wide() ? 2 : 1} />}
trigger={<Trigger title={stayTitle()} placeholder="Check-in – check-out" open={stayOpen()} />}
/>
</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"
offset={4}
margin={8}
popupStyle={surface()}
backdropStyle={backdrop}
calendarStyle={calendar}
headerStyle={{ marginBottom: 4 }}
itemClass={itemClass}
renderItem={(item) => <Item item={item} />}
timeStyle={time()}
timeLabel={<Text style={{ fontSize: controlText, color: ui().muted }}>Time</Text>}
timeAccessibilityLabel="Meeting time"
timeFieldClass={timeField}
segmentClass={segmentClass}
separatorStyle={{ fontSize: controlText, color: ui().faint }}
renderSegment={(segment) => <Segment segment={segment} />}
trigger={<Trigger title={meetingTitle()} placeholder="Not scheduled" open={meetingOpen()} />}
/>
</Field>
</View>
</Split>
</View>
);
}
mount(App);- 在桌面平台及桌面瀏覽器上,於觸發元件處彈出視窗;開啟後,鍵盤焦點會移到日期上。
- 在手機及平板電腦上,於螢幕底部顯示面板,面板後方有背景遮罩。
選擇器負責行為:值(由應用程式持有,或由選擇器自行持有)、開啟狀態、日曆、時間、預設選項、鍵盤操作,以及螢幕閱讀器讀出的內容。外觀則由應用程式決定:應用程式繪製觸發元件(包括值、佔位文字、圖示),並設定彈出視窗、日曆各部分、預設選項及時間欄位的樣式。
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:ring-2 focus: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 來自 nsh/base,即 Rust 的 nsh-base crate。在 Rust 中,date_picker() 會建立一個選擇器,每個屬性有一個 setter(.value(..)、.range(..)、.time_precision(..)),每個事件有一個監聽器(.on_change(..))。其值為 DateTime(DateTime::Single、DateTime::Range,由 chrono 日期或日期與時間組成);onChange 會傳回 PickedDate,即具備選擇器時間精度的值。
#值
值採用 HTML input 的格式:ISO 日期 "2026-10-28",與 <input type="date"> 相同;使用 range 時為 [start, end];使用 timePrecision 時為日期加時間 "2026-10-28T09:30"(精度為秒時為 "2026-10-28T09:30:15"),與 <input type="datetime-local"> 相同;null 表示沒有值。設定 value 時,值由應用程式持有:選擇器顯示該值,並以 onChange({ value }) 回報每次變更;應用程式需設定 value 以跟進。若省略,選擇器會自行保存值,起初取自 defaultValue。
- 單一日期:按一下某日即設定值並關閉彈出視窗。
- 使用
range時,第一次按下開始範圍,第二次按下結束範圍,與日曆相同;完整的範圍會設定值並關閉彈出視窗。 - 使用
timePrecision(僅限單一日期)時,日曆下方會顯示時間欄位,時間的每次編輯都會回報。在桌面平台上,選取日期後彈出視窗會保持開啟以便設定時間,並回報帶有時間的日期;再按一下已選取的日期會關閉彈出視窗。在手機及平板電腦上,輕按某日會以其時間選取該日並關閉面板,與單一日期相同;之後可再次開啟面板設定時間。在設定任何時間之前選取的日期會得到defaultTime(預設為00:00)。hourCycle決定欄位如何計算小時。
cleanable 會在有值時加入清除按鈕:按下即清除值(onChange({ value: null }))。清除按鈕位於觸發元件之後而非其內部,因此按下它不會開啟彈出視窗;應用程式負責放置它並填入內容(clearButton),與 Select 的清除按鈕相同。
#預設選項
presets 是日曆旁用來設定值的按鈕,例如「今天」、「過去 7 天」、「明天 9 時」。每個預設選項為 { label, value },value 日期、範圍或日期與時間,按原樣保留;按下即設定值並關閉彈出視窗。contentClass 負責排列預設選項欄與帶有時間的日曆(橫向排列,flex-row);presetsClass 設定該欄的樣式,presetClass 設定每個按鈕的樣式。
#日曆
除了值以外,Calendar 的每個屬性都會傳遞到選擇器:numberOfMonths、firstDayOfWeek、disabledMatcher、yearRange、previousAccessibilityLabel、nextAccessibilityLabel、各部分(headerClass 至 itemStyle)及 renderItem。calendarClass 與 calendarStyle 設定日曆本身的樣式。其檢視及按鍵與日曆相同。
時間列(timeClass、timeStyle)的起端為 timeLabel,即應用程式為它提供的文字(「時間」),末端為時間欄位(timeFieldClass、timeFieldStyle、timeAccessibilityLabel):這是一個項目置中並向兩端分開排列的橫列(flex-row items-center justify-between,與 gpui-component 相同)。欄位的各區段與 TimeField 相同(segmentClass、separatorClass、renderSegment)。
#屬性
| 屬性 | Rust | 類型 | 預設值 | 說明 |
|---|---|---|---|---|
value |
.value(..) |
DatePickerValue |
無 | 值,由應用程式持有。 |
defaultValue |
.default_value(..) |
DatePickerValue |
null |
未設定 value 時的起始值。 |
range |
.range(..) |
boolean |
false |
選取日期範圍。 |
open、defaultOpen |
.open(..)、.default_open(..) |
boolean |
false |
開啟狀態,由應用程式或選擇器自行持有。 |
disabled |
.disabled(..) |
boolean |
false |
保持關閉,不接受按下操作或鍵盤焦點。 |
accessibilityLabel |
.accessibility_label(..) |
string |
無 | 螢幕閱讀器對它的稱呼。 |
dateFormat |
.date_format(..) |
string |
"%Y/%m/%d" 加時間 |
螢幕閱讀器如何讀出值,採用 chrono 的格式。 |
timePrecision |
.time_precision(..) |
"minute" | "second" |
無 | 同時編輯時間,精確至此單位。 |
hourCycle |
.hour_cycle(..) |
"h23" | "h12" |
"h23" |
時間欄位如何計算小時。 |
defaultTime |
.default_time(..) |
string |
"00:00" |
使用者設定時間之前,日期所得到的時間。 |
cleanable |
.cleanable(..) |
boolean |
false |
有值時顯示的清除按鈕。 |
presets |
.presets(..) |
DateRangePreset[] |
[] |
彈出視窗中用來設定值的按鈕。 |
numberOfMonths、firstDayOfWeek、disabledMatcher、yearRange |
同 Calendar |
同 Calendar |
同 Calendar |
日曆的月份、星期、停用日期及年份。 |
previousAccessibilityLabel、nextAccessibilityLabel |
同 Calendar |
string |
無 | 螢幕閱讀器對日曆「上一個」與「下一個」所讀出的文字。 |
placement、align、offset、margin |
.placement(..),… |
同 Select |
"bottom"、"start"、0、0 |
桌面平台:彈出視窗相對於觸發元件的位置。 |
popupClass、popupStyle |
.popup_class(..)、.popup_style(..) |
string、StyleProp<ViewStyle> |
無 | 彈出視窗(桌面平台)或面板(觸控螢幕)。 |
backdropClass、backdropStyle |
.backdrop_class(..)、.backdrop_style(..) |
string、StyleProp<ViewStyle> |
無 | 面板後方的背景遮罩。 |
contentClass、contentStyle |
.content_class(..)、.content_style(..) |
string、StyleProp<ViewStyle> |
無 | 彈出視窗的內容:日曆旁的預設選項及時間。 |
presetsClass、presetsStyle |
.presets_class(..)、.presets_style(..) |
string、StyleProp<ViewStyle> |
無 | 預設選項欄。 |
presetClass、presetStyle |
.preset_class(..)、.preset_style(..) |
string、StyleProp<TextStyle> |
無 | 每個預設選項的按鈕。 |
calendarClass、calendarStyle |
.calendar_class(..)、.calendar_style(..) |
string、StyleProp<ViewStyle> |
無 | 日曆。 |
headerClass … itemStyle |
同 Calendar |
同 Calendar |
無 | 日曆的標頭、主體、月份、列及項目。 |
renderItem |
.render_item(..) |
(item: CalendarEntry) => JSX.Element |
無 | 日曆的每個項目,由應用程式按其內容繪製;其狀態為項目的 class,同 Calendar。 |
timeClass、timeStyle |
.time_class(..)、.time_style(..) |
string、StyleProp<ViewStyle> |
無 | 時間列:起端為標籤,末端為欄位。 |
timeLabel |
.time_label(..) |
JSX.Element |
無 | 時間列在欄位之前顯示的內容。 |
timeFieldClass、timeFieldStyle |
.time_field_class(..)、.time_field_style(..) |
string、StyleProp<ViewStyle> |
無 | 時間欄位。 |
timeAccessibilityLabel |
.time_accessibility_label(..) |
string |
無 | 螢幕閱讀器對時間欄位的稱呼。 |
segmentClass、segmentStyle、separatorClass、separatorStyle、renderSegment |
同 TimeField |
同 TimeField |
無 | 時間欄位的各區段及 :。 |
clearButtonClass、clearButtonStyle |
.clear_button_class(..)、.clear_button_style(..) |
string、StyleProp<ViewStyle> |
無 | 清除按鈕(cleanable)。 |
clearButton |
.clear_button(..) |
JSX.Element |
無 | 清除按鈕的內容。 |
clearButtonAccessibilityLabel |
.clear_button_accessibility_label(..) |
string |
無 | 螢幕閱讀器對清除按鈕的稱呼。 |
trigger |
.trigger(..) |
JSX.Element |
無 | 按下後開啟彈出視窗的元素;彈出視窗相對於它定位。 |
class、style |
樣式方法 | string、StyleProp<ViewStyle> |
無 | 觸發元件外層的檢視。 |
#事件
| 事件 | Rust | 說明 |
|---|---|---|
onChange |
.on_change(|value| ..) |
值已變更(日期、範圍終點、預設選項、時間、清除按鈕):{ value }。設定 value 以跟進。 |
onOpenChange |
.on_open_change(|e| ..) |
彈出視窗已開啟或關閉,並附帶原因({ open, reason })。設定 open 以跟進。 |
onOpen、onClose |
.on_open(..)、.on_close(..) |
彈出視窗已顯示,或已消失。 |
onCancel |
.on_cancel(..) |
使用者未作選擇便關閉彈出視窗(按 Escape 或返回、按下外部或背景遮罩)。 |
#組成部分
| 部分 | 位置 | 樣式設定方式 |
|---|---|---|
| 觸發元件 | 選擇器的檢視 | 應用程式自己的元素(trigger) |
| 清除按鈕 | 選擇器的檢視,位於觸發元件之後(cleanable,有值時顯示) |
clearButtonClass、clearButtonStyle;其內容 clearButton |
| 彈出視窗或面板 | 位於所有內容之上,在觸發元件處(桌面平台)或在底部(觸控螢幕) | popupClass、popupStyle |
| 背景遮罩 | 面板後方(觸控螢幕) | backdropClass、backdropStyle |
| 內容 | 彈出視窗 | contentClass、contentStyle |
| 預設選項 | 內容中,排在最前(presets) |
presetsClass、presetsStyle;每個選項 presetClass、presetStyle |
| 日曆 | 內容 | calendarClass、calendarStyle,以及 Calendar 的各部分 |
| 時間列 | 日曆下方(timePrecision) |
timeClass、timeStyle;其標籤 timeLabel |
| 時間欄位 | 時間列 | timeFieldClass、timeFieldStyle,以及 TimeField 的各部分 |
#鍵盤
| 按鍵 | 操作 |
|---|---|
| Return(在觸發元件上) | 開啟或關閉彈出視窗。 |
| Delete、Backspace(在觸發元件上) | 彈出視窗關閉時清除值。 |
| Escape | 未作選擇便關閉彈出視窗。 |
在彈出視窗中,日曆的按鍵用來在日期之間移動並選取日期(參閱鍵盤),時間欄位的按鍵則用來編輯時間(參閱鍵盤)。
#無障礙
- 觸發元件對螢幕閱讀器而言是 combobox:其標籤為
accessibilityLabel,其值為依dateFormat寫法呈現的日期(預設為2026/10/28,時間則按timePrecision),並會說明彈出視窗是否已展開。disabled會令它變暗。 - 日曆的日期是以 ISO 日期命名的按鈕(參閱無障礙);預設選項是以其標籤命名的按鈕;時間欄位以
timeAccessibilityLabel命名。 - 清除按鈕是以
clearButtonAccessibilityLabel命名的按鈕。
有關標籤、角色及朗讀內容的整體說明,請參閱無障礙。