@sohanemon/utils 4.0.26 → 4.0.28

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.
@@ -1,22 +1,107 @@
1
- import { type Dispatch, type EffectCallback, type SetStateAction, useLayoutEffect } from 'react';
1
+ import * as React from 'react';
2
2
  export * from './action';
3
- export declare const useClickOutside: (callback?: () => void) => import("react").MutableRefObject<HTMLDivElement>;
3
+ /**
4
+ * Hook to detect clicks outside of a referenced element.
5
+ * @param callback - A function to invoke when a click outside is detected.
6
+ * @returns A React ref object to attach to the target element.
7
+ */
8
+ export declare const useClickOutside: (callback?: () => void) => React.RefObject<HTMLDivElement>;
9
+ /**
10
+ * Hook to match a media query based on Tailwind CSS breakpoints or custom queries.
11
+ * @param tailwindBreakpoint - The Tailwind breakpoint or custom query string.
12
+ * @returns A boolean indicating whether the media query matches.
13
+ */
4
14
  export declare function useMediaQuery(tailwindBreakpoint: 'sm' | 'md' | 'lg' | 'xl' | '2xl' | `(${string})`): boolean;
5
- export declare function useEffectOnce(effect: EffectCallback): void;
6
- export declare function useUpdateEffect(effect: EffectCallback, deps: any[]): void;
15
+ /**
16
+ * Runs an effect only once when the component mounts.
17
+ * @param effect - The effect callback function.
18
+ */
19
+ export declare function useEffectOnce(effect: React.EffectCallback): void;
20
+ /**
21
+ * Runs an effect only when dependencies update, excluding the initial render.
22
+ * @param effect - The effect callback function.
23
+ * @param deps - Dependency array for the effect.
24
+ */
25
+ export declare function useUpdateEffect(effect: React.EffectCallback, deps: React.DependencyList): void;
26
+ /**
27
+ * Debounces a state value with a specified delay.
28
+ * @param state - The state value to debounce.
29
+ * @param delay - The debounce delay in milliseconds (default: 500ms).
30
+ * @returns The debounced state value.
31
+ */
7
32
  export declare function useDebounce<T>(state: T, delay?: number): T;
8
- export declare const useIsomorphicEffect: typeof useLayoutEffect;
33
+ /**
34
+ * Hook to handle effects with layout synchronization in the browser.
35
+ */
36
+ export declare const useIsomorphicEffect: typeof React.useLayoutEffect;
37
+ /**
38
+ * Hook to invoke a callback after a specified timeout.
39
+ * @param callback - The callback function to invoke.
40
+ * @param delay - The timeout delay in milliseconds (default: 1000ms).
41
+ */
9
42
  export declare function useTimeout(callback: () => void, delay?: number | null): void;
