@klinking/colander 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/formats/date.cjs +49 -0
  2. package/dist/formats/date.d.cts +45 -0
  3. package/dist/formats/date.d.mts +45 -0
  4. package/dist/formats/date.mjs +2 -0
  5. package/dist/formats/object.cjs +49 -0
  6. package/dist/formats/object.d.cts +45 -0
  7. package/dist/formats/object.d.mts +45 -0
  8. package/dist/formats/object.mjs +2 -0
  9. package/dist/formats/plain-date-time.cjs +49 -0
  10. package/dist/formats/plain-date-time.d.cts +45 -0
  11. package/dist/formats/plain-date-time.d.mts +45 -0
  12. package/dist/formats/plain-date-time.mjs +2 -0
  13. package/dist/formats/plain-date.cjs +49 -0
  14. package/dist/formats/plain-date.d.cts +45 -0
  15. package/dist/formats/plain-date.d.mts +45 -0
  16. package/dist/formats/plain-date.mjs +2 -0
  17. package/dist/formats/plain-month-day.cjs +49 -0
  18. package/dist/formats/plain-month-day.d.cts +45 -0
  19. package/dist/formats/plain-month-day.d.mts +45 -0
  20. package/dist/formats/plain-month-day.mjs +2 -0
  21. package/dist/formats/plain-year-month.cjs +49 -0
  22. package/dist/formats/plain-year-month.d.cts +45 -0
  23. package/dist/formats/plain-year-month.d.mts +45 -0
  24. package/dist/formats/plain-year-month.mjs +2 -0
  25. package/dist/formats/zoned-date-time.cjs +49 -0
  26. package/dist/formats/zoned-date-time.d.cts +45 -0
  27. package/dist/formats/zoned-date-time.d.mts +45 -0
  28. package/dist/formats/zoned-date-time.mjs +2 -0
  29. package/dist/index.cjs +49 -0
  30. package/dist/index.d.cts +2 -0
  31. package/dist/index.d.mts +2 -0
  32. package/dist/index.mjs +2 -0
  33. package/dist/temporal-polyfill-DTx0VIX5.mjs +4556 -0
  34. package/dist/temporal-polyfill-DU8VfleL.cjs +4860 -0
  35. package/dist/weeks-view-context-BN6qR-83.d.mts +2022 -0
  36. package/dist/weeks-view-context-aHGgYkpt.d.cts +2022 -0
  37. package/package.json +89 -0
  38. package/src/calendar-context.ts +22 -0
  39. package/src/calendar-provider.test.tsx +123 -0
  40. package/src/calendar-provider.tsx +538 -0
  41. package/src/calendar-types.ts +212 -0
  42. package/src/compute-weeks-in-window.test.ts +83 -0
  43. package/src/compute-weeks-in-window.ts +40 -0
  44. package/src/context.ts +34 -0
  45. package/src/day-cell.tsx +635 -0
  46. package/src/drag-handle.tsx +137 -0
  47. package/src/formats/date.ts +110 -0
  48. package/src/formats/formats.test.ts +18 -0
  49. package/src/formats/object.ts +110 -0
  50. package/src/formats/plain-date-time.ts +110 -0
  51. package/src/formats/plain-date.ts +110 -0
  52. package/src/formats/plain-month-day.ts +110 -0
  53. package/src/formats/plain-year-month.ts +110 -0
  54. package/src/formats/zoned-date-time.ts +110 -0
  55. package/src/grid-header.tsx +141 -0
  56. package/src/grid.event-perf.test.tsx +282 -0
  57. package/src/grid.perf.test.tsx +467 -0
  58. package/src/grid.tsx +608 -0
  59. package/src/index.ts +116 -0
  60. package/src/keyboard.test.ts +498 -0
  61. package/src/keyboard.ts +142 -0
  62. package/src/month-separator.test.tsx +183 -0
  63. package/src/month-separator.tsx +238 -0
  64. package/src/month-view-context.ts +26 -0
  65. package/src/month-view-types.ts +89 -0
  66. package/src/month-view.test.tsx +1433 -0
  67. package/src/month-view.tsx +373 -0
  68. package/src/navigation.tsx +350 -0
  69. package/src/overflow.test.ts +124 -0
  70. package/src/overflow.ts +233 -0
  71. package/src/range-preview.tsx +90 -0
  72. package/src/resolve-first-week.test.ts +132 -0
  73. package/src/resolve-first-week.ts +145 -0
  74. package/src/root-selection.ts +621 -0
  75. package/src/selected-range.tsx +163 -0
  76. package/src/temporal-polyfill.test.ts +317 -0
  77. package/src/temporal-polyfill.ts +566 -0
  78. package/src/test-temporal.ts +17 -0
  79. package/src/types.ts +814 -0
  80. package/src/utils.bench.ts +183 -0
  81. package/src/utils.test.ts +983 -0
  82. package/src/utils.ts +493 -0
  83. package/src/view-context.ts +28 -0
  84. package/src/week-number.tsx +118 -0
  85. package/src/weeks-grid.tsx +265 -0
  86. package/src/weeks-keyboard.test.ts +222 -0
  87. package/src/weeks-keyboard.ts +156 -0
  88. package/src/weeks-navigation.tsx +209 -0
  89. package/src/weeks-view-context.ts +26 -0
  90. package/src/weeks-view-state.ts +421 -0
  91. package/src/weeks-view-types.ts +102 -0
  92. package/src/weeks-view.test.tsx +479 -0
  93. package/src/weeks-view.tsx +127 -0
