@barqjs/aria 0.2.0-next.0 → 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 (78) hide show
  1. package/README.md +24 -13
  2. package/package.json +127 -37
  3. package/src/autocomplete.tsx +581 -0
  4. package/src/breadcrumbs.tsx +21 -20
  5. package/src/button.tsx +151 -25
  6. package/src/calendar.tsx +1019 -92
  7. package/src/checkbox.tsx +214 -52
  8. package/src/collections.ts +88 -5
  9. package/src/color.ts +1580 -23
  10. package/src/colorpicker.tsx +698 -153
  11. package/src/colorswatchpicker.tsx +240 -0
  12. package/src/combobox.tsx +635 -113
  13. package/src/command.tsx +78 -59
  14. package/src/date.ts +31 -9
  15. package/src/datefield.tsx +1451 -336
  16. package/src/datepicker.tsx +465 -114
  17. package/src/dialog.tsx +302 -115
  18. package/src/disclosure.tsx +81 -29
  19. package/src/dnd/clipboard.ts +125 -0
  20. package/src/dnd/collection.ts +1265 -0
  21. package/src/dnd/data.ts +409 -0
  22. package/src/dnd/drag-drop.ts +801 -0
  23. package/src/dnd/index.ts +133 -0
  24. package/src/dnd/manager.ts +639 -0
  25. package/src/dnd/strings.ts +1279 -0
  26. package/src/dnd/targets.ts +726 -0
  27. package/src/dnd/types.ts +212 -0
  28. package/src/dom.ts +3 -6
  29. package/src/drag-and-drop.tsx +669 -0
  30. package/src/dropzone.tsx +208 -0
  31. package/src/file-trigger.tsx +103 -0
  32. package/src/form.tsx +18 -18
  33. package/src/gridlist.tsx +912 -121
  34. package/src/group.tsx +146 -0
  35. package/src/index.ts +402 -0
  36. package/src/interactions/focus-events.ts +13 -5
  37. package/src/interactions/keyboard.ts +195 -2
  38. package/src/interactions/modality.ts +18 -6
  39. package/src/interactions/open-link.ts +46 -13
  40. package/src/interactions/press.ts +35 -18
  41. package/src/label.ts +18 -6
  42. package/src/link.tsx +146 -50
  43. package/src/listbox.tsx +615 -89
  44. package/src/live.ts +4 -0
  45. package/src/menu.tsx +182 -89
  46. package/src/menubar.tsx +21 -17
  47. package/src/navigation-tree.tsx +357 -0
  48. package/src/numberfield.tsx +164 -60
  49. package/src/overlay-arrow.tsx +157 -0
  50. package/src/overlays.ts +364 -62
  51. package/src/platform.ts +2 -1
  52. package/src/preview-trigger.tsx +582 -0
  53. package/src/progress-bar-context.ts +15 -0
  54. package/src/questionnaire.tsx +109 -104
  55. package/src/radio.tsx +101 -27
  56. package/src/select.tsx +225 -145
  57. package/src/selection-indicator.tsx +74 -0
  58. package/src/selection.ts +73 -16
  59. package/src/shared-element-transition.tsx +316 -0
  60. package/src/sheet.tsx +1461 -0
  61. package/src/slider.tsx +139 -44
  62. package/src/switch.tsx +47 -21
  63. package/src/table.tsx +0 -0
  64. package/src/tabs.tsx +198 -89
  65. package/src/tag.tsx +217 -32
  66. package/src/textarea.tsx +186 -0
  67. package/src/textfield.tsx +103 -37
  68. package/src/toast-components.tsx +589 -0
  69. package/src/toggle-button-group.tsx +175 -0
  70. package/src/toggle-input.tsx +38 -0
  71. package/src/toggle.ts +68 -5
  72. package/src/tokenfield.tsx +1673 -0
  73. package/src/toolbar.tsx +15 -10
  74. package/src/tooltip.tsx +46 -29
  75. package/src/tree.tsx +2075 -0
  76. package/src/utils.ts +30 -1
  77. package/src/validation.ts +79 -22
  78. package/src/virtualizer.tsx +186 -23
package/src/datefield.tsx CHANGED
@@ -18,9 +18,15 @@
18
18
  * - **An empty field is a PLACEHOLDER, not a value.** It shows a shape to fill
19
19
  * in, and the field has no value at all until every segment is filled — a
20
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.
21
26
  */
22
27
 
