@sohanemon/utils 5.0.7 → 5.0.8

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.
@@ -0,0 +1,417 @@
1
+ import { clsx } from 'clsx';
2
+ import { twMerge } from 'tailwind-merge';
3
+ /**
4
+ * Utility to merge class names with Tailwind CSS and additional custom merging logic.
5
+ *
6
+ * @param {...ClassValue[]} inputs - Class names to merge.
7
+ * @returns {string} - A string of merged class names.
8
+ */
9
+ export function cn(...inputs) {
10
+ return twMerge(clsx(inputs));
11
+ }
12
+ /**
13
+ * @deprecated Use isLinkActive instead.
14
+ *
15
+ * Determines if a navigation link is active based on the current path.
16
+ *
17
+ * @param href - The target URL.
18
+ * @param path - The current browser path.
19
+ * @returns - True if the navigation is active, false otherwise.
20
+ */
21
+ export function isNavActive(href, path) {
22
+ console.warn('isNavActive is deprecated. Use isLinkActive instead.');
23
+ const regex = new RegExp(`^/?${href}(/|$)`);
24
+ return regex.test(path);
25
+ }
26
+ /**
27
+ * Checks if a link is active, considering optional localization prefixes.
28
+ *
29
+ * @param {Object} params - Parameters object.
30
+ * @param {string} params.path - The target path of the link.
31
+ * @param {string} params.currentPath - The current browser path.
32
+ * @param {string[]} [params.locales=['en', 'es', 'de', 'zh', 'bn', 'fr', 'it', 'nl']] - Supported locale prefixes.
33
+ * @returns {boolean} - True if the link is active, false otherwise.
34
+ */
35
+ export function isLinkActive({ path, currentPath, locales = ['en', 'es', 'de', 'zh', 'bn', 'fr', 'it', 'nl'], exact = true, }) {
36
+ const localeRegex = new RegExp(`^/?(${locales.join('|')})/`);
37
+ const normalizePath = (p) => {
38
+ return p
39
+ .replace(localeRegex, '') // Remove localization prefix (e.g., en/, fr/, etc.)
40
+ .replace(/^\/+|\/+$/g, ''); // Trim leading and trailing slashes
41
+ };
42
+ const normalizedPath = normalizePath(path);
43
+ const normalizedCurrentPath = normalizePath(currentPath);
44
+ return exact
45
+ ? normalizedPath === normalizedCurrentPath
46
+ : normalizedCurrentPath.startsWith(normalizedPath);
47
+ }
48
+ /**
49
+ * Cleans a file path by removing the `/public/` prefix if present.
50
+ *
51
+ * @param src - The source path to clean.
52
+ * @returns - The cleaned path.
53
+ */
54
+ export function cleanSrc(src) {
55
+ let cleanedSrc = src;
56
+ if (src.includes('/public/')) {
57
+ cleanedSrc = src.replace('/public/', '/');
58
+ }
59
+ return cleanedSrc.trim();
60
+ }
61
+ /**
62
+ * Smoothly scrolls to the top or bottom of a specified container.
63
+ *
64
+ * @param containerSelector - The CSS selector or React ref for the container.
65
+ * @param to - Specifies whether to scroll to the top or bottom.
66
+ */
67
+ export const scrollTo = (containerSelector, to) => {
68
+ let container;
69
+ if (typeof containerSelector === 'string') {
70
+ container = document.querySelector(containerSelector);
71
+ }
72
+ else if (containerSelector.current) {
73
+ container = containerSelector.current;
74
+ }
75
+ else {
76
+ return;
77
+ }
78
+ if (container) {
79
+ container.scrollTo({
80
+ top: to === 'top' ? 0 : container.scrollHeight - container.clientHeight,
81
+ behavior: 'smooth',
82
+ });
83
+ }
84
+ };
85
+ /**
86
+ * Copies a given string to the clipboard.
87
+ *
88
+ * @param value - The value to copy to the clipboard.
89
+ * @param [onSuccess=() => {}] - Optional callback executed after successful copy.
90
+ */
91
+ export const copyToClipboard = (value, onSuccess = () => { }) => {
92
+ if (typeof window === 'undefined' || !navigator.clipboard?.writeText) {
93
+ return;
94
+ }
95
+ if (!value) {
96
+ return;
97
+ }
98
+ navigator.clipboard.writeText(value).then(onSuccess);
99
+ };
100
+ /**
101
+ * Converts camelCase, PascalCase, kebab-case, snake_case into normal case.
102
+ *
103
+ * @param inputString - The string need to be converted into normal case
104
+ * @returns - Normal Case
105
+ */
106
+ export function convertToNormalCase(inputString) {
107
+ const splittedString = inputString.split('.').pop();
108
+ const string = splittedString || inputString;
109
+ const words = string.replace(/([a-z])([A-Z])/g, '$1 $2').split(/[-_|�\s]+/);
110
+ const capitalizedWords = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1));
111
+ return capitalizedWords.join(' ');
112
+ }
113
+ const from = 'àáãäâèéëêìíïîòóöôùúüûñç·/_,:;';
114
+ const to = 'aaaaaeeeeiiiioooouuuunc------';
115
+ /**
116
+ * Converts a string to a URL-friendly slug by trimming, converting to lowercase,
117
+ * replacing diacritics, removing invalid characters, and replacing spaces with hyphens.
118
+ * @param {string} [str] - The input string to convert.
119
+ * @returns {string} The generated slug.
120
+ * @example
121
+ * convertToSlug("Hello World!"); // "hello-world"
122
+ * convertToSlug("Déjà Vu"); // "deja-vu"
123
+ */
124
+ export const convertToSlug = (str) => {
125
+ if (typeof str !== 'string') {
126
+ throw new TypeError('Input must be a string');
127
+ }
128
+ // Trim the string and convert it to lowercase.
129
+ let slug = str.trim().toLowerCase();
130
+ // Build a mapping of accented characters to their non-accented equivalents.
131
+ const charMap = {};
132
+ for (let i = 0; i < from.length; i++) {
133
+ charMap[from.charAt(i)] = to.charAt(i);
134
+ }
135
+ // Replace all accented characters using the mapping.
136
+ slug = slug.replace(new RegExp(`[${from}]`, 'g'), (match) => charMap[match] || match);
137
+ return (slug
138
+ .replace(/[^a-z0-9 -]/g, '') // Remove invalid characters
139
+ .replace(/\s+/g, '-') // Replace spaces with hyphens
140
+ .replace(/-+/g, '-') // Collapse consecutive hyphens
141
+ .replace(/^-+/, '') // Remove leading hyphens
142
+ .replace(/-+$/, '') || // Remove trailing hyphens
143
+ '');
144
+ };
145
+ /**
146
+ * Checks if the code is running in a server-side environment.
147
+ *
148
+ * @returns - True if the code is executed in SSR (Server-Side Rendering) context, false otherwise
149
+ */
150
+ export const isSSR = typeof window === 'undefined';
151
+ /**
152
+ * Converts an SVG string to a Base64-encoded string.
153
+ *
154
+ * @param str - The SVG string to encode
155
+ * @returns - Base64-encoded string representation of the SVG
156
+ */
157
+ export const svgToBase64 = (str) => isSSR ? Buffer.from(str).toString('base64') : window.btoa(str);
158
+ /**
159
+ * Pauses execution for the specified time.
160
+ *
161
+ * @param time - Time in milliseconds to sleep (default is 1000ms)
162
+ * @returns - A Promise that resolves after the specified time
163
+ */
164
+ export const sleep = (time = 1000) => new Promise((resolve) => setTimeout(resolve, time));
165
+ /**
166
+ * Creates a debounced function that delays invoking the provided function until
167
+ * after the specified `wait` time has elapsed since the last invocation.
168
+ *
169
+ * If the `immediate` option is set to `true`, the function will be invoked immediately
170
+ * on the leading edge of the wait interval. Subsequent calls during the wait interval
171
+ * will reset the timer but not invoke the function until the interval elapses again.
172
+ *
173
+ * The returned function includes the `isPending` property to check if the debounce
174
+ * timer is currently active.
175
+ *
176
+ * @typeParam F - The type of the function to debounce.
177
+ *
178
+ * @param function_ - The function to debounce.
179
+ * @param wait - The number of milliseconds to delay (default is 100ms).
180
+ * @param options - An optional object with the following properties:
181
+ * - `immediate` (boolean): If `true`, invokes the function on the leading edge
182
+ * of the wait interval instead of the trailing edge.
183
+ *
184
+ * @returns A debounced version of the provided function, enhanced with the `isPending` property.
185
+ *
186
+ * @throws {TypeError} If the first parameter is not a function.
187
+ * @throws {RangeError} If the `wait` parameter is negative.
188
+ *
189
+ * @example
190
+ * const log = debounce((message: string) => console.log(message), 200);
191
+ * log('Hello'); // Logs "Hello" after 200ms if no other call is made.
192
+ * console.log(log.isPending); // true if the timer is active.
193
+ */
194
+ export function debounce(function_, wait = 100, options) {
195
+ if (typeof function_ !== 'function') {
196
+ throw new TypeError(`Expected the first parameter to be a function, got \`${typeof function_}\`.`);
197
+ }
198
+ if (wait < 0) {
199
+ throw new RangeError('`wait` must not be negative.');
200
+ }
201
+ const immediate = options?.immediate ?? false;
202
+ let timeoutId;
203
+ let lastArgs;
204
+ let lastContext;
205
+ let result;
206
+ function run() {
207
+ result = function_.apply(lastContext, lastArgs);
208
+ lastArgs = undefined;
209
+ lastContext = undefined;
210
+ return result;
211
+ }
212
+ const debounced = function (...args) {
213
+ lastArgs = args;
214
+ lastContext = this;
215
+ if (timeoutId === undefined && immediate) {
216
+ result = run.call(this);
217
+ }
218
+ if (timeoutId !== undefined) {
219
+ clearTimeout(timeoutId);
220
+ }
221
+ timeoutId = setTimeout(run.bind(this), wait);
222
+ return result;
223
+ };
224
+ Object.defineProperty(debounced, 'isPending', {
225
+ get() {
226
+ return timeoutId !== undefined;
227
+ },
228
+ });
229
+ return debounced;
230
+ }
231
+ /**
232
+ * Creates a throttled function that invokes the provided function at most once
233
+ * every `wait` milliseconds.
234
+ *
235
+ * If the `leading` option is set to `true`, the function will be invoked immediately
236
+ * on the leading edge of the throttle interval. If the `trailing` option is set to `true`,
237
+ * the function will also be invoked at the end of the throttle interval if additional
238
+ * calls were made during the interval.
239
+ *
240
+ * The returned function includes the `isPending` property to check if the throttle
241
+ * timer is currently active.
242
+ *
243
+ * @typeParam F - The type of the function to throttle.
244
+ *
245
+ * @param function_ - The function to throttle.
246
+ * @param wait - The number of milliseconds to wait between invocations (default is 100ms).
247
+ * @param options - An optional object with the following properties:
248
+ * - `leading` (boolean): If `true`, invokes the function on the leading edge of the interval.
249
+ * - `trailing` (boolean): If `true`, invokes the function on the trailing edge of the interval.
250
+ *
251
+ * @returns A throttled version of the provided function, enhanced with the `isPending` property.
252
+ *
253
+ * @throws {TypeError} If the first parameter is not a function.
254
+ * @throws {RangeError} If the `wait` parameter is negative.
255
+ *
256
+ * @example
257
+ * const log = throttle((message: string) => console.log(message), 200);
258
+ * log('Hello'); // Logs "Hello" immediately if leading is true.
259
+ * console.log(log.isPending); // true if the timer is active.
260
+ */
261
+ export function throttle(function_, wait = 100, options) {
262
+ if (typeof function_ !== 'function') {
263
+ throw new TypeError(`Expected the first parameter to be a function, got \`${typeof function_}\`.`);
264
+ }
265
+ if (wait < 0) {
266
+ throw new RangeError('`wait` must not be negative.');
267
+ }
268
+ const leading = options?.leading ?? true;
269
+ const trailing = options?.trailing ?? true;
270
+ let timeoutId;
271
+ let lastArgs;
272
+ let lastContext;
273
+ let lastCallTime;
274
+ let result;
275
+ function invoke() {
276
+ lastCallTime = Date.now();
277
+ result = function_.apply(lastContext, lastArgs);
278
+ lastArgs = undefined;
279
+ lastContext = undefined;
280
+ }
281
+ function later() {
282
+ timeoutId = undefined;
283
+ if (trailing && lastArgs) {
284
+ invoke();
285
+ }
286
+ }
287
+ const throttled = function (...args) {
288
+ const now = Date.now();
289
+ const timeSinceLastCall = lastCallTime
290
+ ? now - lastCallTime
291
+ : Number.POSITIVE_INFINITY;
292
+ lastArgs = args;
293
+ lastContext = this;
294
+ if (timeSinceLastCall >= wait) {
295
+ if (leading) {
296
+ invoke();
297
+ }
298
+ else {
299
+ timeoutId = setTimeout(later, wait);
300
+ }
301
+ }
302
+ else if (!timeoutId && trailing) {
303
+ timeoutId = setTimeout(later, wait - timeSinceLastCall);
304
+ }
305
+ return result;
306
+ };
307
+ Object.defineProperty(throttled, 'isPending', {
308
+ get() {
309
+ return timeoutId !== undefined;
310
+ },
311
+ });
312
+ return throttled;
313
+ }
314
+ /**
315
+ * Formats a string by replacing each '%s' placeholder with the corresponding argument.
316
+ * This function mimics the basic behavior of C's printf for %s substitution.
317
+ *
318
+ * It supports both calls like `printf(format, ...args)` and `printf(format, argsArray)`.
319
+ *
320
+ * @param format - The format string containing '%s' placeholders.
321
+ * @param args - The values to substitute into the placeholders, either as separate arguments or as a single array.
322
+ * @returns The formatted string with all '%s' replaced by the provided arguments.
323
+ *
324
+ * @example
325
+ * ```ts
326
+ * const message = printf("%s love %s", "I", "Bangladesh");
327
+ * // message === "I love Bangladesh"
328
+ *
329
+ * const arr = ["I", "Bangladesh"];
330
+ * const message2 = printf("%s love %s", arr);
331
+ * // message2 === "I love Bangladesh"
332
+ *
333
+ * // If there are too few arguments:
334
+ * const incomplete = printf("Bangladesh is %s %s", "beautiful");
335
+ * // incomplete === "Bangladesh is beautiful"
336
+ * ```
337
+ */
338
+ export function printf(format, ...args) {
339
+ const replacements = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;
340
+ let idx = 0;
341
+ return format.replace(/%s/g, () => {
342
+ const arg = replacements[idx++];
343
+ return arg === undefined ? '' : String(arg);
344
+ });
345
+ }
346
+ export const mergeRefs = (...refs) => {
347
+ return (value) => {
348
+ for (const ref of refs) {
349
+ if (!ref)
350
+ continue;
351
+ if (typeof ref === 'function') {
352
+ ref(value);
353
+ }
354
+ else {
355
+ ref.current = value;
356
+ }
357
+ }
358
+ };
359
+ };
360
+ /**
361
+ * Navigates to the specified client-side hash without ssr.
362
+ * use `scroll-margin-top` with css to add margins
363
+ *
364
+ * @param id - The ID of the element without # to navigate to.
365
+ *
366
+ * @example goToClientSideHash('my-element');
367
+ */
368
+ export function goToClientSideHash(id, opts) {
369
+ const el = document.getElementById(id);
370
+ if (!el)
371
+ return;
372
+ el.scrollIntoView({ behavior: 'smooth', block: 'start', ...opts });
373
+ window.history.pushState(null, '', `#${id}`);
374
+ }
375
+ /**
376
+ * Escapes a string for use in a regular expression.
377
+ *
378
+ * @param str - The string to escape
379
+ * @returns - The escaped string
380
+ *
381
+ * @example
382
+ * const escapedString = escapeRegExp('Hello, world!');
383
+ * // escapedString === 'Hello\\, world!'
384
+ */
385
+ export function escapeRegExp(str) {
386
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
387
+ }
388
+ /**
389
+ * Normalizes a string by:
390
+ * - Applying Unicode normalization (NFC)
391
+ * - Optionally removing diacritic marks (accents)
392
+ * - Optionally trimming leading/trailing non-alphanumeric characters
393
+ * - Optionally converting to lowercase
394
+ *
395
+ * @param str - The string to normalize
396
+ * @param options - Normalization options
397
+ * @param options.lowercase - Whether to convert the result to lowercase (default: true)
398
+ * @param options.removeAccents - Whether to remove diacritic marks like accents (default: true)
399
+ * @param options.removeNonAlphanumeric - Whether to trim non-alphanumeric characters from the edges (default: true)
400
+ * @returns The normalized string
401
+ */
402
+ export function normalizeText(str, options = {}) {
403
+ if (!str)
404
+ return '';
405
+ const { lowercase = true, removeAccents = true, removeNonAlphanumeric = true, } = options;
406
+ let result = str.normalize('NFC');
407
+ if (removeAccents) {
408
+ result = result.replace(/\p{M}/gu, ''); // remove accents
409
+ }
410
+ if (removeNonAlphanumeric) {
411
+ result = result.replace(/^[^\p{L}\p{N}]*|[^\p{L}\p{N}]*$/gu, ''); // trim edges
412
+ }
413
+ if (lowercase) {
414
+ result = result.toLocaleLowerCase();
415
+ }
416
+ return result;
417
+ }
@@ -1,4 +1,4 @@
1
- import { useState, useTransition, useCallback } from 'react';
1
+ import { useCallback, useState, useTransition } from 'react';
2
2
  import { useIsomorphicEffect } from '.';
