@42-central/ui-react 0.20.1 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/dist/{chunk-45QRQKRC.js → chunk-3L5GLI67.js} +12 -8
  2. package/dist/chunk-3L5GLI67.js.map +1 -0
  3. package/dist/{chunk-BNWQ7IAZ.js → chunk-4FEOMQYR.js} +5 -5
  4. package/dist/{chunk-BNWQ7IAZ.js.map → chunk-4FEOMQYR.js.map} +1 -1
  5. package/dist/{chunk-POKLPMSB.js → chunk-D3JYDAUZ.js} +3 -3
  6. package/dist/{chunk-POKLPMSB.js.map → chunk-D3JYDAUZ.js.map} +1 -1
  7. package/dist/{chunk-KMZENCEP.js → chunk-DHJB4UJD.js} +4 -4
  8. package/dist/{chunk-KMZENCEP.js.map → chunk-DHJB4UJD.js.map} +1 -1
  9. package/dist/{chunk-IOYZC7SA.js → chunk-DJAXXLN6.js} +3 -3
  10. package/dist/{chunk-IOYZC7SA.js.map → chunk-DJAXXLN6.js.map} +1 -1
  11. package/dist/{chunk-3BXKTWWD.js → chunk-FB2G4LNH.js} +5 -5
  12. package/dist/{chunk-3BXKTWWD.js.map → chunk-FB2G4LNH.js.map} +1 -1
  13. package/dist/{chunk-E63VD25L.js → chunk-HQPU73WV.js} +4 -4
  14. package/dist/{chunk-E63VD25L.js.map → chunk-HQPU73WV.js.map} +1 -1
  15. package/dist/{chunk-RCF7HTG5.js → chunk-IRNF274I.js} +5 -5
  16. package/dist/chunk-IRNF274I.js.map +1 -0
  17. package/dist/{chunk-O5W3QWJ6.js → chunk-J44FJ7PH.js} +3 -3
  18. package/dist/{chunk-O5W3QWJ6.js.map → chunk-J44FJ7PH.js.map} +1 -1
  19. package/dist/{chunk-TWLJQE75.js → chunk-MRAJ45IM.js} +4 -4
  20. package/dist/{chunk-TWLJQE75.js.map → chunk-MRAJ45IM.js.map} +1 -1
  21. package/dist/{chunk-5HUEBSIS.js → chunk-N66NC6QK.js} +120 -24
  22. package/dist/chunk-N66NC6QK.js.map +1 -0
  23. package/dist/{chunk-SXNAUSEB.js → chunk-OZMSXYBX.js} +4 -4
  24. package/dist/{chunk-SXNAUSEB.js.map → chunk-OZMSXYBX.js.map} +1 -1
  25. package/dist/{chunk-LBAE6FP6.js → chunk-SZEOTXRZ.js} +4 -4
  26. package/dist/{chunk-LBAE6FP6.js.map → chunk-SZEOTXRZ.js.map} +1 -1
  27. package/dist/chunk-V6PY7C6S.js +18 -0
  28. package/dist/chunk-V6PY7C6S.js.map +1 -0
  29. package/dist/{chunk-MKKQE3TM.js → chunk-YPFSRZ3T.js} +4 -4
  30. package/dist/{chunk-MKKQE3TM.js.map → chunk-YPFSRZ3T.js.map} +1 -1
  31. package/dist/{chunk-NJPHZBLI.js → chunk-YWTOW7PZ.js} +5 -5
  32. package/dist/{chunk-NJPHZBLI.js.map → chunk-YWTOW7PZ.js.map} +1 -1
  33. package/dist/{chunk-VTDBWU6H.js → chunk-YZJUPYPO.js} +3 -3
  34. package/dist/{chunk-VTDBWU6H.js.map → chunk-YZJUPYPO.js.map} +1 -1
  35. package/dist/components/autocomplete/index.js +4 -3
  36. package/dist/components/autocomplete/index.js.map +1 -1
  37. package/dist/components/calendar-heatmap/calendar-heatmap-grid.d.ts +94 -0
  38. package/dist/components/calendar-heatmap/calendar-heatmap-grid.d.ts.map +1 -0
  39. package/dist/components/calendar-heatmap/calendar-heatmap.d.ts +76 -0
  40. package/dist/components/calendar-heatmap/calendar-heatmap.d.ts.map +1 -0
  41. package/dist/components/calendar-heatmap/index.d.ts +2 -0
  42. package/dist/components/calendar-heatmap/index.d.ts.map +1 -0
  43. package/dist/components/calendar-heatmap/index.js +311 -0
  44. package/dist/components/calendar-heatmap/index.js.map +1 -0
  45. package/dist/components/camera/index.js +6 -5
  46. package/dist/components/clipboard/index.js +1 -1
  47. package/dist/components/code-block/chrome.js +4 -4
  48. package/dist/components/code-block/index.js +5 -5
  49. package/dist/components/combobox/index.js +4 -3
  50. package/dist/components/combobox-list/index.js +6 -5
  51. package/dist/components/data-table/index.js +16 -16
  52. package/dist/components/date-picker/index.js +7 -6
  53. package/dist/components/date-picker/index.js.map +1 -1
  54. package/dist/components/hover-card/hover-card.d.ts +44 -26
  55. package/dist/components/hover-card/hover-card.d.ts.map +1 -1
  56. package/dist/components/hover-card/index.js +35 -53
  57. package/dist/components/hover-card/index.js.map +1 -1
  58. package/dist/components/input/index.js +1 -1
  59. package/dist/components/input/input.d.ts.map +1 -1
  60. package/dist/components/menu/index.js +3 -3
  61. package/dist/components/menu/menu.d.ts +7 -5
  62. package/dist/components/menu/menu.d.ts.map +1 -1
  63. package/dist/components/multi-combobox-list/index.js +6 -5
  64. package/dist/components/multi-select/index.js +5 -4
  65. package/dist/components/multi-select/index.js.map +1 -1
  66. package/dist/components/navigation-progress/index.d.ts +2 -0
  67. package/dist/components/navigation-progress/index.d.ts.map +1 -0
  68. package/dist/components/navigation-progress/index.js +133 -0
  69. package/dist/components/navigation-progress/index.js.map +1 -0
  70. package/dist/components/navigation-progress/navigation-progress.d.ts +46 -0
  71. package/dist/components/navigation-progress/navigation-progress.d.ts.map +1 -0
  72. package/dist/components/number-input/index.js +4 -3
  73. package/dist/components/number-input/number-input.d.ts.map +1 -1
  74. package/dist/components/password-input/index.js +1 -1
  75. package/dist/components/photo-capture/index.js +6 -5
  76. package/dist/components/photo-capture/index.js.map +1 -1
  77. package/dist/components/pills-input/index.js +2 -2
  78. package/dist/components/pin-input/index.js +1 -1
  79. package/dist/components/popover/index.d.ts +1 -1
  80. package/dist/components/popover/index.d.ts.map +1 -1
  81. package/dist/components/popover/index.js +2 -1
  82. package/dist/components/popover/popover.d.ts +44 -29
  83. package/dist/components/popover/popover.d.ts.map +1 -1
  84. package/dist/components/schedule/index.js +2 -2
  85. package/dist/components/select/index.js +5 -4
  86. package/dist/components/spotlight/index.js +5 -4
  87. package/dist/components/spotlight/index.js.map +1 -1
  88. package/dist/components/tags-input/index.js +4 -3
  89. package/dist/components/tags-input/index.js.map +1 -1
  90. package/dist/components/text-input/index.js +1 -1
  91. package/dist/components/textarea/index.js +1 -1
  92. package/dist/components/time-input/index.js +5 -4
  93. package/dist/components/time-input/index.js.map +1 -1
  94. package/dist/components/tooltip/index.js +2 -2
  95. package/dist/components/tree-multi-select/index.js +5 -4
  96. package/dist/components/tree-multi-select/index.js.map +1 -1
  97. package/dist/components/tree-select/index.js +4 -3
  98. package/dist/components/tree-select/index.js.map +1 -1
  99. package/dist/index.js +2 -2
  100. package/dist/lib/placement.d.ts +42 -1
  101. package/dist/lib/placement.d.ts.map +1 -1
  102. package/dist/lib/slide-on-switch.d.ts +69 -0
  103. package/dist/lib/slide-on-switch.d.ts.map +1 -0
  104. package/package.json +1 -1
  105. package/src/as-child.contract.test.tsx +4 -0
  106. package/src/components/calendar-heatmap/calendar-heatmap-grid.test.ts +186 -0
  107. package/src/components/calendar-heatmap/calendar-heatmap-grid.ts +192 -0
  108. package/src/components/calendar-heatmap/calendar-heatmap.test.tsx +180 -0
  109. package/src/components/calendar-heatmap/calendar-heatmap.tsx +385 -0
  110. package/src/components/calendar-heatmap/index.ts +11 -0
  111. package/src/components/hover-card/hover-card.tsx +89 -167
  112. package/src/components/input/input.test.tsx +23 -0
  113. package/src/components/input/input.tsx +10 -6
  114. package/src/components/menu/menu.tsx +16 -9
  115. package/src/components/navigation-progress/index.ts +14 -0
  116. package/src/components/navigation-progress/navigation-progress.test.tsx +184 -0
  117. package/src/components/navigation-progress/navigation-progress.tsx +228 -0
  118. package/src/components/number-input/number-input.tsx +3 -4
  119. package/src/components/popover/index.ts +2 -0
  120. package/src/components/popover/popover.test.tsx +131 -0
  121. package/src/components/popover/popover.tsx +191 -53
  122. package/src/lib/placement.test.ts +37 -0
  123. package/src/lib/placement.ts +60 -1
  124. package/src/lib/slide-on-switch.ts +99 -0
  125. package/dist/chunk-45QRQKRC.js.map +0 -1
  126. package/dist/chunk-5HUEBSIS.js.map +0 -1
  127. package/dist/chunk-G52U24GR.js +0 -10
  128. package/dist/chunk-G52U24GR.js.map +0 -1
  129. package/dist/chunk-RCF7HTG5.js.map +0 -1