23
28
  import {
29
+ cells,
24
30
  type Accessor,
25
31
  type Child,
26
32
  For,
@@ -31,6 +37,7 @@ import {
31
37
  type Incoming,
32
38
  provide,
33
39
  createSignal,
40
+ untrack,
34
41
  } from "@barqjs/core";
35
42
  import { isServer } from "@barqjs/web";
36
43
  import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
@@ -38,18 +45,30 @@ import {
38
45
  CalendarDate,
39
46
  CalendarDateTime,
40
47
  Time,
41
- getDaysInMonth,
42
48
  today,
43
49
  toCalendarDate,
44
50
  type DateValue,
45
51
  } from "./date.ts";
52
+ import { contains } from "./dom.ts";
46
53
  import { focusRing } from "./focus.ts";
47
- import { dateFormatter, useLocale } from "./i18n.ts";
54
+ import {
55
+ dateFormatter,
56
+ filter,
57
+ numberFormatter,
58
+ numberParser,
59
+ type LocalizedString,
60
+ StringDictionary,
61
+ stringFormatter,
62
+ useLocale,
63
+ } from "./i18n.ts";
48
64
  import { hover } from "./interactions/hover.ts";
49
65
  import type { ElementRef } from "./interactions/press.ts";
50
66
  import { field, type FieldOptions } from "./label.ts";
67
+ import { isIOS } from "./platform.ts";
68
+ import { formReset } from "./toggle.ts";
51
69
  import {
52
70
  fieldValidation,
71
+ formValidation,
53
72
  type ValidationResult,
54
73
  type FormValidationState,
55
74
  type ValidateFunction,
@@ -91,6 +110,8 @@ export interface DateSegment {
91
110
  maxValue?: number;
92
111
  /** Nothing has been typed here yet. */
93
112
  isPlaceholder: boolean;
113
+ /** What it shows while it is empty. */
114
+ placeholder?: string;
94
115
  /** A separator is not a segment the user can stand in. */
95
116
  isEditable: boolean;
96
117
  }
@@ -98,12 +119,237 @@ export interface DateSegment {
98
119
  /** How much of a date the field asks for. */
99
120
  export type Granularity = "day" | "hour" | "minute" | "second";
100
121
 
101
- function segmentsFor(granularity: Granularity): SegmentType[] {
102
- const base: SegmentType[] = ["year", "month", "day"];
103
- if (granularity === "day") return base;
104
- if (granularity === "hour") return [...base, "hour", "dayPeriod"];
105
- if (granularity === "minute") return [...base, "hour", "minute", "dayPeriod"];
106
- return [...base, "hour", "minute", "second", "dayPeriod"];
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
+ }
107
353
  }
108
354
 
109
355
  // ---------------------------------------------------------------------------
@@ -117,8 +363,12 @@ export interface DateFieldStateOptions {
117
363
  placeholderValue?: MaybeAccessor<DateValue | undefined>;
118
364
  minValue?: MaybeAccessor<DateValue | null | undefined>;
119
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;
120
368
  /** @default "day" */
121
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>;
122
372
  /** 12- or 24-hour. Defaults to what the locale does. */
123
373
  hourCycle?: MaybeAccessor<12 | 24 | undefined>;
124
374
  isDisabled?: MaybeAccessor<boolean | undefined>;
@@ -129,11 +379,14 @@ export interface DateFieldStateOptions {
129
379
 
130
380
  export interface DateFieldState {
131
381
  value: Accessor<DateValue | null>;
382
+ /** What a form reset goes back to. */
383
+ defaultValue: Accessor<DateValue | null>;
132
384
  setValue(value: DateValue | null): void;
133
385
  /** The display value: the real one, or the placeholder standing in. */
134
386
  displayValue: Accessor<CalendarDateTime>;
135
387
  segments: Accessor<DateSegment[]>;
136
388
  granularity: Accessor<Granularity>;
389
+ maxGranularity: Accessor<"year" | "hour">;
137
390
  isDisabled: Accessor<boolean>;
138
391
  isReadOnly: Accessor<boolean>;
139
392
  isRequired: Accessor<boolean>;
@@ -146,9 +399,14 @@ export interface DateFieldState {
146
399
  setSegment(type: SegmentType, value: number): void;
147
400
  clearSegment(type: SegmentType): void;
148
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;
149
407
  /** What a formatted value reads as, for a screen reader. */
150
408
  formatValue(options?: Intl.DateTimeFormatOptions): string;
151
- /** What `minValue` and `maxValue` make of the value, or `undefined`. */
409
+ /** What `minValue`, `maxValue` and `isDateUnavailable` make of the value, or `undefined`. */
152
410
  rangeValidation: Accessor<ValidationResult | undefined>;
153
411
  }
154
412
 
@@ -161,10 +419,18 @@ const PAGE: Partial<Record<SegmentType, number>> = {
161
419
  second: 15,
162
420
  };
163
421
 
422
+ function asDateTime(value: DateValue): CalendarDateTime {
423
+ return value instanceof CalendarDateTime ? value : CalendarDateTime.from(value);
424
+ }
425
+
164
426
  export function dateFieldState(options: DateFieldStateOptions): DateFieldState {
165
427
  const locale = useLocale();
428
+ const messages = stringFormatter(FIELD_STRINGS);
429
+ const plainNumber = numberFormatter({ useGrouping: false });
430
+ const twoDigits = numberFormatter({ useGrouping: false, minimumIntegerDigits: 2 });
166
431
 
167
432
  const granularity = (): Granularity => access(options.granularity) ?? "day";
433
+ const maxGranularity = (): "year" | "hour" => access(options.maxGranularity) ?? "year";
168
434
  const isDisabled = (): boolean => access(options.isDisabled) === true;
169
435
  const isReadOnly = (): boolean => access(options.isReadOnly) === true;
170
436
 
@@ -173,200 +439,192 @@ export function dateFieldState(options: DateFieldStateOptions): DateFieldState {
173
439
  () => access(options.defaultValue) ?? null,
174
440
  options.onChange,
175
441
  );
442
+ const initialValue = untrack(value);
176
443
 
177
- /** Which segments the user has actually filled in. */
178
- const [filled, setFilled] = createSignal<Set<SegmentType>>(
179
- new Set(value() === null ? [] : segmentsFor(granularity())),
180
- );
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
+ });
181
452
 
182
- const placeholder = createMemo(() => {
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 => {
183
467
  const given = access(options.placeholderValue);
184
- if (given !== undefined) {
185
- return given instanceof CalendarDateTime ? given : CalendarDateTime.from(given);
186
- }
468
+ if (given !== undefined) return asDateTime(given);
187
469
  return CalendarDateTime.from(today(), new Time());
188
470
  });
189
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
+
190
478
  /**
191
- * What the segments are edited INTO while the field has no value yet.
479
+ * What the user has typed, which is what the segments show.
192
480
  *
193
- * Typing a month into an empty field has to be remembered somewhere: the
194
- * value stays null until every segment is filled, and without this the
195
- * month would be written and immediately thrown away.
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.
196
483
  */
197
- const [draft, setDraft] = createSignal<CalendarDateTime>(placeholder());
198
-
199
- /** What the field SHOWS: the value if it has one, the draft if not. */
200
- const displayValue = createMemo(() => {
201
- const current = value();
202
- if (current !== null) {
203
- return current instanceof CalendarDateTime ? current : CalendarDateTime.from(current);
204
- }
205
- return draft();
206
- });
207
-
208
- const wanted = (): SegmentType[] => segmentsFor(granularity());
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
+ };
209
493
 
210
- const isComplete = (): boolean => {
211
- const marked = filled();
212
- return wanted().every((type) => type === "dayPeriod" || marked.has(type));
494
+ const write = (next: DateValue | null): void => {
495
+ emitted = next;
496
+ setValueRaw(next);
213
497
  };
214
498
 
499
+ const output = (next: CalendarDateTime): DateValue =>
500
+ granularity() === "day" && maxGranularity() === "year" ? next.date : next;
501
+
215
502
  /**
216
- * The value written back, but only once the whole field is filled.
503
+ * The fields shown, and the value reported when they make one.
217
504
  *
218
- * A half-typed date is not a date. Reporting one would put the 1st of
219
- * whatever month happens to be showing into the form.
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.
220
508
  */
221
- const commit = (next: CalendarDateTime, marked: Set<SegmentType>): void => {
222
- setFilled(marked);
223
- setDraft(next);
224
- const complete = wanted().every((type) => type === "dayPeriod" || marked.has(type));
225
- if (!complete) {
226
- if (value() !== null) setValueRaw(null);
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);
227
515
  return;
228
516
  }
229
- setValueRaw(granularity() === "day" ? next.date : next);
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
+ }
230
528
  };
231
529
 
232
- const hourCycle = (): 12 | 24 => {
233
- const given = access(options.hourCycle);
234
- if (given !== undefined) return given;
235
- const parts = new Intl.DateTimeFormat(locale().locale, { hour: "numeric" }).formatToParts(
236
- new Date(2024, 0, 1, 13),
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
+ },
237
540
  );
238
- return parts.some((part) => part.type === "dayPeriod") ? 12 : 24;
239
- };
541
+ }
240
542
 
241
- const limitsFor = (type: SegmentType, at: CalendarDateTime): { min: number; max: number } => {
242
- switch (type) {
243
- case "year":
244
- return { min: 1, max: 9999 };
245
- case "month":
246
- return { min: 1, max: 12 };
247
- case "day":
248
- return { min: 1, max: getDaysInMonth(at.year, at.month) };
249
- case "hour":
250
- return hourCycle() === 12 ? { min: 1, max: 12 } : { min: 0, max: 23 };
251
- case "minute":
252
- case "second":
253
- return { min: 0, max: 59 };
254
- case "dayPeriod":
255
- return { min: 0, max: 12 };
256
- default:
257
- return { min: 0, max: 0 };
258
- }
259
- };
543
+ const isComplete = (): boolean => display().isComplete(shown());
544
+
545
+ const displayValue = createMemo(() => display().toValue(basis()));
260
546
 
261
547
  const format = createMemo(() => {
262
- const parts: Intl.DateTimeFormatOptions = { year: "numeric", month: "2-digit", day: "2-digit" };
548
+ const parts: Intl.DateTimeFormatOptions = {};
549
+ if (maxGranularity() === "year") {
550
+ parts.year = "numeric";
551
+ parts.month = "2-digit";
552
+ parts.day = "2-digit";
553
+ }
263
554
  const level = granularity();
264
- if (level !== "day") {
555
+ if (level !== "day" || maxGranularity() === "hour") {
265
556
  parts.hour = "2-digit";
266
- parts.hour12 = hourCycle() === 12;
557
+ parts.hourCycle = hourCycle();
267
558
  if (level !== "hour") parts.minute = "2-digit";
268
559
  if (level === "second") parts.second = "2-digit";
269
560
  }
270
- return dateFormatter(parts)();
561
+ return dateFormatter(parts, locale)();
271
562
  });
272
563
 
273
564
  const segments = createMemo((): DateSegment[] => {
274
- const at = displayValue();
275
- const marked = filled();
276
- const parts = format().formatToParts(at.toDate());
277
-
278
- return parts
279
- .filter((part) =>
280
- ["year", "month", "day", "hour", "minute", "second", "dayPeriod", "literal"].includes(
281
- part.type,
282
- ),
283
- )
284
- .map((part): DateSegment => {
285
- const type = part.type as SegmentType;
286
- if (type === "literal") {
287
- return { type, text: part.value, isPlaceholder: false, isEditable: false };
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 });
288
612
  }
289
-
290
- const isPlaceholder = type !== "dayPeriod" && !marked.has(type);
291
- const limits = limitsFor(type, at);
292
- const numeric =
293
- type === "dayPeriod" ? (at.hour >= 12 ? 12 : 0) : Number.parseInt(part.value, 10);
294
-
295
- return {
296
- type,
297
- // A placeholder shows the SHAPE: "mm" is a month to fill in, and a
298
- // month that happens to read as today's is a value the user never
299
- // typed.
300
- text: isPlaceholder ? placeholderText(type, part.value.length) : part.value,
301
- value: isPlaceholder ? undefined : numeric,
302
- minValue: limits.min,
303
- maxValue: limits.max,
304
- isPlaceholder,
305
- isEditable: true,
306
- };
307
- });
308
- });
309
-
310
- const withSegment = (type: SegmentType, next: number): CalendarDateTime => {
311
- const at = displayValue();
312
- if (type === "dayPeriod") {
313
- const hour = at.hour % 12;
314
- return at.set({ hour: next >= 12 ? hour + 12 : hour });
315
- }
316
- return at.set({ [type]: next });
317
- };
318
-
319
- const step = (type: SegmentType, amount: number, page: boolean): void => {
320
- if (isDisabled() || isReadOnly() || type === "literal") return;
321
-
322
- const at = displayValue();
323
- const marked = new Set(filled());
324
-
325
- if (type === "dayPeriod") {
326
- // AM and PM are the only two, so either arrow flips it.
327
- const hour = at.hour;
328
- commit(at.set({ hour: hour >= 12 ? hour - 12 : hour + 12 }), marked);
329
- return;
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
+ }
330
619
  }
