@klinking/colander 3.1.0-alpha.7 → 3.1.0-alpha.9

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 (72) hide show
  1. package/dist/formats/date.cjs +2 -3
  2. package/dist/formats/date.d.cts +10 -14
  3. package/dist/formats/date.d.mts +10 -14
  4. package/dist/formats/date.mjs +2 -3
  5. package/dist/formats/object.cjs +2 -3
  6. package/dist/formats/object.d.cts +10 -14
  7. package/dist/formats/object.d.mts +10 -14
  8. package/dist/formats/object.mjs +2 -3
  9. package/dist/formats/plain-date-time.cjs +2 -3
  10. package/dist/formats/plain-date-time.d.cts +10 -14
  11. package/dist/formats/plain-date-time.d.mts +10 -14
  12. package/dist/formats/plain-date-time.mjs +2 -3
  13. package/dist/formats/plain-date.cjs +2 -3
  14. package/dist/formats/plain-date.d.cts +10 -14
  15. package/dist/formats/plain-date.d.mts +10 -14
  16. package/dist/formats/plain-date.mjs +2 -3
  17. package/dist/formats/plain-month-day.cjs +2 -3
  18. package/dist/formats/plain-month-day.d.cts +10 -14
  19. package/dist/formats/plain-month-day.d.mts +10 -14
  20. package/dist/formats/plain-month-day.mjs +2 -3
  21. package/dist/formats/plain-year-month.cjs +2 -3
  22. package/dist/formats/plain-year-month.d.cts +10 -14
  23. package/dist/formats/plain-year-month.d.mts +10 -14
  24. package/dist/formats/plain-year-month.mjs +2 -3
  25. package/dist/formats/zoned-date-time.cjs +2 -3
  26. package/dist/formats/zoned-date-time.d.cts +10 -14
  27. package/dist/formats/zoned-date-time.d.mts +10 -14
  28. package/dist/formats/zoned-date-time.mjs +2 -3
  29. package/dist/{weeks-view-context-BTojXkys.d.cts → index-B5VJ_WF2.d.mts} +91 -114
  30. package/dist/{weeks-view-context-CFXV8orh.d.mts → index-BMsxaq1s.d.cts} +91 -114
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.d.cts +1 -10
  33. package/dist/index.d.mts +1 -10
  34. package/dist/index.mjs +1 -2
  35. package/dist/{weeks-navigation-CPevz3Xg.cjs → weeks-navigation-CUQApLMk.cjs} +531 -400
  36. package/dist/{weeks-navigation-BSKwFvdP.mjs → weeks-navigation-CWNpF_6M.mjs} +531 -399
  37. package/package.json +21 -18
  38. package/src/calendar-provider.test.tsx +1 -1
  39. package/src/calendar-provider.tsx +8 -2
  40. package/src/compute-weeks-in-window.test.ts +1 -1
  41. package/src/day-cell-state.test.ts +1 -1
  42. package/src/day-cell-state.ts +0 -70
  43. package/src/day-cell-store.test.tsx +273 -0
  44. package/src/day-cell-store.tsx +204 -0
  45. package/src/day-cell.test.tsx +73 -90
  46. package/src/day-cell.tsx +93 -78
  47. package/src/formats/formats.test.ts +1 -1
  48. package/src/grid.event-perf.test.tsx +7 -1
  49. package/src/grid.perf.test.tsx +7 -1
  50. package/src/grid.tsx +17 -15
  51. package/src/keyboard.test.ts +1 -1
  52. package/src/month-separator.test.tsx +1 -1
  53. package/src/month-view.bounds.test.tsx +1 -1
  54. package/src/month-view.test.tsx +89 -1
  55. package/src/month-view.tsx +17 -7
  56. package/src/month-window.test.ts +1 -1
  57. package/src/out-of-range.test.ts +1 -1
  58. package/src/range-preview.test.ts +1 -1
  59. package/src/resolve-first-week.test.ts +1 -1
  60. package/src/store.ts +72 -0
  61. package/src/today.test.tsx +8 -1
  62. package/src/utils.bench.ts +158 -106
  63. package/src/utils.test.ts +1 -1
  64. package/src/view-context.test.tsx +1 -1
  65. package/src/view-context.ts +2 -0
  66. package/src/weeks-grid.tsx +20 -10
  67. package/src/weeks-keyboard.test.ts +1 -1
  68. package/src/weeks-view-state.ts +1 -1
  69. package/src/weeks-view.bounds.test.tsx +1 -1
  70. package/src/weeks-view.test.tsx +1 -1
  71. package/src/weeks-view.tsx +2 -1
  72. package/src/weeks-window.test.ts +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@klinking/colander",
