@barqjs/aria 0.0.0-stage → 0.2.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +304 -2
  3. package/package.json +437 -4
  4. package/src/autocomplete.tsx +581 -0
  5. package/src/breadcrumbs.tsx +297 -0
  6. package/src/button.tsx +468 -0
  7. package/src/calendar.tsx +2316 -0
  8. package/src/checkbox.tsx +732 -0
  9. package/src/collections.ts +1059 -0
  10. package/src/color.ts +2119 -0
  11. package/src/colorpicker.tsx +2023 -0
  12. package/src/colorswatchpicker.tsx +240 -0
  13. package/src/combobox.tsx +3003 -0
  14. package/src/command.tsx +1203 -0
  15. package/src/date.ts +674 -0
  16. package/src/datefield.tsx +2066 -0
  17. package/src/datepicker.tsx +907 -0
  18. package/src/dialog.tsx +1077 -0
  19. package/src/disclosure.tsx +711 -0
  20. package/src/dnd/clipboard.ts +125 -0
  21. package/src/dnd/collection.ts +1265 -0
  22. package/src/dnd/data.ts +409 -0
  23. package/src/dnd/drag-drop.ts +801 -0
  24. package/src/dnd/index.ts +133 -0
  25. package/src/dnd/manager.ts +639 -0
  26. package/src/dnd/strings.ts +1279 -0
  27. package/src/dnd/targets.ts +726 -0
  28. package/src/dnd/types.ts +212 -0
  29. package/src/dom.ts +703 -0
  30. package/src/drag-and-drop.tsx +669 -0
  31. package/src/drawer.ts +674 -0
  32. package/src/dropzone.tsx +208 -0
  33. package/src/file-trigger.tsx +103 -0
  34. package/src/focus.ts +1370 -0
  35. package/src/form.tsx +94 -0
  36. package/src/gridlist.tsx +1354 -0
  37. package/src/group.tsx +146 -0
  38. package/src/i18n.ts +823 -0
  39. package/src/index.ts +1672 -0
  40. package/src/interactions/description.ts +73 -0
  41. package/src/interactions/flags.ts +35 -0
  42. package/src/interactions/focus-events.ts +226 -0
  43. package/src/interactions/focusable.ts +86 -0
  44. package/src/interactions/hover.ts +213 -0
  45. package/src/interactions/interact-outside.ts +123 -0
  46. package/src/interactions/keyboard.ts +298 -0
  47. package/src/interactions/listeners.ts +78 -0
  48. package/src/interactions/long-press.ts +160 -0
  49. package/src/interactions/modality.ts +428 -0
  50. package/src/interactions/move.ts +257 -0
  51. package/src/interactions/open-link.ts +226 -0
  52. package/src/interactions/press.ts +915 -0
  53. package/src/interactions/prevent-focus.ts +102 -0
  54. package/src/interactions/scroll-wheel.ts +43 -0
  55. package/src/interactions/text-selection.ts +77 -0
  56. package/src/interactions.ts +81 -0
  57. package/src/label.ts +140 -0
  58. package/src/link.tsx +477 -0
  59. package/src/listbox.tsx +1247 -0
  60. package/src/live.ts +208 -0
  61. package/src/menu.tsx +2383 -0
  62. package/src/menubar.tsx +579 -0
  63. package/src/navigation-tree.tsx +357 -0
  64. package/src/navigation.ts +735 -0
  65. package/src/numberfield.tsx +942 -0
  66. package/src/otp.ts +430 -0
  67. package/src/overlay-arrow.tsx +157 -0
  68. package/src/overlays.ts +1549 -0
  69. package/src/platform.ts +75 -0
  70. package/src/presence.ts +164 -0
  71. package/src/preview-trigger.tsx +582 -0
  72. package/src/progress-bar-context.ts +15 -0
  73. package/src/questionnaire.tsx +1717 -0
  74. package/src/radio.tsx +641 -0
  75. package/src/register-dom.ts +12 -0
  76. package/src/scroller.ts +1165 -0
  77. package/src/select.tsx +1745 -0
  78. package/src/selection-indicator.tsx +74 -0
  79. package/src/selection.ts +1472 -0
  80. package/src/shared-element-transition.tsx +316 -0
  81. package/src/sheet.tsx +1461 -0
  82. package/src/slider.tsx +1137 -0
  83. package/src/splitter.ts +1152 -0
  84. package/src/static-collection.ts +211 -0
  85. package/src/switch.tsx +212 -0
  86. package/src/table.tsx +2218 -0
  87. package/src/tabs.tsx +1127 -0
  88. package/src/tag.tsx +637 -0
  89. package/src/textarea.tsx +186 -0
  90. package/src/textfield.tsx +483 -0
  91. package/src/toast-components.tsx +589 -0
  92. package/src/toast.ts +658 -0
  93. package/src/toggle-button-group.tsx +175 -0
  94. package/src/toggle-input.tsx +86 -0
  95. package/src/toggle.ts +384 -0
  96. package/src/togglegroup.ts +365 -0
  97. package/src/tokenfield.tsx +1673 -0
  98. package/src/toolbar.tsx +184 -0
  99. package/src/tooltip.tsx +674 -0
  100. package/src/tree.tsx +2075 -0
  101. package/src/utils.ts +787 -0
  102. package/src/validation.ts +504 -0
  103. package/src/virtualizer.tsx +837 -0
