@sohanemon/utils 4.0.27 → 4.0.29

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,28 +1,107 @@
1
1
  import * as React from 'react';
2
2
  export * from './action';
3
- export declare const useClickOutside: (callback?: () => void) => 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;
15
+ /**
16
+ * Runs an effect only once when the component mounts.
17
+ * @param effect - The effect callback function.
18
+ */
5
19
  export declare function useEffectOnce(effect: React.EffectCallback): void;
6
- export declare function useUpdateEffect(effect: React.EffectCallback, deps: any[]): 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;
33
+ /**
34
+ * Hook to handle effects with layout synchronization in the browser.
35
+ */
8
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;
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
+ */
11
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
+ */
23
97
  type CalculationProps = {
24
98
  blockIds: string[];
25
- dynamic?: boolean;
99
+ dynamic?: boolean | string;
26
100
  margin?: number;
27
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
+ */
28
107
  export declare const useHeightCalculation: ({ blockIds, margin, dynamic, }: CalculationProps) => number;
@@ -2,6 +2,11 @@
2
2
  import { copyToClipboard } from '../functions';
3
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
11
  const ref = React.useRef(null);
7
12
  const listener = (e) => {
@@ -19,6 +24,11 @@ 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
33
  const parsedQuery = React.useMemo(() => {
24
34
  switch (tailwindBreakpoint) {
@@ -43,11 +53,10 @@ export function useMediaQuery(tailwindBreakpoint) {
43
53
  return false;
44
54
  };
45
55
  const [matches, setMatches] = React.useState(getMatches(parsedQuery));
46
- function handleChange() {
56
+ const handleChange = () => {
47
57
  setMatches(getMatches(parsedQuery));
48
- }
49
- // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
50
- React.useEffect(() => {
58
+ };
59
+ useIsomorphicEffect(() => {
51
60
  const matchMedia = window.matchMedia(parsedQuery);
52
61
  handleChange();
53
62
  matchMedia.addEventListener('change', handleChange);
@@ -57,12 +66,21 @@ 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
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
82
  const isInitialMount = React.useRef(true);
65
- // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
83
+ // biome-ignore lint/correctness/useExhaustiveDependencies: only update specific
66
84
  React.useEffect(() => {
67
85
  if (isInitialMount.current) {
68
86
  isInitialMount.current = false;
@@ -72,6 +90,12 @@ 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
100
  const [debouncedState, setDebouncedState] = React.useState(state);
77
101
  React.useEffect(() => {
@@ -82,7 +106,15 @@ export function useDebounce(state, delay = 500) {
82
106
  }, [state, delay]);
83
107
  return debouncedState;
84
108
  }
109
+ /**
110
+ * Hook to handle effects with layout synchronization in the browser.
111
+ */
85
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
119
  const savedCallback = React.useRef(callback);
88
120
  useIsomorphicEffect(() => {
@@ -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
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
150
  const [storedValue, setStoredValue] = React.useState(defaultValue);
109
- // Use effect to retrieve the stored value from local storage on component mount
110
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
177
  const [value, setValue] = React.useState(defaultValue);
135
- // Use effect to retrieve the value from URL parameters on component mount
136
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,6 +190,11 @@ 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
199
  const [element, setElement] = React.useState(null);
154
200
  const elementRef = React.useRef(null);
@@ -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,6 +219,10 @@ 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
227
  const [isClient, setIsClient] = React.useState(false);
179
228
  React.useEffect(() => {
@@ -181,6 +230,9 @@ export function useIsClient() {
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
237
  React.useLayoutEffect(() => {
186
238
  const originalStyle = window.getComputedStyle(document.body).overflow;
@@ -190,6 +242,11 @@ 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
251
  const [isCopied, setIsCopied] = React.useState(false);
195
252
  const copy = (value) => {
@@ -202,16 +259,31 @@ 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
+ */
205
267
  export const useHeightCalculation = ({ blockIds = [], margin = 0, dynamic = false, }) => {
206
268
  const [height, setTableHeight] = React.useState(500);
207
269
  const handleResize = () => {
208
- const blcokHeight = blockIds.reduce((prevHeight, id) => prevHeight + (document.getElementById(id)?.clientHeight || 0), 0);
209
- setTableHeight(window.innerHeight - blcokHeight - margin);
270
+ const blockHeight = blockIds.reduce((prevHeight, id) => prevHeight + (document.getElementById(id)?.clientHeight || 0), 0);
271
+ setTableHeight(window.innerHeight - blockHeight - margin);
210
272
  };
211
273
  useIsomorphicEffect(() => {
212
274
  handleResize();
213
275
  if (!dynamic)
214
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
+ }
215
287
  window.addEventListener('resize', handleResize);
216
288
  return () => window.removeEventListener('resize', handleResize);
217
289
  }, []);
@@ -0,0 +1,6 @@
1
+ export type Primitive = string | number | bigint | boolean | symbol | null | undefined;
2
+ export type Falsy = false | '' | 0 | null | undefined;
3
+ export type Nullish = null | undefined;
4
+ export declare const isFalsy: (val: unknown) => val is Falsy;
5
+ export declare const isNullish: (val: unknown) => val is Nullish;
6
+ export declare const isPrimitive: (val: unknown) => val is Primitive;
@@ -0,0 +1,18 @@
1
+ export const isFalsy = (val) => !val;
2
+ export const isNullish = (val) => val == null;
3
+ export const isPrimitive = (val) => {
4
+ if (val === null || val === undefined) {
5
+ return true;
6
+ }
7
+ switch (typeof val) {
8
+ case 'string':
9
+ case 'number':
10
+ case 'bigint':
11
+ case 'boolean':
12
+ case 'symbol': {
13
+ return true;
14
+ }
15
+ default:
16
+ return false;
17
+ }
18
+ };
@@ -0,0 +1,2 @@
1
+ export * from './utilities';
2
+ export * from './guards';
@@ -0,0 +1,2 @@
1
+ export * from './utilities';
2
+ export * from './guards';
@@ -0,0 +1,26 @@
1
+ export type Keys<T extends object> = keyof T;
2
+ export type Values<T extends object> = T[keyof T];
3
+ export type DeepPartial<T> = T extends Function ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends object ? {
4
+ [K in keyof T]?: DeepPartial<T[K]>;
5
+ } : T;
6
+ export type SelectivePartial<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
7
+ export type DeepRequired<T> = T extends Function ? T : T extends Array<infer U> ? Array<DeepRequired<U>> : T extends object ? {
8
+ [K in keyof T]-?: DeepRequired<T[K]>;
9
+ } : T;
10
+ export type DeepReadonly<T> = T extends Function ? T : T extends Array<infer U> ? ReadonlyArray<DeepReadonly<U>> : T extends object ? {
11
+ readonly [K in keyof T]: DeepReadonly<T[K]>;
12
+ } : T;
13
+ export type Mutable<T> = {
14
+ -readonly [P in keyof T]: T[P];
15
+ };
16
+ export type KeysOfType<T, U> = {
17
+ [K in keyof T]: T[K] extends U ? K : never;
18
+ }[keyof T];
19
+ export type OmitByType<T, U> = {
20
+ [K in keyof T as T[K] extends U ? never : K]: T[K];
21
+ };
22
+ export type RequiredKeys<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
23
+ export type Diff<T, U> = Omit<T, keyof U> & Omit<U, keyof T>;
24
+ export type Intersection<T extends object, U extends object> = Pick<T, Extract<keyof T, keyof U> & Extract<keyof U, keyof T>>;
25
+ export type Merge<T extends object, U extends object, I = Diff<T, U> & Intersection<U, T> & Diff<U, T>> = Pick<I, keyof I>;
26
+ export type Substract<T extends object, U extends object> = Omit<T, keyof U>;
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sohanemon/utils",
3
- "version": "4.0.27",
3
+ "version": "4.0.29",
4
4
  "author": "Sohan Emon <sohanemon@outlook.com>",
5
5
  "description": "",
6
6
  "type": "module",
@@ -18,6 +18,9 @@
18
18
  "core": [
19
19
  "dist/index.d.ts"
20
20
  ],
21
+ "types": [
22
+ "dist/types/index.d.ts"
23
+ ],
21
24
  "hooks": [
22
25
  "dist/hooks/index.d.ts"
23
26
  ],