620
+ return list;
621
+ });
331
622
 
332
- marked.add(type);
333
-
334
- // From a placeholder, the first press takes the value as it stands rather
335
- // than stepping off it: the user asked for "this month", not "next".
336
- if (filled().has(type)) {
337
- const size = page ? (PAGE[type] ?? 1) : 1;
338
- commit(at.cycle(type, amount * size, { round: page }), marked);
339
- return;
340
- }
341
- commit(at, marked);
623
+ const step = (type: SegmentType, amount: number): void => {
624
+ if (type === "literal") return;
625
+ apply(live.cycle(type, amount, basis()));
342
626
  };
343
627
 
344
- if (!isServer) {
345
- // A value arriving from OUTSIDE fills the field, and one taken away
346
- // empties it back to the placeholder.
347
- createEffect(
348
- () => {
349
- const current = value();
350
- return current === null ? null : ([current, wanted()] as const);
351
- },
352
- (next) => {
353
- if (next === null) return;
354
- const [current, types] = next;
355
- setDraft(current instanceof CalendarDateTime ? current : CalendarDateTime.from(current));
356
- setFilled(new Set(types));
357
- },
358
- );
359
- }
360
-
361
- /**
362
- * What the RANGE makes of the value.
363
- *
364
- * A date field has no native control for the browser to check, so `minValue`
365
- * and `maxValue` would otherwise be documentation: the segments would accept
366
- * a date outside them and nothing would say so. This is the equivalent of
367
- * `rangeUnderflow` and `rangeOverflow` for a field the browser cannot see,
368
- * and it reaches the user through `formValidationState`'s builtin slot.
369
- */
370
628
  const rangeValidation = (): ValidationResult | undefined => {
371
629
  const current = value();
372
630
  if (current === null) return undefined;
@@ -375,17 +633,33 @@ export function dateFieldState(options: DateFieldStateOptions): DateFieldState {
375
633
  const max = access(options.maxValue);
376
634
  const under = min !== null && min !== undefined && current.compare(min) < 0;
377
635
  const over = max !== null && max !== undefined && current.compare(max) > 0;
378
- if (!under && !over) return undefined;
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"));
379
657
 
380
658
  return {
381
659
  isInvalid: true,
382
- validationErrors: [
383
- under
384
- ? "The date is before the earliest one allowed."
385
- : "The date is after the latest one allowed.",
386
- ],
660
+ validationErrors: errors,
387
661
  validationDetails: {
388
- badInput: false,
662
+ badInput: unavailable,
389
663
  customError: false,
390
664
  patternMismatch: false,
391
665
  rangeOverflow: over,
@@ -402,71 +676,68 @@ export function dateFieldState(options: DateFieldStateOptions): DateFieldState {
402
676
 
403
677
  return {
404
678
  value,
679
+ defaultValue: () => access(options.defaultValue) ?? initialValue,
405
680
  rangeValidation,
406
681
  displayValue,
407
682
  segments,
408
683
  granularity,
684
+ maxGranularity,
409
685
  isDisabled,
410
686
  isReadOnly,
411
687
  isRequired: () => access(options.isRequired) === true,
412
688
  isComplete,
413
689
  setValue: (next) => {
414
- setValueRaw(next);
415
- setFilled(new Set(next === null ? [] : wanted()));
690
+ show(new Fields(hourCycle(), next));
691
+ write(next);
416
692
  },
417
- increment: (type) => step(type, 1, false),
418
- decrement: (type) => step(type, -1, false),
419
- incrementPage: (type) => step(type, 1, true),
420
- decrementPage: (type) => step(type, -1, true),
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)),
421
697
  setSegment: (type, next) => {
422
- if (isDisabled() || isReadOnly()) return;
423
- const marked = new Set(filled());
424
- marked.add(type);
425
- commit(withSegment(type, next), marked);
698
+ if (type === "literal") return;
699
+ apply(live.set(type, next, basis()));
426
700
  },
427
701
  clearSegment: (type) => {
428
- if (isDisabled() || isReadOnly()) return;
429
- const marked = new Set(filled());
430
- marked.delete(type);
431
- commit(displayValue(), marked);
702
+ if (type === "literal") return;
703
+ apply(live.clear(type));
432
704
  },
433
705
  clear: () => {
434
706
  if (isDisabled() || isReadOnly()) return;
435
- setFilled(new Set<SegmentType>());
436
- setValueRaw(null);
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);
437
717
  },
438
718
  formatValue: (formatOptions) => {
439
719
  const current = value();
440
720
  if (current === null) return "";
441
- return dateFormatter(
442
- formatOptions ?? { dateStyle: granularity() === "day" ? "long" : "long" },
443
- locale,
444
- )().format(toCalendarDate(current).toDate());
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
+ );
445
729
  },
446
730
  };
447
731
  }
