元素

Calendar

日历从按周排列的月份中选出一个日期,或者在 range 时选出一段日期:表单里的截止日期、一次住宿的几晚、一份报告的天数。它显示一个月,或并排显示几个月,用”上一个”和”下一个”翻月,并可切换到一年中各月的视图或一页年份,以便跳得更远。它就是 DatePicker 弹出层里的日历,单独放在页面中。

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

日历负责行为:值(应用的,或它自己的)、显示的月份、视图、不能选的日期、键盘,以及屏幕阅读器听到的内容。外观由应用决定:应用为头部、主体、每个月、每一行和每个条目设置样式,并绘制条目的内容(月份和星期的名称、今天的标记、范围的色带)。日历的网格像表格的列一样填满给它的宽度:几个月平分它,一行里的条目平分这一行,所以手机底部面板里的日历横跨整个屏幕,而按内容定宽的弹出层里的日历保持条目自身的宽度(在 itemClass 或 monthClass 里写 flex-none 可让条目或月份保持自身宽度)。

use nsh_base::{CalendarEntry, CalendarItemKind, Date, Matcher, calendar};
use nsh_core::prelude::*;

const MONTHS: [&str; 12] = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December",
];
const WEEKDAYS: [&str; 7] = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];

fn due_date() -> impl IntoElement {
    let due = signal(Date::default());
    calendar()
        .value(move || due.get())
        .on_change(move |next: &Date| due.set(*next))
        .disabled_matcher(Matcher::DayOfWeek(vec![0, 6]))
        .previous_accessibility_label("Previous month")
        .next_accessibility_label("Next month")
        .item_class("rounded-md selected:bg-primary selected:text-primary-foreground disabled:opacity-50")
        .render_item(|item: &CalendarEntry| {
            let label = match item.kind {
                CalendarItemKind::Previous => "‹".to_string(),
                CalendarItemKind::Next => "›".to_string(),
                CalendarItemKind::Weekday => WEEKDAYS[item.value as usize].to_string(),
                CalendarItemKind::MonthToggle | CalendarItemKind::Month => {
                    MONTHS[item.value as usize - 1].to_string()
                }
                _ => item.value.to_string(),
            };
            view()
                .w_8()
                .h_8()
                .items_center()
                .justify_center()
                .child(text(label).text_sm())
        })
}

Calendar 来自 nsh/base,在 Rust 中是 nsh-base crate。在 Rust 中,calendar() 创建一个日历,每个属性有一个设置方法(.value(..)、.range(..)、.number_of_months(..)),每个事件有一个监听方法(.on_change(..))。它的值是 Date(Date::Single、Date::Range,由一个 chrono::NaiveDate 或一对日期构成),禁用的日期是 Matcher。

#值

值是一个 ISO 日期 "2026-10-28",与 HTML <input type="date"> 的相同;在 range 时是 [start, end],null 表示没有日期。有 value 时,值由应用持有:日历把它显示为已选,并用 onChange({ value }) 报告一次选择;应用把 value 设为报告的值以跟随它。省略 value 时,日历自己保存值,初始为 defaultValue。

onChange 只报告完整的值,与 gpui-base 的 Selected 相同:按下的一天,或范围的结束日。

  • 不设 range 时,按下某一天就选中它。
  • 在 range 时,第一次按压开始范围,第二次结束范围,两者之间的日期都在范围内(每一天都是 selected,包括两端,见条目)。第二次按在更早的一天上会从那一天重新开始范围,范围完整之后再按也一样。半个范围会一直显示,直到完整时才被报告。

日历打开时显示值所在的月份(范围的开始日),没有值则显示今天所在的月份。

#月份与视图

numberOfMonths 从显示的月份起并排显示这么多个月;“上一个”和”下一个”每次翻一个月。firstDayOfWeek 是每周的第一天,0 为星期日(默认)到 6 为星期六。