@@ -0,0 +1,2066 @@
1
+ /**
2
+ * A date field: one segment per part, in the locale's own order.
3
+ *
4
+ * Not `<input type="date">`, which cannot be styled, cannot be given a range
5
+ * the browser will respect consistently, and shows the format the OS chose
6
+ * rather than the one the page is in. And not a text box either: "03/04/2024"
7
+ * is the 3rd of April in London and the 4th of March in New York, and a field
8
+ * that asks the user to guess which will get both.
9
+ *
10
+ * So each part is its own segment, ordered and separated by
11
+ * `Intl.DateTimeFormat.formatToParts`, and each is a spin button:
12
+ *
13
+ * - **Typing fills the segment and moves on.** Typing 4 in a month segment
14
+ * means April and jumps to the day, because no month starts with 4 that
15
+ * isn't 4. Typing 1 waits, because 1, 10, 11 and 12 all begin with it.
16
+ * - **The arrows cycle within the segment.** December plus one is January of
17
+ * the SAME year: the user is editing the month, not the date.
18
+ * - **An empty field is a PLACEHOLDER, not a value.** It shows a shape to fill
19
+ * in, and the field has no value at all until every segment is filled — a
20
+ * half-typed date is not a date, and reporting one would submit it.
21
+ * - **What is typed is kept as typed.** A day segment takes 31 whatever month
22
+ * is showing, because in a day-first locale the day is typed before the
23
+ * month that decides how long it is. A date that does not exist, the 31st
24
+ * of February, is held until the field is left and only then made into one
25
+ * that does.
26
+ */
27
+
28
+ import {
29
+ cells,
30
+ type Accessor,
31
+ type Child,
32
+ For,
33
+ createMemo,
34
+ createContext,
35
+ createEffect,
36
+ getContext,
37
+ type Incoming,
38
+ provide,
39
+ createSignal,
40
+ untrack,
41
+ } from "@barqjs/core";
42
+ import { isServer } from "@barqjs/web";
43
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
44
+ import {
45
+ CalendarDate,
46
+ CalendarDateTime,
47
+ Time,
48
+ today,
49
+ toCalendarDate,
50
+ type DateValue,
51
+ } from "./date.ts";
52
+ import { contains } from "./dom.ts";
53
+ import { focusRing } from "./focus.ts";
54
+ import {
55
+ dateFormatter,
56
+ filter,
57
+ numberFormatter,
58
+ numberParser,
59
+ type LocalizedString,
60
+ StringDictionary,
61
+ stringFormatter,
62
+ useLocale,
63
+ } from "./i18n.ts";
64
+ import { hover } from "./interactions/hover.ts";
65
+ import type { ElementRef } from "./interactions/press.ts";
66
+ import { field, type FieldOptions } from "./label.ts";
67
+ import { isIOS } from "./platform.ts";
68
+ import { formReset } from "./toggle.ts";
69
+ import {
70
+ fieldValidation,
71
+ formValidation,
72
+ type ValidationResult,
73
+ type FormValidationState,
74
+ type ValidateFunction,
75
+ type ValidationBehavior,
76
+ } from "./validation.ts";
77
+ import {
78
+ access,
79
+ callback,
80
+ controllable,
81
+ type DOMProps,
82
+ filterDOMProps,
83
+ fromProps,
84
+ type MaybeAccessor,
85
+ mergeProps,
86
+ type StyleProps,
87
+ styleProps,
88
+ } from "./utils.ts";
89
+
90
+ // ---------------------------------------------------------------------------
91
+ // Segments
92
+ // ---------------------------------------------------------------------------
93
+
94
+ export type SegmentType =
95
+ | "year"
96
+ | "month"
97
+ | "day"
98
+ | "hour"
99
+ | "minute"
100
+ | "second"
101
+ | "dayPeriod"
102
+ | "literal";
103
+
104
+ export interface DateSegment {
105
+ type: SegmentType;
106
+ /** What it shows: the value, or the placeholder standing in for it. */
107
+ text: string;
108
+ value?: number;
109
+ minValue?: number;
110
+ maxValue?: number;
111
+ /** Nothing has been typed here yet. */
112
+ isPlaceholder: boolean;
113
+ /** What it shows while it is empty. */
114
+ placeholder?: string;
115
+ /** A separator is not a segment the user can stand in. */
116
+ isEditable: boolean;
117
+ }
118
+
119
+ /** How much of a date the field asks for. */
120
+ export type Granularity = "day" | "hour" | "minute" | "second";
121
+
122
+ type HourCycle = "h11" | "h12" | "h23" | "h24";
123
+ type EditableType = Exclude<SegmentType, "literal">;
124
+
125
+ const EDITABLE: readonly EditableType[] = [
126
+ "year",
127
+ "month",
128
+ "day",
129
+ "hour",
130
+ "dayPeriod",
131
+ "minute",
132
+ "second",
133
+ ];
134
+
135
+ /**
136
+ * Puts `text` back into a segment a composition wrote into.
137
+ *
138
+ * Into the text node that is already there rather than through
139
+ * `textContent`, which would replace the node the segment's text is rendered
140
+ * into and leave every later value written to a node no longer on the page.
141
+ */
142
+ function writeText(element: HTMLElement, text: string): void {
143
+ let kept: Text | null = null;
144
+ for (const node of Array.from(element.childNodes)) {
145
+ if (node.nodeType === Node.COMMENT_NODE) continue;
146
+ if (kept === null && node instanceof Text) kept = node;
147
+ else node.remove();
148
+ }
149
+ if (kept === null) element.append(text);
150
+ else kept.data = text;
151
+ }
152
+
153
+ /** A 24-hour hour as the hour cycle writes it, and which half of the day it is in. */
154
+ function toHourCycle(hour: number, cycle: HourCycle): [number | null, number] {
155
+ const period = hour >= 12 ? 1 : 0;
156
+ switch (cycle) {
157
+ case "h11":
158
+ return [period, hour >= 12 ? hour - 12 : hour];
159
+ case "h12":
160
+ return [period, hour === 0 ? 12 : hour > 12 ? hour - 12 : hour];
161
+ case "h24":
162
+ return [null, hour + 1];
163
+ default:
164
+ return [null, hour];
165
+ }
166
+ }
167
+
168
+ function fromHourCycle(hour: number, period: number, cycle: HourCycle): number {
169
+ switch (cycle) {
170
+ case "h11":
171
+ return period === 1 ? hour + 12 : hour;
172
+ case "h12":
173
+ return (hour === 12 ? 0 : hour) + (period === 1 ? 12 : 0);
174
+ case "h24":
175
+ return hour - 1;
176
+ default:
177
+ return hour;
178
+ }
179
+ }
180
+
181
+ /** Steps a number within its limits, wrapping at either end. */
182
+ function cycleValue(
183
+ value: number,
184
+ amount: number,
185
+ min: number,
186
+ max: number,
187
+ round = false,
188
+ ): number {
189
+ let next = value;
190
+ if (round) {
191
+ next += Math.sign(amount);
192
+ if (next < min) next = max;
193
+ const step = Math.abs(amount);
194
+ next = amount > 0 ? Math.ceil(next / step) * step : Math.floor(next / step) * step;
195
+ if (next > max) next = min;
196
+ return next;
197
+ }
198
+ next += amount;
199
+ if (next < min) return max - (min - next - 1);
200
+ if (next > max) return min + (next - max - 1);
201
+ return next;
202
+ }
203
+
204
+ /**
205
+ * A date as the user has typed it so far: any field may be missing, and the
206
+ * fields present need not make a date that exists.
207
+ *
208
+ * The hour is kept in the hour cycle with the half of the day beside it, so
209
+ * the user can change AM to PM without the hour moving.
210
+ */
211
+ class Fields {
212
+ readonly hourCycle: HourCycle;
213
+ year: number | null = null;
214
+ month: number | null = null;
215
+ day: number | null = null;
216
+ hour: number | null = null;
217
+ dayPeriod: number | null = null;
218
+ minute: number | null = null;
219
+ second: number | null = null;
220
+ millisecond: number | null = null;
221
+
222
+ constructor(hourCycle: HourCycle, value?: DateValue | null) {
223
+ this.hourCycle = hourCycle;
224
+ if (value === null || value === undefined) return;
225
+ this.year = value.year;
226
+ this.month = value.month;
227
+ this.day = value.day;
228
+ if (value instanceof CalendarDateTime) {
229
+ [this.dayPeriod, this.hour] = toHourCycle(value.hour, hourCycle);
230
+ this.minute = value.minute;
231
+ this.second = value.second;
232
+ this.millisecond = value.millisecond;
233
+ }
234
+ }
235
+
236
+ copy(): Fields {
237
+ const next = new Fields(this.hourCycle);
238
+ next.year = this.year;
239
+ next.month = this.month;
240
+ next.day = this.day;
241
+ next.hour = this.hour;
242
+ next.dayPeriod = this.dayPeriod;
243
+ next.minute = this.minute;
244
+ next.second = this.second;
245
+ next.millisecond = this.millisecond;
246
+ return next;
247
+ }
248
+
249
+ isComplete(types: readonly EditableType[]): boolean {
250
+ return types.every((type) => this[type] !== null);
251
+ }
252
+
253
+ isCleared(types: readonly EditableType[]): boolean {
254
+ return types.every((type) => this[type] === null);
255
+ }
256
+
257
+ /** Whether `value` says what these fields say, which it does not if it was constrained. */
258
+ matches(value: CalendarDateTime, types: readonly EditableType[]): boolean {
259
+ return types.every((type) => {
260
+ if (type === "hour" || type === "dayPeriod") {
261
+ const [period, hour] = toHourCycle(value.hour, this.hourCycle);
262
+ return this.dayPeriod === period && this.hour === hour;
263
+ }
264
+ return this[type] === value[type];
265
+ });
266
+ }
267
+
268
+ set(type: EditableType, value: number, placeholder: CalendarDateTime): Fields {
269
+ const next = this.copy();
270
+ next[type] = type === "dayPeriod" ? (value >= 1 ? 1 : 0) : value;
271
+ if (type === "hour" && next.dayPeriod === null) {
272
+ next.dayPeriod = toHourCycle(placeholder.hour, this.hourCycle)[0];
273
+ }
274
+ return next;
275
+ }
276
+
277
+ clear(type: EditableType): Fields {
278
+ const next = this.copy();
279
+ next[type] = null;
280
+ return next;
281
+ }
282
+
283
+ /** One step of one field; an empty one takes the placeholder's value instead. */
284
+ cycle(type: EditableType, amount: number, placeholder: CalendarDateTime): Fields {
285
+ const next = this.copy();
286
+ if (next[type] === null && type !== "dayPeriod") {
287
+ if (type === "hour") {
288
+ [next.dayPeriod, next.hour] = toHourCycle(placeholder.hour, this.hourCycle);
289
+ } else {
290
+ next[type] = placeholder[type];
291
+ }
292
+ return next;
293
+ }
294
+
295
+ const limits = this.limits(type);
296
+ switch (type) {
297
+ case "year":
298
+ next.year = cycleValue(next.year ?? placeholder.year, amount, 1, 9999, true);
299
+ break;
300
+ case "minute":
301
+ case "second":
302
+ next[type] = cycleValue(next[type] ?? 0, amount, limits.min, limits.max, true);
303
+ break;
304
+ case "hour":
305
+ next.hour = cycleValue(next.hour ?? 0, amount, limits.min, limits.max);
306
+ if (next.dayPeriod === null) {
307
+ next.dayPeriod = toHourCycle(placeholder.hour, this.hourCycle)[0];
308
+ }
309
+ break;
310
+ default:
311
+ next[type] = cycleValue(next[type] ?? limits.min, amount, limits.min, limits.max);
312
+ }
313
+ return next;
314
+ }
315
+
316
+ /** A whole value: these fields over `base`, with a day its month lacks made into one it has. */
317
+ toValue(base: CalendarDateTime): CalendarDateTime {
318
+ let hour: number | null = this.hour;
319
+ if (hour !== null) hour = fromHourCycle(hour, this.dayPeriod ?? 0, this.hourCycle);
320
+ else if (this.dayPeriod !== null && (this.hourCycle === "h11" || this.hourCycle === "h12")) {
321
+ hour = this.dayPeriod === 1 ? 12 : 0;
322
+ }
323
+ return base.set({
324
+ year: this.year ?? base.year,
325
+ month: this.month ?? base.month,
326
+ day: this.day ?? base.day,
327
+ hour: hour ?? base.hour,
328
+ minute: this.minute ?? base.minute,
329
+ second: this.second ?? base.second,
330
+ millisecond: this.millisecond ?? base.millisecond,
331
+ });
332
+ }
333
+
334
+ limits(type: EditableType): { min: number; max: number } {
335
+ switch (type) {
336
+ case "year":
337
+ return { min: 1, max: 9999 };
338
+ case "month":
339
+ return { min: 1, max: 12 };
340
+ case "day":
341
+ return { min: 1, max: 31 };
342
+ case "dayPeriod":
343
+ return { min: 0, max: 1 };
344
+ case "hour":
345
+ if (this.hourCycle === "h12") return { min: 1, max: 12 };
346
+ if (this.hourCycle === "h11") return { min: 0, max: 11 };
347
+ if (this.hourCycle === "h24") return { min: 1, max: 24 };
348
+ return { min: 0, max: 23 };
349
+ default:
350
+ return { min: 0, max: 59 };
351
+ }
352
+ }
353
+ }
354
+
355
+ // ---------------------------------------------------------------------------
356
+ // State
357
+ // ---------------------------------------------------------------------------
358
+
359
+ export interface DateFieldStateOptions {
360
+ value?: MaybeAccessor<DateValue | null | undefined>;
361
+ defaultValue?: MaybeAccessor<DateValue | null | undefined>;
362
+ /** What an empty field's segments count from. @default today */
363
+ placeholderValue?: MaybeAccessor<DateValue | undefined>;
364
+ minValue?: MaybeAccessor<DateValue | null | undefined>;
365
+ maxValue?: MaybeAccessor<DateValue | null | undefined>;
366
+ /** Days that exist but cannot be chosen: a value on one is invalid. */
367
+ isDateUnavailable?: (date: CalendarDate) => boolean;
368
+ /** @default "day" */
369
+ granularity?: MaybeAccessor<Granularity | undefined>;
370
+ /** The largest part shown. `"hour"` makes it a field for a time alone. @default "year" */
371
+ maxGranularity?: MaybeAccessor<"year" | "hour" | undefined>;
372
+ /** 12- or 24-hour. Defaults to what the locale does. */
373
+ hourCycle?: MaybeAccessor<12 | 24 | undefined>;
374
+ isDisabled?: MaybeAccessor<boolean | undefined>;
375
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
376
+ isRequired?: MaybeAccessor<boolean | undefined>;
377
+ onChange?: (value: DateValue | null) => void;
378
+ }
379
+
380
+ export interface DateFieldState {
381
+ value: Accessor<DateValue | null>;
382
+ /** What a form reset goes back to. */
383
+ defaultValue: Accessor<DateValue | null>;
384
+ setValue(value: DateValue | null): void;
385
+ /** The display value: the real one, or the placeholder standing in. */
386
+ displayValue: Accessor<CalendarDateTime>;
387
+ segments: Accessor<DateSegment[]>;
388
+ granularity: Accessor<Granularity>;
389
+ maxGranularity: Accessor<"year" | "hour">;
390
+ isDisabled: Accessor<boolean>;
391
+ isReadOnly: Accessor<boolean>;
392
+ isRequired: Accessor<boolean>;
393
+ /** Every editable segment has been filled, so the field HAS a value. */
394
+ isComplete: Accessor<boolean>;
395
+ increment(type: SegmentType): void;
396
+ decrement(type: SegmentType): void;
397
+ incrementPage(type: SegmentType): void;
398
+ decrementPage(type: SegmentType): void;
399
+ setSegment(type: SegmentType, value: number): void;
400
+ clearSegment(type: SegmentType): void;
401
+ clear(): void;
402
+ /**
403
+ * The field was left: a whole date that does not exist, the 31st of
404
+ * February, becomes the nearest one that does and is reported.
405
+ */
406
+ confirmPlaceholder(): void;
407
+ /** What a formatted value reads as, for a screen reader. */
408
+ formatValue(options?: Intl.DateTimeFormatOptions): string;
409
+ /** What `minValue`, `maxValue` and `isDateUnavailable` make of the value, or `undefined`. */
410
+ rangeValidation: Accessor<ValidationResult | undefined>;
411
+ }
412
+
413
+ const PAGE: Partial<Record<SegmentType, number>> = {
414
+ year: 5,
415
+ month: 3,
416
+ day: 7,
417
+ hour: 2,
418
+ minute: 15,
419
+ second: 15,
420
+ };
421
+
422
+ function asDateTime(value: DateValue): CalendarDateTime {
423
+ return value instanceof CalendarDateTime ? value : CalendarDateTime.from(value);
424
+ }
425
+
426
+ export function dateFieldState(options: DateFieldStateOptions): DateFieldState {
427
+ const locale = useLocale();
428
+ const messages = stringFormatter(FIELD_STRINGS);
429
+ const plainNumber = numberFormatter({ useGrouping: false });
430
+ const twoDigits = numberFormatter({ useGrouping: false, minimumIntegerDigits: 2 });
431
+
432
+ const granularity = (): Granularity => access(options.granularity) ?? "day";
433
+ const maxGranularity = (): "year" | "hour" => access(options.maxGranularity) ?? "year";
434
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
435
+ const isReadOnly = (): boolean => access(options.isReadOnly) === true;
436
+
437
+ const [value, setValueRaw] = controllable<DateValue | null>(
438
+ () => access(options.value),
439
+ () => access(options.defaultValue) ?? null,
440
+ options.onChange,
441
+ );
442
+ const initialValue = untrack(value);
443
+
444
+ const hourCycle = createMemo((): HourCycle => {
445
+ const given = access(options.hourCycle);
446
+ const resolved = new Intl.DateTimeFormat(locale().locale, {
447
+ hour: "numeric",
448
+ hour12: given === undefined ? undefined : given === 12,
449
+ }).resolvedOptions().hourCycle;
450
+ return resolved ?? (given === 12 ? "h12" : "h23");
451
+ });
452
+
453
+ /** The segments the field shows, which are the ones that must be filled. */
454
+ const shown = createMemo((): EditableType[] => {
455
+ const twelve = hourCycle() === "h11" || hourCycle() === "h12";
456
+ const all: EditableType[] = twelve
457
+ ? ["year", "month", "day", "hour", "dayPeriod", "minute", "second"]
458
+ : ["year", "month", "day", "hour", "minute", "second"];
459
+ const level = granularity();
460
+ const last = all.indexOf(
461
+ level === "day" ? "day" : level === "hour" && twelve ? "dayPeriod" : level,
462
+ );
463
+ return all.slice(maxGranularity() === "hour" ? all.indexOf("hour") : 0, last + 1);
464
+ });
465
+
466
+ const placeholder = createMemo((): CalendarDateTime => {
467
+ const given = access(options.placeholderValue);
468
+ if (given !== undefined) return asDateTime(given);
469
+ return CalendarDateTime.from(today(), new Time());
470
+ });
471
+
472
+ /** What edits are made over: the value, or the placeholder while there is none. */
473
+ const basis = (): CalendarDateTime => {
474
+ const current = value();
475
+ return current === null ? placeholder() : asDateTime(current);
476
+ };
477
+
478
+ /**
479
+ * What the user has typed, which is what the segments show.
480
+ *
481
+ * A plain variable as well as a signal: two keystrokes can arrive before the
482
+ * signal is published, and the second has to build on the first.
483
+ */
484
+ let live = new Fields(untrack(hourCycle), initialValue);
485
+ const [display, setDisplay] = createSignal<Fields>(live);
486
+ /** The value this field last reported, so it is not mistaken for one from outside. */
487
+ let emitted: DateValue | null | undefined;
488
+
489
+ const show = (next: Fields): void => {
490
+ live = next;
491
+ setDisplay(next);
492
+ };
493
+
494
+ const write = (next: DateValue | null): void => {
495
+ emitted = next;
496
+ setValueRaw(next);
497
+ };
498
+
499
+ const output = (next: CalendarDateTime): DateValue =>
500
+ granularity() === "day" && maxGranularity() === "year" ? next.date : next;
501
+
502
+ /**
503
+ * The fields shown, and the value reported when they make one.
504
+ *
505
+ * A half-filled field has no value, so taking a segment away reports null.
506
+ * A whole one that names a day its month lacks reports nothing yet: the
507
+ * user may be about to change the month.
508
+ */
509
+ const apply = (next: Fields): void => {
510
+ if (isDisabled() || isReadOnly()) return;
511
+ show(next);
512
+ const types = shown();
513
+ if (!next.isComplete(types)) {
514
+ if (value() !== null) write(null);
515
+ return;
516
+ }
517
+ const whole = next.toValue(basis());
518
+ if (!next.matches(whole, types)) return;
519
+ const result = output(whole);
520
+ const current = value();
521
+ if (
522
+ current === null ||
523
+ current.compare(result) !== 0 ||
524
+ current.constructor !== result.constructor
525
+ ) {
526
+ write(result);
527
+ }
528
+ };
529
+
530
+ if (!isServer) {
531
+ // A value arriving from OUTSIDE fills the field, and one taken away
532
+ // empties it back to the placeholder.
533
+ createEffect(
534
+ () => [value(), hourCycle()] as const,
535
+ ([current, cycle]) => {
536
+ if (current === emitted && cycle === live.hourCycle) return;
537
+ emitted = undefined;
538
+ show(new Fields(cycle, current));
539
+ },
540
+ );
541
+ }
542
+
543
+ const isComplete = (): boolean => display().isComplete(shown());
544
+
545
+ const displayValue = createMemo(() => display().toValue(basis()));
546
+
547
+ const format = createMemo(() => {
548
+ const parts: Intl.DateTimeFormatOptions = {};
549
+ if (maxGranularity() === "year") {
550
+ parts.year = "numeric";
551
+ parts.month = "2-digit";
552
+ parts.day = "2-digit";
553
+ }
554
+ const level = granularity();
555
+ if (level !== "day" || maxGranularity() === "hour") {
556
+ parts.hour = "2-digit";
557
+ parts.hourCycle = hourCycle();
558
+ if (level !== "hour") parts.minute = "2-digit";
559
+ if (level === "second") parts.second = "2-digit";
560
+ }
561
+ return dateFormatter(parts, locale)();
562
+ });
563
+
564
+ const segments = createMemo((): DateSegment[] => {
565
+ const fields = display();
566
+ const level = granularity();
567
+ const tag = locale().locale;
568
+ const parts = format().formatToParts(displayValue().toDate());
569
+ const list: DateSegment[] = [];
570
+
571
+ for (const part of parts) {
572
+ const named: string = part.type;
573
+ const type = named === "relatedYear" ? "year" : named;
574
+ if (!(EDITABLE as readonly string[]).includes(type)) {
575
+ list.push({ type: "literal", text: part.value, isPlaceholder: false, isEditable: false });
576
+ continue;
577
+ }
578
+
579
+ const editable = type as EditableType;
580
+ const number = fields[editable];
581
+ const limits = fields.limits(editable);
582
+ let text = part.value;
583
+ if (editable !== "dayPeriod" && number !== null) {
584
+ const wide = editable !== "year" && part.value.length >= 2;
585
+ text = (wide ? twoDigits() : plainNumber()).format(number);
586
+ }
587
+ const empty =
588
+ editable === "year" || editable === "month" || editable === "day"
589
+ ? stringFor(PLACEHOLDERS, editable, tag)
590
+ : editable === "dayPeriod"
591
+ ? part.value
592
+ : "––";
593
+
594
+ const segment: DateSegment = {
595
+ type: editable,
596
+ text: number === null ? empty : text,
597
+ value: number ?? undefined,
598
+ minValue: limits.min,
599
+ maxValue: limits.max,
600
+ isPlaceholder: number === null,
601
+ placeholder: empty,
602
+ isEditable: true,
603
+ };
604
+
605
+ // A time reads left to right even in a right-to-left locale, so the
606
+ // time segments are isolated as one left-to-right run.
607
+ if (editable === "hour") {
608
+ list.push({ type: "literal", text: "⁦", isPlaceholder: false, isEditable: false });
609
+ list.push(segment);
610
+ if (level === "hour") {
611
+ list.push({ type: "literal", text: "⁩", isPlaceholder: false, isEditable: false });
612
+ }
613
+ } else if ((editable === "minute" || editable === "second") && editable === level) {
614
+ list.push(segment);
615
+ list.push({ type: "literal", text: "⁩", isPlaceholder: false, isEditable: false });
616
+ } else {
617
+ list.push(segment);
618
+ }
619
+ }
620
+ return list;
621
+ });
622
+
623
+ const step = (type: SegmentType, amount: number): void => {
624
+ if (type === "literal") return;
625
+ apply(live.cycle(type, amount, basis()));
626
+ };
627
+
628
+ const rangeValidation = (): ValidationResult | undefined => {
629
+ const current = value();
630
+ if (current === null) return undefined;
631
+
632
+ const min = access(options.minValue);
633
+ const max = access(options.maxValue);
634
+ const under = min !== null && min !== undefined && current.compare(min) < 0;
635
+ const over = max !== null && max !== undefined && current.compare(max) > 0;
636
+ const unavailable = options.isDateUnavailable?.(toCalendarDate(current)) === true;
637
+ if (!under && !over && !unavailable) return undefined;
638
+
639
+ const formatted = dateFormatter(
640
+ maxGranularity() === "hour"
641
+ ? { hour: "numeric", minute: "2-digit" }
642
+ : granularity() === "day"
643
+ ? { dateStyle: "medium" }
644
+ : { dateStyle: "medium", timeStyle: "short" },
645
+ locale,
646
+ )();
647
+ const errors: string[] = [];
648
+ if (under) {
649
+ errors.push(
650
+ messages().format("rangeUnderflow", { minValue: formatted.format(min.toDate()) }),
651
+ );
652
+ }
653
+ if (over) {
654
+ errors.push(messages().format("rangeOverflow", { maxValue: formatted.format(max.toDate()) }));
655
+ }
656
+ if (unavailable) errors.push(messages().format("unavailableDate"));
657
+
658
+ return {
659
+ isInvalid: true,
660
+ validationErrors: errors,
661
+ validationDetails: {
662
+ badInput: unavailable,
663
+ customError: false,
664
+ patternMismatch: false,
665
+ rangeOverflow: over,
666
+ rangeUnderflow: under,
667
+ stepMismatch: false,
668
+ tooLong: false,
669
+ tooShort: false,
670
+ typeMismatch: false,
671
+ valueMissing: false,
672
+ valid: false,
673
+ },
674
+ };
675
+ };
676
+
677
+ return {
678
+ value,
679
+ defaultValue: () => access(options.defaultValue) ?? initialValue,
680
+ rangeValidation,
681
+ displayValue,
682
+ segments,
683
+ granularity,
684
+ maxGranularity,
685
+ isDisabled,
686
+ isReadOnly,
687
+ isRequired: () => access(options.isRequired) === true,
688
+ isComplete,
689
+ setValue: (next) => {
690
+ show(new Fields(hourCycle(), next));
691
+ write(next);
692
+ },
693
+ increment: (type) => step(type, 1),
694
+ decrement: (type) => step(type, -1),
695
+ incrementPage: (type) => step(type, PAGE[type] ?? 1),
696
+ decrementPage: (type) => step(type, -(PAGE[type] ?? 1)),
697
+ setSegment: (type, next) => {
698
+ if (type === "literal") return;
699
+ apply(live.set(type, next, basis()));
700
+ },
701
+ clearSegment: (type) => {
702
+ if (type === "literal") return;
703
+ apply(live.clear(type));
704
+ },
705
+ clear: () => {
706
+ if (isDisabled() || isReadOnly()) return;
707
+ show(new Fields(hourCycle()));
708
+ write(null);
709
+ },
710
+ confirmPlaceholder: () => {
711
+ if (isDisabled() || isReadOnly()) return;
712
+ if (!live.isComplete(shown())) return;
713
+ const result = output(live.toValue(basis()));
714
+ show(new Fields(hourCycle(), result));
715
+ const current = value();
716
+ if (current === null || current.compare(result) !== 0) write(result);
717
+ },
718
+ formatValue: (formatOptions) => {
719
+ const current = value();
720
+ if (current === null) return "";
721
+ if (maxGranularity() === "hour") {
722
+ return dateFormatter(formatOptions ?? { timeStyle: "short" }, locale)().format(
723
+ asDateTime(current).toDate(),
724
+ );
725
+ }
726
+ return dateFormatter(formatOptions ?? { dateStyle: "long" }, locale)().format(
727
+ toCalendarDate(current).toDate(),
728
+ );
729
+ },
730
+ };
731
+ }
732
+
733
+ // ---------------------------------------------------------------------------
734
+ // Hooks
735
+ // ---------------------------------------------------------------------------
736
+
737
+ export interface DateFieldOptions extends FieldOptions {
738
+ ref: ElementRef;
739
+ /** The hidden input that carries the value into a form, and that a form validates. */
740
+ inputRef?: ElementRef<HTMLInputElement>;
741
+ isDisabled?: MaybeAccessor<boolean | undefined>;
742
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
743
+ isRequired?: MaybeAccessor<boolean | undefined>;
744
+ name?: MaybeAccessor<string | undefined>;
745
+ /** What the page thinks of the date, checked as it changes. */
746
+ validate?: ValidateFunction<DateValue | null>;
747
+ /** @default "aria" */
748
+ validationBehavior?: MaybeAccessor<ValidationBehavior | undefined>;
749
+ }
750
+
751
+ export interface DateFieldResult {
752
+ labelProps: DOMProps;
753
+ /** For the element holding the segments. */
754
+ fieldProps: DOMProps;
755
+ descriptionProps: DOMProps;
756
+ errorMessageProps: DOMProps;
757
+ /** For a hidden input carrying the value into a form. */
758
+ inputProps: DOMProps;
759
+ /** What is wrong with the date, and whether the user is being told. */
760
+ validation: FormValidationState;
761
+ errors: Accessor<string[]>;
762
+ isInvalid: Accessor<boolean>;
763
+ }
764
+
765
+ const SEGMENT_SELECTOR = '[role="spinbutton"], [role="textbox"]';
766
+
767
+ export function dateField(options: DateFieldOptions, state: DateFieldState): DateFieldResult {
768
+ const {
769
+ state: validation,
770
+ behavior,
771
+ isInvalid,
772
+ errors,
773
+ errorMessage,
774
+ } = fieldValidation<DateValue | null>({
775
+ value: state.value,
776
+ builtinValidation: state.rangeValidation,
777
+ validate: options.validate,
778
+ validationBehavior: options.validationBehavior,
779
+ isInvalid: options.isInvalid,
780
+ errorMessage: options.errorMessage,
781
+ name: options.name,
782
+ });
783
+
784
+ const {
785
+ labelProps,
786
+ fieldProps: labelledProps,
787
+ descriptionProps,
788
+ errorMessageProps,
789
+ } = field({ ...options, isInvalid, errorMessage, labelElementType: "span" });
790
+
791
+ const focusFirst = (): void => {
792
+ const group = access(options.ref) as HTMLElement | null;
793
+ group?.querySelector<HTMLElement>(SEGMENT_SELECTOR)?.focus();
794
+ };
795
+
796
+ if (options.inputRef !== undefined && !isServer) {
797
+ formReset(options.inputRef, state.defaultValue, (next) => state.setValue(next));
798
+ formValidation(
799
+ { validationBehavior: behavior, focus: focusFirst },
800
+ validation,
801
+ options.inputRef,
802
+ );
803
+ }
804
+
805
+ const isNative = (): boolean => behavior() === "native";
806
+
807
+ return {
808
+ labelProps,
809
+ descriptionProps,
810
+ errorMessageProps,
811
+ validation,
812
+ errors,
813
+ isInvalid,
814
+ fieldProps: mergeProps(filterDOMProps(options, { labelable: true }), labelledProps, {
815
+ // A group, because the segments are separate controls that together are
816
+ // one field: `role="textbox"` would promise editing the whole string.
817
+ role: "group",
818
+ "aria-disabled": () => state.isDisabled() || undefined,
819
+ "aria-invalid": () => isInvalid() || undefined,
820
+ "aria-required": () => access(options.isRequired) === true || undefined,
821
+ "aria-describedby": () => access(options["aria-describedby"]),
822
+ // A date is committed segment by segment, so leaving the field is the
823
+ // first moment the whole value is worth judging. Moving between its own
824
+ // segments is not leaving it.
825
+ onFocusOut: (event: FocusEvent) => {
826
+ const group = event.currentTarget as Element | null;
827
+ const next = event.relatedTarget as Element | null;
828
+ if (group !== null && next !== null && contains(group, next)) return;
829
+ state.confirmPlaceholder();
830
+ validation.commitValidation();
831
+ },
832
+ }),
833
+ inputProps: {
834
+ // A hidden input is never validated by the browser, so under native
835
+ // validation it is a text input the user cannot see, which is.
836
+ type: () => (isNative() ? "text" : "hidden"),
837
+ hidden: () => isNative() || undefined,
838
+ required: () => (isNative() && access(options.isRequired) === true) || undefined,
839
+ disabled: () => state.isDisabled() || undefined,
840
+ name: () => access(options.name),
841
+ value: () => state.value()?.toString() ?? "",
842
+ },
843
+ };
844
+ }
845
+
846
+ export interface DateSegmentOptions {
847
+ segment: Accessor<DateSegment>;
848
+ ref: ElementRef;
849
+ }
850
+
851
+ export interface DateSegmentResult {
852
+ segmentProps: DOMProps;
853
+ }
854
+
855
+ export function dateSegment(options: DateSegmentOptions, state: DateFieldState): DateSegmentResult {
856
+ const segment = (): DateSegment => options.segment();
857
+ const locale = useLocale();
858
+ const messages = stringFormatter(FIELD_STRINGS);
859
+ const parser = numberParser({ maximumFractionDigits: 0 });
860
+ const { startsWith } = filter({ sensitivity: "base" });
861
+ const monthName = dateFormatter({ month: "long" });
862
+ const hourIn12 = (): Accessor<Intl.DateTimeFormat> =>
863
+ dateFormatter({ hour: "numeric", hour12: true }, locale);
864
+ const hourIn24 = (): Accessor<Intl.DateTimeFormat> =>
865
+ dateFormatter({ hour: "numeric", hour12: false }, locale);
866
+ const periods = dateFormatter({ hour: "numeric", hour12: true });
867
+
868
+ /**
869
+ * What has been typed into this segment since focus arrived.
870
+ *
871
+ * Kept here rather than in the state, because it is not part of the value:
872
+ * a segment left half typed shows what was typed and commits nothing more.
873
+ */
874
+ let entered = "";
875
+
876
+ const isEditable = (): boolean =>
877
+ segment().isEditable && !state.isDisabled() && !state.isReadOnly();
878
+
879
+ const element = (): HTMLElement | null => access(options.ref) as HTMLElement | null;
880
+
881
+ /** The next or previous editable segment: on screen in a right-to-left locale, in the DOM otherwise. */
882
+ const moveFocus = (by: 1 | -1): void => {
883
+ const self = element();
884
+ const container = self?.closest('[role="group"]');
885
+ if (self === null || self === undefined || container === null || container === undefined) {
886
+ return;
887
+ }
888
+ const all = [...container.querySelectorAll<HTMLElement>(SEGMENT_SELECTOR)];
889
+ if (locale().direction !== "rtl") {
890
+ all[all.indexOf(self) + by]?.focus();
891
+ return;
892
+ }
893
+ const from = self.getBoundingClientRect().left;
894
+ let closest: HTMLElement | null = null;
895
+ let distance = Infinity;
896
+ for (const candidate of all) {
897
+ const gap = candidate.getBoundingClientRect().left - from;
898
+ if (Math.sign(gap) === by && Math.abs(gap) < distance) {
899
+ closest = candidate;
900
+ distance = Math.abs(gap);
901
+ }
902
+ }
903
+ closest?.focus();
904
+ };
905
+
906
+ const dayPeriodText = (hour: number): string =>
907
+ periods()
908
+ .formatToParts(new Date(2000, 0, 1, hour))
909
+ .find((part) => part.type === "dayPeriod")?.value ?? "";
910
+
911
+ const matchesPeriod = (marker: string, key: string): boolean =>
912
+ marker !== "" && key !== "" && startsWith(marker, key);
913
+
914
+ /** A character typed into the segment, from a key or from a virtual keyboard. */
915
+ const type = (key: string): void => {
916
+ if (!isEditable()) return;
917
+ const current = segment();
918
+
919
+ if (current.type === "dayPeriod") {
920
+ if (matchesPeriod(dayPeriodText(0), key)) state.setSegment("dayPeriod", 0);
921
+ else if (matchesPeriod(dayPeriodText(12), key)) state.setSegment("dayPeriod", 1);
922
+ else return;
923
+ moveFocus(1);
924
+ return;
925
+ }
926
+
927
+ const next = `${entered}${key}`;
928
+ if (!parser().isValidPartialNumber(next)) return;
929
+ const number = parser().parse(next);
930
+ if (Number.isNaN(number)) return;
931
+
932
+ const max = current.maxValue;
933
+ const written = max !== undefined && number > max ? parser().parse(key) : number;
934
+ if (Number.isNaN(written)) return;
935
+ state.setSegment(current.type, written);
936
+
937
+ // On to the next when no further digit could belong here: typing 4 into a
938
+ // month means April, and waiting for a second digit that cannot come
939
+ // would make every date twice the keystrokes.
940
+ if (max !== undefined && (Number(`${number}0`) > max || next.length >= String(max).length)) {
941
+ entered = "";
942
+ moveFocus(1);
943
+ } else {
944
+ entered = next;
945
+ }
946
+ };
947
+
948
+ /** One digit taken off the end; an empty segment hands the key to the one before. */
949
+ const backspace = (): void => {
950
+ const current = segment();
951
+ if (current.isPlaceholder) {
952
+ moveFocus(-1);
953
+ return;
954
+ }
955
+ if (!isEditable()) return;
956
+ if (current.type === "dayPeriod") {
957
+ state.clearSegment(current.type);
958
+ return;
959
+ }
960
+ if (!parser().isValidPartialNumber(current.text)) return;
961
+ let rest = current.text.slice(0, -1);
962
+ const parsed = parser().parse(rest);
963
+ if (rest.length === 0 || parsed === 0 || Number.isNaN(parsed)) {
964
+ rest = "";
965
+ state.clearSegment(current.type);
966
+ } else {
967
+ state.setSegment(current.type, parsed);
968
+ }
969
+ entered = rest;
970
+ };
971
+
972
+ const onKeyDown = (event: KeyboardEvent): void => {
973
+ const current = segment();
974
+ if (!current.isEditable) return;
975
+ // A modified key belongs to something else: Alt+ArrowDown opens a date
976
+ // picker's calendar, and stepping the segment as well would change the
977
+ // date the user is about to choose.
978
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
979
+
980
+ switch (event.key) {
981
+ case "ArrowUp":
982
+ event.preventDefault();
983
+ if (isEditable()) state.increment(current.type);
984
+ entered = "";
985
+ return;
986
+ case "ArrowDown":
987
+ event.preventDefault();
988
+ if (isEditable()) state.decrement(current.type);
989
+ entered = "";
990
+ return;
991
+ case "PageUp":
992
+ event.preventDefault();
993
+ if (isEditable()) state.incrementPage(current.type);
994
+ entered = "";
995
+ return;
996
+ case "PageDown":
997
+ event.preventDefault();
998
+ if (isEditable()) state.decrementPage(current.type);
999
+ entered = "";
1000
+ return;
1001
+ case "Home":
1002
+ event.preventDefault();
1003
+ if (isEditable() && current.minValue !== undefined) {
1004
+ state.setSegment(current.type, current.minValue);
1005
+ }
1006
+ entered = "";
1007
+ return;
1008
+ case "End":
1009
+ event.preventDefault();
1010
+ if (isEditable() && current.maxValue !== undefined) {
1011
+ state.setSegment(current.type, current.maxValue);
1012
+ }
1013
+ entered = "";
1014
+ return;
1015
+ case "Backspace":
1016
+ case "Delete":
1017
+ event.preventDefault();
1018
+ backspace();
1019
+ return;
1020
+ case "ArrowLeft":
1021
+ case "ArrowRight": {
1022
+ // The caret is between SEGMENTS, so moving it is moving focus.
1023
+ event.preventDefault();
1024
+ moveFocus(event.key === "ArrowRight" ? 1 : -1);
1025
+ return;
1026
+ }
1027
+ default:
1028
+ break;
1029
+ }
1030
+
1031
+ if (event.key.length !== 1 || event.shiftKey) return;
1032
+ // Handled here, the character never reaches `beforeinput`; a virtual
1033
+ // keyboard's keydown carries no key, and its character arrives there.
1034
+ event.preventDefault();
1035
+ type(event.key);
1036
+ };
1037
+
1038
+ /** What the content-editable segment's text was before a composition changed it. */
1039
+ let composed = "";
1040
+
1041
+ const onBeforeInput = (event: InputEvent): void => {
1042
+ const self = element();
1043
+ if (self === null) return;
1044
+ // The segment's text is the state's to write, never the browser's.
1045
+ event.preventDefault();
1046
+ switch (event.inputType) {
1047
+ case "deleteContentBackward":
1048
+ case "deleteContentForward":
1049
+ backspace();
1050
+ return;
1051
+ case "insertCompositionText":
1052
+ composed = self.textContent ?? "";
1053
+ // Safari stays in a composition unless the text is written back.
1054
+ writeText(self, composed);
1055
+ return;
1056
+ default:
1057
+ if (event.data !== null) type(event.data);
1058
+ }
1059
+ };
1060
+
1061
+ const onInput = (event: InputEvent): void => {
1062
+ if (event.inputType !== "insertCompositionText") return;
1063
+ const self = element();
1064
+ // A composition cannot be cancelled, so what it wrote is undone here.
1065
+ if (self !== null) writeText(self, composed);
1066
+ // Android sends some letters as compositions, AM and PM among them.
1067
+ const data = event.data;
1068
+ if (
1069
+ data !== null &&
1070
+ (matchesPeriod(dayPeriodText(0), data) || matchesPeriod(dayPeriodText(12), data))
1071
+ ) {
1072
+ type(data);
1073
+ }
1074
+ };
1075
+
1076
+ if (!isServer) {
1077
+ // A selection spread across the segment makes Android's composition
1078
+ // rewrite the DOM under the field, so it is kept collapsed while focused.
1079
+ createEffect(
1080
+ () => element(),
1081
+ (self) => {
1082
+ if (self === null) return undefined;
1083
+ const document = self.ownerDocument;
1084
+ // Collapsing fires another `selectionchange`, which some engines
1085
+ // dispatch at once, so the listener must not answer its own.
1086
+ let collapsing = false;
1087
+ const collapse = (): void => {
1088
+ const selection = document.getSelection();
1089
+ if (
1090
+ collapsing ||
1091
+ selection?.anchorNode === null ||
1092
+ selection?.anchorNode === undefined ||
1093
+ !contains(self, selection.anchorNode) ||
1094
+ document.activeElement !== self
1095
+ ) {
1096
+ return;
1097
+ }
1098
+ collapsing = true;
1099
+ try {
1100
+ selection.collapse(self);
1101
+ } finally {
1102
+ collapsing = false;
1103
+ }
1104
+ };
1105
+ document.addEventListener("selectionchange", collapse);
1106
+ return () => document.removeEventListener("selectionchange", collapse);
1107
+ },
1108
+ );
1109
+ }
1110
+
1111
+ const name = (): string => {
1112
+ const kind = segment().type;
1113
+ if (kind === "literal") return "";
1114
+ try {
1115
+ const names = new Intl.DisplayNames(locale().locale, { type: "dateTimeField" });
1116
+ const found = names.of(kind);
1117
+ if (found !== undefined) return found;
1118
+ } catch {
1119
+ // `dateTimeField` is the second edition of `Intl.DisplayNames`, which
1120
+ // an older engine does not have.
1121
+ }
1122
+ return messages().format(kind);
1123
+ };
1124
+
1125
+ const valueText = (): string | undefined => {
1126
+ const current = segment();
1127
+ if (current.isPlaceholder) return messages().format("empty");
1128
+ const at = state.displayValue().toDate();
1129
+ if (current.type === "month") {
1130
+ const month = monthName().format(at);
1131
+ return month === current.text ? month : `${current.text} – ${month}`;
1132
+ }
1133
+ if (current.type === "hour") {
1134
+ const twelve = state.segments().some((each) => each.type === "dayPeriod");
1135
+ return (twelve ? hourIn12() : hourIn24())().format(at);
1136
+ }
1137
+ return current.text;
1138
+ };
1139
+
1140
+ // VoiceOver on iOS cannot focus a spin button, so there it is a text box.
1141
+ const asTextbox = (): boolean => isIOS();
1142
+
1143
+ const numericDirection = (): Record<string, string> => {
1144
+ const style: Record<string, string> = { "caret-color": "transparent" };
1145
+ if (locale().direction === "rtl") {
1146
+ // A placeholder is laid out by the bidirectional algorithm differently
1147
+ // from a number, so every segment is embedded, and a number runs left
1148
+ // to right.
1149
+ style["unicode-bidi"] = "embed";
1150
+ if (segment().type !== "dayPeriod") style.direction = "ltr";
1151
+ }
1152
+ return style;
1153
+ };
1154
+
1155
+ return {
1156
+ segmentProps: {
1157
+ role: () => (segment().isEditable ? (asTextbox() ? "textbox" : "spinbutton") : undefined),
1158
+ "aria-hidden": () => (segment().isEditable ? undefined : true),
1159
+ "aria-label": () => (segment().isEditable ? name() : undefined),
1160
+ "aria-valuenow": () => (segment().isEditable && !asTextbox() ? segment().value : undefined),
1161
+ "aria-valuemin": () =>
1162
+ segment().isEditable && !asTextbox() ? segment().minValue : undefined,
1163
+ "aria-valuemax": () =>
1164
+ segment().isEditable && !asTextbox() ? segment().maxValue : undefined,
1165
+ // What the number MEANS: an empty segment reads as "empty" rather than
1166
+ // as the placeholder letters, and a month as its name.
1167
+ "aria-valuetext": () => (segment().isEditable && !asTextbox() ? valueText() : undefined),
1168
+ "aria-disabled": () => (state.isDisabled() ? true : undefined),
1169
+ "aria-readonly": () => (state.isReadOnly() ? true : undefined),
1170
+ // Editable text, so a touch device raises its keyboard for it; what is
1171
+ // typed is intercepted before the browser writes it.
1172
+ contentEditable: () => (segment().isEditable ? (isEditable() ? "true" : "false") : undefined),
1173
+ spellcheck: () => (isEditable() ? "false" : undefined),
1174
+ autocorrect: () => (isEditable() ? "off" : undefined),
1175
+ enterKeyHint: () => (isEditable() ? "next" : undefined),
1176
+ inputMode: () => (isEditable() && segment().type !== "dayPeriod" ? "numeric" : undefined),
1177
+ style: () => (segment().isEditable ? numericDirection() : undefined),
1178
+ tabIndex: () => (segment().isEditable && !state.isDisabled() ? 0 : undefined),
1179
+ onKeyDown,
1180
+ onBeforeInput,
1181
+ onInput,
1182
+ onFocus: () => {
1183
+ entered = "";
1184
+ // Collapsed at the start, or Chrome fires no input events.
1185
+ const self = element();
1186
+ if (self !== null) self.ownerDocument.getSelection()?.collapse(self);
1187
+ },
1188
+ onBlur: () => {
1189
+ entered = "";
1190
+ },
1191
+ },
1192
+ };
1193
+ }
1194
+
1195
+ // ---------------------------------------------------------------------------
1196
+ // Components
1197
+ // ---------------------------------------------------------------------------
1198
+
1199
+ interface DateFieldContextValue {
1200
+ state: DateFieldState;
1201
+ }
1202
+
1203
+ const DateFieldContext = createContext<DateFieldContextValue | null>(null);
1204
+
1205
+ export function useDateField(): DateFieldContextValue {
1206
+ const value = getContext(DateFieldContext);
1207
+ if (value === null || value === undefined) {
1208
+ throw new Error("A DateSegment must be rendered inside a DateField.");
1209
+ }
1210
+ return value;
1211
+ }
1212
+
1213
+ function DateFieldProvider(props: { value: DateFieldContextValue; children?: Child }) {
1214
+ return provide(
1215
+ DateFieldContext,
1216
+ () => props.value,
1217
+ () => props.children as unknown,
1218
+ );
1219
+ }
1220
+
1221
+ export interface DateFieldComponentProps extends StyleProps {
1222
+ label?: Child;
1223
+ description?: Child;
1224
+ errorMessage?: Child;
1225
+ value?: DateValue | null;
1226
+ defaultValue?: DateValue | null;
1227
+ placeholderValue?: DateValue;
1228
+ minValue?: DateValue | null;
1229
+ maxValue?: DateValue | null;
1230
+ /** Days that exist but cannot be chosen: a value on one is invalid. */
1231
+ isDateUnavailable?: (date: CalendarDate) => boolean;
1232
+ /** @default "day" */
1233
+ granularity?: Granularity;
1234
+ hourCycle?: 12 | 24;
1235
+ isDisabled?: boolean;
1236
+ isReadOnly?: boolean;
1237
+ isRequired?: boolean;
1238
+ isInvalid?: boolean;
1239
+ /** What the page thinks of the date, checked as it changes. */
1240
+ validate?: ValidateFunction<DateValue | null>;
1241
+ /** @default "aria" */
1242
+ validationBehavior?: ValidationBehavior;
1243
+ name?: string;
1244
+ "aria-label"?: string;
1245
+ "aria-labelledby"?: string;
1246
+ ref?: RefTarget<HTMLDivElement>;
1247
+ onChange?: (value: DateValue | null) => void;
1248
+ }
1249
+
1250
+ /**
1251
+ * ```tsx
1252
+ * <DateField label="Departure" value={date()} onChange={date.set} />
1253
+ * <DateField label="Starts" granularity="minute" />
1254
+ * ```
1255
+ */
1256
+ export function DateField(props: DateFieldComponentProps) {
1257
+ const state = dateFieldState({
1258
+ value: () => props.value,
1259
+ defaultValue: () => props.defaultValue,
1260
+ placeholderValue: () => props.placeholderValue,
1261
+ minValue: () => props.minValue,
1262
+ maxValue: () => props.maxValue,
1263
+ isDateUnavailable: callback<[CalendarDate], boolean>(cells(props).isDateUnavailable),
1264
+ granularity: () => props.granularity,
1265
+ hourCycle: () => props.hourCycle,
1266
+ isDisabled: () => props.isDisabled,
1267
+ isReadOnly: () => props.isReadOnly,
1268
+ isRequired: () => props.isRequired,
1269
+ onChange: (value) => props.onChange?.(value),
1270
+ });
1271
+
1272
+ return (
1273
+ <FieldBody
1274
+ state={state}
1275
+ of={cells(props)}
1276
+ validate={callback<[DateValue | null], string | string[] | true | null | undefined>(
1277
+ cells(props).validate,
1278
+ )}
1279
+ inputValue={() => state.value()?.toString() ?? ""}
1280
+ />
1281
+ );
1282
+ }
1283
+
1284
+ interface FieldBodyProps {
1285
+ state: DateFieldState;
1286
+ /** The field's own props, still as Cells. */
1287
+ of: Incoming<DateFieldComponentProps>;
1288
+ validate?: ValidateFunction<DateValue | null>;
1289
+ /** What the hidden input submits. */
1290
+ inputValue: () => string;
1291
+ }
1292
+
1293
+ /** The label, the segments, the hidden input and the messages: what both fields are. */
1294
+ function FieldBody(incoming: FieldBodyProps) {
1295
+ const state = incoming.state;
1296
+ const props = incoming.of;
1297
+ const domRef = makeRef<HTMLDivElement>();
1298
+ const inputRef = makeRef<HTMLInputElement>();
1299
+
1300
+ const {
1301
+ labelProps,
1302
+ fieldProps,
1303
+ descriptionProps,
1304
+ errorMessageProps,
1305
+ inputProps,
1306
+ errors,
1307
+ isInvalid,
1308
+ } = dateField(
1309
+ {
1310
+ ref: domRef,
1311
+ inputRef,
1312
+ validate: incoming.validate,
1313
+ validationBehavior: () => props.validationBehavior?.(),
1314
+ label: () => props.label?.(),
1315
+ description: () => props.description?.(),
1316
+ errorMessage: () => props.errorMessage?.(),
1317
+ isDisabled: () => props.isDisabled?.(),
1318
+ isReadOnly: () => props.isReadOnly?.(),
1319
+ isRequired: () => props.isRequired?.(),
1320
+ isInvalid: () => props.isInvalid?.(),
1321
+ name: () => props.name?.(),
1322
+ "aria-label": () => props["aria-label"]?.(),
1323
+ "aria-labelledby": () => props["aria-labelledby"]?.(),
1324
+ },
1325
+ state,
1326
+ );
1327
+
1328
+ const elementProps = mergeProps(
1329
+ fieldProps,
1330
+ filterDOMProps(fromProps(props), { global: true }),
1331
+ styleProps(props),
1332
+ {
1333
+ "data-disabled": () => props.isDisabled?.() === true,
1334
+ "data-invalid": isInvalid,
1335
+ "data-testid": () => props["data-testid"]?.(),
1336
+ },
1337
+ );
1338
+
1339
+ return (
1340
+ <DateFieldProvider value={{ state }}>
1341
+ <span {...labelProps}>{() => props.label?.()}</span>
1342
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
1343
+ {/* Keyed by INDEX, not by the segment: a new object every read would
1344
+ rebuild every element on every keystroke, and the one holding
1345
+ focus would be destroyed under the user. */}
1346
+ <For each={() => state.segments().map((_, at) => at)}>
1347
+ {(at: number) => <DateSegmentPart index={at} />}
1348
+ </For>
1349
+ </div>
1350
+ <input {...inputProps} value={incoming.inputValue} ref={inputRef.set} />
1351
+ <span {...descriptionProps}>{() => props.description?.()}</span>
1352
+ <span {...errorMessageProps}>
1353
+ {() => {
1354
+ const given = props.errorMessage?.();
1355
+ if (given !== undefined && given !== null && given !== "") return given;
1356
+ const found = errors();
1357
+ return found.length === 0 ? null : found.join(" ");
1358
+ }}
1359
+ </span>
1360
+ </DateFieldProvider>
1361
+ );
1362
+ }
1363
+
1364
+ interface DateSegmentPartProps {
1365
+ index: number;
1366
+ }
1367
+
1368
+ /** One segment. Its own component so it keeps its element as the value moves. */
1369
+ function DateSegmentPart(props: DateSegmentPartProps) {
1370
+ const domRef = makeRef<HTMLDivElement>();
1371
+ const { state } = useDateField();
1372
+ const index = props.index;
1373
+
1374
+ const segment = (): DateSegment =>
1375
+ state.segments()[index] ?? {
1376
+ type: "literal",
1377
+ text: "",
1378
+ isPlaceholder: false,
1379
+ isEditable: false,
1380
+ };
1381
+
1382
+ const { segmentProps } = dateSegment({ segment, ref: domRef }, state);
1383
+ const { hoverProps, isHovered } = hover({ isDisabled: state.isDisabled });
1384
+ const { focusProps, isFocusVisible } = focusRing();
1385
+
1386
+ const elementProps = mergeProps(segmentProps, hoverProps, focusProps, {
1387
+ "data-type": () => segment().type,
1388
+ "data-placeholder": () => segment().isPlaceholder,
1389
+ "data-focus-visible": isFocusVisible,
1390
+ "data-hovered": isHovered,
1391
+ });
1392
+
1393
+ return (
1394
+ <div {...elementProps} ref={domRef.set}>
1395
+ {() => segment().text}
1396
+ </div>
1397
+ );
1398
+ }
1399
+
1400
+ export interface TimeFieldComponentProps extends Omit<
1401
+ DateFieldComponentProps,
1402
+ | "granularity"
1403
+ | "value"
1404
+ | "defaultValue"
1405
+ | "placeholderValue"
1406
+ | "minValue"
1407
+ | "maxValue"
1408
+ | "isDateUnavailable"
1409
+ | "onChange"
1410
+ | "validate"
1411
+ > {
1412
+ value?: Time | null;
1413
+ defaultValue?: Time | null;
1414
+ /** What an empty field's segments count from. @default midnight */
1415
+ placeholderValue?: Time;
1416
+ minValue?: Time | null;
1417
+ maxValue?: Time | null;
1418
+ /** @default "minute" */
1419
+ granularity?: "hour" | "minute" | "second";
1420
+ /** What the page thinks of the TIME, not of the date standing behind it. */
1421
+ validate?: ValidateFunction<Time | null>;
1422
+ onChange?: (value: Time | null) => void;
1423
+ }
1424
+
1425
+ /**
1426
+ * A time on its own.
1427
+ *
1428
+ * The same segments without the date ones, so a meeting time is a field the
1429
+ * user fills rather than a string they format. The day a time is kept against
1430
+ * is today, and it never reaches the caller.
1431
+ */
1432
+ export function TimeField(props: TimeFieldComponentProps) {
1433
+ const day = today();
1434
+ const onDay = (time: Time | null | undefined): CalendarDateTime | null | undefined =>
1435
+ time === null || time === undefined ? time : CalendarDateTime.from(day, time);
1436
+ const timeOf = (value: DateValue | null): Time | null =>
1437
+ value === null ? null : asDateTime(value).time;
1438
+
1439
+ const state = dateFieldState({
1440
+ value: () => onDay(props.value),
1441
+ defaultValue: () => onDay(props.defaultValue),
1442
+ placeholderValue: () => onDay(props.placeholderValue) ?? undefined,
1443
+ minValue: () => onDay(props.minValue),
1444
+ maxValue: () => onDay(props.maxValue),
1445
+ granularity: () => props.granularity ?? "minute",
1446
+ maxGranularity: "hour",
1447
+ hourCycle: () => props.hourCycle,
1448
+ isDisabled: () => props.isDisabled,
1449
+ isReadOnly: () => props.isReadOnly,
1450
+ isRequired: () => props.isRequired,
1451
+ onChange: (value) => props.onChange?.(timeOf(value)),
1452
+ });
1453
+
1454
+ const check = callback<[Time | null], string | string[] | true | null | undefined>(
1455
+ cells(props).validate,
1456
+ );
1457
+
1458
+ return (
1459
+ <FieldBody
1460
+ state={state}
1461
+ of={cells(props) as unknown as Incoming<DateFieldComponentProps>}
1462
+ validate={check === undefined ? undefined : (value) => check(timeOf(value))}
1463
+ inputValue={() => timeOf(state.value())?.toString() ?? ""}
1464
+ />
1465
+ );
1466
+ }
1467
+
1468
+ export { CalendarDate, CalendarDateTime, Time };
1469
+
1470
+ // ---------------------------------------------------------------------------
1471
+ // Strings
1472
+ // ---------------------------------------------------------------------------
1473
+
1474
+ /** A message with `{name}` slots filled from the variables it is formatted with. */
1475
+ function say(template: string): LocalizedString {
1476
+ return (variables) =>
1477
+ template.replace(/\{(\w+)\}/g, (_, slot: string) => String(variables?.[slot] ?? ""));
1478
+ }
1479
+
1480
+ function stringFor<K extends string>(
1481
+ dictionary: StringDictionary<K>,
1482
+ key: K,
1483
+ locale: string,
1484
+ ): string {
1485
+ const found = dictionary.get(key, locale);
1486
+ return typeof found === "string" ? found : "";
1487
+ }
1488
+
1489
+ type FieldKey =
1490
+ | "empty"
1491
+ | "era"
1492
+ | "year"
1493
+ | "month"
1494
+ | "day"
1495
+ | "hour"
1496
+ | "minute"
1497
+ | "second"
1498
+ | "dayPeriod"
1499
+ | "rangeUnderflow"
1500
+ | "rangeOverflow"
1501
+ | "unavailableDate";
1502
+
1503
+ // The placeholders browsers show in their own date inputs, per language,
1504
+ // which is more languages than the rest of the strings here have.
1505
+ const PLACEHOLDERS = new StringDictionary<"year" | "month" | "day">(
1506
+ {
1507
+ ach: { year: "mwaka", month: "dwe", day: "nino" },
1508
+ af: { year: "jjjj", month: "mm", day: "dd" },
1509
+ am: { year: "ዓዓዓዓ", month: "ሚሜ", day: "ቀቀ" },
1510
+ an: { year: "aaaa", month: "mm", day: "dd" },
1511
+ ar: { year: "سنة", month: "شهر", day: "يوم" },
1512
+ ast: { year: "aaaa", month: "mm", day: "dd" },
1513
+ az: { year: "iiii", month: "aa", day: "gg" },
1514
+ be: { year: "гггг", month: "мм", day: "дд" },
1515
+ bg: { year: "гггг", month: "мм", day: "дд" },
1516
+ bn: { year: "yyyy", month: "মিমি", day: "dd" },
1517
+ br: { year: "bbbb", month: "mm", day: "dd" },
1518
+ bs: { year: "gggg", month: "mm", day: "dd" },
1519
+ ca: { year: "aaaa", month: "mm", day: "dd" },
1520
+ cak: { year: "jjjj", month: "ii", day: "q'q'" },
1521
+ ckb: { year: "ساڵ", month: "مانگ", day: "ڕۆژ" },
1522
+ cs: { year: "rrrr", month: "mm", day: "dd" },
1523
+ cy: { year: "bbbb", month: "mm", day: "dd" },
1524
+ da: { year: "åååå", month: "mm", day: "dd" },
1525
+ de: { year: "jjjj", month: "mm", day: "tt" },
1526
+ dsb: { year: "llll", month: "mm", day: "źź" },
1527
+ el: { year: "εεεε", month: "μμ", day: "ηη" },
1528
+ en: { year: "yyyy", month: "mm", day: "dd" },
1529
+ eo: { year: "jjjj", month: "mm", day: "tt" },
1530
+ es: { year: "aaaa", month: "mm", day: "dd" },
1531
+ et: { year: "aaaa", month: "kk", day: "pp" },
1532
+ eu: { year: "uuuu", month: "hh", day: "ee" },
1533
+ fa: { year: "سال", month: "ماه", day: "روز" },
1534
+ ff: { year: "hhhh", month: "ll", day: "ññ" },
1535
+ fi: { year: "vvvv", month: "kk", day: "pp" },
1536
+ fr: { year: "aaaa", month: "mm", day: "jj" },
1537
+ fy: { year: "jjjj", month: "mm", day: "dd" },
1538
+ ga: { year: "bbbb", month: "mm", day: "ll" },
1539
+ gd: { year: "bbbb", month: "mm", day: "ll" },
1540
+ gl: { year: "aaaa", month: "mm", day: "dd" },
1541
+ he: { year: "שנה", month: "חודש", day: "יום" },
1542
+ hr: { year: "gggg", month: "mm", day: "dd" },
1543
+ hsb: { year: "llll", month: "mm", day: "dd" },
1544
+ hu: { year: "éééé", month: "hh", day: "nn" },
1545
+ ia: { year: "aaaa", month: "mm", day: "dd" },
1546
+ id: { year: "tttt", month: "bb", day: "hh" },
1547
+ is: { year: "áááá", month: "mm", day: "dd" },
1548
+ it: { year: "aaaa", month: "mm", day: "gg" },
1549
+ ja: { year: "年", month: "月", day: "日" },
1550
+ ka: { year: "წწწწ", month: "თთ", day: "რრ" },
1551
+ kk: { year: "жжжж", month: "аа", day: "кк" },
1552
+ kn: { year: "ವವವವ", month: "ಮಿಮೀ", day: "ದಿದಿ" },
1553
+ ko: { year: "연도", month: "월", day: "일" },
1554
+ lb: { year: "jjjj", month: "mm", day: "dd" },
1555
+ lo: { year: "ປປປປ", month: "ດດ", day: "ວວ" },
1556
+ lt: { year: "mmmm", month: "mm", day: "dd" },
1557
+ lv: { year: "gggg", month: "mm", day: "dd" },
1558
+ meh: { year: "aaaa", month: "mm", day: "dd" },
1559
+ ml: { year: "വർഷം", month: "മാസം", day: "തീയതി" },
1560
+ ms: { year: "tttt", month: "mm", day: "hh" },
1561
+ nb: { year: "åååå", month: "mm", day: "dd" },
1562
+ nl: { year: "jjjj", month: "mm", day: "dd" },
1563
+ nn: { year: "åååå", month: "mm", day: "dd" },
1564
+ no: { year: "åååå", month: "mm", day: "dd" },
1565
+ oc: { year: "aaaa", month: "mm", day: "jj" },
1566
+ pl: { year: "rrrr", month: "mm", day: "dd" },
1567
+ pt: { year: "aaaa", month: "mm", day: "dd" },
1568
+ rm: { year: "oooo", month: "mm", day: "dd" },
1569
+ ro: { year: "aaaa", month: "ll", day: "zz" },
1570
+ ru: { year: "гггг", month: "мм", day: "дд" },
1571
+ sc: { year: "aaaa", month: "mm", day: "dd" },
1572
+ scn: { year: "aaaa", month: "mm", day: "jj" },
1573
+ sk: { year: "rrrr", month: "mm", day: "dd" },
1574
+ sl: { year: "llll", month: "mm", day: "dd" },
1575
+ sr: { year: "гггг", month: "мм", day: "дд" },
1576
+ "sr-Latn": { year: "gggg", month: "mm", day: "dd" },
1577
+ sv: { year: "åååå", month: "mm", day: "dd" },
1578
+ szl: { year: "rrrr", month: "mm", day: "dd" },
1579
+ tg: { year: "сссс", month: "мм", day: "рр" },
1580
+ th: { year: "ปปปป", month: "ดด", day: "วว" },
1581
+ tr: { year: "yyyy", month: "aa", day: "gg" },
1582
+ uk: { year: "рррр", month: "мм", day: "дд" },
1583
+ "zh-CN": { year: "年", month: "月", day: "日" },
1584
+ "zh-TW": { year: "年", month: "月", day: "日" },
1585
+ },
1586
+ "en",
1587
+ );
1588
+
1589
+ const FIELD_STRINGS = new StringDictionary<FieldKey>({
1590
+ "en-US": {
1591
+ empty: "Empty",
1592
+ era: "era",
1593
+ year: "year",
1594
+ month: "month",
1595
+ day: "day",
1596
+ hour: "hour",
1597
+ minute: "minute",
1598
+ second: "second",
1599
+ dayPeriod: "AM/PM",
1600
+ rangeUnderflow: "The date is before the earliest one allowed.",
1601
+ rangeOverflow: "The date is after the latest one allowed.",
1602
+ unavailableDate: "The date is not available.",
1603
+ },
1604
+ "ar-AE": {
1605
+ empty: "فارغ",
1606
+ era: "العصر",
1607
+ year: "السنة",
1608
+ month: "الشهر",
1609
+ day: "يوم",
1610
+ hour: "الساعات",
1611
+ minute: "الدقائق",
1612
+ second: "الثواني",
1613
+ dayPeriod: "ص/م",
1614
+ rangeUnderflow: say("يجب أن تكون القيمة {minValue} أو بعد ذلك."),
1615
+ rangeOverflow: say("يجب أن تكون القيمة {maxValue} أو قبل ذلك."),
1616
+ unavailableDate: "البيانات المحددة غير متاحة.",
1617
+ },
1618
+ "bg-BG": {
1619
+ empty: "Изпразни",
1620
+ era: "ера",
1621
+ year: "година",
1622
+ month: "месец",
1623
+ day: "ден",
1624
+ hour: "час",
1625
+ minute: "минута",
1626
+ second: "секунда",
1627
+ dayPeriod: "пр.об./сл.об.",
1628
+ rangeUnderflow: say("Стойността трябва да е {minValue} или по-късно."),
1629
+ rangeOverflow: say("Стойността трябва да е {maxValue} или по-ранна."),
1630
+ unavailableDate: "Избраната дата не е налична.",
1631
+ },
1632
+ "cs-CZ": {
1633
+ empty: "Prázdné",
1634
+ era: "letopočet",
1635
+ year: "rok",
1636
+ month: "měsíc",
1637
+ day: "den",
1638
+ hour: "hodina",
1639
+ minute: "minuta",
1640
+ second: "sekunda",
1641
+ dayPeriod: "část dne",
1642
+ rangeUnderflow: say("Hodnota musí být {minValue} nebo pozdější."),
1643
+ rangeOverflow: say("Hodnota musí být {maxValue} nebo dřívější."),
1644
+ unavailableDate: "Vybrané datum není k dispozici.",
1645
+ },
1646
+ "da-DK": {
1647
+ empty: "Tom",
1648
+ era: "æra",
1649
+ year: "år",
1650
+ month: "måned",
1651
+ day: "dag",
1652
+ hour: "time",
1653
+ minute: "minut",
1654
+ second: "sekund",
1655
+ dayPeriod: "AM/PM",
1656
+ rangeUnderflow: say("Værdien skal være {minValue} eller nyere."),
1657
+ rangeOverflow: say("Værdien skal være {maxValue} eller tidligere."),
1658
+ unavailableDate: "Den valgte dato er ikke tilgængelig.",
1659
+ },
1660
+ "de-DE": {
1661
+ empty: "Leer",
1662
+ era: "Epoche",
1663
+ year: "Jahr",
1664
+ month: "Monat",
1665
+ day: "Tag",
1666
+ hour: "Stunde",
1667
+ minute: "Minute",
1668
+ second: "Sekunde",
1669
+ dayPeriod: "Tageshälfte",
1670
+ rangeUnderflow: say("Der Wert muss {minValue} oder später sein."),
1671
+ rangeOverflow: say("Der Wert muss {maxValue} oder früher sein."),
1672
+ unavailableDate: "Das ausgewählte Datum ist nicht verfügbar.",
1673
+ },
1674
+ "el-GR": {
1675
+ empty: "Άδειο",
1676
+ era: "περίοδος",
1677
+ year: "έτος",
1678
+ month: "μήνας",
1679
+ day: "ημέρα",
1680
+ hour: "ώρα",
1681
+ minute: "λεπτό",
1682
+ second: "δευτερόλεπτο",
1683
+ dayPeriod: "π.μ./μ.μ.",
1684
+ rangeUnderflow: say("Η τιμή πρέπει να είναι {minValue} ή μεταγενέστερη."),
1685
+ rangeOverflow: say("Η τιμή πρέπει να είναι {maxValue} ή παλαιότερη."),
1686
+ unavailableDate: "Η επιλεγμένη ημερομηνία δεν είναι διαθέσιμη.",
1687
+ },
1688
+ "es-ES": {
1689
+ empty: "Vacío",
1690
+ era: "era",
1691
+ year: "año",
1692
+ month: "mes",
1693
+ day: "día",
1694
+ hour: "hora",
1695
+ minute: "minuto",
1696
+ second: "segundo",
1697
+ dayPeriod: "a. m./p. m.",
1698
+ rangeUnderflow: say("El valor debe ser {minValue} o posterior."),
1699
+ rangeOverflow: say("El valor debe ser {maxValue} o anterior."),
1700
+ unavailableDate: "Fecha seleccionada no disponible.",
1701
+ },
1702
+ "et-EE": {
1703
+ empty: "Tühjenda",
1704
+ era: "ajastu",
1705
+ year: "aasta",
1706
+ month: "kuu",
1707
+ day: "päev",
1708
+ hour: "tund",
1709
+ minute: "minut",
1710
+ second: "sekund",
1711
+ dayPeriod: "enne/pärast lõunat",
1712
+ rangeUnderflow: say("Väärtus peab olema {minValue} või hilisem."),
1713
+ rangeOverflow: say("Väärtus peab olema {maxValue} või varasem."),
1714
+ unavailableDate: "Valitud kuupäev pole saadaval.",
1715
+ },
1716
+ "fi-FI": {
1717
+ empty: "Tyhjä",
1718
+ era: "aikakausi",
1719
+ year: "vuosi",
1720
+ month: "kuukausi",
1721
+ day: "päivä",
1722
+ hour: "tunti",
1723
+ minute: "minuutti",
1724
+ second: "sekunti",
1725
+ dayPeriod: "vuorokaudenaika",
1726
+ rangeUnderflow: say("Arvon on oltava {minValue} tai sitä myöhäisempi."),
1727
+ rangeOverflow: say("Arvon on oltava {maxValue} tai sitä aikaisempi."),
1728
+ unavailableDate: "Valittu päivämäärä ei ole käytettävissä.",
1729
+ },
1730
+ "fr-FR": {
1731
+ empty: "Vide",
1732
+ era: "ère",
1733
+ year: "année",
1734
+ month: "mois",
1735
+ day: "jour",
1736
+ hour: "heure",
1737
+ minute: "minute",
1738
+ second: "seconde",
1739
+ dayPeriod: "cadran",
1740
+ rangeUnderflow: say("La valeur doit être {minValue} ou ultérieure."),
1741
+ rangeOverflow: say("La valeur doit être {maxValue} ou antérieure."),
1742
+ unavailableDate: "La date sélectionnée n’est pas disponible.",
1743
+ },
1744
+ "he-IL": {
1745
+ empty: "ריק",
1746
+ era: "תקופה",
1747
+ year: "שנה",
1748
+ month: "חודש",
1749
+ day: "יום",
1750
+ hour: "שעה",
1751
+ minute: "דקה",
1752
+ second: "שנייה",
1753
+ dayPeriod: "לפנה״צ/אחה״צ",
1754
+ rangeUnderflow: say("הערך חייב להיות {minValue} או מאוחר יותר."),
1755
+ rangeOverflow: say("הערך חייב להיות {maxValue} או מוקדם יותר."),
1756
+ unavailableDate: "התאריך הנבחר אינו זמין.",
1757
+ },
1758
+ "hr-HR": {
1759
+ empty: "Prazno",
1760
+ era: "era",
1761
+ year: "godina",
1762
+ month: "mjesec",
1763
+ day: "dan",
1764
+ hour: "sat",
1765
+ minute: "minuta",
1766
+ second: "sekunda",
1767
+ dayPeriod: "AM/PM",
1768
+ rangeUnderflow: say("Vrijednost mora biti {minValue} ili kasnije."),
1769
+ rangeOverflow: say("Vrijednost mora biti {maxValue} ili ranije."),
1770
+ unavailableDate: "Odabrani datum nije dostupan.",
1771
+ },
1772
+ "hu-HU": {
1773
+ empty: "Üres",
1774
+ era: "éra",
1775
+ year: "év",
1776
+ month: "hónap",
1777
+ day: "nap",
1778
+ hour: "óra",
1779
+ minute: "perc",
1780
+ second: "másodperc",
1781
+ dayPeriod: "napszak",
1782
+ rangeUnderflow: say("Az értéknek {minValue} vagy későbbinek kell lennie."),
1783
+ rangeOverflow: say("Az értéknek {maxValue} vagy korábbinak kell lennie."),
1784
+ unavailableDate: "A kiválasztott dátum nem érhető el.",
1785
+ },
1786
+ "it-IT": {
1787
+ empty: "Vuoto",
1788
+ era: "era",
1789
+ year: "anno",
1790
+ month: "mese",
1791
+ day: "giorno",
1792
+ hour: "ora",
1793
+ minute: "minuto",
1794
+ second: "secondo",
1795
+ dayPeriod: "AM/PM",
1796
+ rangeUnderflow: say("Il valore deve essere {minValue} o successivo."),
1797
+ rangeOverflow: say("Il valore deve essere {maxValue} o precedente."),
1798
+ unavailableDate: "Data selezionata non disponibile.",
1799
+ },
1800
+ "ja-JP": {
1801
+ empty: "空",
1802
+ era: "時代",
1803
+ year: "年",
1804
+ month: "月",
1805
+ day: "日",
1806
+ hour: "時",
1807
+ minute: "分",
1808
+ second: "秒",
1809
+ dayPeriod: "午前/午後",
1810
+ rangeUnderflow: say("値は {minValue} 以上にする必要があります。"),
1811
+ rangeOverflow: say("値は {maxValue} 以下にする必要があります。"),
1812
+ unavailableDate: "選択した日付は使用できません。",
1813
+ },
1814
+ "ko-KR": {
1815
+ empty: "비어 있음",
1816
+ era: "연호",
1817
+ year: "년",
1818
+ month: "월",
1819
+ day: "일",
1820
+ hour: "시",
1821
+ minute: "분",
1822
+ second: "초",
1823
+ dayPeriod: "오전/오후",
1824
+ rangeUnderflow: say("값은 {minValue} 이후여야 합니다."),
1825
+ rangeOverflow: say("값은 {maxValue} 이전이어야 합니다."),
1826
+ unavailableDate: "선택한 날짜를 사용할 수 없습니다.",
1827
+ },
1828
+ "lt-LT": {
1829
+ empty: "Tuščias",
1830
+ era: "era",
1831
+ year: "metai",
1832
+ month: "mėnuo",
1833
+ day: "diena",
1834
+ hour: "valanda",
1835
+ minute: "minutė",
1836
+ second: "sekundė",
1837
+ dayPeriod: "iki pietų / po pietų",
1838
+ rangeUnderflow: say("Reikšmė turi būti {minValue} arba naujesnė."),
1839
+ rangeOverflow: say("Reikšmė turi būti {maxValue} arba ankstesnė."),
1840
+ unavailableDate: "Pasirinkta data nepasiekiama.",
1841
+ },
1842
+ "lv-LV": {
1843
+ empty: "Tukšs",
1844
+ era: "ēra",
1845
+ year: "gads",
1846
+ month: "mēnesis",
1847
+ day: "diena",
1848
+ hour: "stundas",
1849
+ minute: "minūtes",
1850
+ second: "sekundes",
1851
+ dayPeriod: "priekšpusdienā/pēcpusdienā",
1852
+ rangeUnderflow: say("Vērtībai ir jābūt {minValue} vai vēlākai."),
1853
+ rangeOverflow: say("Vērtībai ir jābūt {maxValue} vai agrākai."),
1854
+ unavailableDate: "Atlasītais datums nav pieejams.",
1855
+ },
1856
+ "nb-NO": {
1857
+ empty: "Tom",
1858
+ era: "tidsalder",
1859
+ year: "år",
1860
+ month: "måned",
1861
+ day: "dag",
1862
+ hour: "time",
1863
+ minute: "minutt",
1864
+ second: "sekund",
1865
+ dayPeriod: "a.m./p.m.",
1866
+ rangeUnderflow: say("Verdien må være {minValue} eller senere."),
1867
+ rangeOverflow: say("Verdien må være {maxValue} eller tidligere."),
1868
+ unavailableDate: "Valgt dato utilgjengelig.",
1869
+ },
1870
+ "nl-NL": {
1871
+ empty: "Leeg",
1872
+ era: "tijdperk",
1873
+ year: "jaar",
1874
+ month: "maand",
1875
+ day: "dag",
1876
+ hour: "uur",
1877
+ minute: "minuut",
1878
+ second: "seconde",
1879
+ dayPeriod: "a.m./p.m.",
1880
+ rangeUnderflow: say("Waarde moet {minValue} of later zijn."),
1881
+ rangeOverflow: say("Waarde moet {maxValue} of eerder zijn."),
1882
+ unavailableDate: "Geselecteerde datum niet beschikbaar.",
1883
+ },
1884
+ "pl-PL": {
1885
+ empty: "Pusty",
1886
+ era: "era",
1887
+ year: "rok",
1888
+ month: "miesiąc",
1889
+ day: "dzień",
1890
+ hour: "godzina",
1891
+ minute: "minuta",
1892
+ second: "sekunda",
1893
+ dayPeriod: "rano / po południu / wieczorem",
1894
+ rangeUnderflow: say("Wartość musi mieć wartość {minValue} lub późniejszą."),
1895
+ rangeOverflow: say("Wartość musi mieć wartość {maxValue} lub wcześniejszą."),
1896
+ unavailableDate: "Wybrana data jest niedostępna.",
1897
+ },
1898
+ "pt-BR": {
1899
+ empty: "Vazio",
1900
+ era: "era",
1901
+ year: "ano",
1902
+ month: "mês",
1903
+ day: "dia",
1904
+ hour: "hora",
1905
+ minute: "minuto",
1906
+ second: "segundo",
1907
+ dayPeriod: "AM/PM",
1908
+ rangeUnderflow: say("O valor deve ser {minValue} ou posterior."),
1909
+ rangeOverflow: say("O valor deve ser {maxValue} ou anterior."),
1910
+ unavailableDate: "Data selecionada indisponível.",
1911
+ },
1912
+ "pt-PT": {
1913
+ empty: "Vazio",
1914
+ era: "era",
1915
+ year: "ano",
1916
+ month: "mês",
1917
+ day: "dia",
1918
+ hour: "hora",
1919
+ minute: "minuto",
1920
+ second: "segundo",
1921
+ dayPeriod: "am/pm",
1922
+ rangeUnderflow: say("O valor tem de ser {minValue} ou posterior."),
1923
+ rangeOverflow: say("O valor tem de ser {maxValue} ou anterior."),
1924
+ unavailableDate: "Data selecionada indisponível.",
1925
+ },
1926
+ "ro-RO": {
1927
+ empty: "Gol",
1928
+ era: "eră",
1929
+ year: "an",
1930
+ month: "lună",
1931
+ day: "zi",
1932
+ hour: "oră",
1933
+ minute: "minut",
1934
+ second: "secundă",
1935
+ dayPeriod: "a.m/p.m.",
1936
+ rangeUnderflow: say("Valoarea trebuie să fie {minValue} sau ulterioară."),
1937
+ rangeOverflow: say("Valoarea trebuie să fie {maxValue} sau anterioară."),
1938
+ unavailableDate: "Data selectată nu este disponibilă.",
1939
+ },
1940
+ "ru-RU": {
1941
+ empty: "Не заполнено",
1942
+ era: "эра",
1943
+ year: "год",
1944
+ month: "месяц",
1945
+ day: "день",
1946
+ hour: "час",
1947
+ minute: "минута",
1948
+ second: "секунда",
1949
+ dayPeriod: "AM/PM",
1950
+ rangeUnderflow: say("Значение должно быть не раньше {minValue}."),
1951
+ rangeOverflow: say("Значение должно быть не позже {maxValue}."),
1952
+ unavailableDate: "Выбранная дата недоступна.",
1953
+ },
1954
+ "sk-SK": {
1955
+ empty: "Prázdne",
1956
+ era: "letopočet",
1957
+ year: "rok",
1958
+ month: "mesiac",
1959
+ day: "deň",
1960
+ hour: "hodina",
1961
+ minute: "minúta",
1962
+ second: "sekunda",
1963
+ dayPeriod: "AM/PM",
1964
+ rangeUnderflow: say("Hodnota musí byť {minValue} alebo neskoršia."),
1965
+ rangeOverflow: say("Hodnota musí byť {maxValue} alebo skoršia."),
1966
+ unavailableDate: "Vybratý dátum je nedostupný.",
1967
+ },
1968
+ "sl-SI": {
1969
+ empty: "Prazen",
1970
+ era: "doba",
1971
+ year: "leto",
1972
+ month: "mesec",
1973
+ day: "dan",
1974
+ hour: "ura",
1975
+ minute: "minuta",
1976
+ second: "sekunda",
1977
+ dayPeriod: "dop/pop",
1978
+ rangeUnderflow: say("Vrednost mora biti {minValue} ali novejša."),
1979
+ rangeOverflow: say("Vrednost mora biti {maxValue} ali starejša."),
1980
+ unavailableDate: "Izbrani datum ni na voljo.",
1981
+ },
1982
+ "sr-SP": {
1983
+ empty: "Prazno",
1984
+ era: "ера",
1985
+ year: "година",
1986
+ month: "месец",
1987
+ day: "дан",
1988
+ hour: "сат",
1989
+ minute: "минут",
1990
+ second: "секунд",
1991
+ dayPeriod: "пре подне/по подне",
1992
+ rangeUnderflow: say("Vrednost mora da bude {minValue} ili novija."),
1993
+ rangeOverflow: say("Vrednost mora da bude {maxValue} ili starija."),
1994
+ unavailableDate: "Izabrani datum nije dostupan.",
1995
+ },
1996
+ "sv-SE": {
1997
+ empty: "Tomt",
1998
+ era: "era",
1999
+ year: "år",
2000
+ month: "månad",
2001
+ day: "dag",
2002
+ hour: "timme",
2003
+ minute: "minut",
2004
+ second: "sekund",
2005
+ dayPeriod: "fm/em",
2006
+ rangeUnderflow: say("Värdet måste vara {minValue} eller senare."),
2007
+ rangeOverflow: say("Värdet måste vara {maxValue} eller tidigare."),
2008
+ unavailableDate: "Det valda datumet är inte tillgängligt.",
2009
+ },
2010
+ "tr-TR": {
2011
+ empty: "Boş",
2012
+ era: "çağ",
2013
+ year: "yıl",
2014
+ month: "ay",
2015
+ day: "gün",
2016
+ hour: "saat",
2017
+ minute: "dakika",
2018
+ second: "saniye",
2019
+ dayPeriod: "ÖÖ/ÖS",
2020
+ rangeUnderflow: say("Değer, {minValue} veya sonrası olmalıdır."),
2021
+ rangeOverflow: say("Değer, {maxValue} veya öncesi olmalıdır."),
2022
+ unavailableDate: "Seçilen tarih kullanılamıyor.",
2023
+ },
2024
+ "uk-UA": {
2025
+ empty: "Пусто",
2026
+ era: "ера",
2027
+ year: "рік",
2028
+ month: "місяць",
2029
+ day: "день",
2030
+ hour: "година",
2031
+ minute: "хвилина",
2032
+ second: "секунда",
2033
+ dayPeriod: "дп/пп",
2034
+ rangeUnderflow: say("Значення має бути не раніше {minValue}."),
2035
+ rangeOverflow: say("Значення має бути не пізніше {maxValue}."),
2036
+ unavailableDate: "Вибрана дата недоступна.",
2037
+ },
2038
+ "zh-CN": {
2039
+ empty: "空",
2040
+ era: "纪元",
2041
+ year: "年",
2042
+ month: "月",
2043
+ day: "日",
2044
+ hour: "小时",
2045
+ minute: "分钟",
2046
+ second: "秒",
2047
+ dayPeriod: "上午/下午",
2048
+ rangeUnderflow: say("值必须是 {minValue} 或更晚日期。"),
2049
+ rangeOverflow: say("值必须是 {maxValue} 或更早日期。"),
2050
+ unavailableDate: "所选日期不可用。",
2051
+ },
2052
+ "zh-TW": {
2053
+ empty: "空白",
2054
+ era: "纪元",
2055
+ year: "年",
2056
+ month: "月",
2057
+ day: "日",
2058
+ hour: "小时",
2059
+ minute: "分钟",
2060
+ second: "秒",
2061
+ dayPeriod: "上午/下午",
2062
+ rangeUnderflow: say("值必須是 {minValue} 或更晚。"),
2063
+ rangeOverflow: say("值必須是 {maxValue} 或更早。"),
2064
+ unavailableDate: "所選日期無法使用。",
2065
+ },
2066
+ });