@charcuterie/ui 4.27.3 → 4.28.1

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 (120) hide show
  1. package/dist/Accordion/AccordionSection.d.ts.map +1 -1
  2. package/dist/Accordion/AccordionSection.js +43 -4
  3. package/dist/Accordion/AccordionSection.js.map +1 -1
  4. package/dist/Combobox/Combobox.d.ts.map +1 -1
  5. package/dist/Combobox/Combobox.js +3 -3
  6. package/dist/Combobox/Combobox.js.map +1 -1
  7. package/dist/DatePicker/DatePicker.d.ts.map +1 -1
  8. package/dist/DatePicker/DatePicker.js +3 -3
  9. package/dist/DatePicker/DatePicker.js.map +1 -1
  10. package/dist/Dialog/Dialog.d.ts +7 -1
  11. package/dist/Dialog/Dialog.d.ts.map +1 -1
  12. package/dist/Dialog/Dialog.js +2 -2
  13. package/dist/Dialog/Dialog.js.map +1 -1
  14. package/dist/GroupedList/GroupedList.d.ts +9 -2
  15. package/dist/GroupedList/GroupedList.d.ts.map +1 -1
  16. package/dist/GroupedList/GroupedList.js +39 -5
  17. package/dist/GroupedList/GroupedList.js.map +1 -1
  18. package/dist/GroupedList/GroupedListRow.d.ts +4 -1
  19. package/dist/GroupedList/GroupedListRow.d.ts.map +1 -1
  20. package/dist/GroupedList/GroupedListRow.js +3 -3
  21. package/dist/GroupedList/GroupedListRow.js.map +1 -1
  22. package/dist/GroupedList/GroupedListRows.d.ts +16 -0
  23. package/dist/GroupedList/GroupedListRows.d.ts.map +1 -0
  24. package/dist/GroupedList/GroupedListRows.js +17 -0
  25. package/dist/GroupedList/GroupedListRows.js.map +1 -0
  26. package/dist/Listbox/Listbox.d.ts.map +1 -1
  27. package/dist/Listbox/Listbox.js +6 -4
  28. package/dist/Listbox/Listbox.js.map +1 -1
  29. package/dist/Menu/Menu.d.ts.map +1 -1
  30. package/dist/Menu/Menu.js +6 -4
  31. package/dist/Menu/Menu.js.map +1 -1
  32. package/dist/Modal/Modal.d.ts +7 -1
  33. package/dist/Modal/Modal.d.ts.map +1 -1
  34. package/dist/Modal/Modal.js +1 -1
  35. package/dist/Modal/Modal.js.map +1 -1
  36. package/dist/Motion/useLastPresentValue.d.ts +21 -0
  37. package/dist/Motion/useLastPresentValue.d.ts.map +1 -0
  38. package/dist/Motion/useLastPresentValue.js +30 -0
  39. package/dist/Motion/useLastPresentValue.js.map +1 -0
  40. package/dist/Motion/useListMotion.d.ts +111 -0
  41. package/dist/Motion/useListMotion.d.ts.map +1 -0
  42. package/dist/Motion/useListMotion.js +358 -0
  43. package/dist/Motion/useListMotion.js.map +1 -0
  44. package/dist/Motion/usePresence.d.ts +81 -0
  45. package/dist/Motion/usePresence.d.ts.map +1 -0
  46. package/dist/Motion/usePresence.js +131 -0
  47. package/dist/Motion/usePresence.js.map +1 -0
  48. package/dist/Motion/useValueChangeMotion.d.ts +52 -0
  49. package/dist/Motion/useValueChangeMotion.d.ts.map +1 -0
  50. package/dist/Motion/useValueChangeMotion.js +87 -0
  51. package/dist/Motion/useValueChangeMotion.js.map +1 -0
  52. package/dist/Overlay/OverlayPanel.d.ts +18 -1
  53. package/dist/Overlay/OverlayPanel.d.ts.map +1 -1
  54. package/dist/Overlay/OverlayPanel.js +83 -11
  55. package/dist/Overlay/OverlayPanel.js.map +1 -1
  56. package/dist/Overlay/SharedBackdrop.d.ts +3 -0
  57. package/dist/Overlay/SharedBackdrop.d.ts.map +1 -1
  58. package/dist/Overlay/SharedBackdrop.js +8 -2
  59. package/dist/Overlay/SharedBackdrop.js.map +1 -1
  60. package/dist/Overlay/focusHistory.d.ts +16 -0
  61. package/dist/Overlay/focusHistory.d.ts.map +1 -0
  62. package/dist/Overlay/focusHistory.js +110 -0
  63. package/dist/Overlay/focusHistory.js.map +1 -0
  64. package/dist/Overlay/useAnchoredOverlay.d.ts +17 -3
  65. package/dist/Overlay/useAnchoredOverlay.d.ts.map +1 -1
  66. package/dist/Overlay/useAnchoredOverlay.js +23 -5
  67. package/dist/Overlay/useAnchoredOverlay.js.map +1 -1
  68. package/dist/Popover/Popover.d.ts.map +1 -1
  69. package/dist/Popover/Popover.js +4 -2
  70. package/dist/Popover/Popover.js.map +1 -1
  71. package/dist/ReorderList/ReorderList.d.ts +6 -0
  72. package/dist/ReorderList/ReorderList.d.ts.map +1 -1
  73. package/dist/ReorderList/ReorderList.js +23 -6
  74. package/dist/ReorderList/ReorderList.js.map +1 -1
  75. package/dist/TableViewport/TableViewport.d.ts.map +1 -1
  76. package/dist/TableViewport/TableViewport.js +9 -1
  77. package/dist/TableViewport/TableViewport.js.map +1 -1
  78. package/dist/Tooltip/Tooltip.d.ts.map +1 -1
  79. package/dist/Tooltip/Tooltip.js +16 -13
  80. package/dist/Tooltip/Tooltip.js.map +1 -1
  81. package/dist/index.d.ts +22 -0
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +12 -0
  84. package/dist/index.js.map +1 -1
  85. package/dist/styles.css +191 -1
  86. package/package.json +6 -6
  87. package/src/Accordion/AccordionSection.tsx +63 -4
  88. package/src/Combobox/Combobox.tsx +8 -2
  89. package/src/DatePicker/DatePicker.tsx +7 -1
  90. package/src/Dialog/Dialog.tsx +8 -0
  91. package/src/GroupedList/GroupedList.mdx +3 -2
  92. package/src/GroupedList/GroupedList.test.tsx +283 -0
  93. package/src/GroupedList/GroupedList.tsx +88 -44
  94. package/src/GroupedList/GroupedListRow.tsx +8 -0
  95. package/src/GroupedList/GroupedListRows.tsx +51 -0
  96. package/src/Listbox/Listbox.tsx +9 -1
  97. package/src/Menu/Menu.tsx +9 -1
  98. package/src/Modal/Modal.tsx +8 -0
  99. package/src/Motion/useLastPresentValue.test.tsx +66 -0
  100. package/src/Motion/useLastPresentValue.ts +38 -0
  101. package/src/Motion/useListMotion.test.tsx +527 -0
  102. package/src/Motion/useListMotion.ts +674 -0
  103. package/src/Motion/usePresence.test.tsx +223 -0
  104. package/src/Motion/usePresence.ts +252 -0
  105. package/src/Motion/useValueChangeMotion.test.tsx +131 -0
  106. package/src/Motion/useValueChangeMotion.ts +110 -0
  107. package/src/Overlay/OverlayPanel.server.test.ts +30 -0
  108. package/src/Overlay/OverlayPanel.tsx +146 -14
  109. package/src/Overlay/SharedBackdrop.tsx +17 -2
  110. package/src/Overlay/focusHistory.ts +152 -0
  111. package/src/Overlay/overlayReturnFocus.storyHelpers.tsx +242 -0
  112. package/src/Overlay/overlayReturnFocus.test.tsx +255 -0
  113. package/src/Overlay/useAnchoredOverlay.ts +56 -4
  114. package/src/Popover/Popover.tsx +9 -1
  115. package/src/ReorderList/ReorderList.test.tsx +76 -0
  116. package/src/ReorderList/ReorderList.tsx +86 -48
  117. package/src/TableViewport/TableViewport.tsx +4 -0
  118. package/src/Tooltip/Tooltip.tsx +32 -4
  119. package/src/index.ts +30 -0
  120. package/src/styles.css +191 -1
