@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,155 @@
1
+ import { useEffect, useEffectEvent, useRef, useState } from 'octane';
2
+ import { randomId } from '../utils';
3
+
4
+ function getHeadingsData(
5
+ headings: HTMLElement[],
6
+ getDepth: (element: HTMLElement) => number,
7
+ getValue: (element: HTMLElement) => string,
8
+ ): UseScrollSpyHeadingData[] {
9
+ const result: UseScrollSpyHeadingData[] = [];
10
+
11
+ for (let i = 0; i < headings.length; i += 1) {
12
+ const heading = headings[i];
13
+ result.push({
14
+ depth: getDepth(heading),
15
+ value: getValue(heading),
16
+ id: heading.id || randomId(),
17
+ getNode: () => (heading.id ? document.getElementById(heading.id)! : heading),
18
+ });
19
+ }
20
+
21
+ return result;
22
+ }
23
+
24
+ function getActiveElement(rects: DOMRect[], offset: number = 0) {
25
+ if (rects.length === 0) {
26
+ return -1;
27
+ }
28
+
29
+ const closest = rects.reduce(
30
+ (acc, item, index) => {
31
+ if (Math.abs(acc.position - offset) < Math.abs(item.y - offset)) {
32
+ return acc;
33
+ }
34
+
35
+ return {
36
+ index,
37
+ position: item.y,
38
+ };
39
+ },
40
+ { index: 0, position: rects[0].y },
41
+ );
42
+
43
+ return closest.index;
44
+ }
45
+
46
+ function getDefaultDepth(element: HTMLElement) {
47
+ return Number(element.tagName[1]);
48
+ }
49
+
50
+ function getDefaultValue(element: HTMLElement) {
51
+ return element.textContent || '';
52
+ }
53
+
54
+ export interface UseScrollSpyHeadingData {
55
+ /** Heading depth, 1-6 */
56
+ depth: number;
57
+
58
+ /** Heading text content value */
59
+ value: string;
60
+
61
+ /** Heading id */
62
+ id: string;
63
+
64
+ /** Function to get heading node */
65
+ getNode: () => HTMLElement;
66
+ }
67
+
68
+ export interface UseScrollSpyOptions {
69
+ /** Selector to get headings, `'h1, h2, h3, h4, h5, h6'` by default */
70
+ selector?: string;
71
+
72
+ /** A function to retrieve depth of heading, by default depth is calculated based on tag name */
73
+ getDepth?: (element: HTMLElement) => number;
74
+
75
+ /** A function to retrieve heading value, by default `element.textContent` is used */
76
+ getValue?: (element: HTMLElement) => string;
77
+
78
+ /** Host element to attach scroll event listener, if not provided, `window` is used */
79
+ scrollHost?: HTMLElement;
80
+
81
+ /** Offset from the top of the viewport to use when determining the active heading, `0` by default */
82
+ offset?: number;
83
+ }
84
+
85
+ export interface UseScrollSpyReturnValue {
86
+ /** Index of the active heading in the `data` array */
87
+ active: number;
88
+
89
+ /** Headings data. If not initialize, data is represented by an empty array. */
90
+ data: UseScrollSpyHeadingData[];
91
+
92
+ /** True if headings value have been retrieved from the DOM. */
93
+ initialized: boolean;
94
+
95
+ /** Function to update headings values after the parent component has mounted. */
96
+ reinitialize: () => void;
97
+ }
98
+
99
+ export function useScrollSpy({
100
+ selector = 'h1, h2, h3, h4, h5, h6',
101
+ getDepth = getDefaultDepth,
102
+ getValue = getDefaultValue,
103
+ offset = 0,
104
+ scrollHost,
105
+ }: UseScrollSpyOptions = {}): UseScrollSpyReturnValue {
106
+ const [active, setActive] = useState(-1);
107
+ const [initialized, setInitialized] = useState(false);
108
+ const [data, setData] = useState<UseScrollSpyHeadingData[]>([]);
109
+ const headingsRef = useRef<UseScrollSpyHeadingData[]>([]);
110
+
111
+ const handleScroll = useEffectEvent(() => {
112
+ setActive(
113
+ getActiveElement(
114
+ headingsRef.current.map((d) => d.getNode().getBoundingClientRect()),
115
+ offset,
116
+ ),
117
+ );
118
+ });
119
+
120
+ const initialize = () => {
121
+ const headings = getHeadingsData(
122
+ Array.from(document.querySelectorAll(selector)),
123
+ getDepth,
124
+ getValue,
125
+ );
126
+ headingsRef.current = headings;
127
+ setInitialized(true);
128
+ setData(headings);
129
+ setActive(
130
+ getActiveElement(
131
+ headings.map((d) => d.getNode().getBoundingClientRect()),
132
+ offset,
133
+ ),
134
+ );
135
+ };
136
+
137
+ useEffect(() => {
138
+ initialize();
139
+ const _scrollHost = scrollHost || window;
140
+ _scrollHost.addEventListener('scroll', handleScroll);
141
+ return () => _scrollHost.removeEventListener('scroll', handleScroll);
142
+ }, [scrollHost, selector, offset]);
143
+
144
+ return {
145
+ reinitialize: initialize,
146
+ active,
147
+ initialized,
148
+ data,
149
+ };
150
+ }
151
+
152
+ export namespace useScrollSpy {
153
+ export type Options = UseScrollSpyOptions;
154
+ export type ReturnValue = UseScrollSpyReturnValue;
155
+ }
@@ -0,0 +1,225 @@
1
+ import type { RefCallback } from 'react';
2
+ import { useCallback, useEffect, useRef, useState } from 'octane';
3
+
4
+ export interface UseScrollerOptions {
5
+ /** Amount of pixels to scroll when calling scroll functions, `200` by default */
6
+ scrollAmount?: number;
7
+
8
+ /** Determines whether content can be scrolled by dragging with mouse, `true` by default */
9
+ draggable?: boolean;
10
+
11
+ /** Called when scroll state changes (canScrollStart or canScrollEnd) */
12
+ onScrollStateChange?: (state: UseScrollerScrollState) => void;
13
+ }
14
+
15
+ export interface UseScrollerScrollState {
16
+ /** Whether content can be scrolled towards the start (left in LTR, right in RTL) */
17
+ canScrollStart: boolean;
18
+
19
+ /** Whether content can be scrolled towards the end (right in LTR, left in RTL) */
20
+ canScrollEnd: boolean;
21
+ }
22
+
23
+ export interface UseScrollerReturnValue<T extends HTMLElement = HTMLDivElement> {
24
+ /** Ref callback to attach to the scrollable container element */
25
+ ref: RefCallback<T | null>;
26
+
27
+ /** Whether content can be scrolled towards the start */
28
+ canScrollStart: boolean;
29
+
30
+ /** Whether content can be scrolled towards the end */
31
+ canScrollEnd: boolean;
32
+
33
+ /** Scrolls towards the start direction */
34
+ scrollStart: () => void;
35
+
36
+ /** Scrolls towards the end direction */
37
+ scrollEnd: () => void;
38
+
39
+ /** `true` if the user is currently dragging the content */
40
+ isDragging: boolean;
41
+
42
+ /** Props to spread on the scrollable container for drag functionality */
43
+ dragHandlers: {
44
+ onMouseDown: (e: React.MouseEvent) => void;
45
+ onMouseMove: (e: React.MouseEvent) => void;
46
+ onMouseUp: () => void;
47
+ onMouseLeave: () => void;
48
+ };
49
+ }
50
+
51
+ export function useScroller<T extends HTMLElement = HTMLDivElement>(
52
+ options: UseScrollerOptions = {},
53
+ ): UseScrollerReturnValue<T> {
54
+ const { scrollAmount = 200, draggable = true, onScrollStateChange } = options;
55
+
56
+ const containerRef = useRef<T | null>(null);
57
+
58
+ const [canScrollStart, setCanScrollStart] = useState(false);
59
+ const [canScrollEnd, setCanScrollEnd] = useState(false);
60
+ const [isDragging, setIsDragging] = useState(false);
61
+
62
+ const isDraggingRef = useRef(false);
63
+ const hasDraggedRef = useRef(false);
64
+ const startX = useRef(0);
65
+ const scrollLeftStart = useRef(0);
66
+
67
+ const onScrollStateChangeRef = useRef(onScrollStateChange);
68
+ onScrollStateChangeRef.current = onScrollStateChange;
69
+
70
+ const updateScrollState = useCallback(() => {
71
+ const container = containerRef.current;
72
+ if (container) {
73
+ const { scrollLeft, scrollWidth, clientWidth } = container;
74
+ const isRtl = getComputedStyle(container).direction === 'rtl';
75
+
76
+ let newCanScrollStart: boolean;
77
+ let newCanScrollEnd: boolean;
78
+
79
+ if (isRtl) {
80
+ newCanScrollStart = scrollLeft < -1;
81
+ newCanScrollEnd = scrollLeft > -(scrollWidth - clientWidth) + 1;
82
+ } else {
83
+ newCanScrollStart = scrollLeft > 1;
84
+ newCanScrollEnd = scrollLeft < scrollWidth - clientWidth - 1;
85
+ }
86
+
87
+ setCanScrollStart(newCanScrollStart);
88
+ setCanScrollEnd(newCanScrollEnd);
89
+
90
+ onScrollStateChangeRef.current?.({
91
+ canScrollStart: newCanScrollStart,
92
+ canScrollEnd: newCanScrollEnd,
93
+ });
94
+ }
95
+ }, []);
96
+
97
+ useEffect(() => {
98
+ updateScrollState();
99
+ const container = containerRef.current;
100
+ if (container) {
101
+ container.addEventListener('scroll', updateScrollState);
102
+ const resizeObserver = new ResizeObserver(updateScrollState);
103
+ resizeObserver.observe(container);
104
+ return () => {
105
+ container.removeEventListener('scroll', updateScrollState);
106
+ resizeObserver.disconnect();
107
+ };
108
+ }
109
+ return undefined;
110
+ }, [updateScrollState]);
111
+
112
+ const scroll = useCallback(
113
+ (direction: 'start' | 'end') => {
114
+ const container = containerRef.current;
115
+ if (container) {
116
+ const isRtl = getComputedStyle(container).direction === 'rtl';
117
+ const amount = scrollAmount;
118
+ const scrollBy = direction === 'end' ? amount : -amount;
119
+ const adjustedScrollBy = isRtl ? -scrollBy : scrollBy;
120
+
121
+ container.scrollBy({
122
+ left: adjustedScrollBy,
123
+ behavior: 'smooth',
124
+ });
125
+ }
126
+ },
127
+ [scrollAmount],
128
+ );
129
+
130
+ const scrollStart = useCallback(() => scroll('start'), [scroll]);
131
+ const scrollEnd = useCallback(() => scroll('end'), [scroll]);
132
+
133
+ const handleMouseDown = useCallback(
134
+ (event: React.MouseEvent) => {
135
+ if (!draggable) {
136
+ return;
137
+ }
138
+ const container = containerRef.current;
139
+ if (container) {
140
+ isDraggingRef.current = true;
141
+ hasDraggedRef.current = false;
142
+ setIsDragging(true);
143
+ startX.current = event.pageX - container.offsetLeft;
144
+ scrollLeftStart.current = container.scrollLeft;
145
+ container.style.cursor = 'grabbing';
146
+ container.style.userSelect = 'none';
147
+ }
148
+ },
149
+ [draggable],
150
+ );
151
+
152
+ const handleMouseMove = useCallback((event: React.MouseEvent) => {
153
+ if (!isDraggingRef.current) {
154
+ return;
155
+ }
156
+ event.preventDefault();
157
+ const container = containerRef.current;
158
+ if (container) {
159
+ const x = event.pageX - container.offsetLeft;
160
+ const walk = x - startX.current;
161
+ if (Math.abs(walk) > 5) {
162
+ hasDraggedRef.current = true;
163
+ }
164
+ container.scrollLeft = scrollLeftStart.current - walk;
165
+ }
166
+ }, []);
167
+
168
+ const handleMouseUp = useCallback(() => {
169
+ const wasDragged = hasDraggedRef.current;
170
+ isDraggingRef.current = false;
171
+ hasDraggedRef.current = false;
172
+ setIsDragging(false);
173
+ const container = containerRef.current;
174
+ if (container) {
175
+ container.style.cursor = '';
176
+ container.style.userSelect = '';
177
+
178
+ if (wasDragged) {
179
+ const suppressClick = (event: MouseEvent) => {
180
+ event.stopPropagation();
181
+ event.preventDefault();
182
+ container.removeEventListener('click', suppressClick, true);
183
+ };
184
+ container.addEventListener('click', suppressClick, true);
185
+ }
186
+ }
187
+ }, []);
188
+
189
+ const handleMouseLeave = useCallback(() => {
190
+ if (isDraggingRef.current) {
191
+ handleMouseUp();
192
+ }
193
+ }, [handleMouseUp]);
194
+
195
+ const assignRef: RefCallback<T | null> = useCallback(
196
+ (node) => {
197
+ containerRef.current = node;
198
+ if (node) {
199
+ updateScrollState();
200
+ }
201
+ },
202
+ [updateScrollState],
203
+ );
204
+
205
+ return {
206
+ ref: assignRef,
207
+ canScrollStart,
208
+ canScrollEnd,
209
+ scrollStart,
210
+ scrollEnd,
211
+ isDragging,
212
+ dragHandlers: {
213
+ onMouseDown: handleMouseDown,
214
+ onMouseMove: handleMouseMove,
215
+ onMouseUp: handleMouseUp,
216
+ onMouseLeave: handleMouseLeave,
217
+ },
218
+ };
219
+ }
220
+
221
+ export namespace useScroller {
222
+ export type Options = UseScrollerOptions;
223
+ export type ReturnValue<T extends HTMLElement = HTMLDivElement> = UseScrollerReturnValue<T>;
224
+ export type ScrollState = UseScrollerScrollState;
225
+ }
@@ -0,0 +1,120 @@
1
+ import { useCallback, useState } from 'octane';
2
+ import { useDidUpdate } from '../use-did-update/use-did-update';
3
+
4
+ export interface UseSelectionInput<T> {
5
+ /** The array of items to select from */
6
+ data: T[];
7
+
8
+ /** The initial selection, empty array by default */
9
+ defaultSelection?: T[];
10
+
11
+ /** If true, selection is reset when data changes */
12
+ resetSelectionOnDataChange?: boolean;
13
+ }
14
+
15
+ export interface UseSelectionHandlers<T> {
16
+ /** Add an item to the selection */
17
+ select: (selected: T) => void;
18
+
19
+ /** Remove an item from the selection */
20
+ deselect: (deselected: T) => void;
21
+
22
+ /** Toggle an item's selection state */
23
+ toggle: (toggled: T) => void;
24
+
25
+ /** Returns true if all items from the `data` are selected */
26
+ isAllSelected: () => boolean;
27
+
28
+ /** Returns true if at least one item from the `data` is selected */
29
+ isSomeSelected: () => boolean;
30
+
31
+ /** Set the selection to a specific array of items */
32
+ setSelection: (selection: T[]) => void;
33
+
34
+ /** Clear all selections */
35
+ resetSelection: () => void;
36
+ }
37
+
38
+ export type UseSelectionReturnValue<T> = readonly [T[], UseSelectionHandlers<T>];
39
+
40
+ export function useSelection<T>(input: UseSelectionInput<T>): UseSelectionReturnValue<T> {
41
+ const [selectionSet, setSelectionSet] = useState<Set<T>>(new Set(input.defaultSelection || []));
42
+
43
+ useDidUpdate(() => {
44
+ if (input.resetSelectionOnDataChange) {
45
+ setSelectionSet(new Set());
46
+ }
47
+ }, [input.data, input.resetSelectionOnDataChange]);
48
+
49
+ const select = useCallback((selected: T) => {
50
+ setSelectionSet((state) => {
51
+ if (!state.has(selected)) {
52
+ const newSet = new Set(state);
53
+ newSet.add(selected);
54
+ return newSet;
55
+ }
56
+ return state;
57
+ });
58
+ }, []);
59
+
60
+ const deselect = useCallback((deselected: T) => {
61
+ setSelectionSet((state) => {
62
+ if (state.has(deselected)) {
63
+ const newSet = new Set(state);
64
+ newSet.delete(deselected);
65
+ return newSet;
66
+ }
67
+ return state;
68
+ });
69
+ }, []);
70
+
71
+ const toggle = useCallback((toggled: T) => {
72
+ setSelectionSet((state) => {
73
+ const newSet = new Set(state);
74
+ if (state.has(toggled)) {
75
+ newSet.delete(toggled);
76
+ } else {
77
+ newSet.add(toggled);
78
+ }
79
+ return newSet;
80
+ });
81
+ }, []);
82
+
83
+ const resetSelection = useCallback(() => {
84
+ setSelectionSet(new Set());
85
+ }, []);
86
+
87
+ const setSelection = useCallback((selection: T[]) => {
88
+ setSelectionSet(new Set(selection));
89
+ }, []);
90
+
91
+ const isAllSelected = useCallback(() => {
92
+ if (input.data.length === 0) {
93
+ return false;
94
+ }
95
+ return input.data.every((item) => selectionSet.has(item));
96
+ }, [selectionSet, input.data]);
97
+
98
+ const isSomeSelected = useCallback(() => {
99
+ return input.data.some((item) => selectionSet.has(item));
100
+ }, [selectionSet, input.data]);
101
+
102
+ return [
103
+ Array.from(selectionSet),
104
+ {
105
+ select,
106
+ deselect,
107
+ toggle,
108
+ isAllSelected,
109
+ isSomeSelected,
110
+ setSelection,
111
+ resetSelection,
112
+ },
113
+ ];
114
+ }
115
+
116
+ export namespace useSelection {
117
+ export type Input<T> = UseSelectionInput<T>;
118
+ export type Handlers<T> = UseSelectionHandlers<T>;
119
+ export type ReturnValue<T> = UseSelectionReturnValue<T>;
120
+ }
@@ -0,0 +1,19 @@
1
+ import { createStorage, readValue } from '../use-local-storage/create-storage';
2
+ import type { UseStorageOptions, UseStorageReturnValue } from '../use-local-storage/create-storage';
3
+
4
+ export function useSessionStorage<T = string>(
5
+ props: UseStorageOptions<T> & { defaultValue: T },
6
+ ): UseStorageReturnValue<T>;
7
+ export function useSessionStorage<T = string>(
8
+ props: UseStorageOptions<T>,
9
+ ): UseStorageReturnValue<T | undefined>;
10
+ export function useSessionStorage<T = string>(props: UseStorageOptions<T>) {
11
+ return createStorage<T>('sessionStorage', 'use-session-storage')(props);
12
+ }
13
+
14
+ interface ReadStorageValue {
15
+ <T>(options: UseStorageOptions<T> & { defaultValue: T }): T;
16
+ <T>(options: UseStorageOptions<T>): T | undefined;
17
+ }
18
+
19
+ export const readSessionStorageValue: ReadStorageValue = readValue('sessionStorage');
@@ -0,0 +1,88 @@
1
+ import { useRef, useState } from 'octane';
2
+
3
+ export function readonlySetLikeToSet<T>(input: ReadonlySetLike<T>): Set<T> {
4
+ if (input instanceof Set) {
5
+ return input;
6
+ }
7
+ const result = new Set<T>();
8
+ const iterator = input.keys();
9
+ let next = iterator.next();
10
+ while (!next.done) {
11
+ result.add(next.value);
12
+ next = iterator.next();
13
+ }
14
+ return result;
15
+ }
16
+
17
+ export function useSet<T>(values?: T[]): Set<T> {
18
+ const normalizedValues = typeof values === 'symbol' ? undefined : values;
19
+ const [set, setSet] = useState(() => new Set(normalizedValues));
20
+ const setRef = useRef(set);
21
+ setRef.current = set;
22
+
23
+ set.add = (...args) => {
24
+ const res = Set.prototype.add.apply(setRef.current, args);
25
+ setSet(new Set(setRef.current));
26
+ return res;
27
+ };
28
+
29
+ set.clear = (...args) => {
30
+ Set.prototype.clear.apply(setRef.current, args);
31
+ setSet(new Set(setRef.current));
32
+ };
33
+
34
+ set.delete = (...args) => {
35
+ const res = Set.prototype.delete.apply(setRef.current, args);
36
+ setSet(new Set(setRef.current));
37
+ return res;
38
+ };
39
+
40
+ set.union = <U>(other: ReadonlySetLike<U>): Set<T | U> => {
41
+ const result = new Set<T | U>(setRef.current as Set<T>);
42
+ readonlySetLikeToSet(other).forEach((item) => result.add(item));
43
+ return result;
44
+ };
45
+
46
+ set.intersection = <U>(other: ReadonlySetLike<U>): Set<T & U> => {
47
+ const result = new Set<T & U>();
48
+ const otherSet = readonlySetLikeToSet(other);
49
+ setRef.current.forEach((item) => {
50
+ if (otherSet.has(item as any)) {
51
+ result.add(item as T & U);
52
+ }
53
+ });
54
+ return result;
55
+ };
56
+
57
+ set.difference = <U>(other: ReadonlySetLike<U>): Set<T> => {
58
+ const result = new Set<T>();
59
+ const otherSet = readonlySetLikeToSet(other);
60
+ setRef.current.forEach((item) => {
61
+ if (!otherSet.has(item as any)) {
62
+ result.add(item);
63
+ }
64
+ });
65
+ return result;
66
+ };
67
+
68
+ set.symmetricDifference = <U>(other: ReadonlySetLike<U>): Set<T | U> => {
69
+ const result = new Set<T | U>();
70
+ const otherSet = readonlySetLikeToSet(other);
71
+
72
+ setRef.current.forEach((item) => {
73
+ if (!otherSet.has(item as any)) {
74
+ result.add(item);
75
+ }
76
+ });
77
+
78
+ otherSet.forEach((item) => {
79
+ if (!setRef.current.has(item as any)) {
80
+ result.add(item);
81
+ }
82
+ });
83
+
84
+ return result;
85
+ };
86
+
87
+ return set;
88
+ }
@@ -0,0 +1,29 @@
1
+ import { useCallback, useState } from 'octane';
2
+
3
+ export type UseSetStateCallback<T> = (
4
+ state: Partial<T> | ((currentState: T) => Partial<T>),
5
+ ) => void;
6
+
7
+ export type UseSetStateReturnValue<T> = [T, UseSetStateCallback<T>];
8
+
9
+ export function useSetState<T extends Record<string, any>>(
10
+ initialState: T,
11
+ ): UseSetStateReturnValue<T> {
12
+ const [state, setState] = useState(initialState);
13
+
14
+ const _setState: UseSetStateCallback<T> = useCallback(
15
+ (statePartial) =>
16
+ setState((current) => ({
17
+ ...current,
18
+ ...(typeof statePartial === 'function' ? statePartial(current) : statePartial),
19
+ })),
20
+ [],
21
+ );
22
+
23
+ return [state, _setState];
24
+ }
25
+
26
+ export namespace useSetState {
27
+ export type Callback<T> = UseSetStateCallback<T>;
28
+ export type ReturnValue<T> = UseSetStateReturnValue<T>;
29
+ }
@@ -0,0 +1,40 @@
1
+ import { useEffect, useRef } from 'octane';
2
+ import { shallowEqual } from '../utils/shallow-equal/shallow-equal';
3
+
4
+ function shallowCompare(prevValue?: React.DependencyList | null, currValue?: React.DependencyList) {
5
+ if (!prevValue || !currValue) {
6
+ return false;
7
+ }
8
+
9
+ if (prevValue === currValue) {
10
+ return true;
11
+ }
12
+
13
+ if (prevValue.length !== currValue.length) {
14
+ return false;
15
+ }
16
+
17
+ for (let i = 0; i < prevValue.length; i += 1) {
18
+ if (!shallowEqual(prevValue[i], currValue[i])) {
19
+ return false;
20
+ }
21
+ }
22
+
23
+ return true;
24
+ }
25
+
26
+ function useShallowCompare(dependencies?: React.DependencyList) {
27
+ const ref = useRef<React.DependencyList | null | undefined>([]);
28
+ const updateRef = useRef<number>(0);
29
+
30
+ if (!shallowCompare(ref.current, dependencies)) {
31
+ ref.current = dependencies;
32
+ updateRef.current += 1;
33
+ }
34
+
35
+ return [updateRef.current];
36
+ }
37
+
38
+ export function useShallowEffect(cb: () => void, dependencies?: React.DependencyList): void {
39
+ useEffect(cb, useShallowCompare(dependencies));
40
+ }