package/src/utils.ts ADDED
@@ -0,0 +1,493 @@
1
+ import type { Temporal } from "@js-temporal/polyfill";
2
+ import type { TemporalNamespace, DateValueObject, ValueFormat, WeekStartDay } from "./types";
3
+
4
+ /**
5
+ * Returns the default calendar system for a given locale (e.g. `"gregory"` for `"en-US"`).
6
+ *
7
+ * @param locale - A BCP 47 locale string. Falls back to the runtime default when empty.
8
+ */
9
+ export function calendarForLocale(locale: string): string {
10
+ return new Intl.DateTimeFormat(locale || undefined).resolvedOptions().calendar;
11
+ }
12
+
13
+ /**
14
+ * Resolves a {@link TemporalNamespace} instance.
15
+ *
16
+ * Returns `provided` when given, otherwise checks `globalThis.Temporal`.
17
+ * Throws if neither is available.
18
+ *
19
+ * @param provided - An explicit Temporal polyfill or namespace.
20
+ */
21
+ export function resolveTemporal(provided?: TemporalNamespace): TemporalNamespace {
22
+ if (provided) return provided;
23
+ if (typeof globalThis !== "undefined" && (globalThis as any).Temporal) {
24
+ return (globalThis as any).Temporal;
25
+ }
26
+ throw new Error(
27
+ "DatePicker: Temporal is not available. Pass a Temporal polyfill via the `temporal` prop, or use a browser that supports the Temporal API natively.",
28
+ );
29
+ }
30
+
31
+ /**
32
+ * Returns the IANA time zone identifier of the host environment (e.g. `"America/New_York"`).
33
+ *
34
+ * @param T - Temporal namespace.
35
+ */
36
+ export function getSystemTimeZone(T: TemporalNamespace): string {
37
+ return T.Now.timeZoneId();
38
+ }
39
+
40
+ /**
41
+ * Converts any {@link DateValueObject} into a `Temporal.ZonedDateTime`.
42
+ *
43
+ * Handles all supported value formats (`PlainDate`, `PlainDateTime`,
44
+ * `PlainMonthDay`, `PlainTime`, `PlainYearMonth`, `ZonedDateTime`,
45
+ * `object`, and `Date`). For partial types (`PlainMonthDay`, `PlainTime`)
46
+ * the missing components are filled from the current date/time.
47
+ *
48
+ * @param tagged - The tagged date value to convert.
49
+ * @param timeZone - IANA time zone used for the resulting `ZonedDateTime`.
50
+ * @param T - Temporal namespace.
51
+ */
52
+ export function toZonedDateTime(
53
+ tagged: DateValueObject,
54
+ timeZone: string,
55
+ T: TemporalNamespace,
56
+ ): Temporal.ZonedDateTime {
57
+ const now = T.Now.zonedDateTimeISO(timeZone);
58
+ switch (tagged.format) {
59
+ case "PlainDate":
60
+ return tagged.value.toZonedDateTime(timeZone);
61
+ case "PlainDateTime":
62
+ return tagged.value.toZonedDateTime(timeZone);
63
+ case "PlainMonthDay": {
64
+ const pd = tagged.value.toPlainDate({ year: now.year });
65
+ return pd.toZonedDateTime(timeZone);
66
+ }
67
+ case "PlainTime":
68
+ return now.toPlainDate().toPlainDateTime(tagged.value).toZonedDateTime(timeZone);
69
+ case "PlainYearMonth":
70
+ return tagged.value.toPlainDate({ day: 1 }).toZonedDateTime(timeZone);
71
+ case "ZonedDateTime":
72
+ return tagged.value;
73
+ case "object": {
74
+ const obj = tagged.value;
75
+ return T.PlainDateTime.from({
76
+ year: obj.year ?? now.year,
77
+ month: obj.month ?? now.month,
78
+ day: obj.day ?? now.day,
79
+ hour: obj.hour ?? 0,
80
+ minute: obj.minute ?? 0,
81
+ second: obj.second ?? 0,
82
+ }).toZonedDateTime(obj.timeZone ?? timeZone);
83
+ }
84
+ case "Date": {
85
+ const d = tagged.value;
86
+ return T.PlainDateTime.from({
87
+ year: d.getFullYear(),
88
+ month: d.getMonth() + 1,
89
+ day: d.getDate(),
90
+ hour: d.getHours(),
91
+ minute: d.getMinutes(),
92
+ second: d.getSeconds(),
93
+ }).toZonedDateTime(timeZone);
94
+ }
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Converts a `Temporal.ZonedDateTime` back into a {@link DateValueObject}
100
+ * of the requested format.
101
+ *
102
+ * This is the inverse of {@link toZonedDateTime}.
103
+ *
104
+ * @param zdt - The zoned date-time to convert from.
105
+ * @param format - The target {@link ValueFormat}.
106
+ * @param T - Temporal namespace.
107
+ */
108
+ export function fromZonedDateTime(
109
+ zdt: Temporal.ZonedDateTime,
110
+ format: ValueFormat,
111
+ T: TemporalNamespace,
112
+ ): DateValueObject {
113
+ switch (format) {
114
+ case "PlainDate":
115
+ return { format, value: zdt.toPlainDate() };
116
+ case "PlainDateTime":
117
+ return { format, value: zdt.toPlainDateTime() };
118
+ case "PlainMonthDay":
119
+ return {
120
+ format,
121
+ value: T.PlainMonthDay.from({ month: zdt.month, day: zdt.day }),
122
+ };
123
+ case "PlainTime":
124
+ return { format, value: zdt.toPlainTime() };
125
+ case "PlainYearMonth":
126
+ return {
127
+ format,
128
+ value: T.PlainYearMonth.from({ year: zdt.year, month: zdt.month }),
129
+ };
130
+ case "ZonedDateTime":
131
+ return { format, value: zdt };
132
+ case "object":
133
+ return {
134
+ format,
135
+ value: {
136
+ year: zdt.year,
137
+ month: zdt.month,
138
+ day: zdt.day,
139
+ hour: zdt.hour,
140
+ minute: zdt.minute,
141
+ second: zdt.second,
142
+ timeZone: zdt.timeZoneId,
143
+ },
144
+ };
145
+ case "Date":
146
+ return { format, value: new Date(zdt.epochMilliseconds) };
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Convenience wrapper around {@link toZonedDateTime} that accepts `undefined`.
152
+ *
153
+ * Returns `undefined` when `selected` is not provided, otherwise converts to
154
+ * a `Temporal.ZonedDateTime`.
155
+ *
156
+ * @param selected - The currently selected value, or `undefined`.
157
+ * @param timeZone - IANA time zone.
158
+ * @param T - Temporal namespace.
159
+ */
160
+ export function selectedToZdt(
161
+ selected: DateValueObject | undefined,
162
+ timeZone: string,
163
+ T: TemporalNamespace,
164
+ ): Temporal.ZonedDateTime | undefined {
165
+ if (!selected) return undefined;
166
+ return toZonedDateTime(selected, timeZone, T);
167
+ }
168
+
169
+ /**
170
+ * Builds a 2D array of calendar weeks for a given month.
171
+ *
172
+ * Each inner array has exactly `daysInWeek` entries. The grid is padded
173
+ * with days from adjacent months so every week is complete.
174
+ *
175
+ * @param year - Calendar year.
176
+ * @param month - Calendar month (1–12).
177
+ * @param T - Temporal namespace.
178
+ * @param opts - Optional settings for week start day and fixed weeks.
179
+ * @returns An array of 4–6 weeks, each containing `daysInWeek` `PlainDate` values.
180
+ */
181
+ export function getMonthWeeks(
182
+ year: number,
183
+ month: number,
184
+ T: TemporalNamespace,
185
+ opts?: { weekStartDay?: WeekStartDay; fixedWeeks?: boolean },
186
+ ): Temporal.PlainDate[][] {
187
+ const weekStartDay = opts?.weekStartDay ?? 0;
188
+ const fixedWeeks = opts?.fixedWeeks ?? false;
189
+
190
+ const firstOfMonth = T.PlainDate.from({ year, month, day: 1 });
191
+ const daysInWeek = firstOfMonth.daysInWeek;
192
+ const daysInMonth = firstOfMonth.daysInMonth;
193
+ const lastOfMonth = T.PlainDate.from({ year, month, day: daysInMonth });
194
+
195
+ const adjustedFirst =
196
+ ((firstOfMonth.dayOfWeek % daysInWeek) - weekStartDay + daysInWeek) % daysInWeek;
197
+ const gridStart = firstOfMonth.subtract({ days: adjustedFirst });
198
+
199
+ const adjustedLast =
200
+ ((lastOfMonth.dayOfWeek % daysInWeek) - weekStartDay + daysInWeek) % daysInWeek;
201
+ const daysAfter = daysInWeek - 1 - adjustedLast;
202
+ const gridEnd = lastOfMonth.add({ days: daysAfter });
203
+
204
+ const weeks: Temporal.PlainDate[][] = [];
205
+ let current = gridStart;
206
+ while (T.PlainDate.compare(current, gridEnd) <= 0) {
207
+ const week: Temporal.PlainDate[] = [];
208
+ for (let i = 0; i < daysInWeek; i++) {
209
+ week.push(current);
210
+ current = current.add({ days: 1 });
211
+ }
212
+ weeks.push(week);
213
+ }
214
+
215
+ if (fixedWeeks) {
216
+ while (weeks.length < 6) {
217
+ const week: Temporal.PlainDate[] = [];
218
+ for (let i = 0; i < daysInWeek; i++) {
219
+ week.push(current);
220
+ current = current.add({ days: 1 });
221
+ }
222
+ weeks.push(week);
223
+ }
224
+ }
225
+
226
+ return weeks;
227
+ }
228
+
229
+ /**
230
+ * Converts a `Temporal.ZonedDateTime` to a native JavaScript `Date`.
231
+ *
232
+ * @param zdt - The zoned date-time to convert.
233
+ */
234
+ export function zdtToNativeDate(zdt: Temporal.ZonedDateTime): Date {
235
+ return new Date(zdt.epochMilliseconds);
236
+ }
237
+
238
+ /**
239
+ * Checks whether a `ZonedDateTime` and a `PlainDate` represent the same
240
+ * calendar day (year, month, and day all equal).
241
+ *
242
+ * @param a - A zoned date-time.
243
+ * @param b - A plain date.
244
+ */
245
+ export function sameCalendarDay(a: Temporal.ZonedDateTime, b: Temporal.PlainDate): boolean {
246
+ return a.year === b.year && a.month === b.month && a.day === b.day;
247
+ }
248
+
249
+ /**
250
+ * Returns a date falling on the configured week start day, used as an anchor
251
+ * for generating weekday name lists.
252
+ *
253
+ * @param T - Temporal namespace.
254
+ * @param weekStartDay - 0=Sunday (default), 1=Monday, etc.
255
+ */
256
+ export function getReferenceWeekStart(T: TemporalNamespace, weekStartDay = 0): Temporal.PlainDate {
257
+ const refSunday = T.PlainDate.from("2024-01-07");
258
+ return refSunday.add({ days: weekStartDay });
259
+ }
260
+
261
+ /**
262
+ * Computes the year/month and first day of the month adjacent to `current`.
263
+ *
264
+ * Handles year boundaries (e.g. Dec → Jan, Jan → Dec).
265
+ *
266
+ * @param current - The reference month.
267
+ * @param direction - `"next"` or `"prev"`.
268
+ * @param T - Temporal namespace.
269
+ */
270
+ export function computeAdjacentMonth(
271
+ current: { year: number; month: number },
272
+ direction: "prev" | "next",
273
+ T: TemporalNamespace,
274
+ ): { year: number; month: number; firstDay: Temporal.PlainDate } {
275
+ const d = T.PlainDate.from({
276
+ year: current.year,
277
+ month: current.month,
278
+ day: 1,
279
+ })[direction === "next" ? "add" : "subtract"]({ months: 1 });
280
+ return { year: d.year, month: d.month, firstDay: d };
281
+ }
282
+
283
+ /**
284
+ * Determines the focused date after navigating to a new month.
285
+ *
286
+ * If `currentFocused` is already within `targetMonth`, it is preserved.
287
+ * Otherwise, `firstDay` of the target month is returned.
288
+ *
289
+ * @param currentFocused - The currently focused date.
290
+ * @param targetMonth - The month being navigated to.
291
+ * @param firstDay - The first day of the target month (fallback).
292
+ */
293
+ export function focusedDateForMonth(
294
+ currentFocused: Temporal.PlainDate,
295
+ targetMonth: { year: number; month: number },
296
+ firstDay: Temporal.PlainDate,
297
+ ): Temporal.PlainDate {
298
+ if (currentFocused.year === targetMonth.year && currentFocused.month === targetMonth.month) {
299
+ return currentFocused;
300
+ }
301
+ return firstDay;
302
+ }
303
+
304
+ /**
305
+ * Resolves which date should receive focus/tabindex in the calendar grid.
306
+ *
307
+ * Priority when `gridHasFocus` is `true` (keyboard navigation):
308
+ * 1. `focusedDate` if it exists in the grid.
309
+ * 2. `selectedDate` if it exists in the grid.
310
+ * 3. First enabled day of `currentMonth`, or first grid day as last resort.
311
+ *
312
+ * When `gridHasFocus` is `false` (tab-in), `selectedDate` takes priority
313
+ * over `focusedDate`.
314
+ *
315
+ * @param focusedDate - The date currently tracked as focused.
316
+ * @param selectedDate - The currently selected date, if any.
317
+ * @param weeks - The 2D weeks array from {@link getMonthWeeks}.
318
+ * @param currentMonth - The month being displayed.
319
+ * @param isDateDisabled - Predicate for disabled dates.
320
+ * @param T - Temporal namespace.
321
+ * @param gridHasFocus - Whether the grid currently holds DOM focus.
322
+ */
323
+ export function resolveFocusTarget(
324
+ focusedDate: Temporal.PlainDate,
325
+ selectedDate: Temporal.PlainDate | undefined,
326
+ weeks: Temporal.PlainDate[][],
327
+ currentMonth: { year: number; month: number },
328
+ isDateDisabled: (date: Temporal.PlainDate) => boolean,
329
+ T: TemporalNamespace,
330
+ gridHasFocus = true,
331
+ ): Temporal.PlainDate {
332
+ const allDays = weeks.flat();
333
+ const inGrid = (d: Temporal.PlainDate) => allDays.some((g) => T.PlainDate.compare(g, d) === 0);
334
+
335
+ if (gridHasFocus && inGrid(focusedDate)) return focusedDate;
336
+
337
+ if (selectedDate && inGrid(selectedDate)) return selectedDate;
338
+
339
+ if (!gridHasFocus && inGrid(focusedDate)) return focusedDate;
340
+
341
+ const firstEnabled = allDays.find(
342
+ (d) => d.year === currentMonth.year && d.month === currentMonth.month && !isDateDisabled(d),
343
+ );
344
+ return firstEnabled ?? allDays[0];
345
+ }
346
+
347
+ /**
348
+ * Determines whether a day cell should imperatively receive DOM focus.
349
+ *
350
+ * Only returns `true` when the cell is the focused date **and** the grid
351
+ * currently holds DOM focus (i.e. keyboard navigation is active).
352
+ *
353
+ * @param isFocused - Whether this cell is the logically focused date.
354
+ * @param gridHasFocus - Whether the grid currently holds DOM focus.
355
+ */
356
+ export function shouldMoveDomFocus(isFocused: boolean, gridHasFocus: boolean): boolean {
357
+ return isFocused && gridHasFocus;
358
+ }
359
+
360
+ /**
361
+ * Returns the normalized position of `date` within the inclusive range
362
+ * `[rangeStart, rangeEnd]` as a number from `0` (start) to `1` (end),
363
+ * or `false` if the date is outside the range.
364
+ * A single-day range returns `0` for that date.
365
+ *
366
+ * @param date - The date to test.
367
+ * @param rangeStart - Start of the range (inclusive). When `undefined` and `rangeEnd` is defined, the range collapses to a single-day range at `rangeEnd`.
368
+ * @param rangeEnd - End of the range (inclusive). When `undefined` and `rangeStart` is defined, the range collapses to a single-day range at `rangeStart`. Returns `false` when both boundaries are `undefined`.
369
+ * @param T - Temporal namespace used for date comparison.
370
+ */
371
+ export function isInRange(
372
+ date: Temporal.PlainDate,
373
+ rangeStart: Temporal.PlainDate | undefined,
374
+ rangeEnd: Temporal.PlainDate | undefined,
375
+ T: TemporalNamespace,
376
+ ): number | false {
377
+ if (!rangeStart && !rangeEnd) return false;
378
+ const effectiveStart = rangeStart ?? rangeEnd!;
379
+ const effectiveEnd = rangeEnd ?? rangeStart!;
380
+ if (T.PlainDate.compare(date, effectiveStart) < 0 || T.PlainDate.compare(date, effectiveEnd) > 0)
381
+ return false;
382
+ const totalDays = effectiveEnd.since(effectiveStart).days;
383
+ if (totalDays === 0) return 0;
384
+ const offsetDays = date.since(effectiveStart).days;
385
+ return offsetDays / totalDays;
386
+ }
387
+
388
+ /**
389
+ * Computes how a date range intersects with a single calendar week row.
390
+ *
391
+ * Used to position and style the range highlight overlay within a week.
392
+ *
393
+ * @param weekDays - Array of 7 `PlainDate` values for the week (Sun–Sat).
394
+ * @param rangeStart - Start of the selected range, or `undefined`.
395
+ * @param rangeEnd - End of the selected range, or `undefined`.
396
+ * @param T - Temporal namespace.
397
+ * @returns An object with `active` (whether the range overlaps this week),
398
+ * `startIndex` / `endIndex` (0-based column positions), and
399
+ * `extendsBefore` / `extendsAfter` (whether the range continues beyond the week).
400
+ */
401
+ export function computeWeekRangeInfo(
402
+ weekDays: Temporal.PlainDate[],
403
+ rangeStart: Temporal.PlainDate | undefined,
404
+ rangeEnd: Temporal.PlainDate | undefined,
405
+ T: TemporalNamespace,
406
+ ): {
407
+ active: boolean;
408
+ startIndex: number;
409
+ endIndex: number;
410
+ extendsBefore: boolean;
411
+ extendsAfter: boolean;
412
+ } {
413
+ const inactive = {
414
+ active: false,
415
+ startIndex: 0,
416
+ endIndex: 0,
417
+ extendsBefore: false,
418
+ extendsAfter: false,
419
+ };
420
+ if (weekDays.length === 0) return inactive;
421
+ if (!rangeStart && !rangeEnd) return inactive;
422
+ const effectiveStart = rangeStart ?? rangeEnd!;
423
+ const effectiveEnd = rangeEnd ?? rangeStart!;
424
+
425
+ const weekStart = weekDays[0];
426
+ const weekEnd = weekDays[weekDays.length - 1];
427
+
428
+ if (
429
+ T.PlainDate.compare(effectiveEnd, weekStart) < 0 ||
430
+ T.PlainDate.compare(effectiveStart, weekEnd) > 0
431
+ ) {
432
+ return inactive;
433
+ }
434
+
435
+ const extendsBefore = T.PlainDate.compare(effectiveStart, weekStart) < 0;
436
+ const extendsAfter = T.PlainDate.compare(effectiveEnd, weekEnd) > 0;
437
+
438
+ let startIndex = 0;
439
+ if (!extendsBefore) {
440
+ startIndex = weekDays.findIndex((d) => T.PlainDate.compare(d, effectiveStart) === 0);
441
+ if (startIndex === -1) return inactive;
442
+ }
443
+
444
+ let endIndex = weekDays.length - 1;
445
+ if (!extendsAfter) {
446
+ endIndex = weekDays.findIndex((d) => T.PlainDate.compare(d, effectiveEnd) === 0);
447
+ if (endIndex === -1) return inactive;
448
+ }
449
+
450
+ return { active: true, startIndex, endIndex, extendsBefore, extendsAfter };
451
+ }
452
+
453
+ /**
454
+ * Generates localized weekday names starting from the configured week start day.
455
+ *
456
+ * @param locale - BCP 47 locale string (e.g. `"en-US"`).
457
+ * @param T - Temporal namespace.
458
+ * @param weekStartDay - 0=Sunday (default), 1=Monday, etc.
459
+ * @returns An array of 7 objects with `long`, `short`, and `narrow` name variants.
460
+ */
461
+ export function getWeekdayNames(locale: string, T: TemporalNamespace, weekStartDay = 0) {
462
+ const refStart = getReferenceWeekStart(T, weekStartDay);
463
+ const daysInWeek = refStart.daysInWeek;
464
+ const names: { long: string; short: string; narrow: string }[] = [];
465
+ for (let i = 0; i < daysInWeek; i++) {
466
+ const date = refStart.add({ days: i });
467
+ names.push({
468
+ long: date.toLocaleString(locale, { weekday: "long" }),
469
+ short: date.toLocaleString(locale, { weekday: "short" }),
470
+ narrow: date.toLocaleString(locale, { weekday: "narrow" }),
471
+ });
472
+ }
473
+ return names;
474
+ }
475
+
476
+ /**
477
+ * Computes the ISO 8601 week number for a given date.
478
+ *
479
+ * The ISO week number is determined by the Thursday of the date's ISO week.
480
+ *
481
+ * @param date - The date to compute the week number for.
482
+ * @param T - Temporal namespace.
483
+ */
484
+ export function getISOWeekNumber(date: Temporal.PlainDate, T: TemporalNamespace): number {
485
+ // ISO dayOfWeek: 1=Mon...7=Sun
486
+ // Find the Thursday of this ISO week
487
+ const thursday = date.add({ days: 4 - date.dayOfWeek });
488
+ // Jan 4 is always in ISO week 1
489
+ const jan4 = T.PlainDate.from({ year: thursday.year, month: 1, day: 4 });
490
+ const jan4Thursday = jan4.add({ days: 4 - jan4.dayOfWeek });
491
+ const daysDiff = thursday.since(jan4Thursday, { largestUnit: "days" }).days;
492
+ return Math.round(daysDiff / 7) + 1;
493
+ }
@@ -0,0 +1,28 @@
1
+ import type { Temporal } from "@js-temporal/polyfill";
2
+ import { createContext, useContext } from "react";
3
+
4
+ /** Shared context provided by both MonthView.Root and WeeksView.Root. */
5
+ export interface ViewContextValue {
6
+ /** Which view type is active. */
7
+ viewType: "month" | "weeks";
8
+ /** The logically focused date in the grid. */
9
+ focusedDate: Temporal.PlainDate;
10
+ /** Moves the logically focused date. */
11
+ setFocusedDate: (date: Temporal.PlainDate) => void;
12
+ /** The date that should receive `tabIndex={0}` for roving tabindex. */
13
+ tabTargetDate: Temporal.PlainDate;
14
+ /** Whether the grid currently holds DOM focus. */
15
+ gridHasFocus: boolean;
16
+ /** Tracks whether the grid currently holds DOM focus. */
17
+ setGridHasFocus: (v: boolean) => void;
18
+ }
19
+
20
+ /** @internal React context for the active view (MonthView or WeeksView). */
21
+ export const ViewContext = createContext<ViewContextValue | null>(null);
22
+
23
+ /** Returns the nearest view context (MonthView or WeeksView). */
24
+ export function useViewContext(): ViewContextValue {
25
+ const ctx = useContext(ViewContext);
26
+ if (!ctx) throw new Error("useViewContext must be used within MonthView or WeeksView");
27
+ return ctx;
28
+ }
@@ -0,0 +1,118 @@
1
+ import { mergeProps } from "@base-ui/react/merge-props";
2
+ import { useRender } from "@base-ui/react/use-render";
3
+ import { forwardRef, useContext, useMemo } from "react";
4
+ import { useCalendarStable } from "./calendar-context";
5
+ import { WeekDataContext } from "./context";
6
+ import { useMonthViewState } from "./month-view-context";
7
+ import type { StateAttributesMapping } from "./types";
8
+ import type {
9
+ ValueFormat,
10
+ WeekNumberCellState,
11
+ WeekNumberCellProps,
12
+ WeekNumberHeaderState,
13
+ WeekNumberHeaderProps,
14
+ } from "./types";
15
+ import { getISOWeekNumber } from "./utils";
16
+
17
+ const weekNumberCellStateAttributesMapping = {
18
+ root: () => null,
19
+ weekNumber: (v) => ({ "data-week-number": String(v) }),
20
+ } as const satisfies StateAttributesMapping<WeekNumberCellState>;
21
+
22
+ function WeekNumberCellFn(
23
+ props: WeekNumberCellProps,
24
+ ref: React.ForwardedRef<HTMLTableCellElement>,
25
+ ) {
26
+ const { render, ...otherProps } = props;
27
+ const weekData = useContext(WeekDataContext);
28
+ const { rootState } = useMonthViewState();
29
+ const { temporal: T } = useCalendarStable();
30
+
31
+ const days = weekData?.days ?? [];
32
+
33
+ // ISO week number is determined by the Thursday of the week
34
+ const weekNumber = useMemo(() => {
35
+ if (days.length === 0) return 0;
36
+ // Find the Thursday in this week row — it determines the ISO week number
37
+ let thursday = days[0];
38
+ for (const d of days) {
39
+ if (d.dayOfWeek === 4) {
40
+ thursday = d;
41
+ break;
42
+ }
43
+ }
44
+ return getISOWeekNumber(thursday, T);
45
+ }, [days, T]);
46
+
47
+ const state = useMemo<WeekNumberCellState>(
48
+ () => ({
49
+ root: rootState as unknown as WeekNumberCellState["root"],
50
+ weekNumber,
51
+ }),
52
+ [rootState, weekNumber],
53
+ );
54
+
55
+ const defaultProps: Record<string, unknown> = {
56
+ role: "rowheader",
57
+ "aria-label": `Week ${weekNumber}`,
58
+ children: weekNumber,
59
+ };
60
+
61
+ return useRender({
62
+ defaultTagName: "td",
63
+ render,
64
+ ref: ref ? [ref] : [],
65
+ state,
66
+ stateAttributesMapping: weekNumberCellStateAttributesMapping,
67
+ props: mergeProps<"td">(defaultProps, otherProps),
68
+ });
69
+ }
70
+
71
+ /**
72
+ * Renders the ISO 8601 week number for a week row. Must be used inside
73
+ * a {@link WeekTemplate}. Renders a `<td>` with `role="rowheader"`.
74
+ */
75
+ export const WeekNumberCell = forwardRef(WeekNumberCellFn) as <F extends ValueFormat = ValueFormat>(
76
+ props: WeekNumberCellProps<F> & React.RefAttributes<HTMLTableCellElement>,
77
+ ) => React.ReactElement | null;
78
+
79
+ const weekNumberHeaderStateAttributesMapping = {
80
+ root: () => null,
81
+ } as const satisfies StateAttributesMapping<WeekNumberHeaderState>;
82
+
83
+ function WeekNumberHeaderFn(
84
+ props: WeekNumberHeaderProps,
85
+ ref: React.ForwardedRef<HTMLTableCellElement>,
86
+ ) {
87
+ const { render, ...otherProps } = props;
88
+ const { rootState } = useMonthViewState();
89
+
90
+ const state = useMemo<WeekNumberHeaderState>(
91
+ () => ({ root: rootState as unknown as WeekNumberHeaderState["root"] }),
92
+ [rootState],
93
+ );
94
+
95
+ const defaultProps: Record<string, unknown> = {
96
+ scope: "col",
97
+ "aria-label": "Week number",
98
+ children: "#",
99
+ };
100
+
101
+ return useRender({
102
+ defaultTagName: "th",
103
+ render,
104
+ ref: ref ? [ref] : [],
105
+ state,
106
+ stateAttributesMapping: weekNumberHeaderStateAttributesMapping,
107
+ props: mergeProps<"th">(defaultProps, otherProps),
108
+ });
109
+ }
110
+
111
+ /**
112
+ * Column header for the week number column. Renders a `<th scope="col">`.
113
+ */
114
+ export const WeekNumberHeader = forwardRef(WeekNumberHeaderFn) as <
115
+ F extends ValueFormat = ValueFormat,
116
+ >(
117
+ props: WeekNumberHeaderProps<F> & React.RefAttributes<HTMLTableCellElement>,
118
+ ) => React.ReactElement | null;