@octanejs/mantine-hooks 0.1.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 (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -0
  3. package/package.json +45 -0
  4. package/src/index.ts +259 -0
  5. package/src/internal.ts +6 -0
  6. package/src/use-click-outside/use-click-outside.ts +57 -0
  7. package/src/use-clipboard/use-clipboard.ts +69 -0
  8. package/src/use-collapse/use-collapse.ts +162 -0
  9. package/src/use-collapse/use-horizontal-collapse.ts +164 -0
  10. package/src/use-color-scheme/use-color-scheme.ts +13 -0
  11. package/src/use-counter/use-counter.ts +59 -0
  12. package/src/use-debounced-callback/use-debounced-callback.ts +159 -0
  13. package/src/use-debounced-state/use-debounced-state.ts +44 -0
  14. package/src/use-debounced-value/use-debounced-value.ts +71 -0
  15. package/src/use-did-update/use-did-update.ts +26 -0
  16. package/src/use-disclosure/use-disclosure.ts +57 -0
  17. package/src/use-document-title/use-document-title.ts +9 -0
  18. package/src/use-document-visibility/use-document-visibility.ts +14 -0
  19. package/src/use-drag/use-drag.ts +463 -0
  20. package/src/use-event-listener/use-event-listener.ts +47 -0
  21. package/src/use-eye-dropper/use-eye-dropper.ts +41 -0
  22. package/src/use-favicon/use-favicon.ts +41 -0
  23. package/src/use-fetch/use-fetch.ts +85 -0
  24. package/src/use-file-dialog/use-file-dialog.ts +140 -0
  25. package/src/use-floating-window/use-floating-window.ts +431 -0
  26. package/src/use-focus-return/use-focus-return.ts +65 -0
  27. package/src/use-focus-trap/scope-tab.ts +36 -0
  28. package/src/use-focus-trap/tabbable.ts +65 -0
  29. package/src/use-focus-trap/use-focus-trap.ts +84 -0
  30. package/src/use-focus-within/use-focus-within.ts +90 -0
  31. package/src/use-force-update/use-force-update.ts +8 -0
  32. package/src/use-fullscreen/use-fullscreen.ts +153 -0
  33. package/src/use-hash/use-hash.ts +42 -0
  34. package/src/use-headroom/use-headroom.ts +160 -0
  35. package/src/use-hotkeys/parse-hotkey.ts +130 -0
  36. package/src/use-hotkeys/use-hotkeys.ts +63 -0
  37. package/src/use-hover/use-hover.ts +57 -0
  38. package/src/use-id/use-id.ts +23 -0
  39. package/src/use-idle/use-idle.ts +54 -0
  40. package/src/use-in-viewport/use-in-viewport.ts +34 -0
  41. package/src/use-input-state/use-input-state.ts +41 -0
  42. package/src/use-intersection/use-intersection.ts +41 -0
  43. package/src/use-interval/use-interval.ts +84 -0
  44. package/src/use-is-first-render/use-is-first-render.ts +12 -0
  45. package/src/use-isomorphic-effect/use-isomorphic-effect.ts +5 -0
  46. package/src/use-list-state/use-list-state.ts +157 -0
  47. package/src/use-local-storage/create-storage.ts +200 -0
  48. package/src/use-local-storage/use-local-storage.ts +19 -0
  49. package/src/use-logger/use-logger.ts +16 -0
  50. package/src/use-long-press/use-long-press.ts +188 -0
  51. package/src/use-map/use-map.ts +28 -0
  52. package/src/use-mask/use-mask.ts +1049 -0
  53. package/src/use-media-query/use-media-query.ts +57 -0
  54. package/src/use-merged-ref/use-merged-ref.ts +53 -0
  55. package/src/use-mounted/use-mounted.ts +7 -0
  56. package/src/use-mouse/use-mouse.ts +91 -0
  57. package/src/use-move/use-move.ts +165 -0
  58. package/src/use-mutation-observer/use-mutation-observer.ts +61 -0
  59. package/src/use-network/use-network.ts +70 -0
  60. package/src/use-orientation/use-orientation.ts +87 -0
  61. package/src/use-os/use-os.ts +93 -0
  62. package/src/use-page-leave/use-page-leave.ts +10 -0
  63. package/src/use-pagination/use-pagination.ts +149 -0
  64. package/src/use-previous/use-previous.ts +11 -0
  65. package/src/use-queue/use-queue.ts +71 -0
  66. package/src/use-radial-move/use-radial-move.ts +161 -0
  67. package/src/use-reduced-motion/use-reduced-motion.ts +6 -0
  68. package/src/use-resize-observer/use-resize-observer.ts +95 -0
  69. package/src/use-roving-index/use-roving-index.ts +386 -0
  70. package/src/use-scroll-direction/use-scroll-direction.ts +41 -0
  71. package/src/use-scroll-into-view/use-scroll-into-view.ts +294 -0
  72. package/src/use-scroll-spy/use-scroll-spy.ts +155 -0
  73. package/src/use-scroller/use-scroller.ts +225 -0
  74. package/src/use-selection/use-selection.ts +120 -0
  75. package/src/use-session-storage/use-session-storage.ts +19 -0
  76. package/src/use-set/use-set.ts +88 -0
  77. package/src/use-set-state/use-set-state.ts +29 -0
  78. package/src/use-shallow-effect/use-shallow-effect.ts +40 -0
  79. package/src/use-splitter/use-splitter.ts +1242 -0
  80. package/src/use-state-history/use-state-history.ts +70 -0
  81. package/src/use-text-selection/use-text-selection.ts +20 -0
  82. package/src/use-throttled-callback/use-throttled-callback.ts +60 -0
  83. package/src/use-throttled-state/use-throttled-state.ts +12 -0
  84. package/src/use-throttled-value/use-throttled-value.ts +23 -0
  85. package/src/use-timeout/use-timeout.ts +56 -0
  86. package/src/use-toggle/use-toggle.ts +23 -0
  87. package/src/use-uncontrolled/use-uncontrolled.ts +53 -0
  88. package/src/use-validated-state/use-validated-state.ts +50 -0
  89. package/src/use-viewport-size/use-viewport-size.ts +23 -0
  90. package/src/use-window-event/use-window-event.ts +16 -0
  91. package/src/use-window-scroll/use-window-scroll.ts +49 -0
  92. package/src/utils/clamp/clamp.ts +15 -0
  93. package/src/utils/index.ts +7 -0
  94. package/src/utils/lower-first/lower-first.ts +3 -0
  95. package/src/utils/random-id/random-id.ts +3 -0
  96. package/src/utils/range/range.ts +10 -0
  97. package/src/utils/shallow-equal/shallow-equal.ts +34 -0
  98. package/src/utils/upper-first/upper-first.ts +3 -0
  99. package/src/utils/use-callback-ref/use-callback-ref.ts +11 -0
@@ -0,0 +1,386 @@
1
+ import { useCallback, useEffect, useRef } from 'octane';
2
+ import { useUncontrolled } from '../use-uncontrolled/use-uncontrolled';
3
+
4
+ export interface UseRovingIndexInput {
5
+ /** Total number of items in the group */
6
+ total: number;
7
+
8
+ /** Which arrow keys navigate, `'horizontal'` by default */
9
+ orientation?: 'horizontal' | 'vertical' | 'both';
10
+
11
+ /** Whether navigation wraps at boundaries, `true` by default */
12
+ loop?: boolean;
13
+
14
+ /** Text direction, `'ltr'` by default */
15
+ dir?: 'rtl' | 'ltr';
16
+
17
+ /** Whether to click element when it receives focus via keyboard, `false` by default */
18
+ activateOnFocus?: boolean;
19
+
20
+ /** Number of columns for grid (2D) navigation. When set, enables grid mode */
21
+ columns?: number;
22
+
23
+ /** Controlled focused index */
24
+ focusedIndex?: number;
25
+
26
+ /** Initial focused index for uncontrolled mode, first non-disabled item by default */
27
+ initialIndex?: number;
28
+
29
+ /** Called when focused index changes */
30
+ onFocusChange?: (index: number) => void;
31
+
32
+ /** Function to check if item at given index is disabled, `() => false` by default */
33
+ isItemDisabled?: (index: number) => boolean;
34
+ }
35
+
36
+ export interface UseRovingIndexGetItemPropsInput {
37
+ /** Index of the item in the group */
38
+ index: number;
39
+
40
+ /** Called when item is clicked */
41
+ onClick?: React.MouseEventHandler;
42
+
43
+ /** Called when keydown event fires on item */
44
+ onKeyDown?: React.KeyboardEventHandler;
45
+ }
46
+
47
+ export interface UseRovingIndexReturnValue {
48
+ /** Get props to spread on each navigable item */
49
+ getItemProps: (options: UseRovingIndexGetItemPropsInput) => {
50
+ tabIndex: 0 | -1;
51
+ onKeyDown: React.KeyboardEventHandler;
52
+ onClick: React.MouseEventHandler;
53
+ ref: React.RefCallback<HTMLElement>;
54
+ };
55
+
56
+ /** Currently focused index */
57
+ focusedIndex: number;
58
+
59
+ /** Programmatically set focused index */
60
+ setFocusedIndex: (index: number) => void;
61
+ }
62
+
63
+ function findNextEnabled(
64
+ current: number,
65
+ total: number,
66
+ isItemDisabled: (index: number) => boolean,
67
+ loop: boolean,
68
+ ): number {
69
+ for (let i = current + 1; i < total; i += 1) {
70
+ if (!isItemDisabled(i)) {
71
+ return i;
72
+ }
73
+ }
74
+
75
+ if (loop) {
76
+ for (let i = 0; i < current; i += 1) {
77
+ if (!isItemDisabled(i)) {
78
+ return i;
79
+ }
80
+ }
81
+ }
82
+
83
+ return current;
84
+ }
85
+
86
+ function findPreviousEnabled(
87
+ current: number,
88
+ total: number,
89
+ isItemDisabled: (index: number) => boolean,
90
+ loop: boolean,
91
+ ): number {
92
+ for (let i = current - 1; i >= 0; i -= 1) {
93
+ if (!isItemDisabled(i)) {
94
+ return i;
95
+ }
96
+ }
97
+
98
+ if (loop) {
99
+ for (let i = total - 1; i > current; i -= 1) {
100
+ if (!isItemDisabled(i)) {
101
+ return i;
102
+ }
103
+ }
104
+ }
105
+
106
+ return current;
107
+ }
108
+
109
+ function findFirstEnabled(total: number, isItemDisabled: (index: number) => boolean): number {
110
+ for (let i = 0; i < total; i += 1) {
111
+ if (!isItemDisabled(i)) {
112
+ return i;
113
+ }
114
+ }
115
+
116
+ return 0;
117
+ }
118
+
119
+ function findLastEnabled(total: number, isItemDisabled: (index: number) => boolean): number {
120
+ for (let i = total - 1; i >= 0; i -= 1) {
121
+ if (!isItemDisabled(i)) {
122
+ return i;
123
+ }
124
+ }
125
+
126
+ return 0;
127
+ }
128
+
129
+ const defaultIsItemDisabled = () => false;
130
+
131
+ export function useRovingIndex(input: UseRovingIndexInput): UseRovingIndexReturnValue {
132
+ const {
133
+ total,
134
+ orientation = 'horizontal',
135
+ loop = true,
136
+ dir = 'ltr',
137
+ activateOnFocus = false,
138
+ columns,
139
+ focusedIndex,
140
+ initialIndex,
141
+ onFocusChange,
142
+ isItemDisabled = defaultIsItemDisabled,
143
+ } = input;
144
+
145
+ const itemRefs = useRef<Map<number, HTMLElement>>(new Map());
146
+ const isGrid = typeof columns === 'number' && columns > 0;
147
+
148
+ const resolvedInitialIndex =
149
+ initialIndex !== undefined ? initialIndex : findFirstEnabled(total, isItemDisabled);
150
+
151
+ const [activeIndex, setActiveIndex] = useUncontrolled({
152
+ value: focusedIndex,
153
+ defaultValue: resolvedInitialIndex,
154
+ finalValue: 0,
155
+ onChange: onFocusChange,
156
+ });
157
+
158
+ useEffect(() => {
159
+ if (total === 0) {
160
+ return;
161
+ }
162
+
163
+ if (activeIndex >= total) {
164
+ setActiveIndex(findLastEnabled(total, isItemDisabled));
165
+ } else if (isItemDisabled(activeIndex)) {
166
+ setActiveIndex(findFirstEnabled(total, isItemDisabled));
167
+ }
168
+ }, [total, activeIndex, isItemDisabled]);
169
+
170
+ const focusItem = useCallback(
171
+ (index: number) => {
172
+ setActiveIndex(index);
173
+ const element = itemRefs.current.get(index);
174
+ if (element) {
175
+ element.focus();
176
+ if (activateOnFocus) {
177
+ element.click();
178
+ }
179
+ }
180
+ },
181
+ [activateOnFocus, setActiveIndex],
182
+ );
183
+
184
+ const handleGridKeyDown = useCallback(
185
+ (event: React.KeyboardEvent, currentIndex: number) => {
186
+ const row = Math.floor(currentIndex / columns!);
187
+ const col = currentIndex % columns!;
188
+ const totalRows = Math.ceil(total / columns!);
189
+ let nextIndex: number | null = null;
190
+
191
+ const isRtl = dir === 'rtl';
192
+
193
+ switch (event.key) {
194
+ case 'ArrowRight': {
195
+ const targetCol = isRtl ? col - 1 : col + 1;
196
+ if (targetCol >= 0 && targetCol < columns! && row * columns! + targetCol < total) {
197
+ const candidate = row * columns! + targetCol;
198
+ if (!isItemDisabled(candidate)) {
199
+ nextIndex = candidate;
200
+ }
201
+ }
202
+ break;
203
+ }
204
+
205
+ case 'ArrowLeft': {
206
+ const targetCol = isRtl ? col + 1 : col - 1;
207
+ if (targetCol >= 0 && targetCol < columns! && row * columns! + targetCol < total) {
208
+ const candidate = row * columns! + targetCol;
209
+ if (!isItemDisabled(candidate)) {
210
+ nextIndex = candidate;
211
+ }
212
+ }
213
+ break;
214
+ }
215
+
216
+ case 'ArrowDown': {
217
+ for (let r = row + 1; r < totalRows; r += 1) {
218
+ const candidate = r * columns! + col;
219
+ if (candidate < total && !isItemDisabled(candidate)) {
220
+ nextIndex = candidate;
221
+ break;
222
+ }
223
+ }
224
+ break;
225
+ }
226
+
227
+ case 'ArrowUp': {
228
+ for (let r = row - 1; r >= 0; r -= 1) {
229
+ const candidate = r * columns! + col;
230
+ if (candidate < total && !isItemDisabled(candidate)) {
231
+ nextIndex = candidate;
232
+ break;
233
+ }
234
+ }
235
+ break;
236
+ }
237
+
238
+ case 'Home': {
239
+ if (event.ctrlKey) {
240
+ nextIndex = findFirstEnabled(total, isItemDisabled);
241
+ } else {
242
+ const rowStart = row * columns!;
243
+ for (let i = rowStart; i < rowStart + columns! && i < total; i += 1) {
244
+ if (!isItemDisabled(i)) {
245
+ nextIndex = i;
246
+ break;
247
+ }
248
+ }
249
+ }
250
+ break;
251
+ }
252
+
253
+ case 'End': {
254
+ if (event.ctrlKey) {
255
+ nextIndex = findLastEnabled(total, isItemDisabled);
256
+ } else {
257
+ const rowStart = row * columns!;
258
+ const rowEnd = Math.min(rowStart + columns!, total) - 1;
259
+ for (let i = rowEnd; i >= rowStart; i -= 1) {
260
+ if (!isItemDisabled(i)) {
261
+ nextIndex = i;
262
+ break;
263
+ }
264
+ }
265
+ }
266
+ break;
267
+ }
268
+ }
269
+
270
+ if (nextIndex !== null && nextIndex !== currentIndex) {
271
+ event.preventDefault();
272
+ event.stopPropagation();
273
+ focusItem(nextIndex);
274
+ }
275
+ },
276
+ [total, columns, dir, isItemDisabled, focusItem],
277
+ );
278
+
279
+ const handleListKeyDown = useCallback(
280
+ (event: React.KeyboardEvent, currentIndex: number) => {
281
+ const isRtl = dir === 'rtl';
282
+ let nextIndex: number | null = null;
283
+
284
+ switch (event.key) {
285
+ case 'ArrowRight': {
286
+ if (orientation === 'horizontal' || orientation === 'both') {
287
+ nextIndex = isRtl
288
+ ? findPreviousEnabled(currentIndex, total, isItemDisabled, loop)
289
+ : findNextEnabled(currentIndex, total, isItemDisabled, loop);
290
+ }
291
+ break;
292
+ }
293
+
294
+ case 'ArrowLeft': {
295
+ if (orientation === 'horizontal' || orientation === 'both') {
296
+ nextIndex = isRtl
297
+ ? findNextEnabled(currentIndex, total, isItemDisabled, loop)
298
+ : findPreviousEnabled(currentIndex, total, isItemDisabled, loop);
299
+ }
300
+ break;
301
+ }
302
+
303
+ case 'ArrowDown': {
304
+ if (orientation === 'vertical' || orientation === 'both') {
305
+ nextIndex = findNextEnabled(currentIndex, total, isItemDisabled, loop);
306
+ }
307
+ break;
308
+ }
309
+
310
+ case 'ArrowUp': {
311
+ if (orientation === 'vertical' || orientation === 'both') {
312
+ nextIndex = findPreviousEnabled(currentIndex, total, isItemDisabled, loop);
313
+ }
314
+ break;
315
+ }
316
+
317
+ case 'Home': {
318
+ nextIndex = findFirstEnabled(total, isItemDisabled);
319
+ break;
320
+ }
321
+
322
+ case 'End': {
323
+ nextIndex = findLastEnabled(total, isItemDisabled);
324
+ break;
325
+ }
326
+ }
327
+
328
+ if (nextIndex !== null && nextIndex !== currentIndex) {
329
+ event.preventDefault();
330
+ event.stopPropagation();
331
+ focusItem(nextIndex);
332
+ }
333
+ },
334
+ [total, orientation, loop, dir, isItemDisabled, focusItem],
335
+ );
336
+
337
+ const getItemProps = useCallback(
338
+ (options: UseRovingIndexGetItemPropsInput) => {
339
+ const { index, onClick, onKeyDown } = options;
340
+
341
+ return {
342
+ tabIndex: (index === activeIndex ? 0 : -1) as 0 | -1,
343
+
344
+ ref: (node: HTMLElement | null) => {
345
+ if (node) {
346
+ itemRefs.current.set(index, node);
347
+ } else {
348
+ itemRefs.current.delete(index);
349
+ }
350
+ },
351
+
352
+ onKeyDown: (event: React.KeyboardEvent) => {
353
+ onKeyDown?.(event);
354
+
355
+ if (event.defaultPrevented) {
356
+ return;
357
+ }
358
+
359
+ if (isGrid) {
360
+ handleGridKeyDown(event, index);
361
+ } else {
362
+ handleListKeyDown(event, index);
363
+ }
364
+ },
365
+
366
+ onClick: (event: React.MouseEvent) => {
367
+ onClick?.(event);
368
+ setActiveIndex(index);
369
+ },
370
+ };
371
+ },
372
+ [activeIndex, isGrid, handleGridKeyDown, handleListKeyDown, setActiveIndex],
373
+ );
374
+
375
+ return {
376
+ getItemProps,
377
+ focusedIndex: activeIndex,
378
+ setFocusedIndex: setActiveIndex,
379
+ };
380
+ }
381
+
382
+ export namespace useRovingIndex {
383
+ export type Input = UseRovingIndexInput;
384
+ export type GetItemPropsInput = UseRovingIndexGetItemPropsInput;
385
+ export type ReturnValue = UseRovingIndexReturnValue;
386
+ }
@@ -0,0 +1,41 @@
1
+ import { useEffect, useEffectEvent, useRef, useState } from 'octane';
2
+
3
+ export type ScrollDirection = 'up' | 'down' | 'unknown';
4
+
5
+ export function useScrollDirection(): ScrollDirection {
6
+ const lastScrollTopRef = useRef(0);
7
+ const [scrollDirection, setScrollDirection] = useState<ScrollDirection>('unknown');
8
+ const isResizingRef = useRef(false);
9
+ const resizeTimerRef = useRef<number | undefined>(undefined);
10
+
11
+ const handleScroll = useEffectEvent(() => {
12
+ if (isResizingRef.current) {
13
+ return;
14
+ }
15
+
16
+ const currentScrollTop = window.scrollY || document.documentElement.scrollTop;
17
+ setScrollDirection(currentScrollTop < lastScrollTopRef.current ? 'up' : 'down');
18
+ lastScrollTopRef.current = currentScrollTop;
19
+ });
20
+
21
+ useEffect(() => {
22
+ const handleResize = () => {
23
+ isResizingRef.current = true;
24
+ window.clearTimeout(resizeTimerRef.current);
25
+ resizeTimerRef.current = window.setTimeout(() => {
26
+ isResizingRef.current = false;
27
+ }, 300);
28
+ };
29
+
30
+ window.addEventListener('scroll', handleScroll);
31
+ window.addEventListener('resize', handleResize);
32
+
33
+ return () => {
34
+ window.removeEventListener('scroll', handleScroll);
35
+ window.removeEventListener('resize', handleResize);
36
+ clearTimeout(resizeTimerRef.current);
37
+ };
38
+ }, []);
39
+
40
+ return scrollDirection;
41
+ }
@@ -0,0 +1,294 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'octane';
2
+ import { useReducedMotion } from '../use-reduced-motion/use-reduced-motion';
3
+ import { useWindowEvent } from '../use-window-event/use-window-event';
4
+
5
+ interface UseScrollIntoViewAnimation {
6
+ /** Target element alignment relatively to parent based on current axis */
7
+ alignment?: 'start' | 'end' | 'center';
8
+ }
9
+
10
+ export interface UseScrollIntoViewOptions {
11
+ /** Callback fired after scroll */
12
+ onScrollFinish?: () => void;
13
+
14
+ /** Callback fired when scroll animation is canceled by user interaction */
15
+ onScrollCancel?: () => void;
16
+
17
+ /** Duration of scroll in milliseconds */
18
+ duration?: number;
19
+
20
+ /** Axis of scroll */
21
+ axis?: 'x' | 'y';
22
+
23
+ /** Custom mathematical easing function */
24
+ easing?: (t: number) => number;
25
+
26
+ /** Additional distance between nearest edge and element */
27
+ offset?: number;
28
+
29
+ /** Indicator if animation may be interrupted by user scrolling */
30
+ cancelable?: boolean;
31
+
32
+ /** Prevents content jumping in scrolling lists with multiple targets */
33
+ isList?: boolean;
34
+ }
35
+
36
+ export interface UseScrollIntoViewReturnValue<
37
+ Target extends HTMLElement = any,
38
+ Parent extends HTMLElement | null = null,
39
+ > {
40
+ scrollableRef: React.RefObject<Parent | null>;
41
+ targetRef: React.RefObject<Target | null>;
42
+ scrollIntoView: (params?: UseScrollIntoViewAnimation) => void;
43
+ cancel: () => void;
44
+ scrolling: boolean;
45
+ }
46
+
47
+ export function useScrollIntoView<
48
+ Target extends HTMLElement = any,
49
+ Parent extends HTMLElement | null = null,
50
+ >({
51
+ duration = 1250,
52
+ axis = 'y',
53
+ onScrollFinish,
54
+ onScrollCancel,
55
+ easing,
56
+ offset = 0,
57
+ cancelable = true,
58
+ isList = false,
59
+ }: UseScrollIntoViewOptions = {}): UseScrollIntoViewReturnValue<Target, Parent> {
60
+ const frameID = useRef(0);
61
+ const startTime = useRef(0);
62
+ const shouldStop = useRef(false);
63
+ const [scrolling, setScrolling] = useState(false);
64
+
65
+ const scrollableRef = useRef<Parent | null>(null);
66
+ const targetRef = useRef<Target | null>(null);
67
+
68
+ const reducedMotion = useReducedMotion();
69
+
70
+ const _easing = easing ?? easeInOutQuad;
71
+
72
+ const cancel = (): void => {
73
+ if (frameID.current) {
74
+ cancelAnimationFrame(frameID.current);
75
+ frameID.current = 0;
76
+ setScrolling(false);
77
+ }
78
+ };
79
+
80
+ const scrollIntoView = useCallback(
81
+ ({ alignment = 'start' }: UseScrollIntoViewAnimation = {}) => {
82
+ shouldStop.current = false;
83
+
84
+ if (frameID.current) {
85
+ cancel();
86
+ }
87
+
88
+ const start = getScrollStart({ parent: scrollableRef.current, axis }) ?? 0;
89
+
90
+ const change =
91
+ getRelativePosition({
92
+ parent: scrollableRef.current,
93
+ target: targetRef.current,
94
+ axis,
95
+ alignment,
96
+ offset,
97
+ isList,
98
+ }) - (scrollableRef.current ? 0 : start);
99
+
100
+ setScrolling(true);
101
+
102
+ function animateScroll() {
103
+ if (startTime.current === 0) {
104
+ startTime.current = performance.now();
105
+ }
106
+
107
+ const now = performance.now();
108
+ const elapsed = now - startTime.current;
109
+
110
+ // Easing timing progress
111
+ const t = reducedMotion || duration === 0 ? 1 : elapsed / duration;
112
+
113
+ const distance = start + change * _easing(t);
114
+
115
+ setScrollParam({
116
+ parent: scrollableRef.current,
117
+ axis,
118
+ distance,
119
+ });
120
+
121
+ if (!shouldStop.current && t < 1) {
122
+ frameID.current = requestAnimationFrame(animateScroll);
123
+ } else {
124
+ if (shouldStop.current) {
125
+ typeof onScrollCancel === 'function' && onScrollCancel();
126
+ } else {
127
+ typeof onScrollFinish === 'function' && onScrollFinish();
128
+ }
129
+ startTime.current = 0;
130
+ frameID.current = 0;
131
+ setScrolling(false);
132
+ cancel();
133
+ }
134
+ }
135
+ animateScroll();
136
+ },
137
+ [axis, duration, _easing, isList, offset, onScrollFinish, onScrollCancel, reducedMotion],
138
+ );
139
+
140
+ const handleStop = () => {
141
+ if (cancelable) {
142
+ shouldStop.current = true;
143
+ }
144
+ };
145
+
146
+ /**
147
+ * Detection of one of these events stops scroll animation
148
+ * wheel - mouse wheel / touch pad
149
+ * touchmove - any touchable device
150
+ */
151
+
152
+ useWindowEvent('wheel', handleStop, {
153
+ passive: true,
154
+ });
155
+
156
+ useWindowEvent('touchmove', handleStop, {
157
+ passive: true,
158
+ });
159
+
160
+ // Cleanup requestAnimationFrame
161
+ useEffect(() => cancel, []);
162
+
163
+ return {
164
+ scrollableRef,
165
+ targetRef,
166
+ scrollIntoView,
167
+ cancel,
168
+ scrolling,
169
+ };
170
+ }
171
+
172
+ // ---------------------------------------------------
173
+ // Helpers
174
+ // ---------------------------------------------------
175
+
176
+ function easeInOutQuad(t: number) {
177
+ return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
178
+ }
179
+
180
+ function getRelativePosition({ axis, target, parent, alignment, offset, isList }: any): number {
181
+ if (!target || (!parent && typeof document === 'undefined')) {
182
+ return 0;
183
+ }
184
+ const isCustomParent = !!parent;
185
+ const parentElement = parent || document.body;
186
+ const parentPosition = parentElement.getBoundingClientRect();
187
+ const targetPosition = target.getBoundingClientRect();
188
+
189
+ const getDiff = (property: 'top' | 'left'): number =>
190
+ targetPosition[property] - parentPosition[property];
191
+
192
+ if (axis === 'y') {
193
+ const diff = getDiff('top');
194
+
195
+ if (diff === 0) {
196
+ return 0;
197
+ }
198
+
199
+ if (alignment === 'start') {
200
+ const distance = diff - offset;
201
+ const shouldScroll = distance <= targetPosition.height * (isList ? 0 : 1) || !isList;
202
+
203
+ return shouldScroll ? distance : 0;
204
+ }
205
+
206
+ const parentHeight = isCustomParent ? parentPosition.height : window.innerHeight;
207
+
208
+ if (alignment === 'end') {
209
+ const distance = diff + offset - parentHeight + targetPosition.height;
210
+ const shouldScroll = distance >= -targetPosition.height * (isList ? 0 : 1) || !isList;
211
+
212
+ return shouldScroll ? distance : 0;
213
+ }
214
+
215
+ if (alignment === 'center') {
216
+ return diff - parentHeight / 2 + targetPosition.height / 2;
217
+ }
218
+
219
+ return 0;
220
+ }
221
+
222
+ if (axis === 'x') {
223
+ const diff = getDiff('left');
224
+
225
+ if (diff === 0) {
226
+ return 0;
227
+ }
228
+
229
+ if (alignment === 'start') {
230
+ const distance = diff - offset;
231
+ const shouldScroll = distance <= targetPosition.width || !isList;
232
+
233
+ return shouldScroll ? distance : 0;
234
+ }
235
+
236
+ const parentWidth = isCustomParent ? parentPosition.width : window.innerWidth;
237
+
238
+ if (alignment === 'end') {
239
+ const distance = diff + offset - parentWidth + targetPosition.width;
240
+ const shouldScroll = distance >= -targetPosition.width || !isList;
241
+
242
+ return shouldScroll ? distance : 0;
243
+ }
244
+
245
+ if (alignment === 'center') {
246
+ return diff - parentWidth / 2 + targetPosition.width / 2;
247
+ }
248
+
249
+ return 0;
250
+ }
251
+
252
+ return 0;
253
+ }
254
+
255
+ function getScrollStart({ axis, parent }: any) {
256
+ if (!parent && typeof document === 'undefined') {
257
+ return 0;
258
+ }
259
+
260
+ const method = axis === 'y' ? 'scrollTop' : 'scrollLeft';
261
+
262
+ if (parent) {
263
+ return parent[method];
264
+ }
265
+
266
+ const { body, documentElement } = document;
267
+
268
+ // While one of it has a value the second is equal 0
269
+ return body[method] + documentElement[method];
270
+ }
271
+
272
+ function setScrollParam({ axis, parent, distance }: any) {
273
+ if (!parent && typeof document === 'undefined') {
274
+ return;
275
+ }
276
+
277
+ const method = axis === 'y' ? 'scrollTop' : 'scrollLeft';
278
+
279
+ if (parent) {
280
+ parent[method] = distance;
281
+ } else {
282
+ const { body, documentElement } = document;
283
+ body[method] = distance;
284
+ documentElement[method] = distance;
285
+ }
286
+ }
287
+
288
+ export namespace useScrollIntoView {
289
+ export type Options = UseScrollIntoViewOptions;
290
+ export type ReturnValue<
291
+ Target extends HTMLElement,
292
+ Parent extends HTMLElement | null,
293
+ > = UseScrollIntoViewReturnValue<Target, Parent>;
294
+ }