# Date Input

逐段输入日期，顺序跟随用户语言的写法。

把 Date Input 用于人们记在心里的日期，比如生日或预订日期。日期的每一部分都是一个独立的小输入框，顺序按 locale 的写法排列。

```svelte title="basic.svelte"
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
</script>

<Field>
  <FieldLabel>Start date</FieldLabel>
  <DateInput />
</Field>
```

点击月份并输入 11042026。每一部分填满后都会移到下一部分。在某个部分上按 ArrowUp 或 ArrowDown，可以按步进调整它。

## 安装
```bash
npm install @ui-sdk/svelte @ui-sdk/core
```

## 组合
用下面的组合构建 `DateInput`：

```text
DateInput
├── DateInputSegment
└── DateInputSegment
```

`DateInput` 渲染一个分组，日期的每一部分对应一个 `DateInputSegment`：英语里是月、日、年，德语里是日、月、年。你输入的每个分段都是一个小输入框。它们之间的斜杠或点也是分段，只是纯文本。`DateInput` 会替你渲染分段；只有想改变它们的外观时才自己渲染，参见[自定义渲染](https://ui-sdk.cn/docs/svelte/components/date-input#custom-rendering)。

## 用法
把输入框放进 [Field](/docs/svelte/components/field)，并给它一个标签：

```svelte
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
</script>

<Field>
  <FieldLabel>Start date</FieldLabel>
  <DateInput defaultValue="2026-11-02" />
</Field>
```

值是 `"2026-11-02"` 这样的 ISO 日期字符串，和原生日期输入框一样。在每个分段都填入内容之前，它一直是 `null`，因此你的应用只会看到完整日期。

输入数字，每个分段填满后移到下一个。像 4 这样不能再接一位数字的月份，会立即移到下一个。输入分隔符，比如 `/` 或 `.`，也会移到下一个。日会被限制在当月之内：从 1 月 31 日移到 2 月，显示的是 28 日。把完整日期粘贴到任意分段，可以是 `2026-11-02`，也可以是 locale 的写法。

## 字段
字段的标签为这个分组提供名称，点击标签会把焦点移到第一个分段。它的描述会和输入框一起被读出。

```svelte title="field.svelte"
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
</script>

<Field>
  <FieldLabel>Birthday</FieldLabel>
  <DateInput name="birthday" />
  <FieldDescription>We send a card on the day.</FieldDescription>
</Field>
```

点击 Birthday 把焦点移到月份，然后输入日期。屏幕阅读器会把描述和输入框一起读出。

## 日期与时间
把 `granularity` 设为 `"hour"`、`"minute"` 或 `"second"`，就能加上时间。值会变成 `"2026-11-02T14:30"` 这样的本地日期和时间。只要时间，请用 [Time Input](/docs/svelte/components/time-input)。

```svelte title="date-time.svelte"
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
</script>

<Field>
  <FieldLabel>Departure</FieldLabel>
  <DateInput granularity="minute" defaultValue="2026-11-02T14:30" />
</Field>
```

用 Tab 依次经过日期和时间。在最后一个分段输入 P 或 A，可以在 AM 和 PM 之间切换。

## 最小与最大
`min` 和 `max` 接受 ISO 日期。超出范围的日期无效：输入框会设置 `data-invalid`，它的表单也不会提交。

```svelte title="min-max.svelte"
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import {
    Field,
    FieldDescription,
    FieldError,
    FieldLabel,
  } from "@ui-sdk/svelte/field"
</script>

<Field>
  <FieldLabel>Check-in</FieldLabel>
  <DateInput min="2026-01-01" max="2026-12-31" defaultValue="2026-06-15" />
  <FieldDescription>Any day in 2026.</FieldDescription>
  <FieldError />
</Field>
```

把 Check-in 的年份改成 2027，看它变为无效，再改回 2026。

## 不可用的日期
`unavailable` 接受与 [Calendar](https://ui-sdk.cn/docs/svelte/components/calendar#unavailable-dates) 相同的匹配器：ISO 日期、`{ from, to }` 范围、`{ weekday: [0, 6] }` 这样的星期，或一个函数。不可用的日期无效，并以“This date isn't available.”作为消息。

```svelte title="unavailable.svelte"
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import {
    Field,
    FieldDescription,
    FieldError,
    FieldLabel,
  } from "@ui-sdk/svelte/field"
</script>

<Field>
  <FieldLabel>Delivery date</FieldLabel>
  <DateInput defaultValue="2026-11-02" unavailable={{ weekday: [0, 6] }} />
  <FieldDescription>We deliver Monday to Friday.</FieldDescription>
  <FieldError />
</Field>
```

把 Delivery date 的日往回步进，从 2 日星期一退到 1 日星期日。在你重新选到工作日之前，输入框一直无效。

## 语言
输入框从 `locale` 读取顺序、分隔符和时钟，省略时读取页面的语言。数字始终是 0 到 9，日历始终是公历，所以这个值在任何地方都表示同一个日期。在服务器上，输入框会先以英语渲染，直到读到页面的语言；如果首次渲染很重要，请设置 `locale`。

```svelte title="locale.svelte"
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
</script>

<div data-slot="stack">
  <Field>
    <FieldLabel>Date (en-GB)</FieldLabel>
    <DateInput locale="en-GB" defaultValue="2026-11-02" />
  </Field>
  <Field>
    <FieldLabel>Datum (de-DE)</FieldLabel>
    <DateInput locale="de-DE" defaultValue="2026-11-02" />
  </Field>
  <Field>
    <FieldLabel>日付 (ja-JP)</FieldLabel>
    <DateInput locale="ja-JP" defaultValue="2026-11-02" />
  </Field>
</div>
```

同一个日期在英式英语、德语和日语中的样子。每种语言都按自己的方式排列各部分。

## 禁用
在输入框上，或在它的 Field 或 fieldset 上设置 `disabled`，可以让它无法获得焦点，也不参与表单。

```svelte title="disabled.svelte"
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
</script>

<Field>
  <FieldLabel>Start date</FieldLabel>
  <DateInput defaultValue="2026-11-02" disabled />
</Field>
```

点击 Start date，或按 Tab 试着移到它上面。焦点会跳过它，日期保持 2026 年 11 月 2 日。

## 只读
设置 `readOnly`，得到一个可以聚焦、读取，并按原样提交的日期。

```svelte title="read-only.svelte"
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
</script>

<Field>
  <FieldLabel>Signed on</FieldLabel>
  <DateInput defaultValue="2026-11-02" readOnly />
</Field>
```

聚焦 Signed on，按 ArrowUp 或输入一个数字。日期保持不变。

## 表单
隐藏的输入框会以 `name` 提交 ISO 日期。空日期或只输入了一部分的日期会提交空字符串。设置 `required` 后，表单需要先有日期才能提交。在分段中按 Enter 会用已输入的内容提交表单。

```svelte title="form.svelte"
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import { Field, FieldError, FieldLabel } from "@ui-sdk/svelte/field"
  import { TimeInput } from "@ui-sdk/svelte/time-input"
  import { useLog } from "./log"

  const log = useLog()

  function onsubmit(event: SubmitEvent) {
    event.preventDefault()
    const data = [...new FormData(event.currentTarget as HTMLFormElement)].map(
      ([name, value]) => `${name}=${value}`
    )
    log(`Submitted ${data.join(", ")}`)
  }
</script>

<form data-slot="stack" {onsubmit}>
  <Field>
    <FieldLabel>Date</FieldLabel>
    <DateInput name="date" defaultValue="2026-11-02" required />
    <FieldError />
  </Field>
  <Field>
    <FieldLabel>Time</FieldLabel>
    <TimeInput name="time" defaultValue="09:30" required />
    <FieldError />
  </Field>
  <div data-slot="row">
    <button type="reset">Reset</button>
    <button type="submit" data-variant="solid">Book</button>
  </div>
</form>
```

用 Backspace 清空 Date 的日，然后选择 Book，看表单停止提交。填好后再选择 Book：控制台会记录这些值。Reset 会恢复默认值。

只输入了一部分的日期也会阻止表单提交，并以“Enter a valid date.”作为消息。把 `form` 设为页面中另一个表单的 id，就能用那个表单提交和校验。表单重置会恢复 `defaultValue`，并报告 `reset` 原因。

## 受控
用 `bind:value` 绑定值，用 `onValueChange` 同时获取变更详情。两者都会在得到每个完整日期时运行，在日期的任意部分被擦除后则以 `null` 运行。只输入了一半的日期本身就读作 `null`，所以把值设为 `null` 会保持已输入的内容。调用[控制器](https://ui-sdk.cn/docs/svelte/components/date-input#controller)上的 `clear()` 可以清空每个分段。

```svelte title="controlled.svelte"
<script lang="ts">
  import { DateInput } from "@ui-sdk/svelte/date-input"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import { useLog } from "./log"

  const log = useLog()
  let value = $state<string | null>("2026-11-02")
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => (value = null)}>Clear</button>
  </div>
  <Field>
    <FieldLabel>Due date</FieldLabel>
    <DateInput
      bind:value
      onValueChange={(next) => log(`Due date ${next ?? "empty"}`)}
    />
  </Field>
</div>
```

修改 Due date：控制台会记录每个完整日期。Clear 会把值设为 null。

共享约定见[状态与事件](/docs/svelte/state-and-events)，每次变更的原因见[原因](https://ui-sdk.cn/docs/svelte/components/date-input#reasons)。

## 控制器
用 `createDateInputController()` 创建控制器，并作为 `controller` 传入，就能从别处设置、清空或聚焦输入框。`focus("year")` 按单位聚焦某个分段。

```svelte title="controller.svelte"
<script lang="ts">
  import {
    createDateInputController,
    DateInput,
  } from "@ui-sdk/svelte/date-input"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"

  const publish = createDateInputController()
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => publish.setValue("2026-12-25")}
      >Christmas</button
    >
    <button type="button" onclick={() => publish.focus("year")}
      >Edit Year</button
    >
    <button type="button" onclick={() => publish.clear()}>Clear</button>
  </div>
  <Field>
    <FieldLabel>Publish on</FieldLabel>
    <DateInput controller={publish} />
  </Field>
</div>
```

选择 Christmas 设置日期，选择 Edit Year 聚焦年份，或选择 Clear 清空它。

[控制器](/docs/svelte/controllers)涵盖了创建和共享控制器。

## 自定义渲染
传入 `children` 片段自己渲染分段。片段会收到输入框的状态，其中的 `segments` 按顺序列出每个分段，以及它们之间的文本。在带 key 的 `{#each}` 中为每个分段渲染一个 `DateInputSegment`，并给分段之间的文本传入你自己的内容。

```svelte title="segments.svelte"
<script lang="ts">
  import { DateInput, DateInputSegment } from "@ui-sdk/svelte/date-input"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
</script>

<Field>
  <FieldLabel>Start date</FieldLabel>
  <DateInput defaultValue="2026-11-02">
    {#snippet children(state)}
      {#each state.segments as segment (segment.key)}
        {#if segment.editable}
          <DateInputSegment {segment} />
        {:else}
          <DateInputSegment {segment}>–</DateInputSegment>
        {/if}
      {/each}
    {/snippet}
  </DateInput>
</Field>
```

这里的分段之间用短横线代替 locale 的斜杠。顺序仍按 locale 的。

每个部件的状态列在[状态](https://ui-sdk.cn/docs/svelte/components/date-input#state)下。

## 样式
把根部件当作字段的外框来设置样式，分段则放在其中。每个分段都会把 `data-type` 设成它的单位，所以你可以加宽年份，或弱化分段之间的文本，后者带有 `data-type="literal"`。空的分段会设置 `data-empty` 并显示占位符。日期超出范围或不可用时，根部件会设置 `data-invalid`。

每个部件都有一个 `data-slot`，比如 `date-input-segment`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/svelte/components/date-input#data-attributes)下。

## 数据属性
### DateInput
`[data-slot="date-input"]`

- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-invalid`: Present while the date is before `min`, after `max` or unavailable.
- `data-empty`: Present while every segment is empty.

### DateInputSegment
`[data-slot="date-input-segment"]`

- `data-type` (`year`, `month`, `day`, `hour`, `minute`, `second`, `dayPeriod`, `literal`): The segment's unit, or `literal` for the text between segments.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-invalid`: Present while the date is before `min`, after `max` or unavailable.
- `data-empty`: Present while the segment is empty. It shows its placeholder.

## API 参考
属性（props）与下面相同，都作为 Svelte props。`value` 可以绑定。

### DateInput
- `value?` (`string | null`): The value: an ISO date like `"2026-11-02"`, with a time granularity a date and time like `"2026-11-02T14:30"`, or `null`. Pass it to control the input.
- `defaultValue?` (`string | null`): The value it starts with, when uncontrolled, and goes back to when its form resets.
- `onValueChange?` (`((value: string | null, details: ChangeDetails<DateInputValueChangeReason>) => void)`): Runs when the value wants to change: once every segment holds something, and again with `null` when one is emptied. `details.cancel()` keeps the value.
- `granularity?` (`DateInputGranularity`): The smallest unit it shows. `"day"` shows a date, and `"hour"`, `"minute"` or `"second"` add the time down to it.
- `hourCycle?` (`HourCycle`): A 12 or 24 hour clock for the time. Defaults to the locale's.
- `min?` (`string`): The earliest value, as an ISO date or date and time. A value before it is invalid.
- `max?` (`string`): The latest value. A date alone takes any time that day. A value after it is invalid.
- `unavailable?` (`DateMatchers`): Dates that can't be chosen, as in Calendar: ISO dates, `{ from, to }` ranges, weekdays or a function. A value on one is invalid.
- `locale?` (`string`): The language whose order, separators and clock it shows. Defaults to the page's.
- `disabled?` (`boolean`): Whether it can't be used.
- `readOnly?` (`boolean`): Whether the value can be seen but not changed.
- `required?` (`boolean`): Whether a value must be entered before its form submits.
- `name?` (`string`): The name the value submits under.
- `form?` (`string`): The id of the form it belongs to, when it isn't inside it.
- `controller?` (`object`): Drives it from anywhere. Create one with `createDateInputController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### DateInputSegment
- `segment` (`DateInputSegmentData`): The segment it shows, from the root's `segments`.

### 状态
渲染 snippet 和 `children` 会收到什么。

- `value` (`string | null`): The value, or `null` while empty or partly filled.
- `segments` (`DateInputSegmentData[]`): The segments in the order the locale shows them, with the text between them. Render one part for each.
- `disabled` (`boolean`): Whether it can't be used, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether the value can be seen but not changed.
- `invalid` (`boolean`): Whether the value is before `min`, after `max` or an unavailable date.

每个分段的状态 `DateInputSegmentState`，是分段本身加上它旁边的输入框状态：

- `key` (`string`): Tells segments apart: the type, or `"literal-<n>"` for the text between them.
- `type` (`DateInputSegmentType`)
- `text` (`string`): What it shows: the number, padded, or AM and PM in the locale. Empty while it holds nothing.
- `value` (`number | null`): The number it holds, or `null` while empty. AM is 0 and PM is 1.
- `min` (`number`): The smallest number it takes.
- `max` (`number`): The largest number it takes, like the days in the month.
- `empty` (`boolean`): Whether it holds nothing yet.
- `editable` (`boolean`): Whether it's a segment you type in, rather than the text between segments.
- `label` (`string`): Its name in the locale, like "month", which names it to assistive technology.
- `disabled` (`boolean`): Whether it can't be used.
- `readOnly` (`boolean`): Whether its value can't be changed.
- `invalid` (`boolean`): Whether the value is before `min`, after `max` or an unavailable date.

### 原因
`details.reason` 说明值为什么改变。

- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `step-key` (`KeyboardEvent`): Arrow, Page Up, Page Down, Home or End stepped a slider or a number input.
- `paste` (`ClipboardEvent`): Files were pasted, like a screenshot, or text and tokens into a token input.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

### 控制器
用 `createDateInputController()` 创建一个，并作为 `controller` 传入。

每个写入方法都接受可选的 `{ reason, event }`，像输入一样运行变更回调，并在变更被取消时返回 `false`。

- `getValue()` (`() => string | null`): The value, or `null` while empty or partly filled.
- `setValue(value, options?)` (`(value: string | null, options?: DateInputChangeOptions | undefined) => boolean`): Sets the value. Returns false when it isn't a value the input can show, or when canceled.
- `clear(options?)` (`(options?: DateInputChangeOptions | undefined) => boolean`): Empties every segment.
- `focus(segment?)` (`(segment?: string | undefined) => void`): Focuses a segment, like `"month"`, or the first one.

### 事件
回调先收到新值，然后收到详情。绑定的 `value` 只在 `onValueChange` 未取消变更时更新。

| 属性            | 所属        | 收到                                                                  |
| --------------- | ----------- | --------------------------------------------------------------------- |
| `bind:value`    | `DateInput` | ISO 日期；为空或只输入一部分时为 null                                 |
| `onValueChange` | `DateInput` | `(value, details)`：ISO 日期（被擦除后为 null），以及[原因](https://ui-sdk.cn/docs/svelte/components/date-input#reasons) |

## 无障碍
根部件是一个分组，名称来自它的 Field 标签或你的 `aria-label`。每个分段都是一个 [spinbutton](https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/)，由它的单位命名，比如“month”，并带有它的值、范围和文本。空的分段读作“Empty”。分段之间的文本对屏幕阅读器隐藏，屏幕阅读器改为读取每个分段的名称。

分段是真正的输入框，所以手机显示数字键盘，页面脚本运行之前的输入也能生效。

### 键盘
| 按键                   | 动作                                                          |
| ---------------------- | ------------------------------------------------------------- |
| 0 到 9                 | 填充分段，然后移到下一个。                                    |
| ArrowUp / ArrowDown    | 让分段步进一个值，越界时循环。空的分段从今天开始。            |
| PageUp / PageDown      | 用更大的步进移动：年每次 5，月每次 3，日每次 7，分钟每次 15。 |
| Home / End             | 跳到分段的第一个或最后一个值。                                |
| ArrowLeft / ArrowRight | 移到前一个或后一个分段。                                      |
| Backspace              | 删除最后一位数字，然后清空分段，再往回移动。                  |
| Delete                 | 清空分段。                                                    |
| A / P                  | 在 12 小时制的时间里选择 AM 或 PM。                           |
| Enter                  | 用已输入的内容提交表单。                                      |
| Tab / Shift+Tab        | 依次经过各个分段，然后离开输入框。                            |

在从右到左的页面中，分段保持 locale 的顺序，ArrowLeft 和 ArrowRight 跟随屏幕上的顺序。

### 经过测试的行为
下面每一行都是一个自动化测试。

- Each unit is a spinbutton in the locale's order.
- Another locale orders the segments its own way.
- Typing fills each segment, moves on and reports the date once.
- A press on the box or between segments focuses the nearest segment.
- A digit that can't start a longer number moves on at once.
- A separator moves to the next segment.
- Typing with separators over a filled date or time keeps every segment.
- ArrowUp and ArrowDown step a segment and wrap around.
- PageUp and PageDown take bigger steps.
- Home and End go to a segment's first and last values.
- ArrowLeft and ArrowRight move between segments.
- Tab moves through the segments, then out.
- Backspace empties a segment, then moves back.
- A day past the end of a new month is moved back to its last day.
- Pasting a date fills every segment.
- A time takes hours, minutes and AM or PM.
- A 24-hour clock has no AM or PM.
- A date with a time shows its hour and minute too.
- A controller sets and clears the date.
- A canceled change keeps the date.
- The form submits the ISO date and time under their names.
- Enter submits the form with what was typed.
- Enter submits a form with no submit button, in a segment or the form's one text field.
- Resetting the form brings back the default date.
- A partly filled date can't be submitted.
- A required empty date can't be submitted.
- A date after max is invalid.
- An unavailable date is invalid.
- The field's label focuses the first segment.
- A native label for the input focuses the first segment wherever it's pressed. Web components only.
- A read-only date takes focus but doesn't change.
- A disabled date can't be focused.
- Digits committed through an input method fill the segment.

Runs in React、Vue 和 web components.
