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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +304 -2
  3. package/package.json +437 -4
  4. package/src/autocomplete.tsx +581 -0
  5. package/src/breadcrumbs.tsx +297 -0
  6. package/src/button.tsx +468 -0
  7. package/src/calendar.tsx +2316 -0
  8. package/src/checkbox.tsx +732 -0
  9. package/src/collections.ts +1059 -0
  10. package/src/color.ts +2119 -0
  11. package/src/colorpicker.tsx +2023 -0
  12. package/src/colorswatchpicker.tsx +240 -0
  13. package/src/combobox.tsx +3003 -0
  14. package/src/command.tsx +1203 -0
  15. package/src/date.ts +674 -0
  16. package/src/datefield.tsx +2066 -0
  17. package/src/datepicker.tsx +907 -0
  18. package/src/dialog.tsx +1077 -0
  19. package/src/disclosure.tsx +711 -0
  20. package/src/dnd/clipboard.ts +125 -0
  21. package/src/dnd/collection.ts +1265 -0
  22. package/src/dnd/data.ts +409 -0
  23. package/src/dnd/drag-drop.ts +801 -0
  24. package/src/dnd/index.ts +133 -0
  25. package/src/dnd/manager.ts +639 -0
  26. package/src/dnd/strings.ts +1279 -0
  27. package/src/dnd/targets.ts +726 -0
  28. package/src/dnd/types.ts +212 -0
  29. package/src/dom.ts +703 -0
  30. package/src/drag-and-drop.tsx +669 -0
  31. package/src/drawer.ts +674 -0
  32. package/src/dropzone.tsx +208 -0
  33. package/src/file-trigger.tsx +103 -0
  34. package/src/focus.ts +1370 -0
  35. package/src/form.tsx +94 -0
  36. package/src/gridlist.tsx +1354 -0
  37. package/src/group.tsx +146 -0
  38. package/src/i18n.ts +823 -0
  39. package/src/index.ts +1672 -0
  40. package/src/interactions/description.ts +73 -0
  41. package/src/interactions/flags.ts +35 -0
  42. package/src/interactions/focus-events.ts +226 -0
  43. package/src/interactions/focusable.ts +86 -0
  44. package/src/interactions/hover.ts +213 -0
  45. package/src/interactions/interact-outside.ts +123 -0
  46. package/src/interactions/keyboard.ts +298 -0
  47. package/src/interactions/listeners.ts +78 -0
  48. package/src/interactions/long-press.ts +160 -0
  49. package/src/interactions/modality.ts +428 -0
  50. package/src/interactions/move.ts +257 -0
  51. package/src/interactions/open-link.ts +226 -0
  52. package/src/interactions/press.ts +915 -0
  53. package/src/interactions/prevent-focus.ts +102 -0
  54. package/src/interactions/scroll-wheel.ts +43 -0
  55. package/src/interactions/text-selection.ts +77 -0
  56. package/src/interactions.ts +81 -0
  57. package/src/label.ts +140 -0
  58. package/src/link.tsx +477 -0
  59. package/src/listbox.tsx +1247 -0
  60. package/src/live.ts +208 -0
  61. package/src/menu.tsx +2383 -0
  62. package/src/menubar.tsx +579 -0
  63. package/src/navigation-tree.tsx +357 -0
  64. package/src/navigation.ts +735 -0
  65. package/src/numberfield.tsx +942 -0
  66. package/src/otp.ts +430 -0
  67. package/src/overlay-arrow.tsx +157 -0
  68. package/src/overlays.ts +1549 -0
  69. package/src/platform.ts +75 -0
  70. package/src/presence.ts +164 -0
  71. package/src/preview-trigger.tsx +582 -0
  72. package/src/progress-bar-context.ts +15 -0
  73. package/src/questionnaire.tsx +1717 -0
  74. package/src/radio.tsx +641 -0
  75. package/src/register-dom.ts +12 -0
  76. package/src/scroller.ts +1165 -0
  77. package/src/select.tsx +1745 -0
  78. package/src/selection-indicator.tsx +74 -0
  79. package/src/selection.ts +1472 -0
  80. package/src/shared-element-transition.tsx +316 -0
  81. package/src/sheet.tsx +1461 -0
  82. package/src/slider.tsx +1137 -0
  83. package/src/splitter.ts +1152 -0
  84. package/src/static-collection.ts +211 -0
  85. package/src/switch.tsx +212 -0
  86. package/src/table.tsx +2218 -0
  87. package/src/tabs.tsx +1127 -0
  88. package/src/tag.tsx +637 -0
  89. package/src/textarea.tsx +186 -0
  90. package/src/textfield.tsx +483 -0
  91. package/src/toast-components.tsx +589 -0
  92. package/src/toast.ts +658 -0
  93. package/src/toggle-button-group.tsx +175 -0
  94. package/src/toggle-input.tsx +86 -0
  95. package/src/toggle.ts +384 -0
  96. package/src/togglegroup.ts +365 -0
  97. package/src/tokenfield.tsx +1673 -0
  98. package/src/toolbar.tsx +184 -0
  99. package/src/tooltip.tsx +674 -0
  100. package/src/tree.tsx +2075 -0
  101. package/src/utils.ts +787 -0
  102. package/src/validation.ts +504 -0
  103. package/src/virtualizer.tsx +837 -0
