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