448
732
 
449
- /** The shape a segment shows before anything is typed into it. */
450
- function placeholderText(type: SegmentType, width: number): string {
451
- const letters: Record<string, string> = {
452
- year: "y",
453
- month: "m",
454
- day: "d",
455
- hour: "h",
456
- minute: "m",
457
- second: "s",
458
- dayPeriod: "AM",
459
- };
460
- if (type === "dayPeriod") return "AM";
461
- return (letters[type] ?? "-").repeat(Math.max(width, 2));
462
- }
463
-
464
733
  // ---------------------------------------------------------------------------
465
734
  // Hooks
466
735
  // ---------------------------------------------------------------------------
467
736
 
468
737
  export interface DateFieldOptions extends FieldOptions {
469
738
  ref: ElementRef;
739
+ /** The hidden input that carries the value into a form, and that a form validates. */
740
+ inputRef?: ElementRef<HTMLInputElement>;
470
741
  isDisabled?: MaybeAccessor<boolean | undefined>;
471
742
  isReadOnly?: MaybeAccessor<boolean | undefined>;
472
743
  isRequired?: MaybeAccessor<boolean | undefined>;
@@ -491,9 +762,12 @@ export interface DateFieldResult {
491
762
  isInvalid: Accessor<boolean>;
492
763
  }
493
764
 
765
+ const SEGMENT_SELECTOR = '[role="spinbutton"], [role="textbox"]';
766
+
494
767
  export function dateField(options: DateFieldOptions, state: DateFieldState): DateFieldResult {
495
768
  const {
496
769
  state: validation,
770
+ behavior,
497
771
  isInvalid,
498
772
  errors,
499
773
  errorMessage,
@@ -514,6 +788,22 @@ export function dateField(options: DateFieldOptions, state: DateFieldState): Dat
514
788
  errorMessageProps,
515
789
  } = field({ ...options, isInvalid, errorMessage, labelElementType: "span" });
516
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
+
517
807
  return {
518
808
  labelProps,
519
809
  descriptionProps,
@@ -529,12 +819,24 @@ export function dateField(options: DateFieldOptions, state: DateFieldState): Dat
529
819
  "aria-invalid": () => isInvalid() || undefined,
530
820
  "aria-required": () => access(options.isRequired) === true || undefined,
531
821
  "aria-describedby": () => access(options["aria-describedby"]),
532
- // A date is committed segment by segment, so a blur is the first moment
533
- // the whole value is worth judging.
534
- onFocusOut: () => validation.commitValidation(),
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
+ },
535
832
  }),
