TimePickerВыбор времени
TimePicker выбирает время суток в колонках часов, минут и секунд. TimeRangePicker выбирает начало и конец. Значения — обычные объекты Date.
Когда использовать
- Используйте выбор времени, когда выбирают время суток: начало встречи, часы работы, будильник.
- Шаги и запрещённое время сужают колонки до того, что действительно можно выбрать; знакомое время можно напечатать.
- Для связанных начала и конца используйте
TimeRangePicker, а когда важен и день —DatePickerсshowTime.
Примеры
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
let start = $state<Date | null>(null);
const clock = (time: Date | null) => (time ? time.toTimeString().slice(0, 8) : 'nothing');
</script>
<div class="stack">
<div class="field">
<TimePicker aria-label="Start" bind:value={start} />
<span role="status">Value: {clock(start)}</span>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
</style>
format="HH:mm": two columns
14:05
format="HH": the hour alone
a list: the first writes, each reads (try 7.30)
a function writes; nothing typed is read
14 h 5 min
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
const moment = new Date(2026, 0, 1, 14, 5, 9);
</script>
<div class="stack">
<div class="field">
<span class="caption">format="HH:mm": two columns</span>
<TimePicker aria-label="Hours and minutes" format="HH:mm" value={moment} />
</div>
<div class="field">
<span class="caption">format="HH": the hour alone</span>
<TimePicker aria-label="Hour" format="HH" />
</div>
<div class="field">
<span class="caption">a list: the first writes, each reads (try 7.30)</span>
<TimePicker aria-label="Either way" format={['HH:mm', 'H.mm']} />
</div>
<div class="field">
<span class="caption">a function writes; nothing typed is read</span>
<TimePicker aria-label="In words" format={(time) => `${time.getHours()} h ${time.getMinutes()} min`} value={moment} />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
use12Hours: h:mm:ss a
2:05:09 pm
format="h:mm A"
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
const moment = new Date(2026, 0, 1, 14, 5, 9);
</script>
<div class="stack">
<div class="field">
<span class="caption">use12Hours: h:mm:ss a</span>
<TimePicker aria-label="Twelve hours" use12Hours value={moment} />
</div>
<div class="field">
<span class="caption">format="h:mm A"</span>
<TimePicker aria-label="Twelve hours without seconds" format="h:mm A" />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
every 2 hours, 15 minutes and 30 seconds
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
</script>
<div class="stack">
<div class="field">
<span class="caption">every 2 hours, 15 minutes and 30 seconds</span>
<TimePicker aria-label="In steps" hourStep={2} minuteStep={15} secondStep={30} />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
disabledTime: open from 9:00 to 18:30
hideDisabledOptions: they are not shown
<script lang="ts">
import { TimePicker, type DisabledTimes } from 'svelte-ant-design';
const range = (from: number, to: number) => Array.from({ length: to - from }, (_, index) => from + index);
// Open from 9 to 18; in the last hour only the first half.
const openingHours = (): DisabledTimes => ({
disabledHours: () => [...range(0, 9), ...range(19, 24)],
disabledMinutes: (hour) => (hour === 18 ? range(31, 60) : [])
});
</script>
<div class="stack">
<div class="field">
<span class="caption">disabledTime: open from 9:00 to 18:30</span>
<TimePicker aria-label="Visit" format="HH:mm" disabledTime={openingHours} />
</div>
<div class="field">
<span class="caption">hideDisabledOptions: they are not shown</span>
<TimePicker aria-label="Visit, short list" format="HH:mm" disabledTime={openingHours} hideDisabledOptions />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
the value waits for OK; onok says it was confirmed
needConfirm=false: every choice is taken Value: nothing
showNow=false, defaultOpenValue 09:00
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
let taken = $state<Date | null>(null);
let confirmed = $state('');
const nine = new Date(2026, 0, 1, 9, 0);
const clock = (time: Date | null) => (time ? time.toTimeString().slice(0, 8) : 'nothing');
</script>
<div class="stack">
<div class="field">
<span class="caption">the value waits for OK; onok says it was confirmed</span>
<TimePicker aria-label="Confirmed time" onok={(time) => (confirmed = clock(time))} />
{#if confirmed}<span role="status">Confirmed: {confirmed}</span>{/if}
</div>
<div class="field">
<span class="caption">needConfirm=false: every choice is taken</span>
<TimePicker aria-label="Taken at once" needConfirm={false} bind:value={taken} />
<span role="status">Value: {clock(taken)}</span>
</div>
<div class="field">
<span class="caption">showNow=false, defaultOpenValue 09:00</span>
<TimePicker aria-label="From nine" showNow={false} defaultOpenValue={nine} />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
changeOnScroll with needConfirm=false: scroll a column Value: nothing
changeOnScroll: the scrolled time waits for OK
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
let taken = $state<Date | null>(null);
const clock = (time: Date | null) => (time ? time.toTimeString().slice(0, 8) : 'nothing');
</script>
<div class="stack">
<div class="field">
<span class="caption">changeOnScroll with needConfirm=false: scroll a column</span>
<TimePicker aria-label="Scrolled" changeOnScroll needConfirm={false} bind:value={taken} />
<span role="status">Value: {clock(taken)}</span>
</div>
<div class="field">
<span class="caption">changeOnScroll: the scrolled time waits for OK</span>
<TimePicker aria-label="Scrolled and confirmed" changeOnScroll />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { TimeRangePicker, type DateRange } from 'svelte-ant-design';
let shift = $state<DateRange | null>(null);
let last = $state('');
const clock = (time: Date | null) => (time ? time.toTimeString().slice(0, 5) : 'empty');
</script>
<div class="stack">
<div class="field">
<TimeRangePicker
aria-label="Shift"
format="HH:mm"
bind:value={shift}
oncalendarchange={(_, text, { range }) => (last = `${range}: ${text[range === 'start' ? 0 : 1]}`)}
/>
<span role="status">{shift ? `${clock(shift[0])} – ${clock(shift[1])}` : 'No shift chosen'}</span>
{#if last}<span role="status">Last end chosen, {last}</span>{/if}
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(320px, 100%);
}
</style>
order=false: a night shift ends before it starts
allowEmpty: the end may stay empty
disabled={[true, false]}: the start is fixed
09:00 18:00
disabledTime is told which end it is asked for
<script lang="ts">
import { TimeRangePicker, type DisabledTimes, type RangeEnd } from 'svelte-ant-design';
const opening: [Date, Date] = [new Date(2026, 0, 1, 9, 0), new Date(2026, 0, 1, 18, 0)];
// A start in the morning, an end in the afternoon.
const halves = (_: Date | null, end: RangeEnd): DisabledTimes => ({
disabledHours: () => Array.from({ length: 12 }, (_, hour) => (end === 'start' ? hour + 12 : hour))
});
let open = $state('');
</script>
<div class="stack">
<div class="field">
<span class="caption">order=false: a night shift ends before it starts</span>
<TimeRangePicker aria-label="Night shift" format="HH:mm" order={false} separator="to" id={{ start: 'night-from', end: 'night-to' }} />
</div>
<div class="field">
<span class="caption">allowEmpty: the end may stay empty</span>
<TimeRangePicker
aria-label="Opening"
format="HH:mm"
allowEmpty={[false, true]}
placeholder={['Opens', 'Closes (optional)']}
inputLabels={['Opening time', 'Closing time']}
onchange={(_, text) => (open = text.map((part) => part || 'open').join(' – '))}
/>
{#if open}<span role="status">{open}</span>{/if}
</div>
<div class="field">
<span class="caption">{'disabled={[true, false]}'}: the start is fixed</span>
<TimeRangePicker aria-label="Longer day" format="HH:mm" disabled={[true, false]} value={opening} />
</div>
<div class="field">
<span class="caption">disabledTime is told which end it is asked for</span>
<TimeRangePicker aria-label="Two halves" format="HH:mm" disabledTime={halves} />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(320px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { TimeRangePicker } from 'svelte-ant-design';
const at = (hour: number, minute = 0) => new Date(2026, 0, 1, hour, minute);
const presets = [
{ label: 'Morning', value: [at(9), at(13)] as [Date, Date] },
{ label: 'Evening', value: [at(14), at(18)] as [Date, Date] }
];
</script>
<div class="stack">
<div class="field">
<TimeRangePicker aria-label="Meeting hours" format="HH:mm" {presets} />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(320px, 100%);
}
</style>
disabled
14:30:00
inputReadOnly: chosen in the panel only
14:30:00
allowClear=false
14:30:00
allowClear with its own icon and name
14:30:00
placeholder
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
const moment = new Date(2026, 0, 1, 14, 30);
</script>
<div class="stack">
<div class="field">
<span class="caption">disabled</span>
<TimePicker aria-label="Disabled time" disabled value={moment} />
</div>
<div class="field">
<span class="caption">inputReadOnly: chosen in the panel only</span>
<TimePicker aria-label="Chosen only" inputReadOnly value={moment} />
</div>
<div class="field">
<span class="caption">allowClear=false</span>
<TimePicker aria-label="Always set" allowClear={false} value={moment} />
</div>
<div class="field">
<span class="caption">allowClear with its own icon and name</span>
<TimePicker aria-label="Reset" allowClear={{ label: 'Reset the time', clearIcon: '↺' }} value={moment} />
</div>
<div class="field">
<span class="caption">placeholder</span>
<TimePicker aria-label="Alarm" placeholder="Wake me at" />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
large
medium
small
<script lang="ts">
import { TimePicker, TimeRangePicker } from 'svelte-ant-design';
const sizes = ['large', 'medium', 'small'] as const;
</script>
<div class="stack">
{#each sizes as size (size)}
<div class="field">
<span class="caption">{size}</span>
<TimePicker aria-label="Time, {size}" {size} />
<TimeRangePicker aria-label="Range, {size}" {size} />
</div>
{/each}
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(320px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
outlined
filled
borderless
underlined
<script lang="ts">
import { TimePicker, TimeRangePicker } from 'svelte-ant-design';
const variants = ['outlined', 'filled', 'borderless', 'underlined'] as const;
</script>
<div class="stack">
{#each variants as variant (variant)}
<div class="field">
<span class="caption">{variant}</span>
<TimePicker aria-label="Time, {variant}" {variant} />
<TimeRangePicker aria-label="Range, {variant}" {variant} />
</div>
{/each}
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(320px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
</script>
<div class="stack">
<div class="field">
<TimePicker aria-label="Time with an error" status="error" aria-describedby="time-error" />
<span id="time-error">Choose a time during opening hours.</span>
</div>
<div class="field">
<TimePicker aria-label="Time with a warning" status="warning" aria-describedby="time-warning" />
<span id="time-warning">The office is busy at this hour.</span>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
</style>
prefix
From
suffix replaces the clock
UTC
suffix={null}: no icon
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
</script>
<div class="stack">
<div class="field">
<span class="caption">prefix</span>
<TimePicker aria-label="Departure" prefix="From" />
</div>
<div class="field">
<span class="caption">suffix replaces the clock</span>
<TimePicker aria-label="Arrival" suffix="UTC" />
</div>
<div class="field">
<span class="caption">{'suffix={null}'}: no icon</span>
<TimePicker aria-label="Plain" suffix={null} />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
cellRender: the full quarters are marked; extraFooter as a text
extraFooter as a snippet
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
</script>
<div class="stack">
<div class="field">
<span class="caption">cellRender: the full quarters are marked; extraFooter as a text</span>
<TimePicker aria-label="Quarter" format="HH:mm" extraFooter="Times of the local zone">
{#snippet cellRender({ column, value, text })}
<span class:quarter={column === 'minute' && value % 15 === 0}>{text}</span>
{/snippet}
</TimePicker>
</div>
<div class="field">
<span class="caption">extraFooter as a snippet</span>
<TimePicker aria-label="With a note">
{#snippet extraFooter()}<strong>Closed on Sundays</strong>{/snippet}
</TimePicker>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.quarter {
text-decoration: underline 2px var(--ads-color-primary);
text-underline-offset: 3px;
}
</style>
open held by the page Opened by the field 0 times
placement="topRight"
container: the panel is drawn inside the box
<script lang="ts">
import { Button, TimePicker } from 'svelte-ant-design';
let open = $state(false);
let opened = $state(0);
let box = $state<HTMLDivElement>();
</script>
<div class="stack">
<div class="field">
<span class="caption">open held by the page</span>
<TimePicker aria-label="Controlled panel" bind:open onopenchange={(next) => next && opened++} />
<Button onclick={() => (open = true)}>Open the panel</Button>
<span role="status">Opened by the field {opened} times</span>
</div>
<div class="field">
<span class="caption">placement="topRight"</span>
<TimePicker aria-label="Above the field" placement="topRight" />
</div>
<div class="field">
<span class="caption">container: the panel is drawn inside the box</span>
<div class="box" bind:this={box}>
<TimePicker aria-label="Inside the box" container={() => box ?? document.body} />
</div>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
.box {
position: relative;
justify-self: stretch;
padding: 12px;
border: 1px dashed var(--ads-color-border);
}
</style>
ru, with the halves of the day in words
9:05 утра
zh-cn
上午9:05
ru, a range
<script lang="ts">
import { TimePicker, TimeRangePicker } from 'svelte-ant-design';
import ru from 'svelte-ant-design/locales/ru';
import zhCn from 'svelte-ant-design/locales/zh-cn';
const moment = new Date(2026, 0, 1, 9, 5);
</script>
<div class="stack">
<div class="field">
<span class="caption">ru, with the halves of the day in words</span>
<TimePicker aria-label="Время" locale={ru} format="h:mm A" value={moment} />
</div>
<div class="field">
<span class="caption">zh-cn</span>
<TimePicker aria-label="时间" locale={zhCn} format="Ah:mm" value={moment} />
</div>
<div class="field">
<span class="caption">ru, a range</span>
<TimeRangePicker aria-label="Смена" locale={ru} format="HH:mm" />
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(320px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
</style>
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
let log = $state<string[]>([]);
const note = (line: string) => (log = [line, ...log].slice(0, 4));
</script>
<div class="stack">
<div class="field">
<TimePicker
aria-label="Watched time"
onchange={(_, text) => note(`onchange: ${text || 'empty'}`)}
onclear={() => note('onclear')}
onfocus={() => note('onfocus')}
onblur={() => note('onblur')}
/>
<ul class="log" aria-live="polite">
{#each log as line, index (index)}<li>{line}</li>{/each}
</ul>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.log {
min-height: 5.5em;
margin: 0;
padding-inline-start: 18px;
}
</style>
Departure
<script lang="ts">
import { Button, Select, SpaceCompact, TimePicker } from 'svelte-ant-design';
let kind = $state('Departure');
</script>
<div class="stack">
<div class="field">
<SpaceCompact block>
<Select aria-label="Kind of time" bind:value={kind} options={['Departure', 'Arrival']} style="width: 140px" />
<TimePicker aria-label="Time of the trip" />
<Button type="primary">Search</Button>
</SpaceCompact>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(420px, 100%);
}
</style>
classNames and styles
<script lang="ts">
import { TimePicker } from 'svelte-ant-design';
</script>
<div class="stack">
<div class="field">
<span class="caption">classNames and styles</span>
<TimePicker
aria-label="Styled time"
class="rounded"
style="max-width: 240px"
classNames={{ popup: 'soft', input: 'strong', cell: 'digit' }}
styles={{ root: { 'border-radius': '16px' }, suffix: { color: 'var(--ads-color-primary)' } }}
/>
</div>
</div>
<style>
.stack {
display: grid;
justify-items: start;
gap: 16px;
}
.field {
display: grid;
justify-items: start;
gap: 6px;
width: min(240px, 100%);
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
:global(.rounded .strong) {
font-weight: 600;
}
:global(.soft .digit) {
font-variant-numeric: tabular-nums;
font-weight: 500;
}
</style>
API
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| value | Выбранное время (на дате). Связывается через bind:value. | Date | null | null |
| format | Как пишется время; в списке первый шаблон пишет, читает любой. Шаблон решает, какие колонки есть. С use12Hours по умолчанию h:mm:ss a. | string | string[] | (date: Date) => string | 'HH:mm:ss' |
| use12Hours | Часы от 1 до 12 и колонка AM/PM. | boolean | false |
| hourStep | Каждый n-й час. | number | 1 |
| minuteStep | Каждая n-я минута. | number | 1 |
| secondStep | Каждая n-я секунда. | number | 1 |
| disabledTime | Часы, минуты и секунды, которые нельзя выбрать; аргумент — выбранное или проверяемое время, null, пока ничего не выбрано. | (date: Date | null) => DisabledTimes | — |
| hideDisabledOptions | Недоступные числа не показываются. | boolean | false |
| defaultOpenValue | Время и дата, с которых начинается выбор; без него — сегодня в 00:00:00. | Date | — |
| needConfirm | Значение меняется только по OK. | boolean | true |
| showNow | Кнопка «Сейчас». | boolean | true |
| changeOnScroll | Выбирается число, на котором колонка остановилась после прокрутки пользователем. | boolean | false |
| cellRender | Содержимое числа: { column, value, text, selected, disabled, range }. | Snippet<[cell: TimeCell]> | — |
| extraFooter | Под колонками. | string | Snippet | — |
| placeholder | Подсказка пустого поля; по умолчанию из локали. | string | — |
| disabled | Поле недоступно. | boolean | false |
| inputReadOnly | В поле нельзя печатать; телефон не показывает клавиатуру. | boolean | false |
| allowClear | Кнопка очистки; объект меняет значок, имя и tabindex. | boolean | { clearIcon?, label?, tabIndex? } | true |
| size | medium, если не задан SpaceCompact; middle и default — алиасы. | 'large' | 'medium' | 'middle' | 'small' | 'default' | — |
| variant | Вид поля. | 'outlined' | 'filled' | 'borderless' | 'underlined' | 'outlined' |
| status | Красит поле как ошибку или предупреждение; error ставит aria-invalid. | 'error' | 'warning' | — |
| prefix | Перед текстом. | string | Snippet | — |
| suffix | Заменяет значок часов; null убирает его. | string | Snippet | null | — |
| open | Показана ли панель. Связывается через bind:open. | boolean | false |
| placement | Предпочитаемое положение панели; у края экрана она переворачивается. | 'bottomLeft' | 'bottomRight' | 'topLeft' | 'topRight' | 'bottomLeft' |
| container | Куда помещается панель (по умолчанию в конец <body>). | HTMLElement | (anchor) => HTMLElement | — |
| locale | Тексты и названия AM/PM: import ru from 'svelte-ant-design/locales/ru'. | DatePickerLocale | en |
| onchange | Пользователь изменил значение; второй аргумент — текст. | (value, text: string) => void | — |
| onok | Время подтверждено OK или Enter при needConfirm. | (value: Date) => void | — |
| onopenchange | Панель открылась или закрылась. | (open: boolean) => void | — |
| onclear | Кнопка очистки опустошила значение. | () => void | — |
| onfocus | Фокус пришёл в поле или панель снаружи. | (event: FocusEvent) => void | — |
| onblur | Фокус ушёл и из поля, и из панели. | (event: FocusEvent) => void | — |
| classNames | Дополнительные классы частей root, input, prefix, suffix, popup, body, cell, footer. | TimePickerClassNames | — |
| styles | Инлайн-стили тех же частей. | TimePickerStyles | — |
| class / style | Класс и стиль поля. | string | — |
| native attributes | Остальные атрибуты достаются <input> (id, name, aria-*, autofocus). | HTMLInputAttributes | — |
Отличия от Ant Design: значения — обычные
Date, а не dayjs; TimePicker.RangePicker называется TimeRangePicker; от одного фокуса панель не открывается; клавиатура следует ARIA-шаблонам combobox и listbox; у диапазона есть кнопка «Сейчас». В этой версии нет: миллисекунд, маски format, previewValue, panelRender, своих кнопок в подвале, presets у одиночного TimePicker и другой библиотеки дат.TimeRangePicker
TimeRangePicker принимает пропсы TimePicker; эти отличаются или есть только у него.
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
| value | Начало и конец; невыбранный конец — null. Связывается через bind:value. | [Date | null, Date | null] | null | null |
| placeholder | Подсказки двух полей; по умолчанию из локали. | [string, string] | — |
| inputLabels | Доступные имена двух полей; по умолчанию из локали. | [string, string] | — |
| disabled | Оба конца или каждый. Отключённый конец сохраняет значение и ограничивает порядок. | boolean | [boolean, boolean] | false |
| allowEmpty | Конец, который может остаться пустым. | [boolean, boolean] | [false, false] |
| separator | Между полями; по умолчанию стрелка. | string | Snippet | — |
| order | Начало не позже конца по времени суток: два выбранных сейчас конца меняются местами, прежний конец спрашивается заново. | boolean | true |
| id | Идентификаторы двух полей. | { start?: string; end?: string } | — |
| autofocus | Поле начала получает фокус при загрузке. | boolean | false |
| disabledTime | Недоступное время для спрашиваемого конца. | (date: Date | null, range: 'start' | 'end') => DisabledTimes | — |
| presets | Быстрые варианты, задающие оба конца. | { label: string | Snippet; value: [Date, Date] | (() => [Date, Date]) }[] | [] |
| onchange | Диапазон изменился: один раз, когда он полон. | (value, text: [string, string]) => void | — |
| oncalendarchange | Выбран конец; range говорит какой. | (value, text, info: { range }) => void | — |
| onok | Диапазон подтверждён OK или Enter при needConfirm. | (value) => void | — |
| onfocus | Фокус пришёл в поле или панель снаружи. | (event, info: { range }) => void | — |
| onblur | Фокус ушёл и из поля, и из панели. | (event, info: { range }) => void | — |
| native attributes | Остальные атрибуты достаются корню — группе (group): aria-label, data-*. | HTMLAttributes<HTMLDivElement> | — |
Методы
| Метод | Описание | Тип |
|---|---|---|
| focus | Переводит фокус в поле; в диапазоне — на спрашиваемый конец. Панель не открывается. | (options?: FocusOptions) => void |
| blur | Снимает фокус с поля; панель закрывается. | () => void |
Дизайн-токены
| Токен | Описание | По умолчанию |
|---|---|---|
| --ads-time-picker-column-height | Высота колонок. | 224px |
| --ads-picker-time-column-width | Ширина колонки. | 56px |
| --ads-picker-time-item-height | Высота числа. | 28px |
| --ads-picker-time-selected-bg | Выбранное число. | #e6f4ff |
| --ads-picker-cell-hover-bg | Число под указателем. | rgba(0, 0, 0, 0.04) |
| --ads-picker-popup-radius | Радиус скругления панели. | 8px |
| --ads-picker-popup-bg | Фон панели. | #ffffff |
| --ads-picker-popup-shadow | Тень панели. | 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 9px 28px 8px rgba(0, 0, 0, 0.05) |
| --ads-picker-actions-height | Минимальная высота кнопок под колонками. | 42px |
| --ads-picker-presets-width | Ширина колонки быстрых вариантов. | 120px |
| --ads-picker-icon-color | Значки поля. | rgba(0, 0, 0, 0.45) |
Клавиатура
Стрелка внизв поле открывает панель и переводит фокус в первую колонку.- В колонке
↑и↓меняют число,HomeиEndведут к её краям,←и→— в соседнюю колонку. EnterилиПробелвыбирают число;Enterна выбранном подтверждает то, что ждёт OK. В диапазоне фокус переходит в поле другого конца.Escapeзакрывает панель, отбрасывает неподтверждённое и возвращает фокус в поле.Tabуводит фокус из поля и закрывает панель; в диапазоне сначала переходит от начала к концу. В панели обходит колонки (по одной остановке) и подвал.
Доступность
- Поле — это
combobox, связанный с диалогом; каждая колонка —listboxс именем, её числа — пункты, у которых отмечено, что выбрано и что запрещено. - Диапазон —
groupс двумя названными полями; диалог говорит, какой конец он спрашивает. Назовите группу черезaria-label. - Цвета светлой темы по умолчанию повторяют Ant Design и не все дают контраст 4.5:1; для этого подключите
tokens-accessible.css. Выбранные и запрещённые числа видны в режиме принудительных цветов. - Проверено настоящим скринридером (Orca с Firefox): он читает поле, имя диалога, колонки и их числа, значение после подтверждения и концы диапазона. Orca сам не произносит значение такого поля, поэтому каждое поле ввода даёт его и как своё описание: NVDA, JAWS и VoiceOver, не проверенные, могут произнести его дважды. Orca не сообщает, что число запрещено, а на
Enter, выбирающий число, произносит только клавишу. NVDA, JAWS, VoiceOver и телефоном не проверено.