@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,674 @@
1
+ import { useLatestRef } from "@charcuterie/logic"
2
+ import type { HTMLAttributes } from "react"
3
+ import {
4
+ useCallback,
5
+ useLayoutEffect,
6
+ useRef,
7
+ useState,
8
+ } from "react"
9
+
10
+ import {
11
+ getAnimationLengthMs,
12
+ getTransitionLengthMs,
13
+ } from "./usePresence.ts"
14
+
15
+ /**
16
+ * Motion for a list an action changes: an added item enters, a
17
+ * removed one leaves, and the items around them slide to their new
18
+ * places instead of jumping.
19
+ *
20
+ * ```tsx
21
+ * const { entries } = useListMotion({ items: purchases, getKey: (p) => p.id })
22
+ *
23
+ * <AdaptiveGrid>
24
+ * {entries.map(({ item, key, motionProps }) => (
25
+ * <div key={key} {...motionProps}>
26
+ * <PurchaseCard purchase={item} />
27
+ * </div>
28
+ * ))}
29
+ * </AdaptiveGrid>
30
+ * ```
31
+ *
32
+ * ### The wrapper is the hook's
33
+ *
34
+ * `motionProps` go on an element the hook owns — usually a plain
35
+ * wrapper `div` that is the list's direct child. The hook writes that
36
+ * element's `translate` and `transition` inline while it slides, and
37
+ * its enter and exit animate `opacity` and `scale`, so it must not be
38
+ * an element whose own styles carry those: a running enter or exit
39
+ * overrides the element's own `scale`, and a slide replaces its own
40
+ * `transition`. Put a hover or press effect on an element inside it.
41
+ *
42
+ * ### Only what an action changed moves
43
+ *
44
+ * Items present on the first render do not animate in: a page that
45
+ * loads should not perform. After that, a key the list has not seen
46
+ * enters; a key that disappears stays in the list, `inert` and
47
+ * `aria-hidden`, where it was last shown, until its exit animation
48
+ * ends; and when the order of keys (or the caller's `layoutKey`)
49
+ * changes, every item that moved slides from where it was. A
50
+ * re-render that changes neither moves nothing, so a window resize is
51
+ * never animated after the fact.
52
+ *
53
+ * ### The same three renderings as every other motion
54
+ *
55
+ * Exit lengths are read from the computed style (see `usePresence`),
56
+ * and the slide is a CSS transition on the `--duration-normal` token.
57
+ * Under reduced motion, in the frozen suites, and in a DOM with no CSS
58
+ * engine, an exit is removed in the same commit and a slide has no
59
+ * length.
60
+ *
61
+ * ### Why not `useFlipList`
62
+ *
63
+ * `@charcuterie/logic`'s `useFlipList` slides a list React re-orders,
64
+ * and this hook measures the same way it does: the "before" positions
65
+ * are read during the render that changes the order, from the commit
66
+ * the user is looking at. It does not use that hook, for three
67
+ * reasons. `useFlipList` animates with the Web Animations API, which
68
+ * the suites' motion freeze cannot reach, so a frozen suite would
69
+ * still shoot items mid-slide; it animates `transform`, which a
70
+ * caller's own transform would fight; and it has no exits, which are
71
+ * most of what this hook is for. The slide here is a CSS transition,
72
+ * so the freeze and reduced motion remove it like every other motion.
73
+ *
74
+ * ### Enter classes come off when they finish
75
+ *
76
+ * An element that goes from `display: none` back to shown restarts
77
+ * its CSS animation. So the enter class comes off when its animation
78
+ * ends, or switching back to a hidden tab would replay "added" on an
79
+ * item no action added.
80
+ */
81
+ export type ListMotionProps = Pick<
82
+ HTMLAttributes<HTMLElement>,
83
+ "aria-hidden" | "className" | "inert"
84
+ > & {
85
+ "data-motion-key": string
86
+ ref: (node: HTMLElement | null) => void
87
+ }
88
+
89
+ export type ListMotionEntry<Item> = {
90
+ /**
91
+ * The item's index in `items`. A leaving item keeps the index it had
92
+ * when it was removed, so a row that shows its position does not
93
+ * read "0" while it leaves.
94
+ */
95
+ index: number
96
+ /** Removed, and leaving. Already `inert` through `motionProps`. */
97
+ isExiting: boolean
98
+ item: Item
99
+ key: string
100
+ motionProps: ListMotionProps
101
+ }
102
+
103
+ export type UseListMotionOptions<Item> = {
104
+ getKey: (item: Item) => string
105
+ items: readonly Item[]
106
+ /**
107
+ * Anything else that changes the items' sizes, so the items after
108
+ * a changed one slide to their new places too. Without it, only a
109
+ * change in the order of keys slides anything.
110
+ *
111
+ * `GroupedList` passes each group's row keys: a row added to one
112
+ * group makes the groups below it taller or shorter, and they slide
113
+ * rather than jump.
114
+ */
115
+ layoutKey?: string
116
+ /**
117
+ * Called when a leaving item has finished leaving and is about to be
118
+ * removed, which closes the gap it held. A parent whose own layout
119
+ * that gap changes sets state here: React renders the parent and
120
+ * this list in one batch, so the parent measures before the gap
121
+ * closes and can slide what it moves. `GroupedList` does, so the
122
+ * groups below a group that lost a row slide up.
123
+ */
124
+ onExitEnd?: () => void
125
+ }
126
+
127
+ type ExitingItem<Item> = {
128
+ index: number
129
+ item: Item
130
+ key: string
131
+ }
132
+
133
+ type Position = {
134
+ left: number
135
+ top: number
136
+ }
137
+
138
+ const ENTER_CLASS = "charcuterie-item-enter"
139
+
140
+ const ENTER_ANIMATION = "charcuterie-item-in"
141
+
142
+ const EXIT_CLASS = "charcuterie-item-exit"
143
+
144
+ const SLIDE_TRANSITION =
145
+ "translate var(--duration-normal) var(--easing-standard)"
146
+
147
+ /** As in `usePresence`: a margin past the computed length, not a
148
+ * design duration. */
149
+ const SAFETY_MARGIN_MS = 50
150
+
151
+ /**
152
+ * Where `element` sits inside its parent, the list.
153
+ *
154
+ * Inside the parent's own box, whatever the parent's CSS. `offsetTop`
155
+ * is measured from the nearest positioned ancestor, which is often
156
+ * outside the list: in a `GroupedList`, a row's offset would then
157
+ * include its group's, and a group and its rows moving in one commit
158
+ * would slide each row by the group's move twice, once in the row and
159
+ * once in the group. Offsets ignore `translate`, so a slide in flight
160
+ * does not change what is measured.
161
+ */
162
+ const readPosition = (element: HTMLElement): Position => {
163
+ const parent = element.parentElement
164
+
165
+ if (
166
+ parent === null ||
167
+ element.offsetParent === parent ||
168
+ parent.offsetParent !== element.offsetParent
169
+ ) {
170
+ return {
171
+ left: element.offsetLeft,
172
+ top: element.offsetTop,
173
+ }
174
+ }
175
+
176
+ return {
177
+ left: element.offsetLeft - parent.offsetLeft,
178
+ top: element.offsetTop - parent.offsetTop,
179
+ }
180
+ }
181
+
182
+ export const useListMotion = <Item>({
183
+ getKey,
184
+ items,
185
+ layoutKey = "",
186
+ onExitEnd,
187
+ }: UseListMotionOptions<Item>): {
188
+ entries: ListMotionEntry<Item>[]
189
+ } => {
190
+ // Compared by key, never by array identity. Callers routinely build
191
+ // the array during render (`groupPurchases(recent)`), so an identity
192
+ // check would see a "change" on every render — and this block sets
193
+ // state during render, so that would re-render forever.
194
+ const keySignature = JSON.stringify(items.map(getKey))
195
+
196
+ const [previousKeySignature, setPreviousKeySignature] =
197
+ useState(keySignature)
198
+
199
+ // The items as of the last commit, so a removed item leaves showing
200
+ // its latest content rather than what it held when the keys last
201
+ // changed.
202
+ const committedItemsRef = useRef(items)
203
+
204
+ useLayoutEffect(() => {
205
+ committedItemsRef.current = items
206
+ })
207
+
208
+ // The keys the last commit showed, in order, leaving items included.
209
+ const shownKeysRef = useRef<readonly string[]>(
210
+ items.map(getKey),
211
+ )
212
+
213
+ const [exiting, setExiting] = useState<
214
+ ExitingItem<Item>[]
215
+ >([])
216
+
217
+ // Keys that arrived after the first render. They keep the enter
218
+ // class while they are mounted; it only animates once, on mount.
219
+ const [enteredKeys, setEnteredKeys] = useState<
220
+ ReadonlySet<string>
221
+ >(() => new Set())
222
+
223
+ if (keySignature !== previousKeySignature) {
224
+ // Read during render on purpose: the last committed list is the
225
+ // one the user is looking at, and so the one items leave from.
226
+ const previousItems = committedItemsRef.current
227
+
228
+ const currentKeys = new Set(items.map(getKey))
229
+
230
+ const previousKeys = new Set(previousItems.map(getKey))
231
+
232
+ const removed = previousItems
233
+ .map((item, index) => ({
234
+ index,
235
+ item,
236
+ key: getKey(item),
237
+ }))
238
+ .filter((one) => !currentKeys.has(one.key))
239
+
240
+ const added = items
241
+ .map(getKey)
242
+ .filter((key) => !previousKeys.has(key))
243
+
244
+ setPreviousKeySignature(keySignature)
245
+
246
+ if (removed.length > 0 || exiting.length > 0) {
247
+ setExiting((previous) => [
248
+ // A key that came back stops leaving.
249
+ ...previous.filter(
250
+ (one) => !currentKeys.has(one.key),
251
+ ),
252
+ ...removed.filter(
253
+ (one) =>
254
+ !previous.some(
255
+ (exitingOne) => exitingOne.key === one.key,
256
+ ),
257
+ ),
258
+ ])
259
+ }
260
+
261
+ if (added.length > 0) {
262
+ setEnteredKeys(
263
+ (previous) => new Set([...previous, ...added]),
264
+ )
265
+ }
266
+ }
267
+
268
+ const elementsRef = useRef(new Map<string, HTMLElement>())
269
+
270
+ const refCallbacksRef = useRef(
271
+ new Map<string, (node: HTMLElement | null) => void>(),
272
+ )
273
+
274
+ const getRef = useCallback((key: string) => {
275
+ const existing = refCallbacksRef.current.get(key)
276
+
277
+ if (existing) {
278
+ return existing
279
+ }
280
+
281
+ let stopListening: (() => void) | undefined
282
+
283
+ const callback = (node: HTMLElement | null) => {
284
+ stopListening?.()
285
+
286
+ stopListening = undefined
287
+
288
+ if (node === null) {
289
+ elementsRef.current.delete(key)
290
+
291
+ // Dropped on detach, so a list whose keys keep changing does
292
+ // not keep a callback for every key it ever showed. A key
293
+ // that comes back gets a new one. Only this callback's own
294
+ // entry: React detaches an old callback after a new one for
295
+ // the same key may already be in the map.
296
+ if (refCallbacksRef.current.get(key) === callback) {
297
+ refCallbacksRef.current.delete(key)
298
+ }
299
+
300
+ return
301
+ }
302
+
303
+ elementsRef.current.set(key, node)
304
+
305
+ // StrictMode detaches and re-attaches the same callback; put it
306
+ // back so the next render hands React the same identity.
307
+ if (!refCallbacksRef.current.has(key)) {
308
+ refCallbacksRef.current.set(key, callback)
309
+ }
310
+
311
+ const onAnimationEnd = (event: AnimationEvent) => {
312
+ if (
313
+ event.target === node &&
314
+ event.animationName === ENTER_ANIMATION
315
+ ) {
316
+ setEnteredKeys((previous) => {
317
+ if (!previous.has(key)) {
318
+ return previous
319
+ }
320
+
321
+ const next = new Set(previous)
322
+
323
+ next.delete(key)
324
+
325
+ return next
326
+ })
327
+ }
328
+ }
329
+
330
+ node.addEventListener("animationend", onAnimationEnd)
331
+
332
+ stopListening = () => {
333
+ node.removeEventListener(
334
+ "animationend",
335
+ onAnimationEnd,
336
+ )
337
+ }
338
+ }
339
+
340
+ refCallbacksRef.current.set(key, callback)
341
+
342
+ return callback
343
+ }, [])
344
+
345
+ const exitingKeys = new Set(exiting.map((one) => one.key))
346
+
347
+ // Each leaving item stays where the user last saw it: after the item
348
+ // that was shown just before it, whether that one stayed, left too,
349
+ // or was added in front of it since. A stored index would not hold:
350
+ // in a newest-first list capped at three, `[A, B, C]` becoming
351
+ // `[X, A, B]` would put the leaving C between A and B.
352
+ const itemKeys = items.map(getKey)
353
+
354
+ const itemKeySet = new Set(itemKeys)
355
+
356
+ const exitingByKey = new Map(
357
+ exiting.map((one) => [one.key, one]),
358
+ )
359
+
360
+ // Leaving items, by the key of the staying item they follow. `null`
361
+ // holds the ones that were shown before every staying item.
362
+ const exitingAfter = new Map<
363
+ string | null,
364
+ ExitingItem<Item>[]
365
+ >()
366
+
367
+ const placedKeys = new Set<string>()
368
+
369
+ let lastStayingKey: string | null = null
370
+
371
+ for (const key of shownKeysRef.current) {
372
+ const one = exitingByKey.get(key)
373
+
374
+ if (one !== undefined) {
375
+ exitingAfter.set(lastStayingKey, [
376
+ ...(exitingAfter.get(lastStayingKey) ?? []),
377
+ one,
378
+ ])
379
+
380
+ placedKeys.add(key)
381
+ } else if (itemKeySet.has(key)) {
382
+ lastStayingKey = key
383
+ }
384
+ }
385
+
386
+ // A leaving item the last commit did not show (removed in the same
387
+ // batch that would have shown it) goes at the end.
388
+ const unplaced = exiting.filter(
389
+ (one) => !placedKeys.has(one.key),
390
+ )
391
+
392
+ const toExitingEntry = (
393
+ one: ExitingItem<Item>,
394
+ ): ListMotionEntry<Item> => ({
395
+ index: one.index,
396
+ isExiting: true,
397
+ item: one.item,
398
+ key: one.key,
399
+ motionProps: {
400
+ "aria-hidden": true,
401
+ className: EXIT_CLASS,
402
+ "data-motion-key": one.key,
403
+ inert: true,
404
+ ref: getRef(one.key),
405
+ },
406
+ })
407
+
408
+ const entries: ListMotionEntry<Item>[] = [
409
+ ...(exitingAfter.get(null) ?? []).map(toExitingEntry),
410
+ ...items.flatMap((item, index) => {
411
+ const key = itemKeys[index] ?? getKey(item)
412
+
413
+ return [
414
+ {
415
+ index,
416
+ isExiting: false,
417
+ item,
418
+ key,
419
+ motionProps: {
420
+ className: enteredKeys.has(key)
421
+ ? ENTER_CLASS
422
+ : undefined,
423
+ "data-motion-key": key,
424
+ ref: getRef(key),
425
+ },
426
+ },
427
+ ...(exitingAfter.get(key) ?? []).map(
428
+ toExitingEntry,
429
+ ),
430
+ ]
431
+ }),
432
+ ...unplaced.map(toExitingEntry),
433
+ ]
434
+
435
+ // The order this commit shows, leaving items included, which is
436
+ // where the next change places what leaves.
437
+ useLayoutEffect(() => {
438
+ shownKeysRef.current = entries.map((entry) => entry.key)
439
+ })
440
+
441
+ const onExitEndRef = useLatestRef(onExitEnd)
442
+
443
+ const finishExit = useCallback(
444
+ (key: string) => {
445
+ setExiting((previous) =>
446
+ previous.filter((one) => one.key !== key),
447
+ )
448
+
449
+ onExitEndRef.current?.()
450
+
451
+ setEnteredKeys((previous) => {
452
+ if (!previous.has(key)) {
453
+ return previous
454
+ }
455
+
456
+ const next = new Set(previous)
457
+
458
+ next.delete(key)
459
+
460
+ return next
461
+ })
462
+ },
463
+ [onExitEndRef],
464
+ )
465
+
466
+ const watchersRef = useRef(new Map<string, () => void>())
467
+
468
+ const exitingSignature = [...exitingKeys]
469
+ .sort()
470
+ .join("\n")
471
+
472
+ // Watch each leaving element for the end of its exit.
473
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the signature is the set of leaving keys, which is what this effect depends on.
474
+ useLayoutEffect(() => {
475
+ const watchers = watchersRef.current
476
+
477
+ for (const [key, stop] of watchers) {
478
+ if (!exitingKeys.has(key)) {
479
+ stop()
480
+
481
+ watchers.delete(key)
482
+ }
483
+ }
484
+
485
+ for (const key of exitingKeys) {
486
+ if (watchers.has(key)) {
487
+ continue
488
+ }
489
+
490
+ const element = elementsRef.current.get(key)
491
+
492
+ const lengthMs =
493
+ element === undefined
494
+ ? 0
495
+ : getAnimationLengthMs(element)
496
+
497
+ if (element === undefined || lengthMs === 0) {
498
+ finishExit(key)
499
+
500
+ continue
501
+ }
502
+
503
+ const onAnimationEnd = (event: AnimationEvent) => {
504
+ if (event.target === element) {
505
+ finishExit(key)
506
+ }
507
+ }
508
+
509
+ element.addEventListener(
510
+ "animationend",
511
+ onAnimationEnd,
512
+ )
513
+
514
+ const timer = globalThis.setTimeout(() => {
515
+ finishExit(key)
516
+ }, lengthMs + SAFETY_MARGIN_MS)
517
+
518
+ watchers.set(key, () => {
519
+ element.removeEventListener(
520
+ "animationend",
521
+ onAnimationEnd,
522
+ )
523
+
524
+ globalThis.clearTimeout(timer)
525
+ })
526
+ }
527
+ }, [exitingSignature, finishExit])
528
+
529
+ useLayoutEffect(
530
+ () => () => {
531
+ for (const stop of watchersRef.current.values()) {
532
+ stop()
533
+ }
534
+
535
+ watchersRef.current.clear()
536
+ },
537
+ [],
538
+ )
539
+
540
+ // What slides the items: the order of keys, plus the caller's
541
+ // `layoutKey`.
542
+ const orderSignature = JSON.stringify([
543
+ entries.map((entry) => entry.key),
544
+ layoutKey,
545
+ ])
546
+
547
+ // The order the DOM shows now: the last committed one.
548
+ const committedOrderRef = useRef(orderSignature)
549
+
550
+ const firstPositionsRef = useRef<Map<
551
+ string,
552
+ Position
553
+ > | null>(null)
554
+
555
+ // The listener of the slide each element is running, if any.
556
+ const slideStopsRef = useRef(
557
+ new Map<HTMLElement, () => void>(),
558
+ )
559
+
560
+ // "First", read during the render that changes the order, while the
561
+ // DOM still holds the commit the user is looking at. Read any
562
+ // earlier and a row that grew in between, with no key change, would
563
+ // send every row below it sliding from where it used to be. This is
564
+ // `useFlipList`'s reason too; reading layout here has no effect on
565
+ // the tree, and a repeated render reads the same unchanged DOM.
566
+ if (committedOrderRef.current !== orderSignature) {
567
+ const positions = new Map<string, Position>()
568
+
569
+ for (const [key, element] of elementsRef.current) {
570
+ positions.set(key, readPosition(element))
571
+ }
572
+
573
+ firstPositionsRef.current = positions
574
+ }
575
+
576
+ // Slide every item that the change moved. Positions are offsets
577
+ // inside the list's own box, so scrolling the page between two
578
+ // renders is not mistaken for a move.
579
+ useLayoutEffect(() => {
580
+ const previousPositions = firstPositionsRef.current
581
+
582
+ // Consumed either way: a stale set of positions is worse than
583
+ // none.
584
+ firstPositionsRef.current = null
585
+
586
+ if (committedOrderRef.current === orderSignature) {
587
+ return
588
+ }
589
+
590
+ committedOrderRef.current = orderSignature
591
+
592
+ if (previousPositions === null) {
593
+ return
594
+ }
595
+
596
+ for (const [key, element] of elementsRef.current) {
597
+ const before = previousPositions.get(key)
598
+
599
+ const after = readPosition(element)
600
+
601
+ // Leaving items slide too: one that a reorder moves would
602
+ // otherwise jump, then fade where it never was. Their exit
603
+ // animates `opacity` and `scale`, never `translate`.
604
+ if (before === undefined) {
605
+ continue
606
+ }
607
+
608
+ const deltaLeft = before.left - after.left
609
+
610
+ const deltaTop = before.top - after.top
611
+
612
+ if (deltaLeft === 0 && deltaTop === 0) {
613
+ continue
614
+ }
615
+
616
+ // A slide that starts while the last one runs takes over from
617
+ // it. The last one's listener goes first, without touching the
618
+ // style: if it ran on the cancel this slide causes, it would
619
+ // clear the `transition` this slide is about to set, and a
620
+ // browser that follows the spec would then stop this slide dead.
621
+ slideStopsRef.current.get(element)?.()
622
+
623
+ element.style.transition = "none"
624
+
625
+ element.style.translate = `${deltaLeft}px ${deltaTop}px`
626
+
627
+ // Commit the inverted position before transitioning out of it,
628
+ // or the browser coalesces both writes and nothing moves.
629
+ element.getBoundingClientRect()
630
+
631
+ element.style.transition = SLIDE_TRANSITION
632
+
633
+ element.style.translate = ""
634
+
635
+ // Reduced motion and the frozen suites make the slide 0s long,
636
+ // and a 0s transition never starts, so it would never end and
637
+ // never clear what it wrote.
638
+ if (getTransitionLengthMs(element) === 0) {
639
+ element.style.transition = ""
640
+
641
+ continue
642
+ }
643
+
644
+ const stop = () => {
645
+ element.removeEventListener("transitionend", clear)
646
+
647
+ element.removeEventListener(
648
+ "transitioncancel",
649
+ clear,
650
+ )
651
+
652
+ slideStopsRef.current.delete(element)
653
+ }
654
+
655
+ const clear = (event: TransitionEvent) => {
656
+ if (event.target !== element) {
657
+ return
658
+ }
659
+
660
+ element.style.transition = ""
661
+
662
+ stop()
663
+ }
664
+
665
+ element.addEventListener("transitionend", clear)
666
+
667
+ element.addEventListener("transitioncancel", clear)
668
+
669
+ slideStopsRef.current.set(element, stop)
670
+ }
671
+ }, [orderSignature])
672
+
673
+ return { entries }
674
+ }