536
833
  inputProps: {
537
- type: "hidden",
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,
538
840
  name: () => access(options.name),
539
841
  value: () => state.value()?.toString() ?? "",
540
842
  },
@@ -552,6 +854,16 @@ export interface DateSegmentResult {
552
854
 
553
855
  export function dateSegment(options: DateSegmentOptions, state: DateFieldState): DateSegmentResult {
554
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 });
555
867
 
556
868
  /**
557
869
  * What has been typed into this segment since focus arrived.
@@ -564,9 +876,106 @@ export function dateSegment(options: DateSegmentOptions, state: DateFieldState):
564
876
  const isEditable = (): boolean =>
565
877
  segment().isEditable && !state.isDisabled() && !state.isReadOnly();
566
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
+
567
972
  const onKeyDown = (event: KeyboardEvent): void => {
568
973
  const current = segment();
569
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;
570
979
 
571
980
  switch (event.key) {
572
981
  case "ArrowUp":
@@ -606,101 +1015,175 @@ export function dateSegment(options: DateSegmentOptions, state: DateFieldState):
606
1015
  case "Backspace":
607
1016
  case "Delete":
608
1017
  event.preventDefault();
609
- if (isEditable()) state.clearSegment(current.type);
610
- entered = "";
1018
+ backspace();
611
1019
  return;
612
1020
  case "ArrowLeft":
613
- case "ArrowRight":
1021
+ case "ArrowRight": {
614
1022
  // The caret is between SEGMENTS, so moving it is moving focus.
615
1023
  event.preventDefault();
616
1024
  moveFocus(event.key === "ArrowRight" ? 1 : -1);
617
1025
  return;
1026
+ }
618
1027
  default:
619
1028
  break;
620
1029
  }
621
1030
 
622
- if (!isEditable()) return;
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
+ };
623
1037
 
624
- if (current.type === "dayPeriod") {
625
- const letter = event.key.toLowerCase();
626
- if (letter !== "a" && letter !== "p") return;
627
- event.preventDefault();
628
- const hour = state.displayValue().hour % 12;
629
- state.setSegment("hour", letter === "p" ? hour + 12 : hour);
630
- moveFocus(1);
631
- return;
632
- }
1038
+ /** What the content-editable segment's text was before a composition changed it. */
1039
+ let composed = "";
633
1040
 