@@ -0,0 +1,69 @@
1
+ import { type ElementType, type ReactElement, type ReactNode } from "react";
2
+ import type { Positioning } from "./placement";
3
+ /**
4
+ * Shared by `HoverCard.Group` and `Popover.Group`: several named triggers on
5
+ * one Ark machine, one panel that slides from the active trigger to the next.
6
+ */
7
+ /** Slide transition for a group's shared positioner. Ark sets the
8
+ * positioner's `transform: translate3d(var(--x), var(--y), 0)` inline
9
+ * (`@zag-js/popper`); animating `transform` itself makes the browser
10
+ * interpolate that translate between two trigger anchors when the group's
11
+ * active trigger changes. Passed as `style` (not a class) so it merges with,
12
+ * rather than replaces, Ark's own inline `transform`/`position` (Ark's
13
+ * `mergeProps` shallow-merges style objects); the same override-the-real-style
14
+ * technique `Tabs.Indicator` / `SegmentGroup` use for their sliding pill.
15
+ *
16
+ * Only applied once `useSlideAfterPlaced` reports `sliding`, never on an
17
+ * open's first placement: before it, the positioner sits at its unplaced
18
+ * origin (far off the trigger), and animating *that* jump reads as the panel
19
+ * flying in across the page instead of just appearing. A standalone `Root`
20
+ * never gets this at all: it also repositions on scroll/resize
21
+ * (`autoUpdate`), where an animated `transform` would look laggy rather than
22
+ * responsive. */
23
+ export declare const slideStyle: {
24
+ readonly transitionProperty: "transform";
25
+ readonly transitionDuration: "200ms";
26
+ readonly transitionTimingFunction: "cubic-bezier(0.32, 0.72, 0, 1)";
27
+ };
28
+ type UpdatePosition = NonNullable<Positioning["updatePosition"]>;
29
+ /**
30
+ * `sliding` turns true once an open's first placement has been applied, and
31
+ * false on every close. Waiting for the placement itself, not a frame count:
32
+ * the first one after an open can take several frames (the panel mounts,
33
+ * zag defers to the next frame, floating-ui computes asynchronously), and a
34
+ * transition switched on before it lands slides the panel in from its
35
+ * unplaced origin.
36
+ *
37
+ * Feed every open change to `onOpenChange`, and pass `updatePosition(...)`
38
+ * as the machine's `positioning.updatePosition` — zag calls it for every
39
+ * placement, with its own `updatePosition` to run. A consumer's own
40
+ * `updatePosition`, if any, is wrapped rather than replaced.
41
+ */
42
+ export declare const useSlideAfterPlaced: () => {
43
+ sliding: boolean;
44
+ onOpenChange: (next: boolean) => void;
45
+ updatePosition: (custom?: UpdatePosition) => UpdatePosition;
46
+ };
47
+ /** Split a group's children into its `Content` parts (matched by `type`)
48
+ * and everything else (the triggers), one level deep. */
49
+ export declare const splitGroupChildren: <P extends {
50
+ value?: string;
51
+ }>(children: ReactNode, content: ElementType<P>) => {
52
+ contents: ReactElement<P, string | import("react").JSXElementConstructor<any>>[];
53
+ triggers: (string | number | bigint | Iterable<ReactNode> | Promise<string | number | bigint | boolean | Iterable<ReactNode> | ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | import("react").ReactPortal | null | undefined> | ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | import("react").ReactPortal)[];
54
+ };
55
+ /** The `Content` whose `value` matches the active trigger, under one forced,
56
+ * stable `key` — overriding whatever each was authored with (e.g.
57
+ * `key={person.handle}` in a `.map()`). The slot only ever renders one at a
58
+ * time, but a *different* key switching in reads to React as a different
59
+ * component, unmounting the real Positioner/Content DOM tree and mounting a
60
+ * fresh one instead of updating it in place. That fresh mount breaks the
61
+ * "one shared, sliding panel" contract: its position starts unset again, so
62
+ * every switch would look like the panel jumping in from the top. */
63
+ export declare const activeGroupContent: (contents: ReactElement<{
64
+ value?: string;
65
+ }>[], triggerValue: string | null) => ReactElement<{
66
+ value?: string;
67
+ }, string | import("react").JSXElementConstructor<any>> | null;
68
+ export {};
69
+ //# sourceMappingURL=slide-on-switch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"slide-on-switch.d.ts","sourceRoot":"","sources":["../../src/lib/slide-on-switch.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,WAAW,EAEhB,KAAK,YAAY,EACjB,KAAK,SAAS,EAGf,MAAM,OAAO,CAAA;AACd,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAE9C;;;GAGG;AAEH;;;;;;;;;;;;;;;kBAekB;AAClB,eAAO,MAAM,UAAU;aACrB,kBAAkB,EAAE,WAAW;aAC/B,kBAAkB,EAAE,OAAO;aAC3B,wBAAwB,EAAE,gCAAgC;CAClD,CAAA;AAEV,KAAK,cAAc,GAAG,WAAW,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC,CAAA;AAEhE;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,mBAAmB;;yBAKF,OAAO;8BAKvB,cAAc,KAAG,cAAc;CAM5C,CAAA;AAED;0DAC0D;AAC1D,eAAO,MAAM,kBAAkB,GAAI,CAAC,SAAS;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,YACnD,SAAS,WACV,WAAW,CAAC,CAAC,CAAC;IAKd,QAAQ;IAA2B,QAAQ;CACrD,CAAA;AAED;;;;;;;sEAOsE;AACtE,eAAO,MAAM,kBAAkB,aACnB,YAAY,CAAC;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,EAAE,gBAC9B,MAAM,GAAG,IAAI;YADM,MAAM;8DAKxC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@42-central/ui-react",
3
- "version": "0.20.1",
3
+ "version": "0.22.0",
4
4
  "description": "React UI kit for 42 tools",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -18,6 +18,7 @@ import * as buttonGroup from "./components/button-group"
