@navikt/ds-react 7.30.1 → 7.32.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 (174) hide show
  1. package/cjs/chat/Chat.d.ts +1 -1
  2. package/cjs/chat/Chat.js.map +1 -1
  3. package/cjs/copybutton/CopyButton.js +1 -1
  4. package/cjs/copybutton/CopyButton.js.map +1 -1
  5. package/cjs/form/checkbox/Checkbox.js +1 -1
  6. package/cjs/form/checkbox/Checkbox.js.map +1 -1
  7. package/cjs/form/combobox/Combobox.js +15 -13
  8. package/cjs/form/combobox/Combobox.js.map +1 -1
  9. package/cjs/form/combobox/FilteredOptions/FilteredOptions.js +53 -3
  10. package/cjs/form/combobox/FilteredOptions/FilteredOptions.js.map +1 -1
  11. package/cjs/form/combobox/FilteredOptions/useVirtualFocus.js.map +1 -1
  12. package/cjs/form/combobox/Input/Input.context.d.ts +2 -2
  13. package/cjs/form/combobox/Input/InputController.js +15 -14
  14. package/cjs/form/combobox/Input/InputController.js.map +1 -1
  15. package/cjs/form/file-upload/useFileUpload.d.ts +1 -1
  16. package/cjs/form/radio/Radio.js +1 -1
  17. package/cjs/form/radio/Radio.js.map +1 -1
  18. package/cjs/form/useFormField.js.map +1 -1
  19. package/cjs/modal/ModalUtils.d.ts +2 -2
  20. package/cjs/modal/ModalUtils.js.map +1 -1
  21. package/cjs/overlays/dismissablelayer/DismissableLayer.d.ts +1 -1
  22. package/cjs/overlays/floating/Floating.d.ts +11 -0
  23. package/cjs/overlays/floating/Floating.js +32 -8
  24. package/cjs/overlays/floating/Floating.js.map +1 -1
  25. package/cjs/overlays/overlay/hooks/useAnimationsFinished.d.ts +27 -0
  26. package/cjs/overlays/overlay/hooks/useAnimationsFinished.js +138 -0
  27. package/cjs/overlays/overlay/hooks/useAnimationsFinished.js.map +1 -0
  28. package/cjs/overlays/overlay/hooks/useEventCallback.d.ts +6 -0
  29. package/cjs/overlays/overlay/hooks/useEventCallback.js +89 -0
  30. package/cjs/overlays/overlay/hooks/useEventCallback.js.map +1 -0
  31. package/cjs/overlays/overlay/hooks/useLatestRef.d.ts +5 -0
  32. package/cjs/overlays/overlay/hooks/useLatestRef.js +23 -0
  33. package/cjs/overlays/overlay/hooks/useLatestRef.js.map +1 -0
  34. package/cjs/overlays/overlay/hooks/useOpenChangeAnimationComplete.d.ts +31 -0
  35. package/cjs/overlays/overlay/hooks/useOpenChangeAnimationComplete.js +35 -0
  36. package/cjs/overlays/overlay/hooks/useOpenChangeAnimationComplete.js.map +1 -0
  37. package/cjs/overlays/overlay/hooks/useRefWithInit.d.ts +7 -0
  38. package/cjs/overlays/overlay/hooks/useRefWithInit.js +14 -0
  39. package/cjs/overlays/overlay/hooks/useRefWithInit.js.map +1 -0
  40. package/cjs/overlays/overlay/hooks/useTransitionStatus.d.ts +38 -0
  41. package/cjs/overlays/overlay/hooks/useTransitionStatus.js +118 -0
  42. package/cjs/overlays/overlay/hooks/useTransitionStatus.js.map +1 -0
  43. package/cjs/progress-bar/ProgressBar.js +1 -1
  44. package/cjs/progress-bar/ProgressBar.js.map +1 -1
  45. package/cjs/read-more/ReadMore.d.ts +2 -9
  46. package/cjs/read-more/ReadMore.js +1 -8
  47. package/cjs/read-more/ReadMore.js.map +1 -1
  48. package/cjs/table/AnimateHeight.js +2 -2
  49. package/cjs/table/AnimateHeight.js.map +1 -1
  50. package/cjs/table/ExpandableRow.d.ts +1 -1
  51. package/cjs/table/ExpandableRow.js +2 -10
  52. package/cjs/table/ExpandableRow.js.map +1 -1
  53. package/cjs/table/Row.d.ts +7 -0
  54. package/cjs/table/Row.js +13 -2
  55. package/cjs/table/Row.js.map +1 -1
  56. package/cjs/table/Table.utils.d.ts +9 -0
  57. package/cjs/table/Table.utils.js +57 -0
  58. package/cjs/table/Table.utils.js.map +1 -0
  59. package/cjs/tabs/Tabs.context.d.ts +1 -1
  60. package/cjs/tabs/parts/tab/useTab.d.ts +1 -1
  61. package/cjs/tabs/parts/tablist/useScrollButtons.d.ts +1 -1
  62. package/cjs/tabs/parts/tablist/useScrollButtons.js.map +1 -1
  63. package/cjs/toggle-group/ToggleGroup.context.d.ts +1 -1
  64. package/cjs/toggle-group/parts/useToggleItem.d.ts +1 -1
  65. package/cjs/util/hooks/descendants/useDescendant.d.ts +1 -1
  66. package/cjs/util/hooks/useMergeRefs.d.ts +3 -3
  67. package/cjs/util/hooks/useMergeRefs.js +3 -3
  68. package/cjs/util/hooks/useMergeRefs.js.map +1 -1
  69. package/cjs/util/renderStoriesForChromatic.d.ts +2 -2
  70. package/cjs/util/renderStoriesForChromatic.js +2 -2
  71. package/cjs/util/renderStoriesForChromatic.js.map +1 -1
  72. package/cjs/util/virtualfocus/Context.d.ts +1 -1
  73. package/esm/chat/Chat.d.ts +1 -1
  74. package/esm/chat/Chat.js.map +1 -1
  75. package/esm/copybutton/CopyButton.js +1 -1
  76. package/esm/copybutton/CopyButton.js.map +1 -1
  77. package/esm/form/checkbox/Checkbox.js +1 -1
  78. package/esm/form/checkbox/Checkbox.js.map +1 -1
  79. package/esm/form/combobox/Combobox.js +15 -13
  80. package/esm/form/combobox/Combobox.js.map +1 -1
  81. package/esm/form/combobox/FilteredOptions/FilteredOptions.js +21 -4
  82. package/esm/form/combobox/FilteredOptions/FilteredOptions.js.map +1 -1
  83. package/esm/form/combobox/FilteredOptions/useVirtualFocus.js.map +1 -1
  84. package/esm/form/combobox/Input/Input.context.d.ts +2 -2
  85. package/esm/form/combobox/Input/InputController.js +15 -14
  86. package/esm/form/combobox/Input/InputController.js.map +1 -1
  87. package/esm/form/file-upload/useFileUpload.d.ts +1 -1
  88. package/esm/form/radio/Radio.js +1 -1
  89. package/esm/form/radio/Radio.js.map +1 -1
  90. package/esm/form/useFormField.js.map +1 -1
  91. package/esm/modal/ModalUtils.d.ts +2 -2
  92. package/esm/modal/ModalUtils.js.map +1 -1
  93. package/esm/overlays/dismissablelayer/DismissableLayer.d.ts +1 -1
  94. package/esm/overlays/floating/Floating.d.ts +11 -0
  95. package/esm/overlays/floating/Floating.js +32 -8
  96. package/esm/overlays/floating/Floating.js.map +1 -1
  97. package/esm/overlays/overlay/hooks/useAnimationsFinished.d.ts +27 -0
  98. package/esm/overlays/overlay/hooks/useAnimationsFinished.js +99 -0
  99. package/esm/overlays/overlay/hooks/useAnimationsFinished.js.map +1 -0
  100. package/esm/overlays/overlay/hooks/useEventCallback.d.ts +6 -0
  101. package/esm/overlays/overlay/hooks/useEventCallback.js +53 -0
  102. package/esm/overlays/overlay/hooks/useEventCallback.js.map +1 -0
  103. package/esm/overlays/overlay/hooks/useLatestRef.d.ts +5 -0
  104. package/esm/overlays/overlay/hooks/useLatestRef.js +20 -0
  105. package/esm/overlays/overlay/hooks/useLatestRef.js.map +1 -0
  106. package/esm/overlays/overlay/hooks/useOpenChangeAnimationComplete.d.ts +31 -0
  107. package/esm/overlays/overlay/hooks/useOpenChangeAnimationComplete.js +32 -0
  108. package/esm/overlays/overlay/hooks/useOpenChangeAnimationComplete.js.map +1 -0
  109. package/esm/overlays/overlay/hooks/useRefWithInit.d.ts +7 -0
  110. package/esm/overlays/overlay/hooks/useRefWithInit.js +12 -0
  111. package/esm/overlays/overlay/hooks/useRefWithInit.js.map +1 -0
  112. package/esm/overlays/overlay/hooks/useTransitionStatus.d.ts +38 -0
  113. package/esm/overlays/overlay/hooks/useTransitionStatus.js +113 -0
  114. package/esm/overlays/overlay/hooks/useTransitionStatus.js.map +1 -0
  115. package/esm/progress-bar/ProgressBar.js +1 -1
  116. package/esm/progress-bar/ProgressBar.js.map +1 -1
  117. package/esm/read-more/ReadMore.d.ts +2 -9
  118. package/esm/read-more/ReadMore.js +1 -8
  119. package/esm/read-more/ReadMore.js.map +1 -1
  120. package/esm/table/AnimateHeight.js +2 -2
  121. package/esm/table/AnimateHeight.js.map +1 -1
  122. package/esm/table/ExpandableRow.d.ts +1 -1
  123. package/esm/table/ExpandableRow.js +2 -10
  124. package/esm/table/ExpandableRow.js.map +1 -1
  125. package/esm/table/Row.d.ts +7 -0
  126. package/esm/table/Row.js +13 -2
  127. package/esm/table/Row.js.map +1 -1
  128. package/esm/table/Table.utils.d.ts +9 -0
  129. package/esm/table/Table.utils.js +55 -0
  130. package/esm/table/Table.utils.js.map +1 -0
  131. package/esm/tabs/Tabs.context.d.ts +1 -1
  132. package/esm/tabs/parts/tab/useTab.d.ts +1 -1
  133. package/esm/tabs/parts/tablist/useScrollButtons.d.ts +1 -1
  134. package/esm/tabs/parts/tablist/useScrollButtons.js.map +1 -1
  135. package/esm/toggle-group/ToggleGroup.context.d.ts +1 -1
  136. package/esm/toggle-group/parts/useToggleItem.d.ts +1 -1
  137. package/esm/util/hooks/descendants/useDescendant.d.ts +1 -1
  138. package/esm/util/hooks/useMergeRefs.d.ts +3 -3
  139. package/esm/util/hooks/useMergeRefs.js +3 -3
  140. package/esm/util/hooks/useMergeRefs.js.map +1 -1
  141. package/esm/util/renderStoriesForChromatic.d.ts +2 -2
  142. package/esm/util/renderStoriesForChromatic.js +2 -2
  143. package/esm/util/renderStoriesForChromatic.js.map +1 -1
  144. package/esm/util/virtualfocus/Context.d.ts +1 -1
  145. package/package.json +4 -4
  146. package/src/chat/Chat.tsx +3 -3
  147. package/src/copybutton/CopyButton.tsx +1 -1
  148. package/src/form/checkbox/Checkbox.tsx +5 -3
  149. package/src/form/combobox/Combobox.tsx +44 -41
  150. package/src/form/combobox/FilteredOptions/FilteredOptions.tsx +29 -4
  151. package/src/form/combobox/FilteredOptions/useVirtualFocus.ts +1 -0
  152. package/src/form/combobox/Input/Input.context.tsx +2 -2
  153. package/src/form/combobox/Input/InputController.tsx +33 -29
  154. package/src/form/radio/Radio.tsx +5 -3
  155. package/src/form/useFormField.ts +1 -1
  156. package/src/modal/ModalUtils.ts +2 -2
  157. package/src/overlays/action-menu/ActionMenu.tsx +1 -1
  158. package/src/overlays/floating/Floating.tsx +110 -59
  159. package/src/overlays/overlay/hooks/useAnimationsFinished.ts +117 -0
  160. package/src/overlays/overlay/hooks/useEventCallback.ts +73 -0
  161. package/src/overlays/overlay/hooks/useLatestRef.ts +25 -0
  162. package/src/overlays/overlay/hooks/useOpenChangeAnimationComplete.ts +66 -0
  163. package/src/overlays/overlay/hooks/useRefWithInit.ts +25 -0
  164. package/src/overlays/overlay/hooks/useTransitionStatus.ts +145 -0
  165. package/src/progress-bar/ProgressBar.tsx +1 -1
  166. package/src/read-more/ReadMore.tsx +4 -11
  167. package/src/table/AnimateHeight.tsx +2 -2
  168. package/src/table/ExpandableRow.tsx +4 -17
  169. package/src/table/Row.tsx +33 -1
  170. package/src/table/Table.utils.ts +65 -0
  171. package/src/tabs/parts/tablist/useScrollButtons.ts +3 -1
  172. package/src/util/hooks/useMergeRefs.ts +5 -5
  173. package/src/util/link-anchor/LinkAnchor.tsx +1 -1
  174. package/src/util/renderStoriesForChromatic.tsx +4 -5