头部包含”上一个”、两个切换按钮和”下一个”:

  • 日视图显示各月的日期,每个月是一列,包含星期行和各周;前后月份的日期补满各周(outside、data-outside)。
  • 月份切换按钮(monthToggle)打开月份视图:十二个月,每行三个。选中一个会在日视图中显示它。
  • 年份切换按钮(yearToggle)打开年份视图:一页 20 年,每行五个,“上一个”和”下一个”翻页。选中一个会在日视图中显示那一年。yearRange 是翻页经过的年份,[start, end)(默认:今年之前 50 年到之后 50 年)。

显示多个月时,头部用每个月的标题代替切换按钮(一个不接受按压的 monthToggle 条目),与 gpui-base 的相同。

#禁用的日期

disabledMatcher 是用户不能选的日期,即 gpui-base 的 Matcher,有四种形式:

形式禁用
[0, 6]这些星期几,0 为星期日到 6 为星期六。
{ before, after }before 之前和 after 之后的日期(任一可省略)。
{ from, to }从 from 到 to 的日期,包括两端(省略的一端不限)。
(date) => boolean函数返回 true 的日期,传入每个显示日期的 ISO 日期。

函数对每个显示的日期调用一次,在下一个 JS 轮次中调用,已回答过的日期不再询问:翻月只询问新出现的日期,所以它的结果应只取决于日期。传入另一个函数会重新询问。被禁用的日期应用 disabled:,不接受按压,Return 和 Space 也不会选中它。

#条目

日历中每个可按压的目标和标签都是一个条目:“上一个”、切换按钮、“下一个”、星期、日期、月份和年份。每个条目绘制在一个由 itemClass 和 itemStyle 设置样式的部件中,其变体跟随状态:

变体条目
selected:已选:选中的日期、完整范围中的每一天(包括两端,与 React Aria 的范围日历一致)、半个范围的开始日、显示的月份或年份、已打开视图的切换按钮。屏幕阅读器读到它为已选。
disabled:不可用:被禁用的日期、月份视图中或年份两端的”上一个”和”下一个”。星期和各月标题是标签,屏幕阅读器读作列标题和标题:它们不接受按压,保持自己的样式。
focus:键盘在它上面。
data-range-start:、data-range-end:是完整范围的第一天或最后一天(只有一天的范围两者都是)。
data-range-middle:是完整范围内、不在两端的一天。
data-today:是今天。
data-outside:是补满各周的前后月份的日期。

data-* 变体是 Tailwind 的(data-range-start: 匹配 [data-range-start]),与 shadcn 的日历为日期设置样式的方式相同;在 itemClass 里加上 group,内容就用 group-selected:、group-data-range-middle: 等跟随它们。selected: 指范围中的每一天,所以范围两端用自己的样式覆盖它(后面的变体胜出:data-* 排在 selected: 之后),中间的日期也一样:

<Calendar
  range
  itemClass="group rounded-md selected:bg-primary selected:text-primary-foreground data-range-middle:rounded-none data-range-middle:bg-accent data-range-middle:text-accent-foreground data-range-start:rounded-r-none data-range-end:rounded-l-none data-range-start:data-range-end:rounded-md"
/>

renderItem 根据条目本身(CalendarEntry)绘制其内容,从不根据它的状态:绘制只做一次,条目被选中、获得焦点或进入范围时都保留,所以按键、选择和焦点进出都不再绘制,翻月时只为新出现的日期各绘制一次(一天的绘制按它的月份和日期保留:显示多个月时,仍在显示的月份保留它们的绘制)。

字段含义
kind"previous"、"monthToggle"、"yearToggle"、"next"、"weekday"、"day"、"month" 或 "year"。
value它的数字:一个月中的第几天、月份(1 到 12)、年份、星期几(0 为星期日到 6);“上一个”和”下一个”为 0。
date某一天的 ISO 日期。
year、month它所属的年份和月份:日期的(显示它的那个月)、月份切换按钮或标题的、月份视图中月份的;年份切换按钮和年份是它自己的年份。“上一个”、“下一个”和星期为 0(年份切换按钮和年份的 month 也为 0)。
today这一天是今天。
outside这一天属于前后的月份。

