输入日期,或从日历中选择,支持范围和表单。

Date Picker 把文本输入框与 Calendar 组合在一起。人们可以用自己的语言输入日期,或从浮层中选择。两种方式下,你的应用都会收到一个 ISO 日期字符串。

<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerContent,
    DatePickerHint,
    DatePickerInput,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"
</script>

<DatePicker defaultValue="2026-10-16">
  <div data-slot="row">
    <DatePickerInput aria-label="Due date" />
    <DatePickerTrigger data-variant="ghost">
      <CalendarIcon aria-hidden="true" />
    </DatePickerTrigger>
  </div>
  <DatePickerHint />
  <DatePickerContent>
    <div data-slot="row">
      <CalendarPrevious data-variant="ghost">
        <ChevronLeftIcon aria-hidden="true" />
      </CalendarPrevious>
      <CalendarHeading />
      <CalendarNext data-variant="ghost">
        <ChevronRightIcon aria-hidden="true" />
      </CalendarNext>
    </div>
    <CalendarGrid>
      <CalendarWeekdays>
        {#snippet children(index)}
          <CalendarWeekday {index} />
        {/snippet}
      </CalendarWeekdays>
      <CalendarWeeks>
        {#snippet children(cell)}
          <CalendarDay value={cell.date} />
        {/snippet}
      </CalendarWeeks>
    </CalendarGrid>
  </DatePickerContent>
</DatePicker>
输入一个日期并按 Enter,或打开日历选择一天。提交后,输入框会格式化这个日期。

安装

npm install @ui-sdk/svelte @ui-sdk/core

组合

用下面的组合构建 DatePicker:

DatePicker
├── DatePickerInput
├── DatePickerTrigger
├── DatePickerHint
└── DatePickerContent

输入框接受日期,触发器打开日历,提示描述期望的格式。空的内容部件会替你渲染一个日历。

每个 Calendar 部件 也能在 DatePickerContent 里使用,并从 Date Picker 入口导出。需要添加样式、更改布局或加入自定义日期内容时,把这些部件写出来。

空的 DatePicker 也会渲染输入框、触发器和日历。在范围模式下,它为每一端渲染一个输入框。

用法

导入部件并把它们组合起来:

<script lang="ts">
  import {
    DatePicker,
    DatePickerContent,
    DatePickerHint,
    DatePickerInput,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
</script>

<DatePicker defaultValue="2026-10-16">
  <DatePickerInput aria-label="Due date" />
  <DatePickerTrigger>Choose date</DatePickerTrigger>
  <DatePickerHint />
  <DatePickerContent />
</DatePicker>

取值

日期是 "2026-10-16" 这样的字符串,不带时间或时区。不需要日期库。

模式值
"single"(默认)一个日期字符串或 null。
"range"[start, end] 或 null,每一端各有一个输入框。

输入日期

按下 Enter 或离开输入框时,输入框会解析文本。它使用 locale 的日期顺序,比如美式英语的 10/16/2026 或德语的 16.10.2026。它也接受 ISO 日期、不带分隔符的数字、两位年份,以及 locale 或英语中的月份名称。没有年份的日期使用当前年份。

提交后,输入框会格式化有效日期;在那之前不会改动你输入的内容。无效文本保持可见,并设置 aria-invalid 和 data-invalid;之前的值保持不变。直到文本重新成为日期或变为空之前,输入框会把“Enter a valid date.”作为校验消息报告,因此它的表单不会提交。提示的状态包含一个示例日期,可以显示在输入框旁边。

<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerContent,
    DatePickerHint,
    DatePickerInput,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"
</script>

<DatePicker defaultValue="2026-10-16">
  <div data-slot="row">
    <DatePickerInput aria-label="Due date" />
    <DatePickerTrigger data-variant="ghost">
      <CalendarIcon aria-hidden="true" />
    </DatePickerTrigger>
  </div>
  <DatePickerContent>
    <div data-slot="row">
      <CalendarPrevious data-variant="ghost">
        <ChevronLeftIcon aria-hidden="true" />
      </CalendarPrevious>
      <CalendarHeading />
      <CalendarNext data-variant="ghost">
        <ChevronRightIcon aria-hidden="true" />
      </CalendarNext>
    </div>
    <CalendarGrid>
      <CalendarWeekdays>
        {#snippet children(index)}
          <CalendarWeekday {index} />
        {/snippet}
      </CalendarWeekdays>
      <CalendarWeeks>
        {#snippet children(cell)}
          <CalendarDay value={cell.date} />
        {/snippet}
      </CalendarWeeks>
    </CalendarGrid>
  </DatePickerContent>
  <DatePickerHint>
    {#snippet children(state)}
      Like {state.example}
    {/snippet}
  </DatePickerHint>
</DatePicker>
输入“not a date”并按 Enter,把输入框标记为无效。把它换成 10/18/2026 来清除无效状态。

范围

mode="range" 用一个输入框表示开始,另一个带 end 的输入框表示结束。选中开始日期后日历保持打开,两个日期都选好后关闭。输入的结束日期早于开始日期时无效。

在两端都有效之前,范围是 null。清除任一输入框会清除整个值,同时保留另一个输入框的日期可见。

要并排显示两个月,设置 months={2},并添加第二个带 offset={1} 的 CalendarGrid。pageBy="page" 会让两个月一起翻页。

<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerContent,
    DatePickerInput,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"

  let field: HTMLElement | undefined = $state()
</script>

<DatePicker
  mode="range"
  months={2}
  monthFormat="short"
  defaultValue={["2026-10-12", "2026-10-16"]}
>
  <div data-slot="row" bind:this={field}>
    <DatePickerInput aria-label="Check in" placeholder="Check in" />
    <span data-slot="hint">–</span>
    <DatePickerInput end aria-label="Check out" placeholder="Check out" />
    <DatePickerTrigger data-variant="ghost">
      <CalendarIcon aria-hidden="true" />
    </DatePickerTrigger>
  </div>
  <DatePickerContent anchor={field} align="center">
    <div data-slot="row">
      <CalendarPrevious data-variant="ghost">
        <ChevronLeftIcon aria-hidden="true" />
      </CalendarPrevious>
      <CalendarHeading />
      <CalendarNext data-variant="ghost">
        <ChevronRightIcon aria-hidden="true" />
      </CalendarNext>
    </div>
    <div data-slot="row">
      <CalendarGrid>
        <CalendarWeekdays>
          {#snippet children(index)}
            <CalendarWeekday {index} />
          {/snippet}
        </CalendarWeekdays>
        <CalendarWeeks>
          {#snippet children(cell)}
            <CalendarDay value={cell.date} />
          {/snippet}
        </CalendarWeeks>
      </CalendarGrid>
      <CalendarGrid offset={1}>
        <CalendarWeekdays>
          {#snippet children(index)}
            <CalendarWeekday {index} />
          {/snippet}
        </CalendarWeekdays>
        <CalendarWeeks>
          {#snippet children(cell)}
            <CalendarDay value={cell.date} />
          {/snippet}
        </CalendarWeeks>
      </CalendarGrid>
    </div>
  </DatePickerContent>
</DatePicker>
选择 October 20,然后选择 October 23。选中第一个日期后日历保持打开,选中第二个后关闭。

预设

DatePickerPreset 会选择它的 value 并关闭浮层。当这个值与当前选择匹配时,它会暴露 aria-pressed 和 data-selected。相对日期(比如最近七天)由你的应用计算。

<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerContent,
    DatePickerInput,
    DatePickerPreset,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"
</script>

<DatePicker mode="range" today="2026-10-16">
  <div data-slot="row">
    <DatePickerInput aria-label="Check in" placeholder="Check in" />
    <span data-slot="hint">–</span>
    <DatePickerInput end aria-label="Check out" placeholder="Check out" />
    <DatePickerTrigger data-variant="ghost">
      <CalendarIcon aria-hidden="true" />
    </DatePickerTrigger>
  </div>
  <DatePickerContent>
    <div data-slot="row">
      <CalendarPrevious data-variant="ghost">
        <ChevronLeftIcon aria-hidden="true" />
      </CalendarPrevious>
      <CalendarHeading />
      <CalendarNext data-variant="ghost">
        <ChevronRightIcon aria-hidden="true" />
      </CalendarNext>
    </div>
    <CalendarGrid>
      <CalendarWeekdays>
        {#snippet children(index)}
          <CalendarWeekday {index} />
        {/snippet}
      </CalendarWeekdays>
      <CalendarWeeks>
        {#snippet children(cell)}
          <CalendarDay value={cell.date} />
        {/snippet}
      </CalendarWeeks>
    </CalendarGrid>
    <div data-slot="row">
      <DatePickerPreset
        data-variant="ghost"
        value={["2026-10-10", "2026-10-16"]}
      >
        Last 7 Days
      </DatePickerPreset>
      <DatePickerPreset
        data-variant="ghost"
        value={["2026-09-17", "2026-10-16"]}
      >
        Last 30 Days
      </DatePickerPreset>
      <DatePickerPreset
        data-variant="ghost"
        value={["2026-10-01", "2026-10-31"]}
      >
        This Month
      </DatePickerPreset>
    </div>
  </DatePickerContent>
</DatePicker>
打开日历并选择 Last 7 Days。再次打开,查看选中的预设。

最小、最大与不可用日期

min、max 和 unavailable 会作用于输入、日历选择、预设和控制器。不符合这些规则的日期在输入时无效,包含这类日期的预设会被禁用,控制器也会拒绝它。选择器被禁用或只读时,控制器也会拒绝值。Calendar 说明了可用的匹配器,以及不可用日期与边界有何不同。

对于范围,minDays 和 maxDays 会把两端都计入。allowUnavailable 允许两端之间存在不可用日期,但端点永远不能是不可用日期。参见范围限制。

<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerContent,
    DatePickerHint,
    DatePickerInput,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"
</script>

<DatePicker
  min="2026-10-05"
  max="2026-11-20"
  unavailable={[{ weekday: [0, 6] }]}
  defaultValue="2026-10-16"
>
  <div data-slot="row">
    <DatePickerInput aria-label="Delivery date" />
    <DatePickerTrigger data-variant="ghost">
      <CalendarIcon aria-hidden="true" />
    </DatePickerTrigger>
  </div>
  <DatePickerHint />
  <DatePickerContent>
    <div data-slot="row">
      <CalendarPrevious data-variant="ghost">
        <ChevronLeftIcon aria-hidden="true" />
      </CalendarPrevious>
      <CalendarHeading />
      <CalendarNext data-variant="ghost">
        <ChevronRightIcon aria-hidden="true" />
      </CalendarNext>
    </div>
    <CalendarGrid>
      <CalendarWeekdays>
        {#snippet children(index)}
          <CalendarWeekday {index} />
        {/snippet}
      </CalendarWeekdays>
      <CalendarWeeks>
        {#snippet children(cell)}
          <CalendarDay value={cell.date} />
        {/snippet}
      </CalendarWeeks>
    </CalendarGrid>
  </DatePickerContent>
</DatePicker>
试着输入 11/21/2026,超过最后允许的日期,再输入 10/17/2026(星期六)。两者都无效且无法选择;10/19/2026 会被接受。

语言

locale 设置输入框的格式、提示、月份名称和日期标签。省略它时,Date Picker 会在挂载后读取周围页面的 lang,并以浏览器语言作为回退。最初的服务器和客户端渲染使用英语,因此两者始终一致。日期字符串仍然是公历 ISO 日期。

触发器、浮层和日历导航默认带有英文无障碍名称。传入 aria-label 也可以翻译这些控件的名称。

Calendar 的 weekStartsOn、weekdayFormat、fixedWeeks、showOutsideDays 和 timeZone 选项在这里同样适用。Calendar 展示了不带浮层的这些选项。

<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerContent,
    DatePickerHint,
    DatePickerInput,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"
</script>

<div lang="de">
  <DatePicker defaultValue="2026-10-16">
    <div data-slot="row">
      <DatePickerInput aria-label="Fälligkeitsdatum" />
      <DatePickerTrigger data-variant="ghost">
        <CalendarIcon aria-hidden="true" />
      </DatePickerTrigger>
    </div>
    <DatePickerHint />
    <DatePickerContent>
      <div data-slot="row">
        <CalendarPrevious data-variant="ghost">
          <ChevronLeftIcon aria-hidden="true" />
        </CalendarPrevious>
        <CalendarHeading />
        <CalendarNext data-variant="ghost">
          <ChevronRightIcon aria-hidden="true" />
        </CalendarNext>
      </div>
      <CalendarGrid>
        <CalendarWeekdays>
          {#snippet children(index)}
            <CalendarWeekday {index} />
          {/snippet}
        </CalendarWeekdays>
        <CalendarWeeks>
          {#snippet children(cell)}
            <CalendarDay value={cell.date} />
          {/snippet}
        </CalendarWeeks>
      </CalendarGrid>
    </DatePickerContent>
  </DatePicker>
</div>
输入 3.12.2026 并按 Enter。输入框、格式提示和日历都使用德语日期。

清除

DatePickerClear 清除值并把焦点移到输入框。没有可清除的内容时,它会得到 data-empty。清空单日期输入框也会清除它的值。

<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerClear,
    DatePickerContent,
    DatePickerHint,
    DatePickerInput,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
    XIcon,
  } from "@lucide/svelte"
</script>

<DatePicker defaultValue="2026-10-16">
  <div data-slot="row">
    <DatePickerInput aria-label="Due date" />
    <DatePickerClear data-variant="ghost" aria-label="Clear date">
      <XIcon aria-hidden="true" />
    </DatePickerClear>
    <DatePickerTrigger data-variant="ghost">
      <CalendarIcon aria-hidden="true" />
    </DatePickerTrigger>
  </div>
  <DatePickerHint />
  <DatePickerContent>
    <div data-slot="row">
      <CalendarPrevious data-variant="ghost">
        <ChevronLeftIcon aria-hidden="true" />
      </CalendarPrevious>
      <CalendarHeading />
      <CalendarNext data-variant="ghost">
        <ChevronRightIcon aria-hidden="true" />
      </CalendarNext>
    </div>
    <CalendarGrid>
      <CalendarWeekdays>
        {#snippet children(index)}
          <CalendarWeekday {index} />
        {/snippet}
      </CalendarWeekdays>
      <CalendarWeeks>
        {#snippet children(cell)}
          <CalendarDay value={cell.date} />
        {/snippet}
      </CalendarWeeks>
    </CalendarGrid>
  </DatePickerContent>
</DatePicker>
按 Clear 清空值并把焦点移到输入框。在有值之前,Clear 按钮会消失。

禁用与只读

disabled 阻止输入、打开和选择。readOnly 允许人们打开日历并查看日期,而不改变值。

<DatePicker disabled defaultValue="2026-10-16" />
<DatePicker readOnly defaultValue="2026-10-16" />

保持打开

把 closeOnSelect 设为 false,可以在选择日期、完成范围或按压预设后保持日历打开。

<DatePicker closeOnSelect={false} />

保持打开,直到两个日期都选好

在选择尚未完成时把 dismissible 设为 false。此时 Escape、外部按压或系统返回手势都会让浮层保持打开。onDismissAttempt 会报告有意的尝试,方便你说明还缺少什么。焦点离开会被静默拒绝。触发器和命令式控件仍然可以关闭它。

<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerContent,
    DatePickerInput,
    DatePickerTrigger,
    type DatePickerValue,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"

  let value = $state<DatePickerValue>(null)
  let asking = $state(false)
</script>

<DatePicker
  bind:value
  mode="range"
  defaultMonth="2026-10"
  dismissible={value !== null}
  onValueChange={() => (asking = false)}
  onOpenChange={(open) => open && (asking = false)}
  onDismissAttempt={() => (asking = true)}
>
  <div data-slot="row">
    <DatePickerInput aria-label="Check in" placeholder="Check in" />
    <span data-slot="hint">–</span>
    <DatePickerInput end aria-label="Check out" placeholder="Check out" />
    <DatePickerTrigger data-variant="ghost">
      <CalendarIcon aria-hidden="true" />
    </DatePickerTrigger>
  </div>
  <DatePickerContent>
    <div data-slot="row">
      <CalendarPrevious data-variant="ghost">
        <ChevronLeftIcon aria-hidden="true" />
      </CalendarPrevious>
      <CalendarHeading />
      <CalendarNext data-variant="ghost">
        <ChevronRightIcon aria-hidden="true" />
      </CalendarNext>
    </div>
    <CalendarGrid>
      <CalendarWeekdays>
        {#snippet children(index)}
          <CalendarWeekday {index} />
        {/snippet}
      </CalendarWeekdays>
      <CalendarWeeks>
        {#snippet children(cell)}
          <CalendarDay value={cell.date} />
        {/snippet}
      </CalendarWeeks>
    </CalendarGrid>
    {#if asking}
      <p data-slot="hint" role="alert">
        Pick a check-out date to finish your stay.
      </p>
    {/if}
  </DatePickerContent>
</DatePicker>
选择一个入住日期,然后在日历外按压。消息会要求先选退房日期,之后才能关闭浮层。

DatePickerContent 默认在输入框下方打开。用 side、align 和偏移量定位它,或提供自定义的 anchor。container 改变它渲染的位置;keepMounted 让它在关闭时保持挂载,finalFocus 控制它关闭后的焦点。浮层涵盖了这些共享选项。

presentation="auto" 在小尺寸触摸屏上使用底部面板(sheet),其他地方使用 popover。presentation="sheet" 始终使用底部面板。用 data-presentation 为两种布局设置样式。

控制台
<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerContent,
    DatePickerHint,
    DatePickerInput,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"
  import { useLog } from "./log"

  const log = useLog()
  let anchor: HTMLElement | undefined = $state()
  let container: HTMLElement | undefined = $state()
</script>

<div data-slot="stack">
  <DatePicker
    defaultOpen={false}
    presentation="auto"
    {container}
    onOpenChange={(open, details) =>
      log(`${open ? "Opened" : "Closed"} (${details.reason})`)}
    onOpenChangeComplete={(open) => open || log("Finished closing")}
    onMonthChange={(month, details) =>
      log(`Showing ${month} (${details.reason})`)}
  >
    <div data-slot="row" bind:this={anchor}>
      <DatePickerInput aria-label="Due date" />
      <DatePickerTrigger data-variant="ghost">
        <CalendarIcon aria-hidden="true" />
      </DatePickerTrigger>
    </div>
    <DatePickerHint />
    <DatePickerContent
      {anchor}
      sideOffset={6}
      collisionPadding={16}
      keepMounted
    >
      <div data-slot="row">
        <CalendarPrevious data-variant="ghost">
          <ChevronLeftIcon aria-hidden="true" />
        </CalendarPrevious>
        <CalendarHeading />
        <CalendarNext data-variant="ghost">
          <ChevronRightIcon aria-hidden="true" />
        </CalendarNext>
      </div>
      <CalendarGrid>
        <CalendarWeekdays>
          {#snippet children(index)}
            <CalendarWeekday {index} />
          {/snippet}
        </CalendarWeekdays>
        <CalendarWeeks>
          {#snippet children(cell)}
            <CalendarDay value={cell.date} />
          {/snippet}
        </CalendarWeeks>
      </CalendarGrid>
    </DatePickerContent>
  </DatePicker>
  <div bind:this={container}></div>
</div>
打开日历。在小尺寸触摸屏上,它会作为底部面板打开,控制台会记录每次打开、关闭和月份变更。

表单

name 提交 ISO 日期。在范围模式下,用 startName 和 endName 分别提交两个字段,或用 name 在同一个名称下提交两端。required 阻止空提交,不是日期的文本也会阻止提交;表单重置会恢复 defaultValue,禁用的 fieldset 会禁用选择器。服务端渲染的隐藏输入框也会在水合之前提交初始值。

在 Field 中,字段把标签、描述和错误连接到输入框,并为必填日期为空或文本不是日期显示错误。选择器没有 name 时使用字段的 name,禁用的字段会禁用选择器。

控制台
<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerContent,
    DatePickerInput,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
  import {
    Field,
    FieldDescription,
    FieldError,
    FieldLabel,
  } from "@ui-sdk/svelte/field"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"
  import { useLog } from "./log"

  const log = useLog()

  function submit(event: SubmitEvent) {
    event.preventDefault()
    log(
      `Submitted due=${new FormData(event.currentTarget as HTMLFormElement).get("due")}`
    )
  }
</script>

<form data-slot="stack" onsubmit={submit}>
  <Field name="due">
    <FieldLabel>Due date</FieldLabel>
    <DatePicker required>
      <div data-slot="row">
        <DatePickerInput />
        <DatePickerTrigger data-variant="ghost">
          <CalendarIcon aria-hidden="true" />
        </DatePickerTrigger>
      </div>
      <DatePickerContent>
        <div data-slot="row">
          <CalendarPrevious data-variant="ghost">
            <ChevronLeftIcon aria-hidden="true" />
          </CalendarPrevious>
          <CalendarHeading />
          <CalendarNext data-variant="ghost">
            <ChevronRightIcon aria-hidden="true" />
          </CalendarNext>
        </div>
        <CalendarGrid>
          <CalendarWeekdays>
            {#snippet children(index)}
              <CalendarWeekday {index} />
            {/snippet}
          </CalendarWeekdays>
          <CalendarWeeks>
            {#snippet children(cell)}
              <CalendarDay value={cell.date} />
            {/snippet}
          </CalendarWeeks>
        </CalendarGrid>
      </DatePickerContent>
    </DatePicker>
    <FieldDescription>When the invoice is due.</FieldDescription>
    <div>
      <FieldError match="valueMissing">Choose a due date.</FieldError>
    </div>
  </Field>
  <button type="submit">Submit</button>
</form>
字段为空时按 Submit,查看内联错误,然后选择日期并提交。控制台会记录 ISO 日期。

受控

选中的值、显示的月份和打开状态彼此独立。value 使用所选模式对应的形状;month 是第一个显示的月份,比如 "2026-10";open 是布尔值。

用 value 配 onValueChange、month 配 onMonthChange、open 配 onOpenChange 来控制它们。defaultValue、defaultMonth 和 defaultOpen 则设置初始状态。变更详情带有原因;details.cancel() 拒绝请求的变更。状态与事件涵盖了绑定写法,原因表列出了 Date Picker 的原因。

控制台
<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    DatePicker,
    DatePickerContent,
    DatePickerHint,
    DatePickerInput,
    DatePickerTrigger,
    type DatePickerValue,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"
  import { useLog } from "./log"

  const log = useLog()
  let value = $state<DatePickerValue>("2026-10-16")
</script>

<DatePicker
  bind:value
  onValueChange={(next, details) =>
    log(`${next ?? "No date"} (${details.reason})`)}
>
  <div data-slot="row">
    <DatePickerInput aria-label="Due date" />
    <DatePickerTrigger data-variant="ghost">
      <CalendarIcon aria-hidden="true" />
    </DatePickerTrigger>
  </div>
  <DatePickerHint />
  <DatePickerContent>
    <div data-slot="row">
      <CalendarPrevious data-variant="ghost">
        <ChevronLeftIcon aria-hidden="true" />
      </CalendarPrevious>
      <CalendarHeading />
      <CalendarNext data-variant="ghost">
        <ChevronRightIcon aria-hidden="true" />
      </CalendarNext>
    </div>
    <CalendarGrid>
      <CalendarWeekdays>
        {#snippet children(index)}
          <CalendarWeekday {index} />
        {/snippet}
      </CalendarWeekdays>
      <CalendarWeeks>
        {#snippet children(cell)}
          <CalendarDay value={cell.date} />
        {/snippet}
      </CalendarWeeks>
    </CalendarGrid>
  </DatePickerContent>
</DatePicker>
输入或选择一个日期。控制台会记录每个值以及变更的原因。

从任意位置驱动

createDatePickerController() 实例可以设置值、显示某个月、打开或关闭浮层,并聚焦打开的日历中的某个日期。控制器涵盖了设置和生命周期;控制器参考列出了这些方法。

<script lang="ts">
  import {
    CalendarDay,
    CalendarGrid,
    CalendarHeading,
    CalendarNext,
    CalendarPrevious,
    CalendarWeekday,
    CalendarWeekdays,
    CalendarWeeks,
    createDatePickerController,
    DatePicker,
    DatePickerContent,
    DatePickerHint,
    DatePickerInput,
    DatePickerTrigger,
  } from "@ui-sdk/svelte/date-picker"
  import {
    CalendarIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
  } from "@lucide/svelte"

  const controller = createDatePickerController()
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => controller.setValue("2026-12-25")}
      >Choose Christmas</button
    >
    <button type="button" onclick={() => controller.open()}>Open</button>
  </div>
  <DatePicker {controller} defaultValue="2026-10-16">
    <div data-slot="row">
      <DatePickerInput aria-label="Due date" />
      <DatePickerTrigger data-variant="ghost">
        <CalendarIcon aria-hidden="true" />
      </DatePickerTrigger>
    </div>
    <DatePickerHint />
    <DatePickerContent>
      <div data-slot="row">
        <CalendarPrevious data-variant="ghost">
          <ChevronLeftIcon aria-hidden="true" />
        </CalendarPrevious>
        <CalendarHeading />
        <CalendarNext data-variant="ghost">
          <ChevronRightIcon aria-hidden="true" />
        </CalendarNext>
      </div>
      <CalendarGrid>
        <CalendarWeekdays>
          {#snippet children(index)}
            <CalendarWeekday {index} />
          {/snippet}
        </CalendarWeekdays>
        <CalendarWeeks>
          {#snippet children(cell)}
            <CalendarDay value={cell.date} />
          {/snippet}
        </CalendarWeeks>
      </CalendarGrid>
    </DatePickerContent>
  </DatePicker>
</div>
按 Choose Christmas 从外部设置日期,或按 Open 打开日历。

样式

根部件、输入框和触发器暴露 data-disabled。无效输入会在该输入框和根部件上设置 data-invalid。根部件和触发器暴露 data-open;预设暴露 data-selected,Clear 暴露 data-empty。日历日期带有 Calendar 的状态属性。

每个部件都有一个 data-slot,比如 date-picker-input,它的状态属性列在数据属性下。

DatePickerContent

变量内容
--anchor-widthWidth of the anchor, usually the trigger. Use it to match widths.
--anchor-heightHeight of the anchor.
--available-widthSpace beside the popup, up to the viewport edge. Not inherited either.
--available-heightSpace between the anchor and the viewport edge. Use it for max-height. Not inherited, so a child that needs it copies it on the popup, like [--list-height:var(--available-height)], and reads max-h-(--list-height). The first popup registers both names for the whole page with CSS.registerProperty, so they don't inherit anywhere. A page that needs them to inherit calls it first, with inherits: true. An @property rule can't, since a registration in script wins.
--transform-originThe point on the anchor the popup opens from. Use it to scale from the right place.
--arrow-offsetWhere the anchor's center falls along the popup's edge, kept arrowPadding from the corners. Position a ::before arrow with it.
--drawer-progressWhile it presents as a sheet: how far open the sheet is, from 0 closed to 1 at its largest snap point. Never past 1.
--drawer-dimWhile it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it.
--drawer-expandWhile it presents as a sheet: 0 at the second-largest snap point and below, 1 at the largest. With one snap point, the whole travel.
--drawer-stackWhile it presents as a sheet: how many sheets opened from inside this one are open above it, rising smoothly as each one opens. Push it back with it.
--sheet-backdropSet it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default.

Viewport

变量内容
--keyboard-insetWhile it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one.
--visual-viewport-widthWhile it presents as a sheet: the width of the part of the page you can see.
--visual-viewport-heightWhile it presents as a sheet: the height of the part of the page you can see, above the keyboard.
--visual-viewport-topWhile it presents as a sheet: how far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.

数据属性

DatePicker

[data-slot="date-picker"]

属性含义
data-modesinglerangeHow the date picker selects.
data-openPresent while the popup is open.
data-closedPresent while the popup is closed, including while it animates out.
data-readonlyPresent when the date can be seen but not changed.
data-disabledPresent when the date picker is disabled.
data-invalidPresent when an input holds text that isn't a date, or a date that can't be picked.

DatePickerInput

[data-slot="date-picker-input"]

属性含义
data-disabledPresent when the date picker is disabled.
data-invalidPresent when an input holds text that isn't a date, or a date that can't be picked.

DatePickerTrigger

[data-slot="date-picker-trigger"]

属性含义
data-openPresent while the popup is open.
data-closedPresent while the popup is closed, including while it animates out.
data-disabledPresent when the date picker is disabled.

DatePickerContent

[data-slot="date-picker-content"]

属性含义
data-openPresent while the popup is open.
data-presentationpopoversheetHow the popup presents this time it's open.
data-closedPresent while the popup is closed, including while it animates out.
data-starting-stylePresent for the first frame. Style the state you animate from.
data-ending-stylePresent while the popup animates out. Style the state you animate to.
data-sidetoprightbottomleftWhere the popup ended up, after flipping away from edges.
data-alignstartcenterendHow the popup lines up with the input.

DatePickerClear

[data-slot="date-picker-clear"]

属性含义
data-emptyPresent when there's no date to clear.

DatePickerPreset

[data-slot="date-picker-preset"]

属性含义
data-selectedPresent while the preset's value is the one selected.

API 参考

属性和回调与下面相同,都作为 Svelte props。

DatePicker

debug?boolean
Logs every state change with its reason to the console, in development builds.
month?string
The first month shown, like "2026-10". Pass it to control the calendar.
defaultMonth?string
The first month it shows, when uncontrolled. Defaults to the selected date's month, else today's.
min?string
The earliest date that can be picked. Keys stop there, and Previous stops at its month.
max?string
The latest date that can be picked.
unavailable?DateMatchers
Dates that can't be picked, like booked days, as data: ISO dates, { from, to }, { weekday: [0, 6] } for weekends, { before }, { after }, or a function. They stay focusable, so keyboard users hear them.
disabled?boolean
Whether nothing can be picked or focused.
readOnly?boolean
Whether dates can be focused but not picked.
months?number
How many months show side by side, each in its own grid.
pageBy?"month" | "page"
Whether Previous, Next and keys turn one month, or all the months shown.
locale?string
The language of the names and labels. Defaults to the page's lang, then the browser's.
weekStartsOn?number
The first day of the week, 0 for Sunday. Defaults to the locale's.
weekdayFormat?"long" | "narrow" | "short"
How weekday headers are written.
monthFormat?"long" | "narrow" | "short"
How month names are written, in the heading and the month select.
fixedWeeks?boolean
Whether every month shows six weeks, so the calendar doesn't change height.
showOutsideDays?boolean
Whether the days of the months before and after show at the edges.
today?string
Today's date, for aria-current and the starting month. Defaults to today in timeZone, read on the client.
timeZone?string
The time zone that says what day today is, like "America/New_York". Defaults to the browser's.
minDays?number
The fewest days a range can span, counting both ends.
maxDays?number
The most days a range can span, counting both ends.
allowUnavailable?boolean
Whether a range may hold unavailable dates, like a stay over a booked night.
container?DocumentFragment | Element | null
Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
mode?DatePickerMode
How many dates it selects: one, or a range from a start to an end, with an input for each.
value?DatePickerValue
The selected value: an ISO date, [start, end] in range mode, or null. Pass it to control the date picker.
defaultValue?DatePickerValue
The value it starts with, when uncontrolled, and goes back to when its form resets.
onValueChange?((value: DatePickerValue, details: ChangeDetails<DatePickerValueChangeReason>) => void)
Runs when a date is picked in the calendar ("item-press"), a typed date is committed on Enter or blur ("input-commit"), a preset or Clear is pressed, the form resets, or a controller sets it. A range changes once both ends are set. details.cancel() keeps the value.
onMonthChange?((month: ISOMonth, details: ChangeDetails<DatePickerMonthChangeReason>) => void)
Runs when the months the calendar shows want to change, as in Calendar, or a typed date or a preset turns them.
open?boolean
Whether the popup is open. Pass it to control the popup.
defaultOpen?boolean
Whether the popup starts open, when uncontrolled.
onOpenChange?((open: boolean, details: ChangeDetails<DatePickerOpenChangeReason>) => void)
Runs when the popup wants to open or close. details.reason says why, and details.cancel() stops it.
onOpenChangeComplete?((open: boolean) => void)
Runs once the popup has finished opening or closing, after any animation.
closeOnSelect?boolean
Whether picking a date, or a range's end, or pressing a preset closes the popup.
presentation?PresentationSetting<"popover">
How the popup presents. "sheet" slides it up from the bottom of the screen, and "auto" does that on small touch screens.
name?string
The name the date submits under, as an ISO date. In range mode, both ends submit under it unless startName and endName are set.
startName?string
The name a range's start submits under.
endName?string
The name a range's end submits under.
form?string
The id of the form it belongs to, when it isn't inside it.
required?boolean
Whether a date must be entered before its form submits.
controller?object
Drives it from anywhere. Create one with createDatePickerController().
dismissible?boolean
Whether Escape, an outside press, focus or the window leaving, Android's back gesture and a sheet's swipe can close it. Triggers, Close parts and the controller always can. Pass false while it holds unsaved work, and ask in onDismissAttempt.
onDismissAttempt?function
Runs when dismissible refused a dismissal made on purpose: Escape, an outside press, back or a swipe. Focus or the window leaving is refused without it. Ask "Discard changes?" here.

DatePickerInput

end?boolean
Whether it's a range's end. The input without it holds the start, or the date.

DatePickerTrigger

打开和关闭日历。渲染一个带有 aria-haspopup="dialog" 的 button,名称来自选中的日期。

DatePickerHint

描述期望的格式,它的状态包含一个示例日期。渲染一个描述输入框的 span。

DatePickerClear

清除值并把焦点移到输入框。渲染一个 button。

DatePickerContent

side?Side
Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the input the popup opens on.
align?Align
How the popup lines up with the anchor along that side. start and end follow the reading direction. How the popup lines up with the input along that side.
sideOffset?number
Gap between the anchor and the popup, in pixels. Gap between the input and the popup, in pixels.
alignOffset?number
Shift along the anchor, in pixels. Shift along the input, in pixels.
collisionPadding?number
Space to keep from the viewport edges, in pixels.
arrowPadding?number
Space to keep between the arrow and the popup's corners, in pixels.
anchor?string | Anchor | null
Positions the popup against this instead of its trigger: an element, a CSS selector, a point like { x, y }, or anything with getBoundingClientRect(). It's read on every check, so it can move. A controller's open({ anchor }) wins for that open.
container?DocumentFragment | Element | null
Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
finalFocus?PopupFocusTarget
Where focus goes when the popup closes while focus is inside it.
keepMounted?boolean
Whether the popup stays in the page, hidden, while closed. Its content keeps its state between opens.

DatePickerPreset

valueDatePickerValue
The value it selects: an ISO date, or [start, end] in range mode.

DatePickerTrigger、DatePickerHint 和 DatePickerClear 没有自己的 props。

状态

每个部件的渲染函数、基于状态的类名和 children 函数会收到什么。

DatePicker:

valueDatePickerValue
The selected value.
modeDatePickerMode
How it selects.
openboolean
Whether the popup is open.
disabledboolean
Whether it can't be used.
readOnlyboolean
Whether dates can be seen but not changed.
invalidboolean
Whether an input holds text that isn't a date that can be picked.

DatePickerInput:

invalidboolean
Whether its text isn't a date that can be picked, after Enter or blur.
disabledboolean
Whether it can't be used.
readOnlyboolean
Whether its text can't be changed.

DatePickerTrigger:

openboolean
Whether the popup is open.
disabledboolean
Whether it can't be pressed.

DatePickerContent:

openboolean
Whether the popup is open. False while it animates out.
presentation"popover" | "sheet"
How it presents this time it's open.

DatePickerHint:

placeholderstring
The format, with a letter for each digit, like "MM/DD/YYYY", "TT.MM.JJJJ" in German.
examplestring
December 31 of this year in the format, like "12/31/2026".

DatePickerPreset:

selectedboolean
Whether its value is the one selected.
disabledboolean
Whether it can't be pressed.

DatePickerClear:

emptyboolean
Whether there's nothing to clear.
disabledboolean
Whether it can't be pressed.

原因

details.reason 说明值为什么改变:

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
input-commitKeyboardEvent | FocusEvent
Enter, or leaving a number input, committed what was typed: a number input parses, clamps and snaps it to the step, and an autocomplete closes its suggestions on it.
preset-press
clear-pressMouseEvent | KeyboardEvent
A Clear part was pressed, like on an input, a select or a combobox.
resetnone
A form reset.
restorenone
The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone
A controller or api call.

浮层为什么打开或关闭:

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
preset-press
imperativenone
A controller or api call.
trigger-pressMouseEvent | KeyboardEvent | TouchEvent
Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its touchend.
outside-pressMouseEvent
A press outside the layer.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
focus-outKeyboardEvent | FocusEvent
Focus left the layer, or Tab moved it out.
window-blurFocusEvent
The window lost focus.
close-pressMouseEvent | KeyboardEvent | SubmitEvent
A Close part was pressed, or a form with method="dialog" was submitted.
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent
A swipe gesture: a finger, mouse or pen dragged it.
anchor-hiddennone
The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.

dismissible 为 false 时,onDismissAttempt 报告的、被拒绝的关闭尝试:

outside-pressMouseEvent
A press outside the layer.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent
A swipe gesture: a finger, mouse or pen dragged it.

控制器

用 createDatePickerController() 创建一个,并作为 controller 传入。

getValue()() => DatePickerValue
The selected value: an ISO date, a [start, end] range, or null.
setValue(value, options?)(value: DatePickerValue, options?: DatePickerChangeOptions<DatePickerValueChangeReason> | undefined) => boolean
Selects a value. Returns false when canceled, unchanged, disabled, read-only, or holding a date people can't pick, like one past max.
clear(options?)(options?: DatePickerChangeOptions<DatePickerValueChangeReason> | undefined) => boolean
Selects nothing, as the Clear part does. Returns false when canceled or unchanged.
getMonth()() => string
The first month the calendar shows, like "2026-10".
setMonth(month, options?)(month: string, options?: DatePickerChangeOptions<DatePickerMonthChangeReason> | undefined) => boolean
Shows a month first. Returns false when canceled or unchanged.
previous(options?)(options?: DatePickerChangeOptions<DatePickerMonthChangeReason> | undefined) => boolean
Shows the months before, as the Previous part does.
next(options?)(options?: DatePickerChangeOptions<DatePickerMonthChangeReason> | undefined) => boolean
Shows the months after, as the Next part does.
focus(date?)(date?: string | undefined) => void
Focuses a date in the open calendar, turning the months to show it, or the date with the tab stop.
isOpen()() => boolean
Whether the popup is open.
setOpen(open, options?)(open: boolean, options?: DatePickerChangeOptions<DatePickerOpenChangeReason> | undefined) => boolean
Opens or closes the popup. Returns false when the change was canceled or it was already open or closed.
open(options?)(options?: (DatePickerChangeOptions<DatePickerOpenChangeReason> & { signal?: AbortSignal | undefined; }) | undefined) => Promise<...>
Opens the popup, and resolves once it closes, with why and how. Resolves exactly once and never rejects: on the next close from any source, when signal aborts, or with reason "unmount" when the date picker leaves the page.
close(options?)(options?: DatePickerChangeOptions<DatePickerOpenChangeReason> | undefined) => boolean
Closes the popup. Returns false when the close was canceled or it was already closed.
toggle(options?)(options?: DatePickerChangeOptions<DatePickerOpenChangeReason> | undefined) => boolean
Opens the popup if it's closed, and closes it if it's open. Returns false when the change was canceled.

事件

回调先收到新值,然后收到详情。只有回调没有取消时,绑定的值才会更新。

属性所属收到
bind:valueDatePicker选中的值
bind:openDatePicker浮层是否打开
bind:monthDatePicker日历的第一个月
onValueChangeDatePicker(value, details):新值,以及原因
onOpenChangeDatePicker(open, details):浮层是否打开,以及原因
onOpenChangeCompleteDatePicker(open):浮层完成打开或关闭后
onMonthChangeDatePicker(month, details):日历新的第一个月,以及原因
onDismissAttemptDatePicker({ reason, event }),在关闭尝试被拒绝时

无障碍

它遵循 WAI-ARIA 日期选择器对话框:一个所有屏幕阅读器都能处理的纯文本输入框,一个带有 aria-haspopup="dialog" 和 aria-expanded、名称来自所选日期的按钮,以及一个容纳日历网格的对话框。对话框打开时焦点移入网格,选中日期或按 Escape 关闭时焦点返回按钮。下面每一行都是一个自动化测试。

键盘

按键位置动作
Enter输入框提交输入的日期。
Alt+Down Arrow输入框打开日历。
Enter / Space触发器打开或关闭日历。
Escape浮层先取消未完成的范围;否则关闭浮层。
Tab / Shift+Tab浮层在控件之间移动。允许关闭时,离开浮层会关闭它。

打开时聚焦选中的日期,否则聚焦今天,再否则聚焦第一个可聚焦的日期。日历的方向键与月份导航在这里同样适用。祖先元素的 dir="rtl" 会反转左右方向键,以跟随视觉顺序。

经过测试的行为

  • A typed date in the page's format becomes the value on Enter, and the form submits it as ISO.
  • Text that isn't a date stays as typed and marks the input invalid.
  • Text that isn't a date blocks the form's submit until it's fixed.
  • Clearing text that isn't a date lets the form submit.
  • A message the app set on the input comes back once the text is a date.
  • The date picker element reports text that isn't a date as its own bad input. 仅在 Web components 运行。
  • The format hint describes the input.
  • The trigger opens a dialog with focus on the selected date, and Escape closes it back to the trigger.
  • With nothing selected, focus goes to today.
  • Picking a day fills the input, closes the dialog and returns focus to the trigger.
  • With closeOnSelect off, the dialog stays open after a pick.
  • Alt+ArrowDown in the input opens the calendar.
  • A typed date opens the calendar on its month.
  • A press outside closes the dialog.
  • A preset selects its value and closes the dialog.
  • Clear empties the value and focuses the input.
  • A form reset puts the default value back.
  • A required date picker blocks an empty submit.
  • Days past min and max can't be typed or picked.
  • German reads and writes dates day first.
Range
  • Picking a start and an end fills both inputs and closes after the end.
  • Each end can be typed, and the value changes once both are set.
  • An end before the start is invalid.
  • An end that isn't a date blocks the form's submit until it's fixed.

运行于 React、Vue 和 web components。