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

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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -2
  3. package/package.json +347 -4
  4. package/src/breadcrumbs.tsx +296 -0
  5. package/src/button.tsx +342 -0
  6. package/src/calendar.tsx +1389 -0
  7. package/src/checkbox.tsx +570 -0
  8. package/src/collections.ts +976 -0
  9. package/src/color.ts +562 -0
  10. package/src/colorpicker.tsx +1478 -0
  11. package/src/combobox.tsx +2481 -0
  12. package/src/command.tsx +1184 -0
  13. package/src/date.ts +652 -0
  14. package/src/datefield.tsx +951 -0
  15. package/src/datepicker.tsx +556 -0
  16. package/src/dialog.tsx +890 -0
  17. package/src/disclosure.tsx +659 -0
  18. package/src/dom.ts +706 -0
  19. package/src/drawer.ts +674 -0
  20. package/src/focus.ts +1370 -0
  21. package/src/form.tsx +94 -0
  22. package/src/gridlist.tsx +563 -0
  23. package/src/i18n.ts +823 -0
  24. package/src/index.ts +1270 -0
  25. package/src/interactions/description.ts +73 -0
  26. package/src/interactions/flags.ts +35 -0
  27. package/src/interactions/focus-events.ts +218 -0
  28. package/src/interactions/focusable.ts +86 -0
  29. package/src/interactions/hover.ts +213 -0
  30. package/src/interactions/interact-outside.ts +123 -0
  31. package/src/interactions/keyboard.ts +105 -0
  32. package/src/interactions/listeners.ts +78 -0
  33. package/src/interactions/long-press.ts +160 -0
  34. package/src/interactions/modality.ts +416 -0
  35. package/src/interactions/move.ts +257 -0
  36. package/src/interactions/open-link.ts +193 -0
  37. package/src/interactions/press.ts +898 -0
  38. package/src/interactions/prevent-focus.ts +102 -0
  39. package/src/interactions/scroll-wheel.ts +43 -0
  40. package/src/interactions/text-selection.ts +77 -0
  41. package/src/interactions.ts +81 -0
  42. package/src/label.ts +128 -0
  43. package/src/link.tsx +381 -0
  44. package/src/listbox.tsx +721 -0
  45. package/src/live.ts +204 -0
  46. package/src/menu.tsx +2290 -0
  47. package/src/menubar.tsx +575 -0
  48. package/src/navigation.ts +735 -0
  49. package/src/numberfield.tsx +838 -0
  50. package/src/otp.ts +430 -0
  51. package/src/overlays.ts +1247 -0
  52. package/src/platform.ts +74 -0
  53. package/src/presence.ts +164 -0
  54. package/src/questionnaire.tsx +1712 -0
  55. package/src/radio.tsx +567 -0
  56. package/src/register-dom.ts +12 -0
  57. package/src/scroller.ts +1165 -0
  58. package/src/select.tsx +1665 -0
  59. package/src/selection.ts +1415 -0
  60. package/src/slider.tsx +1042 -0
  61. package/src/splitter.ts +1152 -0
  62. package/src/static-collection.ts +211 -0
  63. package/src/switch.tsx +186 -0
  64. package/src/table.tsx +0 -0
  65. package/src/tabs.tsx +1018 -0
  66. package/src/tag.tsx +452 -0
  67. package/src/textfield.tsx +417 -0
  68. package/src/toast.ts +658 -0
  69. package/src/toggle-input.tsx +48 -0
  70. package/src/toggle.ts +321 -0
  71. package/src/togglegroup.ts +365 -0
  72. package/src/toolbar.tsx +179 -0
  73. package/src/tooltip.tsx +657 -0
  74. package/src/utils.ts +758 -0
  75. package/src/validation.ts +447 -0
  76. package/src/virtualizer.tsx +674 -0