@@ -0,0 +1,223 @@
1
+ import { composeStories } from "@storybook/react"
2
+ import { expect, userEvent, waitFor } from "storybook/test"
3
+ import { afterEach, beforeEach, test } from "vitest"
4
+
5
+ import * as accordionStories from "../Accordion/Accordion.stories.tsx"
6
+ import * as menuStories from "../Menu/Menu.stories.tsx"
7
+ import * as modalStories from "../Modal/Modal.stories.tsx"
8
+ import { mountStory } from "../mountStory.testHelpers.ts"
9
+ import { getAnimationLengthMs } from "./usePresence.ts"
10
+
11
+ const { Playground: ModalPlayground } =
12
+ composeStories(modalStories)
13
+
14
+ const { Playground: MenuPlayground } =
15
+ composeStories(menuStories)
16
+
17
+ const { Playground: AccordionPlayground } = composeStories(
18
+ accordionStories,
19
+ )
20
+
21
+ /**
22
+ * The suite freezes motion for every test (`FREEZE_MOTION_CSS`), which
23
+ * is what keeps every other overlay test synchronous. These tests are
24
+ * about the motion itself, so they lift the freeze for their own
25
+ * duration and put it back after.
26
+ */
27
+ const FREEZE_ID = "charcuterie-freeze-motion"
28
+
29
+ let frozenStyle: HTMLElement | null = null
30
+
31
+ beforeEach(() => {
32
+ frozenStyle = document.getElementById(FREEZE_ID)
33
+
34
+ frozenStyle?.remove()
35
+ })
36
+
37
+ afterEach(() => {
38
+ if (frozenStyle !== null) {
39
+ document.head.append(frozenStyle)
40
+ }
41
+ })
42
+
43
+ const SLOW_EXIT = "1500ms"
44
+
45
+ const MOTION_TIMEOUT = { timeout: 5_000 }
46
+
47
+ test("the animation length is the longest delay plus duration, and zero with no animation", () => {
48
+ const element = document.createElement("div")
49
+
50
+ document.body.append(element)
51
+
52
+ expect(getAnimationLengthMs(element)).toBe(0)
53
+
54
+ element.style.animation =
55
+ "charcuterie-fade-out 120ms linear 30ms, charcuterie-overlay-out 0.2s linear"
56
+
57
+ expect(getAnimationLengthMs(element)).toBe(200)
58
+
59
+ // A zero duration is no animation, whatever its name — that is the
60
+ // frozen suites' rendering, and it must unmount at once.
61
+ element.style.animation = "charcuterie-fade-out 0s linear"
62
+
63
+ expect(getAnimationLengthMs(element)).toBe(0)
64
+ })
65
+
66
+ test("a closing modal stays in the page, closed to everything but the eye, until its exit ends", async () => {
67
+ const { body, canvas } = await mountStory(ModalPlayground)
68
+
69
+ const trigger = canvas.getByRole("button", {
70
+ name: "Open the base modal",
71
+ })
72
+
73
+ await userEvent.click(trigger)
74
+
75
+ const modal = body.getByRole("dialog")
76
+
77
+ expect(modal).toHaveClass("charcuterie-overlay-enter")
78
+
79
+ // Long enough that a loaded host cannot finish the exit between two
80
+ // lines of this test. The inline longhand beats the class's.
81
+ modal.style.animationDuration = SLOW_EXIT
82
+
83
+ await userEvent.keyboard("{Escape}")
84
+
85
+ // Already gone to a role query, the keyboard, and the pointer…
86
+ expect(body.queryByRole("dialog")).toBeNull()
87
+ expect(modal).toHaveAttribute("inert")
88
+ expect(modal).toHaveClass("charcuterie-overlay-exit")
89
+
90
+ // …and focus is back on the trigger without waiting for the motion.
91
+ await waitFor(() => {
92
+ expect(trigger).toHaveFocus()
93
+ })
94
+
95
+ // But still painted, until the exit animation finishes.
96
+ expect(modal.isConnected).toBe(true)
97
+
98
+ await waitFor(() => {
99
+ expect(modal.isConnected).toBe(false)
100
+ }, MOTION_TIMEOUT)
101
+ })
102
+
103
+ test("a modal re-opened during its exit stays open", async () => {
104
+ const { body, canvas } = await mountStory(ModalPlayground)
105
+
106
+ const trigger = canvas.getByRole("button", {
107
+ name: "Open the base modal",
108
+ })
109
+
110
+ await userEvent.click(trigger)
111
+
112
+ const modal = body.getByRole("dialog")
113
+
114
+ modal.style.animationDuration = SLOW_EXIT
115
+
116
+ await userEvent.keyboard("{Escape}")
117
+
118
+ expect(modal).toHaveClass("charcuterie-overlay-exit")
119
+
120
+ await userEvent.click(trigger)
121
+
122
+ // The same element, back to its enter class, and still here well
123
+ // after the abandoned exit would have removed it.
124
+ await waitFor(() => {
125
+ expect(body.getByRole("dialog")).toBe(modal)
126
+ })
127
+
128
+ expect(modal).toHaveClass("charcuterie-overlay-enter")
129
+
130
+ await new Promise((resolve) => {
131
+ globalThis.setTimeout(resolve, 400)
132
+ })
133
+
134
+ expect(modal.isConnected).toBe(true)
135
+
136
+ // Closed again, and gone, so its focus manager has let go of the
137
+ // page before the next test mounts into it.
138
+ modal.style.animationDuration = ""
139
+
140
+ await userEvent.keyboard("{Escape}")
141
+
142
+ await waitFor(() => {
143
+ expect(modal.isConnected).toBe(false)
144
+ }, MOTION_TIMEOUT)
145
+ })
146
+
147
+ test("an anchored menu grows out of its trigger and leaves with motion", async () => {
148
+ const { body, canvas } = await mountStory(MenuPlayground)
149
+
150
+ await userEvent.click(canvas.getAllByRole("button")[0])
151
+
152
+ const menu = await waitFor(() => body.getByRole("menu"))
153
+
154
+ expect(menu).toHaveClass("charcuterie-overlay-enter")
155
+ expect(menu.style.transformOrigin).not.toBe("")
156
+
157
+ menu.style.animationDuration = SLOW_EXIT
158
+
159
+ await userEvent.keyboard("{Escape}")
160
+
161
+ expect(body.queryByRole("menu")).toBeNull()
162
+ expect(menu).toHaveClass("charcuterie-overlay-exit")
163
+
164
+ await waitFor(() => {
165
+ expect(menu.isConnected).toBe(false)
166
+ }, MOTION_TIMEOUT)
167
+ })
168
+
169
+ test("an accordion section stays shown while it collapses, then hides", async () => {
170
+ const { canvas } = await mountStory(AccordionPlayground)
171
+
172
+ const [firstHeader] = canvas.getAllByRole("button", {
173
+ expanded: false,
174
+ })
175
+
176
+ await userEvent.click(firstHeader)
177
+
178
+ const panel = document.getElementById(
179
+ firstHeader.getAttribute("aria-controls") ?? "",
180
+ )
181
+
182
+ expect(panel).not.toBeNull()
183
+ expect(panel).not.toHaveAttribute("hidden")
184
+
185
+ panel?.style.setProperty("animation-duration", SLOW_EXIT)
186
+
187
+ await userEvent.click(firstHeader)
188
+
189
+ // `interpolate-size` is Chromium's, which is what this suite runs.
190
+ expect(panel).toHaveClass("charcuterie-disclosure-exit")
191
+ expect(panel).not.toHaveAttribute("hidden")
192
+ expect(panel).toHaveAttribute("inert")
193
+
194
+ await waitFor(() => {
195
+ expect(panel).toHaveAttribute("hidden")
196
+ }, MOTION_TIMEOUT)
197
+ })
198
+
199
+ test("an accordion section drops its open class when it has opened", async () => {
200
+ const { canvas } = await mountStory(AccordionPlayground)
201
+
202
+ const [firstHeader] = canvas.getAllByRole("button", {
203
+ expanded: false,
204
+ })
205
+
206
+ await userEvent.click(firstHeader)
207
+
208
+ const panel = document.getElementById(
209
+ firstHeader.getAttribute("aria-controls") ?? "",
210
+ ) as HTMLElement
211
+
212
+ expect(panel).toHaveClass("charcuterie-disclosure-enter")
213
+
214
+ // Off once it has opened, so showing an ancestor again does not
215
+ // replay it, and its `overflow: clip` no longer clips the content.
216
+ await waitFor(() => {
217
+ expect(panel).not.toHaveClass(
218
+ "charcuterie-disclosure-enter",
219
+ )
220
+ }, MOTION_TIMEOUT)
221
+
222
+ expect(panel).not.toHaveAttribute("hidden")
223
+ })
@@ -0,0 +1,252 @@
1
+ import type { RefObject } from "react"
2
+ import { useLayoutEffect, useRef, useState } from "react"
3
+
4
+ /**
5
+ * Keeps an element in the page until its exit animation has run, so
6
+ * a closing overlay leaves the screen with motion instead of
7
+ * vanishing in one frame.
8
+ *
9
+ * ### Why the length comes from the computed style
10
+ *
11
+ * The exit's length is **read from the element**, never passed in.
12
+ * The duration is a token (`--duration-fast`), and three different
13
+ * renderings set it to three different things: the designed motion,
14
+ * `prefers-reduced-motion` (where `styles.css` sets `animation: none`),
15
+ * and the automated suites' `FREEZE_MOTION_CSS` (`0s`). A number
16
+ * written here would hold a closed panel in the page for that long
17
+ * under all three, which is a dead overlay the user cannot see but a
18
+ * test still finds. Reading `getComputedStyle` in a layout effect
19
+ * means a motionless exit finishes **in the same commit** — before
20
+ * paint, and inside the test's `act()` — so nothing that asserts "it
21
+ * closed" has to learn to wait.
22
+ *
23
+ * A DOM with no CSS engine (jsdom, happy-dom) reports an empty
24
+ * `animation-name`, which reads as no animation and unmounts at once
25
+ * for the same reason.
26
+ *
27
+ * ### What "exiting" must mean to the caller
28
+ *
29
+ * While `isExiting` is true the element is still in the page but is
30
+ * **closed** in every sense except paint. The caller makes it `inert`
31
+ * and `aria-hidden`, and the exit class sets `pointer-events: none`,
32
+ * so a role query, the keyboard, and the pointer all behave as though
33
+ * it has gone. Only the eye sees it leave.
34
+ *
35
+ * ### Re-opening mid-exit
36
+ *
37
+ * Re-opening during the exit simply swaps the exit class back for the
38
+ * enter class. Changing `animation-name` restarts the animation, and
39
+ * the listener for the abandoned exit is removed by the effect's
40
+ * cleanup, so it can never unmount the re-opened element.
41
+ */
42
+ export type UsePresenceResult<
43
+ Element extends HTMLElement = HTMLElement,
44
+ > = {
45
+ /** Mounted, but closed: make it `inert` and give it the exit class. */
46
+ isExiting: boolean
47
+ /** Whether to render the element at all. */
48
+ isMounted: boolean
49
+ /** Attach to the element whose exit animation ends the presence. */
50
+ presenceRef: RefObject<Element | null>
51
+ }
52
+
53
+ /**
54
+ * If `animationend` never arrives — the tab is hidden, or a consumer
55
+ * class replaced the animation with one that never ends — the
56
+ * element is removed anyway. This is a safety margin past the
57
+ * element's own computed length, not a design duration.
58
+ */
59
+ const EXIT_SAFETY_MARGIN_MS = 50
60
+
61
+ const toMilliseconds = (value: string): number => {
62
+ const trimmed = value.trim()
63
+
64
+ const amount = Number.parseFloat(trimmed)
65
+
66
+ if (Number.isNaN(amount)) {
67
+ return 0
68
+ }
69
+
70
+ return trimmed.endsWith("ms") ? amount : amount * 1000
71
+ }
72
+
73
+ /**
74
+ * The longest `delay + duration` across every animation on the
75
+ * element, or `0` when it has none. CSS repeats the shorter of the two
76
+ * lists to match the longer, so the delays are indexed the same way.
77
+ */
78
+ export const getAnimationLengthMs = (
79
+ element: Element,
80
+ ): number => {
81
+ const style = globalThis.getComputedStyle(element)
82
+
83
+ const names = style.animationName.split(",")
84
+
85
+ const durations = style.animationDuration.split(",")
86
+
87
+ const delays = style.animationDelay.split(",")
88
+
89
+ return names.reduce((longest, name, index) => {
90
+ if (name.trim() === "none" || name.trim() === "") {
91
+ return longest
92
+ }
93
+
94
+ const duration = toMilliseconds(
95
+ durations[index % durations.length] ?? "0s",
96
+ )
97
+
98
+ const delay = toMilliseconds(
99
+ delays[index % delays.length] ?? "0s",
100
+ )
101
+
102
+ return duration === 0
103
+ ? longest
104
+ : Math.max(longest, duration + Math.max(delay, 0))
105
+ }, 0)
106
+ }
107
+
108
+ /**
109
+ * The longest transition on `element`, delay included, in
110
+ * milliseconds. Zero under reduced motion, in the frozen suites, and
111
+ * in a DOM with no CSS engine — the same three cases as
112
+ * `getAnimationLengthMs`.
113
+ */
114
+ export const getTransitionLengthMs = (
115
+ element: Element,
116
+ ): number => {
117
+ const style = globalThis.getComputedStyle(element)
118
+
119
+ const durations = (style.transitionDuration ?? "").split(
120
+ ",",
121
+ )
122
+
123
+ const delays = (style.transitionDelay ?? "").split(",")
124
+
125
+ return durations.reduce((longest, value, index) => {
126
+ const duration = toMilliseconds(value)
127
+
128
+ const delay = toMilliseconds(
129
+ delays[index % delays.length] ?? "0s",
130
+ )
131
+
132
+ return duration === 0
133
+ ? longest
134
+ : Math.max(longest, duration + Math.max(delay, 0))
135
+ }, 0)
136
+ }
137
+
138
+ export const usePresence = <
139
+ Element extends HTMLElement = HTMLElement,
140
+ >(
141
+ isVisible: boolean,
142
+ ): UsePresenceResult<Element> => {
143
+ // Whether the element is still on screen. It lags `isVisible` only
144
+ // on the way out, by exactly the length of the exit animation.
145
+ const [isShown, setIsShown] = useState(isVisible)
146
+
147
+ const presenceRef = useRef<Element | null>(null)
148
+
149
+ const isExiting = !isVisible && isShown
150
+
151
+ useLayoutEffect(() => {
152
+ if (isVisible) {
153
+ setIsShown(true)
154
+ }
155
+ }, [isVisible])
156
+
157
+ useLayoutEffect(() => {
158
+ if (!isExiting) {
159
+ return
160
+ }
161
+
162
+ const element = presenceRef.current
163
+
164
+ const lengthMs =
165
+ element === null ? 0 : getAnimationLengthMs(element)
166
+
167
+ if (element === null || lengthMs === 0) {
168
+ setIsShown(false)
169
+
170
+ return
171
+ }
172
+
173
+ const finish = () => {
174
+ setIsShown(false)
175
+ }
176
+
177
+ const onAnimationEnd = (event: AnimationEvent) => {
178
+ // A child's own animation (a spinner inside a dialog) bubbles
179
+ // here too, and must not end the parent's exit.
180
+ if (event.target === element) {
181
+ finish()
182
+ }
183
+ }
184
+
185
+ element.addEventListener("animationend", onAnimationEnd)
186
+
187
+ const timer = globalThis.setTimeout(
188
+ finish,
189
+ lengthMs + EXIT_SAFETY_MARGIN_MS,
190
+ )
191
+
192
+ return () => {
193
+ element.removeEventListener(
194
+ "animationend",
195
+ onAnimationEnd,
196
+ )
197
+
198
+ globalThis.clearTimeout(timer)
199
+ }
200
+ }, [isExiting])
201
+
202
+ return {
203
+ isExiting,
204
+ isMounted: isVisible || isShown,
205
+ presenceRef,
206
+ }
207
+ }
208
+
209
+ /**
210
+ * The enter and exit classes for a panel that scales from its anchor:
211
+ * a modal box, a popover, a menu, a listbox. Defined in `styles.css`
212
+ * on the `--duration-*` and `--easing-*` tokens, and switched off
213
+ * under `prefers-reduced-motion`.
214
+ */
215
+ export const toOverlayMotionClass = (
216
+ isExiting: boolean,
217
+ ): string =>
218
+ isExiting
219
+ ? "charcuterie-overlay-exit"
220
+ : "charcuterie-overlay-enter"
221
+
222
+ /** The same, for things that only fade: the scrim and a tooltip. */
223
+ export const toFadeMotionClass = (
224
+ isExiting: boolean,
225
+ ): string =>
226
+ isExiting
227
+ ? "charcuterie-fade-exit"
228
+ : "charcuterie-fade-enter"
229
+
230
+ /**
231
+ * Where an anchored panel grows from: the edge that faces its
232
+ * trigger. A menu below its button scales down out of the button, and
233
+ * one flipped above it scales up out of it.
234
+ *
235
+ * Only the side is used, centred on the cross axis. The alignment half
236
+ * of a placement (`-start`, `-end`) is logical and flips under RTL,
237
+ * and a 4% scale is too small for the cross-axis origin to be seen.
238
+ */
239
+ export const toTransformOrigin = (
240
+ placement: string,
241
+ ): string => {
242
+ const [side] = placement.split("-")
243
+
244
+ return (
245
+ {
246
+ bottom: "center top",
247
+ left: "right center",
248
+ right: "left center",
249
+ top: "center bottom",
250
+ }[side ?? "bottom"] ?? "center top"
251
+ )
252
+ }
@@ -0,0 +1,131 @@
1
+ import type { ReactNode } from "react"
2
+ import { useState } from "react"
3
+ import type { Root } from "react-dom/client"
4
+ import { createRoot } from "react-dom/client"
5
+ import { expect, userEvent, waitFor } from "storybook/test"
6
+ import { afterEach, beforeEach, test } from "vitest"
7
+
8
+ import { useValueChangeMotion } from "./useValueChangeMotion.ts"
9
+
10
+ /**
11
+ * As in `usePresence.test.tsx`: the class must come off when its
12
+ * animation ends, and that needs the animation, so these tests lift
13
+ * the suite's motion freeze.
14
+ */
15
+ const FREEZE_ID = "charcuterie-freeze-motion"
16
+
17
+ let frozenStyle: HTMLElement | null = null
18
+
19
+ const mounted: { host: HTMLElement; root: Root }[] = []
20
+
21
+ beforeEach(() => {
22
+ frozenStyle = document.getElementById(FREEZE_ID)
23
+
24
+ frozenStyle?.remove()
25
+ })
26
+
27
+ afterEach(() => {
28
+ for (const { host, root } of mounted.splice(0)) {
29
+ root.unmount()
30
+
31
+ host.remove()
32
+ }
33
+
34
+ if (frozenStyle !== null && !frozenStyle.isConnected) {
35
+ document.head.append(frozenStyle)
36
+ }
37
+ })
38
+
39
+ const mount = (node: ReactNode) => {
40
+ const host = document.createElement("div")
41
+
42
+ // Long enough that a loaded host cannot finish a pop between two
43
+ // lines of a test.
44
+ host.style.setProperty("--duration-slow", "600ms")
45
+
46
+ document.body.append(host)
47
+
48
+ const root = createRoot(host)
49
+
50
+ root.render(node)
51
+
52
+ mounted.push({ host, root })
53
+
54
+ return host
55
+ }
56
+
57
+ const Balance = (): ReactNode => {
58
+ const [value, setValue] = useState<number | null>(null)
59
+
60
+ const changeMotion = useValueChangeMotion(value)
61
+
62
+ return (
63
+ <div>
64
+ <button
65
+ onClick={() => {
66
+ setValue((previous) => (previous ?? 0) + 1)
67
+ }}
68
+ type="button"
69
+ >
70
+ Change
71
+ </button>
72
+
73
+ <output {...changeMotion}>{value}</output>
74
+ </div>
75
+ )
76
+ }
77
+
78
+ const mountBalance = async () => {
79
+ const host = mount(<Balance />)
80
+
81
+ const button = await waitFor(() => {
82
+ const found = host.querySelector("button")
83
+
84
+ if (found === null) {
85
+ throw new Error("not mounted yet")
86
+ }
87
+
88
+ return found
89
+ })
90
+
91
+ const output = host.querySelector("output") as HTMLElement
92
+
93
+ return { button, output }
94
+ }
95
+
96
+ test("a value pops on each change, but not on arrival", async () => {
97
+ const { button, output } = await mountBalance()
98
+
99
+ // null → 1 is data arriving.
100
+ await userEvent.click(button)
101
+
102
+ expect(output.className).toBe("")
103
+
104
+ await userEvent.click(button)
105
+
106
+ expect(output).toHaveClass("charcuterie-value-changed")
107
+
108
+ // A change during the pop swaps the name, which restarts it.
109
+ await userEvent.click(button)
110
+
111
+ expect(output).toHaveClass(
112
+ "charcuterie-value-changed-again",
113
+ )
114
+ })
115
+
116
+ test("the pop class comes off when the pop ends", async () => {
117
+ const { button, output } = await mountBalance()
118
+
119
+ await userEvent.click(button)
120
+
121
+ await userEvent.click(button)
122
+
123
+ expect(output).toHaveClass("charcuterie-value-changed")
124
+
125
+ await waitFor(
126
+ () => {
127
+ expect(output.className).toBe("")
128
+ },
129
+ { timeout: 5_000 },
130
+ )
131
+ })
@@ -0,0 +1,110 @@
1
+ import type { AnimationEvent } from "react"
2
+ import { useCallback, useState } from "react"
3
+
4
+ const POP_ANIMATIONS = new Set([
5
+ "charcuterie-value-pop",
6
+ "charcuterie-value-pop-again",
7
+ ])
8
+
9
+ export type ValueChangeMotionProps = {
10
+ /** The pop class while the pop runs; `undefined` otherwise. */
11
+ className: string | undefined
12
+ onAnimationEnd: (
13
+ event: AnimationEvent<HTMLElement>,
14
+ ) => void
15
+ }
16
+
17
+ /**
18
+ * Props that make an element pop briefly each time `value` changes: a
19
+ * balance after a purchase, a count after an add, a status after a
20
+ * save. They show the user which part of the screen their action
21
+ * changed.
22
+ *
23
+ * ```tsx
24
+ * const changeMotion = useValueChangeMotion(balance.spendable)
25
+ *
26
+ * <div
27
+ * {...changeMotion}
28
+ * className={toClassName("inline-block text-3xl tabular-nums", changeMotion.className)}
29
+ * >
30
+ * {formatPoints(balance.spendable)}
31
+ * </div>
32
+ * ```
33
+ *
34
+ * ### What counts as a change
35
+ *
36
+ * The first value does not pop, and neither does the first real value
37
+ * after `null` or `undefined` — that is data arriving, not an action
38
+ * changing it. Values are compared with `Object.is`, so pass the
39
+ * number or string that is shown, not a fresh object.
40
+ *
41
+ * ### Why the class comes off, and why there are two
42
+ *
43
+ * The class is removed when its animation ends. An element that goes
44
+ * from `display: none` back to shown restarts its CSS animation, so a
45
+ * class left on would pop again each time a hidden tab is shown, for
46
+ * a change made long ago.
47
+ *
48
+ * A CSS animation restarts only when its name changes. A change that
49
+ * arrives while the last pop is still running switches to a second
50
+ * class, with identical keyframes under another name, so two
51
+ * purchases in a row pop twice.
52
+ *
53
+ * ### On the element
54
+ *
55
+ * Spread the props onto the element that shows the value. If it has
56
+ * its own `onAnimationEnd`, call both. The pop animates the `scale`
57
+ * property, which does nothing on a plain inline element: give the
58
+ * element `inline-block` or `block` layout. Under reduced motion the
59
+ * class has no animation and the new value is simply shown.
60
+ */
61
+ export const useValueChangeMotion = (
62
+ value: unknown,
63
+ ): ValueChangeMotionProps => {
64
+ const [state, setState] = useState({
65
+ changeCount: 0,
66
+ settledCount: 0,
67
+ value,
68
+ })
69
+
70
+ if (!Object.is(state.value, value)) {
71
+ const isArrival =
72
+ state.value === null || state.value === undefined
73
+
74
+ setState({
75
+ changeCount: isArrival
76
+ ? state.changeCount
77
+ : state.changeCount + 1,
78
+ settledCount: isArrival
79
+ ? state.changeCount
80
+ : state.settledCount,
81
+ value,
82
+ })
83
+ }
84
+
85
+ const onAnimationEnd = useCallback(
86
+ (event: AnimationEvent<HTMLElement>) => {
87
+ if (
88
+ event.target === event.currentTarget &&
89
+ POP_ANIMATIONS.has(event.animationName)
90
+ ) {
91
+ setState((previous) => ({
92
+ ...previous,
93
+ settledCount: previous.changeCount,
94
+ }))
95
+ }
96
+ },
97
+ [],
98
+ )
99
+
100
+ const isPopping = state.changeCount !== state.settledCount
101
+
102
+ return {
103
+ className: isPopping
104
+ ? state.changeCount % 2 === 1
105
+ ? "charcuterie-value-changed"
106
+ : "charcuterie-value-changed-again"
107
+ : undefined,
108
+ onAnimationEnd,
109
+ }
110
+ }