@klinking/colander 3.1.0-alpha.1 → 3.1.0-alpha.10

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 (98) 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-CNAq2Hiu.d.cts → index-K1_zOIpa.d.mts} +198 -114
  30. package/dist/{weeks-view-context-CsP3PBiu.d.mts → index-bRoYX03d.d.cts} +198 -114
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.d.cts +2 -11
  33. package/dist/index.d.mts +2 -11
  34. package/dist/index.mjs +1 -2
  35. package/dist/{weeks-navigation-CJzhxbgj.cjs → weeks-navigation-3UTRiTUP.cjs} +1102 -952
  36. package/dist/{weeks-navigation-Bg0nZLgh.mjs → weeks-navigation-BoHqK5fq.mjs} +1102 -951
  37. package/package.json +21 -18
  38. package/src/calendar-provider.test.tsx +88 -1
  39. package/src/calendar-provider.tsx +89 -73
  40. package/src/calendar-types.ts +2 -0
  41. package/src/compute-weeks-in-window.test.ts +1 -1
  42. package/src/day-cell-state.test.ts +214 -0
  43. package/src/day-cell-state.ts +244 -0
  44. package/src/day-cell-store.test.tsx +273 -0
  45. package/src/day-cell-store.tsx +204 -0
  46. package/src/day-cell.test.tsx +73 -90
  47. package/src/day-cell.tsx +106 -444
  48. package/src/drag-handle.tsx +2 -2
  49. package/src/formats/date.ts +2 -0
  50. package/src/formats/formats.test.ts +1 -1
  51. package/src/formats/object.ts +2 -0
  52. package/src/formats/plain-date-time.ts +2 -0
  53. package/src/formats/plain-date.ts +2 -0
  54. package/src/formats/plain-month-day.ts +2 -0
  55. package/src/formats/plain-year-month.ts +2 -0
  56. package/src/formats/zoned-date-time.ts +2 -0
  57. package/src/grid-header.tsx +3 -3
  58. package/src/grid.event-perf.test.tsx +7 -1
  59. package/src/grid.perf.test.tsx +7 -1
  60. package/src/grid.tsx +38 -77
  61. package/src/index.ts +2 -0
  62. package/src/keyboard.test.ts +1 -1
  63. package/src/month-separator.test.tsx +1 -1
  64. package/src/month-view-navigation.ts +180 -0
  65. package/src/month-view-types.ts +3 -0
  66. package/src/month-view.bounds.test.tsx +136 -0
  67. package/src/month-view.test.tsx +89 -1
  68. package/src/month-view.tsx +74 -217
  69. package/src/month-window.test.ts +207 -0
  70. package/src/month-window.ts +93 -0
  71. package/src/navigation.tsx +18 -76
  72. package/src/out-of-range.test.ts +34 -54
  73. package/src/out-of-range.ts +47 -123
  74. package/src/range-preview.test.ts +120 -0
  75. package/src/range-preview.tsx +3 -5
  76. package/src/resolve-first-week.test.ts +1 -1
  77. package/src/root-selection.ts +99 -97
  78. package/src/selected-range.tsx +3 -5
  79. package/src/store.ts +72 -0
  80. package/src/today.test.tsx +105 -0
  81. package/src/types.ts +24 -1
  82. package/src/utils.bench.ts +158 -106
  83. package/src/utils.test.ts +26 -1
  84. package/src/utils.ts +40 -9
  85. package/src/view-context.test.tsx +126 -0
  86. package/src/view-context.ts +45 -0
  87. package/src/week-number.test.tsx +76 -0
  88. package/src/week-number.tsx +48 -19
  89. package/src/weeks-grid.tsx +20 -10
  90. package/src/weeks-keyboard.test.ts +1 -1
  91. package/src/weeks-navigation.tsx +15 -31
  92. package/src/weeks-view-state.ts +67 -101
  93. package/src/weeks-view-types.ts +4 -1
  94. package/src/weeks-view.bounds.test.tsx +246 -0
  95. package/src/weeks-view.test.tsx +116 -14
  96. package/src/weeks-view.tsx +24 -52
  97. package/src/weeks-window.test.ts +131 -0
  98. package/src/weeks-window.ts +102 -0