@@ -0,0 +1,951 @@
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
+ */
22
+
23
+ import {
24
+ type Accessor,
25
+ type Child,
26
+ For,
27
+ createMemo,
28
+ createContext,
29
+ createEffect,
30
+ getContext,
31
+ type Incoming,
32
+ provide,
33
+ createSignal,
34
+ } from "@barqjs/core";
35
+ import { isServer } from "@barqjs/web";
36
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
37
+ import {
38
+ CalendarDate,
39
+ CalendarDateTime,
40
+ Time,
41
+ getDaysInMonth,
42
+ today,
43
+ toCalendarDate,
44
+ type DateValue,
45
+ } from "./date.ts";
46
+ import { focusRing } from "./focus.ts";
47
+ import { dateFormatter, useLocale } from "./i18n.ts";
48
+ import { hover } from "./interactions/hover.ts";
49
+ import type { ElementRef } from "./interactions/press.ts";
50
+ import { field, type FieldOptions } from "./label.ts";
51
+ import {
52
+ fieldValidation,
53
+ type ValidationResult,
54
+ type FormValidationState,
55
+ type ValidateFunction,
56
+ type ValidationBehavior,
57
+ } from "./validation.ts";
58
+ import {
59
+ access,
60
+ callback,
61
+ controllable,
62
+ type DOMProps,
63
+ filterDOMProps,
64
+ fromProps,
65
+ type MaybeAccessor,
66
+ mergeProps,
67
+ type StyleProps,
68
+ styleProps,
69
+ } from "./utils.ts";
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // Segments
73
+ // ---------------------------------------------------------------------------
74
+
75
+ export type SegmentType =
76
+ | "year"
77
+ | "month"
78
+ | "day"
79
+ | "hour"
80
+ | "minute"
81
+ | "second"
82
+ | "dayPeriod"
83
+ | "literal";
84
+
85
+ export interface DateSegment {
86
+ type: SegmentType;
87
+ /** What it shows: the value, or the placeholder standing in for it. */
88
+ text: string;
89
+ value?: number;
90
+ minValue?: number;
91
+ maxValue?: number;
92
+ /** Nothing has been typed here yet. */
93
+ isPlaceholder: boolean;
94
+ /** A separator is not a segment the user can stand in. */
95
+ isEditable: boolean;
96
+ }
97
+
98
+ /** How much of a date the field asks for. */
99
+ export type Granularity = "day" | "hour" | "minute" | "second";
100
+
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"];
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // State
111
+ // ---------------------------------------------------------------------------
112
+
113
+ export interface DateFieldStateOptions {
114
+ value?: MaybeAccessor<DateValue | null | undefined>;
115
+ defaultValue?: MaybeAccessor<DateValue | null | undefined>;
116
+ /** What an empty field's segments count from. @default today */
117
+ placeholderValue?: MaybeAccessor<DateValue | undefined>;
118
+ minValue?: MaybeAccessor<DateValue | null | undefined>;
119
+ maxValue?: MaybeAccessor<DateValue | null | undefined>;
120
+ /** @default "day" */
121
+ granularity?: MaybeAccessor<Granularity | undefined>;
122
+ /** 12- or 24-hour. Defaults to what the locale does. */
123
+ hourCycle?: MaybeAccessor<12 | 24 | undefined>;
124
+ isDisabled?: MaybeAccessor<boolean | undefined>;
125
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
126
+ isRequired?: MaybeAccessor<boolean | undefined>;
127
+ onChange?: (value: DateValue | null) => void;
128
+ }
129
+
130
+ export interface DateFieldState {
131
+ value: Accessor<DateValue | null>;
132
+ setValue(value: DateValue | null): void;
133
+ /** The display value: the real one, or the placeholder standing in. */
134
+ displayValue: Accessor<CalendarDateTime>;
135
+ segments: Accessor<DateSegment[]>;
136
+ granularity: Accessor<Granularity>;
137
+ isDisabled: Accessor<boolean>;
138
+ isReadOnly: Accessor<boolean>;
139
+ isRequired: Accessor<boolean>;
140
+ /** Every editable segment has been filled, so the field HAS a value. */
141
+ isComplete: Accessor<boolean>;
142
+ increment(type: SegmentType): void;
143
+ decrement(type: SegmentType): void;
144
+ incrementPage(type: SegmentType): void;
145
+ decrementPage(type: SegmentType): void;
146
+ setSegment(type: SegmentType, value: number): void;
147
+ clearSegment(type: SegmentType): void;
148
+ clear(): void;
149
+ /** What a formatted value reads as, for a screen reader. */
150
+ formatValue(options?: Intl.DateTimeFormatOptions): string;
151
+ /** What `minValue` and `maxValue` make of the value, or `undefined`. */
152
+ rangeValidation: Accessor<ValidationResult | undefined>;
153
+ }
154
+
155
+ const PAGE: Partial<Record<SegmentType, number>> = {
156
+ year: 5,
157
+ month: 3,
158
+ day: 7,
159
+ hour: 2,
160
+ minute: 15,
161
+ second: 15,
162
+ };
163
+
164
+ export function dateFieldState(options: DateFieldStateOptions): DateFieldState {
165
+ const locale = useLocale();
166
+
167
+ const granularity = (): Granularity => access(options.granularity) ?? "day";
168
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
169
+ const isReadOnly = (): boolean => access(options.isReadOnly) === true;
170
+
171
+ const [value, setValueRaw] = controllable<DateValue | null>(
172
+ () => access(options.value),
173
+ () => access(options.defaultValue) ?? null,
174
+ options.onChange,
175
+ );
176
+
177
+ /** Which segments the user has actually filled in. */
178
+ const [filled, setFilled] = createSignal<Set<SegmentType>>(
179
+ new Set(value() === null ? [] : segmentsFor(granularity())),
180
+ );
181
+
182
+ const placeholder = createMemo(() => {
183
+ const given = access(options.placeholderValue);
184
+ if (given !== undefined) {
185
+ return given instanceof CalendarDateTime ? given : CalendarDateTime.from(given);
186
+ }
187
+ return CalendarDateTime.from(today(), new Time());
188
+ });
189
+
190
+ /**
191
+ * What the segments are edited INTO while the field has no value yet.
192
+ *
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.
196
+ */
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());
209
+
210
+ const isComplete = (): boolean => {
211
+ const marked = filled();
212
+ return wanted().every((type) => type === "dayPeriod" || marked.has(type));
213
+ };
214
+
215
+ /**
216
+ * The value written back, but only once the whole field is filled.
217
+ *
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.
220
+ */
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);
227
+ return;
228
+ }
229
+ setValueRaw(granularity() === "day" ? next.date : next);
230
+ };
231
+
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),
237
+ );
238
+ return parts.some((part) => part.type === "dayPeriod") ? 12 : 24;
239
+ };
240
+
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
+ };
260
+
261
+ const format = createMemo(() => {
262
+ const parts: Intl.DateTimeFormatOptions = { year: "numeric", month: "2-digit", day: "2-digit" };
263
+ const level = granularity();
264
+ if (level !== "day") {
265
+ parts.hour = "2-digit";
266
+ parts.hour12 = hourCycle() === 12;
267
+ if (level !== "hour") parts.minute = "2-digit";
268
+ if (level === "second") parts.second = "2-digit";
269
+ }
270
+ return dateFormatter(parts)();
271
+ });
272
+
273
+ 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 };
288
+ }
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;
330
+ }
331
+
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);
342
+ };
343
+
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
+ const rangeValidation = (): ValidationResult | undefined => {
371
+ const current = value();
372
+ if (current === null) return undefined;
373
+
374
+ const min = access(options.minValue);
375
+ const max = access(options.maxValue);
376
+ const under = min !== null && min !== undefined && current.compare(min) < 0;
377
+ const over = max !== null && max !== undefined && current.compare(max) > 0;
378
+ if (!under && !over) return undefined;
379
+
380
+ return {
381
+ 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
+ ],
387
+ validationDetails: {
388
+ badInput: false,
389
+ customError: false,
390
+ patternMismatch: false,
391
+ rangeOverflow: over,
392
+ rangeUnderflow: under,
393
+ stepMismatch: false,
394
+ tooLong: false,
395
+ tooShort: false,
396
+ typeMismatch: false,
397
+ valueMissing: false,
398
+ valid: false,
399
+ },
400
+ };
401
+ };
402
+
403
+ return {
404
+ value,
405
+ rangeValidation,
406
+ displayValue,
407
+ segments,
408
+ granularity,
409
+ isDisabled,
410
+ isReadOnly,
411
+ isRequired: () => access(options.isRequired) === true,
412
+ isComplete,
413
+ setValue: (next) => {
414
+ setValueRaw(next);
415
+ setFilled(new Set(next === null ? [] : wanted()));
416
+ },
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),
421
+ setSegment: (type, next) => {
422
+ if (isDisabled() || isReadOnly()) return;
423
+ const marked = new Set(filled());
424
+ marked.add(type);
425
+ commit(withSegment(type, next), marked);
426
+ },
427
+ clearSegment: (type) => {
428
+ if (isDisabled() || isReadOnly()) return;
429
+ const marked = new Set(filled());
430
+ marked.delete(type);
431
+ commit(displayValue(), marked);
432
+ },
433
+ clear: () => {
434
+ if (isDisabled() || isReadOnly()) return;
435
+ setFilled(new Set<SegmentType>());
436
+ setValueRaw(null);
437
+ },
438
+ formatValue: (formatOptions) => {
439
+ const current = value();
440
+ if (current === null) return "";
441
+ return dateFormatter(
442
+ formatOptions ?? { dateStyle: granularity() === "day" ? "long" : "long" },
443
+ locale,
444
+ )().format(toCalendarDate(current).toDate());
445
+ },
446
+ };
447
+ }
448
+
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
+ // ---------------------------------------------------------------------------
465
+ // Hooks
466
+ // ---------------------------------------------------------------------------
467
+
468
+ export interface DateFieldOptions extends FieldOptions {
469
+ ref: ElementRef;
470
+ isDisabled?: MaybeAccessor<boolean | undefined>;
471
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
472
+ isRequired?: MaybeAccessor<boolean | undefined>;
473
+ name?: MaybeAccessor<string | undefined>;
474
+ /** What the page thinks of the date, checked as it changes. */
475
+ validate?: ValidateFunction<DateValue | null>;
476
+ /** @default "aria" */
477
+ validationBehavior?: MaybeAccessor<ValidationBehavior | undefined>;
478
+ }
479
+
480
+ export interface DateFieldResult {
481
+ labelProps: DOMProps;
482
+ /** For the element holding the segments. */
483
+ fieldProps: DOMProps;
484
+ descriptionProps: DOMProps;
485
+ errorMessageProps: DOMProps;
486
+ /** For a hidden input carrying the value into a form. */
487
+ inputProps: DOMProps;
488
+ /** What is wrong with the date, and whether the user is being told. */
489
+ validation: FormValidationState;
490
+ errors: Accessor<string[]>;
491
+ isInvalid: Accessor<boolean>;
492
+ }
493
+
494
+ export function dateField(options: DateFieldOptions, state: DateFieldState): DateFieldResult {
495
+ const {
496
+ state: validation,
497
+ isInvalid,
498
+ errors,
499
+ errorMessage,
500
+ } = fieldValidation<DateValue | null>({
501
+ value: state.value,
502
+ builtinValidation: state.rangeValidation,
503
+ validate: options.validate,
504
+ validationBehavior: options.validationBehavior,
505
+ isInvalid: options.isInvalid,
506
+ errorMessage: options.errorMessage,
507
+ name: options.name,
508
+ });
509
+
510
+ const {
511
+ labelProps,
512
+ fieldProps: labelledProps,
513
+ descriptionProps,
514
+ errorMessageProps,
515
+ } = field({ ...options, isInvalid, errorMessage, labelElementType: "span" });
516
+
517
+ return {
518
+ labelProps,
519
+ descriptionProps,
520
+ errorMessageProps,
521
+ validation,
522
+ errors,
523
+ isInvalid,
524
+ fieldProps: mergeProps(filterDOMProps(options, { labelable: true }), labelledProps, {
525
+ // A group, because the segments are separate controls that together are
526
+ // one field: `role="textbox"` would promise editing the whole string.
527
+ role: "group",
528
+ "aria-disabled": () => state.isDisabled() || undefined,
529
+ "aria-invalid": () => isInvalid() || undefined,
530
+ "aria-required": () => access(options.isRequired) === true || undefined,
531
+ "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(),
535
+ }),
536
+ inputProps: {
537
+ type: "hidden",
538
+ name: () => access(options.name),
539
+ value: () => state.value()?.toString() ?? "",
540
+ },
541
+ };
542
+ }
543
+
544
+ export interface DateSegmentOptions {
545
+ segment: Accessor<DateSegment>;
546
+ ref: ElementRef;
547
+ }
548
+
549
+ export interface DateSegmentResult {
550
+ segmentProps: DOMProps;
551
+ }
552
+
553
+ export function dateSegment(options: DateSegmentOptions, state: DateFieldState): DateSegmentResult {
554
+ const segment = (): DateSegment => options.segment();
555
+
556
+ /**
557
+ * What has been typed into this segment since focus arrived.
558
+ *
559
+ * Kept here rather than in the state, because it is not part of the value:
560
+ * a segment left half typed shows what was typed and commits nothing more.
561
+ */
562
+ let entered = "";
563
+
564
+ const isEditable = (): boolean =>
565
+ segment().isEditable && !state.isDisabled() && !state.isReadOnly();
566
+
567
+ const onKeyDown = (event: KeyboardEvent): void => {
568
+ const current = segment();
569
+ if (!current.isEditable) return;
570
+
571
+ switch (event.key) {
572
+ case "ArrowUp":
573
+ event.preventDefault();
574
+ if (isEditable()) state.increment(current.type);
575
+ entered = "";
576
+ return;
577
+ case "ArrowDown":
578
+ event.preventDefault();
579
+ if (isEditable()) state.decrement(current.type);
580
+ entered = "";
581
+ return;
582
+ case "PageUp":
583
+ event.preventDefault();
584
+ if (isEditable()) state.incrementPage(current.type);
585
+ entered = "";
586
+ return;
587
+ case "PageDown":
588
+ event.preventDefault();
589
+ if (isEditable()) state.decrementPage(current.type);
590
+ entered = "";
591
+ return;
592
+ case "Home":
593
+ event.preventDefault();
594
+ if (isEditable() && current.minValue !== undefined) {
595
+ state.setSegment(current.type, current.minValue);
596
+ }
597
+ entered = "";
598
+ return;
599
+ case "End":
600
+ event.preventDefault();
601
+ if (isEditable() && current.maxValue !== undefined) {
602
+ state.setSegment(current.type, current.maxValue);
603
+ }
604
+ entered = "";
605
+ return;
606
+ case "Backspace":
607
+ case "Delete":
608
+ event.preventDefault();
609
+ if (isEditable()) state.clearSegment(current.type);
610
+ entered = "";
611
+ return;
612
+ case "ArrowLeft":
613
+ case "ArrowRight":
614
+ // The caret is between SEGMENTS, so moving it is moving focus.
615
+ event.preventDefault();
616
+ moveFocus(event.key === "ArrowRight" ? 1 : -1);
617
+ return;
618
+ default:
619
+ break;
620
+ }
621
+
622
+ if (!isEditable()) return;
623
+
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
+ }
633
+
634
+ if (!/^\d$/.test(event.key)) return;
635
+ event.preventDefault();
636
+
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;
646
+ }
647
+
648
+ entered += event.key;
649
+ state.setSegment(current.type, typed);
650
+
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);
657
+ }
658
+ };
659
+
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();
669
+ };
670
+
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;
682
+ };
683
+
684
+ return {
685
+ segmentProps: {
686
+ role: () => (segment().isEditable ? "spinbutton" : undefined),
687
+ "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),
692
+ // 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,
696
+ "aria-disabled": () => (state.isDisabled() ? true : undefined),
697
+ "aria-readonly": () => (state.isReadOnly() ? true : undefined),
698
+ contentEditable: false,
699
+ inputMode: () => (segment().type === "dayPeriod" ? "text" : "numeric"),
700
+ tabIndex: () => (segment().isEditable && !state.isDisabled() ? 0 : undefined),
701
+ onKeyDown,
702
+ onFocus: () => {
703
+ entered = "";
704
+ },
705
+ onBlur: () => {
706
+ entered = "";
707
+ },
708
+ },
709
+ };
710
+ }
711
+
712
+ // ---------------------------------------------------------------------------
713
+ // Components
714
+ // ---------------------------------------------------------------------------
715
+
716
+ interface DateFieldContextValue {
717
+ state: DateFieldState;
718
+ }
719
+
720
+ const DateFieldContext = createContext<DateFieldContextValue | null>(null);
721
+
722
+ export function useDateField(): DateFieldContextValue {
723
+ const value = getContext(DateFieldContext);
724
+ if (value === null || value === undefined) {
725
+ throw new Error("A DateSegment must be rendered inside a DateField.");
726
+ }
727
+ return value;
728
+ }
729
+
730
+ function DateFieldProvider(props: Incoming<{ value: DateFieldContextValue; children?: Child }>) {
731
+ return provide(
732
+ DateFieldContext,
733
+ () => props.value(),
734
+ () => props.children as unknown,
735
+ );
736
+ }
737
+
738
+ export interface DateFieldComponentProps extends StyleProps {
739
+ label?: Child;
740
+ description?: Child;
741
+ errorMessage?: Child;
742
+ value?: DateValue | null;
743
+ defaultValue?: DateValue | null;
744
+ placeholderValue?: DateValue;
745
+ minValue?: DateValue | null;
746
+ maxValue?: DateValue | null;
747
+ /** @default "day" */
748
+ granularity?: Granularity;
749
+ hourCycle?: 12 | 24;
750
+ isDisabled?: boolean;
751
+ isReadOnly?: boolean;
752
+ isRequired?: boolean;
753
+ isInvalid?: boolean;
754
+ /** What the page thinks of the date, checked as it changes. */
755
+ validate?: ValidateFunction<DateValue | null>;
756
+ /** @default "aria" */
757
+ validationBehavior?: ValidationBehavior;
758
+ name?: string;
759
+ "aria-label"?: string;
760
+ "aria-labelledby"?: string;
761
+ ref?: RefTarget<HTMLDivElement>;
762
+ onChange?: (value: DateValue | null) => void;
763
+ }
764
+
765
+ /**
766
+ * ```tsx
767
+ * <DateField label="Departure" value={date()} onChange={date.set} />
768
+ * <DateField label="Starts" granularity="minute" />
769
+ * ```
770
+ */
771
+ export function DateField(props: Incoming<DateFieldComponentProps>) {
772
+ const domRef = makeRef<HTMLDivElement>();
773
+
774
+ 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),
786
+ });
787
+
788
+ const {
789
+ labelProps,
790
+ fieldProps,
791
+ descriptionProps,
792
+ errorMessageProps,
793
+ inputProps,
794
+ errors,
795
+ isInvalid,
796
+ } = dateField(
797
+ {
798
+ ref: domRef,
799
+ validate: callback<[DateValue | null], string | string[] | true | null | undefined>(
800
+ props.validate,
801
+ ),
802
+ validationBehavior: () => props.validationBehavior?.(),
803
+ label: () => props.label?.(),
804
+ description: () => props.description?.(),
805
+ errorMessage: () => props.errorMessage?.(),
806
+ isDisabled: () => props.isDisabled?.(),
807
+ isReadOnly: () => props.isReadOnly?.(),
808
+ isRequired: () => props.isRequired?.(),
809
+ isInvalid: () => props.isInvalid?.(),
810
+ name: () => props.name?.(),
811
+ "aria-label": () => props["aria-label"]?.(),
812
+ "aria-labelledby": () => props["aria-labelledby"]?.(),
813
+ },
814
+ state,
815
+ );
816
+
817
+ const elementProps = mergeProps(
818
+ fieldProps,
819
+ filterDOMProps(fromProps(props), { global: true }),
820
+ styleProps(props),
821
+ {
822
+ "data-disabled": () => props.isDisabled?.() === true,
823
+ "data-invalid": isInvalid,
824
+ "data-testid": () => props["data-testid"]?.(),
825
+ },
826
+ );
827
+
828
+ return (
829
+ <DateFieldProvider value={{ state }}>
830
+ <span {...labelProps}>{props.label}</span>
831
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
832
+ {/* Keyed by INDEX, not by the segment: a new object every read would
833
+ rebuild every element on every keystroke, and the one holding
834
+ focus would be destroyed under the user. */}
835
+ <For each={() => state.segments().map((_, at) => at)}>
836
+ {(at: number) => <DateSegmentPart index={at} />}
837
+ </For>
838
+ </div>
839
+ {() => (props.name?.() === undefined ? null : <input {...inputProps} />)}
840
+ <span {...descriptionProps}>{props.description}</span>
841
+ <span {...errorMessageProps}>
842
+ {() => {
843
+ const given = props.errorMessage?.();
844
+ if (given !== undefined && given !== null && given !== "") return given;
845
+ const found = errors();
846
+ return found.length === 0 ? null : found.join(" ");
847
+ }}
848
+ </span>
849
+ </DateFieldProvider>
850
+ );
851
+ }
852
+
853
+ interface DateSegmentPartProps {
854
+ index: number;
855
+ }
856
+
857
+ /** One segment. Its own component so it keeps its element as the value moves. */
858
+ function DateSegmentPart(props: Incoming<DateSegmentPartProps>) {
859
+ const domRef = makeRef<HTMLDivElement>();
860
+ const { state } = useDateField();
861
+ const index = props.index();
862
+
863
+ const segment = (): DateSegment =>
864
+ state.segments()[index] ?? {
865
+ type: "literal",
866
+ text: "",
867
+ isPlaceholder: false,
868
+ isEditable: false,
869
+ };
870
+
871
+ const { segmentProps } = dateSegment({ segment, ref: domRef }, state);
872
+ const { hoverProps, isHovered } = hover({ isDisabled: state.isDisabled });
873
+ const { focusProps, isFocusVisible } = focusRing();
874
+
875
+ const elementProps = mergeProps(segmentProps, hoverProps, focusProps, {
876
+ "data-type": () => segment().type,
877
+ "data-placeholder": () => segment().isPlaceholder,
878
+ "data-focus-visible": isFocusVisible,
879
+ "data-hovered": isHovered,
880
+ });
881
+
882
+ return (
883
+ <div {...elementProps} ref={domRef.set}>
884
+ {() => segment().text}
885
+ </div>
886
+ );
887
+ }
888
+
889
+ export interface TimeFieldComponentProps extends Omit<
890
+ DateFieldComponentProps,
891
+ "granularity" | "value" | "defaultValue" | "onChange" | "validate"
892
+ > {
893
+ value?: Time | null;
894
+ defaultValue?: Time | null;
895
+ /** @default "minute" */
896
+ granularity?: "hour" | "minute" | "second";
897
+ /** What the page thinks of the TIME, not of the date standing behind it. */
898
+ validate?: ValidateFunction<Time | null>;
899
+ onChange?: (value: Time | null) => void;
900
+ }
901
+
902
+ /**
903
+ * A time on its own.
904
+ *
905
+ * The same segments without the date ones, so a meeting time is a field the
906
+ * user fills rather than a string they format.
907
+ */
908
+ export function TimeField(props: Incoming<TimeFieldComponentProps>) {
909
+ const day = today();
910
+
911
+ 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
+ }}
947
+ />
948
+ );
949
+ }
950
+
951
+ export { CalendarDate, CalendarDateTime, Time };