10
- export declare function useWindowEvent<K extends string = keyof WindowEventMap>(type: K, listener: K extends keyof WindowEventMap ? (this: Window, ev: WindowEventMap[K]) => void : (this: Window, ev: CustomEvent) => void, options?: boolean | AddEventListenerOptions): void;
11
- type LocalStorageValue<T> = [T, Dispatch<SetStateAction<T>>];
43
+ /**
44
+ * Hook to add and remove a window event listener.
45
+ * @param type - The type of the event to listen for.
46
+ * @param listener - The event listener callback.
47
+ * @param options - Options for the event listener.
48
+ */
49
+ export declare function useWindowEvent<K extends keyof WindowEventMap>(type: K, listener: (this: Window, ev: WindowEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void;
50
+ /**
51
+ * Tuple type for local storage value and updater.
52
+ */
53
+ type LocalStorageValue<T> = [T, React.Dispatch<React.SetStateAction<T>>];
54
+ /**
55
+ * Hook to persist state in local storage.
56
+ * @param key - The key for local storage.
57
+ * @param defaultValue - The default value if no value is found in local storage.
58
+ * @returns A tuple of the stored value and an updater function.
59
+ */
12
60
  export declare const useLocalStorage: <T extends Record<string, any>>(key: string, defaultValue: T) => LocalStorageValue<T>;
61
+ /**
62
+ * Hook to manage URL parameters as state.
63
+ * @param key - The URL parameter key.
64
+ * @param defaultValue - The default value if the parameter is not present.
65
+ * @returns A tuple of the parameter value and a setter function.
66
+ */
13
67
  export declare const useUrlParams: <T extends string | number | boolean>(key: string, defaultValue: T) => [T, (value: T) => void];
68
+ /**
69
+ * Hook to select a DOM element by CSS selector.
70
+ * @param selector - The CSS selector string.
71
+ * @returns The selected DOM element or null if not found.
72
+ */
14
73
  export declare const useQuerySelector: <T extends Element>(selector: string) => T | null;
74
+ /**
75
+ * Hook to detect if the code is running on the client side.
76
+ * @returns A boolean indicating whether the code is running on the client.
77
+ */
15
78
  export declare function useIsClient(): boolean;
79
+ /**
80
+ * Hook to lock scroll by disabling body overflow.
81
+ */
16
82
  export declare function useLockScroll(): void;
83
+ /**
84
+ * Hook to copy text to the clipboard and track the copy status.
85
+ * @param timeout - The timeout duration in milliseconds to reset the copy status (default: 2000ms).
86
+ * @returns An object with the `isCopied` state and `copy` function.
87
+ */
17
88
  export declare function useCopyToClipboard({ timeout }: {
18
89
  timeout?: number;
19
90
  }): {
20
- isCopied: Boolean;
91
+ isCopied: boolean;
21
92
  copy: (value: string) => void;
22
93
  };
94
+ /**
95
+ * Properties for height calculation.
96
+ */
97
+ type CalculationProps = {
98
+ blockIds: string[];
99
+ dynamic?: boolean | string;
100
+ margin?: number;
101
+ };
102
+ /**
103
+ * Hook to calculate the height of an element based on viewport and other block heights.
104
+ * @param params - Configuration object for height calculation.
105
+ * @returns The calculated height.
106
+ */
107
+ export declare const useHeightCalculation: ({ blockIds, margin, dynamic, }: CalculationProps) => number;
@@ -1,15 +1,20 @@
1
1
  'use client';
2
- import { useEffect, useLayoutEffect, useMemo, useRef, useState, } from 'react';
3
2
  import { copyToClipboard } from '../functions';
3
+ import * as React from 'react';
4
4
  export * from './action';
5
+ /**
6
+ * Hook to detect clicks outside of a referenced element.
7
+ * @param callback - A function to invoke when a click outside is detected.
8
+ * @returns A React ref object to attach to the target element.
9
+ */
5
10
  export const useClickOutside = (callback = () => alert('clicked outside')) => {
6
- const ref = useRef(null);
11
+ const ref = React.useRef(null);
7
12
  const listener = (e) => {
8
13
  if (ref.current && !ref.current.contains(e.target)) {
9
14
  callback();
10
15
  }
11
16
  };
12
- useEffect(() => {
17
+ React.useEffect(() => {
13
18
  document.addEventListener('mousedown', listener);
14
19
  document.addEventListener('touchstart', listener);
15
20
  return () => {
@@ -19,8 +24,13 @@ export const useClickOutside = (callback = () => alert('clicked outside')) => {
19
24
  });
20
25
  return ref;
21
26
  };
27
+ /**
28
+ * Hook to match a media query based on Tailwind CSS breakpoints or custom queries.
29
+ * @param tailwindBreakpoint - The Tailwind breakpoint or custom query string.
30
+ * @returns A boolean indicating whether the media query matches.
31
+ */
22
32
  export function useMediaQuery(tailwindBreakpoint) {
23
- const parsedQuery = useMemo(() => {
33
+ const parsedQuery = React.useMemo(() => {
24
34
  switch (tailwindBreakpoint) {
25
35
  case 'sm':
26
36
  return '(min-width: 640px)';
@@ -42,12 +52,11 @@ export function useMediaQuery(tailwindBreakpoint) {
42
52
  }
43
53
  return false;
44
54
  };
45
- const [matches, setMatches] = useState(getMatches(parsedQuery));
46
- function handleChange() {
55
+ const [matches, setMatches] = React.useState(getMatches(parsedQuery));
56
+ const handleChange = () => {
47
57
  setMatches(getMatches(parsedQuery));
48
- }
49
- // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
50
- useEffect(() => {
58
+ };
59
+ useIsomorphicEffect(() => {
51
60
  const matchMedia = window.matchMedia(parsedQuery);
52
61
  handleChange();
53
62
  matchMedia.addEventListener('change', handleChange);
@@ -57,13 +66,22 @@ export function useMediaQuery(tailwindBreakpoint) {
57
66
  }, [parsedQuery]);
58
67
  return matches;
59
68
  }
69
+ /**
70
+ * Runs an effect only once when the component mounts.
71
+ * @param effect - The effect callback function.
72
+ */
60
73
  export function useEffectOnce(effect) {
61
- useEffect(effect, []);
74
+ React.useEffect(effect, []);
62
75
  }
76
+ /**
77
+ * Runs an effect only when dependencies update, excluding the initial render.
78
+ * @param effect - The effect callback function.
79
+ * @param deps - Dependency array for the effect.
80
+ */
63
81
  export function useUpdateEffect(effect, deps) {
64
- const isInitialMount = useRef(true);
65
- // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
66
- useEffect(() => {
82
+ const isInitialMount = React.useRef(true);
83
+ // biome-ignore lint/correctness/useExhaustiveDependencies: only update specific
84
+ React.useEffect(() => {
67
85
  if (isInitialMount.current) {
68
86
  isInitialMount.current = false;
69
87
  }
@@ -72,9 +90,15 @@ export function useUpdateEffect(effect, deps) {
72
90
  }
73
91
  }, deps);
74
92
  }
93
+ /**
94
+ * Debounces a state value with a specified delay.
95
+ * @param state - The state value to debounce.
96
+ * @param delay - The debounce delay in milliseconds (default: 500ms).
97
+ * @returns The debounced state value.
98
+ */
75
99
  export function useDebounce(state, delay = 500) {
76
- const [debouncedState, setDebouncedState] = useState(state);
77
- useEffect(() => {
100
+ const [debouncedState, setDebouncedState] = React.useState(state);
101
+ React.useEffect(() => {
78
102
  const timer = setTimeout(() => setDebouncedState(state), delay);
79
103
  return () => {
80
104
  clearTimeout(timer);
@@ -82,13 +106,21 @@ export function useDebounce(state, delay = 500) {
82
106
  }, [state, delay]);
83
107
  return debouncedState;
84
108
  }
85
- export const useIsomorphicEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
109
+ /**
110
+ * Hook to handle effects with layout synchronization in the browser.
111
+ */
112
+ export const useIsomorphicEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
113
+ /**
114
+ * Hook to invoke a callback after a specified timeout.
115
+ * @param callback - The callback function to invoke.
116
+ * @param delay - The timeout delay in milliseconds (default: 1000ms).
117
+ */
86
118
  export function useTimeout(callback, delay = 1000) {
87
- const savedCallback = useRef(callback);
119
+ const savedCallback = React.useRef(callback);
88
120
  useIsomorphicEffect(() => {
89
121
  savedCallback.current = callback;
90
122
  }, [callback]);
91
- useEffect(() => {
123
+ React.useEffect(() => {
92
124
  if (!delay && delay !== 0) {
93
125
  return;
94
126
  }
@@ -96,30 +128,36 @@ export function useTimeout(callback, delay = 1000) {
96
128
  return () => clearTimeout(id);
97
129
  }, [delay]);
98
130
  }
131
+ /**
132
+ * Hook to add and remove a window event listener.
133
+ * @param type - The type of the event to listen for.
134
+ * @param listener - The event listener callback.
135
+ * @param options - Options for the event listener.
136
+ */
99
137
  export function useWindowEvent(type, listener, options) {
100
- // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
101
- useEffect(() => {
138
+ React.useEffect(() => {
102
139
  window.addEventListener(type, listener, options);
103
140
  return () => window.removeEventListener(type, listener, options);
104
- }, [type, listener]);
141
+ }, [type, listener, options]);
105
142
  }
106
- // Custom hook for using local storage with a specified key and default value
143
+ /**
144
+ * Hook to persist state in local storage.
145
+ * @param key - The key for local storage.
146
+ * @param defaultValue - The default value if no value is found in local storage.
147
+ * @returns A tuple of the stored value and an updater function.
148
+ */
107
149
  export const useLocalStorage = (key, defaultValue) => {
108
- const [storedValue, setStoredValue] = useState(defaultValue);
109
- // Use effect to retrieve the stored value from local storage on component mount
110
- useEffect(() => {
150
+ const [storedValue, setStoredValue] = React.useState(defaultValue);
151
+ React.useEffect(() => {
111
152
  const value = localStorage.getItem(key);
112
153
  if (value) {
113
154
  setStoredValue(JSON.parse(value));
114
155
  }
115
156
  }, [key]);
116
- // Function to update the stored value in local storage and state
117
157
  const updateStoredValue = (valueOrFn) => {
118
- // biome-ignore lint/suspicious/noImplicitAnyLet: <explanation>
119
158
  let newValue;
120
159
  if (typeof valueOrFn === 'function') {
121
- const updateFunction = valueOrFn;
122
- newValue = updateFunction(storedValue);
160
+ newValue = valueOrFn(storedValue);
123
161
  }
124
162
  else {
125
163
  newValue = valueOrFn;
@@ -129,18 +167,21 @@ export const useLocalStorage = (key, defaultValue) => {
129
167
  };
130
168
  return [storedValue, updateStoredValue];
131
169
  };
132
- // Custom hook for using URL parameters with a specified key and default value
170
+ /**
171
+ * Hook to manage URL parameters as state.
172
+ * @param key - The URL parameter key.
173
+ * @param defaultValue - The default value if the parameter is not present.
174
+ * @returns A tuple of the parameter value and a setter function.
175
+ */
133
176
  export const useUrlParams = (key, defaultValue) => {
134
- const [value, setValue] = useState(defaultValue);
135
- // Use effect to retrieve the value from URL parameters on component mount
136
- useEffect(() => {
177
+ const [value, setValue] = React.useState(defaultValue);
178
+ React.useEffect(() => {
137
179
  const params = new URLSearchParams(window.location.search);
138
- const value = params.get(key);
139
- if (value !== null) {
140
- setValue(value);
180
+ const paramValue = params.get(key);
181
+ if (paramValue !== null) {
182
+ setValue(paramValue);
141
183
  }
142
184
  }, [key]);
143
- // Function to update the value in URL parameters and state
144
185
  const updateValue = (newValue) => {
145
186
  const params = new URLSearchParams(window.location.search);
146
187
  params.set(key, String(newValue));
@@ -149,10 +190,15 @@ export const useUrlParams = (key, defaultValue) => {
149
190
  };
150
191
  return [value, updateValue];
151
192
  };
193
+ /**
194
+ * Hook to select a DOM element by CSS selector.
195
+ * @param selector - The CSS selector string.
196
+ * @returns The selected DOM element or null if not found.
197
+ */
152
198
  export const useQuerySelector = (selector) => {
153
- const [element, setElement] = useState(null);
154
- const elementRef = useRef(null);
155
- useLayoutEffect(() => {
199
+ const [element, setElement] = React.useState(null);
200
+ const elementRef = React.useRef(null);
201
+ React.useLayoutEffect(() => {
156
202
  const referenceElement = document.querySelector(selector);
157
203
  if (!referenceElement)
158
204
  return;
@@ -161,7 +207,6 @@ export const useQuerySelector = (selector) => {
161
207
  setElement(referenceElement);
162
208
  }
163
209
  const resizeObserver = new ResizeObserver(() => {
164
- // Only update state if the element reference changes
165
210
  if (elementRef.current !== referenceElement) {
166
211
  elementRef.current = referenceElement;
167
212
  setElement(referenceElement);
@@ -174,15 +219,22 @@ export const useQuerySelector = (selector) => {
174
219
  }, [selector]);
175
220
  return element;
176
221
  };
222
+ /**
223
+ * Hook to detect if the code is running on the client side.
224
+ * @returns A boolean indicating whether the code is running on the client.
225
+ */
177
226
  export function useIsClient() {
178
- const [isClient, setIsClient] = useState(false);
179
- useEffect(() => {
227
+ const [isClient, setIsClient] = React.useState(false);
228
+ React.useEffect(() => {
180
229
  setIsClient(true);
181
230
  }, []);
182
231
  return isClient;
183
232
  }
233
+ /**
234
+ * Hook to lock scroll by disabling body overflow.
235
+ */
184
236
  export function useLockScroll() {
185
- useLayoutEffect(() => {
237
+ React.useLayoutEffect(() => {
186
238
  const originalStyle = window.getComputedStyle(document.body).overflow;
187
239
  document.body.style.overflow = 'hidden';
188
240
  return () => {
@@ -190,8 +242,13 @@ export function useLockScroll() {
190
242
  };
191
243
  }, []);
192
244
  }
245
+ /**
246
+ * Hook to copy text to the clipboard and track the copy status.
247
+ * @param timeout - The timeout duration in milliseconds to reset the copy status (default: 2000ms).
248
+ * @returns An object with the `isCopied` state and `copy` function.
249
+ */
193
250
  export function useCopyToClipboard({ timeout = 2000 }) {
194
- const [isCopied, setIsCopied] = useState(false);
251
+ const [isCopied, setIsCopied] = React.useState(false);
195
252
  const copy = (value) => {
196
253
  copyToClipboard(value, () => {
197
254
  setIsCopied(true);
@@ -202,3 +259,33 @@ export function useCopyToClipboard({ timeout = 2000 }) {
202
259
  };
203
260
  return { isCopied, copy };
204
261
  }
262
+ /**
263
+ * Hook to calculate the height of an element based on viewport and other block heights.
264
+ * @param params - Configuration object for height calculation.
265
+ * @returns The calculated height.
266
+ */
267
+ export const useHeightCalculation = ({ blockIds = [], margin = 0, dynamic = false, }) => {
268
+ const [height, setTableHeight] = React.useState(500);
269
+ const handleResize = () => {
270
+ const blockHeight = blockIds.reduce((prevHeight, id) => prevHeight + (document.getElementById(id)?.clientHeight || 0), 0);
271
+ setTableHeight(window.innerHeight - blockHeight - margin);
272
+ };
273
+ useIsomorphicEffect(() => {
274
+ handleResize();
275
+ if (!dynamic)
276
+ return;
277
+ if (typeof dynamic === 'string') {
278
+ const resizableElement = document.getElementById(dynamic);
279
+ const resizeObserver = new ResizeObserver((entries) => {
280
+ for (const _ of entries)
281
+ handleResize();
282
+ });
283
+ if (resizableElement)
284
+ resizeObserver.observe(resizableElement);
285
+ return () => resizeObserver?.disconnect();
286
+ }
287
+ window.addEventListener('resize', handleResize);
288
+ return () => window.removeEventListener('resize', handleResize);
289
+ }, []);
290
+ return height;
291
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sohanemon/utils",
3
- "version": "4.0.26",
3
+ "version": "4.0.28",
4
4
  "author": "Sohan Emon <sohanemon@outlook.com>",
5
5
  "description": "",
6
6
  "type": "module",