@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
@@ -0,0 +1,209 @@
1
+ import { mergeProps } from "@base-ui/react/merge-props";
2
+ import { useRender } from "@base-ui/react/use-render";
3
+ import React, { forwardRef, useMemo } from "react";
4
+ import { useCalendarStable } from "./calendar-context";
5
+ import { useMonthViewState } from "./month-view-context";
6
+ import { canShift } from "./overflow";
7
+ import type { RootState, StateAttributesMapping } from "./types";
8
+ import { useWeeksViewStable, useWeeksViewState } from "./weeks-view-context";
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // Shared types
12
+ // ---------------------------------------------------------------------------
13
+
14
+ /** State exposed by `PrevWeeksButton` and `NextWeeksButton`. */
15
+ export type WeeksNavButtonState = {
16
+ root: RootState;
17
+ direction: "prev" | "next";
18
+ disabled: boolean;
19
+ };
20
+
21
+ /** Own props for weeks navigation buttons. */
22
+ export interface WeeksNavButtonOwnProps {
23
+ /** Overrides weekCount as the shift amount. Must be a positive integer. */
24
+ shiftBy?: number;
25
+ }
26
+
27
+ /** Full props for the `PrevWeeksButton` component. */
28
+ export type PrevWeeksButtonProps = useRender.ComponentProps<"button", WeeksNavButtonState> &
29
+ WeeksNavButtonOwnProps;
30
+
31
+ /** Full props for the `NextWeeksButton` component. */
32
+ export type NextWeeksButtonProps = useRender.ComponentProps<"button", WeeksNavButtonState> &
33
+ WeeksNavButtonOwnProps;
34
+
35
+ /** State exposed by `WeeksView.WeekCount`. */
36
+ export type WeekCountState = {
37
+ root: RootState;
38
+ weekCount: number;
39
+ };
40
+
41
+ /** Full props for the `WeeksView.WeekCount` component. */
42
+ export type WeekCountProps = useRender.ComponentProps<"span", WeekCountState>;
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // State attribute mappings
46
+ // ---------------------------------------------------------------------------
47
+
48
+ const weeksNavButtonStateAttributesMapping = {
49
+ root: () => null,
50
+ direction: (v) => ({ "data-direction": v }),
51
+ disabled: () => null,
52
+ } as const satisfies StateAttributesMapping<WeeksNavButtonState>;
53
+
54
+ const weekCountStateAttributesMapping = {
55
+ root: () => null,
56
+ weekCount: () => null,
57
+ } as const satisfies StateAttributesMapping<WeekCountState>;
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Shared hook
61
+ // ---------------------------------------------------------------------------
62
+
63
+ function useWeeksNavButton(direction: "prev" | "next", shiftByProp: number | undefined) {
64
+ const {
65
+ disabled: globalDisabled,
66
+ minValue,
67
+ maxValue,
68
+ temporal: T,
69
+ weekStartDay,
70
+ } = useCalendarStable();
71
+ const { weekCount, overflowBehavior, goNext, goPrev } = useWeeksViewStable();
72
+ const { windowInfo } = useWeeksViewState();
73
+ const { rootState } = useMonthViewState();
74
+
75
+ const currentFirstWeek = windowInfo.windowStart;
76
+
77
+ const isDisabled = useMemo(() => {
78
+ if (globalDisabled) return true;
79
+ return !canShift({
80
+ currentFirstWeek,
81
+ weekCount,
82
+ direction: direction === "next" ? 1 : -1,
83
+ shiftBy: shiftByProp,
84
+ behavior: overflowBehavior,
85
+ min: minValue,
86
+ max: maxValue,
87
+ weekStartDay,
88
+ T,
89
+ });
90
+ }, [
91
+ globalDisabled,
92
+ currentFirstWeek,
93
+ weekCount,
94
+ direction,
95
+ shiftByProp,
96
+ overflowBehavior,
97
+ minValue,
98
+ maxValue,
99
+ weekStartDay,
100
+ T,
101
+ ]);
102
+
103
+ const state = useMemo<WeeksNavButtonState>(
104
+ () => ({ root: rootState as any, direction, disabled: isDisabled }),
105
+ [rootState, direction, isDisabled],
106
+ );
107
+
108
+ const goFn = direction === "prev" ? goPrev : goNext;
109
+
110
+ const defaultProps: Record<string, unknown> = {
111
+ type: "button",
112
+ "aria-label": `Go to ${direction === "prev" ? "previous" : "next"} weeks`,
113
+ disabled: isDisabled,
114
+ onClick: isDisabled ? undefined : () => goFn(shiftByProp),
115
+ };
116
+
117
+ return { state, defaultProps };
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // PrevWeeksButton
122
+ // ---------------------------------------------------------------------------
123
+
124
+ function PrevWeeksButtonFn(
125
+ props: PrevWeeksButtonProps,
126
+ ref: React.ForwardedRef<HTMLButtonElement>,
127
+ ) {
128
+ const { render, shiftBy, ...otherProps } = props;
129
+ const { state, defaultProps } = useWeeksNavButton("prev", shiftBy);
130
+
131
+ return useRender({
132
+ defaultTagName: "button",
133
+ render,
134
+ ref: ref ? [ref] : [],
135
+ state,
136
+ stateAttributesMapping: weeksNavButtonStateAttributesMapping,
137
+ props: mergeProps<"button">(defaultProps, otherProps),
138
+ });
139
+ }
140
+
141
+ /**
142
+ * Button that navigates to the previous week(s). Automatically disabled when
143
+ * no more weeks are available based on `overflowBehavior` and `min`.
144
+ * Exposes `data-direction="prev"`.
145
+ */
146
+ export const PrevWeeksButton = forwardRef(PrevWeeksButtonFn);
147
+
148
+ // ---------------------------------------------------------------------------
149
+ // NextWeeksButton
150
+ // ---------------------------------------------------------------------------
151
+
152
+ function NextWeeksButtonFn(
153
+ props: NextWeeksButtonProps,
154
+ ref: React.ForwardedRef<HTMLButtonElement>,
155
+ ) {
156
+ const { render, shiftBy, ...otherProps } = props;
157
+ const { state, defaultProps } = useWeeksNavButton("next", shiftBy);
158
+
159
+ return useRender({
160
+ defaultTagName: "button",
161
+ render,
162
+ ref: ref ? [ref] : [],
163
+ state,
164
+ stateAttributesMapping: weeksNavButtonStateAttributesMapping,
165
+ props: mergeProps<"button">(defaultProps, otherProps),
166
+ });
167
+ }
168
+
169
+ /**
170
+ * Button that navigates to the next week(s). Automatically disabled when
171
+ * no more weeks are available based on `overflowBehavior` and `max`.
172
+ * Exposes `data-direction="next"`.
173
+ */
174
+ export const NextWeeksButton = forwardRef(NextWeeksButtonFn);
175
+
176
+ // ---------------------------------------------------------------------------
177
+ // WeekCount
178
+ // ---------------------------------------------------------------------------
179
+
180
+ function WeekCountFn(props: WeekCountProps, ref: React.ForwardedRef<HTMLSpanElement>) {
181
+ const { render, ...otherProps } = props;
182
+ const { windowInfo } = useWeeksViewState();
183
+ const { rootState } = useMonthViewState();
184
+ const count = windowInfo.weekCount;
185
+
186
+ const state = useMemo<WeekCountState>(
187
+ () => ({ root: rootState as any, weekCount: count }),
188
+ [rootState, count],
189
+ );
190
+
191
+ const defaultProps: Record<string, unknown> = {
192
+ children: count,
193
+ };
194
+
195
+ return useRender({
196
+ defaultTagName: "span",
197
+ render,
198
+ ref: ref ? [ref] : [],
199
+ state,
200
+ stateAttributesMapping: weekCountStateAttributesMapping,
201
+ props: mergeProps<"span">(defaultProps, otherProps),
202
+ });
203
+ }
204
+
205
+ /**
206
+ * Renders the current visible week count as a number. Useful with shrink
207
+ * overflow modes where the actual count may be less than the `weekCount` prop.
208
+ */
209
+ export const WeekCount = forwardRef(WeekCountFn);
@@ -0,0 +1,26 @@
1
+ import { createContext, useContext } from "react";
2
+ import type { WeeksViewStableContextValue, WeeksViewStateContextValue } from "./weeks-view-types";
3
+
4
+ /** @internal React context for WeeksView stable values (config + callbacks). */
5
+ export const WeeksViewStableContext = createContext<WeeksViewStableContextValue | null>(null);
6
+
7
+ /** @internal React context for WeeksView volatile state. */
8
+ export const WeeksViewStateContext = createContext<WeeksViewStateContextValue | null>(null);
9
+
10
+ /** Returns the WeeksView stable context (config + callbacks). */
11
+ export function useWeeksViewStable(): WeeksViewStableContextValue {
12
+ const ctx = useContext(WeeksViewStableContext);
13
+ if (!ctx) {
14
+ throw new Error("useWeeksViewStable must be used within WeeksView.Root");
15
+ }
16
+ return ctx;
17
+ }
18
+
19
+ /** Returns the WeeksView state context (volatile grid data). */
20
+ export function useWeeksViewState(): WeeksViewStateContextValue {
21
+ const ctx = useContext(WeeksViewStateContext);
22
+ if (!ctx) {
23
+ throw new Error("useWeeksViewState must be used within WeeksView.Root");
24
+ }
25
+ return ctx;
26
+ }
@@ -0,0 +1,421 @@
1
+ import type { Temporal } from "@js-temporal/polyfill";
2
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
+ import { useCalendarStable, useCalendarState } from "./calendar-context";
4
+ import { computeWeeksInWindow } from "./compute-weeks-in-window";
5
+ import { applyOverflow, type OverflowBehavior } from "./overflow";
6
+ import { resolveFirstWeekSpec, resolveFirstWeek, type FirstWeekSpec } from "./resolve-first-week";
7
+ import { selectedToZdt, toZonedDateTime } from "./utils";
8
+ import type { ViewContextValue } from "./view-context";
9
+ import type {
10
+ WeeksViewRootProps,
11
+ WeeksViewStableContextValue,
12
+ WeeksViewStateContextValue,
13
+ WindowInfo,
14
+ } from "./weeks-view-types";
15
+
16
+ /**
17
+ * Core state management hook for WeeksView.Root.
18
+ * Reads calendar-level context and manages weeks-specific state.
19
+ */
20
+ export function useWeeksViewRootState(props: WeeksViewRootProps) {
21
+ const {
22
+ weekCount,
23
+ firstWeek: firstWeekProp,
24
+ defaultFirstWeek: defaultFirstWeekProp,
25
+ onFirstWeekChange,
26
+ scrollBy: scrollByProp,
27
+ overflowBehavior: overflowBehaviorProp,
28
+ onWindowChange,
29
+ } = props;
30
+
31
+ const scrollBy = scrollByProp ?? "row";
32
+ const overflowBehavior: OverflowBehavior = overflowBehaviorProp ?? "unbounded";
33
+
34
+ // Read calendar-level context
35
+ const calStable = useCalendarStable();
36
+ const calState = useCalendarState();
37
+
38
+ const T = calStable.temporal;
39
+ const { weekStartDay, isDateDisabled, minValue, maxValue, timeZone } = calStable;
40
+
41
+ // --- Controlled/uncontrolled firstWeek ---
42
+ const isControlled = firstWeekProp !== undefined;
43
+
44
+ const resolveSpec = useCallback(
45
+ (spec: FirstWeekSpec): Temporal.PlainDate => resolveFirstWeekSpec(spec, weekStartDay, T),
46
+ [weekStartDay, T],
47
+ );
48
+
49
+ const [internalFirstWeek, setInternalFirstWeek] = useState<Temporal.PlainDate>(() => {
50
+ if (firstWeekProp !== undefined) return resolveSpec(firstWeekProp);
51
+ if (defaultFirstWeekProp !== undefined) return resolveSpec(defaultFirstWeekProp);
52
+ // Derive from selection or today
53
+ if (calState.selected) {
54
+ const plain = toZonedDateTime(calState.selected, timeZone, T).toPlainDate();
55
+ return resolveSpec(plain);
56
+ }
57
+ return resolveSpec(T.Now.plainDateISO());
58
+ });
59
+
60
+ const resolvedFirstWeek = isControlled ? resolveSpec(firstWeekProp) : internalFirstWeek;
61
+
62
+ // --- Compute week window ---
63
+ const rawWeeks = useMemo(
64
+ () => computeWeeksInWindow(resolvedFirstWeek, weekCount, weekStartDay, T),
65
+ [resolvedFirstWeek, weekCount, weekStartDay, T],
66
+ );
67
+
68
+ // --- Apply overflow ---
69
+ const overflowResult = useMemo(
70
+ () =>
71
+ applyOverflow({
72
+ targetFirstWeek: resolvedFirstWeek,
73
+ weekCount,
74
+ behavior: overflowBehavior,
75
+ min: minValue,
76
+ max: maxValue,
77
+ weekStartDay,
78
+ T,
79
+ }),
80
+ [resolvedFirstWeek, weekCount, overflowBehavior, minValue, maxValue, weekStartDay, T],
81
+ );
82
+
83
+ // Recompute weeks if overflow adjusted the window
84
+ const adjustedWeeks = useMemo(() => {
85
+ const sameFirst = T.PlainDate.compare(overflowResult.firstWeek, resolvedFirstWeek) === 0;
86
+ const sameCount = overflowResult.weekCount === weekCount;
87
+ if (sameFirst && sameCount) return rawWeeks;
88
+ return computeWeeksInWindow(
89
+ overflowResult.firstWeek,
90
+ overflowResult.weekCount,
91
+ weekStartDay,
92
+ T,
93
+ );
94
+ }, [overflowResult, resolvedFirstWeek, weekCount, rawWeeks, weekStartDay, T]);
95
+
96
+ // --- Compute WindowInfo ---
97
+ const isDateEnabled = useCallback(
98
+ (date: Temporal.PlainDate): boolean => {
99
+ if (minValue && T.PlainDate.compare(date, minValue) < 0) return false;
100
+ if (maxValue && T.PlainDate.compare(date, maxValue) > 0) return false;
101
+ if (isDateDisabled?.(date)) return false;
102
+ return true;
103
+ },
104
+ [minValue, maxValue, isDateDisabled, T],
105
+ );
106
+
107
+ const windowInfo = useMemo<WindowInfo>(() => {
108
+ const weeks = adjustedWeeks;
109
+ if (weeks.length === 0) {
110
+ const today = T.Now.plainDateISO();
111
+ return {
112
+ windowStart: today,
113
+ windowEnd: today,
114
+ weekCount: 0,
115
+ dayCount: 0,
116
+ enabledWeekCount: 0,
117
+ enabledDayCount: 0,
118
+ visibleMonths: [],
119
+ };
120
+ }
121
+ const windowStart = weeks[0].startDate;
122
+ const windowEnd = weeks[weeks.length - 1].endDate;
123
+ const wc = weeks.length;
124
+ const dayCount = wc * 7;
125
+
126
+ let enabledDayCount = 0;
127
+ let enabledWeekCount = 0;
128
+ for (const week of weeks) {
129
+ let weekHasEnabled = false;
130
+ // Check all 7 days of the week
131
+ let day = week.startDate;
132
+ for (let d = 0; d < 7; d++) {
133
+ if (isDateEnabled(day)) {
134
+ enabledDayCount++;
135
+ weekHasEnabled = true;
136
+ }
137
+ if (d < 6) day = day.add({ days: 1 });
138
+ }
139
+ if (weekHasEnabled) enabledWeekCount++;
140
+ }
141
+
142
+ // Compute visible months from all days in the window
143
+ const visibleMonths: WindowInfo["visibleMonths"] = [];
144
+ const seenMonths = new Set<string>();
145
+ for (const week of weeks) {
146
+ let day = week.startDate;
147
+ for (let d = 0; d < 7; d++) {
148
+ const key = `${day.year}-${day.month}`;
149
+ if (!seenMonths.has(key)) {
150
+ seenMonths.add(key);
151
+ visibleMonths.push({ month: day.month, year: day.year });
152
+ }
153
+ if (d < 6) day = day.add({ days: 1 });
154
+ }
155
+ }
156
+
157
+ return {
158
+ windowStart,
159
+ windowEnd,
160
+ weekCount: wc,
161
+ dayCount,
162
+ enabledWeekCount,
163
+ enabledDayCount,
164
+ visibleMonths,
165
+ };
166
+ }, [adjustedWeeks, isDateEnabled, T]);
167
+
168
+ // --- Focus management ---
169
+ const selectedPlain = useMemo(() => {
170
+ if (!calState.selected) return undefined;
171
+ return selectedToZdt(calState.selected, timeZone, T)?.toPlainDate();
172
+ }, [calState.selected, timeZone, T]);
173
+
174
+ const isInWindow = useCallback(
175
+ (date: Temporal.PlainDate): boolean => {
176
+ return (
177
+ T.PlainDate.compare(date, windowInfo.windowStart) >= 0 &&
178
+ T.PlainDate.compare(date, windowInfo.windowEnd) <= 0
179
+ );
180
+ },
181
+ [windowInfo.windowStart, windowInfo.windowEnd, T],
182
+ );
183
+
184
+ const [focusedDate, setFocusedDate] = useState<Temporal.PlainDate>(() => {
185
+ if (selectedPlain && isInWindow(selectedPlain)) return selectedPlain;
186
+ return windowInfo.windowStart;
187
+ });
188
+
189
+ // When window shifts, ensure focusedDate stays visible
190
+ useEffect(() => {
191
+ setFocusedDate((prev) => {
192
+ if (isInWindow(prev)) return prev;
193
+ // Focus the start of the new window
194
+ return windowInfo.windowStart;
195
+ });
196
+ }, [windowInfo.windowStart, isInWindow]);
197
+
198
+ const [gridHasFocus, setGridHasFocus] = useState(false);
199
+ const gridFocusedRef = useRef(false);
200
+
201
+ // --- Grid label IDs ---
202
+ const [gridLabelIds, setGridLabelIds] = useState<Record<number, string>>({});
203
+ const setGridLabelId = useCallback((id: string | undefined) => {
204
+ setGridLabelIds((prev) => {
205
+ const key = 0; // WeeksView has a single grid
206
+ if (id === undefined) {
207
+ if (!(key in prev)) return prev;
208
+ const next = { ...prev };
209
+ delete next[key];
210
+ return next;
211
+ }
212
+ if (prev[key] === id) return prev;
213
+ return { ...prev, [key]: id };
214
+ });
215
+ }, []);
216
+
217
+ // --- tabTargetDate ---
218
+ const tabTargetDate = useMemo(() => {
219
+ const allDays: Temporal.PlainDate[] = [];
220
+ for (const week of adjustedWeeks) {
221
+ let day = week.startDate;
222
+ for (let d = 0; d < 7; d++) {
223
+ allDays.push(day);
224
+ if (d < 6) day = day.add({ days: 1 });
225
+ }
226
+ }
227
+ const inGrid = (d: Temporal.PlainDate) => allDays.some((g) => T.PlainDate.compare(g, d) === 0);
228
+
229
+ if (gridHasFocus && inGrid(focusedDate)) return focusedDate;
230
+ if (selectedPlain && inGrid(selectedPlain)) return selectedPlain;
231
+ if (!gridHasFocus && inGrid(focusedDate)) return focusedDate;
232
+
233
+ const firstEnabled = allDays.find((d) => isDateEnabled(d));
234
+ return firstEnabled ?? allDays[0] ?? windowInfo.windowStart;
235
+ }, [
236
+ adjustedWeeks,
237
+ focusedDate,
238
+ selectedPlain,
239
+ gridHasFocus,
240
+ isDateEnabled,
241
+ T,
242
+ windowInfo.windowStart,
243
+ ]);
244
+
245
+ // --- currentDateTime ---
246
+ const selectedZdt = useMemo(
247
+ () => selectedToZdt(calState.selected, timeZone, T),
248
+ [calState.selected, timeZone, T],
249
+ );
250
+
251
+ const currentDateTime = useMemo<Temporal.PlainDateTime>(
252
+ () =>
253
+ T.PlainDateTime.from(
254
+ {
255
+ year: windowInfo.windowStart.year,
256
+ month: windowInfo.windowStart.month,
257
+ day: focusedDate.day,
258
+ hour: selectedZdt?.hour ?? 0,
259
+ minute: selectedZdt?.minute ?? 0,
260
+ second: selectedZdt?.second ?? 0,
261
+ },
262
+ { overflow: "constrain" },
263
+ ),
264
+ [windowInfo.windowStart, focusedDate.day, selectedZdt, T],
265
+ );
266
+
267
+ // --- Navigation ---
268
+ // goNext/goPrev default to weekCount. The scrollBy prop only affects
269
+ // keyboard arrow behavior (in weeks-keyboard.ts), NOT button navigation.
270
+
271
+ const updateFirstWeek = useCallback(
272
+ (newFirstWeek: Temporal.PlainDate) => {
273
+ if (!isControlled) {
274
+ setInternalFirstWeek(newFirstWeek);
275
+ }
276
+ onFirstWeekChange?.(newFirstWeek);
277
+ },
278
+ [isControlled, onFirstWeekChange],
279
+ );
280
+
281
+ const goNext = useCallback(
282
+ (shiftBy?: number) => {
283
+ const shift = shiftBy ?? weekCount;
284
+ const target = resolvedFirstWeek.add({ weeks: shift });
285
+ const adjusted = applyOverflow({
286
+ targetFirstWeek: target,
287
+ weekCount,
288
+ behavior: overflowBehavior,
289
+ min: minValue,
290
+ max: maxValue,
291
+ weekStartDay,
292
+ T,
293
+ });
294
+ updateFirstWeek(adjusted.firstWeek);
295
+ },
296
+ [
297
+ resolvedFirstWeek,
298
+ weekCount,
299
+ overflowBehavior,
300
+ minValue,
301
+ maxValue,
302
+ weekStartDay,
303
+ T,
304
+ updateFirstWeek,
305
+ ],
306
+ );
307
+
308
+ const goPrev = useCallback(
309
+ (shiftBy?: number) => {
310
+ const shift = shiftBy ?? weekCount;
311
+ const target = resolvedFirstWeek.subtract({ weeks: shift });
312
+ const adjusted = applyOverflow({
313
+ targetFirstWeek: target,
314
+ weekCount,
315
+ behavior: overflowBehavior,
316
+ min: minValue,
317
+ max: maxValue,
318
+ weekStartDay,
319
+ T,
320
+ });
321
+ updateFirstWeek(adjusted.firstWeek);
322
+ },
323
+ [
324
+ resolvedFirstWeek,
325
+ weekCount,
326
+ overflowBehavior,
327
+ minValue,
328
+ maxValue,
329
+ weekStartDay,
330
+ T,
331
+ updateFirstWeek,
332
+ ],
333
+ );
334
+
335
+ // --- scrollToWeek ---
336
+ const scrollToWeek = useCallback(
337
+ (target: FirstWeekSpec, options?: { snap?: "start" | "center" | "end" | "nearest" }) => {
338
+ const resolvedTarget = resolveSpec(target);
339
+ const newFirstWeek = resolveFirstWeek(resolvedFirstWeek, weekCount, resolvedTarget, options);
340
+ const adjusted = applyOverflow({
341
+ targetFirstWeek: newFirstWeek,
342
+ weekCount,
343
+ behavior: overflowBehavior,
344
+ min: minValue,
345
+ max: maxValue,
346
+ weekStartDay,
347
+ T,
348
+ });
349
+ updateFirstWeek(adjusted.firstWeek);
350
+ },
351
+ [
352
+ resolvedFirstWeek,
353
+ weekCount,
354
+ resolveSpec,
355
+ overflowBehavior,
356
+ minValue,
357
+ maxValue,
358
+ weekStartDay,
359
+ T,
360
+ updateFirstWeek,
361
+ ],
362
+ );
363
+
364
+ // --- Fire onWindowChange ---
365
+ const onWindowChangeRef = useRef(onWindowChange);
366
+ onWindowChangeRef.current = onWindowChange;
367
+ const prevWindowInfoRef = useRef<WindowInfo | null>(null);
368
+
369
+ useEffect(() => {
370
+ const prev = prevWindowInfoRef.current;
371
+ const changed =
372
+ !prev ||
373
+ T.PlainDate.compare(prev.windowStart, windowInfo.windowStart) !== 0 ||
374
+ T.PlainDate.compare(prev.windowEnd, windowInfo.windowEnd) !== 0 ||
375
+ prev.weekCount !== windowInfo.weekCount;
376
+ if (changed) {
377
+ prevWindowInfoRef.current = windowInfo;
378
+ onWindowChangeRef.current?.(windowInfo);
379
+ }
380
+ }, [windowInfo, T]);
381
+
382
+ // --- Build context values ---
383
+ const stableCtx = useMemo<WeeksViewStableContextValue>(
384
+ () => ({
385
+ weekCount,
386
+ scrollBy,
387
+ overflowBehavior,
388
+ goNext,
389
+ goPrev,
390
+ scrollToWeek,
391
+ gridFocusedRef,
392
+ setGridLabelId,
393
+ }),
394
+ [weekCount, scrollBy, overflowBehavior, goNext, goPrev, scrollToWeek, setGridLabelId],
395
+ );
396
+
397
+ const stateCtx = useMemo<WeeksViewStateContextValue>(
398
+ () => ({
399
+ focusedDate,
400
+ windowInfo,
401
+ gridLabelIds,
402
+ weeks: adjustedWeeks,
403
+ currentDateTime,
404
+ }),
405
+ [focusedDate, windowInfo, gridLabelIds, adjustedWeeks, currentDateTime],
406
+ );
407
+
408
+ const viewCtx = useMemo<ViewContextValue>(
409
+ () => ({
410
+ viewType: "weeks" as const,
411
+ focusedDate,
412
+ setFocusedDate,
413
+ tabTargetDate,
414
+ gridHasFocus,
415
+ setGridHasFocus,
416
+ }),
417
+ [focusedDate, tabTargetDate, gridHasFocus],
418
+ );
419
+
420
+ return { stableCtx, stateCtx, viewCtx, scrollToWeek };
421
+ }