634
- if (!/^\d$/.test(event.key)) return;
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.
635
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
+ };
636
1060
 
637
- const max = current.maxValue ?? 9999;
638
- const typed = Number.parseInt(`${entered}${event.key}`, 10);
639
-
640
- if (typed > max) {
641
- // Too big with what came before, so this digit starts a fresh number.
642
- entered = event.key;
643
- const alone = Number.parseInt(event.key, 10);
644
- state.setSegment(current.type, Math.min(Math.max(alone, current.minValue ?? 0), max));
645
- return;
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);
646
1073
  }
1074
+ };
647
1075
 
648
- entered += event.key;
649
- state.setSegment(current.type, typed);
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
+ }
650
1110
 
651
- // On to the next when no further digit could belong here: typing 4 into a
652
- // month means April, and waiting for a second digit that cannot come
653
- // would make every date twice the keystrokes.
654
- if (typed * 10 > max || entered.length >= String(max).length) {
655
- entered = "";
656
- moveFocus(1);
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.
657
1121
  }
1122
+ return messages().format(kind);
658
1123
  };
659
1124
 
660
- /** The next or previous editable segment, in the DOM. */
661
- const moveFocus = (by: 1 | -1): void => {
662
- const element = access(options.ref) as HTMLElement | null;
663
- const container = element?.closest('[role="group"]');
664
- if (element === null || container === null || container === undefined) return;
665
- const all = [...container.querySelectorAll<HTMLElement>('[role="spinbutton"]')];
666
- const at = all.indexOf(element);
667
- const next = all[at + by];
668
- if (next !== undefined) next.focus();
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;
669
1138
  };
670
1139
 
