@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,149 @@
1
+ import { useCallback, useMemo } from 'octane';
2
+ import { useUncontrolled } from '../use-uncontrolled/use-uncontrolled';
3
+
4
+ function range(start: number, end: number) {
5
+ const length = end - start + 1;
6
+ return Array.from({ length }, (_, index) => index + start);
7
+ }
8
+
9
+ export const DOTS = 'dots';
10
+
11
+ export interface UsePaginationOptions {
12
+ /** Page selected on initial render, defaults to 1 or startValue if provided */
13
+ initialPage?: number;
14
+
15
+ /** Controlled active page number */
16
+ page?: number;
17
+
18
+ /** Total amount of pages */
19
+ total: number;
20
+
21
+ /** Siblings amount on left/right side of selected page, defaults to 1 */
22
+ siblings?: number;
23
+
24
+ /** Amount of elements visible on left/right edges, defaults to 1 */
25
+ boundaries?: number;
26
+
27
+ /** Callback fired after change of each page */
28
+ onChange?: (page: number) => void;
29
+
30
+ /** Starting page number, defaults to 1 */
31
+ startValue?: number;
32
+ }
33
+
34
+ export interface UsePaginationReturnValue {
35
+ /** Array of page numbers and dots */
36
+ range: (number | 'dots')[];
37
+
38
+ /** Active page number */
39
+ active: number;
40
+
41
+ /** Function to set active page */
42
+ setPage: (page: number) => void;
43
+
44
+ /** Function to go to next page */
45
+ next: () => void;
46
+
47
+ /** Function to go to previous page */
48
+ previous: () => void;
49
+
50
+ /** Function to go to first page */
51
+ first: () => void;
52
+
53
+ /** Function to go to last page */
54
+ last: () => void;
55
+ }
56
+
57
+ export function usePagination({
58
+ total,
59
+ siblings = 1,
60
+ boundaries = 1,
61
+ page,
62
+ initialPage,
63
+ onChange,
64
+ startValue = 1,
65
+ }: UsePaginationOptions): UsePaginationReturnValue {
66
+ const _startValue = Math.max(Math.trunc(startValue), 1);
67
+ const _endValue = Math.max(Math.trunc(total), _startValue);
68
+ const _total = _endValue - _startValue + 1;
69
+ const _initialPage = initialPage ?? _startValue;
70
+
71
+ const [activePage, setActivePage] = useUncontrolled({
72
+ value: page,
73
+ onChange,
74
+ defaultValue: _initialPage,
75
+ finalValue: _initialPage,
76
+ });
77
+
78
+ const setPage = useCallback(
79
+ (pageNumber: number) => {
80
+ if (pageNumber < _startValue) {
81
+ setActivePage(_startValue);
82
+ } else if (pageNumber > _endValue) {
83
+ setActivePage(_endValue);
84
+ } else {
85
+ setActivePage(pageNumber);
86
+ }
87
+ },
88
+ [_startValue, _endValue, setActivePage],
89
+ );
90
+
91
+ const next = useCallback(() => setPage(activePage + 1), [activePage, setPage]);
92
+ const previous = useCallback(() => setPage(activePage - 1), [activePage, setPage]);
93
+ const first = useCallback(() => setPage(_startValue), [setPage, _startValue]);
94
+ const last = useCallback(() => setPage(_endValue), [_endValue, setPage]);
95
+
96
+ const paginationRange = useMemo((): (number | 'dots')[] => {
97
+ const totalPageNumbers = siblings * 2 + 3 + boundaries * 2;
98
+ if (totalPageNumbers >= _total) {
99
+ return range(_startValue, _endValue);
100
+ }
101
+
102
+ const leftSiblingIndex = Math.max(activePage - siblings, _startValue + boundaries - 1);
103
+ const rightSiblingIndex = Math.min(activePage + siblings, _endValue - boundaries);
104
+
105
+ const shouldShowLeftDots = leftSiblingIndex > _startValue + boundaries + 1;
106
+ const shouldShowRightDots = rightSiblingIndex < _endValue - boundaries;
107
+
108
+ if (!shouldShowLeftDots && shouldShowRightDots) {
109
+ const leftItemCount = siblings * 2 + boundaries + 2;
110
+ return [
111
+ ...range(_startValue, _startValue + leftItemCount - 1),
112
+ DOTS,
113
+ ...range(_endValue - (boundaries - 1), _endValue),
114
+ ];
115
+ }
116
+
117
+ if (shouldShowLeftDots && !shouldShowRightDots) {
118
+ const rightItemCount = boundaries + 1 + 2 * siblings;
119
+ return [
120
+ ...range(_startValue, _startValue + boundaries - 1),
121
+ DOTS,
122
+ ...range(_endValue - rightItemCount, _endValue),
123
+ ];
124
+ }
125
+
126
+ return [
127
+ ...range(_startValue, _startValue + boundaries - 1),
128
+ DOTS,
129
+ ...range(leftSiblingIndex, rightSiblingIndex),
130
+ DOTS,
131
+ ...range(_endValue - boundaries + 1, _endValue),
132
+ ];
133
+ }, [_total, siblings, activePage, _startValue, _endValue, boundaries]);
134
+
135
+ return {
136
+ range: paginationRange,
137
+ active: activePage,
138
+ setPage,
139
+ next,
140
+ previous,
141
+ first,
142
+ last,
143
+ };
144
+ }
145
+
146
+ export namespace usePagination {
147
+ export type Options = UsePaginationOptions;
148
+ export type ReturnValue = UsePaginationReturnValue;
149
+ }
@@ -0,0 +1,11 @@
1
+ import { useEffect, useRef } from 'octane';
2
+
3
+ export function usePrevious<T>(value: T): T | undefined {
4
+ const ref = useRef<T | undefined>(undefined);
5
+
6
+ useEffect(() => {
7
+ ref.current = value;
8
+ }, [value]);
9
+
10
+ return ref.current;
11
+ }
@@ -0,0 +1,71 @@
1
+ import { useState } from 'octane';
2
+
3
+ export interface UseQueueOptions<T> {
4
+ /** Initial values to be added to the queue */
5
+ initialValues?: T[];
6
+
7
+ /** Maximum number of items in the state */
8
+ limit: number;
9
+ }
10
+
11
+ export interface UseQueueReturnValue<T> {
12
+ /** Array of items in the queue */
13
+ queue: T[];
14
+
15
+ /** Array of items in the state */
16
+ state: T[];
17
+
18
+ /** Function to add items to state or queue */
19
+ add: (...items: T[]) => void;
20
+
21
+ /** Function to apply updates to current items */
22
+ update: (fn: (state: T[]) => T[]) => void;
23
+
24
+ /** Function to clear the queue */
25
+ cleanQueue: () => void;
26
+ }
27
+
28
+ export function useQueue<T>({
29
+ initialValues = [],
30
+ limit,
31
+ }: UseQueueOptions<T>): UseQueueReturnValue<T> {
32
+ const [state, setState] = useState({
33
+ state: initialValues.slice(0, limit),
34
+ queue: initialValues.slice(limit),
35
+ });
36
+
37
+ const add = (...items: T[]) =>
38
+ setState((current) => {
39
+ const results = [...current.state, ...current.queue, ...items];
40
+
41
+ return {
42
+ state: results.slice(0, limit),
43
+ queue: results.slice(limit),
44
+ };
45
+ });
46
+
47
+ const update = (fn: (state: T[]) => T[]) =>
48
+ setState((current) => {
49
+ const results = fn([...current.state, ...current.queue]);
50
+
51
+ return {
52
+ state: results.slice(0, limit),
53
+ queue: results.slice(limit),
54
+ };
55
+ });
56
+
57
+ const cleanQueue = () => setState((current) => ({ state: current.state, queue: [] }));
58
+
59
+ return {
60
+ state: state.state,
61
+ queue: state.queue,
62
+ add,
63
+ update,
64
+ cleanQueue,
65
+ };
66
+ }
67
+
68
+ export namespace useQueue {
69
+ export type Options<T> = UseQueueOptions<T>;
70
+ export type ReturnValue<T> = UseQueueReturnValue<T>;
71
+ }
@@ -0,0 +1,161 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'octane';
2
+ import { clamp } from '../utils';
3
+
4
+ function radiansToDegrees(radians: number) {
5
+ return radians * (180 / Math.PI);
6
+ }
7
+
8
+ function getElementCenter(element: HTMLElement) {
9
+ const rect = element.getBoundingClientRect();
10
+ return [rect.left + rect.width / 2, rect.top + rect.height / 2];
11
+ }
12
+
13
+ function getAngle(coordinates: [number, number], element: HTMLElement) {
14
+ const center = getElementCenter(element);
15
+ const x = coordinates[0] - center[0];
16
+ const y = coordinates[1] - center[1];
17
+ const deg = radiansToDegrees(Math.atan2(x, y)) + 180;
18
+ return 360 - deg;
19
+ }
20
+
21
+ function toFixed(value: number, digits: number) {
22
+ return parseFloat(value.toFixed(digits));
23
+ }
24
+
25
+ function getDigitsAfterDot(value: number) {
26
+ return value.toString().split('.')[1]?.length || 0;
27
+ }
28
+
29
+ export function normalizeRadialValue(degree: number, step: number) {
30
+ const clamped = clamp(degree, 0, 360);
31
+ const high = Math.ceil(clamped / step);
32
+ const low = Math.round(clamped / step);
33
+ return toFixed(
34
+ high >= clamped / step ? (high * step === 360 ? 0 : high * step) : low * step,
35
+ getDigitsAfterDot(step),
36
+ );
37
+ }
38
+
39
+ export interface UseRadialMoveOptions {
40
+ /** Number by which value is incremented/decremented with mouse and touch events, `0.01` by default */
41
+ step?: number;
42
+
43
+ /** Called in `onMouseUp` and `onTouchEnd` events with the current value */
44
+ onChangeEnd?: (value: number) => void;
45
+
46
+ /** Called in `onMouseDown` and `onTouchStart` events */
47
+ onScrubStart?: () => void;
48
+
49
+ /** Called in `onMouseUp` and `onTouchEnd` events */
50
+ onScrubEnd?: () => void;
51
+ }
52
+
53
+ export interface UseRadialMoveReturnValue<T extends HTMLElement = any> {
54
+ /** Ref to be passed to the element that should be used for radial move */
55
+ ref: React.RefCallback<T | null>;
56
+
57
+ /** Indicates whether the radial move is active */
58
+ active: boolean;
59
+ }
60
+
61
+ export function useRadialMove<T extends HTMLElement = any>(
62
+ onChange: (value: number) => void,
63
+ { step = 0.01, onChangeEnd, onScrubStart, onScrubEnd }: UseRadialMoveOptions = {},
64
+ ): UseRadialMoveReturnValue<T> {
65
+ const [active, setActive] = useState(false);
66
+ const cleanupRef = useRef<(() => void) | null>(null);
67
+
68
+ useEffect(() => {
69
+ return () => {
70
+ cleanupRef.current?.();
71
+ };
72
+ }, []);
73
+
74
+ const refCallback: React.RefCallback<T | null> = useCallback(
75
+ (node) => {
76
+ const update = (event: MouseEvent, done = false) => {
77
+ if (node) {
78
+ node.style.userSelect = 'none';
79
+ const deg = getAngle([event.clientX, event.clientY], node);
80
+ const newValue = normalizeRadialValue(deg, step || 1);
81
+
82
+ onChange(newValue);
83
+ done && onChangeEnd?.(newValue);
84
+ }
85
+ };
86
+
87
+ const beginTracking = () => {
88
+ onScrubStart?.();
89
+ setActive(true);
90
+ document.addEventListener('mousemove', handleMouseMove, false);
91
+ document.addEventListener('mouseup', handleMouseUp, false);
92
+ document.addEventListener('touchmove', handleTouchMove, { passive: false });
93
+ document.addEventListener('touchend', handleTouchEnd, false);
94
+ };
95
+
96
+ const endTracking = () => {
97
+ onScrubEnd?.();
98
+ setActive(false);
99
+ document.removeEventListener('mousemove', handleMouseMove, false);
100
+ document.removeEventListener('mouseup', handleMouseUp, false);
101
+ document.removeEventListener('touchmove', handleTouchMove, false);
102
+ document.removeEventListener('touchend', handleTouchEnd, false);
103
+ };
104
+
105
+ const onMouseDown = (event: MouseEvent) => {
106
+ beginTracking();
107
+ update(event);
108
+ };
109
+
110
+ const handleMouseMove = (event: MouseEvent) => {
111
+ update(event);
112
+ };
113
+
114
+ const handleMouseUp = (event: MouseEvent) => {
115
+ update(event, true);
116
+ endTracking();
117
+ };
118
+
119
+ const handleTouchMove = (event: TouchEvent) => {
120
+ event.preventDefault();
121
+ update(event.touches[0] as any);
122
+ };
123
+
124
+ const handleTouchEnd = (event: TouchEvent) => {
125
+ update(event.changedTouches[0] as any, true);
126
+ endTracking();
127
+ };
128
+
129
+ const handleTouchStart = (event: TouchEvent) => {
130
+ event.preventDefault();
131
+ beginTracking();
132
+ update(event.touches[0] as any);
133
+ };
134
+
135
+ node?.addEventListener('mousedown', onMouseDown);
136
+ node?.addEventListener('touchstart', handleTouchStart, { passive: false });
137
+
138
+ cleanupRef.current = () => {
139
+ document.removeEventListener('mousemove', handleMouseMove, false);
140
+ document.removeEventListener('mouseup', handleMouseUp, false);
141
+ document.removeEventListener('touchmove', handleTouchMove, false);
142
+ document.removeEventListener('touchend', handleTouchEnd, false);
143
+ };
144
+
145
+ return () => {
146
+ if (node) {
147
+ node.removeEventListener('mousedown', onMouseDown);
148
+ node.removeEventListener('touchstart', handleTouchStart);
149
+ }
150
+ };
151
+ },
152
+ [onChange],
153
+ );
154
+
155
+ return { ref: refCallback, active };
156
+ }
157
+
158
+ export namespace useRadialMove {
159
+ export type Options = UseRadialMoveOptions;
160
+ export type ReturnValue<T extends HTMLElement> = UseRadialMoveReturnValue<T>;
161
+ }
@@ -0,0 +1,6 @@
1
+ import { useMediaQuery } from '../use-media-query/use-media-query';
2
+ import type { UseMediaQueryOptions } from '../use-media-query/use-media-query';
3
+
4
+ export function useReducedMotion(initialValue?: boolean, options?: UseMediaQueryOptions) {
5
+ return useMediaQuery('(prefers-reduced-motion: reduce)', initialValue, options);
6
+ }
@@ -0,0 +1,95 @@
1
+ import { useCallback, useRef, useState } from 'octane';
2
+
3
+ export type ObserverRect = Omit<DOMRectReadOnly, 'toJSON'>;
4
+
5
+ const defaultState: ObserverRect = {
6
+ x: 0,
7
+ y: 0,
8
+ width: 0,
9
+ height: 0,
10
+ top: 0,
11
+ left: 0,
12
+ bottom: 0,
13
+ right: 0,
14
+ };
15
+
16
+ export type UseResizeObserverReturnValue<T extends HTMLElement = any> = [
17
+ React.RefCallback<T | null>,
18
+ ObserverRect,
19
+ ];
20
+
21
+ export function useResizeObserver<T extends HTMLElement = any>(
22
+ options?: ResizeObserverOptions,
23
+ ): UseResizeObserverReturnValue<T> {
24
+ const frameID = useRef(0);
25
+ const [rect, setRect] = useState<ObserverRect>(defaultState);
26
+ const observerRef = useRef<ResizeObserver | null>(null);
27
+
28
+ const refCallback: React.RefCallback<T | null> = useCallback(
29
+ (node) => {
30
+ if (observerRef.current) {
31
+ observerRef.current.disconnect();
32
+ observerRef.current = null;
33
+ }
34
+
35
+ if (frameID.current) {
36
+ cancelAnimationFrame(frameID.current);
37
+ }
38
+
39
+ if (!node) {
40
+ return;
41
+ }
42
+
43
+ observerRef.current = new ResizeObserver((entries) => {
44
+ const entry = entries[0];
45
+ if (entry) {
46
+ cancelAnimationFrame(frameID.current);
47
+ frameID.current = requestAnimationFrame(() => {
48
+ const boxSize = entry.borderBoxSize?.[0] || entry.contentBoxSize?.[0];
49
+ if (boxSize) {
50
+ const width = boxSize.inlineSize;
51
+ const height = boxSize.blockSize;
52
+ setRect({
53
+ width,
54
+ height,
55
+ x: entry.contentRect.x,
56
+ y: entry.contentRect.y,
57
+ top: entry.contentRect.top,
58
+ left: entry.contentRect.left,
59
+ bottom: entry.contentRect.bottom,
60
+ right: entry.contentRect.right,
61
+ });
62
+ } else {
63
+ setRect(entry.contentRect);
64
+ }
65
+ });
66
+ }
67
+ });
68
+ observerRef.current.observe(node, options);
69
+ },
70
+ [options],
71
+ );
72
+
73
+ return [refCallback, rect] as const;
74
+ }
75
+
76
+ export interface UseElementSizeReturnValue<T extends HTMLElement = any> {
77
+ ref: React.RefCallback<T | null>;
78
+ width: number;
79
+ height: number;
80
+ }
81
+
82
+ export function useElementSize<T extends HTMLElement = any>(
83
+ options?: ResizeObserverOptions,
84
+ ): { ref: React.RefCallback<T | null>; width: number; height: number } {
85
+ const [ref, { width, height }] = useResizeObserver<T>(options);
86
+ return { ref, width, height };
87
+ }
88
+
89
+ export namespace useResizeObserver {
90
+ export type ReturnValue<T extends HTMLElement> = UseResizeObserverReturnValue<T>;
91
+ }
92
+
93
+ export namespace useElementSize {
94
+ export type ReturnValue<T extends HTMLElement> = UseElementSizeReturnValue<T>;
95
+ }