@intlayer/design-system 9.3.2 → 9.4.0-canary.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 (187) hide show
  1. package/README.md +1 -1
  2. package/dist/esm/api/hooks/analytics.mjs +6 -5
  3. package/dist/esm/api/hooks/analytics.mjs.map +1 -1
  4. package/dist/esm/api/hooks/auth.mjs +2 -0
  5. package/dist/esm/api/hooks/auth.mjs.map +1 -1
  6. package/dist/esm/api/index.mjs +2 -2
  7. package/dist/esm/api/useAuth/useOAuth2.mjs +1 -1
  8. package/dist/esm/api/useAuth/useSession.mjs +1 -1
  9. package/dist/esm/components/Accordion/Accordion.mjs +2 -2
  10. package/dist/esm/components/Accordion/Accordion.mjs.map +1 -1
  11. package/dist/esm/components/Browser/Browser.mjs +1 -1
  12. package/dist/esm/components/Browser/Browser.mjs.map +1 -1
  13. package/dist/esm/components/ContentEditor/ContentEditorTextArea.mjs +1 -1
  14. package/dist/esm/components/CopyButton/index.mjs +2 -1
  15. package/dist/esm/components/CopyButton/index.mjs.map +1 -1
  16. package/dist/esm/components/DictionaryFieldEditor/ContentEditor.mjs +4 -5
  17. package/dist/esm/components/DictionaryFieldEditor/ContentEditor.mjs.map +1 -1
  18. package/dist/esm/components/DictionaryFieldEditor/ContentEditorView/TextEditor.mjs +6 -10
  19. package/dist/esm/components/DictionaryFieldEditor/ContentEditorView/TextEditor.mjs.map +1 -1
  20. package/dist/esm/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.mjs +1 -1
  21. package/dist/esm/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.mjs +6 -6
  22. package/dist/esm/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.mjs.map +1 -1
  23. package/dist/esm/components/DictionaryFieldEditor/DictionaryFieldEditor.mjs +3 -7
  24. package/dist/esm/components/DictionaryFieldEditor/DictionaryFieldEditor.mjs.map +1 -1
  25. package/dist/esm/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.mjs +1 -1
  26. package/dist/esm/components/DictionaryFieldEditor/SaveForm/SaveForm.mjs +2 -2
  27. package/dist/esm/components/DictionaryFieldEditor/StructureView/StructureView.mjs +1 -1
  28. package/dist/esm/components/ExpandCollapse/ExpandCollapse.mjs +19 -12
  29. package/dist/esm/components/ExpandCollapse/ExpandCollapse.mjs.map +1 -1
  30. package/dist/esm/components/Form/elements/OTPElement.mjs +4 -4
  31. package/dist/esm/components/Form/elements/OTPElement.mjs.map +1 -1
  32. package/dist/esm/components/HTMLRender/HTMLRender.mjs +2 -2
  33. package/dist/esm/components/HTMLRender/HTMLRender.mjs.map +1 -1
  34. package/dist/esm/components/IDE/Code.mjs +3 -3
  35. package/dist/esm/components/IDE/Code.mjs.map +1 -1
  36. package/dist/esm/components/IDE/CodeBlockClient.mjs +16 -4
  37. package/dist/esm/components/IDE/CodeBlockClient.mjs.map +1 -1
  38. package/dist/esm/components/IDE/CodeBlockHighlight.mjs +14 -5
  39. package/dist/esm/components/IDE/CodeBlockHighlight.mjs.map +1 -1
  40. package/dist/esm/components/IDE/CodeBlockServer.mjs +5 -3
  41. package/dist/esm/components/IDE/CodeBlockServer.mjs.map +1 -1
  42. package/dist/esm/components/IDE/CodeBlockShiki.mjs +18 -18
  43. package/dist/esm/components/IDE/CodeBlockShiki.mjs.map +1 -1
  44. package/dist/esm/components/IDE/IDE.mjs +2 -5
  45. package/dist/esm/components/IDE/IDE.mjs.map +1 -1
  46. package/dist/esm/components/IDE/MarkDownRender.mjs +1 -2
  47. package/dist/esm/components/IDE/MarkDownRender.mjs.map +1 -1
  48. package/dist/esm/components/IDE/index.mjs +2 -2
  49. package/dist/esm/components/IDE/shikiThemes.mjs +18 -0
  50. package/dist/esm/components/IDE/shikiThemes.mjs.map +1 -0
  51. package/dist/esm/components/Link/Link.mjs +10 -5
  52. package/dist/esm/components/Link/Link.mjs.map +1 -1
  53. package/dist/esm/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.mjs +1 -1
  54. package/dist/esm/components/MarkDownRender/MarkDownIframe.mjs +105 -4
  55. package/dist/esm/components/MarkDownRender/MarkDownIframe.mjs.map +1 -1
  56. package/dist/esm/components/MarkDownRender/MarkDownRender.mjs +16 -16
  57. package/dist/esm/components/MarkDownRender/MarkDownRender.mjs.map +1 -1
  58. package/dist/esm/components/MaxHeightSmoother/index.mjs +1 -1
  59. package/dist/esm/components/MaxHeightSmoother/index.mjs.map +1 -1
  60. package/dist/esm/components/MaxWidthSmoother/index.mjs +1 -1
  61. package/dist/esm/components/MaxWidthSmoother/index.mjs.map +1 -1
  62. package/dist/esm/components/Modal/Modal.mjs +2 -2
  63. package/dist/esm/components/Navbar/MobileNavbar.mjs +1 -1
  64. package/dist/esm/components/Pagination/Pagination.mjs +4 -4
  65. package/dist/esm/components/Pagination/Pagination.mjs.map +1 -1
  66. package/dist/esm/components/Pattern/GridDistortionPattern.mjs +103 -17
  67. package/dist/esm/components/Pattern/GridDistortionPattern.mjs.map +1 -1
  68. package/dist/esm/components/Popover/dynamic.mjs +73 -28
  69. package/dist/esm/components/Popover/dynamic.mjs.map +1 -1
  70. package/dist/esm/components/Popover/index.mjs +2 -2
  71. package/dist/esm/components/Popover/static.mjs +47 -18
  72. package/dist/esm/components/Popover/static.mjs.map +1 -1
  73. package/dist/esm/components/RightDrawer/RightDrawer.mjs +5 -4
  74. package/dist/esm/components/RightDrawer/RightDrawer.mjs.map +1 -1
  75. package/dist/esm/components/SwitchSelector/useSwitchSelector.mjs +2 -2
  76. package/dist/esm/components/SwitchSelector/useSwitchSelector.mjs.map +1 -1
  77. package/dist/esm/components/Tab/Tab.mjs +38 -17
  78. package/dist/esm/components/Tab/Tab.mjs.map +1 -1
  79. package/dist/esm/components/TabSelector/TabSelector.mjs +2 -2
  80. package/dist/esm/components/TabSelector/TabSelector.mjs.map +1 -1
  81. package/dist/esm/components/TextArea/AutoSizeTextArea.mjs +3 -2
  82. package/dist/esm/components/TextArea/AutoSizeTextArea.mjs.map +1 -1
  83. package/dist/esm/components/ThemeSwitcherDropDown/DesktopThemeSwitcher.mjs +10 -18
  84. package/dist/esm/components/ThemeSwitcherDropDown/DesktopThemeSwitcher.mjs.map +1 -1
  85. package/dist/esm/components/ThemeSwitcherDropDown/MobileThemeSwitcher.mjs +14 -13
  86. package/dist/esm/components/ThemeSwitcherDropDown/MobileThemeSwitcher.mjs.map +1 -1
  87. package/dist/esm/components/index.mjs +3 -3
  88. package/dist/esm/hooks/index.mjs +9 -9
  89. package/dist/esm/hooks/useDevice.mjs +16 -6
  90. package/dist/esm/hooks/useDevice.mjs.map +1 -1
  91. package/dist/esm/hooks/useItemSelector.mjs +110 -112
  92. package/dist/esm/hooks/useItemSelector.mjs.map +1 -1
  93. package/dist/esm/hooks/useScrollY.mjs +64 -45
  94. package/dist/esm/hooks/useScrollY.mjs.map +1 -1
  95. package/dist/esm/hooks/useStickToBottom.mjs +69 -0
  96. package/dist/esm/hooks/useStickToBottom.mjs.map +1 -0
  97. package/dist/esm/libs/auth.mjs +16 -3
  98. package/dist/esm/libs/auth.mjs.map +1 -1
  99. package/dist/esm/providers/ThemeProvider.mjs +143 -0
  100. package/dist/esm/providers/ThemeProvider.mjs.map +1 -0
  101. package/dist/esm/providers/index.mjs +2 -1
  102. package/dist/esm/routes.mjs +2 -1
  103. package/dist/esm/routes.mjs.map +1 -1
  104. package/dist/esm/structured-data/buildCreativeWorkJsonLd.mjs +1 -1
  105. package/dist/esm/structured-data/buildCreativeWorkJsonLd.mjs.map +1 -1
  106. package/dist/esm/utils/index.mjs +3 -1
  107. package/dist/esm/utils/observeScrollExtent.mjs +39 -0
  108. package/dist/esm/utils/observeScrollExtent.mjs.map +1 -0
  109. package/dist/esm/utils/scheduleFrameTask.mjs +44 -0
  110. package/dist/esm/utils/scheduleFrameTask.mjs.map +1 -0
  111. package/dist/types/api/hooks/analytics.d.ts +5 -3
  112. package/dist/types/api/hooks/analytics.d.ts.map +1 -1
  113. package/dist/types/api/hooks/auth.d.ts.map +1 -1
  114. package/dist/types/components/Browser/Browser.d.ts +7 -1
  115. package/dist/types/components/Browser/Browser.d.ts.map +1 -1
  116. package/dist/types/components/CopyButton/index.d.ts +9 -3
  117. package/dist/types/components/CopyButton/index.d.ts.map +1 -1
  118. package/dist/types/components/DictionaryFieldEditor/ContentEditor.d.ts +0 -1
  119. package/dist/types/components/DictionaryFieldEditor/ContentEditor.d.ts.map +1 -1
  120. package/dist/types/components/DictionaryFieldEditor/ContentEditorView/TextEditor.d.ts +0 -1
  121. package/dist/types/components/DictionaryFieldEditor/ContentEditorView/TextEditor.d.ts.map +1 -1
  122. package/dist/types/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.d.ts +0 -1
  123. package/dist/types/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.d.ts.map +1 -1
  124. package/dist/types/components/ExpandCollapse/ExpandCollapse.d.ts.map +1 -1
  125. package/dist/types/components/HTMLRender/HTMLRender.d.ts +1 -2
  126. package/dist/types/components/HTMLRender/HTMLRender.d.ts.map +1 -1
  127. package/dist/types/components/IDE/Code.d.ts +6 -1
  128. package/dist/types/components/IDE/Code.d.ts.map +1 -1
  129. package/dist/types/components/IDE/CodeBlockClient.d.ts +18 -2
  130. package/dist/types/components/IDE/CodeBlockClient.d.ts.map +1 -1
  131. package/dist/types/components/IDE/CodeBlockHighlight.d.ts +3 -2
  132. package/dist/types/components/IDE/CodeBlockHighlight.d.ts.map +1 -1
  133. package/dist/types/components/IDE/CodeBlockServer.d.ts +0 -1
  134. package/dist/types/components/IDE/CodeBlockServer.d.ts.map +1 -1
  135. package/dist/types/components/IDE/CodeBlockShiki.d.ts +0 -1
  136. package/dist/types/components/IDE/CodeBlockShiki.d.ts.map +1 -1
  137. package/dist/types/components/IDE/IDE.d.ts +0 -1
  138. package/dist/types/components/IDE/IDE.d.ts.map +1 -1
  139. package/dist/types/components/IDE/MarkDownRender.d.ts +0 -1
  140. package/dist/types/components/IDE/MarkDownRender.d.ts.map +1 -1
  141. package/dist/types/components/IDE/index.d.ts +2 -2
  142. package/dist/types/components/IDE/shikiThemes.d.ts +18 -0
  143. package/dist/types/components/IDE/shikiThemes.d.ts.map +1 -0
  144. package/dist/types/components/MarkDownRender/MarkDownIframe.d.ts.map +1 -1
  145. package/dist/types/components/MarkDownRender/MarkDownRender.d.ts +1 -2
  146. package/dist/types/components/MarkDownRender/MarkDownRender.d.ts.map +1 -1
  147. package/dist/types/components/Pattern/GridDistortionPattern.d.ts.map +1 -1
  148. package/dist/types/components/Popover/dynamic.d.ts.map +1 -1
  149. package/dist/types/components/Popover/index.d.ts +2 -2
  150. package/dist/types/components/Popover/static.d.ts +6 -1
  151. package/dist/types/components/Popover/static.d.ts.map +1 -1
  152. package/dist/types/components/Tab/Tab.d.ts +2 -2
  153. package/dist/types/components/Tab/Tab.d.ts.map +1 -1
  154. package/dist/types/components/ThemeSwitcherDropDown/DesktopThemeSwitcher.d.ts +1 -1
  155. package/dist/types/components/ThemeSwitcherDropDown/DesktopThemeSwitcher.d.ts.map +1 -1
  156. package/dist/types/components/ThemeSwitcherDropDown/MobileThemeSwitcher.d.ts +1 -1
  157. package/dist/types/components/ThemeSwitcherDropDown/MobileThemeSwitcher.d.ts.map +1 -1
  158. package/dist/types/components/ThemeSwitcherDropDown/types.d.ts +3 -1
  159. package/dist/types/components/ThemeSwitcherDropDown/types.d.ts.map +1 -1
  160. package/dist/types/components/index.d.ts +3 -3
  161. package/dist/types/hooks/index.d.ts +2 -2
  162. package/dist/types/hooks/useItemSelector.d.ts +2 -0
  163. package/dist/types/hooks/useItemSelector.d.ts.map +1 -1
  164. package/dist/types/hooks/useScrollY.d.ts +10 -0
  165. package/dist/types/hooks/useScrollY.d.ts.map +1 -1
  166. package/dist/types/hooks/useStickToBottom.d.ts +41 -0
  167. package/dist/types/hooks/useStickToBottom.d.ts.map +1 -0
  168. package/dist/types/libs/auth.d.ts +3 -0
  169. package/dist/types/libs/auth.d.ts.map +1 -1
  170. package/dist/types/providers/ThemeProvider.d.ts +41 -0
  171. package/dist/types/providers/ThemeProvider.d.ts.map +1 -0
  172. package/dist/types/providers/index.d.ts +2 -1
  173. package/dist/types/routes.d.ts +2 -1
  174. package/dist/types/routes.d.ts.map +1 -1
  175. package/dist/types/structured-data/buildCreativeWorkJsonLd.d.ts +9 -3
  176. package/dist/types/structured-data/buildCreativeWorkJsonLd.d.ts.map +1 -1
  177. package/dist/types/utils/index.d.ts +3 -1
  178. package/dist/types/utils/observeScrollExtent.d.ts +22 -0
  179. package/dist/types/utils/observeScrollExtent.d.ts.map +1 -0
  180. package/dist/types/utils/scheduleFrameTask.d.ts +25 -0
  181. package/dist/types/utils/scheduleFrameTask.d.ts.map +1 -0
  182. package/package.json +46 -41
  183. package/tailwind.css +27 -1
  184. package/dist/esm/hooks/useIsDarkMode.mjs +0 -17
  185. package/dist/esm/hooks/useIsDarkMode.mjs.map +0 -1
  186. package/dist/types/hooks/useIsDarkMode.d.ts +0 -5
  187. package/dist/types/hooks/useIsDarkMode.d.ts.map +0 -1
