@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
package/src/date.ts ADDED
@@ -0,0 +1,674 @@
1
+ /**
2
+ * Dates as VALUES: a calendar day, a wall-clock time, and the two together.
3
+ *
4
+ * `Date` is an instant — a number of milliseconds — and every calendar bug in
5
+ * every application comes from using one where a DAY was meant. "The 3rd of
6
+ * March" is not an instant: it starts at a different moment in every time
7
+ * zone, it has no hour, and adding a month to it is not adding 30 days. So:
8
+ *
9
+ * - {@link CalendarDate} is a year, a month and a day. No time, no zone.
10
+ * - {@link Time} is an hour, a minute, a second. No day, no zone.
11
+ * - {@link CalendarDateTime} is both. Still no zone: it is what a clock on the
12
+ * wall says, which is what a meeting invitation means.
13
+ *
14
+ * All three are immutable. Every operation returns a new one, so a value can
15
+ * be held in a signal and compared by content.
16
+ *
17
+ * **The calendar is the proleptic Gregorian one, and only that.** Other
18
+ * calendar systems — Hebrew, Islamic, Japanese, Buddhist — change the number
19
+ * of months in a year and the era a year belongs to, and pretending to support
20
+ * them by relabelling Gregorian months is worse than not supporting them.
21
+ * Time zones are absent for the same reason: a correct implementation needs
22
+ * the IANA database, and `Intl.DateTimeFormat` is the only piece of it a
23
+ * browser exposes.
24
+ */
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Days
28
+ // ---------------------------------------------------------------------------
29
+
30
+ export type DateUnit = "year" | "month" | "day";
31
+ export type TimeUnit = "hour" | "minute" | "second" | "millisecond";
32
+ export type DateTimeUnit = DateUnit | TimeUnit;
33
+
34
+ /** Whether a year has 366 days, in the proleptic Gregorian calendar. */
35
+ export function isLeapYear(year: number): boolean {
36
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
37
+ }
38
+
39
+ const MONTH_LENGTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
40
+
41
+ export function getDaysInMonth(year: number, month: number): number {
42
+ if (month === 2) return isLeapYear(year) ? 29 : 28;
43
+ return MONTH_LENGTHS[month - 1] ?? 30;
44
+ }
45
+
46
+ /**
47
+ * Days since 1970-01-01, from a year, month and day.
48
+ *
49
+ * Arithmetic on the day NUMBER rather than on a `Date`, because `Date` applies
50
+ * the local zone's offset and a date near a daylight-saving boundary then
51
+ * lands on the wrong day.
52
+ */
53
+ function toEpochDay(year: number, month: number, day: number): number {
54
+ // Howard Hinnant's civil-from-days, inverted. Shifting the year to start in
55
+ // March makes the leap day the LAST day of the year, which removes every
56
+ // special case from the arithmetic.
57
+ const shifted = month <= 2 ? year - 1 : year;
58
+ const era = Math.floor((shifted >= 0 ? shifted : shifted - 399) / 400);
59
+ const yearOfEra = shifted - era * 400;
60
+ const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
61
+ const dayOfEra =
62
+ yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
63
+ return era * 146097 + dayOfEra - 719468;
64
+ }
65
+
66
+ function fromEpochDay(epochDay: number): [number, number, number] {
67
+ const shifted = epochDay + 719468;
68
+ const era = Math.floor((shifted >= 0 ? shifted : shifted - 146096) / 146097);
69
+ const dayOfEra = shifted - era * 146097;
70
+ const yearOfEra = Math.floor(
71
+ (dayOfEra -
72
+ Math.floor(dayOfEra / 1460) +
73
+ Math.floor(dayOfEra / 36524) -
74
+ Math.floor(dayOfEra / 146096)) /
75
+ 365,
76
+ );
77
+ const year = yearOfEra + era * 400;
78
+ const dayOfYear =
79
+ dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
80
+ const monthOfShiftedYear = Math.floor((5 * dayOfYear + 2) / 153);
81
+ const day = dayOfYear - Math.floor((153 * monthOfShiftedYear + 2) / 5) + 1;
82
+ const month = monthOfShiftedYear + (monthOfShiftedYear < 10 ? 3 : -9);
83
+ return [month <= 2 ? year + 1 : year, month, day];
84
+ }
85
+
86
+ function within(value: number, min: number, max: number): number {
87
+ return Math.min(Math.max(value, min), max);
88
+ }
89
+
90
+ function pad(value: number, width: number): string {
91
+ return String(Math.abs(value)).padStart(width, "0");
92
+ }
93
+
94
+ /** A day in the calendar. No time, no zone. */
95
+ export class CalendarDate {
96
+ readonly year: number;
97
+ readonly month: number;
98
+ readonly day: number;
99
+
100
+ constructor(year: number, month: number, day: number) {
101
+ this.year = year;
102
+ this.month = month;
103
+ this.day = day;
104
+ }
105
+
106
+ /** Days since 1970-01-01, which is what every comparison reduces to. */
107
+ get epochDay(): number {
108
+ return toEpochDay(this.year, this.month, this.day);
109
+ }
110
+
111
+ copy(): CalendarDate {
112
+ return new CalendarDate(this.year, this.month, this.day);
113
+ }
114
+
115
+ /**
116
+ * A field replaced, with the day CONSTRAINED to the resulting month.
117
+ *
118
+ * Setting the month of the 31st of January to February has to answer with a
119
+ * day that exists; the 28th is the only sensible one, and silently producing
120
+ * the 3rd of March is how "set the month" turns into "skip a month".
121
+ */
122
+ set(fields: Partial<Record<DateUnit, number>>): CalendarDate {
123
+ const year = fields.year ?? this.year;
124
+ const month = Math.min(Math.max(fields.month ?? this.month, 1), 12);
125
+ const day = Math.min(fields.day ?? this.day, getDaysInMonth(year, month));
126
+ return new CalendarDate(year, month, Math.max(day, 1));
127
+ }
128
+
129
+ /**
130
+ * A duration added, months before days.
131
+ *
132
+ * The order matters and the standard fixes it: adding one month and one day
133
+ * to the 31st of January is the 28th of February plus a day, not the 1st of
134
+ * March plus a month.
135
+ */
136
+ add(duration: { years?: number; months?: number; weeks?: number; days?: number }): CalendarDate {
137
+ let year = this.year + (duration.years ?? 0);
138
+ let month = this.month + (duration.months ?? 0);
139
+
140
+ year += Math.floor((month - 1) / 12);
141
+ month = ((((month - 1) % 12) + 12) % 12) + 1;
142
+
143
+ const day = Math.min(this.day, getDaysInMonth(year, month));
144
+ const days = (duration.days ?? 0) + (duration.weeks ?? 0) * 7;
145
+ if (days === 0) return new CalendarDate(year, month, day);
146
+
147
+ const [nextYear, nextMonth, nextDay] = fromEpochDay(toEpochDay(year, month, day) + days);
148
+ return new CalendarDate(nextYear, nextMonth, nextDay);
149
+ }
150
+
151
+ subtract(duration: {
152
+ years?: number;
153
+ months?: number;
154
+ weeks?: number;
155
+ days?: number;
156
+ }): CalendarDate {
157
+ return this.add({
158
+ years: -(duration.years ?? 0),
159
+ months: -(duration.months ?? 0),
160
+ weeks: -(duration.weeks ?? 0),
161
+ days: -(duration.days ?? 0),
162
+ });
163
+ }
164
+
165
+ /**
166
+ * One field stepped, wrapping within itself and leaving the others alone.
167
+ *
168
+ * What the up and down arrows in a date field do: December plus one is
169
+ * January of the SAME year, because the user is editing the month segment
170
+ * and not the date.
171
+ */
172
+ cycle(field: DateUnit, amount: number, options: { round?: boolean } = {}): CalendarDate {
173
+ if (field === "year") {
174
+ const year = this.year + amount;
175
+ return this.set({ year, day: Math.min(this.day, getDaysInMonth(year, this.month)) });
176
+ }
177
+
178
+ const limit = field === "month" ? 12 : getDaysInMonth(this.year, this.month);
179
+ let value = field === "month" ? this.month : this.day;
180
+
181
+ if (options.round === true && amount !== 0) {
182
+ // Rounding first: from 7 with a step of 5, up goes to 10 rather than 12.
183
+ value = Math.floor(value / Math.abs(amount)) * Math.abs(amount);
184
+ if (amount > 0) value += Math.abs(amount);
185
+ else if (value === (field === "month" ? this.month : this.day)) value -= Math.abs(amount);
186
+ } else {
187
+ value += amount;
188
+ }
189
+
190
+ // Wraps within the field: 1 to 12 and back to 1.
191
+ value = ((((value - 1) % limit) + limit) % limit) + 1;
192
+ return field === "month" ? this.set({ month: value, day: this.day }) : this.set({ day: value });
193
+ }
194
+
195
+ compare(other: CalendarDate | CalendarDateTime): number {
196
+ const day = other instanceof CalendarDateTime ? other.date : other;
197
+ return this.epochDay - day.epochDay;
198
+ }
199
+
200
+ /** ISO 8601, which is what a form submits and a URL carries. */
201
+ toString(): string {
202
+ const sign = this.year < 0 ? "-" : "";
203
+ return `${sign}${pad(this.year, 4)}-${pad(this.month, 2)}-${pad(this.day, 2)}`;
204
+ }
205
+
206
+ /** Midnight on this day, in the LOCAL zone. The one place a zone enters. */
207
+ toDate(): Date {
208
+ const date = new Date(0);
209
+ date.setFullYear(this.year, this.month - 1, this.day);
210
+ date.setHours(0, 0, 0, 0);
211
+ return date;
212
+ }
213
+ }
214
+
215
+ /** A wall-clock time. No day, no zone. */
216
+ export class Time {
217
+ readonly hour: number;
218
+ readonly minute: number;
219
+ readonly second: number;
220
+ readonly millisecond: number;
221
+
222
+ constructor(hour = 0, minute = 0, second = 0, millisecond = 0) {
223
+ this.hour = within(hour, 0, 23);
224
+ this.minute = within(minute, 0, 59);
225
+ this.second = within(second, 0, 59);
226
+ this.millisecond = within(millisecond, 0, 999);
227
+ }
228
+
229
+ set(fields: Partial<Record<TimeUnit, number>>): Time {
230
+ return new Time(
231
+ fields.hour ?? this.hour,
232
+ fields.minute ?? this.minute,
233
+ fields.second ?? this.second,
234
+ fields.millisecond ?? this.millisecond,
235
+ );
236
+ }
237
+
238
+ /** One field stepped, wrapping within itself. 23:59 plus a minute is 23:00. */
239
+ cycle(field: TimeUnit, amount: number, options: { round?: boolean } = {}): Time {
240
+ const limits: Record<TimeUnit, number> = {
241
+ hour: 24,
242
+ minute: 60,
243
+ second: 60,
244
+ millisecond: 1000,
245
+ };
246
+ const limit = limits[field];
247
+ let value = this[field];
248
+
249
+ if (options.round === true && amount !== 0) {
250
+ const step = Math.abs(amount);
251
+ const rounded = Math.floor(value / step) * step;
252
+ value = amount > 0 ? rounded + step : rounded === value ? value - step : rounded;
253
+ } else {
254
+ value += amount;
255
+ }
256
+
257
+ return this.set({ [field]: ((value % limit) + limit) % limit });
258
+ }
259
+
260
+ compare(other: Time): number {
261
+ return (
262
+ this.hour * 3600000 +
263
+ this.minute * 60000 +
264
+ this.second * 1000 +
265
+ this.millisecond -
266
+ (other.hour * 3600000 + other.minute * 60000 + other.second * 1000 + other.millisecond)
267
+ );
268
+ }
269
+
270
+ toString(): string {
271
+ const base = `${pad(this.hour, 2)}:${pad(this.minute, 2)}:${pad(this.second, 2)}`;
272
+ return this.millisecond === 0 ? base : `${base}.${pad(this.millisecond, 3)}`;
273
+ }
274
+ }
275
+
276
+ /** A day and a wall-clock time. Still no zone. */
277
+ export class CalendarDateTime {
278
+ readonly date: CalendarDate;
279
+ readonly time: Time;
280
+
281
+ constructor(
282
+ year: number,
283
+ month: number,
284
+ day: number,
285
+ hour = 0,
286
+ minute = 0,
287
+ second = 0,
288
+ millisecond = 0,
289
+ ) {
290
+ this.date = new CalendarDate(year, month, day);
291
+ this.time = new Time(hour, minute, second, millisecond);
292
+ }
293
+
294
+ static from(date: CalendarDate, time: Time = new Time()): CalendarDateTime {
295
+ return new CalendarDateTime(
296
+ date.year,
297
+ date.month,
298
+ date.day,
299
+ time.hour,
300
+ time.minute,
301
+ time.second,
302
+ time.millisecond,
303
+ );
304
+ }
305
+
306
+ get year(): number {
307
+ return this.date.year;
308
+ }
309
+ get month(): number {
310
+ return this.date.month;
311
+ }
312
+ get day(): number {
313
+ return this.date.day;
314
+ }
315
+ get hour(): number {
316
+ return this.time.hour;
317
+ }
318
+ get minute(): number {
319
+ return this.time.minute;
320
+ }
321
+ get second(): number {
322
+ return this.time.second;
323
+ }
324
+ get millisecond(): number {
325
+ return this.time.millisecond;
326
+ }
327
+
328
+ set(fields: Partial<Record<DateTimeUnit, number>>): CalendarDateTime {
329
+ return CalendarDateTime.from(this.date.set(fields), this.time.set(fields));
330
+ }
331
+
332
+ add(duration: {
333
+ years?: number;
334
+ months?: number;
335
+ weeks?: number;
336
+ days?: number;
337
+ }): CalendarDateTime {
338
+ return CalendarDateTime.from(this.date.add(duration), this.time);
339
+ }
340
+
341
+ subtract(duration: {
342
+ years?: number;
343
+ months?: number;
344
+ weeks?: number;
345
+ days?: number;
346
+ }): CalendarDateTime {
347
+ return CalendarDateTime.from(this.date.subtract(duration), this.time);
348
+ }
349
+
350
+ cycle(field: DateTimeUnit, amount: number, options: { round?: boolean } = {}): CalendarDateTime {
351
+ if (field === "year" || field === "month" || field === "day") {
352
+ return CalendarDateTime.from(this.date.cycle(field, amount, options), this.time);
353
+ }
354
+ return CalendarDateTime.from(this.date, this.time.cycle(field, amount, options));
355
+ }
356
+
357
+ compare(other: CalendarDate | CalendarDateTime): number {
358
+ const days = this.date.compare(other);
359
+ if (days !== 0) return days;
360
+ return other instanceof CalendarDateTime ? this.time.compare(other.time) : 0;
361
+ }
362
+
363
+ toString(): string {
364
+ return `${this.date.toString()}T${this.time.toString()}`;
365
+ }
366
+
367
+ toDate(): Date {
368
+ const date = this.date.toDate();
369
+ date.setHours(this.hour, this.minute, this.second, this.millisecond);
370
+ return date;
371
+ }
372
+ }
373
+
374
+ export type DateValue = CalendarDate | CalendarDateTime;
375
+
376
+ // ---------------------------------------------------------------------------
377
+ // Reading and writing
378
+ // ---------------------------------------------------------------------------
379
+
380
+ const DATE_PATTERN = /^(-?\d{4,})-(\d{2})-(\d{2})$/;
381
+ const TIME_PATTERN = /^(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/;
382
+
383
+ /** A field of a parsed string, refused when it names something that does not exist. */
384
+ function checked(text: string, min: number, max: number, value: string, kind: string): number {
385
+ const number = Number(text);
386
+ if (number < min || number > max) {
387
+ throw new RangeError(`Not an ISO 8601 ${kind}: ${JSON.stringify(value)}`);
388
+ }
389
+ return number;
390
+ }
391
+
392
+ /**
393
+ * An ISO date, or a throw naming what was given.
394
+ *
395
+ * The 31st of February is refused rather than read as the 3rd of March: a
396
+ * string that names a day that does not exist is a mistake somewhere, and
397
+ * rolling it over hides the mistake inside a plausible date.
398
+ */
399
+ export function parseDate(value: string): CalendarDate {
400
+ const match = DATE_PATTERN.exec(value);
401
+ if (match === null) throw new RangeError(`Not an ISO 8601 date: ${JSON.stringify(value)}`);
402
+ const year = Number(match[1]);
403
+ const month = checked(match[2] as string, 1, 12, value, "date");
404
+ const day = checked(match[3] as string, 1, getDaysInMonth(year, month), value, "date");
405
+ return new CalendarDate(year, month, day);
406
+ }
407
+
408
+ export function parseTime(value: string): Time {
409
+ const match = TIME_PATTERN.exec(value);
410
+ if (match === null) throw new RangeError(`Not an ISO 8601 time: ${JSON.stringify(value)}`);
411
+ return new Time(
412
+ checked(match[1] as string, 0, 23, value, "time"),
413
+ checked(match[2] as string, 0, 59, value, "time"),
414
+ checked(match[3] ?? "0", 0, 59, value, "time"),
415
+ Number((match[4] ?? "0").padEnd(3, "0")),
416
+ );
417
+ }
418
+
419
+ export function parseDateTime(value: string): CalendarDateTime {
420
+ const [date = "", time = "00:00"] = value.split("T");
421
+ return CalendarDateTime.from(parseDate(date), parseTime(time));
422
+ }
423
+
424
+ const zoneFormatters = new Map<string, Intl.DateTimeFormat>();
425
+
426
+ /**
427
+ * Today, as the LOCAL zone reckons it, or as a named IANA zone does.
428
+ *
429
+ * The one question about a zone a calendar of days has to answer: which day it
430
+ * is there right now. `Intl.DateTimeFormat` is the only part of the IANA
431
+ * database a browser exposes, and it is enough for this.
432
+ */
433
+ export function today(timeZone?: string): CalendarDate {
434
+ const at = new Date();
435
+ if (timeZone === undefined) {
436
+ return new CalendarDate(at.getFullYear(), at.getMonth() + 1, at.getDate());
437
+ }
438
+
439
+ let format = zoneFormatters.get(timeZone);
440
+ if (format === undefined) {
441
+ format = new Intl.DateTimeFormat("en-US", {
442
+ timeZone,
443
+ calendar: "gregory",
444
+ numberingSystem: "latn",
445
+ year: "numeric",
446
+ month: "numeric",
447
+ day: "numeric",
448
+ });
449
+ zoneFormatters.set(timeZone, format);
450
+ }
451
+
452
+ const fields = { year: 0, month: 0, day: 0 };
453
+ for (const part of format.formatToParts(at)) {
454
+ if (part.type === "year" || part.type === "month" || part.type === "day") {
455
+ fields[part.type] = Number(part.value);
456
+ }
457
+ }
458
+ return new CalendarDate(fields.year, fields.month, fields.day);
459
+ }
460
+
461
+ /** The wall-clock time now, as the local zone reckons it. */
462
+ export function now(): Time {
463
+ const at = new Date();
464
+ return new Time(at.getHours(), at.getMinutes(), at.getSeconds(), at.getMilliseconds());
465
+ }
466
+
467
+ /** The day part of either kind of value. */
468
+ export function toCalendarDate(value: DateValue): CalendarDate {
469
+ return value instanceof CalendarDateTime ? value.date : value;
470
+ }
471
+
472
+ // ---------------------------------------------------------------------------
473
+ // Weeks and months
474
+ // ---------------------------------------------------------------------------
475
+
476
+ /** 0 for Sunday, as `Date.getDay` numbers them. */
477
+ export function getDayOfWeek(date: DateValue, firstDayOfWeek = 0): number {
478
+ const day = toCalendarDate(date);
479
+ // 1970-01-01 was a Thursday, which is 4.
480
+ const absolute = (((day.epochDay + 4) % 7) + 7) % 7;
481
+ return (((absolute - firstDayOfWeek) % 7) + 7) % 7;
482
+ }
483
+
484
+ export function startOfMonth(date: DateValue): CalendarDate {
485
+ const day = toCalendarDate(date);
486
+ return new CalendarDate(day.year, day.month, 1);
487
+ }
488
+
489
+ export function endOfMonth(date: DateValue): CalendarDate {
490
+ const day = toCalendarDate(date);
491
+ return new CalendarDate(day.year, day.month, getDaysInMonth(day.year, day.month));
492
+ }
493
+
494
+ export function startOfWeek(date: DateValue, firstDayOfWeek = 0): CalendarDate {
495
+ const day = toCalendarDate(date);
496
+ return day.subtract({ days: getDayOfWeek(day, firstDayOfWeek) });
497
+ }
498
+
499
+ export function endOfWeek(date: DateValue, firstDayOfWeek = 0): CalendarDate {
500
+ return startOfWeek(date, firstDayOfWeek).add({ days: 6 });
501
+ }
502
+
503
+ export function startOfYear(date: DateValue): CalendarDate {
504
+ return new CalendarDate(toCalendarDate(date).year, 1, 1);
505
+ }
506
+
507
+ export function endOfYear(date: DateValue): CalendarDate {
508
+ return new CalendarDate(toCalendarDate(date).year, 12, 31);
509
+ }
510
+
511
+ /**
512
+ * How many week rows a month needs.
513
+ *
514
+ * Not always the same: a 31-day month beginning on the last day of a week
515
+ * spans six rows, and a calendar sized for five leaves the last days off.
516
+ */
517
+ export function getWeeksInMonth(date: DateValue, firstDayOfWeek = 0): number {
518
+ const first = startOfMonth(date);
519
+ const days = getDaysInMonth(first.year, first.month);
520
+ return Math.ceil((getDayOfWeek(first, firstDayOfWeek) + days) / 7);
521
+ }
522
+
523
+ export function isSameDay(a: DateValue, b: DateValue): boolean {
524
+ const left = toCalendarDate(a);
525
+ const right = toCalendarDate(b);
526
+ return left.year === right.year && left.month === right.month && left.day === right.day;
527
+ }
528
+
529
+ export function isSameMonth(a: DateValue, b: DateValue): boolean {
530
+ const left = toCalendarDate(a);
531
+ const right = toCalendarDate(b);
532
+ return left.year === right.year && left.month === right.month;
533
+ }
534
+
535
+ export function isToday(date: DateValue, timeZone?: string): boolean {
536
+ return isSameDay(date, today(timeZone));
537
+ }
538
+
539
+ /**
540
+ * Which week of its year a day is in.
541
+ *
542
+ * Two numbers decide it and locales disagree about both: the day a week begins
543
+ * on, and how early in January a day must fall for its week to count as the
544
+ * first. The United States begins on Sunday and counts the week holding 1
545
+ * January; ISO 8601 begins on Monday and counts the week holding 4 January,
546
+ * which is the first with most of its days in the new year.
547
+ *
548
+ * A day at either end of a year can belong to a week of the year beside it.
549
+ */
550
+ export function getWeekOfYear(
551
+ date: DateValue,
552
+ firstDayOfWeek = 0,
553
+ firstWeekContainsDate = 1,
554
+ ): number {
555
+ const day = toCalendarDate(date);
556
+ const firstWeekOf = (year: number): CalendarDate =>
557
+ startOfWeek(new CalendarDate(year, 1, firstWeekContainsDate), firstDayOfWeek);
558
+
559
+ let first = firstWeekOf(day.year + 1);
560
+ if (day.compare(first) < 0) {
561
+ first = firstWeekOf(day.year);
562
+ if (day.compare(first) < 0) first = firstWeekOf(day.year - 1);
563
+ }
564
+ return Math.floor((day.epochDay - first.epochDay) / 7) + 1;
565
+ }
566
+
567
+ /** The ISO 8601 week: Monday first, and week 1 is the one holding 4 January. */
568
+ export function getISOWeek(date: DateValue): number {
569
+ return getWeekOfYear(date, 1, 4);
570
+ }
571
+
572
+ interface WeekInfo {
573
+ firstDay?: number;
574
+ weekend?: number[];
575
+ minimalDays?: number;
576
+ }
577
+
578
+ /**
579
+ * What `Intl.Locale` knows about a locale's week, or nothing.
580
+ *
581
+ * The specification settled on a `getWeekInfo()` method after engines had
582
+ * shipped a `weekInfo` getter, and each engine has one or the other.
583
+ */
584
+ function weekInfo(locale: string): WeekInfo | undefined {
585
+ if (typeof Intl.Locale !== "function") return undefined;
586
+ try {
587
+ const info: { getWeekInfo?: () => WeekInfo; weekInfo?: WeekInfo } = new Intl.Locale(locale);
588
+ return typeof info.getWeekInfo === "function" ? info.getWeekInfo() : info.weekInfo;
589
+ } catch {
590
+ // A tag the engine will not take.
591
+ return undefined;
592
+ }
593
+ }
594
+
595
+ /**
596
+ * Which days a locale counts as the weekend.
597
+ *
598
+ * Not Saturday and Sunday everywhere: Friday and Saturday in much of the
599
+ * Middle East, Sunday alone in parts of Asia. `Intl.Locale` knows, where the
600
+ * browser implements it; the fallback is the most common pair.
601
+ */
602
+ export function getWeekendDays(locale: string): number[] {
603
+ // The week is numbered Monday as 1 and Sunday as 7; `getDay` numbers
604
+ // Sunday as 0.
605
+ const weekend = weekInfo(locale)?.weekend;
606
+ return weekend === undefined ? [0, 6] : weekend.map((day) => day % 7);
607
+ }
608
+
609
+ export function isWeekend(date: DateValue, locale: string): boolean {
610
+ return getWeekendDays(locale).includes(getDayOfWeek(date, 0));
611
+ }
612
+
613
+ /**
614
+ * The first day of the week in a locale.
615
+ *
616
+ * Sunday in the United States, Monday across most of Europe, Saturday in much
617
+ * of the Middle East. Getting it wrong shifts every date in the grid by a
618
+ * column, which reads as the calendar being simply wrong.
619
+ */
620
+ export function getFirstDayOfWeek(locale: string): number {
621
+ const first = weekInfo(locale)?.firstDay;
622
+ return first === undefined ? 0 : first % 7;
623
+ }
624
+
625
+ /**
626
+ * How many days of a week must fall in a year for it to be that year's first.
627
+ *
628
+ * One in the United States, four wherever ISO 8601 is followed. It is also the
629
+ * day of January the first week always holds, which is the form
630
+ * {@link getWeekOfYear} takes it in.
631
+ *
632
+ * `Intl.Locale` stopped reporting this, so where the engine gives nothing a
633
+ * week that begins on Monday is taken to be an ISO one. That is right for
634
+ * Europe and wrong for a few Monday-first locales that count from 1 January;
635
+ * a caller who needs a particular rule passes it to {@link getWeekOfYear}.
636
+ */
637
+ export function getMinimalDaysInFirstWeek(locale: string): number {
638
+ const info = weekInfo(locale);
639
+ if (info?.minimalDays !== undefined) return info.minimalDays;
640
+ return info?.firstDay === 1 ? 4 : 1;
641
+ }
642
+
643
+ /** `value` held between `min` and `max`, either of which may be absent. */
644
+ export function constrainDate<T extends DateValue>(
645
+ value: T,
646
+ minValue?: DateValue | null,
647
+ maxValue?: DateValue | null,
648
+ ): T {
649
+ if (minValue !== undefined && minValue !== null && value.compare(minValue) < 0) {
650
+ return (
651
+ value instanceof CalendarDateTime
652
+ ? CalendarDateTime.from(toCalendarDate(minValue), value.time)
653
+ : toCalendarDate(minValue)
654
+ ) as T;
655
+ }
656
+ if (maxValue !== undefined && maxValue !== null && value.compare(maxValue) > 0) {
657
+ return (
658
+ value instanceof CalendarDateTime
659
+ ? CalendarDateTime.from(toCalendarDate(maxValue), value.time)
660
+ : toCalendarDate(maxValue)
661
+ ) as T;
662
+ }
663
+ return value;
664
+ }
665
+
666
+ export function isDateUnavailable(
667
+ date: DateValue,
668
+ minValue?: DateValue | null,
669
+ maxValue?: DateValue | null,
670
+ ): boolean {
671
+ if (minValue !== undefined && minValue !== null && date.compare(minValue) < 0) return true;
672
+ if (maxValue !== undefined && maxValue !== null && date.compare(maxValue) > 0) return true;
673
+ return false;
674
+ }