18
18
  import * as buttonMultiSelect from "./components/button-multi-select"
19
19
  import * as buttonSelect from "./components/button-select"
20
20
  import * as calendar from "./components/calendar"
21
+ import * as calendarHeatmap from "./components/calendar-heatmap"
21
22
  import * as camera from "./components/camera"
22
23
  import * as card from "./components/card"
23
24
  import * as carousel from "./components/carousel"
@@ -62,6 +63,7 @@ import * as multiComboboxList from "./components/multi-combobox-list"
62
63
  import * as multiSelect from "./components/multi-select"
63
64
  import * as navLink from "./components/nav-link"
64
65
  import * as navLinkTanstack from "./components/nav-link/tanstack"
66
+ import * as navigationProgress from "./components/navigation-progress"
65
67
  import * as notification from "./components/notification"
66
68
  import * as numberInput from "./components/number-input"
67
69
  import * as overlays from "./components/overlays"
@@ -154,6 +156,7 @@ const modules = {
154
156
  buttonMultiSelect,
155
157
  buttonSelect,
156
158
  calendar,
159
+ calendarHeatmap,
157
160
  camera,
158
161
  card,
159
162
  carousel,
@@ -197,6 +200,7 @@ const modules = {
197
200
  multiComboboxList,
198
201
  multiSelect,
199
202
  navLink,
203
+ navigationProgress,
200
204
  notification,
201
205
  numberInput,
202
206
  overlays,
@@ -0,0 +1,186 @@
1
+ import { CalendarDate } from "@internationalized/date"
2
+ import { describe, expect, it } from "vitest"
3
+ import {
4
+ buildHeatmap,
5
+ defaultThresholds,
6
+ intensity,
7
+ legendLevels,
8
+ levelOf,
9
+ nextHeatmapDay,
10
+ } from "./calendar-heatmap-grid"
11
+
12
+ const utc = (iso: string) => new Date(`${iso}T00:00:00Z`)
13
+
14
+ const build = (overrides: Partial<Parameters<typeof buildHeatmap>[0]> = {}) =>
15
+ buildHeatmap({
16
+ data: [],
17
+ start: utc("2026-10-01"),
18
+ end: utc("2026-10-31"),
19
+ timeZone: "UTC",
20
+ locale: "en-US",
21
+ ...overrides,
22
+ })
23
+
24
+ const keys = (layout: ReturnType<typeof buildHeatmap>) =>
25
+ layout.weeks.map((week) => week.map((day) => day?.key ?? null))
26
+
27
+ describe("buildHeatmap", () => {
28
+ it("lays out whole weeks, padding the days outside the range with null", () => {
29
+ // 2026-10-01 is a Thursday; en-US weeks start on Sunday.
30
+ const layout = build()
31
+ expect(layout.weeks).toHaveLength(5)
32
+ expect(layout.weeks.every((week) => week.length === 7)).toBe(true)
33
+ expect(keys(layout)[0]).toEqual([
34
+ null,
35
+ null,
36
+ null,
37
+ null,
38
+ "2026-10-01",
39
+ "2026-10-02",
40
+ "2026-10-03",
41
+ ])
42
+ expect(keys(layout).at(-1)).toEqual([
43
+ "2026-10-25",
44
+ "2026-10-26",
45
+ "2026-10-27",
46
+ "2026-10-28",
47
+ "2026-10-29",
48
+ "2026-10-30",
49
+ "2026-10-31",
50
+ ])
51
+ })
52
+
53
+ it.each([
54
+ ["en-US", undefined, "2026-09-27"],
55
+ ["fr-FR", undefined, "2026-09-28"],
56
+ ["en-US", "mon" as const, "2026-09-28"],
57
+ ["en-US", "sat" as const, "2026-09-26"],
58
+ ])("starts each week on the locale's day (%s, %s)", (locale, startOfWeek, firstRow) => {
59
+ const layout = build({ locale, startOfWeek })
60
+ expect(layout.weekdays[0]?.toISOString().slice(0, 10)).toBe(firstRow)
61
+ // Whatever the week start, every day in range is laid out exactly once.
62
+ expect(keys(layout).flat().filter(Boolean)).toHaveLength(31)
63
+ })
64
+
65
+ it("sums same-day entries and ignores data outside the range", () => {
66
+ const layout = build({
67
+ data: [
68
+ { date: utc("2026-10-05"), value: 2 },
69
+ { date: new Date("2026-10-05T18:30:00Z"), value: 3 },
70
+ { date: utc("2026-11-02"), value: 100 },
71
+ ],
72
+ })
73
+ const day = layout.weeks.flat().find((d) => d?.key === "2026-10-05")
74
+ expect(day?.value).toBe(5)
75
+ // The out-of-range 100 doesn't stretch the default scale.
76
+ expect(layout.thresholds).toEqual([1, 2, 3, 4])
77
+ expect(day?.level).toBe(4)
78
+ })
79
+
80
+ it.each([
81
+ ["UTC", "2026-10-26"],
82
+ ["Europe/Paris", "2026-10-27"],
83
+ ["Pacific/Auckland", "2026-10-27"],
84
+ ["America/Los_Angeles", "2026-10-26"],
85
+ ])("buckets an instant into its day in %s", (timeZone, expected) => {
86
+ const layout = build({
87
+ timeZone,
88
+ data: [{ date: new Date("2026-10-26T23:30:00Z"), value: 1 }],
89
+ })
90
+ const day = layout.weeks.flat().find((d) => d?.value === 1)
91
+ expect(day?.key).toBe(expected)
92
+ })
93
+
94
+ it("keeps one cell per day across a DST change", () => {
95
+ // Europe/Paris falls back on 2026-10-25, a 25-hour day.
96
+ const layout = build({ timeZone: "Europe/Paris" })
97
+ const days = layout.weeks.flat().filter(Boolean)
98
+ expect(days.map((d) => d?.key)).toEqual(
99
+ Array.from({ length: 31 }, (_, i) => `2026-10-${String(i + 1).padStart(2, "0")}`),
100
+ )
101
+ // Each Date is that day's local midnight.
102
+ const after = days.find((d) => d?.key === "2026-10-26")
103
+ expect(after?.date.toISOString()).toBe("2026-10-25T23:00:00.000Z")
104
+ })
105
+
106
+ it("labels a month where its weeks begin, dropping a label that would collide", () => {
107
+ const layout = build({ start: utc("2025-10-27"), end: utc("2026-10-26") })
108
+ const labels = layout.months.map(({ column, date }) => [column, date.toISOString().slice(0, 7)])
109
+ // 2025-10-27 is a Monday. The first column is October's, with one column
110
+ // before November's: too narrow for its label, so it goes.
111
+ expect(labels[0]).toEqual([1, "2025-11"])
112
+ expect(labels.at(-1)?.[1]).toBe("2026-10")
113
+ expect(labels).toHaveLength(12)
114
+ })
115
+ })
116
+
117
+ describe("levels", () => {
118
+ it.each([
119
+ [0, [1]],
120
+ [1, [1]],
121
+ [2, [1, 2]],
122
+ [4, [1, 2, 3, 4]],
123
+ [20, [1, 6, 11, 16]],
124
+ ])("splits a maximum of %i into quarters", (max, expected) => {
125
+ expect(defaultThresholds(max)).toEqual(expected)
126
+ })
127
+
128
+ it("counts the thresholds a value reaches", () => {
129
+ expect([0, 1, 5, 6, 15, 16, 99].map((v) => levelOf(v, [1, 6, 11, 16]))).toEqual([
130
+ 0, 1, 1, 2, 3, 4, 4,
131
+ ])
132
+ })
133
+
134
+ it("spreads fewer levels across the ramp, ending on the strongest", () => {
135
+ expect([0, 1].map((l) => intensity(l, 1))).toEqual([0, 4])
136
+ expect([0, 1, 2].map((l) => intensity(l, 2))).toEqual([0, 2, 4])
137
+ expect([0, 1, 2, 3].map((l) => intensity(l, 3))).toEqual([0, 1, 3, 4])
138
+ })
139
+
140
+ it("describes each level's range for the legend", () => {
141
+ expect(legendLevels([1, 4, 8])).toEqual([
142
+ { level: 0, min: 0, max: 1 },
143
+ { level: 1, min: 1, max: 4 },
144
+ { level: 2, min: 4, max: 8 },
145
+ { level: 3, min: 8, max: null },
146
+ ])
147
+ })
148
+ })
149
+
150
+ describe("nextHeatmapDay", () => {
151
+ const first = new CalendarDate(2026, 10, 1)
152
+ const last = new CalendarDate(2026, 10, 31)
153
+ const day = new CalendarDate(2026, 10, 14)
154
+ const options = { dir: "ltr" as const, ctrlKey: false, column: 2, columns: 5, first, last }
155
+ const next = (key: string, overrides = {}) =>
156
+ nextHeatmapDay(key, day, { ...options, ...overrides })?.toString() ?? null
157
+
158
+ it("moves a week horizontally and a day vertically", () => {
159
+ expect(next("ArrowRight")).toBe("2026-10-21")
160
+ expect(next("ArrowLeft")).toBe("2026-10-07")
161
+ expect(next("ArrowDown")).toBe("2026-10-15")
162
+ expect(next("ArrowUp")).toBe("2026-10-13")
163
+ })
164
+
165
+ it("mirrors the horizontal arrows in RTL", () => {
166
+ expect(next("ArrowLeft", { dir: "rtl" })).toBe("2026-10-21")
167
+ expect(next("ArrowRight", { dir: "rtl" })).toBe("2026-10-07")
168
+ })
169
+
170
+ it("jumps along the row with Home/End, and to the range ends with Ctrl", () => {
171
+ // Home lands on Sep 30, padding outside the range, so it clamps to the first day.
172
+ expect(next("Home")).toBe("2026-10-01")
173
+ expect(next("End")).toBe("2026-10-28")
174
+ expect(next("Home", { ctrlKey: true })).toBe("2026-10-01")
175
+ expect(next("End", { ctrlKey: true })).toBe("2026-10-31")
176
+ })
177
+
178
+ it("pages a month and clamps to the range", () => {
179
+ expect(next("PageDown")).toBe("2026-10-31")
180
+ expect(next("PageUp")).toBe("2026-10-01")
181
+ })
182
+
183
+ it("ignores keys it doesn't handle", () => {
184
+ expect(next("a")).toBeNull()
185
+ })
186
+ })
@@ -0,0 +1,192 @@
1
+ import {
2
+ type CalendarDate,
3
+ endOfWeek,
4
+ fromDate,
5
+ startOfWeek,
6
+ toCalendarDate,
7
+ } from "@internationalized/date"
8
+ import type { FirstDayOfWeek } from "../schedule/schedule-types"
9
+
10
+ /**
11
+ * The calendar heatmap's layout, kept free of React so every edge (week start,
12
+ * a range starting mid-week, DST, time zones) is tested as plain data.
13
+ *
14
+ * All arithmetic is on `CalendarDate`, a zone-free wall-calendar day, so a
15
+ * 23- or 25-hour DST day is still exactly one day. `timeZone` is only read at
16
+ * the two crossings: bucketing the consumer's `Date` instants into days, and
17
+ * turning each day back into the `Date` handed to callbacks and formatters.
18
+ */
19
+
20
+ export type CalendarHeatmapDatum = { date: Date; value: number }
21
+
22
+ /** Lower bounds of levels 1–4, ascending. A value below the first is level 0. */
23
+ export type CalendarHeatmapThresholds =
24
+ | readonly [number]
25
+ | readonly [number, number]
26
+ | readonly [number, number, number]
27
+ | readonly [number, number, number, number]
28
+
29
+ export type HeatmapDay = {
30
+ /** Midnight of the day, in the heatmap's time zone. */
31
+ date: Date
32
+ /** `YYYY-MM-DD`: a stable key, and the cell's `data-date`. */
33
+ key: string
34
+ value: number
35
+ /** 0 for nothing, else 1–4 on the four-step ramp (see `intensity`). */
36
+ level: number
37
+ }
38
+
39
+ export type HeatmapLayout = {
40
+ /** One column per week, seven slots each. `null` pads the days outside the range. */
41
+ weeks: (HeatmapDay | null)[][]
42
+ /** The column each month label sits above. */
43
+ months: { column: number; date: Date }[]
44
+ /** The first week's seven days, one per row, for the weekday labels. */
45
+ weekdays: Date[]
46
+ /** The thresholds actually applied, after defaulting. */
47
+ thresholds: readonly number[]
48
+ first: CalendarDate
49
+ last: CalendarDate
50
+ }
51
+
52
+ /** A month label needs this many columns before the next one, or it is dropped. */
53
+ const MONTH_LABEL_SPAN = 3
54
+
55
+ export const toDay = (date: Date, timeZone: string): CalendarDate =>
56
+ toCalendarDate(fromDate(date, timeZone))
57
+
58
+ /** The year ending on `now`'s day: 365 or 366 days, today last. */
59
+ export function defaultRange(now: Date, timeZone: string) {
60
+ const last = toDay(now, timeZone)
61
+ return {
62
+ start: last.subtract({ years: 1 }).add({ days: 1 }).toDate(timeZone),
63
+ end: last.toDate(timeZone),
64
+ }
65
+ }
66
+
67
+ /**
68
+ * GitHub's split: the busiest day's value cut into quarters, so each level
69
+ * covers a quarter of the range. Duplicates collapse, so a sparse dataset
70
+ * (a maximum of 2) gets two levels rather than four that all mean "1 or 2".
71
+ * Counts are whole numbers, so the bounds are too: data on another scale
72
+ * (hours, a score) passes its own `thresholds`.
73
+ */
74
+ export function defaultThresholds(max: number): readonly number[] {
75
+ return [...new Set([0, 1, 2, 3].map((quarter) => Math.floor((max * quarter) / 4) + 1))]
76
+ }
77
+
78
+ /** How many of `thresholds` the value reaches: 0 below the first. */
79
+ export const levelOf = (value: number, thresholds: readonly number[]) =>
80
+ thresholds.filter((bound) => value >= bound).length
81
+
82
+ /**
83
+ * Which of the four color steps a level paints with. With fewer than four
84
+ * levels they spread across the ramp, ending on the strongest, so the
85
+ * busiest days always read as the full color.
86
+ */
87
+ export const intensity = (level: number, levels: number) =>
88
+ level === 0 ? 0 : Math.round((level * 4) / levels)
89
+
90
+ /** Each level's value range, for the legend. `max` is `null` on the open top level. */
91
+ export function legendLevels(thresholds: readonly number[]) {
92
+ return [0, ...thresholds].map((min, level) => {
93
+ const next = thresholds[level]
94
+ return { level, min, max: next === undefined ? null : next }
95
+ })
96
+ }
97
+
98
+ export function buildHeatmap(options: {
99
+ data: readonly CalendarHeatmapDatum[]
100
+ start: Date
101
+ end: Date
102
+ timeZone: string
103
+ locale: string
104
+ startOfWeek?: FirstDayOfWeek
105
+ thresholds?: readonly number[]
106
+ }): HeatmapLayout {
107
+ const { data, timeZone, locale } = options
108
+ const first = toDay(options.start, timeZone)
109
+ const last = toDay(options.end, timeZone)
110
+
111
+ // Same-day entries add up, so a raw event list works as well as daily totals.
112
+ const totals = data.reduce((sums, { date, value }) => {
113
+ const key = toDay(date, timeZone).toString()
114
+ return sums.set(key, (sums.get(key) ?? 0) + value)
115
+ }, new Map<string, number>())
116
+
117
+ const inRange = [...totals].filter(([key]) => key >= first.toString() && key <= last.toString())
118
+ const max = Math.max(0, ...inRange.map(([, value]) => value))
119
+ const thresholds = options.thresholds ?? defaultThresholds(max)
120
+
121
+ const gridStart = startOfWeek(first, locale, options.startOfWeek)
122
+ const gridEnd = endOfWeek(last, locale, options.startOfWeek)
123
+ const weekCount = (gridEnd.compare(gridStart) + 1) / 7
124
+
125
+ const weeks = Array.from({ length: weekCount }, (_, column) =>
126
+ Array.from({ length: 7 }, (_, row) => {
127
+ const day = gridStart.add({ days: column * 7 + row })
128
+ if (day.compare(first) < 0 || day.compare(last) > 0) return null
129
+ const key = day.toString()
130
+ const value = totals.get(key) ?? 0
131
+ return { date: day.toDate(timeZone), key, value, level: levelOf(value, thresholds) }
132
+ }),
133
+ )
134
+
135
+ // A month's label sits above the first column that opens in it, the way a
136
+ // wall calendar reads. The earlier of two labels too close together is the
137
+ // one dropped: that is the range's partial first month, whose name would
138
+ // collide with the next.
139
+ const opening = weeks.map((week) => week.find((day) => day !== null) ?? null)
140
+ const starts = opening.flatMap((day, column) =>
141
+ day && (column === 0 || day.key.slice(0, 7) !== opening[column - 1]?.key.slice(0, 7))
142
+ ? [{ column, date: day.date }]
143
+ : [],
144
+ )
145
+ const months = starts.filter(
146
+ (label, index) => (starts[index + 1]?.column ?? Infinity) - label.column >= MONTH_LABEL_SPAN,
147
+ )
148
+
149
+ const weekdays = Array.from({ length: 7 }, (_, row) =>
150
+ gridStart.add({ days: row }).toDate(timeZone),
151
+ )
152
+
153
+ return { weeks, months, weekdays, thresholds, first, last }
154
+ }
155
+
156
+ /**
157
+ * Where an arrow key sends focus. Columns are weeks and rows are weekdays, so
158
+ * the horizontal arrows move a week and the vertical ones a day. Every target
159
+ * is clamped to the range, so focus never lands on a padding slot. `null` for
160
+ * a key the grid doesn't handle.
161
+ */
162
+ export function nextHeatmapDay(
163
+ key: string,
164
+ day: CalendarDate,
165
+ options: {
166
+ dir: "ltr" | "rtl"
167
+ ctrlKey: boolean
168
+ /** The day's week index (its column). */
169
+ column: number
170
+ columns: number
171
+ first: CalendarDate
172
+ last: CalendarDate
173
+ },
174
+ ): CalendarDate | null {
175
+ const { dir, ctrlKey, column, columns, first, last } = options
176
+ const clamp = (target: CalendarDate) =>
177
+ target.compare(first) < 0 ? first : target.compare(last) > 0 ? last : target
178
+ const forward = dir === "rtl" ? "ArrowLeft" : "ArrowRight"
179
+ const backward = dir === "rtl" ? "ArrowRight" : "ArrowLeft"
180
+ const step: Record<string, () => CalendarDate> = {
181
+ [forward]: () => day.add({ weeks: 1 }),
182
+ [backward]: () => day.subtract({ weeks: 1 }),
183
+ ArrowDown: () => day.add({ days: 1 }),
184
+ ArrowUp: () => day.subtract({ days: 1 }),
185
+ Home: () => (ctrlKey ? first : day.subtract({ weeks: column })),
186
+ End: () => (ctrlKey ? last : day.add({ weeks: columns - 1 - column })),
187
+ PageDown: () => day.add({ months: 1 }),
188
+ PageUp: () => day.subtract({ months: 1 }),
189
+ }
190
+ const target = step[key]?.()
191
+ return target ? clamp(target) : null
192
+ }
@@ -0,0 +1,180 @@
1
+ import { act, fireEvent, render, screen, within } from "@testing-library/react"
2
+ import { renderToString } from "react-dom/server"
3
+ import { describe, expect, it, vi } from "vitest"
4
+ import { IntlProvider } from "../../lib/intl"
5
+ import { CalendarHeatmap, type CalendarHeatmapProps } from "./calendar-heatmap"
6
+
7
+ const utc = (iso: string) => new Date(`${iso}T00:00:00Z`)
8
+ // 2026-10-01 is a Thursday; en-US weeks start on Sunday.
9
+ const range = { start: utc("2026-10-01"), end: utc("2026-10-31") }
10
+
11
+ const setup = (props: Partial<CalendarHeatmapProps> = {}) =>
12
+ render(<CalendarHeatmap data={[]} range={range} timeZone="UTC" {...props} />)
13
+
14
+ const cell = (key: string) => {
15
+ const found = document.querySelector<HTMLElement>(`[role='gridcell'][data-date='${key}']`)
16
+ if (!found) throw new Error(`no cell for ${key}`)
17
+ return found
18
+ }
19
+
20
+ describe("CalendarHeatmap", () => {
21
+ it("renders a named grid: seven weekday rows, one cell per day in range", () => {
22
+ setup()
23
+ const grid = screen.getByRole("grid", { name: "Activity" })
24
+ const rows = within(grid).getAllByRole("row")
25
+ expect(rows).toHaveLength(7)
26
+ expect(rows.map((row) => within(row).getByRole("rowheader").textContent)).toEqual([
27
+ "Sunday",
28
+ "Monday",
29
+ "Tuesday",
30
+ "Wednesday",
31
+ "Thursday",
32
+ "Friday",
33
+ "Saturday",
34
+ ])
35
+ expect(grid.querySelectorAll("[data-date]")).toHaveLength(31)
36
+ })
37
+
38
+ it("labels every other weekday outside the scroller, so the labels stay in view", () => {
39
+ const { container } = setup()
40
+ const scroller = screen.getByRole("grid").parentElement
41
+ const labels = container.querySelector("[aria-hidden='true']")
42
+ expect(scroller?.contains(labels ?? null)).toBe(false)
43
+ expect([...(labels?.children ?? [])].map((label) => label.textContent)).toEqual([
44
+ "\u00a0",
45
+ "",
46
+ "Mon",
47
+ "",
48
+ "Wed",
49
+ "",
50
+ "Fri",
51
+ "",
52
+ ])
53
+ })
54
+
55
+ it("names every day in full, summing same-day entries", () => {
56
+ setup({
57
+ data: [
58
+ { date: utc("2026-10-05"), value: 2 },
59
+ { date: new Date("2026-10-05T18:00:00Z"), value: 1 },
60
+ { date: utc("2026-10-06"), value: 1 },
61
+ ],
62
+ })
63
+ expect(cell("2026-10-05").textContent).toBe("3 activities on Monday, October 5, 2026")
64
+ expect(cell("2026-10-06").textContent).toBe("1 activity on Tuesday, October 6, 2026")
65
+ expect(cell("2026-10-07").textContent).toBe("No activity on Wednesday, October 7, 2026")
66
+ })
67
+
68
+ it("levels values against the thresholds", () => {
69
+ setup({
70
+ thresholds: [1, 5, 10, 20],
71
+ data: [0, 1, 5, 12, 40].map((value, i) => ({ date: utc(`2026-10-1${i}`), value })),
72
+ })
73
+ expect(
74
+ ["10", "11", "12", "13", "14"].map((d) => cell(`2026-10-${d}`).getAttribute("data-level")),
75
+ ).toEqual(["0", "1", "2", "3", "4"])
76
+ })
77
+
78
+ it("formats dates, weekdays and numbers in the locale, and translates the rest", () => {
79
+ render(
80
+ <IntlProvider locale="fr-FR" timeZone="UTC">
81
+ <CalendarHeatmap
82
+ data={[{ date: utc("2026-10-05"), value: 1200 }]}
83
+ range={range}
84
+ translations={{
85
+ label: "Activité",
86
+ day: ({ formattedValue, formattedDate }) => `${formattedValue} le ${formattedDate}`,
87
+ }}
88
+ />
89
+ </IntlProvider>,
90
+ )
91
+ expect(screen.getByRole("grid", { name: "Activité" })).toBeTruthy()
92
+ // French weeks start on Monday.
93
+ expect(screen.getAllByRole("rowheader")[0]?.textContent).toBe("lundi")
94
+ expect(cell("2026-10-05").textContent?.normalize("NFKC")).toBe("1 200 le lundi 5 octobre 2026")
95
+ })
96
+
97
+ it("has a single tab stop, on the latest day by default", () => {
98
+ setup()
99
+ const stops = document.querySelectorAll("[role='gridcell'][tabindex='0']")
100
+ expect(stops).toHaveLength(1)
101
+ expect(stops[0]?.getAttribute("data-date")).toBe("2026-10-31")
102
+ })
103
+
104
+ it("moves focus with the arrows: a week across, a day down", () => {
105
+ setup()
106
+ act(() => cell("2026-10-14").focus())
107
+ fireEvent.keyDown(cell("2026-10-14"), { key: "ArrowRight" })
108
+ expect(document.activeElement).toBe(cell("2026-10-21"))
109
+ fireEvent.keyDown(cell("2026-10-21"), { key: "ArrowDown" })
110
+ expect(document.activeElement).toBe(cell("2026-10-22"))
111
+ // The stop follows focus.
112
+ expect(cell("2026-10-22").tabIndex).toBe(0)
113
+ expect(cell("2026-10-31").tabIndex).toBe(-1)
114
+ })
115
+
116
+ it("mirrors the horizontal arrows in RTL", () => {
117
+ render(
118
+ <IntlProvider locale="ar" timeZone="UTC">
119
+ <CalendarHeatmap data={[]} range={range} />
120
+ </IntlProvider>,
121
+ )
122
+ act(() => cell("2026-10-14").focus())
123
+ fireEvent.keyDown(cell("2026-10-14"), { key: "ArrowLeft" })
124
+ expect(document.activeElement).toBe(cell("2026-10-21"))
125
+ })
126
+
127
+ it("clamps to the range with Ctrl+Home/End", () => {
128
+ setup()
129
+ act(() => cell("2026-10-14").focus())
130
+ fireEvent.keyDown(cell("2026-10-14"), { key: "Home", ctrlKey: true })
131
+ expect(document.activeElement).toBe(cell("2026-10-01"))
132
+ fireEvent.keyDown(cell("2026-10-01"), { key: "End", ctrlKey: true })
133
+ expect(document.activeElement).toBe(cell("2026-10-31"))
134
+ })
135
+
136
+ it("activates a day by click, Enter or Space when onDayClick is set", () => {
137
+ const onDayClick = vi.fn()
138
+ setup({ onDayClick, data: [{ date: utc("2026-10-05"), value: 4 }] })
139
+ fireEvent.click(cell("2026-10-05"))
140
+ fireEvent.keyDown(cell("2026-10-05"), { key: "Enter" })
141
+ fireEvent.keyDown(cell("2026-10-05"), { key: " " })
142
+ expect(onDayClick).toHaveBeenCalledTimes(3)
143
+ expect(onDayClick).toHaveBeenCalledWith(utc("2026-10-05"), 4)
144
+ })
145
+
146
+ it("never lets the shared tooltip describe a cell that already names itself", () => {
147
+ setup()
148
+ act(() => cell("2026-10-14").focus())
149
+ expect(cell("2026-10-14").hasAttribute("aria-describedby")).toBe(false)
150
+ })
151
+
152
+ it("shows the legend with each level's range", () => {
153
+ setup({ thresholds: [1, 4, 8] })
154
+ expect(screen.getByText("Less")).toBeTruthy()
155
+ expect(screen.getByText("More")).toBeTruthy()
156
+ expect(["0", "1–3", "4–7", "8+"].map((text) => screen.getByText(text))).toHaveLength(4)
157
+ })
158
+
159
+ it("defaults to the year ending today", () => {
160
+ vi.useFakeTimers({ now: new Date("2026-10-26T12:00:00Z"), toFake: ["Date"] })
161
+ try {
162
+ render(<CalendarHeatmap data={[]} timeZone="UTC" />)
163
+ // The DOM runs row by row, so sort the days back into calendar order.
164
+ const days = [...document.querySelectorAll<HTMLElement>("[data-date]")]
165
+ .map((day) => day.getAttribute("data-date"))
166
+ .sort()
167
+ expect(days[0]).toBe("2025-10-27")
168
+ expect(days.at(-1)).toBe("2026-10-26")
169
+ expect(days).toHaveLength(365)
170
+ } finally {
171
+ vi.useRealTimers()
172
+ }
173
+ })
174
+
175
+ it("renders an empty, busy grid on the server when the range defaults to today", () => {
176
+ const html = renderToString(<CalendarHeatmap data={[]} timeZone="UTC" />)
177
+ expect(html).toContain('aria-busy="true"')
178
+ expect(html).not.toContain("data-date")
179
+ })
180
+ })