3
3
  export const useAsync = (fn, opts = {}) => {
4
4
  const { initialArgs, callback = {}, mode = 'onTrigger' } = opts;
@@ -1,6 +1,6 @@
1
1
  'use client';
2
- import { copyToClipboard } from '../functions';
3
2
  import * as React from 'react';
3
+ import { copyToClipboard } from '../functions';
4
4
  export * from './action';
5
5
  /**
6
6
  * Hook to detect clicks outside of a referenced element.
@@ -1,5 +1,5 @@
1
1
  export type Primitive = string | number | bigint | boolean | symbol | null | undefined;
2
2
  export type Falsy = false | '' | 0 | null | undefined;
3
3
  export declare const isFalsy: (val: unknown) => val is Falsy;
4
- export declare const isNullish: (val: unknown) => val is (null | undefined);
4
+ export declare const isNullish: (val: unknown) => val is null | undefined;
5
5
  export declare const isPrimitive: (val: unknown) => val is Primitive;
@@ -1,2 +1,2 @@
1
- export * from './utilities';
2
1
  export * from './guards';
2
+ export * from './utilities';
@@ -1,2 +1,2 @@
1
- export * from './utilities';
2
1
  export * from './guards';
2
+ export * from './utilities';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sohanemon/utils",
3
- "version": "5.0.7",
3
+ "version": "5.0.8",
4
4
  "author": "Sohan Emon <sohanemon@outlook.com>",
5
5
  "description": "",
6
6
  "type": "module",