671
- const label = (): string => {
672
- const names: Record<string, string> = {
673
- year: "year",
674
- month: "month",
675
- day: "day",
676
- hour: "hour",
677
- minute: "minute",
678
- second: "second",
679
- dayPeriod: "AM/PM",
680
- };
681
- return names[segment().type] ?? segment().type;
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;
682
1153
  };
683
1154
 
684
1155
  return {
685
1156
  segmentProps: {
686
- role: () => (segment().isEditable ? "spinbutton" : undefined),
1157
+ role: () => (segment().isEditable ? (asTextbox() ? "textbox" : "spinbutton") : undefined),
687
1158
  "aria-hidden": () => (segment().isEditable ? undefined : true),
688
- "aria-label": () => (segment().isEditable ? label() : undefined),
689
- "aria-valuenow": () => segment().value,
690
- "aria-valuemin": () => (segment().isEditable ? segment().minValue : undefined),
691
- "aria-valuemax": () => (segment().isEditable ? segment().maxValue : undefined),
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,
692
1165
  // What the number MEANS: an empty segment reads as "empty" rather than
693
- // as the placeholder letters.
694
- "aria-valuetext": () =>
695
- segment().isEditable ? (segment().isPlaceholder ? "Empty" : segment().text) : undefined,
1166
+ // as the placeholder letters, and a month as its name.
1167
+ "aria-valuetext": () => (segment().isEditable && !asTextbox() ? valueText() : undefined),
696
1168
  "aria-disabled": () => (state.isDisabled() ? true : undefined),
697
1169
  "aria-readonly": () => (state.isReadOnly() ? true : undefined),
698
- contentEditable: false,
699
- inputMode: () => (segment().type === "dayPeriod" ? "text" : "numeric"),
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),
700
1178
  tabIndex: () => (segment().isEditable && !state.isDisabled() ? 0 : undefined),
701
1179
  onKeyDown,
1180
+ onBeforeInput,
1181
+ onInput,
702
1182
  onFocus: () => {
703
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);
704
1187
  },
