@leancodepl/utils 9.7.1 → 9.7.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 (57) hide show
  1. package/CHANGELOG.md +684 -0
  2. package/LICENSE +201 -0
  3. package/dist/index.d.ts +14 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +146 -0
  6. package/dist/index.umd.cjs +1 -0
  7. package/{src → dist}/lib/addPrefix.d.ts +1 -0
  8. package/dist/lib/addPrefix.d.ts.map +1 -0
  9. package/{src → dist}/lib/assertDefined.d.ts +1 -0
  10. package/dist/lib/assertDefined.d.ts.map +1 -0
  11. package/{src → dist}/lib/assertNotEmpty.d.ts +1 -0
  12. package/dist/lib/assertNotEmpty.d.ts.map +1 -0
  13. package/{src → dist}/lib/assertNotNull.d.ts +1 -0
  14. package/dist/lib/assertNotNull.d.ts.map +1 -0
  15. package/{src → dist}/lib/downloadFile.d.ts +1 -0
  16. package/dist/lib/downloadFile.d.ts.map +1 -0
  17. package/{src → dist}/lib/ensureDefined.d.ts +1 -0
  18. package/dist/lib/ensureDefined.d.ts.map +1 -0
  19. package/{src → dist}/lib/ensureNotEmpty.d.ts +1 -0
  20. package/dist/lib/ensureNotEmpty.d.ts.map +1 -0
  21. package/{src → dist}/lib/ensureNotNull.d.ts +1 -0
  22. package/dist/lib/ensureNotNull.d.ts.map +1 -0
  23. package/dist/lib/hooks/index.d.ts +7 -0
  24. package/dist/lib/hooks/index.d.ts.map +1 -0
  25. package/{src → dist}/lib/hooks/useBoundRunInTask.d.ts +1 -0
  26. package/dist/lib/hooks/useBoundRunInTask.d.ts.map +1 -0
  27. package/{src → dist}/lib/hooks/useDialog.d.ts +1 -0
  28. package/dist/lib/hooks/useDialog.d.ts.map +1 -0
  29. package/{src → dist}/lib/hooks/useKeyByRoute.d.ts +1 -0
  30. package/dist/lib/hooks/useKeyByRoute.d.ts.map +1 -0
  31. package/{src → dist}/lib/hooks/useRunInTask.d.ts +1 -0
  32. package/dist/lib/hooks/useRunInTask.d.ts.map +1 -0
  33. package/{src → dist}/lib/hooks/useSetUnset.d.ts +2 -1
  34. package/dist/lib/hooks/useSetUnset.d.ts.map +1 -0
  35. package/{src → dist}/lib/hooks/useSyncState.d.ts +1 -0
  36. package/dist/lib/hooks/useSyncState.d.ts.map +1 -0
  37. package/{src → dist}/lib/transformDeep.d.ts +2 -1
  38. package/dist/lib/transformDeep.d.ts.map +1 -0
  39. package/{src → dist}/lib/transformFirst.d.ts +1 -0
  40. package/dist/lib/transformFirst.d.ts.map +1 -0
  41. package/dist/lib/types/index.d.ts +3 -0
  42. package/dist/lib/types/index.d.ts.map +1 -0
  43. package/{src → dist}/lib/types/transformDeep.d.ts +2 -1
  44. package/dist/lib/types/transformDeep.d.ts.map +1 -0
  45. package/{src → dist}/lib/types/unpromisify.d.ts +1 -0
  46. package/dist/lib/types/unpromisify.d.ts.map +1 -0
  47. package/{src → dist}/lib/valueContext.d.ts +2 -1
  48. package/dist/lib/valueContext.d.ts.map +1 -0
  49. package/package.json +20 -15
  50. package/index.cjs.default.js +0 -1
  51. package/index.cjs.js +0 -521
  52. package/index.cjs.mjs +0 -2
  53. package/index.d.ts +0 -1
  54. package/index.esm.js +0 -501
  55. package/src/index.d.ts +0 -13
  56. package/src/lib/hooks/index.d.ts +0 -6
  57. package/src/lib/types/index.d.ts +0 -2