不设 renderItem 时,条目显示它的数字,“上一个”和”下一个”显示 ‹ 和 ›,与 gpui-base 的相同;星期也显示它的数字 0 到 6,因为月份和星期的名称是应用用自己的语言说的话。

#属性

属性Rust类型默认值说明
value.value(..)CalendarValue无值,由应用持有。
defaultValue.default_value(..)CalendarValuenull没有 value 时的初始值。
range.range(..)booleanfalse选择范围:第一次按压开始,第二次结束。
numberOfMonths.number_of_months(..)number1并排显示几个月。
firstDayOfWeek.first_day_of_week(..)number0每周的第一天,0 为星期日到 6 为星期六。
disabledMatcher.disabled_matcher(..)DateMatcher无不能选的日期。
yearRange.year_range(..)[number, number]前后各 50 年年份视图翻页经过的年份,[start, end)。
previousAccessibilityLabel.previous_accessibility_label(..)string无屏幕阅读器对”上一个”的称呼。
nextAccessibilityLabel.next_accessibility_label(..)string无屏幕阅读器对”下一个”的称呼。
headerClass、headerStyle.header_class(..)、.header_style(..)string、StyleProp<ViewStyle>无头部:“上一个”、切换按钮(或各月标题)、“下一个”。
bodyClass、bodyStyle.body_class(..)、.body_style(..)string、StyleProp<ViewStyle>无主体:并排的各月,或月份、年份视图的行。
monthClass、monthStyle.month_class(..)、.month_style(..)string、StyleProp<ViewStyle>无日视图中的每个月。
rowClass、rowStyle.row_class(..)、.row_style(..)string、StyleProp<ViewStyle>无每一行:星期、一周、一行月份或年份。
itemClass、itemStyle.item_class(..)、.item_style(..)string、StyleProp<TextStyle>无每个条目:selected:、disabled:、focus:;日期的 data-range-start:、data-range-end:、data-range-middle:、data-today:、data-outside:(条目)。
renderItem.render_item(..)(item: CalendarEntry) => JSX.Element无由应用根据条目本身绘制的内容;否则显示其数字。
class、style样式方法string、StyleProp<ViewStyle>无日历:头部在主体之上。

#事件

事件Rust说明
onChange.on_change(|value| ..)用户选出了一个完整的值:{ value },一天或一个范围。设置 value 以跟随它。应用传入的 value 从不被报告。

#部件

部件位置样式
日历根class、style
头部日历中的第一个headerClass、headerStyle
主体日历中,头部之后bodyClass、bodyStyle
月主体中(日视图)monthClass、monthStyle
行月中,或主体中(月份和年份视图)rowClass、rowStyle
条目头部和各行中itemClass、itemStyle、renderItem(其中用 group-selected:、group-data-range-middle: 等,itemClass 里加 group)

#键盘

所有日期是 Tab 的一站:落在选中的日期上,没有则落在今天,再没有则落在第一个显示的日期;禁用的日期不接受焦点,会被跳过。然后:

按键操作
Left / Right前一天或后一天。
Up / Down一周前或一周后的同一天。
Home / End本周的第一天或最后一天。
Page Up / Page Down一个月前或一个月后的同一天。
Shift+Page Up / Shift+Page Down一年前或一年后的同一天。
Return、Space选中这一天。

在从右到左的布局里,每周从右边开始,Left 是后一天,Right 是前一天;Up 和 Down 仍按周移动。按键到达禁用的日期时,会沿移动方向继续到下一个未禁用的日期(Home 和 End 朝离开的那一天方向回退)。移出显示的月份时会翻月。“上一个”、切换按钮、“下一个”、月份和年份接受按压。gpui-base 的日期只接受按压;这些按键是 NSH 的,参照 WAI-ARIA 的日期选择对话框。

#无障碍

  • 每一天是一个按钮,以其 ISO 日期命名;它是选中的日期或范围中的一天时(包括两端,与 React Aria 的范围日历一致)为已选状态,被禁用时显示为不可用。
  • “上一个”和”下一个”是按钮,名称来自 previousAccessibilityLabel 和 nextAccessibilityLabel;切换按钮、月份和年份是按钮,以其显示的内容命名。

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