705
1188
  onBlur: () => {
706
1189
  entered = "";
@@ -727,10 +1210,10 @@ export function useDateField(): DateFieldContextValue {
727
1210
  return value;
728
1211
  }
729
1212
 
730
- function DateFieldProvider(props: Incoming<{ value: DateFieldContextValue; children?: Child }>) {
1213
+ function DateFieldProvider(props: { value: DateFieldContextValue; children?: Child }) {
731
1214
  return provide(
732
1215
  DateFieldContext,
733
- () => props.value(),
1216
+ () => props.value,
734
1217
  () => props.children as unknown,
735
1218
  );
736
1219
  }
@@ -744,6 +1227,8 @@ export interface DateFieldComponentProps extends StyleProps {
744
1227
  placeholderValue?: DateValue;
745
1228
  minValue?: DateValue | null;
746
1229
  maxValue?: DateValue | null;
1230
+ /** Days that exist but cannot be chosen: a value on one is invalid. */
1231
+ isDateUnavailable?: (date: CalendarDate) => boolean;
747
1232
  /** @default "day" */
748
1233
  granularity?: Granularity;
749
1234
  hourCycle?: 12 | 24;
@@ -768,23 +1253,50 @@ export interface DateFieldComponentProps extends StyleProps {
768
1253
  * <DateField label="Starts" granularity="minute" />
769
1254
  * ```
770
1255
  */
771
- export function DateField(props: Incoming<DateFieldComponentProps>) {
772
- const domRef = makeRef<HTMLDivElement>();
773
-
1256
+ export function DateField(props: DateFieldComponentProps) {
774
1257
  const state = dateFieldState({
775
- value: () => props.value?.(),
776
- defaultValue: () => props.defaultValue?.(),
777
- placeholderValue: () => props.placeholderValue?.(),
778
- minValue: () => props.minValue?.(),
779
- maxValue: () => props.maxValue?.(),
780
- granularity: () => props.granularity?.(),
781
- hourCycle: () => props.hourCycle?.(),
782
- isDisabled: () => props.isDisabled?.(),
783
- isReadOnly: () => props.isReadOnly?.(),
784
- isRequired: () => props.isRequired?.(),
785
- onChange: (value) => props.onChange?.()?.(value),
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),
786
1270
  });
787
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
+
788
1300
  const {
789
1301
  labelProps,
790
1302
  fieldProps,
@@ -796,9 +1308,8 @@ export function DateField(props: Incoming<DateFieldComponentProps>) {
796
1308
  } = dateField(
797
1309
  {
798
1310
  ref: domRef,
799
- validate: callback<[DateValue | null], string | string[] | true | null | undefined>(
800
- props.validate,
801
- ),
1311
+ inputRef,
1312
+ validate: incoming.validate,
802
1313
  validationBehavior: () => props.validationBehavior?.(),
803
1314
  label: () => props.label?.(),
804
1315
  description: () => props.description?.(),
@@ -827,7 +1338,7 @@ export function DateField(props: Incoming<DateFieldComponentProps>) {
827
1338
 
828
1339
  return (
829
1340
  <DateFieldProvider value={{ state }}>
830
- <span {...labelProps}>{props.label}</span>
1341
+ <span {...labelProps}>{() => props.label?.()}</span>
831
1342
  <div {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
832
1343
  {/* Keyed by INDEX, not by the segment: a new object every read would
833
1344
  rebuild every element on every keystroke, and the one holding
@@ -836,8 +1347,8 @@ export function DateField(props: Incoming<DateFieldComponentProps>) {
836
1347
  {(at: number) => <DateSegmentPart index={at} />}
837
1348
  </For>
838
1349
  </div>
839
- {() => (props.name?.() === undefined ? null : <input {...inputProps} />)}
840
- <span {...descriptionProps}>{props.description}</span>
1350
+ <input {...inputProps} value={incoming.inputValue} ref={inputRef.set} />
1351
+ <span {...descriptionProps}>{() => props.description?.()}</span>
841
1352
  <span {...errorMessageProps}>
842
1353
  {() => {
843
1354
  const given = props.errorMessage?.();
@@ -855,10 +1366,10 @@ interface DateSegmentPartProps {
855
1366
  }
856
1367
 
857
1368
  /** One segment. Its own component so it keeps its element as the value moves. */
858
- function DateSegmentPart(props: Incoming<DateSegmentPartProps>) {
1369
+ function DateSegmentPart(props: DateSegmentPartProps) {
859
1370
  const domRef = makeRef<HTMLDivElement>();
860
1371
  const { state } = useDateField();
861
- const index = props.index();
1372
+ const index = props.index;
862
1373
 
863
1374
  const segment = (): DateSegment =>
864
1375
  state.segments()[index] ?? {
@@ -888,10 +1399,22 @@ function DateSegmentPart(props: Incoming<DateSegmentPartProps>) {
888
1399
 
889
1400
  export interface TimeFieldComponentProps extends Omit<
890
1401
  DateFieldComponentProps,
891
- "granularity" | "value" | "defaultValue" | "onChange" | "validate"
1402
+ | "granularity"
1403
+ | "value"
1404
+ | "defaultValue"
1405
+ | "placeholderValue"
1406
+ | "minValue"
1407
+ | "maxValue"
1408
+ | "isDateUnavailable"
1409
+ | "onChange"
1410
+ | "validate"
892
1411
  > {
893
1412
  value?: Time | null;
894
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;
895
1418
  /** @default "minute" */
896
1419
  granularity?: "hour" | "minute" | "second";
897
1420
  /** What the page thinks of the TIME, not of the date standing behind it. */
@@ -903,49 +1426,641 @@ export interface TimeFieldComponentProps extends Omit<
903
1426
  * A time on its own.
904
1427
  *
905
1428
  * The same segments without the date ones, so a meeting time is a field the
906
- * user fills rather than a string they format.
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.
907
1431
  */
908
- export function TimeField(props: Incoming<TimeFieldComponentProps>) {
1432
+ export function TimeField(props: TimeFieldComponentProps) {
909
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
+ );
910
1457
 
911
1458
  return (
912
- <DateField
913
- label={props.label?.()}
914
- description={props.description?.()}
915
- errorMessage={props.errorMessage?.()}
916
- granularity={props.granularity?.() ?? "minute"}
917
- hourCycle={props.hourCycle?.()}
918
- isDisabled={props.isDisabled?.()}
919
- isReadOnly={props.isReadOnly?.()}
920
- isRequired={props.isRequired?.()}
921
- isInvalid={props.isInvalid?.()}
922
- validationBehavior={props.validationBehavior?.()}
923
- validate={(value: DateValue | null) => {
924
- const check = callback<[Time | null], string | string[] | true | null | undefined>(
925
- props.validate,
926
- );
927
- if (check === undefined) return null;
928
- return check(value === null ? null : (value as CalendarDateTime).time);
929
- }}
930
- aria-label={props["aria-label"]?.()}
931
- aria-labelledby={props["aria-labelledby"]?.()}
932
- class={props.class?.() ?? props.className?.()}
933
- data-testid={props["data-testid"]?.()}
934
- value={(() => {
935
- const time = props.value?.();
936
- if (time === undefined) return undefined;
937
- return time === null ? null : CalendarDateTime.from(day, time);
938
- })()}
939
- defaultValue={(() => {
940
- const time = props.defaultValue?.();
941
- if (time === undefined) return undefined;
942
- return time === null ? null : CalendarDateTime.from(day, time);
943
- })()}
944
- onChange={(value) => {
945
- props.onChange?.()?.(value === null ? null : (value as CalendarDateTime).time);
946
- }}
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() ?? ""}
947
1464
  />
948
1465
  );
949
1466
  }
950
1467
 
951
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
+ });