@leancodepl/utils 8.5.0 → 8.6.0

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