3
- "version": "3.1.0-alpha.7",
3
+ "version": "3.1.0-alpha.9",
4
4
  "homepage": "https://github.com/klink-ing/colander#readme",
5
5
  "bugs": "https://github.com/klink-ing/colander/issues",
6
6
  "license": "MIT",
@@ -126,25 +126,28 @@
126
126
  }
127
127
  }
128
128
  },
129
+ "dependencies": {
130
+ "use-sync-external-store": "^1.7.0"
131
+ },
129
132
  "devDependencies": {
130
- "@base-ui/react": "^1.3.0",
133
+ "@base-ui/react": "^1.9.0",
131
134
  "@js-temporal/polyfill": "^0.5.1",
132
- "@playwright/test": "^1.58.2",
133
- "@testing-library/dom": "^10.4.1",
134
- "@testing-library/react": "^16.3.2",
135
- "@types/react": "^19.2.0",
136
- "@types/react-dom": "^19.2.0",
137
- "@vitejs/plugin-react": "^4.7.0",
138
- "jsdom": "^28.1.0",
139
- "oxlint": "^1.58.0",
140
- "react": "^19.2.0",
141
- "react-dom": "^19.2.0",
142
- "rollup-plugin-visualizer": "^7.0.1",
143
- "tsx": "^4.21.0",
144
- "typescript": "^5",
145
- "vite": "npm:@voidzero-dev/vite-plus-core@^0.1.16",
146
- "vite-plus": "latest",
147
- "vitest": "npm:@voidzero-dev/vite-plus-test@latest"
135
+ "@playwright/test": "^1.65.2",
136
+ "@testing-library/dom": "^10.4.2",
137
+ "@testing-library/react": "^16.3.3",
138
+ "@types/react": "^19.3.3",
139
+ "@types/react-dom": "^19.3.0",
140
+ "@types/use-sync-external-store": "^1.7.0",
141
+ "@vitejs/plugin-react": "^6.3.0",
142
+ "jsdom": "^31.0.1",
143
+ "react": "^19.3.1",
144
+ "react-dom": "^19.3.1",
145
+ "rollup-plugin-visualizer": "^7.3.0",
146
+ "ts-morph": "^28.0.0",
147
+ "tsx": "^4.23.15",
148
+ "typescript": "^7.0.2",
149
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8001",
150
+ "vite-plus": "1.8.0"
148
151
  },
