Date Picker
输入日期,或从日历中选择,支持范围和表单。
Date Picker 把文本输入框与 Calendar 组合在一起。人们可以用自己的语言输入日期,或从浮层中选择。两种方式下,你的应用都会收到一个 ISO 日期字符串。
import "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-date-picker default-value="2026-10-16">
<div data-slot="row">
<ui-date-picker-input><input aria-label="Due date" /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-hint></ui-date-picker-hint>
<ui-date-picker-content hidden>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
</ui-date-picker-content>
</ui-date-picker>
`
}
export { mount }安装
npm install @ui-sdk/web @ui-sdk/core导入组件来注册它的元素,包括 Calendar 的元素。这个导入在服务器上也是安全的。
import "@ui-sdk/web/date-picker"组合
用下面的组合构建 ui-date-picker:
ui-date-picker
├── ui-date-picker-input
│ └── input
├── ui-date-picker-trigger
│ └── button
├── ui-date-picker-hint
└── ui-date-picker-content输入框接受日期,触发器打开日历,提示描述期望的格式。空的内容部件会替你渲染一个日历。
每个 Calendar 部件 也能在 ui-date-picker-content 里使用,并由 Date Picker 的导入定义。需要添加样式、更改布局或加入自定义日期内容时,把这些部件写出来。
空的 ui-date-picker 也会渲染输入框、触发器和日历。在范围模式下,它为每一端渲染一个输入框。输入元素会包裹你提供的原生 <input>,或创建一个。触发器、Clear 和预设会包裹一个 <button>,或在它们的内容周围创建一个。
用法
导入部件并把它们组合起来:
<script type="module">
import "@ui-sdk/web/date-picker"
</script>
<ui-date-picker default-value="2026-10-16">
<ui-date-picker-input><input aria-label="Due date" /></ui-date-picker-input>
<ui-date-picker-trigger><button>Choose date</button></ui-date-picker-trigger>
<ui-date-picker-hint></ui-date-picker-hint>
<ui-date-picker-content hidden></ui-date-picker-content>
</ui-date-picker>取值
日期是 "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.”作为校验消息报告,因此它的表单不会提交。提示的状态包含一个示例日期,可以显示在输入框旁边。
import { pageLocale } from "@ui-sdk/core"
import { datePattern } from "@ui-sdk/core/date"
import "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
function mount(root: HTMLElement) {
const { example } = datePattern(pageLocale(root) ?? "en-US")
root.innerHTML = `
<ui-date-picker default-value="2026-10-16">
<div data-slot="row">
<ui-date-picker-input><input aria-label="Due date" /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-content hidden>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
</ui-date-picker-content>
<ui-date-picker-hint>Like ${example}</ui-date-picker-hint>
</ui-date-picker>
`
}
export { mount }范围
mode="range" 用一个输入框表示开始,另一个带 end 的输入框表示结束。选中开始日期后日历保持打开,两个日期都选好后关闭。输入的结束日期早于开始日期时无效。
在两端都有效之前,范围是 null。清除任一输入框会清除整个值,同时保留另一个输入框的日期可见。
要并排显示两个月,设置 months="2",并添加第二个带 offset="1" 的 ui-calendar-grid。page-by="page" 会让两个月一起翻页。
import "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
let count = 0
function mount(root: HTMLElement) {
const id = `date-picker-range-${++count}`
root.innerHTML = `
<ui-date-picker mode="range" months="2" month-format="short" default-value="2026-10-12,2026-10-16">
<div data-slot="row" id="${id}-field">
<ui-date-picker-input><input aria-label="Check in" placeholder="Check in" /></ui-date-picker-input>
<span data-slot="hint">–</span>
<ui-date-picker-input end><input aria-label="Check out" placeholder="Check out" /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-content hidden anchor="#${id}-field" align="center">
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<div data-slot="row">
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
<ui-calendar-grid offset="1">
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
</div>
</ui-date-picker-content>
</ui-date-picker>
`
}
export { mount }预设
ui-date-picker-preset 会选择它的 value 并关闭浮层。当这个值与当前选择匹配时,它会暴露 aria-pressed 和 data-selected。相对日期(比如最近七天)由你的应用计算。在标记中,范围预设保存两个以逗号分隔的 ISO 日期。
import "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-date-picker mode="range" today="2026-10-16">
<div data-slot="row">
<ui-date-picker-input><input aria-label="Check in" placeholder="Check in" /></ui-date-picker-input>
<span data-slot="hint">–</span>
<ui-date-picker-input end><input aria-label="Check out" placeholder="Check out" /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-content hidden>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
<div data-slot="row">
<ui-date-picker-preset value="2026-10-10,2026-10-16"><button data-variant="ghost">Last 7 Days</button></ui-date-picker-preset>
<ui-date-picker-preset value="2026-09-17,2026-10-16"><button data-variant="ghost">Last 30 Days</button></ui-date-picker-preset>
<ui-date-picker-preset value="2026-10-01,2026-10-31"><button data-variant="ghost">This Month</button></ui-date-picker-preset>
</div>
</ui-date-picker-content>
</ui-date-picker>
`
}
export { mount }最小、最大与不可用日期
min、max 和 unavailable 会作用于输入、日历选择、预设和控制器。不符合这些规则的日期在输入时无效,包含这类日期的预设会被禁用,控制器也会拒绝它。选择器被禁用或只读时,控制器也会拒绝值。Calendar 说明了可用的匹配器,以及不可用日期与边界有何不同。
对于范围,min-days 和 max-days 会把两端都计入。allow-unavailable 允许两端之间存在不可用日期,但端点永远不能是不可用日期。参见范围限制。
import "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-date-picker min="2026-10-05" max="2026-11-20" default-value="2026-10-16">
<div data-slot="row">
<ui-date-picker-input><input aria-label="Delivery date" /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-hint></ui-date-picker-hint>
<ui-date-picker-content hidden>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
</ui-date-picker-content>
</ui-date-picker>
`
root.querySelector("ui-date-picker")!.unavailable = [{ weekday: [0, 6] }]
}
export { mount }语言
locale 设置输入框的格式、提示、月份名称和日期标签。省略它时,Date Picker 会在挂载后读取周围页面的 lang,并以浏览器语言作为回退。最初的服务器和客户端渲染使用英语,因此两者始终一致。日期字符串仍然是公历 ISO 日期。
触发器、浮层和日历导航默认带有英文无障碍名称。传入 aria-label 也可以翻译这些控件的名称。
Calendar 的 week-starts-on、weekday-format、fixed-weeks、show-outside-days 和 time-zone 选项在这里同样适用。Calendar 展示了不带浮层的这些选项。
import "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<div lang="de">
<ui-date-picker default-value="2026-10-16">
<div data-slot="row">
<ui-date-picker-input><input aria-label="Fälligkeitsdatum" /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-hint></ui-date-picker-hint>
<ui-date-picker-content hidden>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
</ui-date-picker-content>
</ui-date-picker>
</div>
`
}
export { mount }清除
ui-date-picker-clear 清除值并把焦点移到输入框。没有可清除的内容时,它会得到 data-empty。清空单日期输入框也会清除它的值。
import "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement, X } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-date-picker default-value="2026-10-16">
<div data-slot="row">
<ui-date-picker-input><input aria-label="Due date" /></ui-date-picker-input>
<ui-date-picker-clear>
<button data-variant="ghost" aria-label="Clear date">
${createElement(X, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-clear>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-hint></ui-date-picker-hint>
<ui-date-picker-content hidden>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
</ui-date-picker-content>
</ui-date-picker>
`
}
export { mount }禁用与只读
disabled 阻止输入、打开和选择。read-only 允许人们打开日历并查看日期,而不改变值。
<ui-date-picker disabled default-value="2026-10-16"></ui-date-picker>
<ui-date-picker read-only default-value="2026-10-16"></ui-date-picker>保持打开
把 close-on-select 设为 false,可以在选择日期、完成范围或按压预设后保持日历打开。
<ui-date-picker close-on-select="false"></ui-date-picker>保持打开,直到两个日期都选好
在选择尚未完成时把 dismissible 设为 false。此时 Escape、外部按压或系统返回手势都会让浮层保持打开。dismissattempt 会报告有意的尝试,方便你说明还缺少什么。焦点离开会被静默拒绝。触发器和命令式控件仍然可以关闭它。
import "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-date-picker mode="range" default-month="2026-10" dismissible="false">
<div data-slot="row">
<ui-date-picker-input><input aria-label="Check in" placeholder="Check in" /></ui-date-picker-input>
<span data-slot="hint">–</span>
<ui-date-picker-input end><input aria-label="Check out" placeholder="Check out" /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-content hidden>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
<p data-slot="hint" role="alert" hidden>Pick a check-out date to finish your stay.</p>
</ui-date-picker-content>
</ui-date-picker>
`
const picker = root.querySelector("ui-date-picker")!
const alert = root.querySelector<HTMLElement>('[role="alert"]')!
picker.addEventListener("valuechange", (event) => {
alert.hidden = true
if (event.detail.value === null) {
picker.setAttribute("dismissible", "false")
} else {
picker.removeAttribute("dismissible")
}
})
picker.addEventListener("dismissattempt", () => (alert.hidden = false))
picker.addEventListener("openchange", (event) => {
if (event.detail.value) {
alert.hidden = true
}
})
}
export { mount }浮层与呈现方式
ui-date-picker-content 默认在输入框下方打开。用 side、align 和偏移量定位它,或提供自定义的 anchor。container 改变它渲染的位置;keep-mounted 让它在关闭时保持挂载,final-focus 控制它关闭后的焦点。浮层涵盖了这些共享选项。
presentation="auto" 在小尺寸触摸屏上使用底部面板(sheet),其他地方使用 popover。presentation="sheet" 始终使用底部面板。用 data-presentation 为两种布局设置样式。
import "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
import { log } from "./log"
let count = 0
function mount(root: HTMLElement) {
const id = `date-picker-popup-${++count}`
root.innerHTML = `
<div data-slot="stack">
<ui-date-picker default-open="false" presentation="auto" container="#${id}-container">
<div data-slot="row" id="${id}-anchor">
<ui-date-picker-input><input aria-label="Due date" /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-hint></ui-date-picker-hint>
<ui-date-picker-content hidden anchor="#${id}-anchor" side-offset="6" collision-padding="16" keep-mounted>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
</ui-date-picker-content>
</ui-date-picker>
<div id="${id}-container"></div>
</div>
`
const picker = root.querySelector("ui-date-picker")!
picker.addEventListener("openchange", (event) => {
log(
root,
`${event.detail.value ? "Opened" : "Closed"} (${event.detail.reason})`
)
})
picker.addEventListener("openchangecomplete", (event) => {
if (!event.detail.value) {
log(root, "Finished closing")
}
})
picker.addEventListener("monthchange", (event) => {
log(root, `Showing ${event.detail.value} (${event.detail.reason})`)
})
}
export { mount }表单
name 提交 ISO 日期。在范围模式下,用 start-name 和 end-name 分别提交两个字段,或用 name 在同一个名称下提交两端。required 阻止空提交,不是日期的文本也会阻止提交;表单重置会恢复 default-value,禁用的 fieldset 会禁用选择器。自定义元素定义完成后,才会开始参与表单。
在 Field 中,字段把标签、描述和错误连接到输入框,并为必填日期为空或文本不是日期显示错误。选择器没有 name 时使用字段的 name,禁用的字段会禁用选择器。
import "@ui-sdk/web/date-picker"
import "@ui-sdk/web/field"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<form data-slot="stack">
<ui-field name="due">
<ui-field-label>Due date</ui-field-label>
<ui-date-picker required>
<div data-slot="row">
<ui-date-picker-input><input /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-content hidden>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
</ui-date-picker-content>
</ui-date-picker>
<ui-field-description>When the invoice is due.</ui-field-description>
<div>
<ui-field-error match="valueMissing">Choose a due date.</ui-field-error>
</div>
</ui-field>
<button type="submit">Submit</button>
</form>
`
const form = root.querySelector("form")!
form.addEventListener("submit", (event) => {
event.preventDefault()
log(root, `Submitted due=${new FormData(form).get("due")}`)
})
}
export { mount }受控
选中的值、显示的月份和打开状态彼此独立。value 使用所选模式对应的形状;month 是第一个显示的月份,比如 "2026-10";open 是布尔值。
读取和写入元素的 value、month 和 open property。监听 valuechange、monthchange 和 openchange,并调用 event.preventDefault() 来拒绝变更。用 default-value、default-month 和 default-open 设置初始状态。状态与事件涵盖了绑定写法,原因表列出了 Date Picker 的原因。
import "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-date-picker default-value="2026-10-16">
<div data-slot="row">
<ui-date-picker-input><input aria-label="Due date" /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-hint></ui-date-picker-hint>
<ui-date-picker-content hidden>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
</ui-date-picker-content>
</ui-date-picker>
`
root
.querySelector("ui-date-picker")!
.addEventListener("valuechange", (event) => {
log(root, `${event.detail.value ?? "No date"} (${event.detail.reason})`)
})
}
export { mount }从任意位置驱动
把 createDatePickerController() 实例设置为元素的 controller property,它可以设置值、显示某个月、打开或关闭浮层,并聚焦打开的日历中的某个日期。元素的 api 有同样的方法。控制器涵盖了设置和生命周期;控制器参考列出了这些方法。
import { createDatePickerController } from "@ui-sdk/web/date-picker"
import { Calendar, ChevronLeft, ChevronRight, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<button type="button" data-action="christmas">Choose Christmas</button>
<button type="button" data-action="open">Open</button>
</div>
<ui-date-picker default-value="2026-10-16">
<div data-slot="row">
<ui-date-picker-input><input aria-label="Due date" /></ui-date-picker-input>
<ui-date-picker-trigger>
<button data-variant="ghost">
${createElement(Calendar, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-date-picker-trigger>
</div>
<ui-date-picker-hint></ui-date-picker-hint>
<ui-date-picker-content hidden>
<div data-slot="row">
<ui-calendar-previous>
<button data-variant="ghost">
${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-previous>
<ui-calendar-heading></ui-calendar-heading>
<ui-calendar-next>
<button data-variant="ghost">
${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-calendar-next>
</div>
<ui-calendar-grid>
<ui-calendar-weekdays>
<template><ui-calendar-weekday></ui-calendar-weekday></template>
</ui-calendar-weekdays>
<ui-calendar-weeks>
<template><ui-calendar-day></ui-calendar-day></template>
</ui-calendar-weeks>
</ui-calendar-grid>
</ui-date-picker-content>
</ui-date-picker>
</div>
`
const controller = createDatePickerController()
root.querySelector("ui-date-picker")!.controller = controller
root
.querySelector('[data-action="christmas"]')!
.addEventListener("click", () => controller.setValue("2026-12-25"))
root
.querySelector('[data-action="open"]')!
.addEventListener("click", () => controller.open())
}
export { mount }样式
根部件、输入框和触发器暴露 data-disabled。无效输入会在该输入框和根部件上设置 data-invalid。根部件和触发器暴露 data-open;预设暴露 data-selected,Clear 暴露 data-empty。日历日期带有 Calendar 的状态属性。
每个部件都有一个 data-slot,比如 date-picker-input,它的状态属性列在数据属性下。
<ui-date-picker-content>
| 变量 | 内容 |
|---|---|
--anchor-width | Width of the anchor, usually the trigger. Use it to match widths. |
--anchor-height | Height of the anchor. |
--available-width | Space beside the popup, up to the viewport edge. Not inherited either. |
--available-height | Space 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-origin | The point on the anchor the popup opens from. Use it to scale from the right place. |
--arrow-offset | Where the anchor's center falls along the popup's edge, kept arrowPadding from the corners. Position a ::before arrow with it. |
--drawer-progress | While 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-dim | While it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it. |
--drawer-expand | While 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-stack | While 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-backdrop | Set it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default. |
<ui-date-picker-viewport>
| 变量 | 内容 |
|---|---|
--keyboard-inset | While it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one. |
--visual-viewport-width | While it presents as a sheet: the width of the part of the page you can see. |
--visual-viewport-height | While it presents as a sheet: the height of the part of the page you can see, above the keyboard. |
--visual-viewport-top | While 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. |
数据属性
<ui-date-picker>
[data-slot="date-picker"]
| 属性 | 含义 |
|---|---|
data-mode | singlerangeHow the date picker selects. |
data-open | Present while the popup is open. |
data-closed | Present while the popup is closed, including while it animates out. |
data-readonly | Present when the date can be seen but not changed. |
data-disabled | Present when the date picker is disabled. |
data-invalid | Present when an input holds text that isn't a date, or a date that can't be picked. |
<ui-date-picker-input>
[data-slot="date-picker-input"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when the date picker is disabled. |
data-invalid | Present when an input holds text that isn't a date, or a date that can't be picked. |
<ui-date-picker-trigger>
[data-slot="date-picker-trigger"]
| 属性 | 含义 |
|---|---|
data-open | Present while the popup is open. |
data-closed | Present while the popup is closed, including while it animates out. |
data-disabled | Present when the date picker is disabled. |
<ui-date-picker-content>
[data-slot="date-picker-content"]
| 属性 | 含义 |
|---|---|
data-open | Present while the popup is open. |
data-presentation | popoversheetHow the popup presents this time it's open. |
data-closed | Present while the popup is closed, including while it animates out. |
data-starting-style | Present for the first frame. Style the state you animate from. |
data-ending-style | Present while the popup animates out. Style the state you animate to. |
data-side | toprightbottomleftWhere the popup ended up, after flipping away from edges. |
data-align | startcenterendHow the popup lines up with the input. |
<ui-date-picker-clear>
[data-slot="date-picker-clear"]
| 属性 | 含义 |
|---|---|
data-empty | Present when there's no date to clear. |
<ui-date-picker-preset>
[data-slot="date-picker-preset"]
| 属性 | 含义 |
|---|---|
data-selected | Present while the preset's value is the one selected. |
API 参考
属性是 kebab 形式的,比如 default-value、close-on-select 和 start-name:"false" 表示 false,数字就是数字。value、default-value 和 unavailable 接受以逗号分隔的日期,unavailable property 接受任意匹配器,比如 { weekday: [0, 6] }。container 和 anchor 接受 CSS 选择器,controller 是 property。回调是 DOM 事件。元素与表单关联,因此提交时不需要隐藏输入框。
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-currentand the starting month. Defaults to today intimeZone, 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, ornull. Pass it to control the date picker. defaultValue?DatePickerValue- The value it starts with, when uncontrolled, and goes back to when its form resets.
valuechange event- 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. monthchange event- 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.
openchange event- Runs when the popup wants to open or close.
details.reasonsays why, anddetails.cancel()stops it. openchangecomplete event- 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
startNameandendNameare 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
falsewhile it holds unsaved work, and ask indismissattempt. dismissattempt event- Runs when
dismissiblerefused 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
打开和关闭日历。<ui-date-picker-trigger> 包裹一个带有 aria-haspopup="dialog" 的原生 button,名称来自选中的日期;如果你没有写,它会创建一个。
DatePickerHint
描述期望的格式,它的状态包含一个示例日期。<ui-date-picker-hint> 描述输入框,留空时显示格式。
DatePickerClear
清除值并把焦点移到输入框。<ui-date-picker-clear> 包裹一个原生 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.
startandendfollow 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 withgetBoundingClientRect(). It's read on every check, so it can move. A controller'sopen({ 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.
原因
event.detail.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-pressclear-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
apicall.
浮层为什么打开或关闭:
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
preset-pressimperativenone- A controller or
apicall. 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 时,dismissattempt 报告的、被拒绝的关闭尝试:
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, ornull. 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
signalaborts, 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.
事件
事件在各自的元素上触发,不会冒泡;新值在 event.detail.value 中,reason 和 event 在旁边。调用 preventDefault() 会取消变更。要获得带类型的事件监听器,把元素类型写为 UiDatePickerElement。
| 成员 | 所属 | 说明 |
|---|---|---|
value property | ui-date-picker | 选中的值。设置它会选中该值 |
open property | ui-date-picker | 浮层是否打开。设置它会打开或关闭浮层 |
month property | ui-date-picker | 日历的第一个月。设置它会翻到那个月 |
api property | ui-date-picker | 控制器 |
controller property | ui-date-picker | 来自 createDatePickerController() 的控制器 |
valuechange event | ui-date-picker | detail: { value, reason, event, source } |
openchange event | ui-date-picker | detail: { value: open, reason, event, source } |
openchangecomplete event | ui-date-picker | detail: { value: open },在任何动画结束后 |
monthchange event | ui-date-picker | detail: { value: month, reason, event, source } |
dismissattempt event | ui-date-picker | detail: { 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.
- 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。