package/index.esm.js DELETED
@@ -1,501 +0,0 @@
1
- import { useState, useCallback, useMemo, createContext, useEffect, useContext } from 'react';
2
- import invariant from 'tiny-invariant';
3
- import { jsx } from 'react/jsx-runtime';
4
-
5
- /**
6
- * React hook for tracking async task execution with loading state.
7
- * Automatically manages a loading counter and provides a wrapper function for tasks.
8
- *
9
- * @returns A tuple containing [isLoading: boolean, runInTask: function]
10
- * @example
11
- * ```typescript
12
- * function MyComponent() {
13
- * const [isLoading, runInTask] = useRunInTask();
14
- *
15
- * const handleSave = async () => {
16
- * await runInTask(async () => {
17
- * await saveData();
18
- * });
19
- * };
20
- *
21
- * return (
22
- * <button onClick={handleSave} disabled={isLoading}>
23
- * {isLoading ? 'Saving...' : 'Save'}
24
- * </button>
25
- * );
26
- * }
27
- * ```
28
- */ function useRunInTask() {
29
- const [runningTasks, setRunningTasks] = useState(0);
30
- const runInTask = useCallback(async (task)=>{
31
- setRunningTasks((runningTasks)=>runningTasks + 1);
32
- try {
33
- return await task();
34
- } finally{
35
- setRunningTasks((runningTasks)=>runningTasks - 1);
36
- }
37
- }, []);
38
- return [
39
- runningTasks > 0,
40
- runInTask
41
- ];
42
- }
43
-
44
- function useBoundRunInTask(block) {
45
- const [isRunning, runInTask] = useRunInTask();
46
- const runBlockInTask = useMemo(()=>block ? (...args)=>runInTask(()=>block(...args)) : undefined, [
47
- block,
48
- runInTask
49
- ]);
50
- return [
51
- isRunning,
52
- runBlockInTask
53
- ];
54
- }
55
-
56
- /**
57
- * React hook for boolean state management helpers.
58
- *
59
- * @param set - The state setter function from useState
60
- * @returns A tuple containing [setTrue: function, setFalse: function]
61
- * @example
62
- * ```typescript
63
- * function MyComponent() {
64
- * const [isVisible, setIsVisible] = useState(false);
65
- * const [show, hide] = useSetUnset(setIsVisible);
66
- *
67
- * return (
68
- * <div>
69
- * <button onClick={show}>Show</button>
70
- * <button onClick={hide}>Hide</button>
71
- * {isVisible && <div>Content is visible</div>}
72
- * </div>
73
- * );
74
- * }
75
- * ```
76
- */ function useSetUnset(set) {
77
- return [
78
- useCallback(()=>set(true), [
79
- set
80
- ]),
81
- useCallback(()=>set(false), [
82
- set
83
- ])
84
- ];
85
- }
86
-
87
- /**
88
- * React hook for managing dialog state with optional callback after closing.
89
- * Provides convenient open/close functions and tracks the dialog's open state.
90
- *
91
- * @param onAfterClose - Optional callback function to execute after the dialog closes
92
- * @returns Object containing dialog state and control functions
93
- * @example
94
- * ```typescript
95
- * function MyComponent() {
96
- * const { isDialogOpen, openDialog, closeDialog } = useDialog(() => {
97
- * console.log('Dialog closed');
98
- * });
99
- *
100
- * return (
101
- * <div>
102
- * <button onClick={openDialog}>Open Dialog</button>
103
- * {isDialogOpen && <Dialog onClose={closeDialog} />}
104
- * </div>
105
- * );
106
- * }
107
- * ```
108
- */ function useDialog(onAfterClose) {
109
- const [isDialogOpen, setIsDialogOpen] = useState(false);
110
- const [openDialog, closeDialog] = useSetUnset(setIsDialogOpen);
111
- const close = useCallback(()=>{
112
- closeDialog();
113
- if (onAfterClose) setTimeout(onAfterClose);
114
- }, [
115
- closeDialog,
116
- onAfterClose
117
- ]);
118
- return {
119
- isDialogOpen,
120
- openDialog,
121
- closeDialog: close
122
- };
123
- }
124
-
125
- /**
126
- * React hook for generating keys based on current route matches.
127
- *
128
- * @template TKey - The type of the route keys
129
- * @param routeMatches - Record of route keys to match objects or arrays
130
- * @returns Array of active route keys
131
- * @example
132
- * ```typescript
133
- * function NavigationComponent() {
134
- * const routeMatches = {
135
- * home: useRouteMatch('/'),
136
- * about: useRouteMatch('/about'),
137
- * contact: useRouteMatch('/contact')
138
- * };
139
- *
140
- * const activeRoutes = useKeyByRoute(routeMatches);
141
- * // Returns ['home'] if on home page, ['about'] if on about page, etc.
142
- *
143
- * return (
144
- * <nav>
145
- * {activeRoutes.map(route => (
146
- * <span key={route}>Active: {route}</span>
147
- * ))}
148
- * </nav>
149
- * );
150
- * }
151
- * ```
152
- */ function useKeyByRoute(routeMatches) {
153
- const keys = [];
154
- for(const key in routeMatches){
155
- const matches = routeMatches[key];
156
- if (Array.isArray(matches) ? matches.some((match)=>match !== null) : matches !== null) {
157
- keys.push(key);
158
- }
159
- }
160
- return keys;
161
- }
162
-
163
- /**
164
- * Synchronizes external state changes with a callback function, calling the callback only when state actually changes.
165
- *
166
- * @param state - The current state value to monitor for changes
167
- * @param onChange - Callback function executed when state changes
168
- * @param compare - Optional comparison function to determine if state has changed (defaults to strict equality)
169
- * @example
170
- * ```typescript
171
- * import { useSyncState } from "@leancodepl/utils";
172
- *
173
- * function MyComponent({ externalValue }: { externalValue: string }) {
174
- * useSyncState(externalValue, (newValue) => {
175
- * console.log('Value changed to:', newValue);
176
- * });
177
- *
178
- * return <div>{externalValue}</div>;
179
- * }
180
- * ```
181
- */ function useSyncState(state, onChange, compare) {
182
- const [prevState, setPrevState] = useState(state);
183
- const hasChanged = compare ? !compare(state, prevState) : state !== prevState;
184
- if (hasChanged) {
185
- setPrevState(state);
186
- onChange(state);
187
- }
188
- }
189
-
190
- /**
191
- * Adds a prefix to all keys in an object, creating a new object with prefixed keys.
192
- *
193
- * @template T - The type of the input object
194
- * @template TPrefix - The type of the prefix string
195
- * @param object - The object whose keys will be prefixed
196
- * @param prefix - The prefix string to add to each key
197
- * @returns A new object with all keys prefixed
198
- * @example
199
- * ```typescript
200
- * const apiData = { userId: 1, userName: 'John' };
201
- * const prefixed = addPrefix(apiData, 'api_');
202
- * // Result: { api_userId: 1, api_userName: 'John' }
203
- * ```
204
- */ function addPrefix(object, prefix) {
205
- return Object.fromEntries(Object.entries(object).map(([key, value])=>[
206
- `${prefix}${key}`,
207
- value
208
- ]));
209
- }
210
-
211
- /**
212
- * Asserts that a value is not undefined. Throws an error if the value is undefined.
213
- * This is a type assertion function that narrows the type to exclude undefined.
214
- *
215
- * @template T - The type of the value being checked
216
- * @param value - The value to check for undefined
217
- * @param message - Optional error message to use if assertion fails
218
- * @throws {Error} When the value is undefined
219
- * @example
220
- * ```typescript
221
- * function processUser(user?: User) {
222
- * assertDefined(user);
223
- * return user.name; // TypeScript knows user is defined
224
- * }
225
- * ```
226
- */ function assertDefined(value, message) {
227
- invariant(value !== undefined, message);
228
- }
229
-
230
- /**
231
- * Asserts that a value is not null or undefined. Throws an error if the value is null or undefined.
232
- * This is a type assertion function that narrows the type to exclude null and undefined.
233
- *
234
- * @template T - The type of the value being checked
235
- * @param value - The value to check for null or undefined
236
- * @param message - Optional error message to use if assertion fails
237
- * @throws {Error} When the value is null or undefined
238
- * @example
239
- * ```typescript
240
- * function processOptionalData(data?: string | null) {
241
- * assertNotEmpty(data);
242
- * return data.toUpperCase(); // TypeScript knows data is not null/undefined
243
- * }
244
- * ```
245
- */ function assertNotEmpty(value, message) {
246
- invariant(value !== null && value !== undefined, message);
247
- }
248
-
249
- /**
250
- * Asserts that a value is not null. Throws an error if the value is null.
251
- * This is a type assertion function that narrows the type to exclude null.
252
- *
253
- * @template T - The type of the value being checked
254
- * @param value - The value to check for null
255
- * @param message - Optional error message to use if assertion fails
256
- * @throws {Error} When the value is null
257
- * @example
258
- * ```typescript
259
- * function processData(data: string | null) {
260
- * assertNotNull(data);
261
- * return data.toUpperCase(); // TypeScript knows data is not null
262
- * }
263
- * ```
264
- */ function assertNotNull(value, message) {
265
- invariant(value !== null, message);
266
- }
267
-
268
- function downloadFile(dataOrUrl, options = {}) {
269
- if (typeof dataOrUrl === "string") {
270
- const { name } = options;
271
- const a = document.createElement("a");
272
- a.href = dataOrUrl;
273
- a.target = "_blank";
274
- if (name) a.download = name;
275
- a.click();
276
- } else {
277
- const url = URL.createObjectURL(dataOrUrl);
278
- downloadFile(url, options);
279
- URL.revokeObjectURL(url);
280
- }
281
- }
282
-
283
- /**
284
- * Ensures that a value is defined, returning it if defined or throwing an error if undefined.
285
- *
286
- * @template T - The type of the value being checked
287
- * @param value - The value to ensure is defined
288
- * @param message - Optional error message to use if the value is undefined
289
- * @returns The value if it is defined
290
- * @throws {Error} When the value is undefined
291
- * @example
292
- * ```typescript
293
- * function processUser(user?: User) {
294
- * const definedUser = ensureDefined(user);
295
- * return definedUser.name; // definedUser is guaranteed to be defined
296
- * }
297
- * ```
298
- */ function ensureDefined(value, message) {
299
- assertDefined(value, message);
300
- return value;
301
- }
302
-
303
- /**
304
- * Ensures that a value is not null or undefined, returning it if valid or throwing an error if empty.
305
- *
306
- * @template T - The type of the value being checked
307
- * @param value - The value to ensure is not null or undefined
308
- * @param message - Optional error message to use if the value is null or undefined
309
- * @returns The value if it is not null or undefined
310
- * @throws {Error} When the value is null or undefined
311
- * @example
312
- * ```typescript
313
- * function processOptionalData(data?: string | null) {
314
- * const validData = ensureNotEmpty(data);
315
- * return validData.toUpperCase(); // validData is guaranteed to be not null/undefined
316
- * }
317
- * ```
318
- */ function ensureNotEmpty(value, message) {
319
- assertNotEmpty(value, message);
320
- return value;
321
- }
322
-
323
- /**
324
- * Ensures that a value is not null, returning it if not null or throwing an error if null.
325
- * Unlike assertNotNull, this function returns the value for use in expressions.
326
- *
327
- * @template T - The type of the value being checked
328
- * @param value - The value to ensure is not null
329
- * @param message - Optional error message to use if the value is null
330
- * @returns The value if it is not null
331
- * @throws {Error} When the value is null
332
- * @example
333
- * ```typescript
334
- * function processData(data: string | null) {
335
- * const nonNullData = ensureNotNull(data);
336
- * return nonNullData.toUpperCase(); // nonNullData is guaranteed to be not null
337
- * }
338
- * ```
339
- */ function ensureNotNull(value, message) {
340
- assertNotNull(value, message);
341
- return value;
342
- }
343
-
344
- function _extends() {
345
- _extends = Object.assign || function assign(target) {
346
- for(var i = 1; i < arguments.length; i++){
347
- var source = arguments[i];
348
- for(var key in source)if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
349
- }
350
- return target;
351
- };
352
- return _extends.apply(this, arguments);
353
- }
354
-
355
- function transformFirst(value, transformFn) {
356
- if (value.length === 0) {
357
- return "";
358
- }
359
- return transformFn(value[0]) + value.slice(1);
360
- }
361
- /**
362
- * Converts the first character of a string to lowercase.
363
- *
364
- * @param value - The string to transform
365
- * @returns The string with the first character in lowercase
366
- * @example
367
- * ```typescript
368
- * const result = toLowerFirst('UserName');
369
- * // Result: 'userName'
370
- * ```
371
- */ function toLowerFirst(value) {
372
- return transformFirst(value, (value)=>value.toLowerCase());
373
- }
374
- /**
375
- * Converts the first character of a string to uppercase.
376
- *
377
- * @param value - The string to transform
378
- * @returns The string with the first character in uppercase
379
- * @example
380
- * ```typescript
381
- * const result = toUpperFirst('userName');
382
- * // Result: 'UserName'
383
- * ```
384
- */ function toUpperFirst(value) {
385
- return transformFirst(value, (value)=>value.toUpperCase());
386
- }
387
-
388
- function transformDeep(value, mode) {
389
- if (value === null || value === undefined) {
390
- return undefined;
391
- }
392
- if (Array.isArray(value)) {
393
- return value.map((val)=>transformDeep(val, mode));
394
- }
395
- if (typeof value === "object") {
396
- const transformKey = mode === "capitalize" ? toUpperFirst : toLowerFirst;
397
- return Object.entries(value).reduce((accumulator, [key, value])=>_extends({}, accumulator, {
398
- [transformKey(key)]: transformDeep(value, mode)
399
- }), {});
400
- }
401
- return value;
402
- }
403
- /**
404
- * Recursively transforms all object keys to use uncapitalized (camelCase) format.
405
- *
406
- * @template T - The type of the input value
407
- * @param value - The value to transform (can be object, array, or primitive)
408
- * @returns A new object with all keys converted to camelCase
409
- * @example
410
- * ```typescript
411
- * const serverData = { UserId: 1, UserName: 'John', Profile: { FirstName: 'John' } };
412
- * const clientData = uncapitalizeDeep(serverData);
413
- * // Result: { userId: 1, userName: 'John', profile: { firstName: 'John' } }
414
- * ```
415
- */ function uncapitalizeDeep(value) {
416
- return transformDeep(value, "uncapitalize");
417
- }
418
- /**
419
- * Recursively transforms all object keys to use capitalized (PascalCase) format.
420
- *
421
- * @template T - The type of the input value
422
- * @param value - The value to transform (can be object, array, or primitive)
423
- * @returns A new object with all keys converted to PascalCase
424
- * @example
425
- * ```typescript
426
- * const clientData = { userId: 1, userName: 'John', profile: { firstName: 'John' } };
427
- * const serverData = capitalizeDeep(clientData);
428
- * // Result: { UserId: 1, UserName: 'John', Profile: { FirstName: 'John' } }
429
- * ```
430
- */ function capitalizeDeep(value) {
431
- return transformDeep(value, "capitalize");
432
- }
433
-
434
- /**
435
- * Creates a React context hook for managing optional state values with Provider and setter utilities.
436
- * Returns a hook with attached Provider component and set function for declarative value management.
437
- *
438
- * @returns Hook function with attached Provider component and set function
439
- * @example
440
- * ```typescript
441
- * import { mkValueContext } from "@leancodepl/utils";
442
- *
443
- * const useTheme = mkValueContext<string>();
444
- *
445
- * function App() {
446
- * return (
447
- * <useTheme.Provider initialValue="dark">
448
- * <ThemeConsumer />
449
- * </useTheme.Provider>
450
- * );
451
- * }
452
- *
453
- * function ThemeConsumer() {
454
- * const [theme] = useTheme();
455
- * return <div>Current theme: {theme}</div>;
456
- * }
457
- * ```
458
- * @example
459
- * ```typescript
460
- * // Using set to declaratively set context value
461
- * const useActiveUser = mkValueContext<string>();
462
- *
463
- * function UserProfile({ userId }: { userId: string }) {
464
- * useActiveUser.set(userId); // Sets value on mount, clears on unmount
465
- * return <div>Profile content</div>;
466
- * }
467
- *
468
- * function UserBadge() {
469
- * const [activeUserId] = useActiveUser();
470
- * return <div>Active user: {activeUserId}</div>;
471
- * }
472
- * ```
473
- */ function mkValueContext() {
474
- const valueContext = /*#__PURE__*/ createContext([
475
- undefined,
476
- ()=>void 0
477
- ]);
478
- function useValueContext() {
479
- return useContext(valueContext);
480
- }
481
- useValueContext.Provider = function ValueContextProvider({ children, initialValue }) {
482
- const contextValue = useState(initialValue);
483
- return /*#__PURE__*/ jsx(valueContext.Provider, {
484
- value: contextValue,
485
- children: children
486
- });
487
- };
488
- useValueContext.set = function useSetter(value) {
489
- const [, setValue] = useValueContext();
490
- useEffect(()=>void setValue(value), [
491
- setValue,
492
- value
493
- ]);
494
- useEffect(()=>()=>setValue(undefined), [
495
- setValue
496
- ]);
497
- };
498
- return useValueContext;
499
- }
500
-
501
- export { addPrefix, assertDefined, assertNotEmpty, assertNotNull, capitalizeDeep, downloadFile, ensureDefined, ensureNotEmpty, ensureNotNull, mkValueContext, toLowerFirst, toUpperFirst, uncapitalizeDeep, useBoundRunInTask, useDialog, useKeyByRoute, useRunInTask, useSetUnset, useSyncState };
package/src/index.d.ts DELETED
@@ -1,13 +0,0 @@
1
- export * from "./lib/types";
2
- export * from "./lib/hooks";
3
- export * from "./lib/addPrefix";
4
- export * from "./lib/assertDefined";
5
- export * from "./lib/assertNotEmpty";
6
- export * from "./lib/assertNotNull";
7
- export * from "./lib/downloadFile";
8
- export * from "./lib/ensureDefined";
9
- export * from "./lib/ensureNotEmpty";
10
- export * from "./lib/ensureNotNull";
11
- export * from "./lib/transformDeep";
12
- export * from "./lib/transformFirst";
13
- export * from "./lib/valueContext";
@@ -1,6 +0,0 @@
1
- export * from "./useBoundRunInTask";
2
- export * from "./useDialog";
3
- export * from "./useKeyByRoute";
4
- export * from "./useRunInTask";
5
- export * from "./useSetUnset";
6
- export * from "./useSyncState";
@@ -1,2 +0,0 @@
1
- export * from "./transformDeep";
2
- export * from "./unpromisify";