@@ -1,8 +1,9 @@
1
- import { Children, createContext, forwardRef, isValidElement, memo, useCallback, useContext, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from "react";
1
+ import { Children, createContext, forwardRef, isValidElement, memo, useCallback, useContext, useEffect, useId, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2
+ import { useSyncExternalStoreWithSelector } from "use-sync-external-store/shim/with-selector";
2
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
4
  import { mergeProps } from "@base-ui/react/merge-props";
4
5
  import { useRender } from "@base-ui/react/use-render";
5
- //#region src/calendar-context.ts
6
+ // src/calendar-context.ts
6
7
  /** @internal React context carrying stable CalendarProvider values (callbacks, config). */
7
8
  const CalendarStableContext = createContext(null);
8
9
  /** @internal React context carrying volatile CalendarProvider state. */
@@ -19,8 +20,7 @@ function useCalendarState() {
19
20
  if (!ctx) throw new Error("useCalendarState must be used within CalendarProvider");
20
21
  return ctx;
21
22
  }
22
- //#endregion
23
- //#region src/utils.ts
23
+ // src/utils.ts
24
24
  /**
25
25
  * Resolves a {@link TemporalNamespace} instance.
26
26
  *
@@ -47,6 +47,17 @@ function getSystemTimeZone(T) {
47
47
  return T.Now.timeZoneId();
48
48
  }
49
49
  /**
50
+ * The date a view opens on: the selected date, else today in the provider's time zone.
51
+ *
52
+ * @param selected - The currently selected value, or `undefined`.
53
+ * @param today - Reads today's date in the provider's time zone.
54
+ * @param timeZone - IANA time zone.
55
+ * @param T - Temporal namespace.
56
+ */
57
+ function resolveInitialAnchor(selected, today, timeZone, T) {
58
+ return selectedToZdt(selected, timeZone, T)?.toPlainDate() ?? today();
59
+ }
60
+ /**
50
61
  * Converts any {@link DateValueObject} into a `Temporal.ZonedDateTime`.
51
62
  *
52
63
  * Handles all supported value formats (`PlainDate`, `PlainDateTime`,
@@ -439,24 +450,32 @@ function getWeekdayNames(locale, T, weekStartDay = 0) {
439
450
  /**
440
451
  * Computes the ISO 8601 week number for a given date.
441
452
  *
442
- * The ISO week number is determined by the Thursday of the date's ISO week.
453
+ * The ISO week number is determined by the Thursday of the date's ISO week:
454
+ * a week belongs to the year that contains the majority of its days, i.e.
455
+ * the year containing its midpoint day. For 7-day weeks this is exactly
456
+ * ISO 8601 (Thursday rule, Jan 4 always in week 1).
457
+ *
458
+ * For calendars whose weeks have N ≠ 7 days, the same construction is
459
+ * generalized: the midpoint is day ⌈N/2⌉ of the week, and the anchor date
460
+ * that is always in week 1 is January (N − ⌈N/2⌉ + 1).
443
461
  *
444
462
  * @param date - The date to compute the week number for.
445
463
  * @param T - Temporal namespace.
446
464
  */
447
465
  function getISOWeekNumber(date, T) {
448
- const thursday = date.add({ days: 4 - date.dayOfWeek });
449
- const jan4 = T.PlainDate.from({
450
- year: thursday.year,
466
+ const daysInWeek = date.daysInWeek;
467
+ const midpoint = Math.ceil(daysInWeek / 2);
468
+ const midDay = date.add({ days: midpoint - date.dayOfWeek });
469
+ const anchor = T.PlainDate.from({
470
+ year: midDay.year,
451
471
  month: 1,
452
- day: 4
472
+ day: daysInWeek - midpoint + 1
453
473
  });
454
- const jan4Thursday = jan4.add({ days: 4 - jan4.dayOfWeek });
455
- const daysDiff = thursday.since(jan4Thursday, { largestUnit: "days" }).days;
456
- return Math.round(daysDiff / 7) + 1;
474
+ const anchorMidDay = anchor.add({ days: midpoint - anchor.dayOfWeek });
475
+ const daysDiff = midDay.since(anchorMidDay, { largestUnit: "days" }).days;
476
+ return Math.round(daysDiff / daysInWeek) + 1;
457
477
  }
458
- //#endregion
459
- //#region src/root-selection.ts
478
+ // src/root-selection.ts
460
479
  /** Construct a DateRange (workaround for TS generic conditional type widening). */
461
480
  function mkRange(start, end) {
462
481
  return {
@@ -474,6 +493,18 @@ function tagRaw(raw, format) {
474
493
  value: raw
475
494
  };
476
495
  }
496
+ /**
497
+ * Decodes a range value into committed dates. An empty range is `[]`; a range
498
+ * with only an end is `[end, null]` (pending start, so the end is still the
499
+ * anchor of the next click).
500
+ */
501
+ function decodeRange(range, toPlain) {
502
+ const start = range.start != null ? toPlain(range.start) : null;
503
+ const end = range.end != null ? toPlain(range.end) : null;
504
+ if (start === null && end === null) return [];
505
+ if (start === null && end !== null) return [end, null];
506
+ return [start, end];
507
+ }
477
508
  /** Resolve a `RangeMode` to a concrete "start" | "end" | "reset" action for inside-range clicks. */
478
509
  function resolveInsideAction(mode, date, start, end) {
479
510
  if (mode === "adjust-start") return "start";
@@ -752,23 +783,19 @@ function truncateDatesForMode(opts) {
752
783
  return clamped;
753
784
  }
754
785
  /**
755
- * Pure utility that computes the preview range for a hovered date, using the
756
- * same logic as the internal hook. Useful for deriving the preview in an
757
- * `onHoveredDateChange` handler without needing a controlled `previewRange`.
786
+ * The range a click on `hoveredDate` would produce, or `null` when the click
787
+ * would do nothing (read-only, disabled date). One path for both the
788
+ * provider's own preview and the public {@link computePreviewRange}.
758
789
  */
759
- function computePreviewRange(hoveredDate, currentRange, rangeMode, preventRangeReversal = false, T) {
760
- const Temporal = T ?? globalThis.Temporal;
761
- if (!Temporal) throw new Error("computePreviewRange requires a Temporal namespace. Pass it as the 5th argument or ensure globalThis.Temporal is available.");
762
- const rawStart = currentRange?.start != null ? Temporal.PlainDate.from(currentRange.start) : null;
763
- const rawEnd = currentRange?.end != null ? Temporal.PlainDate.from(currentRange.end) : null;
764
- const committedDates = currentRange ? rawStart === null && rawEnd !== null ? [rawEnd, null] : [rawStart, rawEnd] : [];
790
+ function computeRangePreview(input) {
791
+ const { hoveredDate, committedDates, rangeMode, allowRangeReversal, readOnly, isDateDisabled, T } = input;
765
792
  const committedStart = committedDates[0] ?? void 0;
766
- const committedEnd = committedDates[1] ?? void 0;
767
- const noop = () => [];
793
+ const committedEnd = committedDates.length > 1 ? committedDates[committedDates.length - 1] ?? void 0 : committedStart;
794
+ const unused = () => [];
768
795
  const result = computeSelectionUpdate({
769
796
  date: hoveredDate,
770
- readOnly: false,
771
- isDateDisabled: () => false,
797
+ readOnly,
798
+ isDateDisabled,
772
799
  isMultiple: false,
773
800
  isRange: true,
774
801
  committedDates,
@@ -776,23 +803,83 @@ function computePreviewRange(hoveredDate, currentRange, rangeMode, preventRangeR
776
803
  committedEnd,
777
804
  selectedZdt: void 0,
778
805
  rangeMode,
779
- allowRangeReversal: !preventRangeReversal,
780
- sortDates: (d) => [...d].sort((a, b) => Temporal.PlainDate.compare(a, b)),
781
- currentSingleFormatted: noop,
782
- currentRangeFormatted: () => currentRange,
783
- currentMultipleFormatted: noop,
806
+ allowRangeReversal,
807
+ sortDates: (d) => [...d].sort((a, b) => T.PlainDate.compare(a, b)),
808
+ currentSingleFormatted: unused,
809
+ currentRangeFormatted: unused,
810
+ currentMultipleFormatted: unused,
784
811
  resolvedFormat: "PlainDate",
785
812
  timeZone: "UTC",
786
- T: Temporal
813
+ T
787
814
  });
788
815
  if (result.skip || result.newDates.length === 0) return null;
789
816
  const start = result.newDates[0];
790
817
  const end = result.newDates.length > 1 ? result.newDates[1] : start;
791
818
  if (start == null || end == null) return null;
792
- return mkRange(start, end);
819
+ return [start, end];
820
+ }
821
+ /**
822
+ * Pure utility that computes the preview range for a hovered date, using the
823
+ * same logic as the built-in hover preview. Useful for deriving the preview in
824
+ * an `onHoveredDateChange` handler without needing a controlled `previewRange`.
825
+ *
826
+ * Pass `options.isDateDisabled` and `options.readOnly` to match a calendar that
827
+ * disables dates or is read-only; by default every date is selectable.
828
+ */
829
+ function computePreviewRange(hoveredDate, currentRange, rangeMode, preventRangeReversal = false, T, options = {}) {
830
+ const Temporal = T ?? globalThis.Temporal;
831
+ if (!Temporal) throw new Error("computePreviewRange requires a Temporal namespace. Pass it as the 5th argument or ensure globalThis.Temporal is available.");
832
+ const preview = computeRangePreview({
833
+ hoveredDate,
834
+ committedDates: currentRange ? decodeRange(currentRange, (raw) => Temporal.PlainDate.from(raw)) : [],
835
+ rangeMode,
836
+ allowRangeReversal: !preventRangeReversal,
837
+ readOnly: options.readOnly ?? false,
838
+ isDateDisabled: options.isDateDisabled ?? (() => false),
839
+ T: Temporal
840
+ });
841
+ return preview ? mkRange(preview[0], preview[1]) : null;
842
+ }
843
+ // src/store.ts
844
+ function createStore(initial) {
845
+ let state = initial;
846
+ const listeners = /* @__PURE__ */ new Set();
847
+ return {
848
+ get: () => state,
849
+ set: (next) => {
850
+ if (Object.is(state, next)) return;
851
+ state = next;
852
+ for (const listener of listeners) listener();
853
+ },
854
+ subscribe: (listener) => {
855
+ listeners.add(listener);
856
+ return () => listeners.delete(listener);
857
+ }
858
+ };
859
+ }
860
+ /** `useLayoutEffect` in the browser, `useEffect` on the server (no warning). */
861
+ const useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
862
+ /**
863
+ * Subscribes to the slice of `store` that `select` picks. The component
864
+ * re-renders only when `isEqual` says the slice changed; otherwise the
865
+ * previously returned slice is handed back, keeping its identity.
866
+ */
867
+ function useStoreSelector(store, select, isEqual) {
868
+ return useSyncExternalStoreWithSelector(store.subscribe, store.get, store.get, select, isEqual);
869
+ }
870
+ /**
871
+ * Returns a function with a stable identity that always calls the latest
872
+ * `fn`, so contexts holding it don't change when its closure does. Call it
873
+ * from event handlers and effects, not during render.
874
+ */
875
+ function useStableCallback(fn) {
876
+ const latest = useRef(fn);
877
+ useInsertionEffect(() => {
878
+ latest.current = fn;
879
+ });
880
+ return useCallback((...args) => latest.current(...args), []);
793
881
  }
794
- //#endregion
795
- //#region src/calendar-provider.tsx
882
+ // src/calendar-provider.tsx
796
883
  /**
797
884
  * Provides shared calendar state (selection, config, range preview) to all
798
885
  * descendant view components. Does NOT manage focus, navigation, or grid data.
@@ -803,6 +890,7 @@ function CalendarProvider(props) {
803
890
  const locale = localeProp ?? "en-US";
804
891
  const timeZone = timeZoneProp ?? getSystemTimeZone(T);
805
892
  const weekStartDay = weekStartDayProp ?? 0;
893
+ const today = useCallback(() => T.Now.zonedDateTimeISO(timeZone).toPlainDate(), [T, timeZone]);
806
894
  const resolvedFormat = formatProp ?? "PlainDate";
807
895
  const selectionMode = selectionModeProp ?? "single";
808
896
  const disabled = disabledProp ?? false;
@@ -880,13 +968,7 @@ function CalendarProvider(props) {
880
968
  }
881
969
  if (isRange) {
882
970
  if (rangeValue === null) return [];
883
- if (rangeValue) {
884
- const start = rangeValue.start != null ? rawToPlain(rangeValue.start) : null;
885
- const end = rangeValue.end != null ? rawToPlain(rangeValue.end) : null;
886
- if (start === null && end === null) return [];
887
- if (start === null && end !== null) return [end, null];
888
- return [start, end];
889
- }
971
+ if (rangeValue) return decodeRange(rangeValue, rawToPlain);
890
972
  return;
891
973
  }
892
974
  if (singleValue === null) return [];
@@ -900,18 +982,27 @@ function CalendarProvider(props) {
900
982
  rawToPlain,
901
983
  sortDates
902
984
  ]);
903
- const [internalDates, setInternalDates] = useState(useMemo(() => {
985
+ const warnedMalformedRef = useRef(false);
986
+ useEffect(() => {
987
+ if (!(valueProp != null && (isRange && !isDateRange(valueProp) || isMultiple && !Array.isArray(valueProp)))) {
988
+ warnedMalformedRef.current = false;
989
+ return;
990
+ }
991
+ if (warnedMalformedRef.current) return;
992
+ warnedMalformedRef.current = true;
993
+ if (isRange) console.warn(`[DatePicker] selectionMode="range" expects \`value\` to be a { start, end } DateRange or null, but received ${Array.isArray(valueProp) ? "an array" : typeof valueProp}. Ignoring it and falling back to uncontrolled.`);
994
+ else console.warn(`[DatePicker] selectionMode="multiple" expects \`value\` to be an array or null, but received ${typeof valueProp}. Ignoring it and falling back to uncontrolled.`);
995
+ }, [
996
+ valueProp,
997
+ isRange,
998
+ isMultiple
999
+ ]);
1000
+ const defaultDates = useMemo(() => {
904
1001
  if (isMultiple) {
905
1002
  if (multipleDefault) return sortDates(multipleDefault.map(rawToPlain));
906
1003
  return [];
907
1004
  }
908
- if (rangeDefault) {
909
- const start = rangeDefault.start != null ? rawToPlain(rangeDefault.start) : null;
910
- const end = rangeDefault.end != null ? rawToPlain(rangeDefault.end) : null;
911
- if (start === null && end === null) return [];
912
- if (start === null && end !== null) return [end, null];
913
- return [start, end];
914
- }
1005
+ if (rangeDefault) return decodeRange(rangeDefault, rawToPlain);
915
1006
  if (singleDefault != null) return [rawToPlain(singleDefault)];
916
1007
  return [];
917
1008
  }, [
@@ -921,7 +1012,8 @@ function CalendarProvider(props) {
921
1012
  singleDefault,
922
1013
  rawToPlain,
923
1014
  sortDates
924
- ]));
1015
+ ]);
1016
+ const [internalDates, setInternalDates] = useState(defaultDates);
925
1017
  const isControlled = controlledDates !== void 0;
926
1018
  const committedDates = isControlled ? controlledDates : internalDates;
927
1019
  const rangeStart = !isMultiple && committedDates.length > 0 ? committedDates[0] ?? void 0 : void 0;
@@ -997,40 +1089,18 @@ function CalendarProvider(props) {
997
1089
  const [previewStart, previewEnd] = useMemo(() => {
998
1090
  if (previewRangeProp !== void 0) {
999
1091
  if (!previewRangeProp) return [void 0, void 0];
1000
- const rawToPlainLocal = (raw) => {
1001
- return toZonedDateTime({
1002
- format: resolvedFormat,
1003
- value: raw
1004
- }, timeZone, T).toPlainDate();
1005
- };
1006
- return [previewRangeProp.start != null ? rawToPlainLocal(previewRangeProp.start) : void 0, previewRangeProp.end != null ? rawToPlainLocal(previewRangeProp.end) : void 0];
1092
+ return [previewRangeProp.start != null ? rawToPlain(previewRangeProp.start) : void 0, previewRangeProp.end != null ? rawToPlain(previewRangeProp.end) : void 0];
1007
1093
  }
1008
1094
  if (!hoveredDate || !isRange) return [void 0, void 0];
1009
- const result = computeSelectionUpdate({
1010
- date: hoveredDate,
1095
+ return computeRangePreview({
1096
+ hoveredDate,
1011
1097
  readOnly,
1012
1098
  isDateDisabled,
1013
- isMultiple: false,
1014
- isRange: true,
1015
1099
  committedDates,
1016
- committedStart,
1017
- committedEnd,
1018
- selectedZdt: void 0,
1019
1100
  rangeMode,
1020
1101
  allowRangeReversal,
1021
- sortDates,
1022
- currentSingleFormatted,
1023
- currentRangeFormatted,
1024
- currentMultipleFormatted,
1025
- resolvedFormat,
1026
- timeZone,
1027
1102
  T
1028
- });
1029
- if (result.skip || result.newDates.length === 0) return [void 0, void 0];
1030
- const ps = result.newDates[0];
1031
- const pe = result.newDates.length > 1 ? result.newDates[1] : ps;
1032
- if (ps == null || pe == null) return [void 0, void 0];
1033
- return [ps, pe];
1103
+ }) ?? [void 0, void 0];
1034
1104
  }, [
1035
1105
  previewRangeProp,
1036
1106
  hoveredDate,
@@ -1038,16 +1108,9 @@ function CalendarProvider(props) {
1038
1108
  readOnly,
1039
1109
  isDateDisabled,
1040
1110
  committedDates,
1041
- committedStart,
1042
- committedEnd,
1043
1111
  rangeMode,
1044
1112
  allowRangeReversal,
1045
- sortDates,
1046
- currentSingleFormatted,
1047
- currentRangeFormatted,
1048
- currentMultipleFormatted,
1049
- resolvedFormat,
1050
- timeZone,
1113
+ rawToPlain,
1051
1114
  T
1052
1115
  ]);
1053
1116
  const prevModeRef = useRef(selectionMode);
@@ -1069,22 +1132,35 @@ function CalendarProvider(props) {
1069
1132
  plainToFormatValue,
1070
1133
  isControlled
1071
1134
  ]);
1135
+ const warnedOutOfBoundsRef = useRef(false);
1072
1136
  useEffect(() => {
1073
1137
  if (isRange || isMultiple) return;
1074
1138
  const start = committedStart;
1075
- if (!start) return;
1076
- if (minValue && T.PlainDate.compare(start, minValue) < 0 || maxValue && T.PlainDate.compare(start, maxValue) > 0) {
1077
- const prev = currentSingleFormatted();
1078
- commitSelection({
1079
- newDates: [],
1080
- fireCallback: (onValueChange) => {
1081
- onValueChange?.(null, {
1082
- date: void 0,
1083
- previous: prev
1084
- });
1085
- }
1086
- });
1139
+ if (!start) {
1140
+ warnedOutOfBoundsRef.current = false;
1141
+ return;
1142
+ }
1143
+ if (!(minValue && T.PlainDate.compare(start, minValue) < 0 || maxValue && T.PlainDate.compare(start, maxValue) > 0)) {
1144
+ warnedOutOfBoundsRef.current = false;
1145
+ return;
1087
1146
  }
1147
+ if (isControlled) {
1148
+ if (!warnedOutOfBoundsRef.current) {
1149
+ warnedOutOfBoundsRef.current = true;
1150
+ console.warn(`[DatePicker] The controlled \`value\` is outside the min/max range. It stays selected (rendered disabled) until you update \`value\`; the component will not clear it for you.`);
1151
+ }
1152
+ return;
1153
+ }
1154
+ const prev = currentSingleFormatted();
1155
+ commitSelection({
1156
+ newDates: [],
1157
+ fireCallback: (onValueChange) => {
1158
+ onValueChange?.(null, {
1159
+ date: void 0,
1160
+ previous: prev
1161
+ });
1162
+ }
1163
+ });
1088
1164
  }, [
1089
1165
  minValue,
1090
1166
  maxValue,
@@ -1093,9 +1169,10 @@ function CalendarProvider(props) {
1093
1169
  currentSingleFormatted,
1094
1170
  T,
1095
1171
  isRange,
1096
- isMultiple
1172
+ isMultiple,
1173
+ isControlled
1097
1174
  ]);
1098
- const onSelect = useCallback((date) => {
1175
+ const onSelectLatest = useCallback((date) => {
1099
1176
  const result = computeSelectionUpdate({
1100
1177
  date,
1101
1178
  readOnly,
@@ -1139,7 +1216,7 @@ function CalendarProvider(props) {
1139
1216
  currentRangeFormatted,
1140
1217
  currentMultipleFormatted
1141
1218
  ]);
1142
- const setRange = useCallback((start, end) => {
1219
+ const setRangeLatest = useCallback((start, end) => {
1143
1220
  const result = computeSetRangeUpdate({
1144
1221
  start,
1145
1222
  end,
@@ -1165,6 +1242,8 @@ function CalendarProvider(props) {
1165
1242
  resolvedFormat,
1166
1243
  T
1167
1244
  ]);
1245
+ const onSelect = useStableCallback(onSelectLatest);
1246
+ const setRange = useStableCallback(setRangeLatest);
1168
1247
  const nonNullDates = useMemo(() => committedDates.filter((d) => d != null), [committedDates]);
1169
1248
  const stableCtx = useMemo(() => ({
1170
1249
  onSelect,
@@ -1176,6 +1255,7 @@ function CalendarProvider(props) {
1176
1255
  ...minValue !== void 0 && { minValue },
1177
1256
  ...maxValue !== void 0 && { maxValue },
1178
1257
  timeZone,
1258
+ today,
1179
1259
  locale,
1180
1260
  temporal: T,
1181
1261
  weekStartDay,
@@ -1193,6 +1273,7 @@ function CalendarProvider(props) {
1193
1273
  minValue,
1194
1274
  maxValue,
1195
1275
  timeZone,
1276
+ today,
1196
1277
  locale,
1197
1278
  T,
1198
1279
  weekStartDay,
@@ -1245,8 +1326,293 @@ function CalendarProvider(props) {
1245
1326
  })
1246
1327
  });
1247
1328
  }
1248
- //#endregion
1249
- //#region src/month-view-context.ts
1329
+ // src/context.ts
1330
+ /** @internal Provides the days and index of the current week row to child components. */
1331
+ const WeekDataContext = createContext(null);
1332
+ /** @internal Provides the resolved grid orientation to descendant cells. */
1333
+ const GridContext = createContext({ orientation: "horizontal" });
1334
+ /** @internal Provides the date and column index from a `DayCellTemplate` to its child `DayButton`. */
1335
+ const DayCellDataContext = createContext(null);
1336
+ /** @internal Provides per-grid month data to WeekTemplate and DayCellTemplate. */
1337
+ const GridMonthContext = createContext(null);
1338
+ // src/day-cell-state.ts
1339
+ const NO_RANGE = {
1340
+ rangeStart: false,
1341
+ rangeEnd: false,
1342
+ rangeBoundary: false,
1343
+ inRange: false,
1344
+ rangeIndex: false,
1345
+ rangeLength: false,
1346
+ rangeHasStart: false,
1347
+ rangeHasEnd: false,
1348
+ rangePreviewStart: false,
1349
+ rangePreviewEnd: false,
1350
+ rangePreviewBoundary: false,
1351
+ rangePreviewInRange: false,
1352
+ rangePreviewIndex: false,
1353
+ rangePreviewLength: false,
1354
+ rangePreviewHasStart: false,
1355
+ rangePreviewHasEnd: false
1356
+ };
1357
+ function computeRangeState(date, inputs) {
1358
+ const { T, selectionMode, rangeStart, rangeEnd, previewStart, previewEnd } = inputs;
1359
+ if (selectionMode !== "range") return NO_RANGE;
1360
+ const isRangeStart = rangeStart ? T.PlainDate.compare(date, rangeStart) === 0 : false;
1361
+ const isRangeEnd = rangeEnd ? T.PlainDate.compare(date, rangeEnd) === 0 : false;
1362
+ const inRange = isInRange(date, rangeStart, rangeEnd, T) !== false;
1363
+ const effectiveStart = rangeStart ?? rangeEnd;
1364
+ const effectiveEnd = rangeEnd ?? rangeStart;
1365
+ const isPreviewStart = previewStart ? T.PlainDate.compare(date, previewStart) === 0 : false;
1366
+ const isPreviewEnd = previewEnd ? T.PlainDate.compare(date, previewEnd) === 0 : false;
1367
+ const inPreview = previewStart && previewEnd ? isInRange(date, previewStart, previewEnd, T) !== false : false;
1368
+ return {
1369
+ rangeStart: isRangeStart,
1370
+ rangeEnd: isRangeEnd,
1371
+ rangeBoundary: isRangeStart || isRangeEnd,
1372
+ inRange,
1373
+ rangeIndex: inRange && effectiveStart ? date.since(effectiveStart).days : false,
1374
+ rangeLength: inRange && effectiveStart && effectiveEnd ? effectiveEnd.since(effectiveStart).days + 1 : false,
1375
+ rangeHasStart: inRange && rangeStart !== void 0,
1376
+ rangeHasEnd: inRange && rangeEnd !== void 0,
1377
+ rangePreviewStart: isPreviewStart,
1378
+ rangePreviewEnd: isPreviewEnd,
1379
+ rangePreviewBoundary: isPreviewStart || isPreviewEnd,
1380
+ rangePreviewInRange: inPreview,
1381
+ rangePreviewIndex: inPreview && previewStart ? date.since(previewStart).days : false,
1382
+ rangePreviewLength: inPreview && previewStart && previewEnd ? previewEnd.since(previewStart).days + 1 : false,
1383
+ rangePreviewHasStart: inPreview && previewStart !== void 0,
1384
+ rangePreviewHasEnd: inPreview && previewEnd !== void 0
1385
+ };
1386
+ }
1387
+ /** Derives the state of one day cell. Pure function, no hooks. */
1388
+ function computeDayCellState(date, position, inputs) {
1389
+ const { T, outsideDays } = inputs;
1390
+ const { columnIndex, month } = position;
1391
+ const isCurrentMonth = date.year === month.year && date.month === month.month;
1392
+ const base = {
1393
+ root: inputs.rootState,
1394
+ date,
1395
+ columnIndex,
1396
+ orientation: inputs.orientation
1397
+ };
1398
+ if (!isCurrentMonth && outsideDays === "hidden") return {
1399
+ ...base,
1400
+ ...NO_RANGE,
1401
+ outsideMonth: true,
1402
+ hidden: true,
1403
+ selected: false,
1404
+ today: false,
1405
+ disabled: true,
1406
+ focused: false,
1407
+ isTabTarget: false
1408
+ };
1409
+ const isToday = T.PlainDate.compare(date, inputs.today) === 0;
1410
+ if (!isCurrentMonth && outsideDays !== "enabled") {
1411
+ const suppressRange = outsideDays === "disabled";
1412
+ return {
1413
+ ...base,
1414
+ ...suppressRange ? NO_RANGE : computeRangeState(date, inputs),
1415
+ outsideMonth: true,
1416
+ hidden: false,
1417
+ selected: false,
1418
+ today: isToday,
1419
+ disabled: true,
1420
+ focused: false,
1421
+ isTabTarget: false
1422
+ };
1423
+ }
1424
+ return {
1425
+ ...base,
1426
+ ...computeRangeState(date, inputs),
1427
+ outsideMonth: !isCurrentMonth,
1428
+ hidden: false,
1429
+ selected: inputs.selectionMode !== "range" ? inputs.selectedDates.some((d) => T.PlainDate.compare(d, date) === 0) : false,
1430
+ today: isToday,
1431
+ disabled: inputs.disabled || (inputs.isDateDisabled?.(date) ?? false),
1432
+ focused: T.PlainDate.compare(date, inputs.focusedDate) === 0,
1433
+ isTabTarget: T.PlainDate.compare(date, inputs.tabTargetDate) === 0
1434
+ };
1435
+ }
1436
+ const COMPARED_KEYS = Object.keys({
1437
+ outsideMonth: true,
1438
+ hidden: true,
1439
+ selected: true,
1440
+ today: true,
1441
+ disabled: true,
1442
+ focused: true,
1443
+ rangeStart: true,
1444
+ rangeEnd: true,
1445
+ rangeBoundary: true,
1446
+ inRange: true,
1447
+ rangeIndex: true,
1448
+ rangeLength: true,
1449
+ rangeHasStart: true,
1450
+ rangeHasEnd: true,
1451
+ rangePreviewStart: true,
1452
+ rangePreviewEnd: true,
1453
+ rangePreviewBoundary: true,
1454
+ rangePreviewInRange: true,
1455
+ rangePreviewIndex: true,
1456
+ rangePreviewLength: true,
1457
+ rangePreviewHasStart: true,
1458
+ rangePreviewHasEnd: true,
1459
+ isTabTarget: true
1460
+ });
1461
+ /** Whether two cell states render the same cell. */
1462
+ function dayCellStateEqual(a, b) {
1463
+ for (const key of COMPARED_KEYS) if (a[key] !== b[key]) return false;
1464
+ return true;
1465
+ }
1466
+ // src/view-context.ts
1467
+ /** @internal React context for the active view (MonthView or WeeksView). */
1468
+ const ViewContext = createContext(null);
1469
+ /** Returns the nearest view context (MonthView or WeeksView). */
1470
+ function useViewContext() {
1471
+ const ctx = useContext(ViewContext);
1472
+ if (!ctx) throw new Error("useViewContext must be used within MonthView or WeeksView");
1473
+ return ctx;
1474
+ }
1475
+ /** @internal Context for {@link ViewStableContextValue}. */
1476
+ const ViewStableContext = createContext(null);
1477
+ /** @internal Context for {@link ViewStateContextValue}. */
1478
+ const ViewStateContext = createContext(null);
1479
+ /** Returns the nearest view's stable values. */
1480
+ function useViewStable() {
1481
+ const ctx = useContext(ViewStableContext);
1482
+ if (!ctx) throw new Error("useViewStable must be used within MonthView or WeeksView");
1483
+ return ctx;
1484
+ }
1485
+ /** Returns the nearest view's volatile state. */
1486
+ function useViewState() {
1487
+ const ctx = useContext(ViewStateContext);
1488
+ if (!ctx) throw new Error("useViewState must be used within MonthView or WeeksView");
1489
+ return ctx;
1490
+ }
1491
+ // src/day-cell-store.tsx
1492
+ /** @internal The view's day-cell store. Its identity never changes. */
1493
+ const DayCellStoreContext = createContext(null);
1494
+ /**
1495
+ * Publishes the calendar and view state that day cells derive from. Cells
1496
+ * subscribe per date, so a change re-renders only the cells it affects instead
1497
+ * of every cell under a context.
1498
+ *
1499
+ * The store is seeded on the first render and updated only after a change
1500
+ * commits, never during render: a render React discards (a suspended
1501
+ * transition) must not leak into cells that re-render meanwhile. Cells that
1502
+ * render in the same pass as a change read the previous state first, then
1503
+ * re-render from the layout effect before the browser paints.
1504
+ */
1505
+ function DayCellStoreProvider(props) {
1506
+ const { disabled, isDateDisabled, selectionMode, temporal: T, today, weekStartDay } = useCalendarStable();
1507
+ const { selectedDates, rangeStart, rangeEnd, previewStart, previewEnd } = useCalendarState();
1508
+ const { viewType, focusedDate, tabTargetDate } = useViewContext();
1509
+ const { rootState, currentDateTime } = useViewState();
1510
+ const { outsideDays } = useViewStable();
1511
+ const todayKey = today().toString();
1512
+ const { year, month } = currentDateTime;
1513
+ const snapshot = useMemo(() => ({
1514
+ inputs: {
1515
+ T,
1516
+ today: T.PlainDate.from(todayKey),
1517
+ rootState,
1518
+ selectionMode,
1519
+ selectedDates,
1520
+ rangeStart,
1521
+ rangeEnd,
1522
+ previewStart,
1523
+ previewEnd,
1524
+ disabled,
1525
+ isDateDisabled,
1526
+ focusedDate,
1527
+ tabTargetDate,
1528
+ outsideDays
1529
+ },
1530
+ viewType,
1531
+ viewMonth: {
1532
+ year,
1533
+ month
1534
+ },
1535
+ weekStartDay
1536
+ }), [
1537
+ T,
1538
+ todayKey,
1539
+ rootState,
1540
+ selectionMode,
1541
+ selectedDates,
1542
+ rangeStart,
1543
+ rangeEnd,
1544
+ previewStart,
1545
+ previewEnd,
1546
+ disabled,
1547
+ isDateDisabled,
1548
+ focusedDate,
1549
+ tabTargetDate,
1550
+ outsideDays,
1551
+ viewType,
1552
+ year,
1553
+ month,
1554
+ weekStartDay
1555
+ ]);
1556
+ const [store] = useState(() => createStore(snapshot));
1557
+ useIsoLayoutEffect(() => store.set(snapshot), [store, snapshot]);
1558
+ return /* @__PURE__ */ jsx(DayCellStoreContext.Provider, {
1559
+ value: store,
1560
+ children: props.children
1561
+ });
1562
+ }
1563
+ /**
1564
+ * Hands `state` to render functions with `root` as a non-enumerable getter
1565
+ * that calls `onReadRoot`. Base UI's data-attribute pass only walks
1566
+ * enumerable keys, so `root` counts as read only when user code reads it.
1567
+ */
1568
+ function withLazyRoot(state, onReadRoot) {
1569
+ const { root, ...rest } = state;
1570
+ return Object.defineProperty(rest, "root", {
1571
+ get() {
1572
+ onReadRoot();
1573
+ return root;
1574
+ },
1575
+ enumerable: false
1576
+ });
1577
+ }
1578
+ /**
1579
+ * Subscribes to one day cell's state. The cell re-renders only when a field
1580
+ * it renders changes; `root` joins that comparison once a render function has
1581
+ * read `state.root`, so cells that never read it ignore focus and selection
1582
+ * changes elsewhere in the grid.
1583
+ */
1584
+ function useDayCellState(date, columnIndex, gridMonth) {
1585
+ const store = useContext(DayCellStoreContext);
1586
+ if (!store) throw new Error("Day cells must be used inside MonthView or WeeksView.");
1587
+ const { orientation } = useContext(GridContext);
1588
+ const readsRoot = useRef(false);
1589
+ const state = useStoreSelector(store, useCallback((s) => {
1590
+ const daysInWeek = date.daysInWeek;
1591
+ return computeDayCellState(date, {
1592
+ columnIndex: columnIndex ?? (date.dayOfWeek % daysInWeek - s.weekStartDay + daysInWeek) % daysInWeek,
1593
+ month: s.viewType === "weeks" ? {
1594
+ year: date.year,
1595
+ month: date.month
1596
+ } : gridMonth ?? s.viewMonth
1597
+ }, {
1598
+ ...s.inputs,
1599
+ orientation
1600
+ });
1601
+ }, [
1602
+ date,
1603
+ columnIndex,
1604
+ gridMonth,
1605
+ orientation
1606
+ ]), useCallback((a, b) => a.date === b.date && a.columnIndex === b.columnIndex && a.orientation === b.orientation && dayCellStateEqual(a, b) && (!readsRoot.current || a.root === b.root), []));
1607
+ return useMemo(() => withLazyRoot(state, () => {
1608
+ readsRoot.current = true;
1609
+ }), [state]);
1610
+ }
1611
+ /** Like {@link useDayCellState}, taking the grid month from the enclosing week. */
1612
+ function useStandaloneDayCellState(date) {
1613
+ return useDayCellState(date, void 0, useContext(WeekDataContext)?.gridMonth);
1614
+ }
1615
+ // src/month-view-context.ts
1250
1616
  /** @internal React context for MonthView stable values (config + callbacks). */
1251
1617
  const MonthViewStableContext = createContext(null);
1252
1618
  /** @internal React context for MonthView volatile state. */
@@ -1263,211 +1629,243 @@ function useMonthViewState() {
1263
1629
  if (!ctx) throw new Error("useMonthViewState must be used within MonthView.Root");
1264
1630
  return ctx;
1265
1631
  }
1266
- //#endregion
1267
- //#region src/view-context.ts
1268
- /** @internal React context for the active view (MonthView or WeeksView). */
1269
- const ViewContext = createContext(null);
1270
- /** Returns the nearest view context (MonthView or WeeksView). */
1271
- function useViewContext() {
1272
- const ctx = useContext(ViewContext);
1273
- if (!ctx) throw new Error("useViewContext must be used within MonthView or WeeksView");
1274
- return ctx;
1275
- }
1276
- //#endregion
1277
- //#region src/month-view.tsx
1278
- function MonthViewRoot(props) {
1279
- const { numberOfMonths: numberOfMonthsProp, fixedWeeks: fixedWeeksProp, outsideDays: outsideDaysProp, outOfRangeBehavior: outOfRangeBehaviorProp, month: monthProp, defaultMonth: defaultMonthProp, onMonthChange, children } = props;
1280
- const numberOfMonths = Math.max(1, Math.min(numberOfMonthsProp ?? 1, 12));
1281
- const fixedWeeks = fixedWeeksProp ?? false;
1282
- const outsideDays = outsideDaysProp ?? "enabled";
1283
- const outOfRangeBehavior = outOfRangeBehaviorProp ?? "unbounded";
1284
- const calStable = useCalendarStable();
1285
- const calState = useCalendarState();
1286
- const T = calStable.temporal;
1287
- const { timeZone, weekStartDay, isDateDisabled } = calStable;
1288
- const isMonthControlled = monthProp !== void 0;
1632
+ // src/month-view-navigation.ts
1633
+ /**
1634
+ * Owns which month the view shows, in both controlled and uncontrolled mode:
1635
+ * the month state, the Prev/Next steps, and syncing the window with focus.
1636
+ *
1637
+ * `onMonthChange` fires exactly once per move: from the effect below when
1638
+ * uncontrolled, and from the step or the focus-sync effect when controlled.
1639
+ */
1640
+ function useMonthNavigation(input) {
1641
+ const { month, defaultMonth, initialAnchor, onMonthChange, policy, focusedDate, setFocusedDate, T } = input;
1642
+ const isControlled = month !== void 0;
1289
1643
  const [internalMonth, setInternalMonth] = useState(() => {
1290
- if (monthProp) return {
1291
- year: monthProp.year,
1292
- month: monthProp.month
1644
+ if (month) return {
1645
+ year: month.year,
1646
+ month: month.month
1293
1647
  };
1294
- if (defaultMonthProp) return {
1295
- year: defaultMonthProp.year,
1296
- month: defaultMonthProp.month
1648
+ if (defaultMonth) return {
1649
+ year: defaultMonth.year,
1650
+ month: defaultMonth.month
1297
1651
  };
1298
- if (calState.selected) {
1299
- const zdt = toZonedDateTime(calState.selected, timeZone, T);
1300
- return {
1301
- year: zdt.year,
1302
- month: zdt.month
1303
- };
1304
- }
1305
- const now = T.Now.zonedDateTimeISO(timeZone);
1652
+ const anchor = initialAnchor();
1306
1653
  return {
1307
- year: now.year,
1308
- month: now.month
1654
+ year: anchor.year,
1655
+ month: anchor.month
1309
1656
  };
1310
1657
  });
1311
- const currentMonth = isMonthControlled ? {
1312
- year: monthProp.year,
1313
- month: monthProp.month
1314
- } : internalMonth;
1315
- const [focusedDate, setFocusedDate] = useState(() => {
1316
- if (calState.selected) return toZonedDateTime(calState.selected, timeZone, T).toPlainDate();
1317
- return T.Now.plainDateISO();
1318
- });
1319
- const [gridHasFocus, setGridHasFocus] = useState(false);
1320
- const gridFocusedRef = useRef(false);
1321
- const [gridLabelIds, setGridLabelIds] = useState({});
1322
- const setGridLabelId = useCallback((monthIndex, id) => {
1323
- setGridLabelIds((prev) => {
1324
- if (id === void 0) {
1325
- if (!(monthIndex in prev)) return prev;
1326
- const next = { ...prev };
1327
- delete next[monthIndex];
1328
- return next;
1329
- }
1330
- if (prev[monthIndex] === id) return prev;
1331
- return {
1332
- ...prev,
1333
- [monthIndex]: id
1334
- };
1335
- });
1336
- }, []);
1658
+ const year = isControlled ? month.year : internalMonth.year;
1659
+ const monthNumber = isControlled ? month.month : internalMonth.month;
1660
+ const currentMonth = useMemo(() => ({
1661
+ year,
1662
+ month: monthNumber
1663
+ }), [year, monthNumber]);
1664
+ const viewingYearMonth = useMemo(() => T.PlainYearMonth.from({
1665
+ year,
1666
+ month: monthNumber
1667
+ }), [
1668
+ year,
1669
+ monthNumber,
1670
+ T
1671
+ ]);
1337
1672
  const onMonthChangeRef = useRef(onMonthChange);
1338
1673
  onMonthChangeRef.current = onMonthChange;
1339
- const notifyMonth = useCallback((year, month) => {
1340
- onMonthChangeRef.current?.(T.PlainYearMonth.from({
1341
- year,
1342
- month
1343
- }));
1674
+ const notifyMonth = useCallback((target) => {
1675
+ onMonthChangeRef.current?.(T.PlainYearMonth.from(target));
1344
1676
  }, [T]);
1345
- const isMonthVisible = useCallback((targetYear, targetMonth) => {
1346
- for (let i = 0; i < numberOfMonths; i++) {
1347
- const totalMonths = currentMonth.year * 12 + (currentMonth.month - 1) + i;
1348
- const y = Math.floor(totalMonths / 12);
1349
- const m = totalMonths % 12 + 1;
1350
- if (targetYear === y && targetMonth === m) return true;
1351
- }
1352
- return false;
1353
- }, [
1354
- currentMonth.year,
1355
- currentMonth.month,
1356
- numberOfMonths
1357
- ]);
1358
- const navigateToMonth = useCallback((targetYear, targetMonth) => {
1359
- if (isMonthControlled) return;
1360
- setInternalMonth((prev) => {
1361
- const next = shiftWindowToMonth(prev, {
1362
- year: targetYear,
1363
- month: targetMonth
1364
- }, numberOfMonths);
1365
- if (next.year === prev.year && next.month === prev.month) return prev;
1366
- return next;
1367
- });
1368
- }, [isMonthControlled, numberOfMonths]);
1369
1677
  const skipFocusSyncForRef = useRef(null);
1370
1678
  const prevFocusedRef = useRef(focusedDate);
1371
1679
  useEffect(() => {
1372
1680
  skipFocusSyncForRef.current = null;
1373
- }, [monthProp?.year, monthProp?.month]);
1681
+ }, [month?.year, month?.month]);
1374
1682
  useEffect(() => {
1375
1683
  const prevFocused = prevFocusedRef.current;
1376
1684
  prevFocusedRef.current = focusedDate;
1377
- if (isMonthControlled) {
1685
+ const target = {
1686
+ year: focusedDate.year,
1687
+ month: focusedDate.month
1688
+ };
1689
+ if (isControlled) {
1378
1690
  if (skipFocusSyncForRef.current === focusedDate) {
1379
1691
  skipFocusSyncForRef.current = null;
1380
1692
  return;
1381
1693
  }
1382
1694
  if (prevFocused === focusedDate) return;
1383
- if (isMonthVisible(focusedDate.year, focusedDate.month)) return;
1384
- const next = shiftWindowToMonth({
1385
- year: currentMonth.year,
1386
- month: currentMonth.month
1387
- }, {
1388
- year: focusedDate.year,
1389
- month: focusedDate.month
1390
- }, numberOfMonths);
1391
- notifyMonth(next.year, next.month);
1695
+ if (policy.isVisible(currentMonth, target)) return;
1696
+ notifyMonth(policy.reveal(currentMonth, target));
1392
1697
  return;
1393
1698
  }
1394
- navigateToMonth(focusedDate.year, focusedDate.month);
1699
+ setInternalMonth((prev) => {
1700
+ const next = policy.reveal(prev, target);
1701
+ if (next.year === prev.year && next.month === prev.month) return prev;
1702
+ return next;
1703
+ });
1395
1704
  }, [
1396
1705
  focusedDate,
1397
- navigateToMonth,
1398
- isMonthControlled,
1399
- isMonthVisible,
1400
- notifyMonth,
1401
- currentMonth.year,
1402
- currentMonth.month,
1403
- numberOfMonths
1706
+ isControlled,
1707
+ policy,
1708
+ currentMonth,
1709
+ notifyMonth
1404
1710
  ]);
1405
- const goNextMonth = useCallback(() => {
1406
- if (isMonthControlled) {
1407
- const { year, month, firstDay } = computeAdjacentMonth({
1408
- year: monthProp.year,
1409
- month: monthProp.month
1410
- }, "next", T);
1411
- const nextFocus = focusedDateForMonth(focusedDate, {
1412
- year,
1413
- month
1414
- }, firstDay);
1711
+ const mountedRef = useRef(false);
1712
+ useEffect(() => {
1713
+ if (!mountedRef.current) {
1714
+ mountedRef.current = true;
1715
+ return;
1716
+ }
1717
+ if (isControlled) return;
1718
+ onMonthChangeRef.current?.(viewingYearMonth);
1719
+ }, [viewingYearMonth, isControlled]);
1720
+ const go = useCallback((direction) => {
1721
+ if (isControlled) {
1722
+ const step = policy.step(month, direction);
1723
+ if (step.blocked) return;
1724
+ const nextFocus = focusedDateForMonth(focusedDate, step.start, step.firstDay);
1415
1725
  skipFocusSyncForRef.current = nextFocus;
1416
- notifyMonth(year, month);
1726
+ notifyMonth(step.start);
1417
1727
  setFocusedDate(nextFocus);
1418
1728
  return;
1419
1729
  }
1420
1730
  setInternalMonth((m) => {
1421
- const { year, month, firstDay } = computeAdjacentMonth(m, "next", T);
1422
- setFocusedDate((prev) => focusedDateForMonth(prev, {
1423
- year,
1424
- month
1425
- }, firstDay));
1426
- return {
1427
- year,
1428
- month
1429
- };
1731
+ const step = policy.step(m, direction);
1732
+ if (step.blocked) return m;
1733
+ setFocusedDate((prev) => focusedDateForMonth(prev, step.start, step.firstDay));
1734
+ return step.start;
1430
1735
  });
1431
1736
  }, [
1432
- T,
1433
- isMonthControlled,
1434
- monthProp,
1737
+ isControlled,
1738
+ month,
1739
+ policy,
1435
1740
  notifyMonth,
1436
- focusedDate
1741
+ focusedDate,
1742
+ setFocusedDate
1437
1743
  ]);
1438
- const goPrevMonth = useCallback(() => {
1439
- if (isMonthControlled) {
1440
- const { year, month, firstDay } = computeAdjacentMonth({
1441
- year: monthProp.year,
1442
- month: monthProp.month
1443
- }, "prev", T);
1444
- const nextFocus = focusedDateForMonth(focusedDate, {
1445
- year,
1446
- month
1447
- }, firstDay);
1448
- skipFocusSyncForRef.current = nextFocus;
1449
- notifyMonth(year, month);
1450
- setFocusedDate(nextFocus);
1451
- return;
1744
+ return {
1745
+ currentMonth,
1746
+ viewingYearMonth,
1747
+ goNextMonth: useCallback(() => go("next"), [go]),
1748
+ goPrevMonth: useCallback(() => go("prev"), [go])
1749
+ };
1750
+ }
1751
+ // src/month-window.ts
1752
+ const monthIndex = (m) => m.year * 12 + (m.month - 1);
1753
+ /**
1754
+ * Builds the policy for a MonthView window of `numberOfMonths` months.
1755
+ *
1756
+ * `unbounded` never blocks a step: `min`/`max` only gate which days are
1757
+ * selectable, not which months can be viewed. Any other behavior is `stop`,
1758
+ * which blocks a step whose entering month lies beyond the bound's month.
1759
+ */
1760
+ function createMonthWindowPolicy(input) {
1761
+ const { numberOfMonths, behavior, min, max, T } = input;
1762
+ return {
1763
+ step(start, direction) {
1764
+ const adjacent = computeAdjacentMonth(start, direction, T);
1765
+ const newStart = {
1766
+ year: adjacent.year,
1767
+ month: adjacent.month
1768
+ };
1769
+ const entering = direction === "prev" ? newStart : monthAt(newStart, numberOfMonths - 1);
1770
+ let blocked = false;
1771
+ if (behavior !== "unbounded") {
1772
+ const bound = direction === "prev" ? min : max;
1773
+ if (bound) {
1774
+ const diff = monthIndex(entering) - monthIndex(bound);
1775
+ blocked = direction === "prev" ? diff < 0 : diff > 0;
1776
+ }
1777
+ }
1778
+ return {
1779
+ start: newStart,
1780
+ entering,
1781
+ firstDay: adjacent.firstDay,
1782
+ blocked
1783
+ };
1784
+ },
1785
+ isVisible(start, target) {
1786
+ const offset = monthIndex(target) - monthIndex(start);
1787
+ return offset >= 0 && offset < numberOfMonths;
1788
+ },
1789
+ reveal(start, target) {
1790
+ return shiftWindowToMonth(start, target, numberOfMonths);
1452
1791
  }
1453
- setInternalMonth((m) => {
1454
- const { year, month, firstDay } = computeAdjacentMonth(m, "prev", T);
1455
- setFocusedDate((prev) => focusedDateForMonth(prev, {
1456
- year,
1457
- month
1458
- }, firstDay));
1792
+ };
1793
+ }
1794
+ function monthAt(start, offset) {
1795
+ const index = monthIndex(start) + offset;
1796
+ return {
1797
+ year: Math.floor(index / 12),
1798
+ month: index % 12 + 1
1799
+ };
1800
+ }
1801
+ // src/month-view.tsx
1802
+ function MonthViewRoot(props) {
1803
+ const { numberOfMonths: numberOfMonthsProp, fixedWeeks: fixedWeeksProp, outsideDays: outsideDaysProp, outOfRangeBehavior: outOfRangeBehaviorProp, month: monthProp, defaultMonth: defaultMonthProp, onMonthChange, children } = props;
1804
+ const numberOfMonths = Math.max(1, Math.min(numberOfMonthsProp ?? 1, 12));
1805
+ const fixedWeeks = fixedWeeksProp ?? false;
1806
+ const outsideDays = outsideDaysProp ?? "enabled";
1807
+ const outOfRangeBehavior = outOfRangeBehaviorProp ?? "unbounded";
1808
+ const calStable = useCalendarStable();
1809
+ const calState = useCalendarState();
1810
+ const T = calStable.temporal;
1811
+ const { timeZone, today, weekStartDay, isDateDisabled } = calStable;
1812
+ const [gridHasFocus, setGridHasFocus] = useState(false);
1813
+ const gridFocusedRef = useRef(false);
1814
+ const { minValue, maxValue } = calStable;
1815
+ const windowPolicy = useMemo(() => createMonthWindowPolicy({
1816
+ numberOfMonths,
1817
+ behavior: outOfRangeBehavior,
1818
+ min: minValue,
1819
+ max: maxValue,
1820
+ T
1821
+ }), [
1822
+ numberOfMonths,
1823
+ outOfRangeBehavior,
1824
+ minValue,
1825
+ maxValue,
1826
+ T
1827
+ ]);
1828
+ const [focusedDate, setFocusedDate] = useState(() => {
1829
+ const anchor = resolveInitialAnchor(calState.selected, today, timeZone, T);
1830
+ const opening = monthProp ?? defaultMonthProp;
1831
+ if (!opening || windowPolicy.isVisible(opening, anchor)) return anchor;
1832
+ return T.PlainDate.from({
1833
+ year: opening.year,
1834
+ month: opening.month,
1835
+ day: 1
1836
+ });
1837
+ });
1838
+ const { currentMonth, viewingYearMonth, goNextMonth, goPrevMonth } = useMonthNavigation({
1839
+ month: monthProp,
1840
+ defaultMonth: defaultMonthProp,
1841
+ initialAnchor: useCallback(() => resolveInitialAnchor(calState.selected, today, timeZone, T), [
1842
+ calState.selected,
1843
+ today,
1844
+ timeZone,
1845
+ T
1846
+ ]),
1847
+ onMonthChange,
1848
+ policy: windowPolicy,
1849
+ focusedDate,
1850
+ setFocusedDate,
1851
+ T
1852
+ });
1853
+ const [gridLabelIds, setGridLabelIds] = useState({});
1854
+ const setGridLabelId = useCallback((monthIndex, id) => {
1855
+ setGridLabelIds((prev) => {
1856
+ if (id === void 0) {
1857
+ if (!(monthIndex in prev)) return prev;
1858
+ const next = { ...prev };
1859
+ delete next[monthIndex];
1860
+ return next;
1861
+ }
1862
+ if (prev[monthIndex] === id) return prev;
1459
1863
  return {
1460
- year,
1461
- month
1864
+ ...prev,
1865
+ [monthIndex]: id
1462
1866
  };
1463
1867
  });
1464
- }, [
1465
- T,
1466
- isMonthControlled,
1467
- monthProp,
1468
- notifyMonth,
1469
- focusedDate
1470
- ]);
1868
+ }, []);
1471
1869
  const allMonths = useMemo(() => {
1472
1870
  const opts = {
1473
1871
  weekStartDay,
@@ -1527,19 +1925,6 @@ function MonthViewRoot(props) {
1527
1925
  T,
1528
1926
  gridHasFocus
1529
1927
  ]);
1530
- const viewingYearMonth = useMemo(() => T.PlainYearMonth.from({
1531
- year: currentMonth.year,
1532
- month: currentMonth.month
1533
- }), [currentMonth, T]);
1534
- const mountedRef = useRef(false);
1535
- useEffect(() => {
1536
- if (!mountedRef.current) {
1537
- mountedRef.current = true;
1538
- return;
1539
- }
1540
- if (isMonthControlled) return;
1541
- onMonthChangeRef.current?.(viewingYearMonth);
1542
- }, [viewingYearMonth, isMonthControlled]);
1543
1928
  const rootState = useMemo(() => ({
1544
1929
  ...calState.baseRootState,
1545
1930
  focused: focusedDate,
@@ -1554,6 +1939,7 @@ function MonthViewRoot(props) {
1554
1939
  fixedWeeks,
1555
1940
  outsideDays,
1556
1941
  outOfRangeBehavior,
1942
+ windowPolicy,
1557
1943
  goNextMonth,
1558
1944
  goPrevMonth,
1559
1945
  setGridLabelId,
@@ -1563,6 +1949,7 @@ function MonthViewRoot(props) {
1563
1949
  fixedWeeks,
1564
1950
  outsideDays,
1565
1951
  outOfRangeBehavior,
1952
+ windowPolicy,
1566
1953
  goNextMonth,
1567
1954
  goPrevMonth,
1568
1955
  setGridLabelId
@@ -1594,13 +1981,28 @@ function MonthViewRoot(props) {
1594
1981
  tabTargetDate,
1595
1982
  gridHasFocus
1596
1983
  ]);
1984
+ const viewStableCtx = useMemo(() => ({
1985
+ gridFocusedRef,
1986
+ outsideDays,
1987
+ setFocusedDate
1988
+ }), [outsideDays]);
1989
+ const viewStateCtx = useMemo(() => ({
1990
+ currentDateTime,
1991
+ rootState
1992
+ }), [currentDateTime, rootState]);
1597
1993
  return /* @__PURE__ */ jsx(MonthViewStableContext.Provider, {
1598
1994
  value: stableCtx,
1599
1995
  children: /* @__PURE__ */ jsx(MonthViewStateContext.Provider, {
1600
1996
  value: stateCtx,
1601
- children: /* @__PURE__ */ jsx(ViewContext.Provider, {
1602
- value: viewCtx,
1603
- children
1997
+ children: /* @__PURE__ */ jsx(ViewStableContext.Provider, {
1998
+ value: viewStableCtx,
1999
+ children: /* @__PURE__ */ jsx(ViewStateContext.Provider, {
2000
+ value: viewStateCtx,
2001
+ children: /* @__PURE__ */ jsx(ViewContext.Provider, {
2002
+ value: viewCtx,
2003
+ children: /* @__PURE__ */ jsx(DayCellStoreProvider, { children })
2004
+ })
2005
+ })
1604
2006
  })
1605
2007
  })
1606
2008
  });
@@ -1622,21 +2024,10 @@ function MonthView(props) {
1622
2024
  });
1623
2025
  }
1624
2026
  MonthView.Root = MonthViewRoot;
1625
- //#endregion
1626
- //#region src/context.ts
1627
- /** @internal Provides the days and index of the current week row to child components. */
1628
- const WeekDataContext = createContext(null);
1629
- /** @internal Provides the resolved grid orientation to descendant cells. */
1630
- const GridContext = createContext({ orientation: "horizontal" });
1631
- /** @internal Provides the date and column index from a `DayCellTemplate` to its child `DayButton`. */
1632
- const DayCellDataContext = createContext(null);
1633
- /** @internal Provides per-grid month data to WeekTemplate and DayCellTemplate. */
1634
- const GridMonthContext = createContext(null);
1635
- //#endregion
1636
- //#region src/grid-header.tsx
2027
+ // src/grid-header.tsx
1637
2028
  function useGridHeaderCellState(index) {
1638
2029
  const { locale, temporal: T, weekStartDay } = useCalendarStable();
1639
- const { rootState } = useMonthViewState();
2030
+ const { rootState } = useViewState();
1640
2031
  const weekdayNames = useMemo(() => getWeekdayNames(locale, T, weekStartDay), [
1641
2032
  locale,
1642
2033
  T,
@@ -1712,7 +2103,7 @@ function GridHeaderCellFn(props, ref) {
1712
2103
  const GridHeaderCell = forwardRef(GridHeaderCellFn);
1713
2104
  function GridHeaderFn(props, ref) {
1714
2105
  const { render, children, ...otherProps } = props;
1715
- const { rootState } = useMonthViewState();
2106
+ const { rootState } = useViewState();
1716
2107
  const state = useMemo(() => ({ root: rootState }), [rootState]);
1717
2108
  return useRender({
1718
2109
  defaultTagName: "thead",
@@ -1725,8 +2116,7 @@ function GridHeaderFn(props, ref) {
1725
2116
  }
1726
2117
  /** Table header section (`<thead>`) wrapping a row of {@link GridHeaderCell}s. */
1727
2118
  const GridHeader = forwardRef(GridHeaderFn);
1728
- //#endregion
1729
- //#region src/keyboard.ts
2119
+ // src/keyboard.ts
1730
2120
  /**
1731
2121
  * Computes the target date when jumping by `months` from `focusedDate`.
1732
2122
  *
@@ -1799,8 +2189,7 @@ function computeNextFocusDate(input) {
1799
2189
  if (nextDate) return clampToBounds(nextDate, focusedDate, minValue, maxValue, T);
1800
2190
  return { action: "none" };
1801
2191
  }
1802
- //#endregion
1803
- //#region src/month-separator.tsx
2192
+ // src/month-separator.tsx
1804
2193
  /** Context providing MonthSeparator data to child components. */
1805
2194
  const MonthSeparatorDataContext = createContext(null);
1806
2195
  function useMonthSeparatorData() {
@@ -1930,8 +2319,7 @@ function MonthSeparatorFn(props, ref) {
1930
2319
  * Default children: `<Month /> <Year />`.
1931
2320
  */
1932
2321
  const MonthSeparator = forwardRef(MonthSeparatorFn);
1933
- //#endregion
1934
- //#region src/weeks-view-context.ts
2322
+ // src/weeks-view-context.ts
1935
2323
  /** @internal React context for WeeksView stable values (config + callbacks). */
1936
2324
  const WeeksViewStableContext = createContext(null);
1937
2325
  /** @internal React context for WeeksView volatile state. */
@@ -1948,8 +2336,7 @@ function useWeeksViewState() {
1948
2336
  if (!ctx) throw new Error("useWeeksViewState must be used within WeeksView.Root");
1949
2337
  return ctx;
1950
2338
  }
1951
- //#endregion
1952
- //#region src/weeks-grid.tsx
2339
+ // src/weeks-grid.tsx
1953
2340
  /**
1954
2341
  * @internal WeeksGrid — renders continuous week rows for WeeksView.
1955
2342
  * Not exported from the public API.
@@ -2083,28 +2470,35 @@ function WeeksGrid(props) {
2083
2470
  }
2084
2471
  return map;
2085
2472
  }, [monthBoundaries]);
2473
+ const rowValues = useMemo(() => weeks.map((week, i) => {
2474
+ const days = weekDaysArrays[i] ?? [];
2475
+ return {
2476
+ weekData: {
2477
+ days,
2478
+ weekIndex: week.weekIndex,
2479
+ gridRowIndex: i + 2
2480
+ },
2481
+ gridMonth: {
2482
+ weeks: [days],
2483
+ year: week.year,
2484
+ month: week.month
2485
+ }
2486
+ };
2487
+ }), [weeks, weekDaysArrays]);
2086
2488
  const rows = [];
2087
2489
  for (const [i, week] of weeks.entries()) {
2088
- const days = weekDaysArrays[i];
2089
- if (days === void 0) continue;
2490
+ if (weekDaysArrays[i] === void 0) continue;
2090
2491
  const separators = boundariesAtIndex.get(i);
2091
2492
  if (separators && separatorTemplate.length > 0) for (const separatorData of separators) rows.push(/* @__PURE__ */ jsx(MonthSeparatorDataContext.Provider, {
2092
2493
  value: separatorData,
2093
2494
  children: separatorTemplate
2094
2495
  }, `sep-${separatorData.year}-${separatorData.month}`));
2095
- const weekGridRow = i + 2;
2496
+ const rowValue = rowValues[i];
2497
+ if (rowValue === void 0) continue;
2096
2498
  rows.push(/* @__PURE__ */ jsx(WeekDataContext.Provider, {
2097
- value: {
2098
- days,
2099
- weekIndex: week.weekIndex,
2100
- gridRowIndex: weekGridRow
2101
- },
2499
+ value: rowValue.weekData,
2102
2500
  children: /* @__PURE__ */ jsx(GridMonthContext.Provider, {
2103
- value: {
2104
- weeks: [days],
2105
- year: week.year,
2106
- month: week.month
2107
- },
2501
+ value: rowValue.gridMonth,
2108
2502
  children: weekRowChildren
2109
2503
  })
2110
2504
  }, week.startDate.toString()));
@@ -2115,8 +2509,7 @@ function WeeksGrid(props) {
2115
2509
  children: rows
2116
2510
  });
2117
2511
  }
2118
- //#endregion
2119
- //#region src/weeks-keyboard.ts
2512
+ // src/weeks-keyboard.ts
2120
2513
  const NONE = {
2121
2514
  action: "none",
2122
2515
  windowShift: 0,
@@ -2190,132 +2583,7 @@ function computeWeeksKeyNav(input) {
2190
2583
  default: return NONE;
2191
2584
  }
2192
2585
  }
2193
- //#endregion
2194
- //#region src/day-cell.tsx
2195
- /** Computes derived day cell state from context values. Pure function, no hooks. */
2196
- function computeDayCellState(date, orientation, columnIndex, rootState, selectedDates, currentDateTime, disabled, isDateDisabled, focusedDate, rangeStart, rangeEnd, tabTargetDate, T, selectionMode, outsideDays, previewStart, previewEnd) {
2197
- const isCurrentMonth = date.year === currentDateTime.year && date.month === currentDateTime.month;
2198
- if (!isCurrentMonth && outsideDays === "hidden") return {
2199
- root: rootState,
2200
- date,
2201
- columnIndex,
2202
- orientation,
2203
- outsideMonth: true,
2204
- hidden: true,
2205
- selected: false,
2206
- today: false,
2207
- disabled: true,
2208
- focused: false,
2209
- rangeStart: false,
2210
- rangeEnd: false,
2211
- rangeBoundary: false,
2212
- inRange: false,
2213
- rangeIndex: false,
2214
- rangeLength: false,
2215
- rangeHasStart: false,
2216
- rangeHasEnd: false,
2217
- rangePreviewStart: false,
2218
- rangePreviewEnd: false,
2219
- rangePreviewBoundary: false,
2220
- rangePreviewInRange: false,
2221
- rangePreviewIndex: false,
2222
- rangePreviewLength: false,
2223
- rangePreviewHasStart: false,
2224
- rangePreviewHasEnd: false,
2225
- isTabTarget: false
2226
- };
2227
- const today = T.Now.plainDateISO();
2228
- const isToday = T.PlainDate.compare(date, today) === 0;
2229
- const isRange = selectionMode === "range";
2230
- let isRangeStart = false;
2231
- let isRangeEnd = false;
2232
- let isInRangeDay = false;
2233
- let rangeIdx = false;
2234
- let rangeLen = false;
2235
- let isPreviewRangeStart = false;
2236
- let isPreviewRangeEnd = false;
2237
- let isInPreviewRange = false;
2238
- let previewIdx = false;
2239
- let previewLen = false;
2240
- if (isRange) {
2241
- isRangeStart = rangeStart ? T.PlainDate.compare(date, rangeStart) === 0 : false;
2242
- isRangeEnd = rangeEnd ? T.PlainDate.compare(date, rangeEnd) === 0 : false;
2243
- isInRangeDay = isInRange(date, rangeStart, rangeEnd, T) !== false;
2244
- const effectiveStart = rangeStart ?? rangeEnd;
2245
- const effectiveEnd = rangeEnd ?? rangeStart;
2246
- rangeIdx = isInRangeDay && effectiveStart ? date.since(effectiveStart).days : false;
2247
- rangeLen = isInRangeDay && effectiveStart && effectiveEnd ? effectiveEnd.since(effectiveStart).days + 1 : false;
2248
- isPreviewRangeStart = previewStart ? T.PlainDate.compare(date, previewStart) === 0 : false;
2249
- isPreviewRangeEnd = previewEnd ? T.PlainDate.compare(date, previewEnd) === 0 : false;
2250
- isInPreviewRange = previewStart && previewEnd ? isInRange(date, previewStart, previewEnd, T) !== false : false;
2251
- previewIdx = isInPreviewRange && previewStart ? date.since(previewStart).days : false;
2252
- previewLen = isInPreviewRange && previewStart && previewEnd ? previewEnd.since(previewStart).days + 1 : false;
2253
- }
2254
- const outsideNonInteractive = !isCurrentMonth && outsideDays !== "enabled";
2255
- const suppressRange = !isCurrentMonth && (outsideDays === "disabled" || outsideDays === "hidden");
2256
- if (outsideNonInteractive) return {
2257
- root: rootState,
2258
- date,
2259
- columnIndex,
2260
- orientation,
2261
- outsideMonth: true,
2262
- hidden: false,
2263
- selected: false,
2264
- today: isToday,
2265
- disabled: true,
2266
- focused: false,
2267
- rangeStart: suppressRange ? false : isRangeStart,
2268
- rangeEnd: suppressRange ? false : isRangeEnd,
2269
- rangeBoundary: suppressRange ? false : isRangeStart || isRangeEnd,
2270
- inRange: suppressRange ? false : isInRangeDay,
2271
- rangeIndex: suppressRange ? false : rangeIdx,
2272
- rangeLength: suppressRange ? false : rangeLen,
2273
- rangeHasStart: suppressRange ? false : isInRangeDay && rangeStart !== void 0,
2274
- rangeHasEnd: suppressRange ? false : isInRangeDay && rangeEnd !== void 0,
2275
- rangePreviewStart: suppressRange ? false : isPreviewRangeStart,
2276
- rangePreviewEnd: suppressRange ? false : isPreviewRangeEnd,
2277
- rangePreviewBoundary: suppressRange ? false : isPreviewRangeStart || isPreviewRangeEnd,
2278
- rangePreviewInRange: suppressRange ? false : isInPreviewRange,
2279
- rangePreviewIndex: suppressRange ? false : previewIdx,
2280
- rangePreviewLength: suppressRange ? false : previewLen,
2281
- rangePreviewHasStart: suppressRange ? false : isInPreviewRange && previewStart !== void 0,
2282
- rangePreviewHasEnd: suppressRange ? false : isInPreviewRange && previewEnd !== void 0,
2283
- isTabTarget: false
2284
- };
2285
- const isSelected = selectionMode !== "range" ? selectedDates.some((d) => T.PlainDate.compare(d, date) === 0) : false;
2286
- const isDisabled = disabled || (isDateDisabled?.(date) ?? false);
2287
- const isFocused = T.PlainDate.compare(date, focusedDate) === 0;
2288
- const isTabTarget = T.PlainDate.compare(date, tabTargetDate) === 0;
2289
- return {
2290
- root: rootState,
2291
- date,
2292
- columnIndex,
2293
- orientation,
2294
- selected: isSelected,
2295
- today: isToday,
2296
- disabled: isDisabled,
2297
- outsideMonth: !isCurrentMonth,
2298
- hidden: false,
2299
- focused: isFocused,
2300
- rangeStart: isRangeStart,
2301
- rangeEnd: isRangeEnd,
2302
- rangeBoundary: isRangeStart || isRangeEnd,
2303
- inRange: isInRangeDay,
2304
- rangeIndex: rangeIdx,
2305
- rangeLength: rangeLen,
2306
- rangeHasStart: isInRangeDay && rangeStart !== void 0,
2307
- rangeHasEnd: isInRangeDay && rangeEnd !== void 0,
2308
- rangePreviewStart: isPreviewRangeStart,
2309
- rangePreviewEnd: isPreviewRangeEnd,
2310
- rangePreviewBoundary: isPreviewRangeStart || isPreviewRangeEnd,
2311
- rangePreviewInRange: isInPreviewRange,
2312
- rangePreviewIndex: previewIdx,
2313
- rangePreviewLength: previewLen,
2314
- rangePreviewHasStart: isInPreviewRange && previewStart !== void 0,
2315
- rangePreviewHasEnd: isInPreviewRange && previewEnd !== void 0,
2316
- isTabTarget
2317
- };
2318
- }
2586
+ // src/day-cell.tsx
2319
2587
  const dayStateAttributesMapping = {
2320
2588
  root: () => null,
2321
2589
  date: (v) => v ? { "data-date": v.toString() } : null,
@@ -2344,34 +2612,46 @@ const dayStateAttributesMapping = {
2344
2612
  rangePreviewHasStart: (v) => v ? { "data-range-preview-has-start": "" } : null,
2345
2613
  rangePreviewHasEnd: (v) => v ? { "data-range-preview-has-end": "" } : null
2346
2614
  };
2615
+ /** @internal The enclosing day cell's state, read by its `DayButton`. */
2616
+ const DayCellStateContext = createContext(null);
2347
2617
  function DayCellInstanceFn(props) {
2348
- const { render, date, columnIndex, children, _derivedState, ...otherProps } = props;
2349
- const state = _derivedState;
2618
+ const { render, date, columnIndex, gridMonth, children, ...otherProps } = props;
2619
+ const derived = useDayCellState(date, columnIndex, gridMonth);
2620
+ const state = derived;
2621
+ const defaultProps = state.hidden ? {
2622
+ role: "gridcell",
2623
+ "aria-hidden": true,
2624
+ children: null
2625
+ } : {
2626
+ role: "gridcell",
2627
+ "aria-selected": state.selected || void 0,
2628
+ "aria-disabled": state.disabled || void 0,
2629
+ children: children ?? /* @__PURE__ */ jsx(DayButton, {})
2630
+ };
2350
2631
  const cell = useRender({
2351
2632
  defaultTagName: "td",
2352
2633
  render,
2353
2634
  ref: [],
2354
2635
  state,
2355
2636
  stateAttributesMapping: dayStateAttributesMapping,
2356
- props: mergeProps(state.hidden ? {
2357
- role: "gridcell",
2358
- "aria-hidden": true,
2359
- children: null
2360
- } : {
2361
- role: "gridcell",
2362
- "aria-selected": state.selected || void 0,
2363
- "aria-disabled": state.disabled || void 0,
2364
- children: children ?? /* @__PURE__ */ jsx(DayButton, { _derivedState })
2365
- }, otherProps)
2637
+ props: mergeProps(defaultProps, otherProps)
2366
2638
  });
2367
2639
  const outsideDisabled = state.hidden || state.outsideMonth && state.disabled;
2640
+ const cellData = useMemo(() => ({
2641
+ date,
2642
+ columnIndex,
2643
+ outsideDisabled
2644
+ }), [
2645
+ date,
2646
+ columnIndex,
2647
+ outsideDisabled
2648
+ ]);
2368
2649
  return /* @__PURE__ */ jsx(DayCellDataContext.Provider, {
2369
- value: {
2370
- date,
2371
- columnIndex,
2372
- outsideDisabled
2373
- },
2374
- children: cell
2650
+ value: cellData,
2651
+ children: /* @__PURE__ */ jsx(DayCellStateContext.Provider, {
2652
+ value: derived,
2653
+ children: cell
2654
+ })
2375
2655
  });
2376
2656
  }
2377
2657
  /**
@@ -2387,26 +2667,35 @@ function passThroughPropsEqual(prev, next, handledKeys) {
2387
2667
  for (const key of prevKeys) if (prev[key] !== next[key]) return false;
2388
2668
  return true;
2389
2669
  }
2390
- const DAY_CELL_HANDLED_KEYS = new Set([
2670
+ const DAY_CELL_HANDLED_KEYS = /* @__PURE__ */ new Set([
2391
2671
  "render",
2392
2672
  "date",
2393
2673
  "columnIndex",
2394
- "children",
2395
- "_derivedState"
2674
+ "gridMonth",
2675
+ "children"
2396
2676
  ]);
2397
- const DAY_BUTTON_HANDLED_KEYS = new Set([
2677
+ const DAY_BUTTON_HANDLED_KEYS = /* @__PURE__ */ new Set([
2398
2678
  "render",
2399
2679
  "date",
2400
2680
  "children",
2401
- "_derivedState"
2681
+ "_state"
2402
2682
  ]);
2683
+ /**
2684
+ * Whether a day cell can skip a parent re-render. Its own state comes from
2685
+ * the store, so only props are compared here.
2686
+ */
2403
2687
  function dayCellInstancePropsAreEqual(prev, next) {
2404
- if (prev.date !== next.date || prev.render !== next.render || prev.columnIndex !== next.columnIndex) return false;
2405
- const a = prev._derivedState;
2406
- const b = next._derivedState;
2407
- return a.selected === b.selected && a.today === b.today && a.disabled === b.disabled && a.outsideMonth === b.outsideMonth && a.hidden === b.hidden && a.focused === b.focused && a.rangeStart === b.rangeStart && a.rangeEnd === b.rangeEnd && a.inRange === b.inRange && a.rangeIndex === b.rangeIndex && a.rangeLength === b.rangeLength && a.rangeHasStart === b.rangeHasStart && a.rangeHasEnd === b.rangeHasEnd && a.rangePreviewStart === b.rangePreviewStart && a.rangePreviewEnd === b.rangePreviewEnd && a.rangePreviewBoundary === b.rangePreviewBoundary && a.rangePreviewInRange === b.rangePreviewInRange && a.rangePreviewIndex === b.rangePreviewIndex && a.rangePreviewLength === b.rangePreviewLength && a.rangePreviewHasStart === b.rangePreviewHasStart && a.rangePreviewHasEnd === b.rangePreviewHasEnd && a.isTabTarget === b.isTabTarget && passThroughPropsEqual(prev, next, DAY_CELL_HANDLED_KEYS);
2688
+ return prev.date === next.date && prev.render === next.render && prev.columnIndex === next.columnIndex && prev.gridMonth === next.gridMonth && passThroughPropsEqual(prev, next, DAY_CELL_HANDLED_KEYS);
2408
2689
  }
2409
2690
  const DayCellInstance = memo(DayCellInstanceFn, dayCellInstancePropsAreEqual);
2691
+ /** The cells of a whole month, for a `DayCellTemplate` outside any week row. */
2692
+ function MonthDayCells(props) {
2693
+ const days = useContext(MonthViewStateContext)?.weeks.flat() ?? [];
2694
+ return /* @__PURE__ */ jsx(Fragment, { children: days.map((day) => /* @__PURE__ */ jsx(DayCellInstance, {
2695
+ ...props,
2696
+ date: day
2697
+ }, day.toString())) });
2698
+ }
2410
2699
  /**
2411
2700
  * Renders one `<td role="gridcell">` per day. Exposes data-attributes for
2412
2701
  * `selected`, `today`, `disabled`, `outside-month`, `focused`,
@@ -2418,58 +2707,32 @@ const DayCellInstance = memo(DayCellInstanceFn, dayCellInstancePropsAreEqual);
2418
2707
  function DayCellTemplate(props) {
2419
2708
  const { date: dateProp, ...restProps } = props;
2420
2709
  const weekData = useContext(WeekDataContext);
2421
- const { disabled, isDateDisabled, selectionMode, temporal: T, weekStartDay } = useCalendarStable();
2422
- const { selectedDates, rangeStart, rangeEnd, previewStart, previewEnd } = useCalendarState();
2423
- const viewCtx = useViewContext();
2424
- const { focusedDate, tabTargetDate } = viewCtx;
2425
- const monthStable = useContext(MonthViewStableContext);
2426
- const { rootState, weeks, currentMonth: currentDateTime } = useMonthViewState();
2427
- const outsideDays = monthStable?.outsideDays ?? "enabled";
2428
- const isWeeksView = viewCtx.viewType === "weeks";
2429
- const cellMonth = isWeeksView ? null : weekData?.gridMonth ?? currentDateTime;
2430
- const { orientation } = useContext(GridContext);
2431
- if (dateProp) {
2432
- const daysInWeek = dateProp.daysInWeek;
2433
- const derived = computeDayCellState(dateProp, orientation, (dateProp.dayOfWeek % daysInWeek - weekStartDay + daysInWeek) % daysInWeek, rootState, selectedDates, isWeeksView ? {
2434
- year: dateProp.year,
2435
- month: dateProp.month
2436
- } : cellMonth, disabled, isDateDisabled, focusedDate, rangeStart, rangeEnd, tabTargetDate, T, selectionMode, outsideDays, previewStart, previewEnd);
2437
- return /* @__PURE__ */ jsx(DayCellInstance, {
2438
- ...restProps,
2439
- date: dateProp,
2440
- _derivedState: derived
2441
- });
2442
- }
2443
- const days = weekData ? weekData.days : weeks.flat();
2444
- const perWeek = weekData != null;
2445
- return /* @__PURE__ */ jsx(Fragment, { children: days.map((day, i) => {
2446
- const daysInWeek = day.daysInWeek;
2447
- const derived = computeDayCellState(day, orientation, perWeek ? i : (day.dayOfWeek % daysInWeek - weekStartDay + daysInWeek) % daysInWeek, rootState, selectedDates, isWeeksView ? {
2448
- year: day.year,
2449
- month: day.month
2450
- } : cellMonth, disabled, isDateDisabled, focusedDate, rangeStart, rangeEnd, tabTargetDate, T, selectionMode, outsideDays, previewStart, previewEnd);
2451
- return /* @__PURE__ */ jsx(DayCellInstance, {
2452
- ...restProps,
2453
- date: day,
2454
- columnIndex: perWeek ? i : void 0,
2455
- _derivedState: derived
2456
- }, day.toString());
2457
- }) });
2710
+ if (dateProp) return /* @__PURE__ */ jsx(DayCellInstance, {
2711
+ ...restProps,
2712
+ date: dateProp,
2713
+ gridMonth: weekData?.gridMonth
2714
+ });
2715
+ if (!weekData) return /* @__PURE__ */ jsx(MonthDayCells, { ...restProps });
2716
+ return /* @__PURE__ */ jsx(Fragment, { children: weekData.days.map((day, i) => /* @__PURE__ */ jsx(DayCellInstance, {
2717
+ ...restProps,
2718
+ date: day,
2719
+ columnIndex: i,
2720
+ gridMonth: weekData.gridMonth
2721
+ }, day.toString())) });
2458
2722
  }
2459
2723
  function DayButtonInnerFn(props, ref) {
2460
- const { render, date, _derivedState, ...otherProps } = props;
2724
+ const { render, date, _state, ...otherProps } = props;
2461
2725
  const { onSelect, locale, readOnly, setHoveredDate } = useCalendarStable();
2462
- const { setFocusedDate } = useViewContext();
2463
- const gridFocusedRef = useContext(MonthViewStableContext).gridFocusedRef;
2726
+ const { gridFocusedRef, setFocusedDate } = useViewStable();
2464
2727
  const internalRef = useRef(null);
2465
- const isHidden = _derivedState?.hidden ?? false;
2466
- const isFocused = _derivedState?.focused ?? false;
2467
- const isTabTarget = _derivedState?.isTabTarget ?? false;
2468
- const isDisabled = _derivedState?.disabled ?? false;
2728
+ const isHidden = _state.hidden;
2729
+ const isFocused = _state.focused;
2730
+ const isTabTarget = _state.isTabTarget;
2731
+ const isDisabled = _state.disabled;
2469
2732
  useEffect(() => {
2470
2733
  if (shouldMoveDomFocus(isFocused, gridFocusedRef.current) && internalRef.current) internalRef.current.focus();
2471
2734
  }, [isFocused, gridFocusedRef]);
2472
- const state = _derivedState;
2735
+ const state = _state;
2473
2736
  const defaultProps = isHidden ? {} : {
2474
2737
  type: "button",
2475
2738
  tabIndex: isTabTarget ? 0 : -1,
@@ -2501,12 +2764,7 @@ function DayButtonInnerFn(props, ref) {
2501
2764
  });
2502
2765
  }
2503
2766
  function dayButtonInnerPropsAreEqual(prev, next) {
2504
- if (prev.date !== next.date || prev.render !== next.render) return false;
2505
- if (!passThroughPropsEqual(prev, next, DAY_BUTTON_HANDLED_KEYS)) return false;
2506
- const a = prev._derivedState;
2507
- const b = next._derivedState;
2508
- if (!a || !b) return a === b;
2509
- return a.selected === b.selected && a.today === b.today && a.disabled === b.disabled && a.outsideMonth === b.outsideMonth && a.hidden === b.hidden && a.focused === b.focused && a.rangeStart === b.rangeStart && a.rangeEnd === b.rangeEnd && a.inRange === b.inRange && a.rangeIndex === b.rangeIndex && a.rangeLength === b.rangeLength && a.rangeHasStart === b.rangeHasStart && a.rangeHasEnd === b.rangeHasEnd && a.rangePreviewStart === b.rangePreviewStart && a.rangePreviewEnd === b.rangePreviewEnd && a.rangePreviewBoundary === b.rangePreviewBoundary && a.rangePreviewInRange === b.rangePreviewInRange && a.rangePreviewIndex === b.rangePreviewIndex && a.rangePreviewLength === b.rangePreviewLength && a.rangePreviewHasStart === b.rangePreviewHasStart && a.rangePreviewHasEnd === b.rangePreviewHasEnd && a.isTabTarget === b.isTabTarget;
2767
+ return prev.date === next.date && prev.render === next.render && prev._state === next._state && passThroughPropsEqual(prev, next, DAY_BUTTON_HANDLED_KEYS);
2510
2768
  }
2511
2769
  const DayButtonInner = memo(forwardRef(DayButtonInnerFn), dayButtonInnerPropsAreEqual);
2512
2770
  /**
@@ -2516,53 +2774,37 @@ const DayButtonInner = memo(forwardRef(DayButtonInnerFn), dayButtonInnerPropsAre
2516
2774
  * Must be used inside a {@link DayCellTemplate} or given an explicit `date` prop.
2517
2775
  */
2518
2776
  function DayButtonFn(props, ref) {
2519
- const { date: dateProp, _derivedState, ...restProps } = props;
2777
+ const { date: dateProp, ...restProps } = props;
2778
+ const cellState = useContext(DayCellStateContext);
2520
2779
  const cellData = useContext(DayCellDataContext);
2780
+ if (cellState && (!dateProp || dateProp.equals(cellState.date))) return /* @__PURE__ */ jsx(DayButtonInner, {
2781
+ ...restProps,
2782
+ ref,
2783
+ date: cellState.date,
2784
+ _state: cellState
2785
+ });
2521
2786
  const resolvedDate = dateProp ?? cellData?.date;
2522
- if (resolvedDate) {
2523
- if (_derivedState) return /* @__PURE__ */ jsx(DayButtonInner, {
2524
- ...restProps,
2525
- ref,
2526
- date: resolvedDate,
2527
- _derivedState
2528
- });
2529
- return /* @__PURE__ */ jsx(DayButtonFallback, {
2530
- ref,
2531
- ...restProps,
2532
- date: resolvedDate
2533
- });
2534
- }
2787
+ if (resolvedDate) return /* @__PURE__ */ jsx(StandaloneDayButton, {
2788
+ ...restProps,
2789
+ ref,
2790
+ date: resolvedDate
2791
+ });
2535
2792
  throw new Error("DayButton must be used inside DayCellTemplate or receive an explicit date prop.");
2536
2793
  }
2537
2794
  const DayButton = forwardRef(DayButtonFn);
2538
- /** Fallback for standalone DayButton usage that needs to read context. */
2539
- function DayButtonFallbackFn(props, ref) {
2795
+ /** A `DayButton` outside any day cell: subscribes to its own date's state. */
2796
+ function StandaloneDayButtonFn(props, ref) {
2540
2797
  const { date, ...restProps } = props;
2541
- const { orientation } = useContext(GridContext);
2542
- const weekData = useContext(WeekDataContext);
2543
- const { disabled, isDateDisabled, selectionMode, temporal: T, weekStartDay } = useCalendarStable();
2544
- const { selectedDates, rangeStart, rangeEnd, previewStart, previewEnd } = useCalendarState();
2545
- const viewCtx = useViewContext();
2546
- const { focusedDate, tabTargetDate } = viewCtx;
2547
- const monthStable = useContext(MonthViewStableContext);
2548
- const { rootState, currentMonth: currentDateTime } = useMonthViewState();
2549
- const outsideDays = monthStable?.outsideDays ?? "enabled";
2550
- const cellMonth = viewCtx.viewType === "weeks" ? {
2551
- year: date.year,
2552
- month: date.month
2553
- } : weekData?.gridMonth ?? currentDateTime;
2554
- const daysInWeek = date.daysInWeek;
2555
- const derived = computeDayCellState(date, orientation, (date.dayOfWeek % daysInWeek - weekStartDay + daysInWeek) % daysInWeek, rootState, selectedDates, cellMonth, disabled, isDateDisabled, focusedDate, rangeStart, rangeEnd, tabTargetDate, T, selectionMode, outsideDays, previewStart, previewEnd);
2798
+ const state = useStandaloneDayCellState(date);
2556
2799
  return /* @__PURE__ */ jsx(DayButtonInner, {
2557
2800
  ...restProps,
2558
2801
  ref,
2559
2802
  date,
2560
- _derivedState: derived
2803
+ _state: state
2561
2804
  });
2562
2805
  }
2563
- const DayButtonFallback = forwardRef(DayButtonFallbackFn);
2564
- //#endregion
2565
- //#region src/grid.tsx
2806
+ const StandaloneDayButton = forwardRef(StandaloneDayButtonFn);
2807
+ // src/grid.tsx
2566
2808
  function useGridKeyboard() {
2567
2809
  const { onSelect, disabled, readOnly, isDateDisabled, minValue, maxValue, temporal: T, weekStartDay } = useCalendarStable();
2568
2810
  const { focusedDate, setFocusedDate } = useViewContext();
@@ -2610,7 +2852,7 @@ function useWeeksGridKeyboard() {
2610
2852
  shiftKey: e.shiftKey,
2611
2853
  focusedDate,
2612
2854
  windowStart: weeksState.windowInfo.windowStart,
2613
- weekCount: weeksStable.weekCount,
2855
+ weekCount: weeksState.windowInfo.weekCount,
2614
2856
  minValue,
2615
2857
  maxValue,
2616
2858
  disabled,
@@ -2662,17 +2904,15 @@ const gridStateAttributesMapping = {
2662
2904
  * delegates to the appropriate internal renderer.
2663
2905
  */
2664
2906
  function GridFn(props, ref) {
2665
- const monthState = useContext(MonthViewStableContext);
2666
- const weeksState = useContext(WeeksViewStateContext);
2667
- if (monthState) return /* @__PURE__ */ jsx(MonthGrid, {
2907
+ const view = useContext(ViewContext);
2908
+ if (!view) throw new Error("Grid must be used inside MonthView.Root or WeeksView.Root.");
2909
+ return view.viewType === "weeks" ? /* @__PURE__ */ jsx(WeeksViewGrid, {
2668
2910
  ref,
2669
2911
  ...props
2670
- });
2671
- if (weeksState) return /* @__PURE__ */ jsx(WeeksViewGrid, {
2912
+ }) : /* @__PURE__ */ jsx(MonthGrid, {
2672
2913
  ref,
2673
2914
  ...props
2674
2915
  });
2675
- throw new Error("Grid must be used inside MonthView.Root or WeeksView.Root.");
2676
2916
  }
2677
2917
  const Grid = forwardRef(GridFn);
2678
2918
  function MonthGridFn(props, ref) {
@@ -2779,7 +3019,7 @@ function WeeksViewGridFn(props, ref) {
2779
3019
  const weeksStable = useWeeksViewStable();
2780
3020
  const weeksState = useWeeksViewState();
2781
3021
  const { gridFocusedRef } = weeksStable;
2782
- const { gridLabelIds, weeks, currentDateTime } = weeksState;
3022
+ const { gridLabelIds, weeks } = weeksState;
2783
3023
  const handleKeyDown = useWeeksGridKeyboard();
2784
3024
  const gridRef = useRef(null);
2785
3025
  useEffect(() => {
@@ -2850,47 +3090,16 @@ function WeeksViewGridFn(props, ref) {
2850
3090
  props: mergeProps(defaultProps, otherProps)
2851
3091
  });
2852
3092
  const orientationCtx = useMemo(() => ({ orientation: resolvedOrientation }), [resolvedOrientation]);
2853
- const monthViewStableShim = useMemo(() => ({
2854
- numberOfMonths: 1,
2855
- fixedWeeks: false,
2856
- outsideDays: "enabled",
2857
- outOfRangeBehavior: "unbounded",
2858
- goNextMonth: () => {},
2859
- goPrevMonth: () => {},
2860
- setGridLabelId: () => {},
2861
- gridFocusedRef
2862
- }), [gridFocusedRef]);
2863
- const monthViewStateShim = useMemo(() => ({
2864
- currentMonth: {
2865
- year: currentDateTime.year,
2866
- month: currentDateTime.month
2867
- },
2868
- weeks: [],
2869
- allMonths: [],
2870
- currentDateTime,
2871
- gridLabelIds,
2872
- rootState: weeksState.rootState
2873
- }), [
2874
- currentDateTime,
2875
- gridLabelIds,
2876
- weeksState.rootState
2877
- ]);
2878
- return /* @__PURE__ */ jsx(MonthViewStableContext.Provider, {
2879
- value: monthViewStableShim,
2880
- children: /* @__PURE__ */ jsx(MonthViewStateContext.Provider, {
2881
- value: monthViewStateShim,
2882
- children: /* @__PURE__ */ jsx(GridContext.Provider, {
2883
- value: orientationCtx,
2884
- children: el
2885
- })
2886
- })
3093
+ return /* @__PURE__ */ jsx(GridContext.Provider, {
3094
+ value: orientationCtx,
3095
+ children: el
2887
3096
  });
2888
3097
  }
2889
3098
  const WeeksViewGrid = forwardRef(WeeksViewGridFn);
2890
3099
  const gridBodyStateAttributesMapping = { root: () => null };
2891
3100
  /** Table body wrapping the week rows. Renders a `<tbody>` by default. */
2892
3101
  function GridBodyFn(props, ref) {
2893
- if (useContext(WeeksViewStateContext)) {
3102
+ if (useContext(ViewContext)?.viewType === "weeks") {
2894
3103
  const { children, className, style } = props;
2895
3104
  return /* @__PURE__ */ jsx(WeeksGrid, {
2896
3105
  className,
@@ -2906,7 +3115,7 @@ function GridBodyFn(props, ref) {
2906
3115
  const GridBody = forwardRef(GridBodyFn);
2907
3116
  function MonthGridBodyFn(props, ref) {
2908
3117
  const { render, ...otherProps } = props;
2909
- const { rootState } = useMonthViewState();
3118
+ const { rootState } = useViewState();
2910
3119
  const state = useMemo(() => ({ root: rootState }), [rootState]);
2911
3120
  const defaultProps = { children: props.children ?? /* @__PURE__ */ jsx(WeekTemplate, { children: /* @__PURE__ */ jsx(DayCellTemplate, { children: /* @__PURE__ */ jsx(DayButton, {}) }) }) };
2912
3121
  const { children: _children, ...restOtherProps } = otherProps;
@@ -2928,20 +3137,21 @@ const weekInstanceStateAttributesMapping = {
2928
3137
  function WeekInstance(props) {
2929
3138
  const { render, ...otherProps } = props;
2930
3139
  const weekData = useContext(WeekDataContext);
2931
- const { rootState } = useMonthViewState();
3140
+ const { rootState } = useViewState();
3141
+ const state = useMemo(() => ({
3142
+ root: rootState,
3143
+ weekIndex: weekData.weekIndex,
3144
+ gridRowIndex: weekData.gridRowIndex
3145
+ }), [
3146
+ rootState,
3147
+ weekData.weekIndex,
3148
+ weekData.gridRowIndex
3149
+ ]);
2932
3150
  return useRender({
2933
3151
  defaultTagName: "tr",
2934
3152
  render,
2935
3153
  ref: [],
2936
- state: useMemo(() => ({
2937
- root: rootState,
2938
- weekIndex: weekData.weekIndex,
2939
- gridRowIndex: weekData.gridRowIndex
2940
- }), [
2941
- rootState,
2942
- weekData.weekIndex,
2943
- weekData.gridRowIndex
2944
- ]),
3154
+ state,
2945
3155
  stateAttributesMapping: weekInstanceStateAttributesMapping,
2946
3156
  props: mergeProps({}, otherProps)
2947
3157
  });
@@ -2953,29 +3163,33 @@ function WeekInstance(props) {
2953
3163
  function WeekTemplate(props) {
2954
3164
  const outerWeekData = useContext(WeekDataContext);
2955
3165
  const gridMonthCtx = useContext(GridMonthContext);
2956
- const { weeks: defaultWeeks } = useMonthViewState();
2957
- const weeks = gridMonthCtx?.weeks ?? defaultWeeks;
3166
+ const monthState = useContext(MonthViewStateContext);
3167
+ const weeks = gridMonthCtx?.weeks ?? monthState?.weeks ?? [];
2958
3168
  const gridMonth = useMemo(() => gridMonthCtx ? {
2959
3169
  year: gridMonthCtx.year,
2960
3170
  month: gridMonthCtx.month
2961
3171
  } : void 0, [gridMonthCtx]);
2962
- const Instance = WeekInstance;
2963
- return /* @__PURE__ */ jsx(Fragment, { children: weeks.map((weekDays, i) => {
2964
- const firstDay = weekDays[0];
3172
+ const gridRowIndex = outerWeekData?.gridRowIndex;
3173
+ const weekValues = useMemo(() => weeks.map((weekDays, i) => ({
3174
+ days: weekDays,
3175
+ weekIndex: i,
3176
+ ...gridMonth !== void 0 && { gridMonth },
3177
+ ...gridRowIndex !== void 0 && { gridRowIndex }
3178
+ })), [
3179
+ weeks,
3180
+ gridMonth,
3181
+ gridRowIndex
3182
+ ]);
3183
+ return /* @__PURE__ */ jsx(Fragment, { children: weekValues.map((value) => {
3184
+ const firstDay = value.days[0];
2965
3185
  if (firstDay === void 0) return null;
2966
3186
  return /* @__PURE__ */ jsx(WeekDataContext.Provider, {
2967
- value: {
2968
- days: weekDays,
2969
- weekIndex: i,
2970
- ...gridMonth !== void 0 && { gridMonth },
2971
- ...outerWeekData?.gridRowIndex !== void 0 && { gridRowIndex: outerWeekData.gridRowIndex }
2972
- },
2973
- children: /* @__PURE__ */ jsx(Instance, { ...props })
3187
+ value,
3188
+ children: /* @__PURE__ */ jsx(WeekInstance, { ...props })
2974
3189
  }, firstDay.toString());
2975
3190
  }) });
2976
3191
  }
2977
- //#endregion
2978
- //#region src/navigation.tsx
3192
+ // src/navigation.tsx
2979
3193
  const dateStringStateAttributesMapping = {
2980
3194
  root: () => null,
2981
3195
  month: () => null,
@@ -2997,7 +3211,7 @@ function DateStringFn(props, ref) {
2997
3211
  const { render, locales, options, ...otherProps } = props;
2998
3212
  const { locale, temporal: T, timeZone } = useCalendarStable();
2999
3213
  const { selected } = useCalendarState();
3000
- const { currentDateTime, rootState } = useMonthViewState();
3214
+ const { currentDateTime, rootState } = useViewState();
3001
3215
  const selectedZdt = selectedToZdt(selected, timeZone, T);
3002
3216
  const displayDate = selectedZdt ? zdtToNativeDate(selectedZdt) : new Date(currentDateTime.year, currentDateTime.month - 1, 1);
3003
3217
  const formatted = displayDate.toLocaleDateString(locales ?? locale, options);
@@ -3036,7 +3250,7 @@ function TimeStringFn(props, ref) {
3036
3250
  const { render, locales, options, ...otherProps } = props;
3037
3251
  const { locale, temporal: T, timeZone } = useCalendarStable();
3038
3252
  const { selected } = useCalendarState();
3039
- const { rootState } = useMonthViewState();
3253
+ const { rootState } = useViewState();
3040
3254
  const selZdt = selectedToZdt(selected, timeZone, T);
3041
3255
  const displayDate = selZdt ? zdtToNativeDate(selZdt) : zdtToNativeDate(T.Now.zonedDateTimeISO(timeZone));
3042
3256
  const mergedOptions = {
@@ -3141,37 +3355,16 @@ function MonthYearStringFn(props, ref) {
3141
3355
  */
3142
3356
  const MonthYearString = forwardRef(MonthYearStringFn);
3143
3357
  function useNavButton(direction) {
3144
- const { disabled: globalDisabled, minValue, maxValue, temporal: T } = useCalendarStable();
3145
- const monthViewStable = useMonthViewStable();
3146
- const monthViewState = useMonthViewState();
3147
- const { goNextMonth: goToNextMonth, goPrevMonth: goToPrevMonth, numberOfMonths, outOfRangeBehavior } = monthViewStable;
3148
- const { currentMonth: currentDateTime, allMonths, rootState } = monthViewState;
3149
- const refMonth = direction === "next" ? allMonths[numberOfMonths - 1] ?? currentDateTime : currentDateTime;
3150
- const destMonth = direction === "prev" ? refMonth.month === 1 ? 12 : refMonth.month - 1 : refMonth.month === 12 ? 1 : refMonth.month + 1;
3151
- const destYear = direction === "prev" ? refMonth.month === 1 ? refMonth.year - 1 : refMonth.year : refMonth.month === 12 ? refMonth.year + 1 : refMonth.year;
3152
- const boundValue = direction === "prev" ? minValue : maxValue;
3153
- const isDisabled = useMemo(() => {
3154
- if (globalDisabled) return true;
3155
- if (outOfRangeBehavior === "unbounded") return false;
3156
- if (!boundValue) return false;
3157
- if (direction === "prev") return destYear < boundValue.year || destYear === boundValue.year && destMonth < boundValue.month;
3158
- return destYear > boundValue.year || destYear === boundValue.year && destMonth > boundValue.month;
3159
- }, [
3160
- globalDisabled,
3161
- outOfRangeBehavior,
3162
- destYear,
3163
- destMonth,
3164
- boundValue,
3358
+ const { disabled: globalDisabled, temporal: T } = useCalendarStable();
3359
+ const { goNextMonth: goToNextMonth, goPrevMonth: goToPrevMonth, windowPolicy } = useMonthViewStable();
3360
+ const { currentMonth, rootState } = useMonthViewState();
3361
+ const step = useMemo(() => windowPolicy.step(currentMonth, direction), [
3362
+ windowPolicy,
3363
+ currentMonth,
3165
3364
  direction
3166
3365
  ]);
3167
- const target = useMemo(() => T.PlainYearMonth.from({
3168
- year: destYear,
3169
- month: destMonth
3170
- }), [
3171
- destYear,
3172
- destMonth,
3173
- T
3174
- ]);
3366
+ const isDisabled = globalDisabled || step.blocked;
3367
+ const target = useMemo(() => T.PlainYearMonth.from(step.entering), [step.entering, T]);
3175
3368
  return {
3176
3369
  state: useMemo(() => ({
3177
3370
  root: rootState,
@@ -3232,8 +3425,7 @@ function NextMonthButtonFn(props, ref) {
3232
3425
  * when the next month falls after `max`. Exposes `data-direction="next"`.
3233
3426
  */
3234
3427
  const NextMonthButton = forwardRef(NextMonthButtonFn);
3235
- //#endregion
3236
- //#region src/selected-range.tsx
3428
+ // src/selected-range.tsx
3237
3429
  const rangeOverlayStateAttributesMapping = {
3238
3430
  root: () => null,
3239
3431
  active: (v) => v ? { "data-active": "" } : null,
@@ -3302,9 +3494,8 @@ function RangeSelectedInnerFn(props, ref) {
3302
3494
  const { orientation } = useContext(GridContext);
3303
3495
  const { temporal: T } = useCalendarStable();
3304
3496
  const { rangeStart, rangeEnd } = useCalendarState();
3305
- const monthStable = useContext(MonthViewStableContext);
3306
- const { rootState } = useMonthViewState();
3307
- const outsideDays = monthStable?.outsideDays ?? "enabled";
3497
+ const { rootState } = useViewState();
3498
+ const { outsideDays } = useViewStable();
3308
3499
  const days = weekData?.days ?? [];
3309
3500
  const gridMonth = weekData?.gridMonth;
3310
3501
  const info = useMemo(() => computeClippedRangeInfo(days, rangeStart, rangeEnd, T, outsideDays, gridMonth), [
@@ -3354,8 +3545,7 @@ function RangeSelectedInnerFn(props, ref) {
3354
3545
  });
3355
3546
  }
3356
3547
  const RangeSelectedInner = forwardRef(RangeSelectedInnerFn);
3357
- //#endregion
3358
- //#region src/range-preview.tsx
3548
+ // src/range-preview.tsx
3359
3549
  function RangePreviewFn(props, ref) {
3360
3550
  const { selectionMode } = useCalendarStable();
3361
3551
  if (selectionMode !== "range") return null;
@@ -3377,9 +3567,8 @@ function RangePreviewInnerFn(props, ref) {
3377
3567
  const { orientation } = useContext(GridContext);
3378
3568
  const { temporal: T } = useCalendarStable();
3379
3569
  const { previewStart, previewEnd } = useCalendarState();
3380
- const monthStable = useContext(MonthViewStableContext);
3381
- const { rootState } = useMonthViewState();
3382
- const outsideDays = monthStable?.outsideDays ?? "enabled";
3570
+ const { rootState } = useViewState();
3571
+ const { outsideDays } = useViewStable();
3383
3572
  const days = weekData?.days ?? [];
3384
3573
  const gridMonth = weekData?.gridMonth;
3385
3574
  const info = useMemo(() => computeClippedRangeInfo(days, previewStart, previewEnd, T, outsideDays, gridMonth), [
@@ -3429,8 +3618,7 @@ function RangePreviewInnerFn(props, ref) {
3429
3618
  });
3430
3619
  }
3431
3620
  const RangePreviewInner = forwardRef(RangePreviewInnerFn);
3432
- //#endregion
3433
- //#region src/drag-handle.tsx
3621
+ // src/drag-handle.tsx
3434
3622
  const dragHandleStateAttributesMapping = {
3435
3623
  root: () => null,
3436
3624
  active: (v) => v ? { "data-active": "" } : null,
@@ -3441,7 +3629,7 @@ const dragHandleStateAttributesMapping = {
3441
3629
  function useDragHandle(edge, { dragging: draggingProp }) {
3442
3630
  const { temporal: T, setHoveredDate, readOnly, disabled } = useCalendarStable();
3443
3631
  const { rangeStart, rangeEnd } = useCalendarState();
3444
- const { rootState } = useMonthViewState();
3632
+ const { rootState } = useViewState();
3445
3633
  const cellData = useContext(DayCellDataContext);
3446
3634
  const { orientation } = useContext(GridContext);
3447
3635
  const date = cellData?.date;
@@ -3449,32 +3637,34 @@ function useDragHandle(edge, { dragging: draggingProp }) {
3449
3637
  const isActive = readOnly || disabled || outsideDisabled ? false : edge === "start" ? !!(date && rangeStart && T.PlainDate.compare(date, rangeStart) === 0) : !!(date && rangeEnd && T.PlainDate.compare(date, rangeEnd) === 0);
3450
3638
  const isDragging = !!draggingProp && isActive;
3451
3639
  const handleRef = useRef(null);
3640
+ const state = useMemo(() => ({
3641
+ root: rootState,
3642
+ active: isActive,
3643
+ dragging: isDragging,
3644
+ edge,
3645
+ orientation
3646
+ }), [
3647
+ rootState,
3648
+ isActive,
3649
+ isDragging,
3650
+ edge,
3651
+ orientation
3652
+ ]);
3653
+ const defaultProps = {
3654
+ role: "slider",
3655
+ "aria-roledescription": "drag handle",
3656
+ "aria-label": edge === "start" ? "Range start date" : "Range end date",
3657
+ "aria-valuetext": date?.toString(),
3658
+ "aria-grabbed": isActive ? isDragging : void 0,
3659
+ "aria-hidden": isActive ? void 0 : true,
3660
+ onPointerEnter: () => {
3661
+ if (date && !outsideDisabled) setHoveredDate(date);
3662
+ }
3663
+ };
3452
3664
  return {
3453
- state: useMemo(() => ({
3454
- root: rootState,
3455
- active: isActive,
3456
- dragging: isDragging,
3457
- edge,
3458
- orientation
3459
- }), [
3460
- rootState,
3461
- isActive,
3462
- isDragging,
3463
- edge,
3464
- orientation
3465
- ]),
3665
+ state,
3466
3666
  stateAttributesMapping: dragHandleStateAttributesMapping,
3467
- defaultProps: {
3468
- role: "slider",
3469
- "aria-roledescription": "drag handle",
3470
- "aria-label": edge === "start" ? "Range start date" : "Range end date",
3471
- "aria-valuetext": date?.toString(),
3472
- "aria-grabbed": isActive ? isDragging : void 0,
3473
- "aria-hidden": isActive ? void 0 : true,
3474
- onPointerEnter: () => {
3475
- if (date && !outsideDisabled) setHoveredDate(date);
3476
- }
3477
- },
3667
+ defaultProps,
3478
3668
  handleRef
3479
3669
  };
3480
3670
  }
@@ -3515,27 +3705,41 @@ function RangeEndDragHandleFn(props, ref) {
3515
3705
  }
3516
3706
  /** Convenience wrapper for {@link RangeDragHandle} with `edge="end"`. */
3517
3707
  const RangeEndDragHandle = forwardRef(RangeEndDragHandleFn);
3518
- //#endregion
3519
- //#region src/week-number.tsx
3708
+ // src/week-number.tsx
3520
3709
  const weekNumberCellStateAttributesMapping = {
3521
3710
  root: () => null,
3522
3711
  weekNumber: (v) => ({ "data-week-number": String(v) })
3523
3712
  };
3713
+ /**
3714
+ * Default strategy: ISO 8601, generalized to the week's midpoint day.
3715
+ *
3716
+ * A week belongs to the year containing the majority of its days, i.e. the
3717
+ * year containing its midpoint day (day ⌈N/2⌉ of an N-day week — Thursday
3718
+ * for 7-day ISO weeks). The midpoint day of the row is located and its week
3719
+ * number computed via {@link getISOWeekNumber}.
3720
+ */
3721
+ const defaultWeekNumberStrategy = (weekDays, T) => {
3722
+ let midDay = weekDays[0];
3723
+ if (midDay === void 0) return 0;
3724
+ const midpoint = Math.ceil(midDay.daysInWeek / 2);
3725
+ for (const d of weekDays) if (d.dayOfWeek === midpoint) {
3726
+ midDay = d;
3727
+ break;
3728
+ }
3729
+ return getISOWeekNumber(midDay, T);
3730
+ };
3524
3731
  function WeekNumberCellFn(props, ref) {
3525
- const { render, ...otherProps } = props;
3732
+ const { render, getWeekNumber, ...otherProps } = props;
3526
3733
  const weekData = useContext(WeekDataContext);
3527
- const { rootState } = useMonthViewState();
3734
+ const { rootState } = useViewState();
3528
3735
  const { temporal: T } = useCalendarStable();
3529
3736
  const days = weekData?.days ?? [];
3530
- const weekNumber = useMemo(() => {
3531
- let thursday = days[0];
3532
- if (thursday === void 0) return 0;
3533
- for (const d of days) if (d.dayOfWeek === 4) {
3534
- thursday = d;
3535
- break;
3536
- }
3537
- return getISOWeekNumber(thursday, T);
3538
- }, [days, T]);
3737
+ const strategy = getWeekNumber ?? defaultWeekNumberStrategy;
3738
+ const weekNumber = useMemo(() => strategy(days, T), [
3739
+ strategy,
3740
+ days,
3741
+ T
3742
+ ]);
3539
3743
  const state = useMemo(() => ({
3540
3744
  root: rootState,
3541
3745
  weekNumber
@@ -3555,14 +3759,32 @@ function WeekNumberCellFn(props, ref) {
3555
3759
  });
3556
3760
  }
3557
3761
  /**
3558
- * Renders the ISO 8601 week number for a week row. Must be used inside
3559
- * a {@link WeekTemplate}. Renders a `<td>` with `role="rowheader"`.
3762
+ * Renders the week number for a week row. Must be used inside a
3763
+ * {@link WeekTemplate}. Renders a `<td>` with `role="rowheader"`.
3764
+ *
3765
+ * ## Week numbering
3766
+ *
3767
+ * By default, week numbers follow ISO 8601: a week belongs to the year that
3768
+ * contains the majority of its days, which is the year containing the week's
3769
+ * midpoint day (Thursday for a Monday–Sunday 7-day week), and week 1 is the
3770
+ * week containing the year's first midpoint day (equivalently, January 4).
3771
+ * This holds regardless of which day the displayed week row starts on.
3772
+ *
3773
+ * For calendars whose weeks are not 7 days, the default generalizes the same
3774
+ * rule: the midpoint is day ⌈N/2⌉ of an N-day week and the week-1 anchor is
3775
+ * January (N − ⌈N/2⌉ + 1). Note that no standard defines week numbering for
3776
+ * such calendars, so the default is a best-effort extrapolation.
3777
+ *
3778
+ * Pass `getWeekNumber` to override the numbering entirely (e.g. US-style
3779
+ * numbering where week 1 contains January 1, or fiscal-year weeks). It
3780
+ * receives the week row's dates in display order plus the calendar's
3781
+ * Temporal namespace, and must return the number to display.
3560
3782
  */
3561
3783
  const WeekNumberCell = forwardRef(WeekNumberCellFn);
3562
3784
  const weekNumberHeaderStateAttributesMapping = { root: () => null };
3563
3785
  function WeekNumberHeaderFn(props, ref) {
3564
3786
  const { render, ...otherProps } = props;
3565
- const { rootState } = useMonthViewState();
3787
+ const { rootState } = useViewState();
3566
3788
  const state = useMemo(() => ({ root: rootState }), [rootState]);
3567
3789
  return useRender({
3568
3790
  defaultTagName: "th",
@@ -3581,8 +3803,7 @@ function WeekNumberHeaderFn(props, ref) {
3581
3803
  * Column header for the week number column. Renders a `<th scope="col">`.
3582
3804
  */
3583
3805
  const WeekNumberHeader = forwardRef(WeekNumberHeaderFn);
3584
- //#endregion
3585
- //#region src/compute-weeks-in-window.ts
3806
+ // src/compute-weeks-in-window.ts
3586
3807
  /**
3587
3808
  * Computes an array of week descriptors for a continuous window.
3588
3809
  * `firstWeek` is snapped back to the nearest `weekStartDay`.
@@ -3604,115 +3825,7 @@ function computeWeeksInWindow(firstWeek, weekCount, weekStartDay, _T) {
3604
3825
  }
3605
3826
  return weeks;
3606
3827
  }
3607
- //#endregion
3608
- //#region src/out-of-range.ts
3609
- /** Returns true if any day in the 7-day span starting at weekStart falls within [min, max]. */
3610
- function weekHasValidDay(weekStart, min, max, T) {
3611
- const weekEnd = weekStart.add({ days: 6 });
3612
- return T.PlainDate.compare(weekStart, max) <= 0 && T.PlainDate.compare(weekEnd, min) >= 0;
3613
- }
3614
- /**
3615
- * Returns the start of the week (per weekStartDay) that contains the given date.
3616
- * Uses dayOfWeek % 7 → Sun=0…Sat=6 convention.
3617
- */
3618
- function weekStartContaining(date, weekStartDay, _T) {
3619
- const daysFromStart = (date.dayOfWeek % 7 - weekStartDay + 7) % 7;
3620
- return date.subtract({ days: daysFromStart });
3621
- }
3622
- /** Find the week start (per weekStartDay) whose 7-day span contains min. */
3623
- function findFirstValidWeekStart(min, weekStartDay, T) {
3624
- return weekStartContaining(min, weekStartDay, T);
3625
- }
3626
- /** Find the week start (per weekStartDay) whose 7-day span contains max. */
3627
- function findLastValidWeekStart(max, weekStartDay, T) {
3628
- return weekStartContaining(max, weekStartDay, T);
3629
- }
3630
- /**
3631
- * Trim leading and trailing fully-disabled weeks from a window.
3632
- * Returns new { firstWeek, weekCount }.
3633
- */
3634
- function shrinkWindow(firstWeek, weekCount, min, max, T) {
3635
- let start = 0;
3636
- let end = weekCount - 1;
3637
- while (start <= end) {
3638
- if (weekHasValidDay(firstWeek.add({ days: start * 7 }), min, max, T)) break;
3639
- start++;
3640
- }
3641
- while (end >= start) {
3642
- if (weekHasValidDay(firstWeek.add({ days: end * 7 }), min, max, T)) break;
3643
- end--;
3644
- }
3645
- if (start > end) return {
3646
- firstWeek,
3647
- weekCount
3648
- };
3649
- return {
3650
- firstWeek: firstWeek.add({ days: start * 7 }),
3651
- weekCount: end - start + 1
3652
- };
3653
- }
3654
- /**
3655
- * Given a target firstWeek and weekCount, apply the out-of-range behavior and return
3656
- * the adjusted { firstWeek, weekCount }.
3657
- */
3658
- function applyOutOfRange({ targetFirstWeek, weekCount, behavior, min, max, weekStartDay, T }) {
3659
- if (!min || !max || behavior === "unbounded") return {
3660
- firstWeek: targetFirstWeek,
3661
- weekCount
3662
- };
3663
- if (behavior === "stop") return {
3664
- firstWeek: targetFirstWeek,
3665
- weekCount
3666
- };
3667
- if (behavior === "stop-shrink") return shrinkWindow(targetFirstWeek, weekCount, min, max, T);
3668
- if (behavior === "snap" || behavior === "snap-shrink") {
3669
- const lastValid = findLastValidWeekStart(max, weekStartDay, T);
3670
- const snappedFirst = lastValid.subtract({ days: (weekCount - 1) * 7 });
3671
- const targetLastWeek = targetFirstWeek.add({ days: (weekCount - 1) * 7 });
3672
- let resolvedFirst;
3673
- if (T.PlainDate.compare(targetLastWeek, lastValid) <= 0) {
3674
- const firstValid = findFirstValidWeekStart(min, weekStartDay, T);
3675
- if (T.PlainDate.compare(targetFirstWeek, firstValid) >= 0) resolvedFirst = targetFirstWeek;
3676
- else resolvedFirst = firstValid;
3677
- } else resolvedFirst = snappedFirst;
3678
- if (behavior === "snap-shrink") return shrinkWindow(resolvedFirst, weekCount, min, max, T);
3679
- return {
3680
- firstWeek: resolvedFirst,
3681
- weekCount
3682
- };
3683
- }
3684
- return {
3685
- firstWeek: targetFirstWeek,
3686
- weekCount
3687
- };
3688
- }
3689
- /**
3690
- * Returns whether the navigation button for the given direction should be enabled.
3691
- */
3692
- function canShift({ currentFirstWeek, weekCount, direction, shiftBy, behavior, min, max, weekStartDay, T }) {
3693
- if (behavior === "unbounded" || !min || !max) return true;
3694
- const shift = shiftBy ?? weekCount;
3695
- const targetFirstWeek = currentFirstWeek.add({ days: direction * shift * 7 });
3696
- if (behavior === "stop" || behavior === "stop-shrink") {
3697
- for (let i = 0; i < weekCount; i++) if (weekHasValidDay(targetFirstWeek.add({ days: i * 7 }), min, max, T)) return true;
3698
- return false;
3699
- }
3700
- if (behavior === "snap" || behavior === "snap-shrink") {
3701
- const applied = applyOutOfRange({
3702
- targetFirstWeek,
3703
- weekCount,
3704
- behavior,
3705
- min,
3706
- max,
3707
- weekStartDay,
3708
- T
3709
- });
3710
- return T.PlainDate.compare(applied.firstWeek, currentFirstWeek) !== 0;
3711
- }
3712
- return true;
3713
- }
3714
- //#endregion
3715
- //#region src/resolve-first-week.ts
3828
+ // src/resolve-first-week.ts
3716
3829
  /** Snaps `date` back to the start of its containing week (determined by `weekStartDay`). */
3717
3830
  function snapToWeekStart(date, weekStartDay) {
3718
3831
  const offset = (date.dayOfWeek % 7 - weekStartDay + 7) % 7;
@@ -3803,8 +3916,109 @@ function resolveFirstWeek(currentFirstWeek, weekCount, target, options) {
3803
3916
  }
3804
3917
  }
3805
3918
  }
3806
- //#endregion
3807
- //#region src/weeks-view-state.ts
3919
+ // src/out-of-range.ts
3920
+ /** Returns true if any day in the 7-day span starting at weekStart falls within [min, max]. */
3921
+ function weekHasValidDay(weekStart, min, max, T) {
3922
+ const weekEnd = weekStart.add({ days: 6 });
3923
+ return (!max || T.PlainDate.compare(weekStart, max) <= 0) && (!min || T.PlainDate.compare(weekEnd, min) >= 0);
3924
+ }
3925
+ /** Returns true if any of the `weekCount` weeks starting at firstWeek has a day in [min, max]. */
3926
+ function windowHasValidWeek(firstWeek, weekCount, min, max, T) {
3927
+ for (let i = 0; i < weekCount; i++) if (weekHasValidDay(firstWeek.add({ weeks: i }), min, max, T)) return true;
3928
+ return false;
3929
+ }
3930
+ /**
3931
+ * Returns the start of the week (per weekStartDay) that contains the given date.
3932
+ * Uses dayOfWeek % 7 → Sun=0…Sat=6 convention.
3933
+ */
3934
+ function weekStartContaining(date, weekStartDay) {
3935
+ const daysFromStart = (date.dayOfWeek % 7 - weekStartDay + 7) % 7;
3936
+ return date.subtract({ days: daysFromStart });
3937
+ }
3938
+ /**
3939
+ * Trim leading and trailing fully-disabled weeks from a window.
3940
+ * Returns new { firstWeek, weekCount }.
3941
+ */
3942
+ function shrinkWindow(firstWeek, weekCount, min, max, T) {
3943
+ let start = 0;
3944
+ let end = weekCount - 1;
3945
+ while (start <= end) {
3946
+ if (weekHasValidDay(firstWeek.add({ days: start * 7 }), min, max, T)) break;
3947
+ start++;
3948
+ }
3949
+ while (end >= start) {
3950
+ if (weekHasValidDay(firstWeek.add({ days: end * 7 }), min, max, T)) break;
3951
+ end--;
3952
+ }
3953
+ if (start > end) return {
3954
+ firstWeek,
3955
+ weekCount
3956
+ };
3957
+ return {
3958
+ firstWeek: firstWeek.add({ days: start * 7 }),
3959
+ weekCount: end - start + 1
3960
+ };
3961
+ }
3962
+ /**
3963
+ * Given a target firstWeek and weekCount, apply the out-of-range behavior and return
3964
+ * the adjusted { firstWeek, weekCount }.
3965
+ */
3966
+ function applyOutOfRange({ targetFirstWeek, weekCount, behavior, min, max, weekStartDay, T }) {
3967
+ if (!min && !max || behavior === "unbounded") return {
3968
+ firstWeek: targetFirstWeek,
3969
+ weekCount
3970
+ };
3971
+ if (behavior === "stop") return {
3972
+ firstWeek: targetFirstWeek,
3973
+ weekCount
3974
+ };
3975
+ if (behavior === "stop-shrink") return shrinkWindow(targetFirstWeek, weekCount, min, max, T);
3976
+ const targetLastWeek = targetFirstWeek.add({ weeks: weekCount - 1 });
3977
+ const lastValid = max && weekStartContaining(max, weekStartDay);
3978
+ const firstValid = min && weekStartContaining(min, weekStartDay);
3979
+ let resolvedFirst = targetFirstWeek;
3980
+ if (lastValid && T.PlainDate.compare(targetLastWeek, lastValid) > 0) resolvedFirst = lastValid.subtract({ weeks: weekCount - 1 });
3981
+ else if (firstValid && T.PlainDate.compare(targetFirstWeek, firstValid) < 0) resolvedFirst = firstValid;
3982
+ if (behavior === "snap-shrink") return shrinkWindow(resolvedFirst, weekCount, min, max, T);
3983
+ return {
3984
+ firstWeek: resolvedFirst,
3985
+ weekCount
3986
+ };
3987
+ }
3988
+ // src/weeks-window.ts
3989
+ function createWeekWindowPolicy({ weekCount, behavior, min, max, weekStartDay, T }) {
3990
+ const bounds = {
3991
+ weekCount,
3992
+ behavior,
3993
+ ...min !== void 0 && { min },
3994
+ ...max !== void 0 && { max },
3995
+ weekStartDay,
3996
+ T
3997
+ };
3998
+ const isStop = behavior === "stop" || behavior === "stop-shrink";
3999
+ const isBounded = min !== void 0 || max !== void 0;
4000
+ const resolve = (requestedFirstWeek) => applyOutOfRange({
4001
+ ...bounds,
4002
+ targetFirstWeek: requestedFirstWeek
4003
+ });
4004
+ const moveTo = (requestedFirstWeek) => {
4005
+ if (isStop && isBounded && !windowHasValidWeek(requestedFirstWeek, weekCount, min, max, T)) return null;
4006
+ return resolve(requestedFirstWeek);
4007
+ };
4008
+ return {
4009
+ resolve,
4010
+ moveTo,
4011
+ shift: (current, direction, shiftBy) => {
4012
+ const by = shiftBy ?? current.weekCount;
4013
+ const target = current.firstWeek.add({ weeks: direction * by });
4014
+ const next = moveTo(target);
4015
+ if (next === null) return null;
4016
+ if ((behavior === "snap" || behavior === "snap-shrink") && isBounded && T.PlainDate.compare(next.firstWeek, current.firstWeek) === 0) return null;
4017
+ return next;
4018
+ }
4019
+ };
4020
+ }
4021
+ // src/weeks-view-state.ts
3808
4022
  /**
3809
4023
  * Core state management hook for WeeksView.Root.
3810
4024
  * Reads calendar-level context and manages weeks-specific state.
@@ -3816,14 +4030,13 @@ function useWeeksViewRootState(props) {
3816
4030
  const calStable = useCalendarStable();
3817
4031
  const calState = useCalendarState();
3818
4032
  const T = calStable.temporal;
3819
- const { weekStartDay, isDateDisabled, minValue, maxValue, timeZone } = calStable;
4033
+ const { weekStartDay, isDateDisabled, minValue, maxValue, timeZone, today } = calStable;
3820
4034
  const isControlled = firstWeekProp !== void 0;
3821
4035
  const resolveSpec = useCallback((spec) => resolveFirstWeekSpec(spec, weekStartDay, T), [weekStartDay, T]);
3822
4036
  const [internalFirstWeek, setInternalFirstWeek] = useState(() => {
3823
4037
  if (firstWeekProp !== void 0) return resolveSpec(firstWeekProp);
3824
4038
  if (defaultFirstWeekProp !== void 0) return resolveSpec(defaultFirstWeekProp);
3825
- if (calState.selected) return resolveSpec(toZonedDateTime(calState.selected, timeZone, T).toPlainDate());
3826
- return resolveSpec(T.Now.plainDateISO());
4039
+ return resolveSpec(resolveInitialAnchor(calState.selected, today, timeZone, T));
3827
4040
  });
3828
4041
  const resolvedFirstWeek = isControlled ? resolveSpec(firstWeekProp) : internalFirstWeek;
3829
4042
  const rawWeeks = useMemo(() => computeWeeksInWindow(resolvedFirstWeek, weekCount, weekStartDay, T), [
@@ -3832,16 +4045,14 @@ function useWeeksViewRootState(props) {
3832
4045
  weekStartDay,
3833
4046
  T
3834
4047
  ]);
3835
- const outOfRangeResult = useMemo(() => applyOutOfRange({
3836
- targetFirstWeek: resolvedFirstWeek,
4048
+ const windowPolicy = useMemo(() => createWeekWindowPolicy({
3837
4049
  weekCount,
3838
4050
  behavior: outOfRangeBehavior,
3839
- ...minValue !== void 0 && { min: minValue },
3840
- ...maxValue !== void 0 && { max: maxValue },
4051
+ min: minValue,
4052
+ max: maxValue,
3841
4053
  weekStartDay,
3842
4054
  T
3843
4055
  }), [
3844
- resolvedFirstWeek,
3845
4056
  weekCount,
3846
4057
  outOfRangeBehavior,
3847
4058
  minValue,
@@ -3849,6 +4060,7 @@ function useWeeksViewRootState(props) {
3849
4060
  weekStartDay,
3850
4061
  T
3851
4062
  ]);
4063
+ const outOfRangeResult = useMemo(() => windowPolicy.resolve(resolvedFirstWeek), [windowPolicy, resolvedFirstWeek]);
3852
4064
  const adjustedWeeks = useMemo(() => {
3853
4065
  const sameFirst = T.PlainDate.compare(outOfRangeResult.firstWeek, resolvedFirstWeek) === 0;
3854
4066
  const sameCount = outOfRangeResult.weekCount === weekCount;
@@ -3878,10 +4090,10 @@ function useWeeksViewRootState(props) {
3878
4090
  const firstWeek = weeks[0];
3879
4091
  const lastWeek = weeks[weeks.length - 1];
3880
4092
  if (firstWeek === void 0 || lastWeek === void 0) {
3881
- const today = T.Now.plainDateISO();
4093
+ const now = today();
3882
4094
  return {
3883
- windowStart: today,
3884
- windowEnd: today,
4095
+ windowStart: now,
4096
+ windowEnd: now,
3885
4097
  weekCount: 0,
3886
4098
  dayCount: 0,
3887
4099
  enabledWeekCount: 0,
@@ -4026,67 +4238,35 @@ function useWeeksViewRootState(props) {
4026
4238
  if (!isControlled) setInternalFirstWeek(newFirstWeek);
4027
4239
  onFirstWeekChange?.(newFirstWeek);
4028
4240
  }, [isControlled, onFirstWeekChange]);
4241
+ const shownWindow = useMemo(() => ({
4242
+ firstWeek: windowInfo.windowStart,
4243
+ weekCount: windowInfo.weekCount
4244
+ }), [windowInfo.windowStart, windowInfo.weekCount]);
4029
4245
  const goNext = useCallback((shiftBy) => {
4030
- const shift = shiftBy ?? weekCount;
4031
- updateFirstWeek(applyOutOfRange({
4032
- targetFirstWeek: resolvedFirstWeek.add({ weeks: shift }),
4033
- weekCount,
4034
- behavior: outOfRangeBehavior,
4035
- ...minValue !== void 0 && { min: minValue },
4036
- ...maxValue !== void 0 && { max: maxValue },
4037
- weekStartDay,
4038
- T
4039
- }).firstWeek);
4246
+ const next = windowPolicy.shift(shownWindow, 1, shiftBy);
4247
+ if (next) updateFirstWeek(next.firstWeek);
4040
4248
  }, [
4041
- resolvedFirstWeek,
4042
- weekCount,
4043
- outOfRangeBehavior,
4044
- minValue,
4045
- maxValue,
4046
- weekStartDay,
4047
- T,
4249
+ shownWindow,
4250
+ windowPolicy,
4048
4251
  updateFirstWeek
4049
4252
  ]);
4050
4253
  const goPrev = useCallback((shiftBy) => {
4051
- const shift = shiftBy ?? weekCount;
4052
- updateFirstWeek(applyOutOfRange({
4053
- targetFirstWeek: resolvedFirstWeek.subtract({ weeks: shift }),
4054
- weekCount,
4055
- behavior: outOfRangeBehavior,
4056
- ...minValue !== void 0 && { min: minValue },
4057
- ...maxValue !== void 0 && { max: maxValue },
4058
- weekStartDay,
4059
- T
4060
- }).firstWeek);
4254
+ const next = windowPolicy.shift(shownWindow, -1, shiftBy);
4255
+ if (next) updateFirstWeek(next.firstWeek);
4061
4256
  }, [
4062
- resolvedFirstWeek,
4063
- weekCount,
4064
- outOfRangeBehavior,
4065
- minValue,
4066
- maxValue,
4067
- weekStartDay,
4068
- T,
4257
+ shownWindow,
4258
+ windowPolicy,
4069
4259
  updateFirstWeek
4070
4260
  ]);
4071
4261
  const scrollToWeek = useCallback((target, options) => {
4072
- updateFirstWeek(applyOutOfRange({
4073
- targetFirstWeek: resolveFirstWeek(resolvedFirstWeek, weekCount, resolveSpec(target), options),
4074
- weekCount,
4075
- behavior: outOfRangeBehavior,
4076
- ...minValue !== void 0 && { min: minValue },
4077
- ...maxValue !== void 0 && { max: maxValue },
4078
- weekStartDay,
4079
- T
4080
- }).firstWeek);
4262
+ const requested = resolveFirstWeek(shownWindow.firstWeek, weekCount, resolveSpec(target), options);
4263
+ const next = windowPolicy.moveTo(requested);
4264
+ if (next) updateFirstWeek(next.firstWeek);
4081
4265
  }, [
4082
- resolvedFirstWeek,
4266
+ shownWindow,
4083
4267
  weekCount,
4084
4268
  resolveSpec,
4085
- outOfRangeBehavior,
4086
- minValue,
4087
- maxValue,
4088
- weekStartDay,
4089
- T,
4269
+ windowPolicy,
4090
4270
  updateFirstWeek
4091
4271
  ]);
4092
4272
  const onWindowChangeRef = useRef(onWindowChange);
@@ -4103,6 +4283,7 @@ function useWeeksViewRootState(props) {
4103
4283
  weekCount,
4104
4284
  scrollBy,
4105
4285
  outOfRangeBehavior,
4286
+ windowPolicy,
4106
4287
  goNext,
4107
4288
  goPrev,
4108
4289
  scrollToWeek,
@@ -4112,6 +4293,7 @@ function useWeeksViewRootState(props) {
4112
4293
  weekCount,
4113
4294
  scrollBy,
4114
4295
  outOfRangeBehavior,
4296
+ windowPolicy,
4115
4297
  goNext,
4116
4298
  goPrev,
4117
4299
  scrollToWeek,
@@ -4159,52 +4341,34 @@ function useWeeksViewRootState(props) {
4159
4341
  tabTargetDate,
4160
4342
  gridHasFocus
4161
4343
  ]),
4344
+ viewStableCtx: useMemo(() => ({
4345
+ gridFocusedRef,
4346
+ outsideDays: "enabled",
4347
+ setFocusedDate
4348
+ }), []),
4349
+ viewStateCtx: useMemo(() => ({
4350
+ currentDateTime,
4351
+ rootState
4352
+ }), [currentDateTime, rootState]),
4162
4353
  scrollToWeek
4163
4354
  };
4164
4355
  }
4165
- //#endregion
4166
- //#region src/weeks-view.tsx
4356
+ // src/weeks-view.tsx
4167
4357
  function WeeksViewRootFn(props, ref) {
4168
4358
  const { children } = props;
4169
- const { stableCtx, stateCtx, viewCtx, scrollToWeek } = useWeeksViewRootState(props);
4359
+ const { stableCtx, stateCtx, viewCtx, viewStableCtx, viewStateCtx, scrollToWeek } = useWeeksViewRootState(props);
4170
4360
  useImperativeHandle(ref, () => ({ scrollToWeek }), [scrollToWeek]);
4171
- const gridFocusedRef = useRef(false);
4172
- const monthViewStableShim = useMemo(() => ({
4173
- numberOfMonths: 1,
4174
- fixedWeeks: false,
4175
- outsideDays: "enabled",
4176
- outOfRangeBehavior: "unbounded",
4177
- goNextMonth: () => {},
4178
- goPrevMonth: () => {},
4179
- setGridLabelId: () => {},
4180
- gridFocusedRef
4181
- }), []);
4182
- const monthViewStateShim = useMemo(() => ({
4183
- currentMonth: {
4184
- year: stateCtx.currentDateTime.year,
4185
- month: stateCtx.currentDateTime.month
4186
- },
4187
- weeks: [],
4188
- allMonths: [],
4189
- currentDateTime: stateCtx.currentDateTime,
4190
- gridLabelIds: stateCtx.gridLabelIds,
4191
- rootState: stateCtx.rootState
4192
- }), [
4193
- stateCtx.currentDateTime,
4194
- stateCtx.gridLabelIds,
4195
- stateCtx.rootState
4196
- ]);
4197
- return /* @__PURE__ */ jsx(MonthViewStableContext.Provider, {
4198
- value: monthViewStableShim,
4199
- children: /* @__PURE__ */ jsx(MonthViewStateContext.Provider, {
4200
- value: monthViewStateShim,
4201
- children: /* @__PURE__ */ jsx(WeeksViewStableContext.Provider, {
4202
- value: stableCtx,
4203
- children: /* @__PURE__ */ jsx(WeeksViewStateContext.Provider, {
4204
- value: stateCtx,
4361
+ return /* @__PURE__ */ jsx(WeeksViewStableContext.Provider, {
4362
+ value: stableCtx,
4363
+ children: /* @__PURE__ */ jsx(WeeksViewStateContext.Provider, {
4364
+ value: stateCtx,
4365
+ children: /* @__PURE__ */ jsx(ViewStableContext.Provider, {
4366
+ value: viewStableCtx,
4367
+ children: /* @__PURE__ */ jsx(ViewStateContext.Provider, {
4368
+ value: viewStateCtx,
4205
4369
  children: /* @__PURE__ */ jsx(ViewContext.Provider, {
4206
4370
  value: viewCtx,
4207
- children
4371
+ children: /* @__PURE__ */ jsx(DayCellStoreProvider, { children })
4208
4372
  })
4209
4373
  })
4210
4374
  })
@@ -4231,8 +4395,7 @@ function WeeksViewFn(props, ref) {
4231
4395
  }
4232
4396
  const WeeksView = forwardRef(WeeksViewFn);
4233
4397
  WeeksView.Root = WeeksViewRoot;
4234
- //#endregion
4235
- //#region src/weeks-navigation.tsx
4398
+ // src/weeks-navigation.tsx
4236
4399
  const weeksNavButtonStateAttributesMapping = {
4237
4400
  root: () => null,
4238
4401
  direction: (v) => ({ "data-direction": v }),
@@ -4243,35 +4406,24 @@ const weekCountStateAttributesMapping = {
4243
4406
  weekCount: () => null
4244
4407
  };
4245
4408
  function useWeeksNavButton(direction, shiftByProp) {
4246
- const { disabled: globalDisabled, minValue, maxValue, temporal: T, weekStartDay } = useCalendarStable();
4247
- const { weekCount, outOfRangeBehavior, goNext, goPrev } = useWeeksViewStable();
4409
+ const { disabled: globalDisabled } = useCalendarStable();
4410
+ const { windowPolicy, goNext, goPrev } = useWeeksViewStable();
4248
4411
  const { windowInfo } = useWeeksViewState();
4249
- const { rootState } = useMonthViewState();
4250
- const currentFirstWeek = windowInfo.windowStart;
4412
+ const { rootState } = useViewState();
4413
+ const { windowStart, weekCount } = windowInfo;
4251
4414
  const isDisabled = useMemo(() => {
4252
4415
  if (globalDisabled) return true;
4253
- return !canShift({
4254
- currentFirstWeek,
4255
- weekCount,
4256
- direction: direction === "next" ? 1 : -1,
4257
- ...shiftByProp !== void 0 && { shiftBy: shiftByProp },
4258
- behavior: outOfRangeBehavior,
4259
- ...minValue !== void 0 && { min: minValue },
4260
- ...maxValue !== void 0 && { max: maxValue },
4261
- weekStartDay,
4262
- T
4263
- });
4416
+ return windowPolicy.shift({
4417
+ firstWeek: windowStart,
4418
+ weekCount
4419
+ }, direction === "next" ? 1 : -1, shiftByProp) === null;
4264
4420
  }, [
4265
4421
  globalDisabled,
4266
- currentFirstWeek,
4422
+ windowPolicy,
4423
+ windowStart,
4267
4424
  weekCount,
4268
4425
  direction,
4269
- shiftByProp,
4270
- outOfRangeBehavior,
4271
- minValue,
4272
- maxValue,
4273
- weekStartDay,
4274
- T
4426
+ shiftByProp
4275
4427
  ]);
4276
4428
  const state = useMemo(() => ({
4277
4429
  root: rootState,
@@ -4332,7 +4484,7 @@ const NextWeeksButton = forwardRef(NextWeeksButtonFn);
4332
4484
  function WeekCountFn(props, ref) {
4333
4485
  const { render, ...otherProps } = props;
4334
4486
  const { windowInfo } = useWeeksViewState();
4335
- const { rootState } = useMonthViewState();
4487
+ const { rootState } = useViewState();
4336
4488
  const count = windowInfo.weekCount;
4337
4489
  const state = useMemo(() => ({
4338
4490
  root: rootState,
@@ -4352,5 +4504,4 @@ function WeekCountFn(props, ref) {
4352
4504
  * out-of-range modes where the actual count may be less than the `weekCount` prop.
4353
4505
  */
4354
4506
  const WeekCount = forwardRef(WeekCountFn);
4355
- //#endregion
4356
- export { MonthSeparatorRow as A, useViewContext as B, DayButton as C, MonthSeparator as D, useWeeksViewState as E, DayCellDataContext as F, useCalendarStable as G, useMonthViewState as H, GridContext as I, useCalendarState as K, WeekDataContext as L, MonthSeparatorYear as M, GridHeader as N, MonthSeparatorCell as O, GridHeaderCell as P, MonthView as R, WeekTemplate as S, useWeeksViewStable as T, CalendarProvider as U, useMonthViewStable as V, computePreviewRange as W, NextMonthButton as _, WeeksViewRoot as a, Grid as b, computeWeeksInWindow as c, RangeEndDragHandle as d, RangeStartDragHandle as f, MonthYearString as g, DateString as h, WeeksView as i, MonthSeparatorWeekCount as j, MonthSeparatorMonth as k, WeekNumberCell as l, RangeSelected as m, PrevWeeksButton as n, resolveFirstWeek as o, RangePreview as p, WeekCount as r, resolveFirstWeekSpec as s, NextWeeksButton as t, WeekNumberHeader as u, PrevMonthButton as v, DayCellTemplate as w, GridBody as x, TimeString as y, MonthViewRoot as z };
4507
+ export { MonthSeparatorRow as A, DayCellDataContext as B, DayButton as C, MonthSeparator as D, useWeeksViewState as E, MonthView as F, useCalendarStable as G, WeekDataContext as H, MonthViewRoot as I, useCalendarState as K, useMonthViewStable as L, MonthSeparatorYear as M, GridHeader as N, MonthSeparatorCell as O, GridHeaderCell as P, useMonthViewState as R, WeekTemplate as S, useWeeksViewStable as T, CalendarProvider as U, GridContext as V, computePreviewRange as W, NextMonthButton as _, WeeksViewRoot as a, Grid as b, computeWeeksInWindow as c, RangeEndDragHandle as d, RangeStartDragHandle as f, MonthYearString as g, DateString as h, WeeksView as i, MonthSeparatorWeekCount as j, MonthSeparatorMonth as k, WeekNumberCell as l, RangeSelected as m, PrevWeeksButton as n, resolveFirstWeek as o, RangePreview as p, WeekCount as r, resolveFirstWeekSpec as s, NextWeeksButton as t, WeekNumberHeader as u, PrevMonthButton as v, DayCellTemplate as w, GridBody as x, TimeString as y, useViewContext as z };