@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,1389 @@
1
+ /**
2
+ * A calendar: a month of days, one of which may be chosen.
3
+ *
4
+ * The grid is a real `role="grid"` of `columnheader`s and `gridcell`s, because
5
+ * the relationship between a day and its weekday column is what a screen
6
+ * reader reads out. Inside it, focus is a ROVING one: exactly one day is in
7
+ * the Tab order, and the arrows move it — a month of 31 separate Tab stops is
8
+ * the failure mode this pattern exists to avoid.
9
+ *
10
+ * The details that make it usable rather than merely correct:
11
+ *
12
+ * - **A day outside the visible month is not focusable.** It is rendered so
13
+ * the grid stays rectangular, and it is `aria-hidden`: Down from the last
14
+ * week should reach the next MONTH, not a greyed-out duplicate of a day the
15
+ * next grid also shows.
16
+ * - **Moving past the edge turns the page.** Right from the last day of the
17
+ * month shows the next month with its first day focused, so the arrows alone
18
+ * navigate the whole calendar.
19
+ * - **Disabled and unavailable are different.** A disabled day cannot be
20
+ * reached at all; an unavailable one is focusable and announced, because
21
+ * "the 14th is booked" is information and a day you cannot land on tells
22
+ * you nothing.
23
+ * - **Every cell is labelled with its full date.** "14" means nothing read out
24
+ * of context; "Thursday, 14 March 2024, selected" is the whole cell.
25
+ * - **Several months are one calendar.** Each is a grid of its own, named for
26
+ * its month, and the roving focus is shared between them: one Tab stop, and
27
+ * an arrow off the end of one month lands in the next without the months
28
+ * changing places. A day drawn in two grids is the day in one of them only.
29
+ */
30
+
31
+ import {
32
+ type Accessor,
33
+ type Child,
34
+ For,
35
+ createMemo,
36
+ createContext,
37
+ createEffect,
38
+ getContext,
39
+ type Incoming,
40
+ provide,
41
+ Repeat,
42
+ createSignal,
43
+ untrack,
44
+ } from "@barqjs/core";
45
+ import { isServer } from "@barqjs/web";
46
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
47
+ import { button } from "./button.tsx";
48
+ import {
49
+ CalendarDate,
50
+ constrainDate,
51
+ endOfMonth,
52
+ endOfWeek,
53
+ getDayOfWeek,
54
+ getFirstDayOfWeek,
55
+ getISOWeek,
56
+ getMinimalDaysInFirstWeek,
57
+ getWeekOfYear,
58
+ getWeeksInMonth,
59
+ isSameDay,
60
+ isSameMonth,
61
+ startOfMonth,
62
+ startOfWeek,
63
+ today,
64
+ type DateValue,
65
+ } from "./date.ts";
66
+ import { activeElement, contains, ownerDocument } from "./dom.ts";
67
+ import { focusRing } from "./focus.ts";
68
+ import { dateFormatter, useLocale } from "./i18n.ts";
69
+ import { focusSafely } from "./interactions/focusable.ts";
70
+ import { hover } from "./interactions/hover.ts";
71
+ import type { ElementRef } from "./interactions/press.ts";
72
+ import { announce } from "./live.ts";
73
+ import {
74
+ access,
75
+ callback,
76
+ controllable,
77
+ type DOMProps,
78
+ filterDOMProps,
79
+ fromProps,
80
+ id,
81
+ type MaybeAccessor,
82
+ mergeProps,
83
+ type StyleProps,
84
+ styleProps,
85
+ } from "./utils.ts";
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // State
89
+ // ---------------------------------------------------------------------------
90
+
91
+ export interface DateRange {
92
+ start: CalendarDate;
93
+ end: CalendarDate;
94
+ }
95
+
96
+ /**
97
+ * What a day is tested against to decide whether it is switched off, booked or
98
+ * otherwise marked.
99
+ *
100
+ * - a day, or a list of days;
101
+ * - a range, both ends included, as `{ from, to }` or `{ start, end }`;
102
+ * - `{ before }` and `{ after }`, neither including the day they name; given
103
+ * together they are the days strictly between, or the days outside when
104
+ * `after` is the later of the two;
105
+ * - `{ dayOfWeek }`, Sunday as 0;
106
+ * - a function, a plain yes or no, or a list of any of these.
107
+ */
108
+ export type DateMatcher =
109
+ | boolean
110
+ | CalendarDate
111
+ | ((date: CalendarDate) => boolean)
112
+ | DateRange
113
+ | { from: CalendarDate | null | undefined; to?: CalendarDate | null }
114
+ | { before: CalendarDate; after?: CalendarDate }
115
+ | { after: CalendarDate; before?: CalendarDate }
116
+ | { dayOfWeek: number | readonly number[] }
117
+ | readonly DateMatcher[];
118
+
119
+ export function dateMatches(date: CalendarDate, matcher: DateMatcher | undefined): boolean {
120
+ if (matcher === undefined) return false;
121
+ if (typeof matcher === "boolean") return matcher;
122
+ if (typeof matcher === "function") return matcher(date);
123
+ if (matcher instanceof CalendarDate) return isSameDay(date, matcher);
124
+ if (Array.isArray(matcher)) return matcher.some((one: DateMatcher) => dateMatches(date, one));
125
+
126
+ if ("dayOfWeek" in matcher) {
127
+ const days = typeof matcher.dayOfWeek === "number" ? [matcher.dayOfWeek] : matcher.dayOfWeek;
128
+ return days.includes(getDayOfWeek(date));
129
+ }
130
+ if ("start" in matcher) {
131
+ return date.compare(matcher.start) >= 0 && date.compare(matcher.end) <= 0;
132
+ }
133
+ if ("from" in matcher) {
134
+ const from = matcher.from;
135
+ if (from === null || from === undefined) return false;
136
+ const to = matcher.to ?? from;
137
+ return date.compare(from) >= 0 && date.compare(to) <= 0;
138
+ }
139
+
140
+ const { before, after } = matcher as { before?: CalendarDate; after?: CalendarDate };
141
+ if (before !== undefined && after !== undefined) {
142
+ return after.compare(before) < 0
143
+ ? date.compare(after) > 0 && date.compare(before) < 0
144
+ : date.compare(before) < 0 || date.compare(after) > 0;
145
+ }
146
+ if (before !== undefined) return date.compare(before) < 0;
147
+ return after !== undefined && date.compare(after) > 0;
148
+ }
149
+
150
+ export interface CalendarStateOptions {
151
+ value?: MaybeAccessor<CalendarDate | null | undefined>;
152
+ defaultValue?: MaybeAccessor<CalendarDate | null | undefined>;
153
+ focusedValue?: MaybeAccessor<CalendarDate | undefined>;
154
+ defaultFocusedValue?: MaybeAccessor<CalendarDate | undefined>;
155
+ minValue?: MaybeAccessor<DateValue | null | undefined>;
156
+ maxValue?: MaybeAccessor<DateValue | null | undefined>;
157
+ /** Days that exist but cannot be chosen: booked, closed, sold out. */
158
+ isDateUnavailable?: (date: CalendarDate) => boolean;
159
+ /**
160
+ * Days that are switched off, beyond the two bounds.
161
+ *
162
+ * Unlike an unavailable day these are not information: they cannot be
163
+ * chosen, and the arrow keys step over them.
164
+ */
165
+ isDateDisabled?: (date: CalendarDate) => boolean;
166
+ isDisabled?: MaybeAccessor<boolean | undefined>;
167
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
168
+ autoFocus?: MaybeAccessor<boolean | undefined>;
169
+ /** Pressing the chosen day again clears it. @default false */
170
+ allowsDeselection?: MaybeAccessor<boolean | undefined>;
171
+ /** Which day starts the week. Defaults to what the locale says. */
172
+ firstDayOfWeek?: MaybeAccessor<number | undefined>;
173
+ /** How many months are on show side by side. @default 1 */
174
+ visibleMonths?: MaybeAccessor<number | undefined>;
175
+ /** Turn every month on show at once, rather than sliding by one. @default false */
176
+ pagedNavigation?: MaybeAccessor<boolean | undefined>;
177
+ /**
178
+ * The first month on show, when its owner keeps it.
179
+ *
180
+ * Then the focused day follows the month instead of the month following the
181
+ * focused day, and a move that would turn the page only asks for it through
182
+ * `onVisibleMonthChange`.
183
+ */
184
+ visibleMonth?: MaybeAccessor<DateValue | null | undefined>;
185
+ onVisibleMonthChange?: (month: CalendarDate) => void;
186
+ /** The first and last month that can be paged to. Their days stay open. */
187
+ startMonth?: MaybeAccessor<DateValue | null | undefined>;
188
+ endMonth?: MaybeAccessor<DateValue | null | undefined>;
189
+ /** Which day counts as today. Defaults to today in `timeZone`. */
190
+ today?: MaybeAccessor<CalendarDate | undefined>;
191
+ /** The IANA zone today is reckoned in. Defaults to the local one. */
192
+ timeZone?: MaybeAccessor<string | undefined>;
193
+ onChange?: (value: CalendarDate | null) => void;
194
+ onFocusChange?: (date: CalendarDate) => void;
195
+ }
196
+
197
+ export interface CalendarState {
198
+ readonly selectionMode: "single";
199
+ value: Accessor<CalendarDate | null>;
200
+ setValue(value: CalendarDate | null): void;
201
+ focusedDate: Accessor<CalendarDate>;
202
+ setFocusedDate(date: CalendarDate): void;
203
+ /** The months on show, as the first day of the first and the last of the last. */
204
+ visibleRange: Accessor<DateRange>;
205
+ visibleMonths: Accessor<number>;
206
+ today: Accessor<CalendarDate>;
207
+ /** Put a month on show, `position` months in from the first one. */
208
+ showMonth(month: DateValue, position?: number): void;
209
+ isFocused: Accessor<boolean>;
210
+ setFocused(isFocused: boolean): void;
211
+ firstDayOfWeek: Accessor<number>;
212
+ isDisabled: Accessor<boolean>;
213
+ isReadOnly: Accessor<boolean>;
214
+ isSelected(date: CalendarDate): boolean;
215
+ isCellFocused(date: CalendarDate): boolean;
216
+ isCellDisabled(date: CalendarDate): boolean;
217
+ isCellUnavailable(date: CalendarDate): boolean;
218
+ isPreviousVisibleRangeInvalid(): boolean;
219
+ isNextVisibleRangeInvalid(): boolean;
220
+ focusPreviousDay(): void;
221
+ focusNextDay(): void;
222
+ focusPreviousRow(): void;
223
+ focusNextRow(): void;
224
+ focusPreviousSection(larger?: boolean): void;
225
+ focusNextSection(larger?: boolean): void;
226
+ focusSectionStart(): void;
227
+ focusSectionEnd(): void;
228
+ selectDate(date: CalendarDate): void;
229
+ selectFocusedDate(): void;
230
+ /** Show the month before or after the one on show. */
231
+ focusPreviousPage(): void;
232
+ focusNextPage(): void;
233
+ }
234
+
235
+ type Duration = Parameters<CalendarDate["add"]>[0];
236
+
237
+ /** A month a page button or a caption asked for. Compared by identity. */
238
+ interface PageRequest {
239
+ start: CalendarDate;
240
+ }
241
+
242
+ function unavailable(options: CalendarStateOptions, date: CalendarDate): boolean {
243
+ return options.isDateUnavailable?.(date) === true;
244
+ }
245
+
246
+ export function calendarState(options: CalendarStateOptions): CalendarState {
247
+ const locale = useLocale();
248
+
249
+ const [value, setValueRaw] = controllable<CalendarDate | null>(
250
+ () => access(options.value),
251
+ () => access(options.defaultValue) ?? null,
252
+ options.onChange,
253
+ );
254
+
255
+ const firstDayOfWeek = (): number =>
256
+ access(options.firstDayOfWeek) ?? getFirstDayOfWeek(locale().locale);
257
+
258
+ const todayDate = (): CalendarDate => access(options.today) ?? today(access(options.timeZone));
259
+ const visibleMonths = (): number => Math.max(1, Math.floor(access(options.visibleMonths) ?? 1));
260
+
261
+ const constrained = (date: CalendarDate): CalendarDate =>
262
+ constrainDate(date, access(options.minValue), access(options.maxValue));
263
+
264
+ const [rawFocusedDate, setFocusedDateRaw] = controllable<CalendarDate>(
265
+ () => access(options.focusedValue),
266
+ () => constrained(access(options.defaultFocusedValue) ?? value() ?? todayDate()),
267
+ options.onFocusChange,
268
+ );
269
+
270
+ const [isFocused, setIsFocused] = createSignal(access(options.autoFocus) === true);
271
+
272
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
273
+ const isReadOnly = (): boolean => access(options.isReadOnly) === true;
274
+
275
+ const [requested, setRequested] = createSignal<PageRequest | null>(null);
276
+
277
+ /** A first month kept inside the months that can be reached. */
278
+ const bounded = (start: CalendarDate): CalendarDate => {
279
+ const first = access(options.startMonth);
280
+ const last = access(options.endMonth);
281
+ let next = start;
282
+ if (last !== undefined && last !== null) {
283
+ const latest = startOfMonth(last).subtract({ months: visibleMonths() - 1 });
284
+ if (next.compare(latest) > 0) next = latest;
285
+ }
286
+ if (first !== undefined && first !== null) {
287
+ const earliest = startOfMonth(first);
288
+ if (next.compare(earliest) < 0) next = earliest;
289
+ }
290
+ return next;
291
+ };
292
+
293
+ /** A first month moved just far enough for the window to hold a day. */
294
+ const holding = (start: CalendarDate, date: CalendarDate): CalendarDate => {
295
+ const month = startOfMonth(date);
296
+ if (month.compare(start) < 0) return month;
297
+ const last = start.add({ months: visibleMonths() - 1 });
298
+ return month.compare(last) > 0 ? month.subtract({ months: visibleMonths() - 1 }) : start;
299
+ };
300
+
301
+ // Where the window begins. It stays where it was until the focused day leaves
302
+ // it or a page is asked for, which is what lets focus cross from one visible
303
+ // month into the next without the months changing places under it.
304
+ const firstMonth = createMemo<{ start: CalendarDate; request: PageRequest | null }>(
305
+ (previous) => {
306
+ const request = requested();
307
+ const kept = access(options.visibleMonth);
308
+ if (kept !== undefined && kept !== null) return { start: startOfMonth(kept), request };
309
+
310
+ const focused = rawFocusedDate();
311
+ let from = startOfMonth(focused);
312
+ if (previous !== undefined) {
313
+ from = request !== null && request !== previous.request ? request.start : previous.start;
314
+ }
315
+ return { start: bounded(holding(from, focused)), request };
316
+ },
317
+ );
318
+
319
+ // The month on show, and it changes when the MONTH does.
320
+ //
321
+ // Written as a plain function reading `focusedDate()`, every consumer of it
322
+ // depended on the focused DAY: an arrow key re-ran `weekDates`, which hands
323
+ // `<For>` seven new `CalendarDate` objects a row, so all forty-two cells were
324
+ // destroyed and built again — and the one holding focus went with them. A
325
+ // real browser then leaves focus on `<body>`, which happy-dom does not, so no
326
+ // test saw it.
327
+ const visibleRange = createMemo<DateRange>(
328
+ () => {
329
+ const start = firstMonth().start;
330
+ return { start, end: endOfMonth(start.add({ months: visibleMonths() - 1 })) };
331
+ },
332
+ { equals: (a, b) => isSameDay(a.start, b.start) && isSameDay(a.end, b.end) },
333
+ );
334
+
335
+ // Held to the months on show. The two only part when the window is kept by
336
+ // its owner or stopped at a bound, and a focused day nobody can see is a
337
+ // grid with no Tab stop.
338
+ const focusedDate = (): CalendarDate => {
339
+ const raw = rawFocusedDate();
340
+ const range = visibleRange();
341
+ if (raw.compare(range.start) < 0) return range.start;
342
+ return raw.compare(range.end) > 0 ? range.end : raw;
343
+ };
344
+
345
+ const isCellDisabled = (date: CalendarDate): boolean => {
346
+ if (isDisabled()) return true;
347
+ const min = access(options.minValue);
348
+ const max = access(options.maxValue);
349
+ if (min !== undefined && min !== null && date.compare(min) < 0) return true;
350
+ if (max !== undefined && max !== null && date.compare(max) > 0) return true;
351
+ return options.isDateDisabled?.(date) === true;
352
+ };
353
+
354
+ const isCellUnavailable = (date: CalendarDate): boolean => unavailable(options, date);
355
+
356
+ /** Focus, held inside the allowed range rather than refused at its edge. */
357
+ const setFocusedDate = (date: CalendarDate): void => {
358
+ const next = constrained(date);
359
+ const current = untrack(visibleRange).start;
360
+ const start = bounded(holding(current, next));
361
+ setFocusedDateRaw(next);
362
+ if (!isSameDay(start, current)) options.onVisibleMonthChange?.(start);
363
+ };
364
+
365
+ /** The window moved to begin at a month, and the focused day carried with it. */
366
+ const showFrom = (month: CalendarDate): void => {
367
+ const current = untrack(visibleRange).start;
368
+ const start = bounded(month);
369
+ if (isSameDay(start, current)) return;
370
+ const months = (start.year - current.year) * 12 + start.month - current.month;
371
+ setRequested({ start });
372
+ setFocusedDateRaw(constrained(untrack(focusedDate).add({ months })));
373
+ options.onVisibleMonthChange?.(start);
374
+ };
375
+
376
+ const page = (direction: 1 | -1): void => {
377
+ const months = access(options.pagedNavigation) === true ? visibleMonths() : 1;
378
+ showFrom(untrack(visibleRange).start.add({ months: months * direction }));
379
+ };
380
+
381
+ /**
382
+ * `date`, or the nearest day further that way that is not switched off.
383
+ *
384
+ * Null when there is none within a year, or the bounds are reached first:
385
+ * the focus then stays where it is rather than resting on a day that cannot
386
+ * be chosen.
387
+ */
388
+ const reachable = (date: CalendarDate, step: Duration): CalendarDate | null => {
389
+ const off = options.isDateDisabled;
390
+ let next = constrained(date);
391
+ if (off === undefined) return next;
392
+ for (let tries = 0; off(next); tries++) {
393
+ const further = constrained(next.add(step));
394
+ if (tries === 366 || isSameDay(further, next)) return null;
395
+ next = further;
396
+ }
397
+ return next;
398
+ };
399
+
400
+ const land = (date: CalendarDate, step: Duration): void => {
401
+ const next = reachable(date, step);
402
+ if (next !== null) setFocusedDate(next);
403
+ };
404
+
405
+ const move = (duration: Duration): void => land(focusedDate().add(duration), duration);
406
+
407
+ const selectDate = (date: CalendarDate): void => {
408
+ if (isReadOnly() || isDisabled()) return;
409
+ if (isCellDisabled(date) || isCellUnavailable(date)) return;
410
+ const chosen = untrack(value);
411
+ if (access(options.allowsDeselection) === true && chosen !== null && isSameDay(chosen, date)) {
412
+ setValueRaw(null);
413
+ return;
414
+ }
415
+ setValueRaw(date);
416
+ };
417
+
418
+ return {
419
+ selectionMode: "single",
420
+ value,
421
+ setValue: (next) => setValueRaw(next),
422
+ focusedDate,
423
+ setFocusedDate,
424
+ visibleRange,
425
+ visibleMonths,
426
+ today: todayDate,
427
+ showMonth: (month, position = 0) =>
428
+ showFrom(startOfMonth(month).subtract({ months: position })),
429
+ isFocused,
430
+ setFocused: (next) => setIsFocused(next),
431
+ firstDayOfWeek,
432
+ isDisabled,
433
+ isReadOnly,
434
+ isSelected: (date) => {
435
+ const selected = value();
436
+ return selected !== null && isSameDay(selected, date);
437
+ },
438
+ isCellFocused: (date) => isFocused() && isSameDay(focusedDate(), date),
439
+ isCellDisabled,
440
+ isCellUnavailable,
441
+ isPreviousVisibleRangeInvalid: () => {
442
+ const first = access(options.startMonth);
443
+ if (first !== undefined && first !== null) {
444
+ if (visibleRange().start.compare(startOfMonth(first)) <= 0) return true;
445
+ }
446
+ const min = access(options.minValue);
447
+ if (min === undefined || min === null) return false;
448
+ return visibleRange().start.subtract({ days: 1 }).compare(min) < 0;
449
+ },
450
+ isNextVisibleRangeInvalid: () => {
451
+ const last = access(options.endMonth);
452
+ if (last !== undefined && last !== null) {
453
+ if (visibleRange().end.compare(endOfMonth(last)) >= 0) return true;
454
+ }
455
+ const max = access(options.maxValue);
456
+ if (max === undefined || max === null) return false;
457
+ return visibleRange().end.add({ days: 1 }).compare(max) > 0;
458
+ },
459
+ focusPreviousDay: () => move({ days: -1 }),
460
+ focusNextDay: () => move({ days: 1 }),
461
+ focusPreviousRow: () => move({ weeks: -1 }),
462
+ focusNextRow: () => move({ weeks: 1 }),
463
+ focusPreviousSection: (larger) => move(larger === true ? { years: -1 } : { months: -1 }),
464
+ focusNextSection: (larger) => move(larger === true ? { years: 1 } : { months: 1 }),
465
+ focusSectionStart: () => land(startOfWeek(focusedDate(), firstDayOfWeek()), { days: 1 }),
466
+ focusSectionEnd: () => land(endOfWeek(focusedDate(), firstDayOfWeek()), { days: -1 }),
467
+ selectDate,
468
+ selectFocusedDate: () => selectDate(focusedDate()),
469
+ focusPreviousPage: () => page(-1),
470
+ focusNextPage: () => page(1),
471
+ };
472
+ }
473
+
474
+ // ---------------------------------------------------------------------------
475
+ // A range of days
476
+ // ---------------------------------------------------------------------------
477
+
478
+ export interface RangeCalendarStateOptions extends Omit<
479
+ CalendarStateOptions,
480
+ "value" | "defaultValue" | "onChange"
481
+ > {
482
+ value?: MaybeAccessor<DateRange | null | undefined>;
483
+ defaultValue?: MaybeAccessor<DateRange | null | undefined>;
484
+ /** Nothing between the ends may be unavailable. @default false */
485
+ allowsNonContiguousRanges?: MaybeAccessor<boolean | undefined>;
486
+ /** The fewest and the most days a range may cover, both ends counted. */
487
+ minDays?: MaybeAccessor<number | undefined>;
488
+ maxDays?: MaybeAccessor<number | undefined>;
489
+ /** A switched-off day between the ends breaks the range. @default false */
490
+ excludeDisabled?: MaybeAccessor<boolean | undefined>;
491
+ onChange?: (value: DateRange | null) => void;
492
+ }
493
+
494
+ export interface RangeCalendarState extends Omit<
495
+ CalendarState,
496
+ "value" | "setValue" | "selectionMode"
497
+ > {
498
+ readonly selectionMode: "range";
499
+ value: Accessor<DateRange | null>;
500
+ setValue(value: DateRange | null): void;
501
+ /** Where a range being drawn began, or null when none is. */
502
+ anchorDate: Accessor<CalendarDate | null>;
503
+ setAnchorDate(date: CalendarDate | null): void;
504
+ /** What the range currently covers: the value, or the drag in progress. */
505
+ highlightedRange: Accessor<DateRange | null>;
506
+ highlightDate(date: CalendarDate): void;
507
+ }
508
+
509
+ function ordered(a: CalendarDate, b: CalendarDate): DateRange {
510
+ // A range drawn backwards is still a range: the anchor is where the user
511
+ // started, not necessarily the earlier day.
512
+ return a.compare(b) <= 0 ? { start: a, end: b } : { start: b, end: a };
513
+ }
514
+
515
+ export function rangeCalendarState(options: RangeCalendarStateOptions): RangeCalendarState {
516
+ const [value, setValueRaw] = controllable<DateRange | null>(
517
+ () => access(options.value),
518
+ () => access(options.defaultValue) ?? null,
519
+ options.onChange,
520
+ );
521
+
522
+ const [anchorDate, writeAnchorDate] = createSignal<CalendarDate | null>(null);
523
+ const [drawn, setDrawn] = createSignal<DateRange | null>(null);
524
+
525
+ const base = calendarState({
526
+ ...(options as CalendarStateOptions),
527
+ value: () => value()?.start ?? null,
528
+ defaultValue: undefined,
529
+ onChange: undefined,
530
+ onFocusChange: (date) => {
531
+ // While a range is being drawn, moving focus IS drawing it, whichever
532
+ // way the focus moved: a press, an arrow key or a page button.
533
+ if (untrack(anchorDate) !== null) highlightDate(date);
534
+ options.onFocusChange?.(date);
535
+ },
536
+ });
537
+
538
+ const highlightedRange = (): DateRange | null => {
539
+ const anchor = anchorDate();
540
+ if (anchor === null) return value();
541
+ return drawn();
542
+ };
543
+
544
+ /** Whether every day between two ends can be chosen. */
545
+ const contiguous = (range: DateRange): boolean => {
546
+ const gaps = access(options.allowsNonContiguousRanges) === true;
547
+ const holes = access(options.excludeDisabled) !== true;
548
+ if (gaps && holes) return true;
549
+ for (let day = range.start; day.compare(range.end) <= 0; day = day.add({ days: 1 })) {
550
+ if (!gaps && base.isCellUnavailable(day)) return false;
551
+ if (!holes && base.isCellDisabled(day)) return false;
552
+ }
553
+ return true;
554
+ };
555
+
556
+ const allowedLength = (range: DateRange): boolean => {
557
+ const days = range.end.epochDay - range.start.epochDay + 1;
558
+ const min = access(options.minDays);
559
+ const max = access(options.maxDays);
560
+ return (min === undefined || days >= min) && (max === undefined || days <= max);
561
+ };
562
+
563
+ const highlightDate = (date: CalendarDate): void => {
564
+ const anchor = anchorDate();
565
+ if (anchor === null) return;
566
+ setDrawn(ordered(anchor, date));
567
+ };
568
+
569
+ const selectDate = (date: CalendarDate): void => {
570
+ if (base.isReadOnly() || base.isDisabled()) return;
571
+ if (base.isCellDisabled(date) || base.isCellUnavailable(date)) return;
572
+
573
+ const anchor = anchorDate();
574
+ if (anchor === null) {
575
+ writeAnchorDate(date);
576
+ setDrawn({ start: date, end: date });
577
+ return;
578
+ }
579
+
580
+ const range = ordered(anchor, date);
581
+ writeAnchorDate(null);
582
+ setDrawn(null);
583
+ // A range with something unavailable inside it is not a range the user can
584
+ // have; the second press starts a new one rather than silently failing.
585
+ if (!contiguous(range) || !allowedLength(range)) {
586
+ writeAnchorDate(date);
587
+ setDrawn({ start: date, end: date });
588
+ return;
589
+ }
590
+ setValueRaw(range);
591
+ };
592
+
593
+ return {
594
+ ...base,
595
+ selectionMode: "range",
596
+ value,
597
+ setValue: (next) => setValueRaw(next),
598
+ anchorDate,
599
+ setAnchorDate: (date) => {
600
+ writeAnchorDate(date);
601
+ setDrawn(date === null ? null : { start: date, end: date });
602
+ },
603
+ highlightedRange,
604
+ highlightDate,
605
+ isSelected: (date) => {
606
+ const range = highlightedRange();
607
+ if (range === null) return false;
608
+ return date.compare(range.start) >= 0 && date.compare(range.end) <= 0;
609
+ },
610
+ selectDate,
611
+ selectFocusedDate: () => selectDate(base.focusedDate()),
612
+ };
613
+ }
614
+
615
+ // ---------------------------------------------------------------------------
616
+ // Several days
617
+ // ---------------------------------------------------------------------------
618
+
619
+ export interface MultipleCalendarStateOptions extends Omit<
620
+ CalendarStateOptions,
621
+ "value" | "defaultValue" | "onChange"
622
+ > {
623
+ value?: MaybeAccessor<readonly CalendarDate[] | undefined>;
624
+ defaultValue?: MaybeAccessor<readonly CalendarDate[] | undefined>;
625
+ /** The fewest days that may be left chosen, and the most that may be. */
626
+ min?: MaybeAccessor<number | undefined>;
627
+ max?: MaybeAccessor<number | undefined>;
628
+ /** The last chosen day cannot be taken away. @default false */
629
+ required?: MaybeAccessor<boolean | undefined>;
630
+ onChange?: (value: CalendarDate[]) => void;
631
+ }
632
+
633
+ export interface MultipleCalendarState extends Omit<
634
+ CalendarState,
635
+ "value" | "setValue" | "selectionMode"
636
+ > {
637
+ readonly selectionMode: "multiple";
638
+ /** The chosen days, in the order they were chosen. */
639
+ value: Accessor<readonly CalendarDate[]>;
640
+ setValue(value: readonly CalendarDate[]): void;
641
+ }
642
+
643
+ /**
644
+ * Any number of days, each pressed on and off on its own.
645
+ *
646
+ * A press that would leave fewer than `min` or make more than `max` does
647
+ * nothing, rather than dropping some other day to make room: which day to drop
648
+ * is not a decision a calendar can make for anyone.
649
+ */
650
+ export function multipleCalendarState(
651
+ options: MultipleCalendarStateOptions,
652
+ ): MultipleCalendarState {
653
+ const [value, setValueRaw] = controllable<readonly CalendarDate[]>(
654
+ () => access(options.value),
655
+ () => access(options.defaultValue) ?? [],
656
+ (next) => options.onChange?.([...next]),
657
+ );
658
+
659
+ const base = calendarState({
660
+ ...(options as CalendarStateOptions),
661
+ value: () => value()[0] ?? null,
662
+ defaultValue: undefined,
663
+ onChange: undefined,
664
+ });
665
+
666
+ const isSelected = (date: CalendarDate): boolean =>
667
+ value().some((chosen) => isSameDay(chosen, date));
668
+
669
+ const selectDate = (date: CalendarDate): void => {
670
+ if (base.isReadOnly() || base.isDisabled()) return;
671
+ if (base.isCellDisabled(date) || base.isCellUnavailable(date)) return;
672
+
673
+ const chosen = untrack(value);
674
+ if (chosen.some((one) => isSameDay(one, date))) {
675
+ const least = Math.max(access(options.min) ?? 0, access(options.required) === true ? 1 : 0);
676
+ if (chosen.length - 1 < least) return;
677
+ setValueRaw(chosen.filter((one) => !isSameDay(one, date)));
678
+ return;
679
+ }
680
+
681
+ const most = access(options.max);
682
+ if (most !== undefined && chosen.length >= most) return;
683
+ setValueRaw([...chosen, date]);
684
+ };
685
+
686
+ return {
687
+ ...base,
688
+ selectionMode: "multiple",
689
+ value,
690
+ setValue: (next) => setValueRaw(next),
691
+ isSelected,
692
+ selectDate,
693
+ selectFocusedDate: () => selectDate(base.focusedDate()),
694
+ };
695
+ }
696
+
697
+ /** Any of the three states a calendar can be built on. */
698
+ export type AnyCalendarState = CalendarState | RangeCalendarState | MultipleCalendarState;
699
+
700
+ // ---------------------------------------------------------------------------
701
+ // Hooks
702
+ // ---------------------------------------------------------------------------
703
+
704
+ export interface CalendarOptions {
705
+ // No `isDisabled`: the STATE carries it, and a second copy here would be a
706
+ // flag a caller could set and watch do nothing.
707
+ "aria-label"?: MaybeAccessor<string | undefined>;
708
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
709
+ }
710
+
711
+ export interface CalendarResult {
712
+ calendarProps: DOMProps;
713
+ /** Options for {@link button}, not props for an element. */
714
+ prevButtonProps: DOMProps;
715
+ nextButtonProps: DOMProps;
716
+ errorMessageProps: DOMProps;
717
+ /** The month on show, as a heading. With several on show, the first to the last. */
718
+ title: Accessor<string>;
719
+ baseId: Accessor<string>;
720
+ }
721
+
722
+ export function calendar(options: CalendarOptions, state: AnyCalendarState): CalendarResult {
723
+ const baseId = id();
724
+ const errorMessageId = id();
725
+ const titleFormat = dateFormatter({ month: "long", year: "numeric" });
726
+
727
+ const title = (): string => {
728
+ const range = state.visibleRange();
729
+ const first = range.start.toDate();
730
+ if (state.visibleMonths() === 1) return titleFormat().format(first);
731
+ return titleFormat().formatRange(first, startOfMonth(range.end).toDate());
732
+ };
733
+
734
+ if (!isServer) {
735
+ // The month changing under a pointer press has nothing on screen to say
736
+ // so; a screen reader user pressing "next" hears only the button.
737
+ let previous = title();
738
+ createEffect(title, (current) => {
739
+ if (current === previous) return;
740
+ previous = current;
741
+ if (!untrack(state.isFocused)) announce(current);
742
+ });
743
+ }
744
+
745
+ return {
746
+ baseId,
747
+ title,
748
+ errorMessageProps: { id: errorMessageId },
749
+ calendarProps: mergeProps(filterDOMProps(options, { labelable: true }), {
750
+ role: "group",
751
+ id: baseId,
752
+ "aria-label": () => access(options["aria-label"]),
753
+ "aria-labelledby": () => access(options["aria-labelledby"]),
754
+ }),
755
+ prevButtonProps: {
756
+ "aria-label": "Previous month",
757
+ isDisabled: () => state.isDisabled() || state.isPreviousVisibleRangeInvalid(),
758
+ onPress: () => state.focusPreviousPage(),
759
+ },
760
+ nextButtonProps: {
761
+ "aria-label": "Next month",
762
+ isDisabled: () => state.isDisabled() || state.isNextVisibleRangeInvalid(),
763
+ onPress: () => state.focusNextPage(),
764
+ },
765
+ };
766
+ }
767
+
768
+ export interface CalendarGridOptions {
769
+ /** @default "narrow" */
770
+ weekdayStyle?: MaybeAccessor<"narrow" | "short" | "long" | undefined>;
771
+ /** Which of the months on show this grid draws, counted from the first. @default 0 */
772
+ monthOffset?: MaybeAccessor<number | undefined>;
773
+ /** Always six week rows, so paging never changes the height. @default false */
774
+ fixedWeeks?: MaybeAccessor<boolean | undefined>;
775
+ /** Number the weeks by ISO 8601 rather than by the locale. @default false */
776
+ isoWeek?: MaybeAccessor<boolean | undefined>;
777
+ "aria-label"?: MaybeAccessor<string | undefined>;
778
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
779
+ }
780
+
781
+ export interface CalendarGridResult {
782
+ gridProps: DOMProps;
783
+ headerProps: DOMProps;
784
+ /** The first day of the month this grid draws. */
785
+ month: Accessor<CalendarDate>;
786
+ /** That month as a heading. */
787
+ title: Accessor<string>;
788
+ /** The weekday names, from the locale, starting on its first day. */
789
+ weekDays: Accessor<string[]>;
790
+ weeksInMonth: Accessor<number>;
791
+ /** Every day of a week row, including the ones outside the month. */
792
+ weekDates: (week: number) => CalendarDate[];
793
+ /** Which week of the year a row is, going by the row's first day. */
794
+ weekNumber: (week: number) => number;
795
+ }
796
+
797
+ export function calendarGrid(
798
+ options: CalendarGridOptions,
799
+ state: AnyCalendarState,
800
+ ): CalendarGridResult {
801
+ const locale = useLocale();
802
+ const titleFormat = dateFormatter({ month: "long", year: "numeric" });
803
+
804
+ const month = (): CalendarDate =>
805
+ state.visibleRange().start.add({ months: access(options.monthOffset) ?? 0 });
806
+ const dayFormat = createMemo(() =>
807
+ dateFormatter({ weekday: access(options.weekdayStyle) ?? "narrow" })(),
808
+ );
809
+
810
+ const weekDays = createMemo(() => {
811
+ const start = startOfWeek(today(), state.firstDayOfWeek());
812
+ return Array.from({ length: 7 }, (_, at) =>
813
+ dayFormat().format(start.add({ days: at }).toDate()),
814
+ );
815
+ });
816
+
817
+ const weeksInMonth = (): number =>
818
+ access(options.fixedWeeks) === true ? 6 : getWeeksInMonth(month(), state.firstDayOfWeek());
819
+
820
+ const weekDates = (week: number): CalendarDate[] => {
821
+ const first = startOfWeek(month(), state.firstDayOfWeek());
822
+ const start = first.add({ weeks: week });
823
+ return Array.from({ length: 7 }, (_, at) => start.add({ days: at }));
824
+ };
825
+
826
+ const weekNumber = (week: number): number => {
827
+ const first = startOfWeek(month(), state.firstDayOfWeek()).add({ weeks: week });
828
+ if (access(options.isoWeek) === true) return getISOWeek(first);
829
+ return getWeekOfYear(first, state.firstDayOfWeek(), getMinimalDaysInFirstWeek(locale().locale));
830
+ };
831
+
832
+ const onKeyDown = (event: KeyboardEvent): void => {
833
+ const rtl = locale().direction === "rtl";
834
+
835
+ switch (event.key) {
836
+ case "ArrowLeft":
837
+ if (rtl) state.focusNextDay();
838
+ else state.focusPreviousDay();
839
+ break;
840
+ case "ArrowRight":
841
+ if (rtl) state.focusPreviousDay();
842
+ else state.focusNextDay();
843
+ break;
844
+ case "ArrowUp":
845
+ state.focusPreviousRow();
846
+ break;
847
+ case "ArrowDown":
848
+ state.focusNextRow();
849
+ break;
850
+ case "PageUp":
851
+ state.focusPreviousSection(event.shiftKey);
852
+ break;
853
+ case "PageDown":
854
+ state.focusNextSection(event.shiftKey);
855
+ break;
856
+ case "Home":
857
+ state.focusSectionStart();
858
+ break;
859
+ case "End":
860
+ state.focusSectionEnd();
861
+ break;
862
+ case "Enter":
863
+ case " ":
864
+ state.selectFocusedDate();
865
+ break;
866
+ case "Escape": {
867
+ // Abandon a range half drawn, rather than leaving an anchor behind
868
+ // that the next press would finish against.
869
+ if ("setAnchorDate" in state) {
870
+ event.preventDefault();
871
+ state.setAnchorDate(null);
872
+ }
873
+ return;
874
+ }
875
+ default:
876
+ return;
877
+ }
878
+
879
+ event.preventDefault();
880
+ event.stopPropagation();
881
+ };
882
+
883
+ const title = (): string => titleFormat().format(month().toDate());
884
+
885
+ return {
886
+ month,
887
+ title,
888
+ weekDays,
889
+ weeksInMonth,
890
+ weekDates,
891
+ weekNumber,
892
+ headerProps: { "aria-hidden": true },
893
+ gridProps: {
894
+ role: "grid",
895
+ "aria-multiselectable": state.selectionMode === "single" ? undefined : true,
896
+ "aria-readonly": () => state.isReadOnly() || undefined,
897
+ "aria-disabled": () => state.isDisabled() || undefined,
898
+ // A grid nobody named is named for its month: with a caption made of
899
+ // selects there is no heading to point at, and an unnamed grid is announced
900
+ // as "grid" and nothing else.
901
+ "aria-label": () =>
902
+ access(options["aria-label"]) ??
903
+ (access(options["aria-labelledby"]) === undefined ? title() : undefined),
904
+ "aria-labelledby": () => access(options["aria-labelledby"]),
905
+ onKeyDown,
906
+ onFocusIn: () => state.setFocused(true),
907
+ // Removing the focused day fires `focusout` exactly as leaving the
908
+ // calendar does, and moving between months removes a row. Clearing here
909
+ // told the calendar it had lost focus in the middle of moving it, so the
910
+ // day it moved TO no longer wanted focus and it stayed on `<body>`. The
911
+ // question is answered a microtask later, against where focus actually
912
+ // is.
913
+ onFocusOut: (event: FocusEvent) => {
914
+ const grid = event.currentTarget as Element | null;
915
+ if (grid === null) {
916
+ state.setFocused(false);
917
+ return;
918
+ }
919
+ queueMicrotask(() => {
920
+ if (!contains(grid, activeElement(ownerDocument(grid)))) state.setFocused(false);
921
+ });
922
+ },
923
+ },
924
+ };
925
+ }
926
+
927
+ export interface CalendarCellOptions {
928
+ /**
929
+ * The day.
930
+ *
931
+ * An accessor, because a cell OUTLIVES the day it draws: the grid keys its
932
+ * rows and columns by position, so changing month moves 42 dates through 42
933
+ * elements that stay where they are. A cell that was rebuilt instead would
934
+ * be destroyed while it held focus.
935
+ */
936
+ date: MaybeAccessor<CalendarDate>;
937
+ ref: ElementRef;
938
+ /** Rendered to keep the grid rectangular, but belonging to another month. */
939
+ isOutsideMonth?: MaybeAccessor<boolean | undefined>;
940
+ /**
941
+ * The month of the grid this cell is in. Defaults to the first one on show.
942
+ *
943
+ * With several months side by side the same day can be drawn twice, once in
944
+ * its own grid and once as the tail of its neighbour's last week; only the
945
+ * first of those is the day.
946
+ */
947
+ month?: MaybeAccessor<CalendarDate | undefined>;
948
+ }
949
+
950
+ export interface CalendarCellResult {
951
+ cellProps: DOMProps;
952
+ /** For the element inside the cell that the user actually presses. */
953
+ buttonProps: DOMProps;
954
+ isSelected: Accessor<boolean>;
955
+ isFocused: Accessor<boolean>;
956
+ isDisabled: Accessor<boolean>;
957
+ isUnavailable: Accessor<boolean>;
958
+ isOutsideVisibleRange: Accessor<boolean>;
959
+ isToday: Accessor<boolean>;
960
+ /**
961
+ * The first and last day of the range this cell is in, if it is in one.
962
+ *
963
+ * Both are false in a calendar that selects a single day: there is no range,
964
+ * so there are no ends to it. A range's three positions — its two ends and
965
+ * everything between — are what a stylesheet needs to round the corners of
966
+ * one selection and not of the days inside it.
967
+ */
968
+ isSelectionStart: Accessor<boolean>;
969
+ isSelectionEnd: Accessor<boolean>;
970
+ formattedDate: Accessor<string>;
971
+ }
972
+
973
+ export function calendarCell(
974
+ options: CalendarCellOptions,
975
+ state: AnyCalendarState,
976
+ ): CalendarCellResult {
977
+ const labelFormat = dateFormatter({
978
+ weekday: "long",
979
+ day: "numeric",
980
+ month: "long",
981
+ year: "numeric",
982
+ });
983
+ const dayFormat = dateFormatter({ day: "numeric" });
984
+
985
+ const date = (): CalendarDate => access(options.date);
986
+
987
+ const isOutside = (): boolean =>
988
+ access(options.isOutsideMonth) === true ||
989
+ !isSameMonth(date(), access(options.month) ?? state.visibleRange().start);
990
+
991
+ const isDisabled = (): boolean => state.isCellDisabled(date()) || isOutside();
992
+ const isUnavailable = (): boolean => state.isCellUnavailable(date());
993
+ const isSelectable = (): boolean => !isDisabled() && !isUnavailable();
994
+ const isSelected = (): boolean => state.isSelected(date()) && isSelectable();
995
+ const isFocused = (): boolean => state.isCellFocused(date()) && !isOutside();
996
+ const isTodayCell = (): boolean => isSameDay(date(), state.today());
997
+
998
+ const highlighted = (): DateRange | null =>
999
+ "highlightedRange" in state ? state.highlightedRange() : null;
1000
+ const isSelectionStart = (): boolean => {
1001
+ const range = highlighted();
1002
+ return isSelected() && range !== null && isSameDay(date(), range.start);
1003
+ };
1004
+ const isSelectionEnd = (): boolean => {
1005
+ const range = highlighted();
1006
+ return isSelected() && range !== null && isSameDay(date(), range.end);
1007
+ };
1008
+
1009
+ if (!isServer) {
1010
+ // The state decides which day is focused; the DOM follows it, so the
1011
+ // arrows move focus without every cell having to watch the keyboard.
1012
+ createEffect(
1013
+ () => (isFocused() ? { element: access(options.ref) as HTMLElement | null } : null),
1014
+ (focused) => {
1015
+ if (focused === null) return;
1016
+ const { element } = focused;
1017
+ if (element === null) return;
1018
+ if (activeElement(ownerDocument(element)) !== element) focusSafely(element);
1019
+ },
1020
+ );
1021
+ }
1022
+
1023
+ const label = (): string => {
1024
+ let text = labelFormat().format(date().toDate());
1025
+ if (isTodayCell()) text = `Today, ${text}`;
1026
+ if (isSelected()) text = `${text}, selected`;
1027
+ return text;
1028
+ };
1029
+
1030
+ return {
1031
+ isSelected,
1032
+ isFocused,
1033
+ isDisabled,
1034
+ isUnavailable,
1035
+ isOutsideVisibleRange: isOutside,
1036
+ isToday: isTodayCell,
1037
+ isSelectionStart,
1038
+ isSelectionEnd,
1039
+ formattedDate: () => dayFormat().format(date().toDate()),
1040
+ cellProps: {
1041
+ role: "gridcell",
1042
+ "aria-selected": () => isSelected() || undefined,
1043
+ "aria-disabled": () => (!isSelectable() ? true : undefined),
1044
+ },
1045
+ buttonProps: {
1046
+ role: "button",
1047
+ // A day outside the month is scaffolding: hidden from the tree, so Down
1048
+ // from the last week reaches the next MONTH and not a duplicate.
1049
+ "aria-hidden": () => isOutside() || undefined,
1050
+ "aria-label": label,
1051
+ "aria-invalid": () => undefined,
1052
+ // The roving focus: one day in the Tab order, and it moves with the
1053
+ // arrows.
1054
+ tabIndex: () =>
1055
+ isOutside() ? undefined : isFocused() || isSameDay(state.focusedDate(), date()) ? 0 : -1,
1056
+ onPointerEnter: () => {
1057
+ // Drawing a range follows the pointer, so the highlight is what the
1058
+ // user would get by releasing here.
1059
+ if ("highlightDate" in state && state.anchorDate() !== null) {
1060
+ state.highlightDate(date());
1061
+ }
1062
+ },
1063
+ onClick: () => {
1064
+ if (isOutside() || state.isCellDisabled(date())) return;
1065
+ state.setFocusedDate(date());
1066
+ state.selectDate(date());
1067
+ },
1068
+ },
1069
+ };
1070
+ }
1071
+
1072
+ // ---------------------------------------------------------------------------
1073
+ // Components
1074
+ // ---------------------------------------------------------------------------
1075
+
1076
+ interface CalendarContextValue {
1077
+ state: AnyCalendarState;
1078
+ baseId: Accessor<string>;
1079
+ }
1080
+
1081
+ const CalendarContext = createContext<CalendarContextValue | null>(null);
1082
+
1083
+ export function useCalendar(): CalendarContextValue {
1084
+ const value = getContext(CalendarContext);
1085
+ if (value === null || value === undefined) {
1086
+ throw new Error("This must be rendered inside a Calendar.");
1087
+ }
1088
+ return value;
1089
+ }
1090
+
1091
+ function CalendarProvider(props: Incoming<{ value: CalendarContextValue; children?: Child }>) {
1092
+ return provide(
1093
+ CalendarContext,
1094
+ () => props.value(),
1095
+ () => props.children as unknown,
1096
+ );
1097
+ }
1098
+
1099
+ export interface CalendarComponentProps extends StyleProps {
1100
+ value?: CalendarDate | null;
1101
+ defaultValue?: CalendarDate | null;
1102
+ focusedValue?: CalendarDate;
1103
+ defaultFocusedValue?: CalendarDate;
1104
+ minValue?: DateValue | null;
1105
+ maxValue?: DateValue | null;
1106
+ isDateUnavailable?: (date: CalendarDate) => boolean;
1107
+ /** Days that cannot be chosen and that the arrow keys step over. */
1108
+ isDateDisabled?: (date: CalendarDate) => boolean;
1109
+ isDisabled?: boolean;
1110
+ isReadOnly?: boolean;
1111
+ autoFocus?: boolean;
1112
+ /** Pressing the chosen day again clears it. @default false */
1113
+ allowsDeselection?: boolean;
1114
+ firstDayOfWeek?: number;
1115
+ /** Always six week rows. @default false */
1116
+ fixedWeeks?: boolean;
1117
+ /** The IANA zone today is reckoned in. Defaults to the local one. */
1118
+ timeZone?: string;
1119
+ /** @default "narrow" */
1120
+ weekdayStyle?: "narrow" | "short" | "long";
1121
+ errorMessage?: Child;
1122
+ "aria-label"?: string;
1123
+ "aria-labelledby"?: string;
1124
+ ref?: RefTarget<HTMLDivElement>;
1125
+ onChange?: (value: CalendarDate | null) => void;
1126
+ onFocusChange?: (date: CalendarDate) => void;
1127
+ }
1128
+
1129
+ /**
1130
+ * ```tsx
1131
+ * <Calendar aria-label="Departure" value={date()} onChange={date.set}
1132
+ * minValue={today()} />
1133
+ * ```
1134
+ */
1135
+ export function Calendar(props: Incoming<CalendarComponentProps>) {
1136
+ const state = calendarState({
1137
+ value: () => props.value?.(),
1138
+ defaultValue: () => props.defaultValue?.(),
1139
+ focusedValue: () => props.focusedValue?.(),
1140
+ defaultFocusedValue: () => props.defaultFocusedValue?.(),
1141
+ minValue: () => props.minValue?.(),
1142
+ maxValue: () => props.maxValue?.(),
1143
+ isDateUnavailable: callback<[CalendarDate], boolean>(props.isDateUnavailable),
1144
+ isDateDisabled: callback<[CalendarDate], boolean>(props.isDateDisabled),
1145
+ isDisabled: () => props.isDisabled?.(),
1146
+ isReadOnly: () => props.isReadOnly?.(),
1147
+ autoFocus: () => props.autoFocus?.(),
1148
+ allowsDeselection: () => props.allowsDeselection?.(),
1149
+ firstDayOfWeek: () => props.firstDayOfWeek?.(),
1150
+ timeZone: () => props.timeZone?.(),
1151
+ onChange: (value) => props.onChange?.()?.(value),
1152
+ onFocusChange: (date) => props.onFocusChange?.()?.(date),
1153
+ });
1154
+
1155
+ return <CalendarBody state={state} of={props} />;
1156
+ }
1157
+
1158
+ export interface RangeCalendarComponentProps extends Omit<
1159
+ CalendarComponentProps,
1160
+ "value" | "defaultValue" | "onChange"
1161
+ > {
1162
+ value?: DateRange | null;
1163
+ defaultValue?: DateRange | null;
1164
+ allowsNonContiguousRanges?: boolean;
1165
+ onChange?: (value: DateRange | null) => void;
1166
+ }
1167
+
1168
+ /**
1169
+ * Two days, and everything between them.
1170
+ *
1171
+ * The first press anchors, the second finishes. Moving the pointer or the
1172
+ * focus between the two DRAWS: what is highlighted is what releasing would
1173
+ * give, so the user is never guessing.
1174
+ */
1175
+ export function RangeCalendar(props: Incoming<RangeCalendarComponentProps>) {
1176
+ const state = rangeCalendarState({
1177
+ value: () => props.value?.(),
1178
+ defaultValue: () => props.defaultValue?.(),
1179
+ focusedValue: () => props.focusedValue?.(),
1180
+ defaultFocusedValue: () => props.defaultFocusedValue?.(),
1181
+ minValue: () => props.minValue?.(),
1182
+ maxValue: () => props.maxValue?.(),
1183
+ isDateUnavailable: callback<[CalendarDate], boolean>(props.isDateUnavailable),
1184
+ isDateDisabled: callback<[CalendarDate], boolean>(props.isDateDisabled),
1185
+ isDisabled: () => props.isDisabled?.(),
1186
+ isReadOnly: () => props.isReadOnly?.(),
1187
+ autoFocus: () => props.autoFocus?.(),
1188
+ firstDayOfWeek: () => props.firstDayOfWeek?.(),
1189
+ timeZone: () => props.timeZone?.(),
1190
+ allowsNonContiguousRanges: () => props.allowsNonContiguousRanges?.(),
1191
+ onChange: (value) => props.onChange?.()?.(value),
1192
+ onFocusChange: (date) => props.onFocusChange?.()?.(date),
1193
+ });
1194
+
1195
+ return <CalendarBody state={state} of={props as unknown as Incoming<CalendarComponentProps>} />;
1196
+ }
1197
+
1198
+ export interface MultipleCalendarComponentProps extends Omit<
1199
+ CalendarComponentProps,
1200
+ "value" | "defaultValue" | "onChange"
1201
+ > {
1202
+ value?: readonly CalendarDate[];
1203
+ defaultValue?: readonly CalendarDate[];
1204
+ /** The fewest days that may be left chosen, and the most that may be. */
1205
+ min?: number;
1206
+ max?: number;
1207
+ /** The last chosen day cannot be taken away. @default false */
1208
+ required?: boolean;
1209
+ onChange?: (value: CalendarDate[]) => void;
1210
+ }
1211
+
1212
+ /**
1213
+ * Any number of days.
1214
+ *
1215
+ * Each press turns one day on or off and leaves the rest alone, and the grid
1216
+ * says it takes more than one so a screen reader does not announce a choice
1217
+ * as having replaced the last.
1218
+ */
1219
+ export function MultipleCalendar(props: Incoming<MultipleCalendarComponentProps>) {
1220
+ const state = multipleCalendarState({
1221
+ value: () => props.value?.(),
1222
+ defaultValue: () => props.defaultValue?.(),
1223
+ focusedValue: () => props.focusedValue?.(),
1224
+ defaultFocusedValue: () => props.defaultFocusedValue?.(),
1225
+ minValue: () => props.minValue?.(),
1226
+ maxValue: () => props.maxValue?.(),
1227
+ isDateUnavailable: callback<[CalendarDate], boolean>(props.isDateUnavailable),
1228
+ isDateDisabled: callback<[CalendarDate], boolean>(props.isDateDisabled),
1229
+ isDisabled: () => props.isDisabled?.(),
1230
+ isReadOnly: () => props.isReadOnly?.(),
1231
+ autoFocus: () => props.autoFocus?.(),
1232
+ firstDayOfWeek: () => props.firstDayOfWeek?.(),
1233
+ timeZone: () => props.timeZone?.(),
1234
+ min: () => props.min?.(),
1235
+ max: () => props.max?.(),
1236
+ required: () => props.required?.(),
1237
+ onChange: (value) => props.onChange?.()?.(value),
1238
+ onFocusChange: (date) => props.onFocusChange?.()?.(date),
1239
+ });
1240
+
1241
+ return <CalendarBody state={state} of={props as unknown as Incoming<CalendarComponentProps>} />;
1242
+ }
1243
+
1244
+ interface CalendarBodyProps {
1245
+ state: AnyCalendarState;
1246
+ /** The calendar's own props, still as Cells. */
1247
+ of: Incoming<CalendarComponentProps>;
1248
+ }
1249
+
1250
+ /** The heading, the two page buttons and the grid: what both calendars are. */
1251
+ function CalendarBody(incoming: Incoming<CalendarBodyProps>) {
1252
+ const state = incoming.state();
1253
+ const props = incoming.of();
1254
+ const prevRef = makeRef<HTMLButtonElement>();
1255
+ const nextRef = makeRef<HTMLButtonElement>();
1256
+
1257
+ const { calendarProps, prevButtonProps, nextButtonProps, errorMessageProps, title, baseId } =
1258
+ calendar(
1259
+ {
1260
+ "aria-label": () => props["aria-label"]?.(),
1261
+ "aria-labelledby": () => props["aria-labelledby"]?.(),
1262
+ },
1263
+ state,
1264
+ );
1265
+
1266
+ const titleId = id();
1267
+
1268
+ const { gridProps, headerProps, weekDays, weeksInMonth, weekDates } = calendarGrid(
1269
+ {
1270
+ weekdayStyle: () => props.weekdayStyle?.(),
1271
+ fixedWeeks: () => props.fixedWeeks?.(),
1272
+ "aria-labelledby": titleId,
1273
+ },
1274
+ state,
1275
+ );
1276
+
1277
+ const previous = button(prevButtonProps, prevRef);
1278
+ const next = button(nextButtonProps, nextRef);
1279
+
1280
+ const value: CalendarContextValue = { state, baseId };
1281
+
1282
+ const elementProps = mergeProps(
1283
+ calendarProps,
1284
+ filterDOMProps(fromProps(props), { global: true }),
1285
+ styleProps(props),
1286
+ {
1287
+ "data-disabled": () => props.isDisabled?.() === true,
1288
+ "data-testid": () => props["data-testid"]?.(),
1289
+ },
1290
+ );
1291
+
1292
+ return (
1293
+ <CalendarProvider value={value}>
1294
+ <div {...elementProps} ref={mergeRefs(props.ref?.())}>
1295
+ <div>
1296
+ <button {...previous.buttonProps} type="button" ref={prevRef.set}>
1297
+ <span aria-hidden="true">‹</span>
1298
+ </button>
1299
+ <h2 id={titleId}>{title}</h2>
1300
+ <button {...next.buttonProps} type="button" ref={nextRef.set}>
1301
+ <span aria-hidden="true">›</span>
1302
+ </button>
1303
+ </div>
1304
+ <div {...gridProps}>
1305
+ <div {...headerProps} role="row">
1306
+ <For each={() => weekDays()}>
1307
+ {(day: string) => (
1308
+ <div role="columnheader" aria-label={day}>
1309
+ {day}
1310
+ </div>
1311
+ )}
1312
+ </For>
1313
+ </div>
1314
+ {/* Keyed by POSITION, not by the day: `weekDates` builds seven new
1315
+ `CalendarDate` objects every read, so keying by them destroyed
1316
+ all forty-two cells whenever the month changed — with the one
1317
+ holding focus among them. */}
1318
+ <For each={() => Array.from({ length: weeksInMonth() }, (_, week) => week)}>
1319
+ {(week: number) => (
1320
+ <div role="row">
1321
+ <Repeat count={7}>
1322
+ {(at: number) => <CalendarCell date={weekDates(week)[at] as CalendarDate} />}
1323
+ </Repeat>
1324
+ </div>
1325
+ )}
1326
+ </For>
1327
+ </div>
1328
+ <span {...errorMessageProps}>{props.errorMessage}</span>
1329
+ </div>
1330
+ </CalendarProvider>
1331
+ );
1332
+ }
1333
+
1334
+ export interface CalendarCellComponentProps extends StyleProps {
1335
+ date: CalendarDate;
1336
+ ref?: RefTarget<HTMLDivElement>;
1337
+ }
1338
+
1339
+ /** One day. */
1340
+ export function CalendarCell(props: Incoming<CalendarCellComponentProps>) {
1341
+ const domRef = makeRef<HTMLDivElement>();
1342
+ const { state } = useCalendar();
1343
+
1344
+ const {
1345
+ cellProps,
1346
+ buttonProps,
1347
+ isSelected,
1348
+ isFocused,
1349
+ isDisabled,
1350
+ isUnavailable,
1351
+ isOutsideVisibleRange,
1352
+ isToday: isTodayCell,
1353
+ isSelectionStart,
1354
+ isSelectionEnd,
1355
+ formattedDate,
1356
+ } = calendarCell({ date: () => props.date(), ref: domRef }, state);
1357
+
1358
+ const { hoverProps, isHovered } = hover({ isDisabled });
1359
+ const { focusProps, isFocusVisible } = focusRing();
1360
+
1361
+ const elementProps = mergeProps(
1362
+ buttonProps,
1363
+ hoverProps,
1364
+ focusProps,
1365
+ filterDOMProps(fromProps(props), { global: true }),
1366
+ styleProps(props),
1367
+ {
1368
+ "data-selected": isSelected,
1369
+ "data-focused": isFocused,
1370
+ "data-focus-visible": isFocusVisible,
1371
+ "data-hovered": isHovered,
1372
+ "data-disabled": isDisabled,
1373
+ "data-unavailable": isUnavailable,
1374
+ "data-outside-month": isOutsideVisibleRange,
1375
+ "data-today": isTodayCell,
1376
+ "data-selection-start": isSelectionStart,
1377
+ "data-selection-end": isSelectionEnd,
1378
+ "data-testid": () => props["data-testid"]?.(),
1379
+ },
1380
+ );
1381
+
1382
+ return (
1383
+ <div {...cellProps}>
1384
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
1385
+ {formattedDate}
1386
+ </div>
1387
+ </div>
1388
+ );
1389
+ }