react-simplikit 0.0.2 → 0.0.3

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 (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -0
  3. package/dist/components/ImpressionArea/index.d.ts +48 -0
  4. package/dist/components/ImpressionArea/index.js +276 -0
  5. package/dist/components/Separated/index.d.ts +38 -0
  6. package/dist/components/Separated/index.js +40 -0
  7. package/dist/components/SwitchCase/index.d.ts +46 -0
  8. package/dist/components/SwitchCase/index.js +35 -0
  9. package/dist/hooks/useAsyncEffect/index.d.ts +25 -0
  10. package/dist/hooks/useAsyncEffect/index.js +43 -0
  11. package/dist/hooks/useBooleanState/index.d.ts +19 -0
  12. package/dist/hooks/useBooleanState/index.js +45 -0
  13. package/dist/hooks/useCallbackOnce/index.d.ts +41 -0
  14. package/dist/hooks/useCallbackOnce/index.js +59 -0
  15. package/dist/hooks/useDebounce/index.d.ts +47 -0
  16. package/dist/hooks/useDebounce/index.js +123 -0
  17. package/dist/hooks/useImpressionRef/index.d.ts +38 -0
  18. package/dist/hooks/useImpressionRef/index.js +237 -0
  19. package/dist/hooks/useInputState/index.d.ts +27 -0
  20. package/dist/hooks/useInputState/index.js +45 -0
  21. package/dist/hooks/useIntersectionObserver/index.d.ts +33 -0
  22. package/dist/hooks/useIntersectionObserver/index.js +91 -0
  23. package/dist/hooks/useInterval/index.d.ts +37 -0
  24. package/dist/hooks/useInterval/index.js +64 -0
  25. package/dist/hooks/useLoading/index.d.ts +37 -0
  26. package/dist/hooks/useLoading/index.js +61 -0
  27. package/dist/hooks/useOutsideClickEffect/index.d.ts +27 -0
  28. package/dist/hooks/useOutsideClickEffect/index.js +70 -0
  29. package/dist/hooks/usePreservedCallback/index.d.ts +30 -0
  30. package/dist/hooks/usePreservedCallback/index.js +41 -0
  31. package/dist/hooks/usePreservedReference/index.d.ts +42 -0
  32. package/dist/hooks/usePreservedReference/index.js +44 -0
  33. package/dist/hooks/usePrevious/index.d.ts +21 -0
  34. package/dist/hooks/usePrevious/index.js +47 -0
  35. package/dist/hooks/useRefEffect/index.d.ts +31 -0
  36. package/dist/hooks/useRefEffect/index.js +68 -0
  37. package/dist/hooks/useStorageState/index.d.ts +50 -0
  38. package/dist/hooks/useStorageState/index.js +168 -0
  39. package/dist/hooks/useThrottle/index.d.ts +47 -0
  40. package/dist/hooks/useThrottle/index.js +147 -0
  41. package/dist/hooks/useTimeout/index.d.ts +30 -0
  42. package/dist/hooks/useTimeout/index.js +53 -0
  43. package/dist/hooks/useToggle/index.d.ts +30 -0
  44. package/dist/hooks/useToggle/index.js +36 -0
  45. package/dist/hooks/useVisibilityEvent/index.d.ts +27 -0
  46. package/dist/hooks/useVisibilityEvent/index.js +46 -0
  47. package/dist/index.d.ts +26 -0
  48. package/dist/index.js +761 -0
  49. package/dist/utils/buildContext/index.d.ts +38 -0
  50. package/dist/utils/buildContext/index.js +55 -0
  51. package/dist/utils/mergeRefs/index.d.ts +37 -0
  52. package/dist/utils/mergeRefs/index.js +45 -0
  53. package/esm/components/ImpressionArea/index.d.mts +48 -0
  54. package/esm/components/ImpressionArea/index.mjs +249 -0
  55. package/esm/components/Separated/index.d.mts +38 -0
  56. package/esm/components/Separated/index.mjs +13 -0
  57. package/esm/components/SwitchCase/index.d.mts +46 -0
  58. package/esm/components/SwitchCase/index.mjs +8 -0
  59. package/esm/hooks/useAsyncEffect/index.d.mts +25 -0
  60. package/esm/hooks/useAsyncEffect/index.mjs +16 -0
  61. package/esm/hooks/useBooleanState/index.d.mts +19 -0
  62. package/esm/hooks/useBooleanState/index.mjs +18 -0
  63. package/esm/hooks/useCallbackOnce/index.d.mts +41 -0
  64. package/esm/hooks/useCallbackOnce/index.mjs +32 -0
  65. package/esm/hooks/useDebounce/index.d.mts +47 -0
  66. package/esm/hooks/useDebounce/index.mjs +96 -0
  67. package/esm/hooks/useImpressionRef/index.d.mts +38 -0
  68. package/esm/hooks/useImpressionRef/index.mjs +210 -0
  69. package/esm/hooks/useInputState/index.d.mts +27 -0
  70. package/esm/hooks/useInputState/index.mjs +18 -0
  71. package/esm/hooks/useIntersectionObserver/index.d.mts +33 -0
  72. package/esm/hooks/useIntersectionObserver/index.mjs +64 -0
  73. package/esm/hooks/useInterval/index.d.mts +37 -0
  74. package/esm/hooks/useInterval/index.mjs +37 -0
  75. package/esm/hooks/useLoading/index.d.mts +37 -0
  76. package/esm/hooks/useLoading/index.mjs +34 -0
  77. package/esm/hooks/useOutsideClickEffect/index.d.mts +27 -0
  78. package/esm/hooks/useOutsideClickEffect/index.mjs +43 -0
  79. package/esm/hooks/usePreservedCallback/index.d.mts +30 -0
  80. package/esm/hooks/usePreservedCallback/index.mjs +14 -0
  81. package/esm/hooks/usePreservedReference/index.d.mts +42 -0
  82. package/esm/hooks/usePreservedReference/index.mjs +17 -0
  83. package/esm/hooks/usePrevious/index.d.mts +21 -0
  84. package/esm/hooks/usePrevious/index.mjs +20 -0
  85. package/esm/hooks/useRefEffect/index.d.mts +31 -0
  86. package/esm/hooks/useRefEffect/index.mjs +41 -0
  87. package/esm/hooks/useStorageState/index.d.mts +50 -0
  88. package/esm/hooks/useStorageState/index.mjs +141 -0
  89. package/esm/hooks/useThrottle/index.d.mts +47 -0
  90. package/esm/hooks/useThrottle/index.mjs +120 -0
  91. package/esm/hooks/useTimeout/index.d.mts +30 -0
  92. package/esm/hooks/useTimeout/index.mjs +26 -0
  93. package/esm/hooks/useToggle/index.d.mts +30 -0
  94. package/esm/hooks/useToggle/index.mjs +9 -0
  95. package/esm/hooks/useVisibilityEvent/index.d.mts +27 -0
  96. package/esm/hooks/useVisibilityEvent/index.mjs +19 -0
  97. package/esm/index.d.mts +26 -0
  98. package/esm/index.mjs +711 -0
  99. package/esm/utils/buildContext/index.d.mts +38 -0
  100. package/esm/utils/buildContext/index.mjs +28 -0
  101. package/esm/utils/mergeRefs/index.d.mts +37 -0
  102. package/esm/utils/mergeRefs/index.mjs +18 -0
  103. package/package.json +79 -7
@@ -0,0 +1,41 @@
1
+ import { DependencyList } from 'react';
2
+
3
+ /**
4
+ * @description
5
+ * A React hook that ensures a callback function is executed only once, regardless of
6
+ * how many times it's called. This is useful for one-time operations that should not
7
+ * be repeated, even if the component re-renders.
8
+ *
9
+ * @param {() => void} callback - The callback function to be executed once.
10
+ * @param {DependencyList} deps - Dependencies array that will trigger a new one-time execution when changed.
11
+ *
12
+ * @returns {(...args: any[]) => void} A memoized function that will only execute once until dependencies change.
13
+ *
14
+ * @example
15
+ * import { useCallbackOnce } from 'react-simplikit';
16
+ *
17
+ * function Component() {
18
+ * const handleOneTimeEvent = useCallbackOnce(() => {
19
+ * console.log('This will only run once');
20
+ * }, []);
21
+ *
22
+ * return <button onClick={handleOneTimeEvent}>Click me</button>;
23
+ * }
24
+ *
25
+ * @example
26
+ * // With dependencies
27
+ * function TrackingComponent({ userId }: { userId: string }) {
28
+ * const trackUserVisit = useCallbackOnce(() => {
29
+ * analytics.trackVisit(userId);
30
+ * }, [userId]);
31
+ *
32
+ * useEffect(() => {
33
+ * trackUserVisit();
34
+ * }, [trackUserVisit]);
35
+ *
36
+ * return <div>User page</div>;
37
+ * }
38
+ */
39
+ declare function useCallbackOnce<F extends (...args: any[]) => void>(callback: F, deps: DependencyList): (...args: Parameters<F>) => void;
40
+
41
+ export { useCallbackOnce };
@@ -0,0 +1,32 @@
1
+ // src/hooks/useCallbackOnce/useCallbackOnce.ts
2
+ import { useEffect as useEffect2, useRef as useRef2 } from "react";
3
+
4
+ // src/hooks/usePreservedCallback/usePreservedCallback.ts
5
+ import { useCallback, useEffect, useRef } from "react";
6
+ function usePreservedCallback(callback) {
7
+ const callbackRef = useRef(callback);
8
+ useEffect(() => {
9
+ callbackRef.current = callback;
10
+ }, [callback]);
11
+ return useCallback((...args) => {
12
+ return callbackRef.current(...args);
13
+ }, []);
14
+ }
15
+
16
+ // src/hooks/useCallbackOnce/useCallbackOnce.ts
17
+ function useCallbackOnce(callback, deps) {
18
+ const hasFired = useRef2(false);
19
+ useEffect2(() => {
20
+ hasFired.current = false;
21
+ }, deps);
22
+ return usePreservedCallback((...args) => {
23
+ if (hasFired.current) {
24
+ return;
25
+ }
26
+ callback(...args);
27
+ hasFired.current = true;
28
+ });
29
+ }
30
+ export {
31
+ useCallbackOnce
32
+ };
@@ -0,0 +1,47 @@
1
+ type DebouncedFunction<F extends (...args: any[]) => void> = {
2
+ (...args: Parameters<F>): void;
3
+ cancel: () => void;
4
+ };
5
+
6
+ type DebounceOptions = {
7
+ leading?: boolean;
8
+ trailing?: boolean;
9
+ };
10
+ /**
11
+ * @description
12
+ * `useDebounce` is a React hook that returns a debounced version of the provided callback function.
13
+ * It helps optimize event handling by delaying function execution and grouping multiple calls into one.
14
+ *
15
+ * @param {F} callback - The function to debounce.
16
+ * @param {number} wait - The number of milliseconds to delay the function execution.
17
+ * @param {object} [options] - Configuration options for debounce behavior.
18
+ * @param {boolean} [options.leading=false] - If `true`, the function is called at the start of the sequence.
19
+ * @param {boolean} [options.trailing=true] - If `true`, the function is called at the end of the sequence.
20
+ *
21
+ * @returns {F & { cancel: () => void }} A debounced function that delays invoking the callback.
22
+ * It also includes a `cancel` method to cancel any pending debounced execution.
23
+ *
24
+ * @example
25
+ * function SearchInput() {
26
+ * const [query, setQuery] = useState('');
27
+ *
28
+ * const debouncedSearch = useDebounce((value: string) => {
29
+ * // Actual API call
30
+ * searchAPI(value);
31
+ * }, 300);
32
+ *
33
+ * return (
34
+ * <input
35
+ * value={query}
36
+ * onChange={e => {
37
+ * setQuery(e.target.value);
38
+ * debouncedSearch(e.target.value);
39
+ * }}
40
+ * placeholder="Enter search term"
41
+ * />
42
+ * );
43
+ * }
44
+ */
45
+ declare function useDebounce<F extends (...args: any[]) => unknown>(callback: F, wait: number, options?: DebounceOptions): DebouncedFunction<F>;
46
+
47
+ export { useDebounce };
@@ -0,0 +1,96 @@
1
+ // src/hooks/useDebounce/useDebounce.ts
2
+ import { useEffect as useEffect2 } from "react";
3
+ import { useMemo } from "react";
4
+
5
+ // src/hooks/usePreservedCallback/usePreservedCallback.ts
6
+ import { useCallback, useEffect, useRef } from "react";
7
+ function usePreservedCallback(callback) {
8
+ const callbackRef = useRef(callback);
9
+ useEffect(() => {
10
+ callbackRef.current = callback;
11
+ }, [callback]);
12
+ return useCallback((...args) => {
13
+ return callbackRef.current(...args);
14
+ }, []);
15
+ }
16
+
17
+ // src/hooks/useDebounce/debounce.ts
18
+ function debounce(func, debounceMs, { edges = ["leading", "trailing"] } = {}) {
19
+ let pendingThis = void 0;
20
+ let pendingArgs = null;
21
+ const leading = edges != null && edges.includes("leading");
22
+ const trailing = edges == null || edges.includes("trailing");
23
+ const invoke = () => {
24
+ if (pendingArgs !== null) {
25
+ func.apply(pendingThis, pendingArgs);
26
+ pendingThis = void 0;
27
+ pendingArgs = null;
28
+ }
29
+ };
30
+ const onTimerEnd = () => {
31
+ if (trailing) {
32
+ invoke();
33
+ }
34
+ cancel();
35
+ };
36
+ let timeoutId = null;
37
+ const schedule = () => {
38
+ if (timeoutId != null) {
39
+ clearTimeout(timeoutId);
40
+ }
41
+ timeoutId = setTimeout(() => {
42
+ timeoutId = null;
43
+ onTimerEnd();
44
+ }, debounceMs);
45
+ };
46
+ const cancelTimer = () => {
47
+ if (timeoutId !== null) {
48
+ clearTimeout(timeoutId);
49
+ timeoutId = null;
50
+ }
51
+ };
52
+ const cancel = () => {
53
+ cancelTimer();
54
+ pendingThis = void 0;
55
+ pendingArgs = null;
56
+ };
57
+ const debounced = function(...args) {
58
+ pendingThis = this;
59
+ pendingArgs = args;
60
+ const isFirstCall = timeoutId == null;
61
+ schedule();
62
+ if (leading && isFirstCall) {
63
+ invoke();
64
+ }
65
+ };
66
+ debounced.cancel = cancel;
67
+ return debounced;
68
+ }
69
+
70
+ // src/hooks/useDebounce/useDebounce.ts
71
+ function useDebounce(callback, wait, options = {}) {
72
+ const preservedCallback = usePreservedCallback(callback);
73
+ const { leading = false, trailing = true } = options;
74
+ const edges = useMemo(() => {
75
+ const _edges = [];
76
+ if (leading) {
77
+ _edges.push("leading");
78
+ }
79
+ if (trailing) {
80
+ _edges.push("trailing");
81
+ }
82
+ return _edges;
83
+ }, [leading, trailing]);
84
+ const debounced = useMemo(() => {
85
+ return debounce(preservedCallback, wait, { edges });
86
+ }, [preservedCallback, wait, edges]);
87
+ useEffect2(() => {
88
+ return () => {
89
+ debounced.cancel();
90
+ };
91
+ }, [debounced]);
92
+ return debounced;
93
+ }
94
+ export {
95
+ useDebounce
96
+ };
@@ -0,0 +1,38 @@
1
+ type UseImpressionRefOptions = Partial<{
2
+ onImpressionStart: () => void;
3
+ onImpressionEnd: () => void;
4
+ rootMargin: string;
5
+ areaThreshold: number;
6
+ timeThreshold: number;
7
+ }>;
8
+ /**
9
+ * @description
10
+ * `useImpressionRef` is a custom hook that measures the time a specific DOM element is visible on the screen and executes callbacks when the element enters or exits the viewport.
11
+ * This hook uses `IntersectionObserver` and the `Visibility API` to track the element's visibility.
12
+ *
13
+ * @param options - An options object for tracking the element's visibility.
14
+ * - `onImpressionStart`: Callback function executed when the element enters the view
15
+ * - `onImpressionEnd`: Callback function executed when the element exits the view
16
+ * - `timeThreshold`: Minimum time the element must be visible (in milliseconds)
17
+ * - `areaThreshold`: Minimum ratio of the element that must be visible (0 to 1)
18
+ * - `rootMargin`: Margin to adjust the detection area
19
+ *
20
+ * @returns A function to set the element. Attach this function to the `ref` attribute, and the callbacks will be executed whenever the element's visibility changes.
21
+ *
22
+ * @example
23
+ * import { useImpressionRef } from 'react-simplikit';
24
+ *
25
+ * function Component() {
26
+ * const ref = useImpressionRef<HTMLDivElement>({
27
+ * onImpressionStart: () => console.log('Element entered view'),
28
+ * onImpressionEnd: () => console.log('Element exited view'),
29
+ * timeThreshold: 1000,
30
+ * areaThreshold: 0.5,
31
+ * });
32
+ *
33
+ * return <div ref={ref}>Track my visibility!</div>;
34
+ * }
35
+ */
36
+ declare function useImpressionRef<Element extends HTMLElement>({ onImpressionStart, onImpressionEnd, rootMargin, areaThreshold, timeThreshold, }: UseImpressionRefOptions): (element: Element | null) => void;
37
+
38
+ export { type UseImpressionRefOptions, useImpressionRef };
@@ -0,0 +1,210 @@
1
+ // src/hooks/useImpressionRef/useImpressionRef.ts
2
+ import { useRef as useRef4 } from "react";
3
+
4
+ // src/hooks/useIntersectionObserver/useIntersectionObserver.ts
5
+ import { useMemo } from "react";
6
+
7
+ // src/hooks/usePreservedCallback/usePreservedCallback.ts
8
+ import { useCallback, useEffect, useRef } from "react";
9
+ function usePreservedCallback(callback) {
10
+ const callbackRef = useRef(callback);
11
+ useEffect(() => {
12
+ callbackRef.current = callback;
13
+ }, [callback]);
14
+ return useCallback((...args) => {
15
+ return callbackRef.current(...args);
16
+ }, []);
17
+ }
18
+
19
+ // src/hooks/useRefEffect/useRefEffect.ts
20
+ import { useCallback as useCallback2, useRef as useRef2 } from "react";
21
+ function useRefEffect(callback, deps) {
22
+ const preservedCallback = usePreservedCallback(callback);
23
+ const cleanupCallbackRef = useRef2(() => {
24
+ });
25
+ const effect = useCallback2(
26
+ (element) => {
27
+ cleanupCallbackRef.current();
28
+ cleanupCallbackRef.current = () => {
29
+ };
30
+ if (element == null) {
31
+ return;
32
+ }
33
+ const cleanup = preservedCallback(element);
34
+ if (typeof cleanup === "function") {
35
+ cleanupCallbackRef.current = cleanup;
36
+ }
37
+ },
38
+ // eslint-disable-next-line react-hooks/exhaustive-deps
39
+ [preservedCallback, ...deps]
40
+ );
41
+ return effect;
42
+ }
43
+
44
+ // src/hooks/useIntersectionObserver/useIntersectionObserver.ts
45
+ function useIntersectionObserver(callback, options) {
46
+ const preservedCallback = usePreservedCallback(callback);
47
+ const observer = useMemo(() => {
48
+ if (typeof IntersectionObserver === "undefined") {
49
+ return;
50
+ }
51
+ return new IntersectionObserver(([entry]) => {
52
+ preservedCallback(entry);
53
+ }, options);
54
+ }, [preservedCallback, options]);
55
+ return useRefEffect(
56
+ (element) => {
57
+ observer?.observe(element);
58
+ return () => {
59
+ observer?.unobserve(element);
60
+ };
61
+ },
62
+ [preservedCallback, options]
63
+ );
64
+ }
65
+
66
+ // src/hooks/useVisibilityEvent/useVisibilityEvent.ts
67
+ import { useCallback as useCallback3, useEffect as useEffect2 } from "react";
68
+ function useVisibilityEvent(callback, options = {}) {
69
+ const handleVisibilityChange = useCallback3(() => {
70
+ callback(document.visibilityState);
71
+ }, [callback]);
72
+ useEffect2(() => {
73
+ if (options?.immediate ?? false) {
74
+ handleVisibilityChange();
75
+ }
76
+ document.addEventListener("visibilitychange", handleVisibilityChange);
77
+ return () => {
78
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
79
+ };
80
+ }, [handleVisibilityChange, options?.immediate]);
81
+ }
82
+
83
+ // src/hooks/useImpressionRef/useDebouncedCallback.ts
84
+ import { useCallback as useCallback4, useEffect as useEffect3, useRef as useRef3 } from "react";
85
+
86
+ // src/hooks/useDebounce/debounce.ts
87
+ function debounce(func, debounceMs, { edges = ["leading", "trailing"] } = {}) {
88
+ let pendingThis = void 0;
89
+ let pendingArgs = null;
90
+ const leading = edges != null && edges.includes("leading");
91
+ const trailing = edges == null || edges.includes("trailing");
92
+ const invoke = () => {
93
+ if (pendingArgs !== null) {
94
+ func.apply(pendingThis, pendingArgs);
95
+ pendingThis = void 0;
96
+ pendingArgs = null;
97
+ }
98
+ };
99
+ const onTimerEnd = () => {
100
+ if (trailing) {
101
+ invoke();
102
+ }
103
+ cancel();
104
+ };
105
+ let timeoutId = null;
106
+ const schedule = () => {
107
+ if (timeoutId != null) {
108
+ clearTimeout(timeoutId);
109
+ }
110
+ timeoutId = setTimeout(() => {
111
+ timeoutId = null;
112
+ onTimerEnd();
113
+ }, debounceMs);
114
+ };
115
+ const cancelTimer = () => {
116
+ if (timeoutId !== null) {
117
+ clearTimeout(timeoutId);
118
+ timeoutId = null;
119
+ }
120
+ };
121
+ const cancel = () => {
122
+ cancelTimer();
123
+ pendingThis = void 0;
124
+ pendingArgs = null;
125
+ };
126
+ const debounced = function(...args) {
127
+ pendingThis = this;
128
+ pendingArgs = args;
129
+ const isFirstCall = timeoutId == null;
130
+ schedule();
131
+ if (leading && isFirstCall) {
132
+ invoke();
133
+ }
134
+ };
135
+ debounced.cancel = cancel;
136
+ return debounced;
137
+ }
138
+
139
+ // src/hooks/useImpressionRef/useDebouncedCallback.ts
140
+ function useDebouncedCallback({
141
+ onChange,
142
+ timeThreshold
143
+ }) {
144
+ const handleChange = usePreservedCallback(onChange);
145
+ const ref = useRef3({ value: false, clearPreviousDebounce: () => {
146
+ } });
147
+ useEffect3(() => {
148
+ const current = ref.current;
149
+ return () => {
150
+ current.clearPreviousDebounce();
151
+ };
152
+ }, []);
153
+ return useCallback4(
154
+ (nextValue) => {
155
+ if (nextValue === ref.current.value) {
156
+ return;
157
+ }
158
+ const debounced = debounce(() => {
159
+ handleChange(nextValue);
160
+ ref.current.value = nextValue;
161
+ }, timeThreshold);
162
+ ref.current.clearPreviousDebounce();
163
+ debounced();
164
+ ref.current.clearPreviousDebounce = debounced.cancel;
165
+ },
166
+ [handleChange, timeThreshold]
167
+ );
168
+ }
169
+
170
+ // src/hooks/useImpressionRef/useImpressionRef.ts
171
+ function useImpressionRef({
172
+ onImpressionStart = () => {
173
+ },
174
+ onImpressionEnd = () => {
175
+ },
176
+ rootMargin,
177
+ areaThreshold = 0,
178
+ timeThreshold = 0
179
+ }) {
180
+ const impressionStartHandler = usePreservedCallback(onImpressionStart);
181
+ const impressionEndHandler = usePreservedCallback(onImpressionEnd);
182
+ const isIntersectingRef = useRef4(false);
183
+ const impressionEventHandler = useDebouncedCallback({
184
+ timeThreshold,
185
+ onChange: (impressed) => {
186
+ (impressed ? impressionStartHandler : impressionEndHandler)();
187
+ }
188
+ });
189
+ useVisibilityEvent((documentVisible) => {
190
+ if (!isIntersectingRef.current) {
191
+ return;
192
+ }
193
+ impressionEventHandler(documentVisible === "visible");
194
+ });
195
+ return useIntersectionObserver(
196
+ (entry) => {
197
+ if (document.visibilityState === "hidden") {
198
+ return;
199
+ }
200
+ const currentRatio = entry.intersectionRatio;
201
+ const isIntersecting = areaThreshold === 0 ? entry.isIntersecting : currentRatio >= areaThreshold;
202
+ isIntersectingRef.current = isIntersecting;
203
+ impressionEventHandler(isIntersecting);
204
+ },
205
+ { rootMargin, threshold: areaThreshold }
206
+ );
207
+ }
208
+ export {
209
+ useImpressionRef
210
+ };
@@ -0,0 +1,27 @@
1
+ import { ChangeEventHandler } from 'react';
2
+
3
+ /**
4
+ * @description
5
+ * `useInputState` is a React hook that manages an input state with optional value transformation.
6
+ *
7
+ * @param {string} initialValue - The initial value of the input. Defaults to an empty string (`""`).
8
+ * @param {(value: string) => string} [transformValue] - A function to transform the input value.
9
+ * Defaults to an identity function that returns the input unchanged.
10
+ *
11
+ * @returns {readonly [string, (value: string) => void]} A tuple containing:
12
+ * - `string` - The current state value.
13
+ * - `(value: string) => void` - A function to update the state.
14
+ *
15
+ * @example
16
+ * import { useInputState } from 'react-simplikit';
17
+ *
18
+ * function Example() {
19
+ * const [value, setValue] = useInputState('');
20
+ * return <input type="text" value={value} onChange={setValue} />;
21
+ * }
22
+ */
23
+ declare function useInputState(initialValue?: string, transformValue?: (value: string) => string): readonly [string, ChangeEventHandler<HTMLElement & {
24
+ value: string;
25
+ }>];
26
+
27
+ export { useInputState };
@@ -0,0 +1,18 @@
1
+ // src/hooks/useInputState/useInputState.ts
2
+ import { useCallback, useState } from "react";
3
+ function useInputState(initialValue = "", transformValue = echo) {
4
+ const [value, setValue] = useState(initialValue);
5
+ const handleValueChange = useCallback(
6
+ ({ target: { value: value2 } }) => {
7
+ setValue(transformValue(value2));
8
+ },
9
+ [transformValue]
10
+ );
11
+ return [value, handleValueChange];
12
+ }
13
+ function echo(v) {
14
+ return v;
15
+ }
16
+ export {
17
+ useInputState
18
+ };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @description
3
+ * `useIntersectionObserver` is a custom hook that detects whether a specific DOM element is visible on the screen.
4
+ * This hook uses the `IntersectionObserver` API to execute a callback when the element enters or exits the viewport.
5
+ *
6
+ * @param callback - A callback function that is executed when the visibility of the element changes.
7
+ * You can check `entry.isIntersecting` to determine if the element is in view.
8
+ * @param options - Options for the `IntersectionObserver`.
9
+ * You can specify values such as `root`, `rootMargin`, and `threshold`.
10
+ *
11
+ * @returns A function to set the element. Attach this function to the `ref` attribute, and the `callback` will be executed whenever the element's visibility changes.
12
+ *
13
+ * @example
14
+ * import { useIntersectionObserver } from 'react-simplikit';
15
+ *
16
+ * function Component() {
17
+ * const ref = useIntersectionObserver<HTMLDivElement>(
18
+ * entry => {
19
+ * if (entry.isIntersecting) {
20
+ * console.log('Element is in view:', entry.target);
21
+ * } else {
22
+ * console.log('Element is out of view:', entry.target);
23
+ * }
24
+ * },
25
+ * { threshold: 0.5 }
26
+ * );
27
+ *
28
+ * return <div ref={ref}>Observe me!</div>;
29
+ * }
30
+ */
31
+ declare function useIntersectionObserver<Element extends HTMLElement>(callback: (entry: IntersectionObserverEntry) => void, options: IntersectionObserverInit): (element: Element | null) => void;
32
+
33
+ export { useIntersectionObserver };
@@ -0,0 +1,64 @@
1
+ // src/hooks/useIntersectionObserver/useIntersectionObserver.ts
2
+ import { useMemo } from "react";
3
+
4
+ // src/hooks/usePreservedCallback/usePreservedCallback.ts
5
+ import { useCallback, useEffect, useRef } from "react";
6
+ function usePreservedCallback(callback) {
7
+ const callbackRef = useRef(callback);
8
+ useEffect(() => {
9
+ callbackRef.current = callback;
10
+ }, [callback]);
11
+ return useCallback((...args) => {
12
+ return callbackRef.current(...args);
13
+ }, []);
14
+ }
15
+
16
+ // src/hooks/useRefEffect/useRefEffect.ts
17
+ import { useCallback as useCallback2, useRef as useRef2 } from "react";
18
+ function useRefEffect(callback, deps) {
19
+ const preservedCallback = usePreservedCallback(callback);
20
+ const cleanupCallbackRef = useRef2(() => {
21
+ });
22
+ const effect = useCallback2(
23
+ (element) => {
24
+ cleanupCallbackRef.current();
25
+ cleanupCallbackRef.current = () => {
26
+ };
27
+ if (element == null) {
28
+ return;
29
+ }
30
+ const cleanup = preservedCallback(element);
31
+ if (typeof cleanup === "function") {
32
+ cleanupCallbackRef.current = cleanup;
33
+ }
34
+ },
35
+ // eslint-disable-next-line react-hooks/exhaustive-deps
36
+ [preservedCallback, ...deps]
37
+ );
38
+ return effect;
39
+ }
40
+
41
+ // src/hooks/useIntersectionObserver/useIntersectionObserver.ts
42
+ function useIntersectionObserver(callback, options) {
43
+ const preservedCallback = usePreservedCallback(callback);
44
+ const observer = useMemo(() => {
45
+ if (typeof IntersectionObserver === "undefined") {
46
+ return;
47
+ }
48
+ return new IntersectionObserver(([entry]) => {
49
+ preservedCallback(entry);
50
+ }, options);
51
+ }, [preservedCallback, options]);
52
+ return useRefEffect(
53
+ (element) => {
54
+ observer?.observe(element);
55
+ return () => {
56
+ observer?.unobserve(element);
57
+ };
58
+ },
59
+ [preservedCallback, options]
60
+ );
61
+ }
62
+ export {
63
+ useIntersectionObserver
64
+ };
@@ -0,0 +1,37 @@
1
+ type IntervalOptions = number | {
2
+ delay: number;
3
+ immediate?: boolean;
4
+ enabled?: boolean;
5
+ };
6
+ /**
7
+ * @description
8
+ * `useInterval` is a React hook that executes a function at a specified interval.
9
+ * It is useful for timers, polling data, and other recurring tasks.
10
+ *
11
+ * @param {() => void} callback - The function to be executed periodically.
12
+ * @param {number | { delay: number; enabled?: boolean; immediate?: boolean }} options - Configures the interval behavior.
13
+ * @param {number} options.delay - The interval duration in milliseconds. If `null`, the interval will not run.
14
+ * @param {boolean} [options.immediate=false] - If `true`, executes immediately before starting the interval.
15
+ * @param {boolean} [options.enabled=true] - If `false`, the interval will not run.
16
+ *
17
+ * @example
18
+ * import { useInterval } from 'react-simplikit';
19
+ * import { useState } from 'react';
20
+ *
21
+ * function Timer() {
22
+ * const [time, setTime] = useState(0);
23
+ *
24
+ * useInterval(() => {
25
+ * setTime(prev => prev + 1);
26
+ * }, 1000);
27
+ *
28
+ * return (
29
+ * <div>
30
+ * <p>{time} seconds</p>
31
+ * </div>
32
+ * );
33
+ * }
34
+ */
35
+ declare function useInterval(callback: () => void, options: IntervalOptions): void;
36
+
37
+ export { useInterval };
@@ -0,0 +1,37 @@
1
+ // src/hooks/useInterval/useInterval.ts
2
+ import { useEffect as useEffect2 } from "react";
3
+
4
+ // src/hooks/usePreservedCallback/usePreservedCallback.ts
5
+ import { useCallback, useEffect, useRef } from "react";
6
+ function usePreservedCallback(callback) {
7
+ const callbackRef = useRef(callback);
8
+ useEffect(() => {
9
+ callbackRef.current = callback;
10
+ }, [callback]);
11
+ return useCallback((...args) => {
12
+ return callbackRef.current(...args);
13
+ }, []);
14
+ }
15
+
16
+ // src/hooks/useInterval/useInterval.ts
17
+ function useInterval(callback, options) {
18
+ const delay = typeof options === "number" ? options : options.delay;
19
+ const immediate = typeof options === "number" ? false : options.immediate;
20
+ const enabled = typeof options === "number" ? true : options.enabled ?? true;
21
+ const preservedCallback = usePreservedCallback(callback);
22
+ useEffect2(() => {
23
+ if (immediate === true && enabled) {
24
+ preservedCallback();
25
+ }
26
+ }, [immediate, preservedCallback, enabled]);
27
+ useEffect2(() => {
28
+ if (!enabled) {
29
+ return;
30
+ }
31
+ const id = window.setInterval(preservedCallback, delay);
32
+ return () => window.clearInterval(id);
33
+ }, [delay, preservedCallback, enabled]);
34
+ }
35
+ export {
36
+ useInterval
37
+ };