149
152
  "peerDependencies": {
150
153
  "@base-ui/react": ">=1.0.0",
@@ -1,7 +1,7 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { render, act, cleanup } from "@testing-library/react";
3
3
  import type { ComponentProps } from "react";
4
- import { describe, it, expect, vi, afterEach } from "vitest";
4
+ import { describe, it, expect, vi, afterEach } from "vite-plus/test";
5
5
  import { useCalendarStable, useCalendarState } from "./calendar-context";
6
6
  import { CalendarProvider } from "./calendar-provider";
7
7
 
@@ -19,6 +19,7 @@ import {
19
19
  truncateDatesForMode,
20
20
  type SelectionResult,
21
21
  } from "./root-selection";
22
+ import { useStableCallback } from "./store";
22
23
  import type {
23
24
  BaseRootState,
24
25
  DateRange,
@@ -466,7 +467,7 @@ function CalendarProvider<F extends ValueFormat = "PlainDate">(
466
467
  ]);
467
468
 
468
469
  // --- onSelect ---
469
- const onSelect = useCallback(
470
+ const onSelectLatest = useCallback(
470
471
  (date: Temporal.PlainDate) => {
471
472
  const result = computeSelectionUpdate<F>({
472
473
  date,
@@ -515,7 +516,7 @@ function CalendarProvider<F extends ValueFormat = "PlainDate">(
515
516
  );
516
517
 
517
518
  // --- setRange ---
518
- const setRange = useCallback(
519
+ const setRangeLatest = useCallback(
519
520
  (start: Temporal.PlainDate, end: Temporal.PlainDate) => {
520
521
  const result = computeSetRangeUpdate<F>({
521
522
  start,
@@ -545,6 +546,11 @@ function CalendarProvider<F extends ValueFormat = "PlainDate">(
545
546
  ],
546
547
  );
547
548
 
549
+ // Stable identities: both close over the committed selection, and the stable
550
+ // context holding them would otherwise change on every selection.
551
+ const onSelect = useStableCallback(onSelectLatest);
552
+ const setRange = useStableCallback(setRangeLatest);
553
+
548
554
  // --- Selected dates (non-null) ---
549
555
  const nonNullDates = useMemo(
550
556
  () => committedDates.filter((d): d is Temporal.PlainDate => d != null),
@@ -1,5 +1,5 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
- import { describe, it, expect } from "vitest";
2
+ import { describe, it, expect } from "vite-plus/test";
3
3
  import { computeWeeksInWindow } from "./compute-weeks-in-window";
4
4
 
5
5
  const T = Temporal;
@@ -1,5 +1,5 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
- import { describe, expect, it } from "vitest";
2
+ import { describe, expect, it } from "vite-plus/test";
3
3
  import { computeDayCellState, dayCellStateEqual } from "./day-cell-state";
4
4
  import type { DayCellInputs } from "./day-cell-state";
5
5
  import type { OutsideDays } from "./types";
@@ -1,7 +1,4 @@
1
1
  import type { Temporal } from "@js-temporal/polyfill";
2
- import { useContext } from "react";
3
- import { useCalendarStable, useCalendarState } from "./calendar-context";
4
- import { WeekDataContext, GridContext } from "./context";
5
2
  import type { GridOrientation } from "./context";
6
3
  import type {
7
4
  DayCellTemplateState,
@@ -9,7 +6,6 @@ import type {
9
6
  TemporalNamespace,
10
7
  } from "./types";
11
8
  import { isInRange as isInRangeUtil } from "./utils";
12
- import { useViewContext, useViewStable, useViewState } from "./view-context";
13
9
 
14
10
  /** A day cell's state: the public {@link DayCellTemplateState} plus the roving-tabindex flag. */
15
11
  export type DayCellState = DayCellTemplateState & { isTabTarget: boolean };
@@ -246,69 +242,3 @@ export function dayCellStateEqual(a: DayCellState, b: DayCellState): boolean {
246
242
  }
247
243
  return true;
248
244
  }
249
-
250
- /**
251
- * Reads the contexts a day cell depends on and returns a function that derives
252
- * the state of any cell. `columnIndex` defaults to the date's column in a
253
- * week starting on the calendar's `weekStartDay`.
254
- */
255
- export function useDayCellDeriver(): (
256
- date: Temporal.PlainDate,
257
- columnIndex?: number,
258
- ) => DayCellState {
259
- const { orientation } = useContext(GridContext);
260
- const weekData = useContext(WeekDataContext);
261
- const {
262
- disabled,
263
- isDateDisabled,
264
- selectionMode,
265
- temporal: T,
266
- today,
267
- weekStartDay,
268
- } = useCalendarStable();
269
- const { selectedDates, rangeStart, rangeEnd, previewStart, previewEnd } =
270
- useCalendarState();
271
- const viewCtx = useViewContext();
272
- const { focusedDate, tabTargetDate } = viewCtx;
273
- const { rootState, currentDateTime } = useViewState();
274
- const { outsideDays } = useViewStable();
275
-
276
- const inputs: DayCellInputs = {
277
- T,
278
- today: today(),
279
- orientation,
280
- rootState,
281
- selectionMode,
282
- selectedDates,
283
- rangeStart,
284
- rangeEnd,
285
- previewStart,
286
- previewEnd,
287
- disabled,
288
- isDateDisabled,
289
- focusedDate,
290
- tabTargetDate,
291
- outsideDays,
292
- };
293
-
294
- // A weeks view has no "current month": every cell is in its own month, so
295
- // `outsideMonth` is always false. Otherwise a cell belongs to the month of
296
- // the grid it sits in (set per grid in multi-month mode).
297
- const isWeeksView = viewCtx.viewType === "weeks";
298
- const gridMonth = weekData?.gridMonth ?? currentDateTime;
299
-
300
- return (date, columnIndex) => {
301
- const daysInWeek = date.daysInWeek;
302
- return computeDayCellState(
303
- date,
304
- {
305
- columnIndex:
306
- columnIndex ??
307
- ((date.dayOfWeek % daysInWeek) - weekStartDay + daysInWeek) %
308
- daysInWeek,
309
- month: isWeeksView ? { year: date.year, month: date.month } : gridMonth,
310
- },
311
- inputs,
312
- );
313
- };
314
- }
@@ -0,0 +1,273 @@
1
+ // @vitest-environment jsdom
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+ import { act, fireEvent, render } from "@testing-library/react";
4
+ import { Suspense, startTransition, useState, type ReactNode } from "react";
5
+ import { describe, expect, it } from "vite-plus/test";
6
+ import { DayButton, DayCellTemplate } from "./day-cell";
7
+ import { Grid, GridBody, WeekTemplate } from "./grid";
8
+ import { MonthView } from "./month-view";
9
+ import type { DayCellTemplateState } from "./types";
10
+
11
+ const temporal = {
12
+ Now: Temporal.Now,
13
+ PlainDate: Temporal.PlainDate,
14
+ PlainDateTime: Temporal.PlainDateTime,
15
+ PlainMonthDay: Temporal.PlainMonthDay,
16
+ PlainYearMonth: Temporal.PlainYearMonth,
17
+ };
18
+ const base = {
19
+ temporal,
20
+ locale: "en-US",
21
+ timeZone: "America/New_York",
22
+ format: "PlainDate" as const,
23
+ };
24
+ const d = (s: string) => Temporal.PlainDate.from(s);
25
+
26
+ /** March 2026 without fixed weeks renders 5 rows of 7 cells. */
27
+ const MARCH_CELLS = 35;
28
+
29
+ /** Counts render-function calls; cleared between the setup and the action. */
30
+ let renders = 0;
31
+
32
+ const readsNothing = (props: object) => {
33
+ renders++;
34
+ return <td {...props} />;
35
+ };
36
+ const readsRoot = (props: object, state: DayCellTemplateState) => {
37
+ renders++;
38
+ return <td {...props} data-root-selected={String(state.root.selected)} />;
39
+ };
40
+ const buttonReadsNothing = (props: object) => {
41
+ renders++;
42
+ return <button {...props} />;
43
+ };
44
+ const buttonReadsRoot = (props: object, state: DayCellTemplateState) => {
45
+ renders++;
46
+ return <button {...props} data-root-selected={String(state.root.selected)} />;
47
+ };
48
+
49
+ function Cells(props: { children: ReactNode }) {
50
+ return (
51
+ <Grid>
52
+ <GridBody>
53
+ <WeekTemplate>{props.children}</WeekTemplate>
54
+ </GridBody>
55
+ </Grid>
56
+ );
57
+ }
58
+
59
+ function rootValues(container: HTMLElement) {
60
+ return new Set(
61
+ [...container.querySelectorAll("[data-root-selected]")].map((el) =>
62
+ el.getAttribute("data-root-selected"),
63
+ ),
64
+ );
65
+ }
66
+
67
+ describe("day cells subscribe to the store per date", () => {
68
+ it.each([
69
+ {
70
+ description:
71
+ "a cell render that ignores root re-renders the two cells that changed",
72
+ cells: <DayCellTemplate render={readsNothing} />,
73
+ expected: { renders: 2, rootValues: [] },
74
+ },
75
+ {
76
+ description:
77
+ "a cell render that reads root re-renders every cell, none stale",
78
+ cells: <DayCellTemplate render={readsRoot} />,
79
+ expected: { renders: MARCH_CELLS, rootValues: ["2026-03-20"] },
80
+ },
81
+ {
82
+ description:
83
+ "a DayButton child that ignores root re-renders the two buttons that changed",
84
+ cells: (
85
+ <DayCellTemplate>
86
+ <DayButton render={buttonReadsNothing} />
87
+ </DayCellTemplate>
88
+ ),
89
+ expected: { renders: 2, rootValues: [] },
90
+ },
91
+ {
92
+ description:
93
+ "a DayButton child that reads root re-renders every button, none stale",
94
+ cells: (
95
+ <DayCellTemplate>
96
+ <DayButton render={buttonReadsRoot} />
97
+ </DayCellTemplate>
98
+ ),
99
+ expected: { renders: MARCH_CELLS, rootValues: ["2026-03-20"] },
100
+ },
101
+ ])("$description", ({ cells, expected }) => {
102
+ const ui = (value: Temporal.PlainDate) => (
103
+ <MonthView {...base} value={value}>
104
+ <Cells>{cells}</Cells>
105
+ </MonthView>
106
+ );
107
+ const { container, rerender } = render(ui(d("2026-03-15")));
108
+ renders = 0;
109
+
110
+ rerender(ui(d("2026-03-20")));
111
+
112
+ expect({
113
+ renders,
114
+ rootValues: [...rootValues(container)],
115
+ }).toEqual(expected);
116
+ });
117
+
118
+ it("moving focus with the keyboard re-renders only the two buttons it moved between", () => {
119
+ const { container } = render(
120
+ <MonthView {...base} defaultValue={d("2026-03-15")}>
121
+ <Cells>
122
+ <DayCellTemplate>
123
+ <DayButton render={buttonReadsNothing} />
124
+ </DayCellTemplate>
125
+ </Cells>
126
+ </MonthView>,
127
+ );
128
+ renders = 0;
129
+
130
+ const grid = container.querySelector('[role="grid"]')!;
131
+ act(() => {
132
+ grid.dispatchEvent(
133
+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }),
134
+ );
135
+ });
136
+
137
+ expect({
138
+ renders,
139
+ focused: container
140
+ .querySelector("button[data-focused]")
141
+ ?.getAttribute("data-date"),
142
+ }).toEqual({ renders: 2, focused: "2026-03-16" });
143
+ });
144
+
145
+ it("a hover preview re-renders only the cells entering the preview", () => {
146
+ const { container } = render(
147
+ <MonthView
148
+ {...base}
149
+ selectionMode="range"
150
+ month={Temporal.PlainYearMonth.from("2026-03")}
151
+ >
152
+ <Cells>
153
+ <DayCellTemplate>
154
+ <DayButton render={buttonReadsNothing} />
155
+ </DayCellTemplate>
156
+ </Cells>
157
+ </MonthView>,
158
+ );
159
+ const button = (date: string) =>
160
+ container.querySelector(`button[data-date="${date}"]`)!;
161
+ fireEvent.click(button("2026-03-10"));
162
+ renders = 0;
163
+
164
+ fireEvent.pointerOver(button("2026-03-14"));
165
+
166
+ expect({
167
+ renders,
168
+ previewed: container.querySelectorAll(
169
+ "button[data-range-preview-in-range]",
170
+ ).length,
171
+ }).toEqual({ renders: 5, previewed: 5 });
172
+ });
173
+
174
+ it("cells mounted by a month change see that month's state on first render", () => {
175
+ const { container } = render(
176
+ <MonthView {...base} defaultValue={d("2026-03-31")}>
177
+ <Cells>
178
+ <DayCellTemplate>
179
+ <DayButton />
180
+ </DayCellTemplate>
181
+ </Cells>
182
+ </MonthView>,
183
+ );
184
+
185
+ const grid = container.querySelector('[role="grid"]')!;
186
+ act(() => {
187
+ grid.dispatchEvent(
188
+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }),
189
+ );
190
+ });
191
+ act(() => {
192
+ grid.dispatchEvent(
193
+ new KeyboardEvent("keydown", { key: "PageDown", bubbles: true }),
194
+ );
195
+ });
196
+
197
+ expect({
198
+ focused: container
199
+ .querySelector("button[data-focused]")
200
+ ?.getAttribute("data-date"),
201
+ firstInMonth: container
202
+ .querySelector("td:not([data-outside-month])")
203
+ ?.getAttribute("data-date"),
204
+ }).toEqual({ focused: "2026-05-01", firstInMonth: "2026-05-01" });
205
+ });
206
+
207
+ it("a standalone DayButton tracks its own date's state", () => {
208
+ const ui = (value: Temporal.PlainDate) => (
209
+ <MonthView {...base} value={value}>
210
+ <DayButton date={d("2026-03-20")} />
211
+ </MonthView>
212
+ );
213
+ const { container, rerender } = render(ui(d("2026-03-15")));
214
+ const button = () => container.querySelector("button")!;
215
+ const before = button().hasAttribute("data-selected");
216
+
217
+ rerender(ui(d("2026-03-20")));
218
+
219
+ expect({ before, after: button().hasAttribute("data-selected") }).toEqual({
220
+ before: false,
221
+ after: true,
222
+ });
223
+ });
224
+
225
+ it("a suspended transition's value stays out of cells that re-render meanwhile", async () => {
226
+ const never = new Promise(() => {});
227
+ function SuspendOn20(props: { value: Temporal.PlainDate }) {
228
+ if (props.value.day === 20) throw never;
229
+ return null;
230
+ }
231
+ let setValue!: (value: Temporal.PlainDate) => void;
232
+ let setClassName!: (className: string) => void;
233
+ function UserCells() {
234
+ const [className, set] = useState("a");
235
+ setClassName = set;
236
+ return (
237
+ <Cells>
238
+ <DayCellTemplate className={className}>
239
+ <DayButton />
240
+ </DayCellTemplate>
241
+ </Cells>
242
+ );
243
+ }
244
+ function App() {
245
+ const [value, set] = useState(d("2026-03-15"));
246
+ setValue = set;
247
+ return (
248
+ <>
249
+ <MonthView {...base} value={value}>
250
+ <UserCells />
251
+ </MonthView>
252
+ <Suspense fallback={null}>
253
+ <SuspendOn20 value={value} />
254
+ </Suspense>
255
+ </>
256
+ );
257
+ }
258
+ const { container } = render(<App />);
259
+
260
+ // The transition renders the calendar with 03-20, then suspends, so it
261
+ // never commits. A re-render of the cells alone must still show 03-15.
262
+ await act(async () => {
263
+ startTransition(() => setValue(d("2026-03-20")));
264
+ });
265
+ act(() => setClassName("b"));
266
+
267
+ expect(
268
+ [...container.querySelectorAll("button[data-selected]")].map((b) =>
269
+ b.getAttribute("data-date"),
270
+ ),
271
+ ).toEqual(["2026-03-15"]);
272
+ });
273
+ });
@@ -0,0 +1,204 @@
1
+ import type { Temporal } from "@js-temporal/polyfill";
2
+ import {
3
+ createContext,
4
+ useCallback,
5
+ useContext,
6
+ useMemo,
7
+ useRef,
8
+ useState,
9
+ } from "react";
10
+ import { useCalendarStable, useCalendarState } from "./calendar-context";
11
+ import { GridContext, WeekDataContext } from "./context";
12
+ import {
13
+ computeDayCellState,
14
+ dayCellStateEqual,
15
+ type DayCellInputs,
16
+ type DayCellState,
17
+ } from "./day-cell-state";
18
+ import { createStore, useIsoLayoutEffect, useStoreSelector } from "./store";
19
+ import type { Store } from "./store";
20
+ import { useViewContext, useViewStable, useViewState } from "./view-context";
21
+
22
+ /** Everything a day cell's state is derived from, apart from its own position. */
23
+ interface DayCellStoreState {
24
+ inputs: Omit<DayCellInputs, "orientation">;
25
+ viewType: "month" | "weeks";
26
+ /** The month a cell outside a multi-month grid belongs to. */
27
+ viewMonth: { year: number; month: number };
28
+ weekStartDay: number;
29
+ }
30
+
31
+ type MonthKey = { year: number; month: number };
32
+
33
+ /** @internal The view's day-cell store. Its identity never changes. */
34
+ export const DayCellStoreContext =
35
+ createContext<Store<DayCellStoreState> | null>(null);
36
+
37
+ /**
38
+ * Publishes the calendar and view state that day cells derive from. Cells
39
+ * subscribe per date, so a change re-renders only the cells it affects instead
40
+ * of every cell under a context.
41
+ *
42
+ * The store is seeded on the first render and updated only after a change
43
+ * commits, never during render: a render React discards (a suspended
44
+ * transition) must not leak into cells that re-render meanwhile. Cells that
45
+ * render in the same pass as a change read the previous state first, then
46
+ * re-render from the layout effect before the browser paints.
47
+ */
48
+ export function DayCellStoreProvider(props: { children?: React.ReactNode }) {
49
+ const {
50
+ disabled,
51
+ isDateDisabled,
52
+ selectionMode,
53
+ temporal: T,
54
+ today,
55
+ weekStartDay,
56
+ } = useCalendarStable();
57
+ const { selectedDates, rangeStart, rangeEnd, previewStart, previewEnd } =
58
+ useCalendarState();
59
+ const { viewType, focusedDate, tabTargetDate } = useViewContext();
60
+ const { rootState, currentDateTime } = useViewState();
61
+ const { outsideDays } = useViewStable();
62
+ const todayKey = today().toString();
63
+ const { year, month } = currentDateTime;
64
+
65
+ const snapshot = useMemo<DayCellStoreState>(
66
+ () => ({
67
+ inputs: {
68
+ T,
69
+ today: T.PlainDate.from(todayKey),
70
+ rootState,
71
+ selectionMode,
72
+ selectedDates,
73
+ rangeStart,
74
+ rangeEnd,
75
+ previewStart,
76
+ previewEnd,
77
+ disabled,
78
+ isDateDisabled,
79
+ focusedDate,
80
+ tabTargetDate,
81
+ outsideDays,
82
+ },
83
+ viewType,
84
+ viewMonth: { year, month },
85
+ weekStartDay,
86
+ }),
87
+ [
88
+ T,
89
+ todayKey,
90
+ rootState,
91
+ selectionMode,
92
+ selectedDates,
93
+ rangeStart,
94
+ rangeEnd,
95
+ previewStart,
96
+ previewEnd,
97
+ disabled,
98
+ isDateDisabled,
99
+ focusedDate,
100
+ tabTargetDate,
101
+ outsideDays,
102
+ viewType,
103
+ year,
104
+ month,
105
+ weekStartDay,
106
+ ],
107
+ );
108
+
109
+ const [store] = useState(() => createStore(snapshot));
110
+ useIsoLayoutEffect(() => store.set(snapshot), [store, snapshot]);
111
+
112
+ return (
113
+ <DayCellStoreContext.Provider value={store}>
114
+ {props.children}
115
+ </DayCellStoreContext.Provider>
116
+ );
117
+ }
118
+
119
+ /**
120
+ * Hands `state` to render functions with `root` as a non-enumerable getter
121
+ * that calls `onReadRoot`. Base UI's data-attribute pass only walks
122
+ * enumerable keys, so `root` counts as read only when user code reads it.
123
+ */
124
+ function withLazyRoot(
125
+ state: DayCellState,
126
+ onReadRoot: () => void,
127
+ ): DayCellState {
128
+ const { root, ...rest } = state;
129
+ return Object.defineProperty(rest, "root", {
130
+ get() {
131
+ onReadRoot();
132
+ return root;
133
+ },
134
+ enumerable: false,
135
+ }) as DayCellState;
136
+ }
137
+
138
+ /**
139
+ * Subscribes to one day cell's state. The cell re-renders only when a field
140
+ * it renders changes; `root` joins that comparison once a render function has
141
+ * read `state.root`, so cells that never read it ignore focus and selection
142
+ * changes elsewhere in the grid.
143
+ */
144
+ export function useDayCellState(
145
+ date: Temporal.PlainDate,
146
+ columnIndex?: number,
147
+ gridMonth?: MonthKey,
148
+ ): DayCellState {
149
+ const store = useContext(DayCellStoreContext);
150
+ if (!store) {
151
+ throw new Error("Day cells must be used inside MonthView or WeeksView.");
152
+ }
153
+ const { orientation } = useContext(GridContext);
154
+ const readsRoot = useRef(false);
155
+
156
+ const select = useCallback(
157
+ (s: DayCellStoreState): DayCellState => {
158
+ const daysInWeek = date.daysInWeek;
159
+ return computeDayCellState(
160
+ date,
161
+ {
162
+ columnIndex:
163
+ columnIndex ??
164
+ ((date.dayOfWeek % daysInWeek) - s.weekStartDay + daysInWeek) %
165
+ daysInWeek,
166
+ // A weeks view has no "current month": each cell is in its own.
167
+ month:
168
+ s.viewType === "weeks"
169
+ ? { year: date.year, month: date.month }
170
+ : (gridMonth ?? s.viewMonth),
171
+ },
172
+ { ...s.inputs, orientation },
173
+ );
174
+ },
175
+ [date, columnIndex, gridMonth, orientation],
176
+ );
177
+
178
+ const isEqual = useCallback(
179
+ (a: DayCellState, b: DayCellState) =>
180
+ a.date === b.date &&
181
+ a.columnIndex === b.columnIndex &&
182
+ a.orientation === b.orientation &&
183
+ dayCellStateEqual(a, b) &&
184
+ (!readsRoot.current || a.root === b.root),
185
+ [],
186
+ );
187
+
188
+ const state = useStoreSelector(store, select, isEqual);
189
+ return useMemo(
190
+ () =>
191
+ withLazyRoot(state, () => {
192
+ readsRoot.current = true;
193
+ }),
194
+ [state],
195
+ );
196
+ }
197
+
198
+ /** Like {@link useDayCellState}, taking the grid month from the enclosing week. */
199
+ export function useStandaloneDayCellState(
200
+ date: Temporal.PlainDate,
201
+ ): DayCellState {
202
+ const weekData = useContext(WeekDataContext);
203
+ return useDayCellState(date, undefined, weekData?.gridMonth);
204
+ }