@@ -0,0 +1,2316 @@
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
+ cells,
33
+ type Accessor,
34
+ type Child,
35
+ For,
36
+ createMemo,
37
+ createContext,
38
+ createEffect,
39
+ getContext,
40
+ type Incoming,
41
+ provide,
42
+ Repeat,
43
+ createSignal,
44
+ onSettled,
45
+ untrack,
46
+ } from "@barqjs/core";
47
+ import { isServer } from "@barqjs/web";
48
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
49
+ import { button } from "./button.tsx";
50
+ import {
51
+ CalendarDate,
52
+ constrainDate,
53
+ endOfMonth,
54
+ endOfWeek,
55
+ getDayOfWeek,
56
+ getFirstDayOfWeek,
57
+ getISOWeek,
58
+ getMinimalDaysInFirstWeek,
59
+ getWeekOfYear,
60
+ getWeeksInMonth,
61
+ isSameDay,
62
+ isSameMonth,
63
+ startOfMonth,
64
+ startOfWeek,
65
+ today,
66
+ type DateValue,
67
+ } from "./date.ts";
68
+ import { activeElement, contains, ownerDocument } from "./dom.ts";
69
+ import { focusRing } from "./focus.ts";
70
+ import {
71
+ dateFormatter,
72
+ listFormatter,
73
+ type LocalizedString,
74
+ StringDictionary,
75
+ stringFormatter,
76
+ useLocale,
77
+ } from "./i18n.ts";
78
+ import { focusSafely } from "./interactions/focusable.ts";
79
+ import { hover } from "./interactions/hover.ts";
80
+ import type { ElementRef } from "./interactions/press.ts";
81
+ import { announce } from "./live.ts";
82
+ import {
83
+ access,
84
+ callback,
85
+ controllable,
86
+ type DOMProps,
87
+ filterDOMProps,
88
+ fromProps,
89
+ id,
90
+ type MaybeAccessor,
91
+ mergeProps,
92
+ type StyleProps,
93
+ styleProps,
94
+ } from "./utils.ts";
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // State
98
+ // ---------------------------------------------------------------------------
99
+
100
+ export interface DateRange {
101
+ start: CalendarDate;
102
+ end: CalendarDate;
103
+ }
104
+
105
+ /**
106
+ * What a day is tested against to decide whether it is switched off, booked or
107
+ * otherwise marked.
108
+ *
109
+ * - a day, or a list of days;
110
+ * - a range, both ends included, as `{ from, to }` or `{ start, end }`;
111
+ * - `{ before }` and `{ after }`, neither including the day they name; given
112
+ * together they are the days strictly between, or the days outside when
113
+ * `after` is the later of the two;
114
+ * - `{ dayOfWeek }`, Sunday as 0;
115
+ * - a function, a plain yes or no, or a list of any of these.
116
+ */
117
+ export type DateMatcher =
118
+ | boolean
119
+ | CalendarDate
120
+ | ((date: CalendarDate) => boolean)
121
+ | DateRange
122
+ | { from: CalendarDate | null | undefined; to?: CalendarDate | null }
123
+ | { before: CalendarDate; after?: CalendarDate }
124
+ | { after: CalendarDate; before?: CalendarDate }
125
+ | { dayOfWeek: number | readonly number[] }
126
+ | readonly DateMatcher[];
127
+
128
+ export function dateMatches(date: CalendarDate, matcher: DateMatcher | undefined): boolean {
129
+ if (matcher === undefined) return false;
130
+ if (typeof matcher === "boolean") return matcher;
131
+ if (typeof matcher === "function") return matcher(date);
132
+ if (matcher instanceof CalendarDate) return isSameDay(date, matcher);
133
+ if (Array.isArray(matcher)) return matcher.some((one: DateMatcher) => dateMatches(date, one));
134
+
135
+ if ("dayOfWeek" in matcher) {
136
+ const days = typeof matcher.dayOfWeek === "number" ? [matcher.dayOfWeek] : matcher.dayOfWeek;
137
+ return days.includes(getDayOfWeek(date));
138
+ }
139
+ if ("start" in matcher) {
140
+ return date.compare(matcher.start) >= 0 && date.compare(matcher.end) <= 0;
141
+ }
142
+ if ("from" in matcher) {
143
+ const from = matcher.from;
144
+ if (from === null || from === undefined) return false;
145
+ const to = matcher.to ?? from;
146
+ return date.compare(from) >= 0 && date.compare(to) <= 0;
147
+ }
148
+
149
+ const { before, after } = matcher as { before?: CalendarDate; after?: CalendarDate };
150
+ if (before !== undefined && after !== undefined) {
151
+ return after.compare(before) < 0
152
+ ? date.compare(after) > 0 && date.compare(before) < 0
153
+ : date.compare(before) < 0 || date.compare(after) > 0;
154
+ }
155
+ if (before !== undefined) return date.compare(before) < 0;
156
+ return after !== undefined && date.compare(after) > 0;
157
+ }
158
+
159
+ export interface CalendarStateOptions {
160
+ value?: MaybeAccessor<CalendarDate | null | undefined>;
161
+ defaultValue?: MaybeAccessor<CalendarDate | null | undefined>;
162
+ focusedValue?: MaybeAccessor<CalendarDate | undefined>;
163
+ defaultFocusedValue?: MaybeAccessor<CalendarDate | undefined>;
164
+ minValue?: MaybeAccessor<DateValue | null | undefined>;
165
+ maxValue?: MaybeAccessor<DateValue | null | undefined>;
166
+ /** Days that exist but cannot be chosen: booked, closed, sold out. */
167
+ isDateUnavailable?: (date: CalendarDate) => boolean;
168
+ /**
169
+ * Days that are switched off, beyond the two bounds.
170
+ *
171
+ * Unlike an unavailable day these are not information: they cannot be
172
+ * chosen, and the arrow keys step over them.
173
+ */
174
+ isDateDisabled?: (date: CalendarDate) => boolean;
175
+ isDisabled?: MaybeAccessor<boolean | undefined>;
176
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
177
+ autoFocus?: MaybeAccessor<boolean | undefined>;
178
+ /** Pressing the chosen day again clears it. @default false */
179
+ allowsDeselection?: MaybeAccessor<boolean | undefined>;
180
+ /** Which day starts the week. Defaults to what the locale says. */
181
+ firstDayOfWeek?: MaybeAccessor<number | undefined>;
182
+ /** How many months are on show side by side. @default 1 */
183
+ visibleMonths?: MaybeAccessor<number | undefined>;
184
+ /** Turn every month on show at once, rather than sliding by one. @default false */
185
+ pagedNavigation?: MaybeAccessor<boolean | undefined>;
186
+ /**
187
+ * The first month on show, when its owner keeps it.
188
+ *
189
+ * Then the focused day follows the month instead of the month following the
190
+ * focused day, and a move that would turn the page only asks for it through
191
+ * `onVisibleMonthChange`.
192
+ */
193
+ visibleMonth?: MaybeAccessor<DateValue | null | undefined>;
194
+ onVisibleMonthChange?: (month: CalendarDate) => void;
195
+ /** The first and last month that can be paged to. Their days stay open. */
196
+ startMonth?: MaybeAccessor<DateValue | null | undefined>;
197
+ endMonth?: MaybeAccessor<DateValue | null | undefined>;
198
+ /** Which day counts as today. Defaults to today in `timeZone`. */
199
+ today?: MaybeAccessor<CalendarDate | undefined>;
200
+ /** The IANA zone today is reckoned in. Defaults to the local one. */
201
+ timeZone?: MaybeAccessor<string | undefined>;
202
+ /** Said by the caller, whatever the value is. */
203
+ isInvalid?: MaybeAccessor<boolean | undefined>;
204
+ /**
205
+ * Where the chosen day, or today, sits among several months when the
206
+ * calendar first shows. @default "center"
207
+ */
208
+ selectionAlignment?: MaybeAccessor<"start" | "center" | "end" | undefined>;
209
+ /** Every month drawn with this many week rows, however many it needs. */
210
+ weeksInMonth?: MaybeAccessor<number | undefined>;
211
+ onChange?: (value: CalendarDate | null) => void;
212
+ onFocusChange?: (date: CalendarDate) => void;
213
+ }
214
+
215
+ export interface CalendarState {
216
+ readonly selectionMode: "single";
217
+ value: Accessor<CalendarDate | null>;
218
+ setValue(value: CalendarDate | null): void;
219
+ focusedDate: Accessor<CalendarDate>;
220
+ setFocusedDate(date: CalendarDate): void;
221
+ /** The months on show, as the first day of the first and the last of the last. */
222
+ visibleRange: Accessor<DateRange>;
223
+ visibleMonths: Accessor<number>;
224
+ today: Accessor<CalendarDate>;
225
+ /** Put a month on show, `position` months in from the first one. */
226
+ showMonth(month: DateValue, position?: number): void;
227
+ isFocused: Accessor<boolean>;
228
+ setFocused(isFocused: boolean): void;
229
+ firstDayOfWeek: Accessor<number>;
230
+ isDisabled: Accessor<boolean>;
231
+ isReadOnly: Accessor<boolean>;
232
+ /**
233
+ * The value is one the calendar would not offer, or the caller said it is
234
+ * wrong: the chosen days say so, and point at the error message.
235
+ */
236
+ isValueInvalid: Accessor<boolean>;
237
+ /** The week rows every month is drawn with, when the caller fixed them. */
238
+ weeksInMonth: Accessor<number | undefined>;
239
+ isSelected(date: CalendarDate): boolean;
240
+ isCellFocused(date: CalendarDate): boolean;
241
+ isCellDisabled(date: CalendarDate): boolean;
242
+ isCellUnavailable(date: CalendarDate): boolean;
243
+ isPreviousVisibleRangeInvalid(): boolean;
244
+ isNextVisibleRangeInvalid(): boolean;
245
+ focusPreviousDay(): void;
246
+ focusNextDay(): void;
247
+ focusPreviousRow(): void;
248
+ focusNextRow(): void;
249
+ focusPreviousSection(larger?: boolean): void;
250
+ focusNextSection(larger?: boolean): void;
251
+ focusSectionStart(): void;
252
+ focusSectionEnd(): void;
253
+ selectDate(date: CalendarDate): void;
254
+ selectFocusedDate(): void;
255
+ /** Show the month before or after the one on show. */
256
+ focusPreviousPage(): void;
257
+ focusNextPage(): void;
258
+ }
259
+
260
+ type Duration = Parameters<CalendarDate["add"]>[0];
261
+
262
+ /** A month a page button or a caption asked for. Compared by identity. */
263
+ interface PageRequest {
264
+ start: CalendarDate;
265
+ }
266
+
267
+ function unavailable(options: CalendarStateOptions, date: CalendarDate): boolean {
268
+ return options.isDateUnavailable?.(date) === true;
269
+ }
270
+
271
+ export function calendarState(options: CalendarStateOptions): CalendarState {
272
+ const locale = useLocale();
273
+
274
+ const [value, setValueRaw] = controllable<CalendarDate | null>(
275
+ () => access(options.value),
276
+ () => access(options.defaultValue) ?? null,
277
+ options.onChange,
278
+ );
279
+
280
+ const firstDayOfWeek = (): number =>
281
+ access(options.firstDayOfWeek) ?? getFirstDayOfWeek(locale().locale);
282
+
283
+ const todayDate = (): CalendarDate => access(options.today) ?? today(access(options.timeZone));
284
+ const visibleMonths = (): number => Math.max(1, Math.floor(access(options.visibleMonths) ?? 1));
285
+
286
+ const constrained = (date: CalendarDate): CalendarDate =>
287
+ constrainDate(date, access(options.minValue), access(options.maxValue));
288
+
289
+ const [rawFocusedDate, setFocusedDateRaw] = controllable<CalendarDate>(
290
+ () => access(options.focusedValue),
291
+ () => constrained(access(options.defaultFocusedValue) ?? value() ?? todayDate()),
292
+ options.onFocusChange,
293
+ );
294
+
295
+ const [isFocused, setIsFocused] = createSignal(access(options.autoFocus) === true);
296
+
297
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
298
+ const isReadOnly = (): boolean => access(options.isReadOnly) === true;
299
+
300
+ const [requested, setRequested] = createSignal<PageRequest | null>(null);
301
+
302
+ /** A first month kept inside the months that can be reached. */
303
+ const bounded = (start: CalendarDate): CalendarDate => {
304
+ const first = access(options.startMonth);
305
+ const last = access(options.endMonth);
306
+ let next = start;
307
+ if (last !== undefined && last !== null) {
308
+ const latest = startOfMonth(last).subtract({ months: visibleMonths() - 1 });
309
+ if (next.compare(latest) > 0) next = latest;
310
+ }
311
+ if (first !== undefined && first !== null) {
312
+ const earliest = startOfMonth(first);
313
+ if (next.compare(earliest) < 0) next = earliest;
314
+ }
315
+ return next;
316
+ };
317
+
318
+ /** A first month moved just far enough for the window to hold a day. */
319
+ const holding = (start: CalendarDate, date: CalendarDate): CalendarDate => {
320
+ const month = startOfMonth(date);
321
+ if (month.compare(start) < 0) return month;
322
+ const last = start.add({ months: visibleMonths() - 1 });
323
+ return month.compare(last) > 0 ? month.subtract({ months: visibleMonths() - 1 }) : start;
324
+ };
325
+
326
+ /**
327
+ * The first month on show when the calendar is built, placed so the focused
328
+ * day sits where `selectionAlignment` asks and no month beyond the bounds is
329
+ * shown to make room for it.
330
+ */
331
+ const aligned = (focused: CalendarDate): CalendarDate => {
332
+ const count = visibleMonths();
333
+ const month = startOfMonth(focused);
334
+ let before: number;
335
+ switch (access(options.selectionAlignment) ?? "center") {
336
+ case "start":
337
+ before = 0;
338
+ break;
339
+ case "end":
340
+ before = count - 1;
341
+ break;
342
+ default: {
343
+ const half = Math.floor(count / 2);
344
+ before = half > 0 && count % 2 === 0 ? half - 1 : half;
345
+ }
346
+ }
347
+ let start = month.subtract({ months: before });
348
+ const max = access(options.maxValue);
349
+ if (max !== undefined && max !== null && focused.compare(max) <= 0) {
350
+ const latest = startOfMonth(max).subtract({ months: count - 1 });
351
+ if (start.compare(latest) > 0) start = latest;
352
+ }
353
+ const min = access(options.minValue);
354
+ if (min !== undefined && min !== null && focused.compare(min) >= 0) {
355
+ const earliest = startOfMonth(min);
356
+ if (start.compare(earliest) < 0) start = earliest;
357
+ }
358
+ return start;
359
+ };
360
+
361
+ // Where the window begins. It stays where it was until the focused day leaves
362
+ // it or a page is asked for, which is what lets focus cross from one visible
363
+ // month into the next without the months changing places under it.
364
+ const firstMonth = createMemo<{ start: CalendarDate; request: PageRequest | null }>(
365
+ (previous) => {
366
+ const request = requested();
367
+ const kept = access(options.visibleMonth);
368
+ if (kept !== undefined && kept !== null) return { start: startOfMonth(kept), request };
369
+
370
+ const focused = rawFocusedDate();
371
+ let from = aligned(focused);
372
+ if (previous !== undefined) {
373
+ from = request !== null && request !== previous.request ? request.start : previous.start;
374
+ }
375
+ return { start: bounded(holding(from, focused)), request };
376
+ },
377
+ );
378
+
379
+ // The month on show, and it changes when the MONTH does.
380
+ //
381
+ // Written as a plain function reading `focusedDate()`, every consumer of it
382
+ // depended on the focused DAY: an arrow key re-ran `weekDates`, which hands
383
+ // `<For>` seven new `CalendarDate` objects a row, so all forty-two cells were
384
+ // destroyed and built again — and the one holding focus went with them. A
385
+ // real browser then leaves focus on `<body>`, which happy-dom does not, so no
386
+ // test saw it.
387
+ const visibleRange = createMemo<DateRange>(
388
+ () => {
389
+ const start = firstMonth().start;
390
+ return { start, end: endOfMonth(start.add({ months: visibleMonths() - 1 })) };
391
+ },
392
+ { equals: (a, b) => isSameDay(a.start, b.start) && isSameDay(a.end, b.end) },
393
+ );
394
+
395
+ // Held to the months on show. The two only part when the window is kept by
396
+ // its owner or stopped at a bound, and a focused day nobody can see is a
397
+ // grid with no Tab stop.
398
+ const focusedDate = (): CalendarDate => {
399
+ const raw = rawFocusedDate();
400
+ const range = visibleRange();
401
+ if (raw.compare(range.start) < 0) return range.start;
402
+ return raw.compare(range.end) > 0 ? range.end : raw;
403
+ };
404
+
405
+ const isCellDisabled = (date: CalendarDate): boolean => {
406
+ if (isDisabled()) return true;
407
+ const min = access(options.minValue);
408
+ const max = access(options.maxValue);
409
+ if (min !== undefined && min !== null && date.compare(min) < 0) return true;
410
+ if (max !== undefined && max !== null && date.compare(max) > 0) return true;
411
+ return options.isDateDisabled?.(date) === true;
412
+ };
413
+
414
+ const isCellUnavailable = (date: CalendarDate): boolean => unavailable(options, date);
415
+
416
+ /** Focus, held inside the allowed range rather than refused at its edge. */
417
+ const setFocusedDate = (date: CalendarDate): void => {
418
+ const next = constrained(date);
419
+ const current = untrack(visibleRange).start;
420
+ const start = bounded(holding(current, next));
421
+ setFocusedDateRaw(next);
422
+ if (!isSameDay(start, current)) options.onVisibleMonthChange?.(start);
423
+ };
424
+
425
+ /** The window moved to begin at a month, and the focused day carried with it. */
426
+ const showFrom = (month: CalendarDate): void => {
427
+ const current = untrack(visibleRange).start;
428
+ const start = bounded(month);
429
+ if (isSameDay(start, current)) return;
430
+ const months = (start.year - current.year) * 12 + start.month - current.month;
431
+ setRequested({ start });
432
+ setFocusedDateRaw(constrained(untrack(focusedDate).add({ months })));
433
+ options.onVisibleMonthChange?.(start);
434
+ };
435
+
436
+ const page = (direction: 1 | -1): void => {
437
+ const months = access(options.pagedNavigation) === true ? visibleMonths() : 1;
438
+ showFrom(untrack(visibleRange).start.add({ months: months * direction }));
439
+ };
440
+
441
+ /**
442
+ * `date`, or the nearest day further that way that is not switched off.
443
+ *
444
+ * Null when there is none within a year, or the bounds are reached first:
445
+ * the focus then stays where it is rather than resting on a day that cannot
446
+ * be chosen.
447
+ */
448
+ const reachable = (date: CalendarDate, step: Duration): CalendarDate | null => {
449
+ const off = options.isDateDisabled;
450
+ let next = constrained(date);
451
+ if (off === undefined) return next;
452
+ for (let tries = 0; off(next); tries++) {
453
+ const further = constrained(next.add(step));
454
+ if (tries === 366 || isSameDay(further, next)) return null;
455
+ next = further;
456
+ }
457
+ return next;
458
+ };
459
+
460
+ const land = (date: CalendarDate, step: Duration): void => {
461
+ const next = reachable(date, step);
462
+ if (next !== null) setFocusedDate(next);
463
+ };
464
+
465
+ const move = (duration: Duration): void => land(focusedDate().add(duration), duration);
466
+
467
+ /** A day the calendar would not let anyone choose, for whatever reason. */
468
+ const isRefused = (date: CalendarDate): boolean => {
469
+ const min = access(options.minValue);
470
+ const max = access(options.maxValue);
471
+ if (min !== undefined && min !== null && date.compare(min) < 0) return true;
472
+ if (max !== undefined && max !== null && date.compare(max) > 0) return true;
473
+ return isCellUnavailable(date) || options.isDateDisabled?.(date) === true;
474
+ };
475
+
476
+ const selectDate = (date: CalendarDate): void => {
477
+ if (isReadOnly() || isDisabled()) return;
478
+ if (isCellDisabled(date) || isCellUnavailable(date)) return;
479
+ const chosen = untrack(value);
480
+ if (access(options.allowsDeselection) === true && chosen !== null && isSameDay(chosen, date)) {
481
+ setValueRaw(null);
482
+ return;
483
+ }
484
+ setValueRaw(date);
485
+ };
486
+
487
+ return {
488
+ selectionMode: "single",
489
+ value,
490
+ setValue: (next) => setValueRaw(next),
491
+ focusedDate,
492
+ setFocusedDate,
493
+ visibleRange,
494
+ visibleMonths,
495
+ today: todayDate,
496
+ showMonth: (month, position = 0) =>
497
+ showFrom(startOfMonth(month).subtract({ months: position })),
498
+ isFocused,
499
+ setFocused: (next) => setIsFocused(next),
500
+ firstDayOfWeek,
501
+ isDisabled,
502
+ isReadOnly,
503
+ isValueInvalid: () => {
504
+ if (access(options.isInvalid) === true) return true;
505
+ const selected = value();
506
+ return selected !== null && isRefused(selected);
507
+ },
508
+ weeksInMonth: () => access(options.weeksInMonth),
509
+ isSelected: (date) => {
510
+ const selected = value();
511
+ return selected !== null && isSameDay(selected, date);
512
+ },
513
+ isCellFocused: (date) => isFocused() && isSameDay(focusedDate(), date),
514
+ isCellDisabled,
515
+ isCellUnavailable,
516
+ isPreviousVisibleRangeInvalid: () => {
517
+ const first = access(options.startMonth);
518
+ if (first !== undefined && first !== null) {
519
+ if (visibleRange().start.compare(startOfMonth(first)) <= 0) return true;
520
+ }
521
+ const min = access(options.minValue);
522
+ if (min === undefined || min === null) return false;
523
+ return visibleRange().start.subtract({ days: 1 }).compare(min) < 0;
524
+ },
525
+ isNextVisibleRangeInvalid: () => {
526
+ const last = access(options.endMonth);
527
+ if (last !== undefined && last !== null) {
528
+ if (visibleRange().end.compare(endOfMonth(last)) >= 0) return true;
529
+ }
530
+ const max = access(options.maxValue);
531
+ if (max === undefined || max === null) return false;
532
+ return visibleRange().end.add({ days: 1 }).compare(max) > 0;
533
+ },
534
+ focusPreviousDay: () => move({ days: -1 }),
535
+ focusNextDay: () => move({ days: 1 }),
536
+ focusPreviousRow: () => move({ weeks: -1 }),
537
+ focusNextRow: () => move({ weeks: 1 }),
538
+ focusPreviousSection: (larger) => move(larger === true ? { years: -1 } : { months: -1 }),
539
+ focusNextSection: (larger) => move(larger === true ? { years: 1 } : { months: 1 }),
540
+ focusSectionStart: () => land(startOfWeek(focusedDate(), firstDayOfWeek()), { days: 1 }),
541
+ focusSectionEnd: () => land(endOfWeek(focusedDate(), firstDayOfWeek()), { days: -1 }),
542
+ selectDate,
543
+ selectFocusedDate: () => selectDate(focusedDate()),
544
+ focusPreviousPage: () => page(-1),
545
+ focusNextPage: () => page(1),
546
+ };
547
+ }
548
+
549
+ // ---------------------------------------------------------------------------
550
+ // A range of days
551
+ // ---------------------------------------------------------------------------
552
+
553
+ export interface RangeCalendarStateOptions extends Omit<
554
+ CalendarStateOptions,
555
+ "value" | "defaultValue" | "onChange" | "isDateUnavailable"
556
+ > {
557
+ value?: MaybeAccessor<DateRange | null | undefined>;
558
+ /**
559
+ * Days that exist but cannot be chosen. The second argument is the day the
560
+ * range being drawn began on, or null, so what is available can depend on
561
+ * it: a stay of at most a week from wherever it starts.
562
+ */
563
+ isDateUnavailable?: (date: CalendarDate, anchorDate: CalendarDate | null) => boolean;
564
+ defaultValue?: MaybeAccessor<DateRange | null | undefined>;
565
+ /** Nothing between the ends may be unavailable. @default false */
566
+ allowsNonContiguousRanges?: MaybeAccessor<boolean | undefined>;
567
+ /** The fewest and the most days a range may cover, both ends counted. */
568
+ minDays?: MaybeAccessor<number | undefined>;
569
+ maxDays?: MaybeAccessor<number | undefined>;
570
+ /** A switched-off day between the ends breaks the range. @default false */
571
+ excludeDisabled?: MaybeAccessor<boolean | undefined>;
572
+ onChange?: (value: DateRange | null) => void;
573
+ }
574
+
575
+ export interface RangeCalendarState extends Omit<
576
+ CalendarState,
577
+ "value" | "setValue" | "selectionMode"
578
+ > {
579
+ readonly selectionMode: "range";
580
+ value: Accessor<DateRange | null>;
581
+ setValue(value: DateRange | null): void;
582
+ /** Where a range being drawn began, or null when none is. */
583
+ anchorDate: Accessor<CalendarDate | null>;
584
+ setAnchorDate(date: CalendarDate | null): void;
585
+ /** What the range currently covers: the value, or the drag in progress. */
586
+ highlightedRange: Accessor<DateRange | null>;
587
+ highlightDate(date: CalendarDate): void;
588
+ /** A pointer is down and drawing the range. */
589
+ isDragging: Accessor<boolean>;
590
+ setDragging(isDragging: boolean): void;
591
+ /** Finish the range being drawn at the day it reaches now. */
592
+ commitSelection(): void;
593
+ /** Abandon the range being drawn and the value with it. */
594
+ clearSelection(): void;
595
+ }
596
+
597
+ function ordered(a: CalendarDate, b: CalendarDate): DateRange {
598
+ // A range drawn backwards is still a range: the anchor is where the user
599
+ // started, not necessarily the earlier day.
600
+ return a.compare(b) <= 0 ? { start: a, end: b } : { start: b, end: a };
601
+ }
602
+
603
+ export function rangeCalendarState(options: RangeCalendarStateOptions): RangeCalendarState {
604
+ const [value, setValueRaw] = controllable<DateRange | null>(
605
+ () => access(options.value),
606
+ () => access(options.defaultValue) ?? null,
607
+ options.onChange,
608
+ );
609
+
610
+ const [anchorDate, writeAnchorSignal] = createSignal<CalendarDate | null>(null);
611
+ const [drawn, setDrawn] = createSignal<DateRange | null>(null);
612
+ const [isDragging, setDragging] = createSignal(false);
613
+
614
+ // The anchor and the day the drawing reached, as plain variables too: a
615
+ // pointer's down and up can arrive before a signal write is published, and
616
+ // the up has to see what the down did.
617
+ let anchorNow: CalendarDate | null = null;
618
+ let reached: CalendarDate | null = null;
619
+
620
+ const writeAnchorDate = (date: CalendarDate | null): void => {
621
+ anchorNow = date;
622
+ reached = date;
623
+ writeAnchorSignal(date);
624
+ };
625
+
626
+ const ask = options.isDateUnavailable;
627
+ const visibleMonths = (): number => Math.max(1, Math.floor(access(options.visibleMonths) ?? 1));
628
+
629
+ // Centred on the range's start, unless its end would then be off the
630
+ // window, in which case the start goes first.
631
+ const alignment = (): "start" | "center" | "end" => {
632
+ const given = access(options.selectionAlignment);
633
+ if (given !== undefined) return given;
634
+ const range = untrack(value);
635
+ if (range === null) return "center";
636
+ const count = visibleMonths();
637
+ const half = Math.floor(count / 2);
638
+ const before = half > 0 && count % 2 === 0 ? half - 1 : half;
639
+ const last = endOfMonth(startOfMonth(range.start).add({ months: count - 1 - before }));
640
+ return range.end.compare(last) > 0 ? "start" : "center";
641
+ };
642
+
643
+ const base = calendarState({
644
+ ...(options as Omit<CalendarStateOptions, "isDateUnavailable">),
645
+ value: () => value()?.start ?? null,
646
+ defaultValue: undefined,
647
+ onChange: undefined,
648
+ selectionAlignment: alignment,
649
+ isDateUnavailable: ask === undefined ? undefined : (date) => ask(date, anchorDate()),
650
+ onFocusChange: (date) => {
651
+ // While a range is being drawn, moving focus IS drawing it, whichever
652
+ // way the focus moved: a press, an arrow key or a page button.
653
+ if (anchorNow !== null) highlightDate(date);
654
+ options.onFocusChange?.(date);
655
+ },
656
+ });
657
+
658
+ const highlightedRange = (): DateRange | null => {
659
+ const anchor = anchorDate();
660
+ if (anchor === null) return value();
661
+ return drawn();
662
+ };
663
+
664
+ /** Whether every day between two ends can be chosen. */
665
+ const contiguous = (range: DateRange): boolean => {
666
+ const gaps = access(options.allowsNonContiguousRanges) === true;
667
+ const holes = access(options.excludeDisabled) !== true;
668
+ if (gaps && holes) return true;
669
+ for (let day = range.start; day.compare(range.end) <= 0; day = day.add({ days: 1 })) {
670
+ if (!gaps && base.isCellUnavailable(day)) return false;
671
+ if (!holes && base.isCellDisabled(day)) return false;
672
+ }
673
+ return true;
674
+ };
675
+
676
+ const allowedLength = (range: DateRange): boolean => {
677
+ const days = range.end.epochDay - range.start.epochDay + 1;
678
+ const min = access(options.minDays);
679
+ const max = access(options.maxDays);
680
+ return (min === undefined || days >= min) && (max === undefined || days <= max);
681
+ };
682
+
683
+ const highlightDate = (date: CalendarDate): void => {
684
+ const anchor = anchorNow;
685
+ if (anchor === null) return;
686
+ reached = date;
687
+ setDrawn(ordered(anchor, date));
688
+ };
689
+
690
+ const selectDate = (date: CalendarDate): void => {
691
+ if (base.isReadOnly() || base.isDisabled()) return;
692
+ if (base.isCellDisabled(date) || base.isCellUnavailable(date)) return;
693
+
694
+ const anchor = anchorNow;
695
+ if (anchor === null) {
696
+ writeAnchorDate(date);
697
+ setDrawn({ start: date, end: date });
698
+ return;
699
+ }
700
+
701
+ const range = ordered(anchor, date);
702
+ writeAnchorDate(null);
703
+ setDrawn(null);
704
+ // A range with something unavailable inside it is not a range the user can
705
+ // have; the second press starts a new one rather than silently failing.
706
+ if (!contiguous(range) || !allowedLength(range)) {
707
+ writeAnchorDate(date);
708
+ setDrawn({ start: date, end: date });
709
+ return;
710
+ }
711
+ setValueRaw(range);
712
+ };
713
+
714
+ const isAvailable = (date: CalendarDate): boolean => {
715
+ const min = access(options.minValue);
716
+ const max = access(options.maxValue);
717
+ if (min !== undefined && min !== null && date.compare(min) < 0) return false;
718
+ if (max !== undefined && max !== null && date.compare(max) > 0) return false;
719
+ return !base.isCellUnavailable(date) && options.isDateDisabled?.(date) !== true;
720
+ };
721
+
722
+ return {
723
+ ...base,
724
+ selectionMode: "range",
725
+ value,
726
+ setValue: (next) => setValueRaw(next),
727
+ // The signal is read so a reader is told when it changes; the variable is
728
+ // returned so a handler sees what the event before it in the same tick did.
729
+ anchorDate: () => {
730
+ anchorDate();
731
+ return anchorNow;
732
+ },
733
+ setAnchorDate: (date) => {
734
+ writeAnchorDate(date);
735
+ setDrawn(date === null ? null : { start: date, end: date });
736
+ },
737
+ highlightedRange,
738
+ highlightDate,
739
+ isDragging,
740
+ setDragging: (next) => setDragging(next),
741
+ commitSelection: () => {
742
+ if (anchorNow === null) return;
743
+ selectDate(reached ?? base.focusedDate());
744
+ },
745
+ clearSelection: () => {
746
+ writeAnchorDate(null);
747
+ setDrawn(null);
748
+ setValueRaw(null);
749
+ },
750
+ isValueInvalid: () => {
751
+ if (access(options.isInvalid) === true) return true;
752
+ const range = value();
753
+ if (range === null || anchorDate() !== null) return false;
754
+ return !isAvailable(range.start) || !isAvailable(range.end);
755
+ },
756
+ isSelected: (date) => {
757
+ const range = highlightedRange();
758
+ if (range === null) return false;
759
+ return date.compare(range.start) >= 0 && date.compare(range.end) <= 0;
760
+ },
761
+ selectDate,
762
+ selectFocusedDate: () => selectDate(base.focusedDate()),
763
+ };
764
+ }
765
+
766
+ // ---------------------------------------------------------------------------
767
+ // Several days
768
+ // ---------------------------------------------------------------------------
769
+
770
+ export interface MultipleCalendarStateOptions extends Omit<
771
+ CalendarStateOptions,
772
+ "value" | "defaultValue" | "onChange"
773
+ > {
774
+ value?: MaybeAccessor<readonly CalendarDate[] | undefined>;
775
+ defaultValue?: MaybeAccessor<readonly CalendarDate[] | undefined>;
776
+ /** The fewest days that may be left chosen, and the most that may be. */
777
+ min?: MaybeAccessor<number | undefined>;
778
+ max?: MaybeAccessor<number | undefined>;
779
+ /** The last chosen day cannot be taken away. @default false */
780
+ required?: MaybeAccessor<boolean | undefined>;
781
+ onChange?: (value: CalendarDate[]) => void;
782
+ }
783
+
784
+ export interface MultipleCalendarState extends Omit<
785
+ CalendarState,
786
+ "value" | "setValue" | "selectionMode"
787
+ > {
788
+ readonly selectionMode: "multiple";
789
+ /** The chosen days, in the order they were chosen. */
790
+ value: Accessor<readonly CalendarDate[]>;
791
+ setValue(value: readonly CalendarDate[]): void;
792
+ }
793
+
794
+ /**
795
+ * Any number of days, each pressed on and off on its own.
796
+ *
797
+ * A press that would leave fewer than `min` or make more than `max` does
798
+ * nothing, rather than dropping some other day to make room: which day to drop
799
+ * is not a decision a calendar can make for anyone.
800
+ */
801
+ export function multipleCalendarState(
802
+ options: MultipleCalendarStateOptions,
803
+ ): MultipleCalendarState {
804
+ const [value, setValueRaw] = controllable<readonly CalendarDate[]>(
805
+ () => access(options.value),
806
+ () => access(options.defaultValue) ?? [],
807
+ (next) => options.onChange?.([...next]),
808
+ );
809
+
810
+ const base = calendarState({
811
+ ...(options as CalendarStateOptions),
812
+ value: () => value()[0] ?? null,
813
+ defaultValue: undefined,
814
+ onChange: undefined,
815
+ });
816
+
817
+ const isSelected = (date: CalendarDate): boolean =>
818
+ value().some((chosen) => isSameDay(chosen, date));
819
+
820
+ const selectDate = (date: CalendarDate): void => {
821
+ if (base.isReadOnly() || base.isDisabled()) return;
822
+ if (base.isCellDisabled(date) || base.isCellUnavailable(date)) return;
823
+
824
+ const chosen = untrack(value);
825
+ if (chosen.some((one) => isSameDay(one, date))) {
826
+ const least = Math.max(access(options.min) ?? 0, access(options.required) === true ? 1 : 0);
827
+ if (chosen.length - 1 < least) return;
828
+ setValueRaw(chosen.filter((one) => !isSameDay(one, date)));
829
+ return;
830
+ }
831
+
832
+ const most = access(options.max);
833
+ if (most !== undefined && chosen.length >= most) return;
834
+ setValueRaw([...chosen, date]);
835
+ };
836
+
837
+ const isRefused = (date: CalendarDate): boolean => {
838
+ const min = access(options.minValue);
839
+ const max = access(options.maxValue);
840
+ if (min !== undefined && min !== null && date.compare(min) < 0) return true;
841
+ if (max !== undefined && max !== null && date.compare(max) > 0) return true;
842
+ return base.isCellUnavailable(date) || options.isDateDisabled?.(date) === true;
843
+ };
844
+
845
+ return {
846
+ ...base,
847
+ selectionMode: "multiple",
848
+ value,
849
+ setValue: (next) => setValueRaw(next),
850
+ isValueInvalid: () => access(options.isInvalid) === true || value().some(isRefused),
851
+ isSelected,
852
+ selectDate,
853
+ selectFocusedDate: () => selectDate(base.focusedDate()),
854
+ };
855
+ }
856
+
857
+ /** Any of the three states a calendar can be built on. */
858
+ export type AnyCalendarState = CalendarState | RangeCalendarState | MultipleCalendarState;
859
+
860
+ // ---------------------------------------------------------------------------
861
+ // Hooks
862
+ // ---------------------------------------------------------------------------
863
+
864
+ export interface CalendarOptions {
865
+ // No `isDisabled`: the STATE carries it, and a second copy here would be a
866
+ // flag a caller could set and watch do nothing.
867
+ "aria-label"?: MaybeAccessor<string | undefined>;
868
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
869
+ /** The calendar's element, for telling a release or a blur outside it from one inside. */
870
+ ref?: ElementRef;
871
+ /**
872
+ * What a range half drawn becomes when the pointer is released outside the
873
+ * calendar or focus leaves it: finished where it reached, abandoned, or
874
+ * abandoned with the value cleared. @default "select"
875
+ */
876
+ commitBehavior?: MaybeAccessor<"clear" | "reset" | "select" | undefined>;
877
+ }
878
+
879
+ /** What a calendar's cells need from the calendar around them. */
880
+ interface CalendarData {
881
+ errorMessageId: Accessor<string>;
882
+ }
883
+
884
+ const calendarData = new WeakMap<AnyCalendarState, CalendarData>();
885
+
886
+ /** The press a range is being drawn with, shared by the cells of one calendar. */
887
+ interface Drag {
888
+ /** The day the press began on, and what it did there. */
889
+ origin: CalendarDate | null;
890
+ kind: "anchor" | "boundary" | null;
891
+ /** A touch waits before it draws, in case it is a scroll. */
892
+ timer: ReturnType<typeof setTimeout> | undefined;
893
+ /** A cell handled the press, so the click that follows is not a second one. */
894
+ clickPending: boolean;
895
+ }
896
+
897
+ const drags = new WeakMap<AnyCalendarState, Drag>();
898
+
899
+ function dragOf(state: AnyCalendarState): Drag {
900
+ let drag = drags.get(state);
901
+ if (drag === undefined) {
902
+ drag = { origin: null, kind: null, timer: undefined, clickPending: false };
903
+ drags.set(state, drag);
904
+ }
905
+ return drag;
906
+ }
907
+
908
+ /** A screen reader's pointer has no size; its press is a click, and handled as one. */
909
+ function isVirtualPointer(event: PointerEvent): boolean {
910
+ return event.pointerType === "" || (event.width === 0 && event.height === 0);
911
+ }
912
+
913
+ /**
914
+ * Splits a formatted range into its two ends, at the last literal they share.
915
+ *
916
+ * The locale's own range format puts the separator where it belongs, "11–13
917
+ * March" or "March 11 – 13", and the message around the two ends is the
918
+ * locale's too.
919
+ */
920
+ function formatRange(
921
+ format: Intl.DateTimeFormat,
922
+ start: CalendarDate,
923
+ end: CalendarDate,
924
+ ): { startDate: string; endDate: string } {
925
+ const parts = format.formatRangeToParts(start.toDate(), end.toDate());
926
+ let separator = -1;
927
+ for (const [at, part] of parts.entries()) {
928
+ if (part.source === "shared" && part.type === "literal") separator = at;
929
+ else if (part.source === "endRange") break;
930
+ }
931
+ let startDate = "";
932
+ let endDate = "";
933
+ for (const [at, part] of parts.entries()) {
934
+ if (at < separator) startDate += part.value;
935
+ else if (at > separator) endDate += part.value;
936
+ }
937
+ return { startDate, endDate };
938
+ }
939
+
940
+ export interface CalendarResult {
941
+ calendarProps: DOMProps;
942
+ /** Options for {@link button}, not props for an element. */
943
+ prevButtonProps: DOMProps;
944
+ nextButtonProps: DOMProps;
945
+ errorMessageProps: DOMProps;
946
+ /** The month on show, as a heading. With several on show, the first to the last. */
947
+ title: Accessor<string>;
948
+ baseId: Accessor<string>;
949
+ }
950
+
951
+ export function calendar(options: CalendarOptions, state: AnyCalendarState): CalendarResult {
952
+ const baseId = id();
953
+ const errorMessageId = id();
954
+ const titleFormat = dateFormatter({ month: "long", year: "numeric" });
955
+ const messages = stringFormatter(CALENDAR_STRINGS);
956
+ const longDate = dateFormatter({
957
+ weekday: "long",
958
+ month: "long",
959
+ year: "numeric",
960
+ day: "numeric",
961
+ });
962
+ const list = listFormatter();
963
+ calendarData.set(state, { errorMessageId });
964
+
965
+ /** What has been chosen, in words, or nothing while a range is half drawn. */
966
+ const selection = (): string => {
967
+ const spoken = (date: CalendarDate): string => longDate().format(date.toDate());
968
+ if (state.selectionMode === "range") {
969
+ const range = state.value();
970
+ if (range === null || state.anchorDate() !== null) return "";
971
+ if (isSameDay(range.start, range.end)) {
972
+ return messages().format("selectedDateDescription", { date: spoken(range.start) });
973
+ }
974
+ const dateRange = messages().format(
975
+ "dateRange",
976
+ formatRange(longDate(), range.start, range.end),
977
+ );
978
+ return messages().format("selectedRangeDescription", { dateRange });
979
+ }
980
+ if (state.selectionMode === "multiple") {
981
+ const days = state.value();
982
+ if (days.length === 0) return "";
983
+ return messages().format("selectedDateDescription", {
984
+ date: list().format(days.map(spoken)),
985
+ });
986
+ }
987
+ const chosen = state.value();
988
+ return chosen === null
989
+ ? ""
990
+ : messages().format("selectedDateDescription", { date: spoken(chosen) });
991
+ };
992
+
993
+ const commit = (): void => {
994
+ if (state.selectionMode !== "range" || state.anchorDate() === null) return;
995
+ const behavior = access(options.commitBehavior) ?? "select";
996
+ if (behavior === "clear") state.clearSelection();
997
+ else if (behavior === "reset") state.setAnchorDate(null);
998
+ else state.commitSelection();
999
+ };
1000
+
1001
+ const title = (): string => {
1002
+ const range = state.visibleRange();
1003
+ const first = range.start.toDate();
1004
+ if (state.visibleMonths() === 1) return titleFormat().format(first);
1005
+ return titleFormat().formatRange(first, startOfMonth(range.end).toDate());
1006
+ };
1007
+
1008
+ if (!isServer) {
1009
+ // The month changing under a pointer press has nothing on screen to say
1010
+ // so; a screen reader user pressing "next" hears only the button.
1011
+ let previous = title();
1012
+ createEffect(title, (current) => {
1013
+ if (current === previous) return;
1014
+ previous = current;
1015
+ if (!untrack(state.isFocused)) announce(current);
1016
+ });
1017
+
1018
+ // A choice is said once it is made, since the day pressed is announced
1019
+ // before the press changes it.
1020
+ let chosen = untrack(selection);
1021
+ createEffect(selection, (current) => {
1022
+ if (current === chosen) return;
1023
+ chosen = current;
1024
+ if (current !== "") announce(current, "polite", 4000);
1025
+ });
1026
+
1027
+ if (state.selectionMode === "range") {
1028
+ // A range drawn by dragging ends where the pointer is released. Released
1029
+ // outside the calendar, or anywhere in it but on a day, the range is
1030
+ // finished, abandoned or cleared as `commitBehavior` says.
1031
+ onSettled(() => {
1032
+ const view = typeof window === "undefined" ? null : window;
1033
+ if (view === null) return undefined;
1034
+ const release = (event: PointerEvent): void => {
1035
+ if (isVirtualPointer(event)) return;
1036
+ const drag = dragOf(state);
1037
+ clearTimeout(drag.timer);
1038
+ drag.timer = undefined;
1039
+ drag.origin = null;
1040
+ drag.kind = null;
1041
+ state.setDragging(false);
1042
+ if (state.anchorDate() === null) return;
1043
+ const root = access(options.ref) as Element | null;
1044
+ if (root === null || !contains(root, activeElement(ownerDocument(root)))) return;
1045
+ const target = event.target instanceof Element ? event.target : null;
1046
+ if (
1047
+ target !== null &&
1048
+ contains(root, target) &&
1049
+ target.closest('button, [role="button"]') !== null
1050
+ ) {
1051
+ return;
1052
+ }
1053
+ commit();
1054
+ };
1055
+ const clicked = (): void => {
1056
+ dragOf(state).clickPending = false;
1057
+ };
1058
+ view.addEventListener("pointerup", release);
1059
+ view.addEventListener("click", clicked);
1060
+ return () => {
1061
+ view.removeEventListener("pointerup", release);
1062
+ view.removeEventListener("click", clicked);
1063
+ };
1064
+ });
1065
+ }
1066
+ }
1067
+
1068
+ return {
1069
+ baseId,
1070
+ title,
1071
+ errorMessageProps: { id: errorMessageId },
1072
+ calendarProps: mergeProps(filterDOMProps(options, { labelable: true }), {
1073
+ role: "group",
1074
+ id: baseId,
1075
+ "aria-label": () => access(options["aria-label"]),
1076
+ "aria-labelledby": () => access(options["aria-labelledby"]),
1077
+ // Leaving the calendar with a range half drawn finishes it, as letting
1078
+ // go of the pointer outside it does. Focus leaving because the focused
1079
+ // day was removed is not leaving, and is told apart a microtask later.
1080
+ onFocusOut: (event: FocusEvent) => {
1081
+ if (state.selectionMode !== "range") return;
1082
+ const root = event.currentTarget as Element | null;
1083
+ if (root === null) return;
1084
+ const next = event.relatedTarget instanceof Element ? event.relatedTarget : null;
1085
+ if (next !== null) {
1086
+ if (!contains(root, next)) commit();
1087
+ return;
1088
+ }
1089
+ queueMicrotask(() => {
1090
+ if (!contains(root, activeElement(ownerDocument(root)))) commit();
1091
+ });
1092
+ },
1093
+ }),
1094
+ prevButtonProps: {
1095
+ "aria-label": () => messages().format("previous"),
1096
+ isDisabled: () => state.isDisabled() || state.isPreviousVisibleRangeInvalid(),
1097
+ onPress: () => state.focusPreviousPage(),
1098
+ },
1099
+ nextButtonProps: {
1100
+ "aria-label": () => messages().format("next"),
1101
+ isDisabled: () => state.isDisabled() || state.isNextVisibleRangeInvalid(),
1102
+ onPress: () => state.focusNextPage(),
1103
+ },
1104
+ };
1105
+ }
1106
+
1107
+ export interface CalendarGridOptions {
1108
+ /** @default "narrow" */
1109
+ weekdayStyle?: MaybeAccessor<"narrow" | "short" | "long" | undefined>;
1110
+ /** Which of the months on show this grid draws, counted from the first. @default 0 */
1111
+ monthOffset?: MaybeAccessor<number | undefined>;
1112
+ /** Always six week rows, so paging never changes the height. @default false */
1113
+ fixedWeeks?: MaybeAccessor<boolean | undefined>;
1114
+ /** Number the weeks by ISO 8601 rather than by the locale. @default false */
1115
+ isoWeek?: MaybeAccessor<boolean | undefined>;
1116
+ "aria-label"?: MaybeAccessor<string | undefined>;
1117
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
1118
+ }
1119
+
1120
+ export interface CalendarGridResult {
1121
+ gridProps: DOMProps;
1122
+ headerProps: DOMProps;
1123
+ /** The first day of the month this grid draws. */
1124
+ month: Accessor<CalendarDate>;
1125
+ /** That month as a heading. */
1126
+ title: Accessor<string>;
1127
+ /** The weekday names, from the locale, starting on its first day. */
1128
+ weekDays: Accessor<string[]>;
1129
+ weeksInMonth: Accessor<number>;
1130
+ /** Every day of a week row, including the ones outside the month. */
1131
+ weekDates: (week: number) => CalendarDate[];
1132
+ /** Which week of the year a row is, going by the row's first day. */
1133
+ weekNumber: (week: number) => number;
1134
+ }
1135
+
1136
+ export function calendarGrid(
1137
+ options: CalendarGridOptions,
1138
+ state: AnyCalendarState,
1139
+ ): CalendarGridResult {
1140
+ const locale = useLocale();
1141
+ const titleFormat = dateFormatter({ month: "long", year: "numeric" });
1142
+
1143
+ const month = (): CalendarDate =>
1144
+ state.visibleRange().start.add({ months: access(options.monthOffset) ?? 0 });
1145
+ const dayFormat = createMemo(() =>
1146
+ dateFormatter({ weekday: access(options.weekdayStyle) ?? "narrow" })(),
1147
+ );
1148
+
1149
+ const weekDays = createMemo(() => {
1150
+ const start = startOfWeek(today(), state.firstDayOfWeek());
1151
+ return Array.from({ length: 7 }, (_, at) =>
1152
+ dayFormat().format(start.add({ days: at }).toDate()),
1153
+ );
1154
+ });
1155
+
1156
+ const weeksInMonth = (): number =>
1157
+ access(options.fixedWeeks) === true
1158
+ ? 6
1159
+ : (state.weeksInMonth() ?? getWeeksInMonth(month(), state.firstDayOfWeek()));
1160
+
1161
+ const weekDates = (week: number): CalendarDate[] => {
1162
+ const first = startOfWeek(month(), state.firstDayOfWeek());
1163
+ const start = first.add({ weeks: week });
1164
+ return Array.from({ length: 7 }, (_, at) => start.add({ days: at }));
1165
+ };
1166
+
1167
+ const weekNumber = (week: number): number => {
1168
+ const first = startOfWeek(month(), state.firstDayOfWeek()).add({ weeks: week });
1169
+ if (access(options.isoWeek) === true) return getISOWeek(first);
1170
+ return getWeekOfYear(first, state.firstDayOfWeek(), getMinimalDaysInFirstWeek(locale().locale));
1171
+ };
1172
+
1173
+ const onKeyDown = (event: KeyboardEvent): void => {
1174
+ const rtl = locale().direction === "rtl";
1175
+
1176
+ switch (event.key) {
1177
+ case "ArrowLeft":
1178
+ if (rtl) state.focusNextDay();
1179
+ else state.focusPreviousDay();
1180
+ break;
1181
+ case "ArrowRight":
1182
+ if (rtl) state.focusPreviousDay();
1183
+ else state.focusNextDay();
1184
+ break;
1185
+ case "ArrowUp":
1186
+ state.focusPreviousRow();
1187
+ break;
1188
+ case "ArrowDown":
1189
+ state.focusNextRow();
1190
+ break;
1191
+ case "PageUp":
1192
+ state.focusPreviousSection(event.shiftKey);
1193
+ break;
1194
+ case "PageDown":
1195
+ state.focusNextSection(event.shiftKey);
1196
+ break;
1197
+ case "Home":
1198
+ state.focusSectionStart();
1199
+ break;
1200
+ case "End":
1201
+ state.focusSectionEnd();
1202
+ break;
1203
+ case "Enter":
1204
+ case " ":
1205
+ state.selectFocusedDate();
1206
+ break;
1207
+ case "Escape": {
1208
+ // Abandon a range half drawn, rather than leaving an anchor behind
1209
+ // that the next press would finish against.
1210
+ if ("setAnchorDate" in state) {
1211
+ event.preventDefault();
1212
+ state.setAnchorDate(null);
1213
+ }
1214
+ return;
1215
+ }
1216
+ default:
1217
+ return;
1218
+ }
1219
+
1220
+ event.preventDefault();
1221
+ event.stopPropagation();
1222
+ };
1223
+
1224
+ const title = (): string => titleFormat().format(month().toDate());
1225
+
1226
+ return {
1227
+ month,
1228
+ title,
1229
+ weekDays,
1230
+ weeksInMonth,
1231
+ weekDates,
1232
+ weekNumber,
1233
+ headerProps: { "aria-hidden": true },
1234
+ gridProps: {
1235
+ role: "grid",
1236
+ "aria-multiselectable": state.selectionMode === "single" ? undefined : true,
1237
+ "aria-readonly": () => state.isReadOnly() || undefined,
1238
+ "aria-disabled": () => state.isDisabled() || undefined,
1239
+ // A grid nobody named is named for its month: with a caption made of
1240
+ // selects there is no heading to point at, and an unnamed grid is announced
1241
+ // as "grid" and nothing else.
1242
+ "aria-label": () =>
1243
+ access(options["aria-label"]) ??
1244
+ (access(options["aria-labelledby"]) === undefined ? title() : undefined),
1245
+ "aria-labelledby": () => access(options["aria-labelledby"]),
1246
+ onKeyDown,
1247
+ onFocusIn: () => state.setFocused(true),
1248
+ // Removing the focused day fires `focusout` exactly as leaving the
1249
+ // calendar does, and moving between months removes a row. Clearing here
1250
+ // told the calendar it had lost focus in the middle of moving it, so the
1251
+ // day it moved TO no longer wanted focus and it stayed on `<body>`. The
1252
+ // question is answered a microtask later, against where focus actually
1253
+ // is.
1254
+ onFocusOut: (event: FocusEvent) => {
1255
+ const grid = event.currentTarget as Element | null;
1256
+ if (grid === null) {
1257
+ state.setFocused(false);
1258
+ return;
1259
+ }
1260
+ queueMicrotask(() => {
1261
+ if (!contains(grid, activeElement(ownerDocument(grid)))) state.setFocused(false);
1262
+ });
1263
+ },
1264
+ },
1265
+ };
1266
+ }
1267
+
1268
+ export interface CalendarCellOptions {
1269
+ /**
1270
+ * The day.
1271
+ *
1272
+ * An accessor, because a cell OUTLIVES the day it draws: the grid keys its
1273
+ * rows and columns by position, so changing month moves 42 dates through 42
1274
+ * elements that stay where they are. A cell that was rebuilt instead would
1275
+ * be destroyed while it held focus.
1276
+ */
1277
+ date: MaybeAccessor<CalendarDate>;
1278
+ ref: ElementRef;
1279
+ /** Rendered to keep the grid rectangular, but belonging to another month. */
1280
+ isOutsideMonth?: MaybeAccessor<boolean | undefined>;
1281
+ /**
1282
+ * The month of the grid this cell is in. Defaults to the first one on show.
1283
+ *
1284
+ * With several months side by side the same day can be drawn twice, once in
1285
+ * its own grid and once as the tail of its neighbour's last week; only the
1286
+ * first of those is the day.
1287
+ */
1288
+ month?: MaybeAccessor<CalendarDate | undefined>;
1289
+ }
1290
+
1291
+ export interface CalendarCellResult {
1292
+ cellProps: DOMProps;
1293
+ /** For the element inside the cell that the user actually presses. */
1294
+ buttonProps: DOMProps;
1295
+ isSelected: Accessor<boolean>;
1296
+ isFocused: Accessor<boolean>;
1297
+ isDisabled: Accessor<boolean>;
1298
+ isUnavailable: Accessor<boolean>;
1299
+ isOutsideVisibleRange: Accessor<boolean>;
1300
+ isToday: Accessor<boolean>;
1301
+ /**
1302
+ * The first and last day of the range this cell is in, if it is in one.
1303
+ *
1304
+ * Both are false in a calendar that selects a single day: there is no range,
1305
+ * so there are no ends to it. A range's three positions — its two ends and
1306
+ * everything between — are what a stylesheet needs to round the corners of
1307
+ * one selection and not of the days inside it.
1308
+ */
1309
+ isSelectionStart: Accessor<boolean>;
1310
+ isSelectionEnd: Accessor<boolean>;
1311
+ formattedDate: Accessor<string>;
1312
+ }
1313
+
1314
+ export function calendarCell(
1315
+ options: CalendarCellOptions,
1316
+ state: AnyCalendarState,
1317
+ ): CalendarCellResult {
1318
+ const labelFormat = dateFormatter({
1319
+ weekday: "long",
1320
+ day: "numeric",
1321
+ month: "long",
1322
+ year: "numeric",
1323
+ });
1324
+ const dayFormat = dateFormatter({ day: "numeric" });
1325
+ const messages = stringFormatter(CALENDAR_STRINGS);
1326
+ const drag = dragOf(state);
1327
+
1328
+ const date = (): CalendarDate => access(options.date);
1329
+
1330
+ const isOutside = (): boolean =>
1331
+ access(options.isOutsideMonth) === true ||
1332
+ !isSameMonth(date(), access(options.month) ?? state.visibleRange().start);
1333
+
1334
+ const isDisabled = (): boolean => state.isCellDisabled(date()) || isOutside();
1335
+ const isUnavailable = (): boolean => state.isCellUnavailable(date());
1336
+ const isSelectable = (): boolean => !isDisabled() && !isUnavailable();
1337
+
1338
+ /** This day is part of a value the calendar says is wrong. */
1339
+ const isInvalid = (): boolean => {
1340
+ if (!state.isValueInvalid()) return false;
1341
+ const day = date();
1342
+ if (state.selectionMode === "range") {
1343
+ const range = state.highlightedRange();
1344
+ return (
1345
+ state.anchorDate() === null &&
1346
+ range !== null &&
1347
+ day.compare(range.start) >= 0 &&
1348
+ day.compare(range.end) <= 0
1349
+ );
1350
+ }
1351
+ if (state.selectionMode === "multiple") return state.value().some((one) => isSameDay(one, day));
1352
+ const chosen = state.value();
1353
+ return chosen !== null && isSameDay(chosen, day);
1354
+ };
1355
+
1356
+ // A chosen day stays drawn as chosen while it is invalid, even when it is
1357
+ // one that could not be chosen now: the value is what it is, and hiding it
1358
+ // would leave the error pointing at nothing.
1359
+ const isSelected = (): boolean =>
1360
+ (state.isSelected(date()) && isSelectable()) || (isInvalid() && !isDisabled());
1361
+ const isFocused = (): boolean => state.isCellFocused(date()) && !isOutside();
1362
+ const isTodayCell = (): boolean => isSameDay(date(), state.today());
1363
+
1364
+ const highlighted = (): DateRange | null =>
1365
+ "highlightedRange" in state ? state.highlightedRange() : null;
1366
+ const isSelectionStart = (): boolean => {
1367
+ const range = highlighted();
1368
+ return isSelected() && range !== null && isSameDay(date(), range.start);
1369
+ };
1370
+ const isSelectionEnd = (): boolean => {
1371
+ const range = highlighted();
1372
+ return isSelected() && range !== null && isSameDay(date(), range.end);
1373
+ };
1374
+
1375
+ if (!isServer) {
1376
+ // The state decides which day is focused; the DOM follows it, so the
1377
+ // arrows move focus without every cell having to watch the keyboard.
1378
+ createEffect(
1379
+ () => (isFocused() ? { element: access(options.ref) as HTMLElement | null } : null),
1380
+ (focused) => {
1381
+ if (focused === null) return;
1382
+ const { element } = focused;
1383
+ if (element === null) return;
1384
+ if (activeElement(ownerDocument(element)) !== element) focusSafely(element);
1385
+ },
1386
+ );
1387
+ }
1388
+
1389
+ const label = (): string => {
1390
+ const text = labelFormat().format(date().toDate());
1391
+ if (isTodayCell()) {
1392
+ return messages().format(isSelected() ? "todayDateSelected" : "todayDate", { date: text });
1393
+ }
1394
+ return isSelected() ? messages().format("dateSelected", { date: text }) : text;
1395
+ };
1396
+
1397
+ /** A range drawn by pressing one day and releasing on another. */
1398
+ const onPointerDown = (event: PointerEvent): void => {
1399
+ if (state.selectionMode !== "range" || event.button !== 0 || isVirtualPointer(event)) return;
1400
+ drag.clickPending = true;
1401
+ // A touch keeps the pointer on the element it began on unless released,
1402
+ // and the days it is dragged over would then never hear it.
1403
+ const target = event.target instanceof Element ? event.target : null;
1404
+ if (target?.hasPointerCapture?.(event.pointerId) === true) {
1405
+ target.releasePointerCapture(event.pointerId);
1406
+ }
1407
+ if (!isSelectable()) return;
1408
+ const day = date();
1409
+ if (state.isReadOnly()) {
1410
+ state.setFocusedDate(day);
1411
+ return;
1412
+ }
1413
+ if (state.anchorDate() !== null) return;
1414
+
1415
+ // Pressing an end of the chosen range takes hold of it, so dragging moves
1416
+ // that end and leaves the other where it is.
1417
+ const range = state.highlightedRange();
1418
+ if (range !== null && !isInvalid()) {
1419
+ const other = isSameDay(day, range.start)
1420
+ ? range.end
1421
+ : isSameDay(day, range.end)
1422
+ ? range.start
1423
+ : null;
1424
+ if (other !== null) {
1425
+ state.setAnchorDate(other);
1426
+ state.setFocusedDate(day);
1427
+ state.setDragging(true);
1428
+ drag.origin = day;
1429
+ drag.kind = "boundary";
1430
+ return;
1431
+ }
1432
+ }
1433
+
1434
+ const start = (): void => {
1435
+ drag.timer = undefined;
1436
+ state.setDragging(true);
1437
+ state.selectDate(day);
1438
+ state.setFocusedDate(day);
1439
+ drag.origin = day;
1440
+ drag.kind = "anchor";
1441
+ };
1442
+ if (event.pointerType === "touch") drag.timer = setTimeout(start, 200);
1443
+ else start();
1444
+ };
1445
+
1446
+ const onPointerUp = (event: PointerEvent): void => {
1447
+ if (state.selectionMode !== "range" || event.button !== 0 || isVirtualPointer(event)) return;
1448
+ drag.clickPending = true;
1449
+ if (state.isReadOnly()) return;
1450
+ const day = date();
1451
+
1452
+ // A tap quicker than the wait for a drag is a press like any other.
1453
+ if (drag.timer !== undefined) {
1454
+ clearTimeout(drag.timer);
1455
+ drag.timer = undefined;
1456
+ state.selectDate(day);
1457
+ state.setFocusedDate(day);
1458
+ return;
1459
+ }
1460
+
1461
+ const fromHere = drag.origin !== null && isSameDay(drag.origin, day);
1462
+ if (drag.kind === "boundary" && fromHere) {
1463
+ // An end pressed and let go without moving starts a new range there.
1464
+ state.setAnchorDate(day);
1465
+ } else if (state.anchorDate() !== null && !(drag.kind === "anchor" && fromHere)) {
1466
+ state.selectDate(day);
1467
+ state.setFocusedDate(day);
1468
+ }
1469
+ };
1470
+
1471
+ return {
1472
+ isSelected,
1473
+ isFocused,
1474
+ isDisabled,
1475
+ isUnavailable,
1476
+ isOutsideVisibleRange: isOutside,
1477
+ isToday: isTodayCell,
1478
+ isSelectionStart,
1479
+ isSelectionEnd,
1480
+ formattedDate: () => dayFormat().format(date().toDate()),
1481
+ cellProps: {
1482
+ role: "gridcell",
1483
+ "aria-selected": () => isSelected() || undefined,
1484
+ "aria-disabled": () => (!isSelectable() ? true : undefined),
1485
+ "aria-invalid": () => isInvalid() || undefined,
1486
+ },
1487
+ buttonProps: {
1488
+ role: "button",
1489
+ // A day outside the month is scaffolding: hidden from the tree, so Down
1490
+ // from the last week reaches the next MONTH and not a duplicate.
1491
+ "aria-hidden": () => isOutside() || undefined,
1492
+ "aria-label": label,
1493
+ "aria-invalid": () => isInvalid() || undefined,
1494
+ // The error message says what is wrong with the value, so the days that
1495
+ // make it up point at it.
1496
+ "aria-describedby": () =>
1497
+ isInvalid() ? calendarData.get(state)?.errorMessageId() : undefined,
1498
+ // The roving focus: one day in the Tab order, and it moves with the
1499
+ // arrows.
1500
+ tabIndex: () =>
1501
+ isOutside() ? undefined : isFocused() || isSameDay(state.focusedDate(), date()) ? 0 : -1,
1502
+ onPointerEnter: (event: PointerEvent) => {
1503
+ // Drawing a range follows the pointer, so the highlight is what the
1504
+ // user would get by releasing here. A touch only draws once it has
1505
+ // waited long enough to be a drag rather than a scroll.
1506
+ if (state.selectionMode !== "range" || state.anchorDate() === null) return;
1507
+ if (event.pointerType === "touch" && !state.isDragging()) return;
1508
+ if (isSelectable()) state.highlightDate(date());
1509
+ },
1510
+ onPointerDown,
1511
+ onPointerUp,
1512
+ onContextMenu: (event: MouseEvent) => {
1513
+ // A long press on a touch screen is a drag here, not a menu.
1514
+ if (state.selectionMode === "range") event.preventDefault();
1515
+ },
1516
+ onClick: () => {
1517
+ // The pointer already chose; this is the click the browser sends after.
1518
+ if (drag.clickPending) {
1519
+ drag.clickPending = false;
1520
+ return;
1521
+ }
1522
+ if (isOutside() || state.isCellDisabled(date())) return;
1523
+ state.setFocusedDate(date());
1524
+ state.selectDate(date());
1525
+ },
1526
+ },
1527
+ };
1528
+ }
1529
+
1530
+ // ---------------------------------------------------------------------------
1531
+ // Components
1532
+ // ---------------------------------------------------------------------------
1533
+
1534
+ interface CalendarContextValue {
1535
+ state: AnyCalendarState;
1536
+ baseId: Accessor<string>;
1537
+ }
1538
+
1539
+ const CalendarContext = createContext<CalendarContextValue | null>(null);
1540
+
1541
+ export function useCalendar(): CalendarContextValue {
1542
+ const value = getContext(CalendarContext);
1543
+ if (value === null || value === undefined) {
1544
+ throw new Error("This must be rendered inside a Calendar.");
1545
+ }
1546
+ return value;
1547
+ }
1548
+
1549
+ function CalendarProvider(props: { value: CalendarContextValue; children?: Child }) {
1550
+ return provide(
1551
+ CalendarContext,
1552
+ () => props.value,
1553
+ () => props.children as unknown,
1554
+ );
1555
+ }
1556
+
1557
+ export interface CalendarComponentProps extends StyleProps {
1558
+ value?: CalendarDate | null;
1559
+ defaultValue?: CalendarDate | null;
1560
+ focusedValue?: CalendarDate;
1561
+ defaultFocusedValue?: CalendarDate;
1562
+ minValue?: DateValue | null;
1563
+ maxValue?: DateValue | null;
1564
+ isDateUnavailable?: (date: CalendarDate) => boolean;
1565
+ /** Days that cannot be chosen and that the arrow keys step over. */
1566
+ isDateDisabled?: (date: CalendarDate) => boolean;
1567
+ isDisabled?: boolean;
1568
+ isReadOnly?: boolean;
1569
+ autoFocus?: boolean;
1570
+ /** Pressing the chosen day again clears it. @default false */
1571
+ allowsDeselection?: boolean;
1572
+ firstDayOfWeek?: number;
1573
+ /** Always six week rows. @default false */
1574
+ fixedWeeks?: boolean;
1575
+ /** The IANA zone today is reckoned in. Defaults to the local one. */
1576
+ timeZone?: string;
1577
+ /** @default "narrow" */
1578
+ weekdayStyle?: "narrow" | "short" | "long";
1579
+ /** Where the chosen day sits among several months when first shown. @default "center" */
1580
+ selectionAlignment?: "start" | "center" | "end";
1581
+ /** Every month drawn with this many week rows. */
1582
+ weeksInMonth?: number;
1583
+ /** Said by the caller, whatever the value is. */
1584
+ isInvalid?: boolean;
1585
+ errorMessage?: Child;
1586
+ "aria-label"?: string;
1587
+ "aria-labelledby"?: string;
1588
+ ref?: RefTarget<HTMLDivElement>;
1589
+ onChange?: (value: CalendarDate | null) => void;
1590
+ onFocusChange?: (date: CalendarDate) => void;
1591
+ }
1592
+
1593
+ /**
1594
+ * ```tsx
1595
+ * <Calendar aria-label="Departure" value={date()} onChange={date.set}
1596
+ * minValue={today()} />
1597
+ * ```
1598
+ */
1599
+ export function Calendar(props: CalendarComponentProps) {
1600
+ const state = calendarState({
1601
+ value: () => props.value,
1602
+ defaultValue: () => props.defaultValue,
1603
+ focusedValue: () => props.focusedValue,
1604
+ defaultFocusedValue: () => props.defaultFocusedValue,
1605
+ minValue: () => props.minValue,
1606
+ maxValue: () => props.maxValue,
1607
+ isDateUnavailable: callback<[CalendarDate], boolean>(cells(props).isDateUnavailable),
1608
+ isDateDisabled: callback<[CalendarDate], boolean>(cells(props).isDateDisabled),
1609
+ isDisabled: () => props.isDisabled,
1610
+ isReadOnly: () => props.isReadOnly,
1611
+ autoFocus: () => props.autoFocus,
1612
+ allowsDeselection: () => props.allowsDeselection,
1613
+ firstDayOfWeek: () => props.firstDayOfWeek,
1614
+ timeZone: () => props.timeZone,
1615
+ isInvalid: () => props.isInvalid,
1616
+ selectionAlignment: () => props.selectionAlignment,
1617
+ weeksInMonth: () => props.weeksInMonth,
1618
+ onChange: (value) => props.onChange?.(value),
1619
+ onFocusChange: (date) => props.onFocusChange?.(date),
1620
+ });
1621
+
1622
+ return <CalendarBody state={state} of={cells(props)} />;
1623
+ }
1624
+
1625
+ export interface RangeCalendarComponentProps extends Omit<
1626
+ CalendarComponentProps,
1627
+ "value" | "defaultValue" | "onChange" | "isDateUnavailable"
1628
+ > {
1629
+ value?: DateRange | null;
1630
+ defaultValue?: DateRange | null;
1631
+ allowsNonContiguousRanges?: boolean;
1632
+ /** Days that cannot be chosen, told the day the range being drawn began on. */
1633
+ isDateUnavailable?: (date: CalendarDate, anchorDate: CalendarDate | null) => boolean;
1634
+ /**
1635
+ * What a range half drawn becomes when the pointer is released outside the
1636
+ * calendar or focus leaves it. @default "select"
1637
+ */
1638
+ commitBehavior?: "clear" | "reset" | "select";
1639
+ onChange?: (value: DateRange | null) => void;
1640
+ }
1641
+
1642
+ /**
1643
+ * Two days, and everything between them.
1644
+ *
1645
+ * The first press anchors, the second finishes. Moving the pointer or the
1646
+ * focus between the two DRAWS: what is highlighted is what releasing would
1647
+ * give, so the user is never guessing.
1648
+ */
1649
+ export function RangeCalendar(props: RangeCalendarComponentProps) {
1650
+ const state = rangeCalendarState({
1651
+ value: () => props.value,
1652
+ defaultValue: () => props.defaultValue,
1653
+ focusedValue: () => props.focusedValue,
1654
+ defaultFocusedValue: () => props.defaultFocusedValue,
1655
+ minValue: () => props.minValue,
1656
+ maxValue: () => props.maxValue,
1657
+ isDateUnavailable: callback<[CalendarDate, CalendarDate | null], boolean>(
1658
+ cells(props).isDateUnavailable,
1659
+ ),
1660
+ isDateDisabled: callback<[CalendarDate], boolean>(cells(props).isDateDisabled),
1661
+ isDisabled: () => props.isDisabled,
1662
+ isReadOnly: () => props.isReadOnly,
1663
+ autoFocus: () => props.autoFocus,
1664
+ firstDayOfWeek: () => props.firstDayOfWeek,
1665
+ timeZone: () => props.timeZone,
1666
+ isInvalid: () => props.isInvalid,
1667
+ selectionAlignment: () => props.selectionAlignment,
1668
+ weeksInMonth: () => props.weeksInMonth,
1669
+ allowsNonContiguousRanges: () => props.allowsNonContiguousRanges,
1670
+ onChange: (value) => props.onChange?.(value),
1671
+ onFocusChange: (date) => props.onFocusChange?.(date),
1672
+ });
1673
+
1674
+ return (
1675
+ <CalendarBody
1676
+ state={state}
1677
+ of={cells(props) as unknown as Incoming<CalendarComponentProps>}
1678
+ commitBehavior={props.commitBehavior}
1679
+ />
1680
+ );
1681
+ }
1682
+
1683
+ export interface MultipleCalendarComponentProps extends Omit<
1684
+ CalendarComponentProps,
1685
+ "value" | "defaultValue" | "onChange"
1686
+ > {
1687
+ value?: readonly CalendarDate[];
1688
+ defaultValue?: readonly CalendarDate[];
1689
+ /** The fewest days that may be left chosen, and the most that may be. */
1690
+ min?: number;
1691
+ max?: number;
1692
+ /** The last chosen day cannot be taken away. @default false */
1693
+ required?: boolean;
1694
+ onChange?: (value: CalendarDate[]) => void;
1695
+ }
1696
+
1697
+ /**
1698
+ * Any number of days.
1699
+ *
1700
+ * Each press turns one day on or off and leaves the rest alone, and the grid
1701
+ * says it takes more than one so a screen reader does not announce a choice
1702
+ * as having replaced the last.
1703
+ */
1704
+ export function MultipleCalendar(props: MultipleCalendarComponentProps) {
1705
+ const state = multipleCalendarState({
1706
+ value: () => props.value,
1707
+ defaultValue: () => props.defaultValue,
1708
+ focusedValue: () => props.focusedValue,
1709
+ defaultFocusedValue: () => props.defaultFocusedValue,
1710
+ minValue: () => props.minValue,
1711
+ maxValue: () => props.maxValue,
1712
+ isDateUnavailable: callback<[CalendarDate], boolean>(cells(props).isDateUnavailable),
1713
+ isDateDisabled: callback<[CalendarDate], boolean>(cells(props).isDateDisabled),
1714
+ isDisabled: () => props.isDisabled,
1715
+ isReadOnly: () => props.isReadOnly,
1716
+ autoFocus: () => props.autoFocus,
1717
+ firstDayOfWeek: () => props.firstDayOfWeek,
1718
+ timeZone: () => props.timeZone,
1719
+ isInvalid: () => props.isInvalid,
1720
+ selectionAlignment: () => props.selectionAlignment,
1721
+ weeksInMonth: () => props.weeksInMonth,
1722
+ min: () => props.min,
1723
+ max: () => props.max,
1724
+ required: () => props.required,
1725
+ onChange: (value) => props.onChange?.(value),
1726
+ onFocusChange: (date) => props.onFocusChange?.(date),
1727
+ });
1728
+
1729
+ return (
1730
+ <CalendarBody state={state} of={cells(props) as unknown as Incoming<CalendarComponentProps>} />
1731
+ );
1732
+ }
1733
+
1734
+ interface CalendarBodyProps {
1735
+ state: AnyCalendarState;
1736
+ /** The calendar's own props, still as Cells. */
1737
+ of: Incoming<CalendarComponentProps>;
1738
+ commitBehavior?: "clear" | "reset" | "select";
1739
+ }
1740
+
1741
+ /** The heading, the two page buttons and the grid: what both calendars are. */
1742
+ function CalendarBody(incoming: CalendarBodyProps) {
1743
+ const state = incoming.state;
1744
+ const props = incoming.of;
1745
+ const prevRef = makeRef<HTMLButtonElement>();
1746
+ const nextRef = makeRef<HTMLButtonElement>();
1747
+ const rootRef = makeRef<HTMLDivElement>();
1748
+
1749
+ const { calendarProps, prevButtonProps, nextButtonProps, errorMessageProps, title, baseId } =
1750
+ calendar(
1751
+ {
1752
+ ref: rootRef,
1753
+ "aria-label": () => props["aria-label"]?.(),
1754
+ "aria-labelledby": () => props["aria-labelledby"]?.(),
1755
+ commitBehavior: () => incoming.commitBehavior,
1756
+ },
1757
+ state,
1758
+ );
1759
+
1760
+ const titleId = id();
1761
+
1762
+ const { gridProps, headerProps, weekDays, weeksInMonth, weekDates } = calendarGrid(
1763
+ {
1764
+ weekdayStyle: () => props.weekdayStyle?.(),
1765
+ fixedWeeks: () => props.fixedWeeks?.(),
1766
+ "aria-labelledby": titleId,
1767
+ },
1768
+ state,
1769
+ );
1770
+
1771
+ const previous = button(prevButtonProps, prevRef);
1772
+ const next = button(nextButtonProps, nextRef);
1773
+
1774
+ const value: CalendarContextValue = { state, baseId };
1775
+
1776
+ const elementProps = mergeProps(
1777
+ calendarProps,
1778
+ filterDOMProps(fromProps(props), { global: true }),
1779
+ styleProps(props),
1780
+ {
1781
+ "data-disabled": () => props.isDisabled?.() === true,
1782
+ "data-testid": () => props["data-testid"]?.(),
1783
+ },
1784
+ );
1785
+
1786
+ return (
1787
+ <CalendarProvider value={value}>
1788
+ <div {...elementProps} ref={mergeRefs(rootRef.set, props.ref?.())}>
1789
+ <div>
1790
+ <button {...previous.buttonProps} type="button" ref={prevRef.set}>
1791
+ <span aria-hidden="true">‹</span>
1792
+ </button>
1793
+ <h2 id={titleId}>{title}</h2>
1794
+ <button {...next.buttonProps} type="button" ref={nextRef.set}>
1795
+ <span aria-hidden="true">›</span>
1796
+ </button>
1797
+ </div>
1798
+ <div {...gridProps}>
1799
+ <div {...headerProps} role="row">
1800
+ <For each={() => weekDays()}>
1801
+ {(day: string) => (
1802
+ <div role="columnheader" aria-label={day}>
1803
+ {day}
1804
+ </div>
1805
+ )}
1806
+ </For>
1807
+ </div>
1808
+ {/* Keyed by POSITION, not by the day: `weekDates` builds seven new
1809
+ `CalendarDate` objects every read, so keying by them destroyed
1810
+ all forty-two cells whenever the month changed — with the one
1811
+ holding focus among them. */}
1812
+ <For each={() => Array.from({ length: weeksInMonth() }, (_, week) => week)}>
1813
+ {(week: number) => (
1814
+ <div role="row">
1815
+ <Repeat count={7}>
1816
+ {(at: number) => <CalendarCell date={weekDates(week)[at] as CalendarDate} />}
1817
+ </Repeat>
1818
+ </div>
1819
+ )}
1820
+ </For>
1821
+ </div>
1822
+ <span {...errorMessageProps}>{props.errorMessage}</span>
1823
+ </div>
1824
+ </CalendarProvider>
1825
+ );
1826
+ }
1827
+
1828
+ export interface CalendarCellComponentProps extends StyleProps {
1829
+ date: CalendarDate;
1830
+ ref?: RefTarget<HTMLDivElement>;
1831
+ }
1832
+
1833
+ /** One day. */
1834
+ export function CalendarCell(props: CalendarCellComponentProps) {
1835
+ const domRef = makeRef<HTMLDivElement>();
1836
+ const { state } = useCalendar();
1837
+
1838
+ const {
1839
+ cellProps,
1840
+ buttonProps,
1841
+ isSelected,
1842
+ isFocused,
1843
+ isDisabled,
1844
+ isUnavailable,
1845
+ isOutsideVisibleRange,
1846
+ isToday: isTodayCell,
1847
+ isSelectionStart,
1848
+ isSelectionEnd,
1849
+ formattedDate,
1850
+ } = calendarCell({ date: () => props.date, ref: domRef }, state);
1851
+
1852
+ const { hoverProps, isHovered } = hover({ isDisabled });
1853
+ const { focusProps, isFocusVisible } = focusRing();
1854
+
1855
+ const elementProps = mergeProps(
1856
+ buttonProps,
1857
+ hoverProps,
1858
+ focusProps,
1859
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1860
+ styleProps(cells(props)),
1861
+ {
1862
+ "data-selected": isSelected,
1863
+ "data-focused": isFocused,
1864
+ "data-focus-visible": isFocusVisible,
1865
+ "data-hovered": isHovered,
1866
+ "data-disabled": isDisabled,
1867
+ "data-unavailable": isUnavailable,
1868
+ "data-outside-month": isOutsideVisibleRange,
1869
+ "data-today": isTodayCell,
1870
+ "data-selection-start": isSelectionStart,
1871
+ "data-selection-end": isSelectionEnd,
1872
+ "data-testid": () => props["data-testid"],
1873
+ },
1874
+ );
1875
+
1876
+ return (
1877
+ <div {...cellProps}>
1878
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref)}>
1879
+ {formattedDate}
1880
+ </div>
1881
+ </div>
1882
+ );
1883
+ }
1884
+
1885
+ // ---------------------------------------------------------------------------
1886
+ // Strings
1887
+ // ---------------------------------------------------------------------------
1888
+
1889
+ /** A message with `{name}` slots filled from the variables it is formatted with. */
1890
+ function say(template: string): LocalizedString {
1891
+ return (variables) =>
1892
+ template.replace(/\{(\w+)\}/g, (_, slot: string) => String(variables?.[slot] ?? ""));
1893
+ }
1894
+
1895
+ type CalendarKey =
1896
+ | "previous"
1897
+ | "next"
1898
+ | "selectedDateDescription"
1899
+ | "selectedRangeDescription"
1900
+ | "todayDate"
1901
+ | "todayDateSelected"
1902
+ | "dateSelected"
1903
+ | "minimumDate"
1904
+ | "maximumDate"
1905
+ | "dateRange";
1906
+
1907
+ const CALENDAR_STRINGS = new StringDictionary<CalendarKey>({
1908
+ "en-US": {
1909
+ previous: "Previous month",
1910
+ next: "Next month",
1911
+ selectedDateDescription: say("Selected Date: {date}"),
1912
+ selectedRangeDescription: say("Selected Range: {dateRange}"),
1913
+ todayDate: say("Today, {date}"),
1914
+ todayDateSelected: say("Today, {date} selected"),
1915
+ dateSelected: say("{date} selected"),
1916
+ minimumDate: "First available date",
1917
+ maximumDate: "Last available date",
1918
+ dateRange: say("{startDate} to {endDate}"),
1919
+ },
1920
+ "ar-AE": {
1921
+ previous: "السابق",
1922
+ next: "التالي",
1923
+ selectedDateDescription: say("تاريخ محدد: {date}"),
1924
+ selectedRangeDescription: say("المدى الزمني المحدد: {dateRange}"),
1925
+ todayDate: say("اليوم، {date}"),
1926
+ todayDateSelected: say("اليوم، {date} محدد"),
1927
+ dateSelected: say("{date} المحدد"),
1928
+ minimumDate: "أول تاريخ متاح",
1929
+ maximumDate: "آخر تاريخ متاح",
1930
+ dateRange: say("{startDate} إلى {endDate}"),
1931
+ },
1932
+ "bg-BG": {
1933
+ previous: "Назад",
1934
+ next: "Напред",
1935
+ selectedDateDescription: say("Избрана дата: {date}"),
1936
+ selectedRangeDescription: say("Избран диапазон: {dateRange}"),
1937
+ todayDate: say("Днес, {date}"),
1938
+ todayDateSelected: say("Днес, {date} са избрани"),
1939
+ dateSelected: say("Избрано е {date}"),
1940
+ minimumDate: "Първа налична дата",
1941
+ maximumDate: "Последна налична дата",
1942
+ dateRange: say("{startDate} до {endDate}"),
1943
+ },
1944
+ "cs-CZ": {
1945
+ previous: "Předchozí",
1946
+ next: "Další",
1947
+ selectedDateDescription: say("Vybrané datum: {date}"),
1948
+ selectedRangeDescription: say("Vybrané období: {dateRange}"),
1949
+ todayDate: say("Dnes, {date}"),
1950
+ todayDateSelected: say("Dnes, vybráno {date}"),
1951
+ dateSelected: say("Vybráno {date}"),
1952
+ minimumDate: "První dostupné datum",
1953
+ maximumDate: "Poslední dostupné datum",
1954
+ dateRange: say("{startDate} až {endDate}"),
1955
+ },
1956
+ "da-DK": {
1957
+ previous: "Forrige",
1958
+ next: "Næste",
1959
+ selectedDateDescription: say("Valgt dato: {date}"),
1960
+ selectedRangeDescription: say("Valgt interval: {dateRange}"),
1961
+ todayDate: say("I dag, {date}"),
1962
+ todayDateSelected: say("I dag, {date} valgt"),
1963
+ dateSelected: say("{date} valgt"),
1964
+ minimumDate: "Første ledige dato",
1965
+ maximumDate: "Sidste ledige dato",
1966
+ dateRange: say("{startDate} til {endDate}"),
1967
+ },
1968
+ "de-DE": {
1969
+ previous: "Zurück",
1970
+ next: "Weiter",
1971
+ selectedDateDescription: say("Ausgewähltes Datum: {date}"),
1972
+ selectedRangeDescription: say("Ausgewählter Bereich: {dateRange}"),
1973
+ todayDate: say("Heute, {date}"),
1974
+ todayDateSelected: say("Heute, {date} ausgewählt"),
1975
+ dateSelected: say("{date} ausgewählt"),
1976
+ minimumDate: "Erstes verfügbares Datum",
1977
+ maximumDate: "Letztes verfügbares Datum",
1978
+ dateRange: say("{startDate} bis {endDate}"),
1979
+ },
1980
+ "el-GR": {
1981
+ previous: "Προηγούμενο",
1982
+ next: "Επόμενο",
1983
+ selectedDateDescription: say("Επιλεγμένη ημερομηνία: {date}"),
1984
+ selectedRangeDescription: say("Επιλεγμένο εύρος: {dateRange}"),
1985
+ todayDate: say("Σήμερα, {date}"),
1986
+ todayDateSelected: say("Σήμερα, επιλέχτηκε {date}"),
1987
+ dateSelected: say("Επιλέχθηκε {date}"),
1988
+ minimumDate: "Πρώτη διαθέσιμη ημερομηνία",
1989
+ maximumDate: "Τελευταία διαθέσιμη ημερομηνία",
1990
+ dateRange: say("{startDate} έως {endDate}"),
1991
+ },
1992
+ "es-ES": {
1993
+ previous: "Anterior",
1994
+ next: "Siguiente",
1995
+ selectedDateDescription: say("Fecha seleccionada: {date}"),
1996
+ selectedRangeDescription: say("Intervalo seleccionado: {dateRange}"),
1997
+ todayDate: say("Hoy, {date}"),
1998
+ todayDateSelected: say("Hoy, {date} seleccionado"),
1999
+ dateSelected: say("{date} seleccionado"),
2000
+ minimumDate: "Primera fecha disponible",
2001
+ maximumDate: "Última fecha disponible",
2002
+ dateRange: say("{startDate} a {endDate}"),
2003
+ },
2004
+ "et-EE": {
2005
+ previous: "Eelmine",
2006
+ next: "Järgmine",
2007
+ selectedDateDescription: say("Valitud kuupäev: {date}"),
2008
+ selectedRangeDescription: say("Valitud vahemik: {dateRange}"),
2009
+ todayDate: say("Täna, {date}"),
2010
+ todayDateSelected: say("Täna, {date} valitud"),
2011
+ dateSelected: say("{date} valitud"),
2012
+ minimumDate: "Esimene saadaolev kuupäev",
2013
+ maximumDate: "Viimane saadaolev kuupäev",
2014
+ dateRange: say("{startDate} kuni {endDate}"),
2015
+ },
2016
+ "fi-FI": {
2017
+ previous: "Edellinen",
2018
+ next: "Seuraava",
2019
+ selectedDateDescription: say("Valittu päivämäärä: {date}"),
2020
+ selectedRangeDescription: say("Valittu aikaväli: {dateRange}"),
2021
+ todayDate: say("Tänään, {date}"),
2022
+ todayDateSelected: say("Tänään, {date} valittu"),
2023
+ dateSelected: say("{date} valittu"),
2024
+ minimumDate: "Ensimmäinen varattavissa oleva päivämäärä",
2025
+ maximumDate: "Viimeinen varattavissa oleva päivämäärä",
2026
+ dateRange: say("{startDate} – {endDate}"),
2027
+ },
2028
+ "fr-FR": {
2029
+ previous: "Précédent",
2030
+ next: "Suivant",
2031
+ selectedDateDescription: say("Date sélectionnée : {date}"),
2032
+ selectedRangeDescription: say("Plage sélectionnée : {dateRange}"),
2033
+ todayDate: say("Aujourd'hui, {date}"),
2034
+ todayDateSelected: say("Aujourd’hui, {date} sélectionné"),
2035
+ dateSelected: say("{date} sélectionné"),
2036
+ minimumDate: "Première date disponible",
2037
+ maximumDate: "Dernière date disponible",
2038
+ dateRange: say("{startDate} à {endDate}"),
2039
+ },
2040
+ "he-IL": {
2041
+ previous: "הקודם",
2042
+ next: "הבא",
2043
+ selectedDateDescription: say("תאריך נבחר: {date}"),
2044
+ selectedRangeDescription: say("טווח נבחר: {dateRange}"),
2045
+ todayDate: say("היום, {date}"),
2046
+ todayDateSelected: say("היום, {date} נבחר"),
2047
+ dateSelected: say("{date} נבחר"),
2048
+ minimumDate: "תאריך פנוי ראשון",
2049
+ maximumDate: "תאריך פנוי אחרון",
2050
+ dateRange: say("{startDate} עד {endDate}"),
2051
+ },
2052
+ "hr-HR": {
2053
+ previous: "Prethodni",
2054
+ next: "Sljedeći",
2055
+ selectedDateDescription: say("Odabrani datum: {date}"),
2056
+ selectedRangeDescription: say("Odabrani raspon: {dateRange}"),
2057
+ todayDate: say("Danas, {date}"),
2058
+ todayDateSelected: say("Danas, odabran {date}"),
2059
+ dateSelected: say("{date} odabran"),
2060
+ minimumDate: "Prvi raspoloživi datum",
2061
+ maximumDate: "Posljednji raspoloživi datum",
2062
+ dateRange: say("{startDate} do {endDate}"),
2063
+ },
2064
+ "hu-HU": {
2065
+ previous: "Előző",
2066
+ next: "Következő",
2067
+ selectedDateDescription: say("Kijelölt dátum: {date}"),
2068
+ selectedRangeDescription: say("Kijelölt tartomány: {dateRange}"),
2069
+ todayDate: say("Ma, {date}"),
2070
+ todayDateSelected: say("Ma, {date} kijelölve"),
2071
+ dateSelected: say("{date} kiválasztva"),
2072
+ minimumDate: "Az első elérhető dátum",
2073
+ maximumDate: "Utolsó elérhető dátum",
2074
+ dateRange: say("{startDate}–{endDate}"),
2075
+ },
2076
+ "it-IT": {
2077
+ previous: "Precedente",
2078
+ next: "Successivo",
2079
+ selectedDateDescription: say("Data selezionata: {date}"),
2080
+ selectedRangeDescription: say("Intervallo selezionato: {dateRange}"),
2081
+ todayDate: say("Oggi, {date}"),
2082
+ todayDateSelected: say("Oggi, {date} selezionata"),
2083
+ dateSelected: say("{date} selezionata"),
2084
+ minimumDate: "Prima data disponibile",
2085
+ maximumDate: "Ultima data disponibile",
2086
+ dateRange: say("Da {startDate} a {endDate}"),
2087
+ },
2088
+ "ja-JP": {
2089
+ previous: "前へ",
2090
+ next: "次へ",
2091
+ selectedDateDescription: say("選択した日付 : {date}"),
2092
+ selectedRangeDescription: say("選択範囲 : {dateRange}"),
2093
+ todayDate: say("本日、{date}"),
2094
+ todayDateSelected: say("本日、{date} を選択"),
2095
+ dateSelected: say("{date} を選択"),
2096
+ minimumDate: "最初の利用可能日",
2097
+ maximumDate: "最終利用可能日",
2098
+ dateRange: say("{startDate} から {endDate}"),
2099
+ },
2100
+ "ko-KR": {
2101
+ previous: "이전",
2102
+ next: "다음",
2103
+ selectedDateDescription: say("선택 일자: {date}"),
2104
+ selectedRangeDescription: say("선택 범위: {dateRange}"),
2105
+ todayDate: say("오늘, {date}"),
2106
+ todayDateSelected: say("오늘, {date} 선택됨"),
2107
+ dateSelected: say("{date} 선택됨"),
2108
+ minimumDate: "처음으로 사용 가능한 일자",
2109
+ maximumDate: "마지막으로 사용 가능한 일자",
2110
+ dateRange: say("{startDate} ~ {endDate}"),
2111
+ },
2112
+ "lt-LT": {
2113
+ previous: "Ankstesnis",
2114
+ next: "Paskesnis",
2115
+ selectedDateDescription: say("Pasirinkta data: {date}"),
2116
+ selectedRangeDescription: say("Pasirinktas intervalas: {dateRange}"),
2117
+ todayDate: say("Šiandien, {date}"),
2118
+ todayDateSelected: say("Šiandien, pasirinkta {date}"),
2119
+ dateSelected: say("Pasirinkta {date}"),
2120
+ minimumDate: "Pirmoji galima data",
2121
+ maximumDate: "Paskutinė galima data",
2122
+ dateRange: say("Nuo {startDate} iki {endDate}"),
2123
+ },
2124
+ "lv-LV": {
2125
+ previous: "Atpakaļ",
2126
+ next: "Tālāk",
2127
+ selectedDateDescription: say("Atlasītais datums: {date}"),
2128
+ selectedRangeDescription: say("Atlasītais diapazons: {dateRange}"),
2129
+ todayDate: say("Šodien, {date}"),
2130
+ todayDateSelected: say("Atlasīta šodiena, {date}"),
2131
+ dateSelected: say("Atlasīts: {date}"),
2132
+ minimumDate: "Pirmais pieejamais datums",
2133
+ maximumDate: "Pēdējais pieejamais datums",
2134
+ dateRange: say("No {startDate} līdz {endDate}"),
2135
+ },
2136
+ "nb-NO": {
2137
+ previous: "Forrige",
2138
+ next: "Neste",
2139
+ selectedDateDescription: say("Valgt dato: {date}"),
2140
+ selectedRangeDescription: say("Valgt område: {dateRange}"),
2141
+ todayDate: say("I dag, {date}"),
2142
+ todayDateSelected: say("I dag, {date} valgt"),
2143
+ dateSelected: say("{date} valgt"),
2144
+ minimumDate: "Første tilgjengelige dato",
2145
+ maximumDate: "Siste tilgjengelige dato",
2146
+ dateRange: say("{startDate} til {endDate}"),
2147
+ },
2148
+ "nl-NL": {
2149
+ previous: "Vorige",
2150
+ next: "Volgende",
2151
+ selectedDateDescription: say("Geselecteerde datum: {date}"),
2152
+ selectedRangeDescription: say("Geselecteerd bereik: {dateRange}"),
2153
+ todayDate: say("Vandaag, {date}"),
2154
+ todayDateSelected: say("Vandaag, {date} geselecteerd"),
2155
+ dateSelected: say("{date} geselecteerd"),
2156
+ minimumDate: "Eerste beschikbare datum",
2157
+ maximumDate: "Laatste beschikbare datum",
2158
+ dateRange: say("{startDate} tot {endDate}"),
2159
+ },
2160
+ "pl-PL": {
2161
+ previous: "Wstecz",
2162
+ next: "Dalej",
2163
+ selectedDateDescription: say("Wybrana data: {date}"),
2164
+ selectedRangeDescription: say("Wybrany zakres: {dateRange}"),
2165
+ todayDate: say("Dzisiaj, {date}"),
2166
+ todayDateSelected: say("Dzisiaj wybrano {date}"),
2167
+ dateSelected: say("Wybrano {date}"),
2168
+ minimumDate: "Pierwsza dostępna data",
2169
+ maximumDate: "Ostatnia dostępna data",
2170
+ dateRange: say("{startDate} do {endDate}"),
2171
+ },
2172
+ "pt-BR": {
2173
+ previous: "Anterior",
2174
+ next: "Próximo",
2175
+ selectedDateDescription: say("Data selecionada: {date}"),
2176
+ selectedRangeDescription: say("Intervalo selecionado: {dateRange}"),
2177
+ todayDate: say("Hoje, {date}"),
2178
+ todayDateSelected: say("Hoje, {date} selecionado"),
2179
+ dateSelected: say("{date} selecionado"),
2180
+ minimumDate: "Primeira data disponível",
2181
+ maximumDate: "Última data disponível",
2182
+ dateRange: say("{startDate} a {endDate}"),
2183
+ },
2184
+ "pt-PT": {
2185
+ previous: "Anterior",
2186
+ next: "Próximo",
2187
+ selectedDateDescription: say("Data selecionada: {date}"),
2188
+ selectedRangeDescription: say("Intervalo selecionado: {dateRange}"),
2189
+ todayDate: say("Hoje, {date}"),
2190
+ todayDateSelected: say("Hoje, {date} selecionado"),
2191
+ dateSelected: say("{date} selecionado"),
2192
+ minimumDate: "Primeira data disponível",
2193
+ maximumDate: "Última data disponível",
2194
+ dateRange: say("{startDate} a {endDate}"),
2195
+ },
2196
+ "ro-RO": {
2197
+ previous: "Înainte",
2198
+ next: "Următorul",
2199
+ selectedDateDescription: say("Dată selectată: {date}"),
2200
+ selectedRangeDescription: say("Interval selectat: {dateRange}"),
2201
+ todayDate: say("Astăzi, {date}"),
2202
+ todayDateSelected: say("Azi, {date} selectată"),
2203
+ dateSelected: say("{date} selectată"),
2204
+ minimumDate: "Prima dată disponibilă",
2205
+ maximumDate: "Ultima dată disponibilă",
2206
+ dateRange: say("De la {startDate} până la {endDate}"),
2207
+ },
2208
+ "ru-RU": {
2209
+ previous: "Назад",
2210
+ next: "Далее",
2211
+ selectedDateDescription: say("Выбранная дата: {date}"),
2212
+ selectedRangeDescription: say("Выбранный диапазон: {dateRange}"),
2213
+ todayDate: say("Сегодня, {date}"),
2214
+ todayDateSelected: say("Сегодня, выбрано {date}"),
2215
+ dateSelected: say("Выбрано {date}"),
2216
+ minimumDate: "Первая доступная дата",
2217
+ maximumDate: "Последняя доступная дата",
2218
+ dateRange: say("С {startDate} по {endDate}"),
2219
+ },
2220
+ "sk-SK": {
2221
+ previous: "Predchádzajúce",
2222
+ next: "Nasledujúce",
2223
+ selectedDateDescription: say("Vybratý dátum: {date}"),
2224
+ selectedRangeDescription: say("Vybratý rozsah: {dateRange}"),
2225
+ todayDate: say("Dnes {date}"),
2226
+ todayDateSelected: say("Vybratý dnešný dátum {date}"),
2227
+ dateSelected: say("Vybratý dátum {date}"),
2228
+ minimumDate: "Prvý dostupný dátum",
2229
+ maximumDate: "Posledný dostupný dátum",
2230
+ dateRange: say("Od {startDate} do {endDate}"),
2231
+ },
2232
+ "sl-SI": {
2233
+ previous: "Nazaj",
2234
+ next: "Naprej",
2235
+ selectedDateDescription: say("Izbrani datum: {date}"),
2236
+ selectedRangeDescription: say("Izbrano območje: {dateRange}"),
2237
+ todayDate: say("Danes, {date}"),
2238
+ todayDateSelected: say("Danes, {date} izbrano"),
2239
+ dateSelected: say("{date} izbrano"),
2240
+ minimumDate: "Prvi razpoložljivi datum",
2241
+ maximumDate: "Zadnji razpoložljivi datum",
2242
+ dateRange: say("{startDate} do {endDate}"),
2243
+ },
2244
+ "sr-SP": {
2245
+ previous: "Prethodni",
2246
+ next: "Sledeći",
2247
+ selectedDateDescription: say("Izabrani datum: {date}"),
2248
+ selectedRangeDescription: say("Izabrani period: {dateRange}"),
2249
+ todayDate: say("Danas, {date}"),
2250
+ todayDateSelected: say("Danas, izabran {date}"),
2251
+ dateSelected: say("{date} izabran"),
2252
+ minimumDate: "Prvi raspoloživi datum",
2253
+ maximumDate: "Zadnji raspoloživi datum",
2254
+ dateRange: say("{startDate} do {endDate}"),
2255
+ },
2256
+ "sv-SE": {
2257
+ previous: "Föregående",
2258
+ next: "Nästa",
2259
+ selectedDateDescription: say("Valt datum: {date}"),
2260
+ selectedRangeDescription: say("Valt intervall: {dateRange}"),
2261
+ todayDate: say("Idag, {date}"),
2262
+ todayDateSelected: say("Idag, {date} har valts"),
2263
+ dateSelected: say("{date} har valts"),
2264
+ minimumDate: "Första tillgängliga datum",
2265
+ maximumDate: "Sista tillgängliga datum",
2266
+ dateRange: say("{startDate} till {endDate}"),
2267
+ },
2268
+ "tr-TR": {
2269
+ previous: "Önceki",
2270
+ next: "Sonraki",
2271
+ selectedDateDescription: say("Seçilen Tarih: {date}"),
2272
+ selectedRangeDescription: say("Seçilen Aralık: {dateRange}"),
2273
+ todayDate: say("Bugün, {date}"),
2274
+ todayDateSelected: say("Bugün, {date} seçildi"),
2275
+ dateSelected: say("{date} seçildi"),
2276
+ minimumDate: "İlk müsait tarih",
2277
+ maximumDate: "Son müsait tarih",
2278
+ dateRange: say("{startDate} - {endDate}"),
2279
+ },
2280
+ "uk-UA": {
2281
+ previous: "Попередній",
2282
+ next: "Наступний",
2283
+ selectedDateDescription: say("Вибрана дата: {date}"),
2284
+ selectedRangeDescription: say("Вибраний діапазон: {dateRange}"),
2285
+ todayDate: say("Сьогодні, {date}"),
2286
+ todayDateSelected: say("Сьогодні, вибрано {date}"),
2287
+ dateSelected: say("Вибрано {date}"),
2288
+ minimumDate: "Перша доступна дата",
2289
+ maximumDate: "Остання доступна дата",
2290
+ dateRange: say("{startDate} — {endDate}"),
2291
+ },
2292
+ "zh-CN": {
2293
+ previous: "上一页",
2294
+ next: "下一页",
2295
+ selectedDateDescription: say("选定的日期:{date}"),
2296
+ selectedRangeDescription: say("选定的范围:{dateRange}"),
2297
+ todayDate: say("今天,即 {date}"),
2298
+ todayDateSelected: say("已选择今天,即 {date}"),
2299
+ dateSelected: say("已选择 {date}"),
2300
+ minimumDate: "第一个可用日期",
2301
+ maximumDate: "最后一个可用日期",
2302
+ dateRange: say("{startDate} 至 {endDate}"),
2303
+ },
2304
+ "zh-TW": {
2305
+ previous: "上一頁",
2306
+ next: "下一頁",
2307
+ selectedDateDescription: say("選定的日期:{date}"),
2308
+ selectedRangeDescription: say("選定的範圍:{dateRange}"),
2309
+ todayDate: say("今天,{date}"),
2310
+ todayDateSelected: say("已選取今天,{date}"),
2311
+ dateSelected: say("已選取 {date}"),
2312
+ minimumDate: "第一個可用日期",
2313
+ maximumDate: "最後一個可用日期",
2314
+ dateRange: say("{startDate} 至 {endDate}"),
2315
+ },
2316
+ });