@@ -1,161 +1,159 @@
1
1
  'use client';
2
2
 
3
- import { useLayoutEffect, useRef, useState } from "react";
3
+ import { scheduleFrameTask } from "../utils/scheduleFrameTask.mjs";
4
+ import { useCallback, useEffect, useRef, useState } from "react";
4
5
 
5
6
  //#region src/hooks/useItemSelector.ts
6
7
  const selectorDefault = (option) => option?.getAttribute("aria-selected") === "true";
8
+ /** Attributes whose change moves the indicator to another option. */
9
+ const WATCHED_ATTRIBUTES = [
10
+ "aria-selected",
11
+ "data-active",
12
+ "data-indicator"
13
+ ];
14
+ /** Delay before the indicator leaves the option the pointer just left. */
15
+ const HOVER_RELEASE_DELAY = 150;
7
16
  const useItemSelector = (optionsRefs, { selector = selectorDefault, isHoverable = false, orientation = "horizontal" } = {
8
17
  selector: selectorDefault,
9
18
  isHoverable: false,
10
19
  orientation: "horizontal"
11
20
  }) => {
12
21
  const [choiceIndicatorPosition, setChoiceIndicatorPosition] = useState(null);
13
- const [hoveredItem, setHoveredItem] = useState(null);
22
+ const hoveredItemRef = useRef(null);
14
23
  const hideTimeoutRef = useRef(null);
15
24
  const lastPositionRef = useRef(null);
25
+ const cancelMeasurementRef = useRef(null);
26
+ const selectorRef = useRef(selector);
27
+ selectorRef.current = selector;
28
+ const orientationRef = useRef(orientation);
29
+ orientationRef.current = orientation;
16
30
  const itemsLength = optionsRefs.current.length;
17
- const calculatePosition = () => {
18
- let targetElement = null;
19
- if (hoveredItem) {
20
- targetElement = hoveredItem;
21
- if (hideTimeoutRef.current) {
22
- clearTimeout(hideTimeoutRef.current);
23
- hideTimeoutRef.current = null;
24
- }
25
- } else targetElement = optionsRefs.current.find(selector) ?? null;
31
+ const calculatePosition = useCallback(() => {
32
+ const targetElement = hoveredItemRef.current ?? optionsRefs.current.find(selectorRef.current) ?? null;
33
+ if (hoveredItemRef.current && hideTimeoutRef.current) {
34
+ clearTimeout(hideTimeoutRef.current);
35
+ hideTimeoutRef.current = null;
36
+ }
37
+ const isVertical = orientationRef.current === "vertical";
26
38
  if (!targetElement) {
27
- if (orientation === "vertical") {
28
- const verticalPrev = lastPositionRef.current;
29
- const newPosition = {
30
- top: verticalPrev?.top ?? 0,
31
- height: verticalPrev?.height ?? 0,
32
- opacity: 0
33
- };
34
- if (verticalPrev?.opacity !== 0) {
35
- setChoiceIndicatorPosition(newPosition);
36
- lastPositionRef.current = newPosition;
37
- }
38
- } else {
39
- const horizontalPrev = lastPositionRef.current;
40
- const newPosition = {
41
- left: horizontalPrev?.left ?? 0,
42
- width: horizontalPrev?.width ?? 0,
43
- opacity: 0
44
- };
45
- if (horizontalPrev?.opacity !== 0) {
46
- setChoiceIndicatorPosition(newPosition);
47
- lastPositionRef.current = newPosition;
48
- }
49
- }
39
+ if (lastPositionRef.current?.opacity === 0) return;
40
+ const newPosition = isVertical ? {
41
+ top: lastPositionRef.current?.top ?? 0,
42
+ height: lastPositionRef.current?.height ?? 0,
43
+ opacity: 0
44
+ } : {
45
+ left: lastPositionRef.current?.left ?? 0,
46
+ width: lastPositionRef.current?.width ?? 0,
47
+ opacity: 0
48
+ };
49
+ setChoiceIndicatorPosition(newPosition);
50
+ lastPositionRef.current = newPosition;
50
51
  return;
51
52
  }
52
- if (orientation === "vertical") {
53
+ if (isVertical) {
53
54
  const top = targetElement.offsetTop;
54
55
  const height = targetElement.offsetHeight;
56
+ const previous = lastPositionRef.current;
57
+ if (previous?.top === top && previous.height === height && previous.opacity === 1) return;
55
58
  const newPosition = {
56
59
  top,
57
60
  height,
58
61
  opacity: 1
59
62
  };
60
- const prev = lastPositionRef.current;
61
- if (!prev || prev.top !== top || prev.height !== height || prev.opacity !== 1) {
62
- setChoiceIndicatorPosition(newPosition);
63
- lastPositionRef.current = newPosition;
64
- }
65
- } else {
66
- const left = targetElement.offsetLeft;
67
- const width = targetElement.offsetWidth;
68
- const newPosition = {
69
- left,
70
- width,
71
- opacity: 1
72
- };
73
- const prev = lastPositionRef.current;
74
- if (!prev || prev.left !== left || prev.width !== width || prev.opacity !== 1) {
75
- setChoiceIndicatorPosition(newPosition);
76
- lastPositionRef.current = newPosition;
77
- }
63
+ setChoiceIndicatorPosition(newPosition);
64
+ lastPositionRef.current = newPosition;
65
+ return;
78
66
  }
79
- };
80
- useLayoutEffect(() => {
81
- calculatePosition();
82
- window.addEventListener("resize", calculatePosition);
83
- window.addEventListener("DOMContentLoaded", calculatePosition);
84
- const mutationObservers = [];
85
- optionsRefs.current.forEach((option) => {
86
- if (option) {
87
- const observer = new MutationObserver((mutations) => {
88
- for (const mutation of mutations) if (mutation.type === "attributes" && (mutation.attributeName === "aria-selected" || mutation.attributeName === "data-active" || mutation.attributeName === "data-indicator")) {
89
- calculatePosition();
90
- break;
91
- }
92
- });
93
- observer.observe(option, {
94
- attributes: true,
95
- attributeFilter: [
96
- "aria-selected",
97
- "data-active",
98
- "data-indicator"
99
- ]
100
- });
101
- mutationObservers.push(observer);
102
- }
103
- });
104
- const resizeObservers = [];
105
- const observeSize = (element) => {
106
- if (!element) return;
107
- const resizeObserver = new ResizeObserver(() => {
108
- calculatePosition();
109
- });
110
- resizeObserver.observe(element);
111
- resizeObservers.push(resizeObserver);
67
+ const left = targetElement.offsetLeft;
68
+ const width = targetElement.offsetWidth;
69
+ const previous = lastPositionRef.current;
70
+ if (previous?.left === left && previous.width === width && previous.opacity === 1) return;
71
+ const newPosition = {
72
+ left,
73
+ width,
74
+ opacity: 1
112
75
  };
113
- const selectedItem = optionsRefs.current.find(selector) ?? null;
114
- if (selectedItem) observeSize(selectedItem);
115
- if (hoveredItem) observeSize(hoveredItem);
76
+ setChoiceIndicatorPosition(newPosition);
77
+ lastPositionRef.current = newPosition;
78
+ }, [optionsRefs]);
79
+ /**
80
+ * Defers the measurement to the next frame, and to a single one however many
81
+ * observers fire.
82
+ *
83
+ * Reading `offsetLeft` straight from a mutation, resize or scroll callback
84
+ * forces a synchronous reflow, and a documentation page mounts one selector
85
+ * per tab group and one per code block. The frame is shared with every other
86
+ * selector on the page, so React commits their positions in one pass instead
87
+ * of invalidating layout between two measurements.
88
+ */
89
+ const scheduleMeasurement = useCallback(() => {
90
+ if (cancelMeasurementRef.current !== null) return;
91
+ cancelMeasurementRef.current = scheduleFrameTask(() => {
92
+ cancelMeasurementRef.current = null;
93
+ calculatePosition();
94
+ });
95
+ }, [calculatePosition]);
96
+ useEffect(() => {
97
+ scheduleMeasurement();
98
+ window.addEventListener("resize", scheduleMeasurement, { passive: true });
99
+ window.addEventListener("DOMContentLoaded", scheduleMeasurement);
100
+ const options = optionsRefs.current.filter(Boolean);
101
+ const mutationObserver = new MutationObserver(scheduleMeasurement);
102
+ const resizeObserver = new ResizeObserver(scheduleMeasurement);
116
103
  const handleMouseEnter = (event) => {
117
104
  if (hideTimeoutRef.current) {
118
105
  clearTimeout(hideTimeoutRef.current);
119
106
  hideTimeoutRef.current = null;
120
107
  }
121
- setHoveredItem(event.currentTarget);
108
+ hoveredItemRef.current = event.currentTarget;
109
+ scheduleMeasurement();
122
110
  };
123
111
  const handleMouseLeave = () => {
124
112
  if (hideTimeoutRef.current) clearTimeout(hideTimeoutRef.current);
125
113
  hideTimeoutRef.current = setTimeout(() => {
126
- setHoveredItem(null);
127
- }, 150);
114
+ hoveredItemRef.current = null;
115
+ scheduleMeasurement();
116
+ }, HOVER_RELEASE_DELAY);
128
117
  };
129
- if (isHoverable) optionsRefs.current.forEach((option) => {
130
- option?.addEventListener("mouseenter", handleMouseEnter, { passive: true });
131
- option?.addEventListener("mouseleave", handleMouseLeave, { passive: true });
132
- });
133
- return () => {
134
- if (hideTimeoutRef.current) clearTimeout(hideTimeoutRef.current);
135
- window.removeEventListener("resize", calculatePosition);
136
- window.removeEventListener("DOMContentLoaded", calculatePosition);
137
- mutationObservers.forEach((observer) => {
138
- observer.disconnect();
139
- });
140
- resizeObservers.forEach((observer) => {
141
- observer.disconnect();
142
- });
143
- optionsRefs.current.forEach((option) => {
144
- option?.removeEventListener("mouseenter", handleMouseEnter);
145
- option?.removeEventListener("mouseleave", handleMouseLeave);
118
+ for (const option of options) {
119
+ mutationObserver.observe(option, {
120
+ attributes: true,
121
+ attributeFilter: WATCHED_ATTRIBUTES
146
122
  });
123
+ resizeObserver.observe(option);
124
+ if (isHoverable) {
125
+ option.addEventListener("mouseenter", handleMouseEnter, { passive: true });
126
+ option.addEventListener("mouseleave", handleMouseLeave, { passive: true });
127
+ }
128
+ }
129
+ return () => {
130
+ cancelMeasurementRef.current?.();
131
+ cancelMeasurementRef.current = null;
132
+ if (hideTimeoutRef.current) {
133
+ clearTimeout(hideTimeoutRef.current);
134
+ hideTimeoutRef.current = null;
135
+ }
136
+ window.removeEventListener("resize", scheduleMeasurement);
137
+ window.removeEventListener("DOMContentLoaded", scheduleMeasurement);
138
+ mutationObserver.disconnect();
139
+ resizeObserver.disconnect();
140
+ if (isHoverable) for (const option of options) {
141
+ option.removeEventListener("mouseenter", handleMouseEnter);
142
+ option.removeEventListener("mouseleave", handleMouseLeave);
143
+ }
147
144
  };
148
145
  }, [
149
146
  optionsRefs,
150
- selector,
151
- hoveredItem,
152
147
  itemsLength,
148
+ isHoverable,
153
149
  orientation,
154
- isHoverable
150
+ scheduleMeasurement
155
151
  ]);
156
152
  return {
157
153
  choiceIndicatorPosition,
154
+ /** Measures immediately. Prefer `scheduleMeasurement`, which does not force a reflow. */
158
155
  calculatePosition,
156
+ scheduleMeasurement,
159
157
  orientation
160
158
  };
161
159
  };
@@ -1 +1 @@
1
- {"version":3,"file":"useItemSelector.mjs","names":[],"sources":["../../../src/hooks/useItemSelector.ts"],"sourcesContent":["'use client';\n\nimport { type RefObject, useLayoutEffect, useRef, useState } from 'react';\n\nexport type ItemSelectorOrientation = 'horizontal' | 'vertical';\n\ntype HorizontalStyleState = {\n left: number;\n width: number;\n opacity: number;\n};\n\ntype VerticalStyleState = {\n top: number;\n height: number;\n opacity: number;\n};\n\ntype StyleState = HorizontalStyleState | VerticalStyleState;\n\nconst selectorDefault = (option: HTMLElement) =>\n option?.getAttribute('aria-selected') === 'true';\n\ntype Options = {\n selector?: (option: HTMLElement, index: number) => boolean;\n isHoverable?: boolean;\n orientation?: ItemSelectorOrientation;\n};\n\nexport const useItemSelector = (\n optionsRefs: RefObject<HTMLElement[]>,\n {\n selector = selectorDefault,\n isHoverable = false,\n orientation = 'horizontal',\n }: Options = {\n selector: selectorDefault,\n isHoverable: false,\n orientation: 'horizontal',\n }\n) => {\n const [choiceIndicatorPosition, setChoiceIndicatorPosition] =\n useState<StyleState | null>(null);\n\n const [hoveredItem, setHoveredItem] = useState<HTMLElement | null>(null);\n const hideTimeoutRef = useRef<NodeJS.Timeout | null>(null);\n const lastPositionRef = useRef<StyleState | null>(null);\n\n const itemsLength = optionsRefs.current.length;\n\n const calculatePosition = () => {\n let targetElement: HTMLElement | null = null;\n\n if (hoveredItem) {\n targetElement = hoveredItem;\n // Clear any pending hide timeout when hovering over an item\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n } else {\n targetElement = optionsRefs.current.find(selector) ?? null;\n }\n\n if (!targetElement) {\n // Keep previous position but set opacity to 0\n if (orientation === 'vertical') {\n const verticalPrev =\n lastPositionRef.current as VerticalStyleState | null;\n const newPosition: VerticalStyleState = {\n top: verticalPrev?.top ?? 0,\n height: verticalPrev?.height ?? 0,\n opacity: 0,\n };\n\n if (verticalPrev?.opacity !== 0) {\n setChoiceIndicatorPosition(newPosition);\n lastPositionRef.current = newPosition;\n }\n } else {\n const horizontalPrev =\n lastPositionRef.current as HorizontalStyleState | null;\n const newPosition: HorizontalStyleState = {\n left: horizontalPrev?.left ?? 0,\n width: horizontalPrev?.width ?? 0,\n opacity: 0,\n };\n\n if (horizontalPrev?.opacity !== 0) {\n setChoiceIndicatorPosition(newPosition);\n lastPositionRef.current = newPosition;\n }\n }\n return;\n }\n\n if (orientation === 'vertical') {\n const top = targetElement.offsetTop;\n const height = targetElement.offsetHeight;\n\n const newPosition = {\n top,\n height,\n opacity: 1,\n };\n\n const prev = lastPositionRef.current as VerticalStyleState | null;\n\n if (\n !prev ||\n prev.top !== top ||\n prev.height !== height ||\n prev.opacity !== 1\n ) {\n setChoiceIndicatorPosition(newPosition);\n lastPositionRef.current = newPosition;\n }\n } else {\n const left = targetElement.offsetLeft;\n const width = targetElement.offsetWidth;\n\n const newPosition = {\n left,\n width,\n opacity: 1,\n };\n\n const prev = lastPositionRef.current as HorizontalStyleState | null;\n\n if (\n !prev ||\n prev.left !== left ||\n prev.width !== width ||\n prev.opacity !== 1\n ) {\n setChoiceIndicatorPosition(newPosition);\n lastPositionRef.current = newPosition;\n }\n }\n };\n\n useLayoutEffect(() => {\n calculatePosition();\n\n // Event listeners for window events\n window.addEventListener('resize', calculatePosition);\n window.addEventListener('DOMContentLoaded', calculatePosition);\n\n // MutationObserver to watch for 'aria-selected' changes\n const mutationObservers: MutationObserver[] = [];\n\n optionsRefs.current.forEach((option) => {\n if (option) {\n const observer = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (\n mutation.type === 'attributes' &&\n (mutation.attributeName === 'aria-selected' ||\n mutation.attributeName === 'data-active' ||\n mutation.attributeName === 'data-indicator')\n ) {\n calculatePosition();\n break;\n }\n }\n });\n\n observer.observe(option, {\n attributes: true,\n attributeFilter: ['aria-selected', 'data-active', 'data-indicator'],\n });\n\n mutationObservers.push(observer);\n }\n });\n\n // ResizeObserver to watch for size changes\n const resizeObservers: ResizeObserver[] = [];\n\n const observeSize = (element: HTMLElement) => {\n if (!element) return;\n const resizeObserver = new ResizeObserver(() => {\n calculatePosition();\n });\n resizeObserver.observe(element);\n resizeObservers.push(resizeObserver);\n };\n\n // Observe the selected item\n const selectedItem = optionsRefs.current.find(selector) ?? null;\n\n if (selectedItem) {\n observeSize(selectedItem);\n }\n\n // Observe the hovered item\n if (hoveredItem) {\n observeSize(hoveredItem);\n }\n\n // Add hover event listeners\n const handleMouseEnter = (event: Event) => {\n // Clear any pending hide timeout\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n setHoveredItem(event.currentTarget as HTMLElement);\n };\n\n const handleMouseLeave = () => {\n // Clear any existing timeout\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n }\n\n // Keep the indicator at its current position for 150ms\n // before removing the hovered item\n hideTimeoutRef.current = setTimeout(() => {\n setHoveredItem(null);\n }, 150); // 150ms delay before hiding\n };\n\n if (isHoverable) {\n optionsRefs.current.forEach((option) => {\n option?.addEventListener('mouseenter', handleMouseEnter, {\n passive: true,\n });\n option?.addEventListener('mouseleave', handleMouseLeave, {\n passive: true,\n });\n });\n }\n\n return () => {\n // Clear any pending hide timeout\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n }\n\n // Cleanup window event listeners\n window.removeEventListener('resize', calculatePosition);\n window.removeEventListener('DOMContentLoaded', calculatePosition);\n\n // Disconnect MutationObservers\n mutationObservers.forEach((observer) => {\n observer.disconnect();\n });\n\n // Disconnect ResizeObservers\n resizeObservers.forEach((observer) => {\n observer.disconnect();\n });\n\n // Remove hover event listeners\n optionsRefs.current.forEach((option) => {\n option?.removeEventListener('mouseenter', handleMouseEnter);\n option?.removeEventListener('mouseleave', handleMouseLeave);\n });\n };\n }, [\n optionsRefs,\n selector,\n hoveredItem,\n itemsLength,\n orientation,\n isHoverable,\n ]);\n\n return { choiceIndicatorPosition, calculatePosition, orientation };\n};\n"],"mappings":";;;;;AAoBA,MAAM,mBAAmB,WACvB,QAAQ,aAAa,eAAe,MAAM;AAQ5C,MAAa,mBACX,aACA,EACE,WAAW,iBACX,cAAc,OACd,cAAc,iBACH;CACX,UAAU;CACV,aAAa;CACb,aAAa;AACf,MACG;CACH,MAAM,CAAC,yBAAyB,8BAC9B,SAA4B,IAAI;CAElC,MAAM,CAAC,aAAa,kBAAkB,SAA6B,IAAI;CACvE,MAAM,iBAAiB,OAA8B,IAAI;CACzD,MAAM,kBAAkB,OAA0B,IAAI;CAEtD,MAAM,cAAc,YAAY,QAAQ;CAExC,MAAM,0BAA0B;EAC9B,IAAI,gBAAoC;EAExC,IAAI,aAAa;GACf,gBAAgB;GAEhB,IAAI,eAAe,SAAS;IAC1B,aAAa,eAAe,OAAO;IACnC,eAAe,UAAU;GAC3B;EACF,OACE,gBAAgB,YAAY,QAAQ,KAAK,QAAQ,KAAK;EAGxD,IAAI,CAAC,eAAe;GAElB,IAAI,gBAAgB,YAAY;IAC9B,MAAM,eACJ,gBAAgB;IAClB,MAAM,cAAkC;KACtC,KAAK,cAAc,OAAO;KAC1B,QAAQ,cAAc,UAAU;KAChC,SAAS;IACX;IAEA,IAAI,cAAc,YAAY,GAAG;KAC/B,2BAA2B,WAAW;KACtC,gBAAgB,UAAU;IAC5B;GACF,OAAO;IACL,MAAM,iBACJ,gBAAgB;IAClB,MAAM,cAAoC;KACxC,MAAM,gBAAgB,QAAQ;KAC9B,OAAO,gBAAgB,SAAS;KAChC,SAAS;IACX;IAEA,IAAI,gBAAgB,YAAY,GAAG;KACjC,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;GACpB,CAAC;GACD,eAAe,QAAQ,OAAO;GAC9B,gBAAgB,KAAK,cAAc;EACrC;EAGA,MAAM,eAAe,YAAY,QAAQ,KAAK,QAAQ,KAAK;EAE3D,IAAI,cACF,YAAY,YAAY;EAI1B,IAAI,aACF,YAAY,WAAW;EAIzB,MAAM,oBAAoB,UAAiB;GAEzC,IAAI,eAAe,SAAS;IAC1B,aAAa,eAAe,OAAO;IACnC,eAAe,UAAU;GAC3B;GACA,eAAe,MAAM,aAA4B;EACnD;EAEA,MAAM,yBAAyB;GAE7B,IAAI,eAAe,SACjB,aAAa,eAAe,OAAO;GAKrC,eAAe,UAAU,iBAAiB;IACxC,eAAe,IAAI;GACrB,GAAG,GAAG;EACR;EAEA,IAAI,aACF,YAAY,QAAQ,SAAS,WAAW;GACtC,QAAQ,iBAAiB,cAAc,kBAAkB,EACvD,SAAS,KACX,CAAC;GACD,QAAQ,iBAAiB,cAAc,kBAAkB,EACvD,SAAS,KACX,CAAC;EACH,CAAC;EAGH,aAAa;GAEX,IAAI,eAAe,SACjB,aAAa,eAAe,OAAO;GAIrC,OAAO,oBAAoB,UAAU,iBAAiB;GACtD,OAAO,oBAAoB,oBAAoB,iBAAiB;GAGhE,kBAAkB,SAAS,aAAa;IACtC,SAAS,WAAW;GACtB,CAAC;GAGD,gBAAgB,SAAS,aAAa;IACpC,SAAS,WAAW;GACtB,CAAC;GAGD,YAAY,QAAQ,SAAS,WAAW;IACtC,QAAQ,oBAAoB,cAAc,gBAAgB;IAC1D,QAAQ,oBAAoB,cAAc,gBAAgB;GAC5D,CAAC;EACH;CACF,GAAG;EACD;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CAED,OAAO;EAAE;EAAyB;EAAmB;CAAY;AACnE"}
1
+ {"version":3,"file":"useItemSelector.mjs","names":[],"sources":["../../../src/hooks/useItemSelector.ts"],"sourcesContent":["'use client';\n\nimport { scheduleFrameTask } from '@utils/scheduleFrameTask';\nimport {\n type RefObject,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nexport type ItemSelectorOrientation = 'horizontal' | 'vertical';\n\ntype HorizontalStyleState = {\n left: number;\n width: number;\n opacity: number;\n};\n\ntype VerticalStyleState = {\n top: number;\n height: number;\n opacity: number;\n};\n\ntype StyleState = HorizontalStyleState | VerticalStyleState;\n\nconst selectorDefault = (option: HTMLElement) =>\n option?.getAttribute('aria-selected') === 'true';\n\n/** Attributes whose change moves the indicator to another option. */\nconst WATCHED_ATTRIBUTES = ['aria-selected', 'data-active', 'data-indicator'];\n\n/** Delay before the indicator leaves the option the pointer just left. */\nconst HOVER_RELEASE_DELAY = 150;\n\ntype Options = {\n selector?: (option: HTMLElement, index: number) => boolean;\n isHoverable?: boolean;\n orientation?: ItemSelectorOrientation;\n};\n\nexport const useItemSelector = (\n optionsRefs: RefObject<HTMLElement[]>,\n {\n selector = selectorDefault,\n isHoverable = false,\n orientation = 'horizontal',\n }: Options = {\n selector: selectorDefault,\n isHoverable: false,\n orientation: 'horizontal',\n }\n) => {\n const [choiceIndicatorPosition, setChoiceIndicatorPosition] =\n useState<StyleState | null>(null);\n\n const hoveredItemRef = useRef<HTMLElement | null>(null);\n const hideTimeoutRef = useRef<NodeJS.Timeout | null>(null);\n const lastPositionRef = useRef<StyleState | null>(null);\n const cancelMeasurementRef = useRef<(() => void) | null>(null);\n\n /*\n * Callers build their options object inline, so `selector` and `orientation`\n * are new values on every render. Reading them from refs keeps the observers\n * below from being torn down and rebuilt each time — a switch selector used\n * to re-subscribe one MutationObserver per option per render.\n */\n const selectorRef = useRef(selector);\n selectorRef.current = selector;\n\n const orientationRef = useRef(orientation);\n orientationRef.current = orientation;\n\n const itemsLength = optionsRefs.current.length;\n\n const calculatePosition = useCallback(() => {\n const targetElement =\n hoveredItemRef.current ??\n optionsRefs.current.find(selectorRef.current) ??\n null;\n\n if (hoveredItemRef.current && hideTimeoutRef.current) {\n // Clear any pending hide timeout when hovering over an item\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n\n const isVertical = orientationRef.current === 'vertical';\n\n if (!targetElement) {\n // Keep previous position but set opacity to 0\n if (lastPositionRef.current?.opacity === 0) return;\n\n const newPosition: StyleState = isVertical\n ? {\n top:\n (lastPositionRef.current as VerticalStyleState | null)?.top ?? 0,\n height:\n (lastPositionRef.current as VerticalStyleState | null)?.height ??\n 0,\n opacity: 0,\n }\n : {\n left:\n (lastPositionRef.current as HorizontalStyleState | null)?.left ??\n 0,\n width:\n (lastPositionRef.current as HorizontalStyleState | null)?.width ??\n 0,\n opacity: 0,\n };\n\n setChoiceIndicatorPosition(newPosition);\n lastPositionRef.current = newPosition;\n return;\n }\n\n if (isVertical) {\n const top = targetElement.offsetTop;\n const height = targetElement.offsetHeight;\n const previous = lastPositionRef.current as VerticalStyleState | null;\n\n if (\n previous?.top === top &&\n previous.height === height &&\n previous.opacity === 1\n ) {\n return;\n }\n\n const newPosition: VerticalStyleState = { top, height, opacity: 1 };\n\n setChoiceIndicatorPosition(newPosition);\n lastPositionRef.current = newPosition;\n return;\n }\n\n const left = targetElement.offsetLeft;\n const width = targetElement.offsetWidth;\n const previous = lastPositionRef.current as HorizontalStyleState | null;\n\n if (\n previous?.left === left &&\n previous.width === width &&\n previous.opacity === 1\n ) {\n return;\n }\n\n const newPosition: HorizontalStyleState = { left, width, opacity: 1 };\n\n setChoiceIndicatorPosition(newPosition);\n lastPositionRef.current = newPosition;\n }, [optionsRefs]);\n\n /**\n * Defers the measurement to the next frame, and to a single one however many\n * observers fire.\n *\n * Reading `offsetLeft` straight from a mutation, resize or scroll callback\n * forces a synchronous reflow, and a documentation page mounts one selector\n * per tab group and one per code block. The frame is shared with every other\n * selector on the page, so React commits their positions in one pass instead\n * of invalidating layout between two measurements.\n */\n const scheduleMeasurement = useCallback(() => {\n if (cancelMeasurementRef.current !== null) return;\n\n cancelMeasurementRef.current = scheduleFrameTask(() => {\n cancelMeasurementRef.current = null;\n calculatePosition();\n });\n }, [calculatePosition]);\n\n useEffect(() => {\n scheduleMeasurement();\n\n window.addEventListener('resize', scheduleMeasurement, { passive: true });\n window.addEventListener('DOMContentLoaded', scheduleMeasurement);\n\n const options = optionsRefs.current.filter(Boolean);\n\n // One observer of each kind covers every option: both accept repeated\n // `observe` calls, so a group of ten options costs two observers, not\n // twenty.\n const mutationObserver = new MutationObserver(scheduleMeasurement);\n const resizeObserver = new ResizeObserver(scheduleMeasurement);\n\n const handleMouseEnter = (event: Event) => {\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n\n hoveredItemRef.current = event.currentTarget as HTMLElement;\n scheduleMeasurement();\n };\n\n const handleMouseLeave = () => {\n if (hideTimeoutRef.current) clearTimeout(hideTimeoutRef.current);\n\n // Keep the indicator where it is for a moment, so moving between two\n // neighbouring options does not make it blink out and back in.\n hideTimeoutRef.current = setTimeout(() => {\n hoveredItemRef.current = null;\n scheduleMeasurement();\n }, HOVER_RELEASE_DELAY);\n };\n\n for (const option of options) {\n mutationObserver.observe(option, {\n attributes: true,\n attributeFilter: WATCHED_ATTRIBUTES,\n });\n resizeObserver.observe(option);\n\n if (isHoverable) {\n option.addEventListener('mouseenter', handleMouseEnter, {\n passive: true,\n });\n option.addEventListener('mouseleave', handleMouseLeave, {\n passive: true,\n });\n }\n }\n\n return () => {\n cancelMeasurementRef.current?.();\n cancelMeasurementRef.current = null;\n\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n\n window.removeEventListener('resize', scheduleMeasurement);\n window.removeEventListener('DOMContentLoaded', scheduleMeasurement);\n\n mutationObserver.disconnect();\n resizeObserver.disconnect();\n\n if (isHoverable) {\n for (const option of options) {\n option.removeEventListener('mouseenter', handleMouseEnter);\n option.removeEventListener('mouseleave', handleMouseLeave);\n }\n }\n };\n }, [optionsRefs, itemsLength, isHoverable, orientation, scheduleMeasurement]);\n\n return {\n choiceIndicatorPosition,\n /** Measures immediately. Prefer `scheduleMeasurement`, which does not force a reflow. */\n calculatePosition,\n scheduleMeasurement,\n orientation,\n };\n};\n"],"mappings":";;;;;;AA2BA,MAAM,mBAAmB,WACvB,QAAQ,aAAa,eAAe,MAAM;;AAG5C,MAAM,qBAAqB;CAAC;CAAiB;CAAe;AAAgB;;AAG5E,MAAM,sBAAsB;AAQ5B,MAAa,mBACX,aACA,EACE,WAAW,iBACX,cAAc,OACd,cAAc,iBACH;CACX,UAAU;CACV,aAAa;CACb,aAAa;AACf,MACG;CACH,MAAM,CAAC,yBAAyB,8BAC9B,SAA4B,IAAI;CAElC,MAAM,iBAAiB,OAA2B,IAAI;CACtD,MAAM,iBAAiB,OAA8B,IAAI;CACzD,MAAM,kBAAkB,OAA0B,IAAI;CACtD,MAAM,uBAAuB,OAA4B,IAAI;CAQ7D,MAAM,cAAc,OAAO,QAAQ;CACnC,YAAY,UAAU;CAEtB,MAAM,iBAAiB,OAAO,WAAW;CACzC,eAAe,UAAU;CAEzB,MAAM,cAAc,YAAY,QAAQ;CAExC,MAAM,oBAAoB,kBAAkB;EAC1C,MAAM,gBACJ,eAAe,WACf,YAAY,QAAQ,KAAK,YAAY,OAAO,KAC5C;EAEF,IAAI,eAAe,WAAW,eAAe,SAAS;GAEpD,aAAa,eAAe,OAAO;GACnC,eAAe,UAAU;EAC3B;EAEA,MAAM,aAAa,eAAe,YAAY;EAE9C,IAAI,CAAC,eAAe;GAElB,IAAI,gBAAgB,SAAS,YAAY,GAAG;GAE5C,MAAM,cAA0B,aAC5B;IACE,KACG,gBAAgB,SAAuC,OAAO;IACjE,QACG,gBAAgB,SAAuC,UACxD;IACF,SAAS;GACX,IACA;IACE,MACG,gBAAgB,SAAyC,QAC1D;IACF,OACG,gBAAgB,SAAyC,SAC1D;IACF,SAAS;GACX;GAEJ,2BAA2B,WAAW;GACtC,gBAAgB,UAAU;GAC1B;EACF;EAEA,IAAI,YAAY;GACd,MAAM,MAAM,cAAc;GAC1B,MAAM,SAAS,cAAc;GAC7B,MAAM,W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AAiB,QAAQ,QAAQ;IAC/B,YAAY;IACZ,iBAAiB;GACnB,CAAC;GACD,eAAe,QAAQ,MAAM;GAE7B,IAAI,aAAa;IACf,OAAO,iBAAiB,cAAc,kBAAkB,EACtD,SAAS,KACX,CAAC;IACD,OAAO,iBAAiB,cAAc,kBAAkB,EACtD,SAAS,KACX,CAAC;GACH;EACF;EAEA,aAAa;GACX,qBAAqB,UAAU;GAC/B,qBAAqB,UAAU;GAE/B,IAAI,eAAe,SAAS;IAC1B,aAAa,eAAe,OAAO;IACnC,eAAe,UAAU;GAC3B;GAEA,OAAO,oBAAoB,UAAU,mBAAmB;GACxD,OAAO,oBAAoB,oBAAoB,mBAAmB;GAElE,iBAAiB,WAAW;GAC5B,eAAe,WAAW;GAE1B,IAAI,aACF,KAAK,MAAM,UAAU,SAAS;IAC5B,OAAO,oBAAoB,cAAc,gBAAgB;IACzD,OAAO,oBAAoB,cAAc,gBAAgB;GAC3D;EAEJ;CACF,GAAG;EAAC;EAAa;EAAa;EAAa;EAAa;CAAmB,CAAC;CAE5E,OAAO;EACL;;EAEA;EACA;EACA;CACF;AACF"}
@@ -1,7 +1,9 @@
1
1
  'use client';
2
2
 
3
+ import { scheduleFrameTask } from "../utils/scheduleFrameTask.mjs";
3
4
  import { useGetElementOrWindow } from "./useGetElementOrWindow.mjs";
4
- import { useCallback, useSyncExternalStore } from "react";
5
+ import { observeScrollExtent } from "../utils/observeScrollExtent.mjs";
6
+ import { useEffect, useState } from "react";
5
7
 
6
8
  //#region src/hooks/useScrollY.ts
7
9
  const INITIAL_SCROLL_STATE = {
@@ -9,59 +11,76 @@ const INITIAL_SCROLL_STATE = {
9
11
  scrollPercentage: 0,
10
12
  scrollYMax: 0
11
13
  };
12
- let lastSnapshot = INITIAL_SCROLL_STATE;
14
+ /**
15
+ * Tracks the vertical scroll of an element — or of the page — as a position and
16
+ * a 0-to-1 progress.
17
+ *
18
+ * @param props.element - Scrollable element. Defaults to the document.
19
+ * @returns The current offset, its maximum, and the ratio between the two.
20
+ *
21
+ * @example
22
+ * const { scrollPercentage } = useScrollY({ element: contentElement });
23
+ */
13
24
  const useScrollY = (props) => {
14
25
  const { element } = props ?? {};
15
26
  const containerElement = useGetElementOrWindow(element);
16
- const subscribe = useCallback((onChange) => {
17
- if (typeof window === "undefined" || !containerElement) return () => {};
18
- let raf = 0;
19
- const handler = () => {
20
- if (raf) return;
21
- raf = window.requestAnimationFrame(() => {
22
- raf = 0;
23
- onChange();
24
- });
25
- };
26
- containerElement.addEventListener("scroll", handler, { passive: true });
27
- return () => {
28
- containerElement.removeEventListener("scroll", handler);
29
- if (raf) window.cancelAnimationFrame(raf);
27
+ const [scrollState, setScrollState] = useState(INITIAL_SCROLL_STATE);
28
+ useEffect(() => {
29
+ if (typeof window === "undefined" || !containerElement) return;
30
+ const isElementScroll = containerElement instanceof HTMLElement;
31
+ /**
32
+ * Travel available to the scroll, cached between layout changes.
33
+ *
34
+ * `scrollHeight` and `clientHeight` both flush pending layout, so reading
35
+ * them on every scroll frame would recompute the whole page while the user
36
+ * scrolls. Only `scrollTop` is read per frame; the rest is refreshed when
37
+ * the content or the viewport actually resizes.
38
+ */
39
+ let scrollYMax = 0;
40
+ const measureScrollRange = () => {
41
+ const scrollHeight = isElementScroll ? containerElement.scrollHeight : document.documentElement?.scrollHeight ?? document.body?.scrollHeight ?? 0;
42
+ const clientHeight = isElementScroll ? containerElement.clientHeight : document.documentElement?.clientHeight ?? window.innerHeight ?? 0;
43
+ scrollYMax = Math.max(0, scrollHeight - clientHeight);
30
44
  };
31
- }, [containerElement]);
32
- const getSnapshot = () => {
33
- if (typeof window === "undefined" || !containerElement) return INITIAL_SCROLL_STATE;
34
- if (containerElement instanceof HTMLElement) {
35
- const scrollY = containerElement.scrollTop;
36
- const scrollHeight = containerElement.scrollHeight;
37
- const clientHeight = containerElement.clientHeight;
38
- const scrollYMax = Math.max(0, scrollHeight - clientHeight);
45
+ const updateScrollState = () => {
46
+ const scrollY = isElementScroll ? containerElement.scrollTop : window.scrollY ?? document.documentElement?.scrollTop ?? 0;
39
47
  const scrollPercentage = scrollYMax > 0 ? scrollY / scrollYMax : 0;
40
- if (lastSnapshot.scrollY === scrollY && lastSnapshot.scrollPercentage === scrollPercentage && lastSnapshot.scrollYMax === scrollYMax) return lastSnapshot;
41
- lastSnapshot = {
48
+ setScrollState((previousState) => previousState.scrollY === scrollY && previousState.scrollPercentage === scrollPercentage && previousState.scrollYMax === scrollYMax ? previousState : {
42
49
  scrollY,
43
50
  scrollPercentage,
44
51
  scrollYMax
45
- };
46
- return lastSnapshot;
47
- }
48
- const doc = document.documentElement;
49
- const body = document.body;
50
- const scrollY = window.scrollY ?? window.pageYOffset ?? doc?.scrollTop ?? body?.scrollTop ?? 0;
51
- const scrollHeight = doc?.scrollHeight ?? body?.scrollHeight ?? 0;
52
- const clientHeight = doc?.clientHeight ?? window.innerHeight ?? 0;
53
- const scrollYMax = Math.max(0, scrollHeight - clientHeight);
54
- const scrollPercentage = scrollYMax > 0 ? scrollY / scrollYMax : 0;
55
- if (lastSnapshot.scrollY === scrollY && lastSnapshot.scrollPercentage === scrollPercentage && lastSnapshot.scrollYMax === scrollYMax) return lastSnapshot;
56
- lastSnapshot = {
57
- scrollY,
58
- scrollPercentage,
59
- scrollYMax
52
+ });
53
+ };
54
+ let cancelScheduledRead = null;
55
+ const scheduleScrollRead = () => {
56
+ if (cancelScheduledRead) return;
57
+ cancelScheduledRead = scheduleFrameTask(() => {
58
+ cancelScheduledRead = null;
59
+ updateScrollState();
60
+ });
61
+ };
62
+ let cancelScheduledRangeRead = null;
63
+ const scheduleRangeRead = () => {
64
+ if (cancelScheduledRangeRead) return;
65
+ cancelScheduledRangeRead = scheduleFrameTask(() => {
66
+ cancelScheduledRangeRead = null;
67
+ measureScrollRange();
68
+ updateScrollState();
69
+ });
60
70
  };
61
- return lastSnapshot;
62
- };
63
- const getServerSnapshot = () => INITIAL_SCROLL_STATE;
64
- return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
71
+ scheduleRangeRead();
72
+ const stopObservingScrollExtent = observeScrollExtent(isElementScroll ? containerElement : document.documentElement, scheduleRangeRead);
73
+ containerElement.addEventListener("scroll", scheduleScrollRead, { passive: true });
74
+ window.addEventListener("resize", scheduleRangeRead, { passive: true });
75
+ return () => {
76
+ cancelScheduledRead?.();
77
+ cancelScheduledRangeRead?.();
78
+ stopObservingScrollExtent();
79
+ containerElement.removeEventListener("scroll", scheduleScrollRead);
80
+ window.removeEventListener("resize", scheduleRangeRead);
81
+ };
82
+ }, [containerElement]);
83
+ return scrollState;
65
84
  };
66
85
 
67
86
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"useScrollY.mjs","names":[],"sources":["../../../src/hooks/useScrollY.ts"],"sourcesContent":["'use client';\n\nimport { useCallback, useSyncExternalStore } from 'react';\nimport { useGetElementOrWindow } from './useGetElementOrWindow';\n\ntype UseScrollYProps = {\n element?: HTMLElement;\n};\n\ntype UseScrollYResult = {\n scrollY: number;\n scrollPercentage: number;\n scrollYMax: number;\n};\n\nconst INITIAL_SCROLL_STATE: UseScrollYResult = {\n scrollY: 0,\n scrollPercentage: 0,\n scrollYMax: 0,\n};\n\nlet lastSnapshot: UseScrollYResult = INITIAL_SCROLL_STATE;\n\nexport const useScrollY = (props?: UseScrollYProps): UseScrollYResult => {\n const { element } = props ?? {};\n\n const containerElement = useGetElementOrWindow(element);\n\n const subscribe = useCallback(\n (onChange: () => void) => {\n if (typeof window === 'undefined' || !containerElement) return () => {};\n let raf = 0;\n\n const handler = () => {\n if (raf) return;\n raf = window.requestAnimationFrame(() => {\n raf = 0;\n onChange();\n });\n };\n\n containerElement.addEventListener('scroll', handler, { passive: true });\n\n return () => {\n containerElement.removeEventListener('scroll', handler);\n if (raf) window.cancelAnimationFrame(raf);\n };\n },\n [containerElement]\n );\n\n const getSnapshot = (): UseScrollYResult => {\n if (typeof window === 'undefined' || !containerElement) {\n return INITIAL_SCROLL_STATE; // SSR/hydration-safe\n }\n\n // Handle custom element\n if (containerElement instanceof HTMLElement) {\n const scrollY = containerElement.scrollTop;\n const scrollHeight = containerElement.scrollHeight;\n const clientHeight = containerElement.clientHeight;\n const scrollYMax = Math.max(0, scrollHeight - clientHeight);\n const scrollPercentage = scrollYMax > 0 ? scrollY / scrollYMax : 0;\n\n if (\n lastSnapshot.scrollY === scrollY &&\n lastSnapshot.scrollPercentage === scrollPercentage &&\n lastSnapshot.scrollYMax === scrollYMax\n ) {\n return lastSnapshot;\n }\n\n lastSnapshot = { scrollY, scrollPercentage, scrollYMax };\n return lastSnapshot;\n }\n\n // Handle window\n const doc = document.documentElement;\n const body = document.body;\n\n const scrollY =\n window.scrollY ??\n window.pageYOffset ??\n doc?.scrollTop ??\n body?.scrollTop ??\n 0;\n\n const scrollHeight = doc?.scrollHeight ?? body?.scrollHeight ?? 0;\n const clientHeight = doc?.clientHeight ?? window.innerHeight ?? 0;\n const scrollYMax = Math.max(0, scrollHeight - clientHeight);\n const scrollPercentage = scrollYMax > 0 ? scrollY / scrollYMax : 0;\n\n if (\n lastSnapshot.scrollY === scrollY &&\n lastSnapshot.scrollPercentage === scrollPercentage &&\n lastSnapshot.scrollYMax === scrollYMax\n ) {\n return lastSnapshot;\n }\n\n lastSnapshot = { scrollY, scrollPercentage, scrollYMax };\n return lastSnapshot;\n };\n\n const getServerSnapshot = (): UseScrollYResult => INITIAL_SCROLL_STATE;\n\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n};\n"],"mappings":";;;;;;AAeA,MAAM,uBAAyC;CAC7C,SAAS;CACT,kBAAkB;CAClB,YAAY;AACd;AAEA,IAAI,eAAiC;AAErC,MAAa,cAAc,UAA8C;CACvE,MAAM,EAAE,YAAY,SAAS,CAAC;CAE9B,MAAM,mBAAmB,sBAAsB,OAAO;CAEtD,MAAM,YAAY,aACf,aAAyB;EACxB,IAAI,OAAO,WAAW,eAAe,CAAC,kBAAkB,aAAa,CAAC;EACtE,IAAI,MAAM;EAEV,MAAM,gBAAgB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esContent":["'use client';\n\nimport { observeScrollExtent } from '@utils/observeScrollExtent';\nimport { scheduleFrameTask } from '@utils/scheduleFrameTask';\nimport { useEffect, useState } from 'react';\nimport { useGetElementOrWindow } from './useGetElementOrWindow';\n\ntype UseScrollYProps = {\n element?: HTMLElement;\n};\n\ntype UseScrollYResult = {\n scrollY: number;\n scrollPercentage: number;\n scrollYMax: number;\n};\n\nconst INITIAL_SCROLL_STATE: UseScrollYResult = {\n scrollY: 0,\n scrollPercentage: 0,\n scrollYMax: 0,\n};\n\n/**\n * Tracks the vertical scroll of an element — or of the page — as a position and\n * a 0-to-1 progress.\n *\n * @param props.element - Scrollable element. Defaults to the document.\n * @returns The current offset, its maximum, and the ratio between the two.\n *\n * @example\n * const { scrollPercentage } = useScrollY({ element: contentElement });\n */\nexport const useScrollY = (props?: UseScrollYProps): UseScrollYResult => {\n const { element } = props ?? {};\n const containerElement = useGetElementOrWindow(element);\n const [scrollState, setScrollState] =\n useState<UseScrollYResult>(INITIAL_SCROLL_STATE);\n\n useEffect(() => {\n if (typeof window === 'undefined' || !containerElement) return;\n\n const isElementScroll = containerElement instanceof HTMLElement;\n\n /**\n * Travel available to the scroll, cached between layout changes.\n *\n * `scrollHeight` and `clientHeight` both flush pending layout, so reading\n * them on every scroll frame would recompute the whole page while the user\n * scrolls. Only `scrollTop` is read per frame; the rest is refreshed when\n * the content or the viewport actually resizes.\n */\n let scrollYMax = 0;\n\n const measureScrollRange = () => {\n const scrollHeight = isElementScroll\n ? containerElement.scrollHeight\n : (document.documentElement?.scrollHeight ??\n document.body?.scrollHeight ??\n 0);\n\n const clientHeight = isElementScroll\n ? containerElement.clientHeight\n : (document.documentElement?.clientHeight ?? window.innerHeight ?? 0);\n\n scrollYMax = Math.max(0, scrollHeight - clientHeight);\n };\n\n const updateScrollState = () => {\n const scrollY = isElementScroll\n ? containerElement.scrollTop\n : (window.scrollY ?? document.documentElement?.scrollTop ?? 0);\n\n const scrollPercentage = scrollYMax > 0 ? scrollY / scrollYMax : 0;\n\n setScrollState((previousState) =>\n previousState.scrollY === scrollY &&\n previousState.scrollPercentage === scrollPercentage &&\n previousState.scrollYMax === scrollYMax\n ? previousState\n : { scrollY, scrollPercentage, scrollYMax }\n );\n };\n\n let cancelScheduledRead: (() => void) | null = null;\n\n const scheduleScrollRead = () => {\n if (cancelScheduledRead) return;\n\n cancelScheduledRead = scheduleFrameTask(() => {\n cancelScheduledRead = null;\n updateScrollState();\n });\n };\n\n let cancelScheduledRangeRead: (() => void) | null = null;\n\n const scheduleRangeRead = () => {\n if (cancelScheduledRangeRead) return;\n\n cancelScheduledRangeRead = scheduleFrameTask(() => {\n cancelScheduledRangeRead = null;\n measureScrollRange();\n updateScrollState();\n });\n };\n\n // Initial measurement, deferred so that it shares the frame of every other\n // measurement the page schedules while mounting.\n scheduleRangeRead();\n\n const stopObservingScrollExtent = observeScrollExtent(\n isElementScroll ? containerElement : document.documentElement,\n scheduleRangeRead\n );\n\n containerElement.addEventListener('scroll', scheduleScrollRead, {\n passive: true,\n });\n window.addEventListener('resize', scheduleRangeRead, { passive: true });\n\n return () => {\n cancelScheduledRead?.();\n cancelScheduledRangeRead?.();\n stopObservingScrollExtent();\n containerElement.removeEventListener('scroll', scheduleScrollRead);\n window.removeEventListener('resize', scheduleRangeRead);\n };\n }, [containerElement]);\n\n return scrollState;\n};\n"],"mappings":";;;;;;;;AAiBA,MAAM,uBAAyC;CAC7C,SAAS;CACT,kBAAkB;CAClB,YAAY;AACd;;;;;;;;;;;AAYA,MAAa,cAAc,UAA8C;CACvE,MAAM,EAAE,YAAY,SAAS,CAAC;CAC9B,MAAM,mBAAmB,sBAAsB,OAAO;CACtD,MAAM,CAAC,aAAa,kBAClB,SAA2B,oBAAoB;CAEjD,gBAAgB;EACd,IAAI,OAAO,WAAW,eAAe,CAAC,kBAAkB;EAExD,MAAM,kBAAkB,4BAA4B;;;;;;;;;EAUpD,IAAI,aAAa;EAEjB,MAAM,2BAA2B;GAC/B,MAAM,eAAe,kBAC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ance from the bottom, in pixels, under which the list still counts as
8
+ * pinned. Sub-pixel scroll positions and zoom levels never land exactly on the
9
+ * bottom, so an exact comparison would unpin a list the user never moved.
10
+ */
11
+ const PIN_THRESHOLD = 32;
12
+ /**
13
+ * Keeps a scrolling container pinned to its bottom edge as its content grows,
14
+ * and releases the pin as soon as the user scrolls away from the bottom.
15
+ *
16
+ * Growth is detected with a `ResizeObserver` rather than from a render effect,
17
+ * so a message streaming in token by token follows without the component
18
+ * having to describe what changed. Both the read and the write happen inside
19
+ * the observer callback, which the browser runs once layout is already
20
+ * computed — neither forces a reflow, unlike measuring the same container from
21
+ * an effect that has just committed new nodes.
22
+ *
23
+ * @returns The refs to attach to the container and to its content wrapper.
24
+ *
25
+ * @example
26
+ * const { scrollRef, contentRef } = useStickToBottom<HTMLDivElement, HTMLUListElement>();
27
+ *
28
+ * return (
29
+ * <div ref={scrollRef} className="overflow-auto">
30
+ * <ul ref={contentRef}>{items}</ul>
31
+ * </div>
32
+ * );
33
+ */
34
+ const useStickToBottom = () => {
35
+ const scrollRef = useRef(null);
36
+ const contentRef = useRef(null);
37
+ const isPinnedRef = useRef(true);
38
+ useEffect(() => {
39
+ const scrollElement = scrollRef.current;
40
+ const contentElement = contentRef.current;
41
+ if (!scrollElement || !contentElement) return;
42
+ const getDistanceFromBottom = () => scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight;
43
+ const handleScroll = () => {
44
+ isPinnedRef.current = getDistanceFromBottom() <= PIN_THRESHOLD;
45
+ };
46
+ const resizeObserver = new ResizeObserver(() => {
47
+ if (!isPinnedRef.current) return;
48
+ if (getDistanceFromBottom() <= 0) return;
49
+ scrollElement.scrollTop = scrollElement.scrollHeight - scrollElement.clientHeight;
50
+ });
51
+ resizeObserver.observe(contentElement);
52
+ scrollElement.addEventListener("scroll", handleScroll, { passive: true });
53
+ return () => {
54
+ resizeObserver.disconnect();
55
+ scrollElement.removeEventListener("scroll", handleScroll);
56
+ };
57
+ }, []);
58
+ return {
59
+ scrollRef,
60
+ contentRef,
61
+ unpin: useCallback(() => {
62
+ isPinnedRef.current = false;
63
+ }, [])
64
+ };
65
+ };
66
+
67
+ //#endregion
68
+ export { useStickToBottom };
69
+ //# sourceMappingURL=useStickToBottom.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useStickToBottom.mjs","names":[],"sources":["../../../src/hooks/useStickToBottom.ts"],"sourcesContent":["'use client';\n\nimport { type RefObject, useCallback, useEffect, useRef } from 'react';\n\n/**\n * Distance from the bottom, in pixels, under which the list still counts as\n * pinned. Sub-pixel scroll positions and zoom levels never land exactly on the\n * bottom, so an exact comparison would unpin a list the user never moved.\n */\nconst PIN_THRESHOLD = 32;\n\nexport type StickToBottomRefs<\n ScrollElement extends HTMLElement,\n ContentElement extends HTMLElement,\n> = {\n /** Attach to the scrolling container. */\n scrollRef: RefObject<ScrollElement | null>;\n /** Attach to the element wrapping the items, whose growth triggers the follow. */\n contentRef: RefObject<ContentElement | null>;\n /**\n * Releases the pin until the user scrolls back down to the bottom.\n *\n * Call it before growing the content upwards — prepending older items to a\n * pinned list would otherwise scroll straight past what was just revealed.\n */\n unpin: () => void;\n};\n\n/**\n * Keeps a scrolling container pinned to its bottom edge as its content grows,\n * and releases the pin as soon as the user scrolls away from the bottom.\n *\n * Growth is detected with a `ResizeObserver` rather than from a render effect,\n * so a message streaming in token by token follows without the component\n * having to describe what changed. Both the read and the write happen inside\n * the observer callback, which the browser runs once layout is already\n * computed — neither forces a reflow, unlike measuring the same container from\n * an effect that has just committed new nodes.\n *\n * @returns The refs to attach to the container and to its content wrapper.\n *\n * @example\n * const { scrollRef, contentRef } = useStickToBottom<HTMLDivElement, HTMLUListElement>();\n *\n * return (\n * <div ref={scrollRef} className=\"overflow-auto\">\n * <ul ref={contentRef}>{items}</ul>\n * </div>\n * );\n */\nexport const useStickToBottom = <\n ScrollElement extends HTMLElement,\n ContentElement extends HTMLElement,\n>(): StickToBottomRefs<ScrollElement, ContentElement> => {\n const scrollRef = useRef<ScrollElement>(null);\n const contentRef = useRef<ContentElement>(null);\n const isPinnedRef = useRef(true);\n\n useEffect(() => {\n const scrollElement = scrollRef.current;\n const contentElement = contentRef.current;\n\n if (!scrollElement || !contentElement) return;\n\n const getDistanceFromBottom = () =>\n scrollElement.scrollHeight -\n scrollElement.scrollTop -\n scrollElement.clientHeight;\n\n /*\n * Scroll events are dispatched after the browser has laid the page out, so\n * reading the geometry here is free — deferring it to an animation frame\n * would move the read *before* the next layout and force one instead.\n */\n const handleScroll = () => {\n isPinnedRef.current = getDistanceFromBottom() <= PIN_THRESHOLD;\n };\n\n const resizeObserver = new ResizeObserver(() => {\n if (!isPinnedRef.current) return;\n if (getDistanceFromBottom() <= 0) return;\n\n // Jumping rather than animating: a streamed answer resizes on nearly\n // every frame, and a smooth scroll restarted that often never reaches\n // the bottom.\n scrollElement.scrollTop =\n scrollElement.scrollHeight - scrollElement.clientHeight;\n });\n\n resizeObserver.observe(contentElement);\n scrollElement.addEventListener('scroll', handleScroll, { passive: true });\n\n return () => {\n resizeObserver.disconnect();\n scrollElement.removeEventListener('scroll', handleScroll);\n };\n }, []);\n\n const unpin = useCallback(() => {\n isPinnedRef.current = false;\n }, []);\n\n return { scrollRef, contentRef, unpin };\n};\n"],"mappings":";;;;;;;;;;AASA,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;AAyCtB,MAAa,yBAG4C;CACvD,MAAM,YAAY,OAAsB,IAAI;CAC5C,MAAM,aAAa,OAAuB,IAAI;CAC9C,MAAM,cAAc,OAAO,IAAI;CAE/B,gBAAgB;EACd,MAAM,gBAAgB,UAAU;EAChC,MAAM,iBAAiB,WAAW;EAElC,IAAI,CAAC,iBAAiB,CAAC,gBAAgB;EAEvC,MAAM,8BACJ,cAAc,eACd,cAAc,YACd,cAAc;EAOhB,MAAM,qBAAqB;GACzB,YAAY,UAAU,sBAAsB,KAAK;EACnD;EAEA,MAAM,iBAAiB,IAAI,qBAAqB;GAC9C,IAAI,CAAC,YAAY,SAAS;GAC1B,IAAI,sBAAsB,KAAK,GAAG;GAKlC,cAAc,YACZ,cAAc,eAAe,cAAc;EAC/C,CAAC;EAED,eAAe,QAAQ,cAAc;EACrC,cAAc,iBAAiB,UAAU,cAAc,EAAE,SAAS,KAAK,CAAC;EAExE,aAAa;GACX,eAAe,WAAW;GAC1B,cAAc,oBAAoB,UAAU,YAAY;EAC1D;CACF,GAAG,CAAC,CAAC;CAML,OAAO;EAAE;EAAW;EAAY,OAJlB,kBAAkB;GAC9B,YAAY,UAAU;EACxB,GAAG,CAAC,CAEgC;CAAE;AACxC"}
@@ -3,7 +3,7 @@ import { ssoClient } from "@better-auth/sso/client";
3
3
  import { editor } from "@intlayer/config/built";
4
4
  import { BACKEND_URL } from "@intlayer/config/defaultValues";
5
5
  import { createAuthClient } from "better-auth/client";
6
- import { magicLinkClient, twoFactorClient } from "better-auth/client/plugins";
6
+ import { magicLinkClient, multiSessionClient, twoFactorClient } from "better-auth/client/plugins";
7
7
 
8
8
  //#region src/libs/auth.ts
9
9
  const getAuthClient = (backendURL) => createAuthClient({
@@ -17,7 +17,8 @@ const getAuthClient = (backendURL) => createAuthClient({
17
17
  } }),
18
18
  passkeyClient(),
19
19
  magicLinkClient(),
20
- ssoClient()
20
+ ssoClient(),
21
+ multiSessionClient()
21
22
  ]
22
23
  });
23
24
  const getAuthAPI = (intlayerConfig) => {
@@ -138,6 +139,15 @@ const getAuthAPI = (intlayerConfig) => {
138
139
  const deleteSSOProvider = async (args) => {
139
140
  return client.sso.deleteProvider({ providerId: args.providerId });
140
141
  };
142
+ const listDeviceSessions = async (...args) => {
143
+ return client.multiSession.listDeviceSessions(...args);
144
+ };
145
+ const setActiveSession = async (...args) => {
146
+ return client.multiSession.setActive(...args);
147
+ };
148
+ const revokeDeviceSession = async (...args) => {
149
+ return client.multiSession.revoke(...args);
150
+ };
141
151
  return {
142
152
  getAuthClient: () => client,
143
153
  signInEmail,
@@ -176,7 +186,10 @@ const getAuthAPI = (intlayerConfig) => {
176
186
  signInSSO,
177
187
  registerSSO,
178
188
  listSSOProviders,
179
- deleteSSOProvider
189
+ deleteSSOProvider,
190
+ listDeviceSessions,
191
+ revokeDeviceSession,
192
+ setActiveSession
180
193
  };
181
194
  };
182
195