@@ -18,6 +18,7 @@ import React, {
18
18
  useRef,
19
19
  useState,
20
20
  } from "react";
21
+ import { useModalContext } from "../../modal/Modal.context";
21
22
  import { Slot } from "../../slot/Slot";
22
23
  import { createContext } from "../../util/create-context";
23
24
  import {
@@ -26,6 +27,7 @@ import {
26
27
  useMergeRefs,
27
28
  } from "../../util/hooks";
28
29
  import { AsChildProps } from "../../util/types";
30
+ import { useOpenChangeAnimationComplete } from "../overlay/hooks/useOpenChangeAnimationComplete";
29
31
  import {
30
32
  type Align,
31
33
  type Measurable,
@@ -188,7 +190,17 @@ interface FloatingContentProps extends HTMLAttributes<HTMLDivElement> {
188
190
  collisionPadding?: number | Partial<Record<Side, number>>;
189
191
  hideWhenDetached?: boolean;
190
192
  updatePositionStrategy?: "optimized" | "always";
193
+ fallbackPlacements?: FlipOptions["fallbackPlacements"];
191
194
  onPlaced?: () => void;
195
+ /**
196
+ * @default true
197
+ */
198
+ enabled?: boolean;
199
+ /**
200
+ * Only use this option if your floating element is conditionally rendered, not hidden with CSS.
201
+ * @default true
202
+ */
203
+ autoUpdateWhileMounted?: boolean;
192
204
  arrow?: {
193
205
  className?: string;
194
206
  padding?: number;
@@ -212,11 +224,15 @@ const FloatingContent = forwardRef<HTMLDivElement, FloatingContentProps>(
212
224
  updatePositionStrategy = "optimized",
213
225
  onPlaced,
214
226
  arrow: _arrow,
227
+ fallbackPlacements,
228
+ enabled = true,
229
+ autoUpdateWhileMounted = true,
215
230
  ...contentProps
216
231
  }: FloatingContentProps,
217
232
  forwardedRef,
218
233
  ) => {
219
234
  const context = useFloatingContext();
235
+ const modalContext = useModalContext(false);
220
236
 
221
237
  const arrowDefaults = {
222
238
  padding: 5,
@@ -256,68 +272,103 @@ const FloatingContent = forwardRef<HTMLDivElement, FloatingContentProps>(
256
272
  altBoundary: hasExplicitBoundaries,
257
273
  /* https://floating-ui.com/docs/flip#fallbackaxissidedirection */
258
274
  fallbackAxisSideDirection: "end",
275
+ fallbackPlacements,
259
276
  };
260
277
 
261
- const { refs, floatingStyles, placement, isPositioned, middlewareData } =
262
- useFloating({
263
- // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues
264
- strategy: "fixed",
265
- placement: desiredPlacement,
266
- whileElementsMounted: (...args) => {
267
- const cleanup = autoUpdate(...args, {
268
- animationFrame: updatePositionStrategy === "always",
269
- });
270
- return cleanup;
271
- },
272
- elements: {
273
- reference: context.anchor,
274
- },
275
- middleware: [
276
- offset({
277
- mainAxis: sideOffset + arrowHeight,
278
- alignmentAxis: alignOffset,
278
+ const {
279
+ refs,
280
+ floatingStyles,
281
+ placement,
282
+ isPositioned,
283
+ middlewareData,
284
+ elements: floatingElements,
285
+ update,
286
+ } = useFloating({
287
+ open: enabled,
288
+ // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues
289
+ strategy: "fixed",
290
+ placement: desiredPlacement,
291
+ whileElementsMounted: autoUpdateWhileMounted
292
+ ? (...args) => {
293
+ const cleanup = autoUpdate(...args, {
294
+ animationFrame: updatePositionStrategy === "always",
295
+ });
296
+ return cleanup;
297
+ }
298
+ : undefined,
299
+ elements: {
300
+ reference: context.anchor,
301
+ },
302
+ middleware: [
303
+ offset({
304
+ mainAxis: sideOffset + arrowHeight,
305
+ alignmentAxis: alignOffset,
306
+ }),
307
+ avoidCollisions &&
308
+ shift({
309
+ mainAxis: true,
310
+ crossAxis: false,
311
+ limiter: limitShift(),
279
312
  }),
280
- avoidCollisions &&
281
- shift({
282
- mainAxis: true,
283
- crossAxis: false,
284
- limiter: limitShift(),
285
- }),
286
- avoidCollisions && flip({ ...detectOverflowOptions }),
287
- size({
288
- ...detectOverflowOptions,
289
- apply: ({ elements, rects, availableWidth, availableHeight }) => {
290
- const { width: anchorWidth, height: anchorHeight } =
291
- rects.reference;
292
- const contentStyle = elements.floating.style;
293
- /**
294
- * Allows styling and animations based on the available space.
295
- */
296
- contentStyle.setProperty(
297
- "--ac-floating-available-width",
298
- `${availableWidth}px`,
299
- );
300
- contentStyle.setProperty(
301
- "--ac-floating-available-height",
302
- `${availableHeight}px`,
303
- );
304
- contentStyle.setProperty(
305
- "--ac-floating-anchor-width",
306
- `${anchorWidth}px`,
307
- );
308
- contentStyle.setProperty(
309
- "--ac-floating-anchor-height",
310
- `${anchorHeight}px`,
311
- );
312
- },
313
- }),
314
- arrow &&
315
- floatingArrow({ element: arrow, padding: arrowDefaults.padding }),
316
- transformOrigin({ arrowWidth, arrowHeight }),
317
- hideWhenDetached &&
318
- hide({ strategy: "referenceHidden", ...detectOverflowOptions }),
319
- ],
320
- });
313
+ avoidCollisions && flip({ ...detectOverflowOptions }),
314
+ size({
315
+ ...detectOverflowOptions,
316
+ apply: ({ elements, rects, availableWidth, availableHeight }) => {
317
+ const { width: anchorWidth, height: anchorHeight } =
318
+ rects.reference;
319
+ const contentStyle = elements.floating.style;
320
+ /**
321
+ * Allows styling and animations based on the available space.
322
+ */
323
+ contentStyle.setProperty(
324
+ "--ac-floating-available-width",
325
+ `${availableWidth}px`,
326
+ );
327
+ contentStyle.setProperty(
328
+ "--ac-floating-available-height",
329
+ `${availableHeight}px`,
330
+ );
331
+ contentStyle.setProperty(
332
+ "--ac-floating-anchor-width",
333
+ `${anchorWidth}px`,
334
+ );
335
+ contentStyle.setProperty(
336
+ "--ac-floating-anchor-height",
337
+ `${anchorHeight}px`,
338
+ );
339
+ },
340
+ }),
341
+ arrow &&
342
+ floatingArrow({ element: arrow, padding: arrowDefaults.padding }),
343
+ transformOrigin({ arrowWidth, arrowHeight }),
344
+ hideWhenDetached &&
345
+ hide({ strategy: "referenceHidden", ...detectOverflowOptions }),
346
+ ],
347
+ });
348
+
349
+ useEffect(() => {
350
+ if (autoUpdateWhileMounted || !enabled) {
351
+ return;
352
+ }
353
+ if (floatingElements.reference && floatingElements.floating) {
354
+ const cleanup = autoUpdate(
355
+ floatingElements.reference,
356
+ floatingElements.floating,
357
+ update,
358
+ );
359
+
360
+ return () => {
361
+ cleanup();
362
+ };
363
+ }
364
+ }, [autoUpdateWhileMounted, enabled, floatingElements, update]);
365
+
366
+ useOpenChangeAnimationComplete({
367
+ enabled: !!modalContext?.ref,
368
+ open: enabled,
369
+ ref: modalContext?.ref,
370
+ onComplete: update,
371
+ });
321
372
 
322
373
  const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);
323
374
 
@@ -0,0 +1,117 @@
1
+ "use client";
2
+
3
+ import React, { useCallback, useEffect } from "react";
4
+ import ReactDOM from "react-dom";
5
+ import { useEventCallback } from "./useEventCallback";
6
+
7
+ /**
8
+ * Returns a stable function that, when invoked, waits for all current CSS/Web Animations
9
+ * on a target element (and its subtree) to finish before executing a callback.
10
+ *
11
+ * Why:
12
+ * - Coordinate logic (unmount, focus restore, measuring) after exit / enter animations.
13
+ * - Avoid `animationend` event bookkeeping across multiple animations / nested elements.
14
+ * - Batch detection using `requestAnimationFrame` so freshly-applied animations are discoverable.
15
+ *
16
+ * Mechanics:
17
+ * 1. Resolves the concrete `HTMLElement` (direct element or from ref) – early no-op if missing.
18
+ * 2. If `getAnimations` is unsupported or animations are globally disabled (`AKSEL_ANIMATIONS_DISABLED`),
19
+ * runs the callback immediately.
20
+ * 3. Schedules a frame so style/animation changes applied this render are committed.
21
+ * 4. Optionally schedules an additional frame (`waitForNextTick=true`) to catch animations that
22
+ * start only after layout (e.g. when an `open` class triggers the animation).
23
+ * 5. Captures all current animations, waits on their `.finished` promises (using `Promise.allSettled`
24
+ * so rejections don't block), then `flushSync` executes the callback (ensures React state updates
25
+ * inside run before the browser paints the next frame).
26
+ * 6. If an `AbortSignal` aborts while waiting, it silently cancels execution.
27
+ *
28
+ * @param elementOrRef HTMLElement or ref to observe.
29
+ * @param waitForNextTick If true, waits an extra frame to ensure enter animations are detectable.
30
+ * @returns Stable function (identity preserved) accepting (fn, abortSignal?).
31
+ */
32
+ export function useAnimationsFinished(
33
+ elementOrRef: React.RefObject<HTMLElement | null> | HTMLElement | null,
34
+ waitForNextTick = false,
35
+ ) {
36
+ const rootFrameRef = React.useRef<number | null>(null);
37
+ const nestedFrameRef = React.useRef<number | null>(null);
38
+
39
+ const cancelScheduled = useCallback(() => {
40
+ for (const ref of [rootFrameRef, nestedFrameRef]) {
41
+ if (ref.current !== null) {
42
+ cancelAnimationFrame(ref.current);
43
+ ref.current = null;
44
+ }
45
+ }
46
+ }, []);
47
+
48
+ /* Unmount cleanup */
49
+ useEffect(() => {
50
+ return () => cancelScheduled();
51
+ }, [cancelScheduled]);
52
+
53
+ return useEventCallback(
54
+ (
55
+ /**
56
+ * A function to execute once all animations have finished.
57
+ */
58
+ fnToExecute: () => void,
59
+ /**
60
+ * An optional [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that
61
+ * can be used to abort `fnToExecute` before all the animations have finished.
62
+ * @default null
63
+ */
64
+ signal: AbortSignal | null = null,
65
+ ) => {
66
+ // Cancel any in-flight scheduling from a previous invocation (next-frame debounce semantics)
67
+ cancelScheduled();
68
+
69
+ if (elementOrRef == null) {
70
+ return;
71
+ }
72
+
73
+ const element =
74
+ "current" in elementOrRef ? elementOrRef.current : elementOrRef;
75
+ if (element == null) {
76
+ return;
77
+ }
78
+
79
+ // Fast path: no Web Animations API support OR animations globally disabled.
80
+ if (
81
+ typeof element.getAnimations !== "function" ||
82
+ // Flag hook for test envs.
83
+ (globalThis as any).AKSEL_ANIMATIONS_DISABLED
84
+ ) {
85
+ fnToExecute();
86
+ return;
87
+ }
88
+
89
+ rootFrameRef.current = requestAnimationFrame(() => {
90
+ function exec() {
91
+ if (!element) {
92
+ return;
93
+ }
94
+ // Collect animations present at this moment; we don't continuously observe
95
+ // if new animations start after these settle, caller should invoke again.
96
+ Promise.allSettled(
97
+ element.getAnimations().map((anim) => anim.finished),
98
+ ).then(() => {
99
+ if (signal?.aborted) return;
100
+ // Ensure any state updates inside the callback are flushed synchronously,
101
+ // guaranteeing that dependent logic observes the current
102
+ // tree rather than a stale in-progress update.
103
+ ReactDOM.flushSync(fnToExecute);
104
+ });
105
+ }
106
+
107
+ // Some animations (e.g. triggered by a class applied this same frame) only
108
+ // become observable after an extra frame; opt-in via flag.
109
+ if (waitForNextTick) {
110
+ nestedFrameRef.current = requestAnimationFrame(exec);
111
+ } else {
112
+ exec();
113
+ }
114
+ });
115
+ },
116
+ );
117
+ }
@@ -0,0 +1,73 @@
1
+ "use client";
2
+
3
+ /**
4
+ * Stable event callback: returns a function whose identity never changes but always
5
+ * invokes the latest `callback`. Avoids stale closures without re‑creating handlers.
6
+ *
7
+ * Why not `useCallback`? Its identity depends on a deps array:
8
+ * - omit deps -> stale; include deps -> new function each render.
9
+ * - This hook decouples identity from freshness.
10
+ *
11
+ * How it works: a single stable "trampoline" function delegates to a mutable ref. The current
12
+ * `callback` is promoted from `next` in an insertion/layout phase effect so abandoned concurrent
13
+ * renders cannot leak outdated handlers.
14
+ *
15
+ * Guarantees: stable identity; latest logic executed; no calls from uncommitted renders; dev
16
+ * error if invoked during render; safe when `callback` is undefined (no-op).
17
+ */
18
+ import React, { useLayoutEffect } from "react";
19
+ import { useRefWithInit } from "./useRefWithInit";
20
+
21
+ /* https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379 */
22
+ const useInsertionEffect = (React as any)[
23
+ `useInsertionEffect${Math.random().toFixed(1)}`.slice(0, -3)
24
+ ];
25
+
26
+ const useSafeInsertionEffect =
27
+ // React 17 doesn't have useInsertionEffect.
28
+ useInsertionEffect &&
29
+ // Preact replaces useInsertionEffect with useLayoutEffect and fires too late.
30
+ useInsertionEffect !== useLayoutEffect
31
+ ? useInsertionEffect
32
+ : (fn: any) => fn();
33
+
34
+ type Callback = (...args: any[]) => any;
35
+
36
+ type Stable<T extends Callback> = {
37
+ /** The next value for callback */
38
+ next: T | undefined;
39
+ /** The function to be called by trampoline. This must fail during the initial render phase. */
40
+ callback: T | undefined;
41
+ trampoline: T;
42
+ effect: () => void;
43
+ };
44
+
45
+ /**
46
+ * TODO: Long term, replace `useCallbackRef` with this hook.
47
+ */
48
+ export function useEventCallback<T extends Callback>(
49
+ callback: T | undefined,
50
+ ): T {
51
+ const stable = useRefWithInit(createStableCallback).current as Stable<T>;
52
+ stable.next = callback;
53
+ useSafeInsertionEffect(stable.effect);
54
+ return stable.trampoline;
55
+ }
56
+
57
+ function createStableCallback() {
58
+ const stable: Stable<Callback> = {
59
+ next: undefined,
60
+ callback: assertNotCalled,
61
+ trampoline: (...args: any[]) => stable.callback?.(...args),
62
+ effect: () => {
63
+ stable.callback = stable.next;
64
+ },
65
+ };
66
+ return stable;
67
+ }
68
+
69
+ function assertNotCalled() {
70
+ if (process.env.NODE_ENV !== "production") {
71
+ throw new Error("Aksel: Cannot call an event handler while rendering.");
72
+ }
73
+ }
@@ -0,0 +1,25 @@
1
+ "use client";
2
+
3
+ import { useClientLayoutEffect } from "../../../util";
4
+ import { useRefWithInit } from "./useRefWithInit";
5
+
6
+ export function useLatestRef<T>(value: T) {
7
+ const latest = useRefWithInit(createLatestRef, value).current!;
8
+
9
+ latest.next = value;
10
+
11
+ useClientLayoutEffect(latest.effect);
12
+
13
+ return latest;
14
+ }
15
+
16
+ function createLatestRef<T>(value: T) {
17
+ const latest = {
18
+ current: value,
19
+ next: value,
20
+ effect: () => {
21
+ latest.current = latest.next;
22
+ },
23
+ };
24
+ return latest;
25
+ }
@@ -0,0 +1,66 @@
1
+ "use client";
2
+
3
+ import React, { useEffect } from "react";
4
+ import { useAnimationsFinished } from "./useAnimationsFinished";
5
+ import { useEventCallback } from "./useEventCallback";
6
+ import { useLatestRef } from "./useLatestRef";
7
+
8
+ interface useOpenChangeAnimationCompleteParameters {
9
+ /**
10
+ * Enable / disable the effect. Disabled => no animation tracking / callback.
11
+ * @default true
12
+ */
13
+ enabled?: boolean;
14
+ /**
15
+ * Current open state (e.g. popover open). When this flips we wait for any
16
+ * associated CSS/Web animations on `ref` to finish before firing `onComplete`.
17
+ */
18
+ open?: boolean;
19
+ /**
20
+ * Element whose animations/transition we observe. Should be stable while the
21
+ * open/close animation runs (typically the root animated node).
22
+ */
23
+ ref?: React.RefObject<HTMLElement | null>;
24
+ /**
25
+ * Called exactly once per open-change cycle after animations finish OR
26
+ * immediately if animations are disabled / unsupported.
27
+ */
28
+ onComplete: () => void;
29
+ }
30
+
31
+ /**
32
+ * Waits for the element's current Web Animations / CSS transitions to finish after an
33
+ * `open` state change, then invokes `onComplete`. Guards against race conditions by
34
+ * comparing the `open` value captured at scheduling time with the latest `open` via ref;
35
+ * if they differ (state flipped again mid‑animation) the callback is skipped.
36
+ */
37
+ export function useOpenChangeAnimationComplete(
38
+ parameters: useOpenChangeAnimationCompleteParameters,
39
+ ) {
40
+ const {
41
+ enabled = true,
42
+ open,
43
+ ref = null,
44
+ onComplete: onCompleteParam,
45
+ } = parameters;
46
+
47
+ const openRef = useLatestRef(open);
48
+ const onComplete = useEventCallback(onCompleteParam);
49
+ const runOnceAnimationsFinish = useAnimationsFinished(ref, open);
50
+
51
+ useEffect(() => {
52
+ if (!enabled) {
53
+ return;
54
+ }
55
+
56
+ /*
57
+ * Schedule completion once the *current* set of animations settle. If during
58
+ * that wait `open` toggles again, skip to avoid firing for an outdated cycle.
59
+ */
60
+ runOnceAnimationsFinish(() => {
61
+ if (open === openRef.current) {
62
+ onComplete();
63
+ }
64
+ });
65
+ }, [enabled, open, onComplete, runOnceAnimationsFinish, openRef]);
66
+ }
@@ -0,0 +1,25 @@
1
+ "use client";
2
+
3
+ import React, { useRef } from "react";
4
+
5
+ const UNINITIALIZED = {};
6
+
7
+ /**
8
+ * useRef initialized with a function on mount.
9
+ */
10
+ function useRefWithInit<T>(init: () => T): React.RefObject<T>;
11
+ function useRefWithInit<T, U>(
12
+ init: (arg: U) => T,
13
+ initArg: U,
14
+ ): React.RefObject<T>;
15
+ function useRefWithInit(init: (arg?: unknown) => unknown, initArg?: unknown) {
16
+ const ref = useRef(UNINITIALIZED as any);
17
+
18
+ if (ref.current === UNINITIALIZED) {
19
+ ref.current = init(initArg);
20
+ }
21
+
22
+ return ref;
23
+ }
24
+
25
+ export { useRefWithInit };
@@ -0,0 +1,145 @@
1
+ "use client";
2
+
3
+ import { useMemo, useState } from "react";
4
+ import ReactDOM from "react-dom";
5
+ import { useClientLayoutEffect } from "../../../util";
6
+
7
+ type TransitionStatus = "entering" | "exiting" | "idle" | undefined;
8
+
9
+ /**
10
+ * Transition status state machine for components that animate between an
11
+ * `open` boolean and actual mount/unmount. Keeps the element mounted while
12
+ * exit animations run and introduces an optional stable `idle` phase.
13
+ *
14
+ * Adapted from MUI Base + Floating UI examples:
15
+ * - Source: https://github.com/mui/base-ui/blob/6fd69008d83561dbe75ff89acf270f0fac3e0049/packages/react/src/utils/useTransitionStatus.ts
16
+ * - Originally based on https://github.com/floating-ui/floating-ui/blob/7c33a3d0198a9b523d54ae2c37cedb315a309452/packages/react/src/hooks/useTransition.ts
17
+ *
18
+ * States (transitionStatus):
19
+ * - "entering" : just entered (initial frame of enter) OR re-entering to reach "idle".
20
+ * - "idle" : stable open (only when `enableIdleState === true`).
21
+ * - "exiting" : exit animation is running; element still mounted.
22
+ * - undefined : closed (unmounted) OR stable open when idle state is disabled.
23
+ * When `enableIdleState` is false we clear the label after
24
+ * the first frame so styling can rely purely on `mounted`.
25
+ *
26
+ * Distinction:
27
+ * - `mounted` tells you whether to render DOM.
28
+ * - `transitionStatus` tells you which phase-specific classes to apply.
29
+ *
30
+ * Frame separation: state changes that must trigger CSS transitions are
31
+ * scheduled with `requestAnimationFrame` so the browser sees distinct style
32
+ * mutations across frames (avoids missed transitions due to batching).
33
+ *
34
+ * @param open Controls visibility lifecycle.
35
+ * @param enableIdleState Insert a persistent "idle" phase after entering.
36
+ * @param deferExitingState Delay entering the exit phase by one frame to allow
37
+ * measurement / layout work before applying exit styles.
38
+ */
39
+ function useTransitionStatus(
40
+ open: boolean,
41
+ enableIdleState: boolean = false,
42
+ deferExitingState: boolean = false,
43
+ ) {
44
+ const [mounted, setMounted] = useState(open);
45
+ const [transitionStatus, setTransitionStatus] = useState<TransitionStatus>(
46
+ open && enableIdleState ? "idle" : undefined,
47
+ );
48
+
49
+ /* Opening: mount immediately and label as "entering" for the first frame. */
50
+ if (open && !mounted) {
51
+ setMounted(true);
52
+ setTransitionStatus("entering");
53
+ }
54
+
55
+ /* Closing (no defer): begin exit animation right away. */
56
+ if (
57
+ !open &&
58
+ mounted &&
59
+ transitionStatus !== "exiting" &&
60
+ !deferExitingState
61
+ ) {
62
+ setTransitionStatus("exiting");
63
+ }
64
+
65
+ /* Cleanup: after unmount post-exit ensure status returns to undefined. */
66
+ if (!open && !mounted && transitionStatus === "exiting") {
67
+ setTransitionStatus(undefined);
68
+ }
69
+
70
+ /* Deferred closing: provide one frame to measure / flush layout before exit styles. */
71
+ useClientLayoutEffect(() => {
72
+ if (
73
+ !open &&
74
+ mounted &&
75
+ transitionStatus !== "exiting" &&
76
+ deferExitingState
77
+ ) {
78
+ const frame = requestAnimationFrame(() => {
79
+ setTransitionStatus("exiting");
80
+ });
81
+
82
+ return () => {
83
+ cancelAnimationFrame(frame);
84
+ };
85
+ }
86
+
87
+ return undefined;
88
+ }, [open, mounted, transitionStatus, deferExitingState]);
89
+
90
+ /* Enter (no idle): hold "entering" for one frame, then clear label (stable open). */
91
+ useClientLayoutEffect(() => {
92
+ if (!open || enableIdleState) {
93
+ return undefined;
94
+ }
95
+
96
+ const frame = requestAnimationFrame(() => {
97
+ ReactDOM.flushSync(() => {
98
+ setTransitionStatus(undefined);
99
+ });
100
+ });
101
+
102
+ return () => {
103
+ cancelAnimationFrame(frame);
104
+ };
105
+ }, [enableIdleState, open]);
106
+
107
+ useClientLayoutEffect(() => {
108
+ if (!open || !enableIdleState) {
109
+ return undefined;
110
+ }
111
+
112
+ /*
113
+ * We can enter this state by re-opening before exiting-state was finished
114
+ * (open → close → open in quick succession).
115
+ */
116
+ if (open && mounted && transitionStatus !== "idle") {
117
+ setTransitionStatus("entering");
118
+ }
119
+
120
+ /**
121
+ * Next frame, after "entering", switch to persistent "idle" state.
122
+ * By delaying to the next frame we ensure any "entering" styles are
123
+ * applied and the transition can run.
124
+ */
125
+ const frame = requestAnimationFrame(() => {
126
+ setTransitionStatus("idle");
127
+ });
128
+
129
+ return () => {
130
+ cancelAnimationFrame(frame);
131
+ };
132
+ }, [enableIdleState, open, mounted, setTransitionStatus, transitionStatus]);
133
+
134
+ return useMemo(
135
+ () => ({
136
+ mounted,
137
+ setMounted,
138
+ transitionStatus,
139
+ }),
140
+ [mounted, transitionStatus],
141
+ );
142
+ }
143
+
144
+ export { useTransitionStatus };
145
+ export type { TransitionStatus };
@@ -95,7 +95,7 @@ export const ProgressBar = forwardRef<HTMLDivElement, ProgressBarProps>(
95
95
  ) => {
96
96
  const { cn } = useRenameCSS();
97
97
  const translateX = 100 - (Math.round(value) / valueMax) * 100;
98
- const onTimeoutRef = useRef<() => void>();
98
+ const onTimeoutRef = useRef<() => void>(undefined);
99
99
  onTimeoutRef.current = simulated?.onTimeout;
100
100
  const translate = useI18n("ProgressBar");
101
101