元素

TimeField

时间输入框逐段编辑一天中的时间:小时、分钟,在 precision="second" 时还有秒,在 hourCycle="h12" 时还有上午或下午。一个提醒的时间、一场会议的开始、一家店的营业时间。它就是 DatePicker 在 timePrecision 时日历下方的时间,单独放在页面中。

el-date-picker.tsx
el-date-picker.tsx运行中
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);

时间输入框负责行为:时间(应用的,或它自己的)、按键编辑哪一段、输入和步进数字,以及屏幕阅读器听到的内容。外观由应用决定:应用为各段和它们之间的 : 设置样式,或者自己绘制各段。

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())))
}

TimeField 来自 nsh/base,在 Rust 中是 nsh-base crate。在 Rust 中,time_field() 创建一个时间输入框,每个属性有一个设置方法(.value(..)、.precision(..)、.hour_cycle(..)),每个事件有一个监听方法(.on_change(..))。它的时间是 TimeOfDay,即一个 chrono::NaiveTime。

#值

值是 24 小时制的一天中的时间,与 HTML <input type="time"> 的相同:"HH:MM",在 precision="second" 时为 "HH:MM:SS",不论输入框显示哪种 hourCycle。有 value 时,值由应用持有:输入框显示它,并用 onChange({ value }) 报告每次编辑;应用把 value 设为报告的值以跟随它。省略 value 时,输入框自己保存时间,初始为 defaultValue(默认 00:00)。

precision 是输入框编辑的最小单位,"minute"(默认)或 "second"。hourCycle 是小时的计法:"h23"(默认)从 00 到 23,"h12" 从 12 到 11,并在数字后加一个上午/下午段。localeSettings().hourCycle 为 "h11" 或 "h12" 时用户的是 "h12",否则是 "h23"(地区偏好)。

#编辑

总有一段被选中;按键编辑它,与 gpui-base 的时间输入框相同:

  • Up 和 Down 把这一段加减一,到头后回绕(59 到 00),不会进位到相邻的段。
  • 数字输入到这一段,每段两位:一个不能作为更长数值开头的数字(小时里的 7)会直接填完这一段并移到下一段。
  • a 和 p 设为上午和下午。
  • Backspace 和 Delete 重置这一段。

按下某一段会选中它。按下已选中的上午/下午段会切换它,因为手机上没有 a 和 p 键。按键交给各段后面一个透明的原生文本输入框,与 OtpInput 的一样:在手机和平板上它会弹出数字键盘。

#属性

属性 Rust 类型 默认值 说明
value .value(..) string 无 时间,由应用持有。
defaultValue .default_value(..) string "00:00" 没有 value 时的初始时间。
precision .precision(..) "minute" | "second" "minute" 编辑的最小单位。
hourCycle .hour_cycle(..) "h23" | "h12" "h23" 小时的计法;"h12" 会加一个上午/下午段。
disabled .disabled(..) boolean false 不接受焦点和编辑;输入框和各段应用 disabled: 样式。
accessibilityLabel .accessibility_label(..) string 无 屏幕阅读器对输入框的称呼。
segmentClass、segmentStyle .segment_class(..)、.segment_style(..) string、StyleProp<TextStyle> 无 每一段:输入框有焦点时选中的段应用 focus:,随输入框应用 disabled:;加上 group 时其内容跟随(group-focus:、group-disabled:)。
separatorClass、separatorStyle .separator_class(..)、.separator_style(..) string、StyleProp<TextStyle> 无 数字之间的每个 :。
renderSegment .render_segment(..) (segment: TimeFieldSegmentEntry) => JSX.Element 无 由应用根据段显示的内容绘制;否则显示其标签。
class、style 样式方法 string、StyleProp<ViewStyle> 无 输入框,包住各段(一行)。

renderSegment 得到一个 TimeFieldSegmentEntry:segment("hour"、"minute"、"second" 或 "period")、value(输入框钟面上的小时、分钟或秒;上午为 0,下午为 1)和 label(两位数字,或 AM / PM)。它从不包含段的状态:按键编辑的段是 focus:,输入框禁用时段是 disabled:;在 segmentClass 里加上 group,内容就用 group-focus: 和 group-disabled: 跟随。所以一个段只在它的值变化时重新绘制,在段之间移动、焦点进出都不绘制:

<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>}
/>

#事件

事件 Rust 说明
onChange .on_change(|value| ..) 用户改变了时间:{ value }。设置 value 以跟随它。应用传入的 value 从不被报告。

#部件

部件 位置 样式
输入框 根,一行 class、style
段 输入框中:小时、分钟、秒、上午/下午 segmentClass、segmentStyle、renderSegment(其中用 group-focus:、group-disabled:,segmentClass 里加 group)
分隔符 输入框中,两个数字之间 separatorClass、separatorStyle

#键盘

Tab 到达输入框时停在选中的段上。然后:

按键 操作
Left / Right 前一段或后一段。
Tab / Shift+Tab 后一段或前一段;在最后一段按 Tab、在第一段按 Shift+Tab 会离开输入框。
Up / Down 把这一段加减一,到头回绕。
0 到 9 输入到这一段。
A / P 上午或下午。
Backspace、Delete 重置这一段。

#无障碍

  • 输入框是一个文本输入框,名称来自 accessibilityLabel;屏幕阅读器读出它显示的时间。disabled 时它显示为不可用。
  • 手机和平板显示数字键盘。

关于标签、角色和播报的一般说明,见无障碍。