@gateweb/react-utils 1.16.0 → 1.17.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/dist/es/index.mjs CHANGED
@@ -1,754 +1,10 @@
1
+ export { B as ByteSize, M as MimeTypeMap, O as OtherMimeType, c as convertBytes, g as createEnumLikeObject, z as debounce, d as decodeBase64, b as decodeJson, x as deepClone, w as deepMerge, e as encodeBase64, a as encodeJson, f as extractEnumLikeObject, h as fakeApi, D as getLocalStorage, j as getMimeType, l as invariant, i as isEqual, n as isServer, m as mergeConfig, o as objectToSearchParams, q as omit, r as omitByValue, k as parseFileInfoFromFilename, p as parseFilenameFromDisposition, t as pick, u as pickByValue, y as renameKey, s as searchParamsToObject, E as setLocalStorage, A as throttle, v as validateFileType, C as wait } from './webStorage-12s-gvD4qbeR.mjs';
1
2
  import dayjs from 'dayjs';
2
3
  export { Q as QueryProvider, u as useQueryContext } from './queryStore-12s-CFQTVwrg.mjs';
3
4
  import React, { useMemo, createContext, useContext, useState, useCallback } from 'react';
4
5
  export { u as useCountdown } from './useCountdown-12s-t52WIHfq.mjs';
5
6
  export { u as useDisclosure } from './useDisclosure-12s-BQAHpAXK.mjs';
6
7
  export { d as downloadFile } from './download-12s-CnaJ0p_f.mjs';
7
- export { g as getLocalStorage, s as setLocalStorage } from './webStorage-12s-W1DItzhS.mjs';
8
-
9
- const FILE_SIZE_UNITS$1 = [
10
- 'Bytes',
11
- 'KB',
12
- 'MB',
13
- 'GB',
14
- 'TB',
15
- 'PB',
16
- 'EB',
17
- 'ZB',
18
- 'YB'
19
- ];
20
- /**
21
- * 代表字節大小的類,提供各種格式化和轉換方法
22
- */ class ByteSize {
23
- /**
24
- * 建立一個新的 ByteSize 實例
25
- * @param bytes 位元組數值
26
- */ constructor(bytes){
27
- this.bytes = bytes;
28
- }
29
- /**
30
- * 取得原始位元組數值
31
- */ get value() {
32
- return this.bytes;
33
- }
34
- /**
35
- * 將位元組轉換為指定單位的數值
36
- *
37
- * @param unit 目標單位 (例如 'KB', 'MB', 'GB')
38
- * @returns 轉換後的數值
39
- *
40
- * @example
41
- * ```ts
42
- * const size = createByteSize(1024);
43
- * size.to('KB'); // 1
44
- * size.to('MB'); // 0.0009765625
45
- * ```
46
- */ to(unit) {
47
- if (!FILE_SIZE_UNITS$1.includes(unit)) {
48
- console.warn(`Invalid unit: ${unit}. Valid units are: ${FILE_SIZE_UNITS$1.join(', ')}`);
49
- return this.bytes;
50
- }
51
- const k = 1024;
52
- const i = FILE_SIZE_UNITS$1.indexOf(unit);
53
- return this.bytes / k ** i;
54
- }
55
- /**
56
- * 轉換為適當單位的可讀字符串
57
- *
58
- * @param unit 指定單位 (例如 'KB', 'MB', 'GB'),不指定則自動選擇最適合的單位
59
- * @param decimals 小數點位數 (預設為 2)
60
- * @returns 格式化後的字符串
61
- *
62
- * @example
63
- * ```ts
64
- * const size = createByteSize(1024);
65
- * size.format(); // '1.00 KB'
66
- * size.format('KB'); // '1.00 KB'
67
- * size.format('MB', 3); // '0.001 MB'
68
- * ```
69
- */ format(unit, decimals = 2) {
70
- if (this.bytes === 0) return `0 ${unit || 'Bytes'}`;
71
- const k = 1024;
72
- // 如果指定了有效單位,則使用;否則,計算最適合的單位
73
- const i = unit && FILE_SIZE_UNITS$1.includes(unit) ? FILE_SIZE_UNITS$1.indexOf(unit) : Math.floor(Math.log(this.bytes) / Math.log(k));
74
- return `${(this.bytes / k ** i).toFixed(decimals)} ${FILE_SIZE_UNITS$1[i]}`;
75
- }
76
- /**
77
- * 比較兩個 ByteSize 實例
78
- *
79
- * @param other 要比較的另一個 ByteSize 實例
80
- * @returns 比較結果:-1 表示小於,0 表示等於,1 表示大於
81
- */ compareTo(other) {
82
- if (this.bytes < other.value) return -1;
83
- if (this.bytes > other.value) return 1;
84
- return 0;
85
- }
86
- /**
87
- * 轉換為字符串表示
88
- * @returns 預設格式化的字符串
89
- */ toString() {
90
- return this.format();
91
- }
92
- }
93
- /**
94
- * 將位元組轉換為可讀字符串 (保留舊的 API 以確保向後兼容)
95
- *
96
- * @param bytes 位元組數值
97
- * @param unit 目標單位 (例如 'KB', 'MB', 'GB'),不指定則自動選擇最適合的單位
98
- * @param decimals 小數點位數 (預設為 2)
99
- * @returns 格式化後的字符串
100
- *
101
- * @example
102
- * ```ts
103
- * convertBytes(0) // '0 Bytes'
104
- * convertBytes(1024, 'KB') // '1 KB'
105
- * convertBytes(1024, 'KB', 2) // '1.00 KB'
106
- * convertBytes(1024 * 1024, 'MB') // '1 MB'
107
- * convertBytes(1024 * 1024, 'KB') // '1024 KB'
108
- * ```
109
- */ const convertBytes = (bytes, unit, decimals = 2)=>new ByteSize(bytes).format(unit, decimals);
110
-
111
- /**
112
- * 檢查兩個值是否相等(包含陣列等引用型別)
113
- * - 支援基本型別的直接比較
114
- * - 特別處理空陣列比較
115
- * - 支援非空陣列的深度比較
116
- *
117
- * @param value1 - 第一個值
118
- * @param value2 - 第二個值
119
- * @returns 如果值相等則返回 true
120
- *
121
- * @example
122
- * // 基本型別比較
123
- * isEqual(1, 1); // true
124
- * isEqual('abc', 'abc'); // true
125
- * isEqual(null, null); // true
126
- *
127
- * // 陣列比較
128
- * isEqual([], []); // true
129
- * isEqual([1, 2], [1, 2]); // true
130
- * isEqual([1, 2], [1, 3]); // false
131
- */ const isEqual = (value1, value2)=>{
132
- // 處理基本型別
133
- if (value1 === value2) {
134
- return true;
135
- }
136
- // 處理空陣列
137
- if (Array.isArray(value1) && Array.isArray(value2) && value1.length === 0 && value2.length === 0) {
138
- return true;
139
- }
140
- // 兩者都是非 null 的物件(包含陣列)
141
- if (value1 !== null && value2 !== null && typeof value1 === 'object' && typeof value2 === 'object') {
142
- // 處理非空陣列
143
- if (Array.isArray(value1) && Array.isArray(value2)) {
144
- if (value1.length !== value2.length) {
145
- return false;
146
- }
147
- return value1.every((item, index)=>isEqual(item, value2[index]));
148
- }
149
- // 未來可以擴展這裡,增加其他物件型別的深度比較
150
- }
151
- return false;
152
- };
153
-
154
- /**
155
- * 將指定格式的物件轉換成類似 enum 的物件
156
- *
157
- * @param enumObject enum 物件
158
- * @param valueKey value 的 key
159
- *
160
- * @example
161
- * const myObj = {
162
- * A: { value: 'a' },
163
- * B: { value: 'b', other: 'other' },
164
- * } as const;
165
- * const enumCode = extractEnumLikeObject(myObj, 'value');
166
- * // => { A: 'a', B: 'b' }
167
- */ const extractEnumLikeObject = (enumObject, valueKey)=>Object.entries(enumObject).reduce((acc, [key, value])=>({
168
- ...acc,
169
- [key]: value[valueKey]
170
- }), {});
171
- // 實作
172
- function createEnumLikeObject(obj, options) {
173
- const name = options?.name;
174
- const scene = options?.scene;
175
- const valueKey = options?.valueKey ?? 'value';
176
- const Enum = extractEnumLikeObject(obj, valueKey);
177
- // List:根據有無 scene 做不同處理
178
- let list;
179
- if (scene) {
180
- // scenes 版本:解構指定 scene 的 label
181
- list = Object.entries(obj).map(([key, item])=>({
182
- key,
183
- value: item?.[valueKey],
184
- ...item.scenes?.[scene] ?? {}
185
- }));
186
- } else {
187
- // label only 版本
188
- list = Object.entries(obj).map(([key, item])=>({
189
- key,
190
- value: item?.[valueKey],
191
- ...item
192
- }));
193
- }
194
- function getLabel(value) {
195
- const targetItem = list.find((item)=>// 如果 list 項目內含有 valueKey 對應欄位,優先以該欄位比對;否則以 value 欄位比對
196
- valueKey in item ? item[valueKey] === value : item.value === value);
197
- if (!targetItem) return String(value);
198
- if ('label' in targetItem) return targetItem.label;
199
- return String(value);
200
- }
201
- if (name) {
202
- // 命名版:使用 Enum${name}, ${name}List, get${name}Label 鍵名
203
- return {
204
- [`Enum${name}`]: Enum,
205
- [`${name}List`]: list,
206
- [`get${name}Label`]: getLabel
207
- };
208
- }
209
- // 未命名:提供預設鍵名 Enum, List, getLabel
210
- return {
211
- Enum,
212
- List: list,
213
- getLabel
214
- };
215
- }
216
-
217
- /**
218
- * simulate a fake api request
219
- *
220
- * @param returnValue the value to return
221
- * @param result the result of the request
222
- * @param time the time to wait before resolving
223
- *
224
- * @example
225
- *
226
- * const result = await fakeApi({ foo: 'bar' });
227
- * console.log(result); // { result: true, data: { foo: 'bar' } }
228
- */ const fakeApi = (returnValue, result = true, time = 1000)=>new Promise((resolve)=>{
229
- setTimeout(()=>{
230
- if (result) resolve({
231
- result,
232
- data: returnValue
233
- });
234
- else resolve({
235
- result,
236
- message: 'error'
237
- });
238
- }, time);
239
- });
240
-
241
- const MimeTypeMap = {
242
- jpeg: 'image/jpeg',
243
- jpg: 'image/jpeg',
244
- gif: 'image/gif',
245
- png: 'image/png',
246
- pdf: 'application/pdf',
247
- zip: 'application/zip',
248
- csv: 'text/csv',
249
- ppt: 'application/vnd.ms-powerpoint',
250
- pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
251
- xls: 'application/vnd.ms-excel',
252
- xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
253
- doc: 'application/msword',
254
- docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
255
- txt: 'text/plain'
256
- };
257
- const OtherMimeType = 'application/octet-stream';
258
-
259
- /**
260
- * 檢查檔案是否為合法的檔案類型
261
- *
262
- * `accepts` 可同時接受副檔名以及 MIME 類型
263
- *
264
- * @param file 檔案
265
- * @param accepts 允許的類型
266
- *
267
- * @example
268
- *
269
- * ```js
270
- * validateFileType({ type: 'image/png' }, ['image/png', 'image/jpeg']) // true
271
- * validateFileType({ type: 'image/png' }, ['image/jpeg']) // false
272
- * validateFileType({ type: 'image/png' }, ['image/*']) // true
273
- * validateFileType({ name: '圖片.png', type: 'image/png' }, ['.png']) // true
274
- * ```
275
- */ const validateFileType = (file, accepts)=>{
276
- if (accepts.length === 0) return true;
277
- // 獲取文件的MIME類型
278
- const fileMimeType = file.type;
279
- // 提取副檔名(含 .,且轉小寫)
280
- const fileExt = file.name.includes('.') ? `.${file.name.split('.').pop().toLowerCase()}` : '';
281
- return accepts.some((accept)=>{
282
- if (accept.startsWith('.')) {
283
- // 以副檔名檢查,忽略大小寫
284
- return fileExt === accept.toLowerCase();
285
- }
286
- if (accept === fileMimeType) {
287
- return true;
288
- }
289
- if (accept.endsWith('/*')) {
290
- return accept.split('/')[0] === fileMimeType.split('/')[0];
291
- }
292
- return false;
293
- });
294
- };
295
- /**
296
- * 根據檔案副檔名取得對應的 MIME Type
297
- *
298
- * 目前支援的副檔名有:pdf, csv, jpeg, jpg, png, zip, txt
299
- * 除此之外的副檔名皆回傳 application/octet-stream
300
- *
301
- * @param fileExtension 檔案副檔名
302
- *
303
- * @example
304
- *
305
- * getMimeType('pdf') // 'application/pdf'
306
- * getMimeType('csv') // 'text/csv'
307
- * getMimeType('jpeg') // 'image/jpeg'
308
- * getMimeType('jpg') // 'image/jpeg'
309
- * getMimeType('png') // 'image/png'
310
- * getMimeType('txt') // 'text/plain'
311
- * getMimeType('zip') // 'application/zip'
312
- * getMimeType('mp4') // 'application/octet-stream'
313
- * getMimeType('xls') // 'application/vnd.ms-excel'
314
- * getMimeType('xlsx') // 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
315
- * getMimeType('doc') // 'application/msword'
316
- * getMimeType('docx') // 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
317
- *
318
- * @deprecated use `parseFileInfoFromFilename` instead
319
- */ const getMimeType = (fileName)=>{
320
- const ext = (fileName.split('.').pop() || '').toLowerCase();
321
- return MimeTypeMap[ext] ?? OtherMimeType;
322
- };
323
- /**
324
- * 用來解析後端在 response header content-disposition 的內容
325
- *
326
- * 一般來說格式會有以下兩種
327
- *
328
- * - Content-Disposition: attachment; filename="file name.jpg"
329
- * - Content-Disposition: attachment; filename*=UTF-8''file%20name2.jpg
330
- *
331
- * 如果格式正確就會取得檔案名稱(包含副檔名),優先取 filename* 內的內容
332
- *
333
- * @param disposition Content-Disposition
334
- *
335
- * @example
336
- *
337
- * parseFilenameFromDisposition('attachment; filename="file name1.jpg') // file name.jpg
338
- * parseFilenameFromDisposition('attachment; filename*=UTF-8''file%20name2.jpg') // file name2.jpg
339
- * parseFilenameFromDisposition('attachment; filename="file name.jpg; filename*=UTF-8''file%20name2.jpg') // file name2.jpg
340
- */ const parseFilenameFromDisposition = (disposition)=>{
341
- // 1. 先找 filename*
342
- const filenameStarMatch = disposition.match(/filename\*\s*=\s*(?:UTF-8'')?([^;]+)/i);
343
- if (filenameStarMatch && filenameStarMatch[1]) {
344
- // 依 RFC 5987 格式(UTF-8''URL-ENCODED),要先 decode
345
- try {
346
- return decodeURIComponent(filenameStarMatch[1].replace(/(^['"]|['"]$)/g, ''));
347
- } catch {
348
- // fallback,如果 decode 失敗,直接傳回原值
349
- return filenameStarMatch[1];
350
- }
351
- }
352
- // 2. 沒有 filename*,再找 filename
353
- const filenameMatch = disposition.match(/filename\s*=\s*("?)([^";]+)\1/i);
354
- if (filenameMatch && filenameMatch[2]) {
355
- return filenameMatch[2];
356
- }
357
- // 3. 都沒有則 undefined
358
- return undefined;
359
- };
360
- /**
361
- * 解析 `filename` 回傳檔名、副檔名、MIME type
362
- *
363
- * @param filename 檔案名稱
364
- *
365
- * @example
366
- *
367
- * parseFileInfoFromFilename('image.jpg') // ['image', 'jpg', 'image/jpeg']
368
- * parseFileInfoFromFilename('image') // ['image', '', 'application/octet-stream']
369
- */ const parseFileInfoFromFilename = (filename)=>{
370
- const lastDot = filename.lastIndexOf('.');
371
- if (lastDot === -1) return [
372
- filename,
373
- '',
374
- OtherMimeType
375
- ]; // 沒有副檔名
376
- return [
377
- filename.slice(0, lastDot),
378
- filename.slice(lastDot + 1),
379
- MimeTypeMap[filename.slice(lastDot + 1)] ?? OtherMimeType
380
- ];
381
- };
382
-
383
- // const isProduction: boolean = process.env.NODE_ENV === 'production';
384
- const prefix = 'Invariant failed';
385
- // Throw an error if the condition fails
386
- // Strip out error messages for production
387
- // > Not providing an inline default argument for message as the result is smaller
388
- function invariant(condition, // Can provide a string, or a function that returns a string for cases where
389
- // the message takes a fair amount of effort to compute
390
- message) {
391
- if (condition) {
392
- return;
393
- }
394
- // Condition not passed
395
- // In production we strip the message but still throw
396
- if (process.env.NODE_ENV === 'production') {
397
- throw new Error(prefix);
398
- }
399
- // When not in production we allow the message to pass through
400
- // *This block will be removed in production builds*
401
- const provided = typeof message === 'function' ? message() : message;
402
- // Options:
403
- // 1. message provided: `${prefix}: ${provided}`
404
- // 2. message not provided: prefix
405
- const value = provided ? `${prefix}: ${provided}` : prefix;
406
- throw new Error(value);
407
- }
408
-
409
- /**
410
- * 判斷執行環境是否為 Server(node.js) 端
411
- */ const isServer = ()=>typeof window === 'undefined';
412
-
413
- /**
414
- * 將物件中的某些 key 排除
415
- *
416
- * @param object 原始物件
417
- * @param keys 要排除的 key
418
- *
419
- * @example
420
- * const a = { a: 1, b: 2, c: 3, d: 4 };
421
- * const b = omit(a, 'a', 'b'); // { c: 3, d: 4 }
422
- */ const omit = (object, ...keys)=>Object.keys(object).reduce((acc, cur)=>{
423
- if (keys.includes(cur)) {
424
- return acc;
425
- }
426
- return {
427
- ...acc,
428
- [cur]: object[cur]
429
- };
430
- }, {});
431
- /**
432
- * 將物件中的某些 value 排除
433
- *
434
- * @param object 原始物件
435
- * @param values 要排除的 value
436
- *
437
- * @example
438
- * const a = { a: undefined, b: null, c: 3, d: 4, e: [] };
439
- * const b = omitByValue(a, undefined, null, []); // { c: 3, d: 4 }
440
- */ const omitByValue = (object, ...values)=>Object.entries(object).reduce((acc, [key, value])=>{
441
- // 使用深度比較檢查值是否應該被排除
442
- const shouldOmit = values.some((excludeValue)=>isEqual(value, excludeValue));
443
- if (shouldOmit) {
444
- return acc;
445
- }
446
- return {
447
- ...acc,
448
- [key]: value
449
- };
450
- }, {});
451
- /**
452
- * extract the object fields by the given keys
453
- *
454
- * @param object - the object to pick fields from
455
- * @param keys - the keys to pick
456
- *
457
- * @example
458
- *
459
- * const a = { a: 1, b: 2, c: 3, d: 4 };
460
- * const b = pick(a, 'a', 'b'); // { a: 1, b: 2 }
461
- */ const pick = (object, ...keys)=>keys.reduce((acc, cur)=>({
462
- ...acc,
463
- [cur]: object[cur]
464
- }), {});
465
- /**
466
- * extract the object fields by the given values
467
- *
468
- * @param object - the object to pick fields from
469
- * @param values - the values to pick
470
- *
471
- * @example
472
- *
473
- * const a = { a: 1, b: 2, c: 3, d: 4, e: [] };
474
- * const b = pickByValue(a, 1, 2, []); // { a: 1, b: 2, e: [] }
475
- */ const pickByValue = (object, ...values)=>Object.entries(object).reduce((acc, [key, value])=>{
476
- // 使用深度比較檢查值是否應該被選擇
477
- const shouldPick = values.some((pickValue)=>isEqual(value, pickValue));
478
- if (shouldPick) {
479
- return {
480
- ...acc,
481
- [key]: value
482
- };
483
- }
484
- return acc;
485
- }, {});
486
- const isObject = (value)=>value !== null && typeof value === 'object';
487
- /**
488
- * merge two objects deeply
489
- *
490
- * @param target - the target object
491
- * @param source - the source object
492
- *
493
- * @example
494
- *
495
- * const obja = { a: { a1: { a11: 'value 1', a12: 'value 2' }, a2: 'value 3' }, b: 'value 4' };
496
- * const objb = { a: { a1: { a13: 'value 5', a14: 'value 6' }, a3: 'value 7' }};
497
- *
498
- * const mergeResult = deepMerge(obja, objb); // { a: { a1: { a11: 'value 1', a12: 'value 2', a13: 'value 5', a14: 'value 6' }, a2: 'value 3', a3: 'value 7' }, b: 'value 4' }
499
- *
500
- */ const deepMerge = (target, source)=>Object.entries(source).reduce((acc, [key, value])=>{
501
- if (isObject(value)) {
502
- acc[key] = key in target && isObject(target[key]) ? deepMerge(target[key], value) : value;
503
- } else {
504
- acc[key] = value;
505
- }
506
- return acc;
507
- }, {
508
- ...target
509
- });
510
- /**
511
- * A utility function to deeply clone an object.
512
- * @param obj - The object to clone.
513
- *
514
- * @example
515
- *
516
- * const original = { a: 1, b: { c: 2 } };
517
- * const cloned = deepClone(original);
518
- * console.log(cloned); // { a: 1, b: { c: 2 } }
519
- *
520
- */ const deepClone = (obj)=>{
521
- if (obj === null || typeof obj !== 'object') {
522
- return obj;
523
- }
524
- if (obj instanceof Date) {
525
- return new Date(obj.getTime());
526
- }
527
- if (Array.isArray(obj)) {
528
- return obj.map((item)=>deepClone(item));
529
- }
530
- const cloned = Object.keys(obj).reduce((acc, key)=>{
531
- acc[key] = deepClone(obj[key]);
532
- return acc;
533
- }, {});
534
- return cloned;
535
- };
536
- /**
537
- * A utility function to rename a key in an object.
538
- *
539
- * @param obj - The object to modify.
540
- * @param oldKey - The key to rename.
541
- * @param newKey - The new key name.
542
- *
543
- * @example
544
- *
545
- * const obj = { a: 1, b: 2 };
546
- * const newObj = renameKey(obj, 'a', 'c');
547
- * console.log(newObj); // { c: 1, b: 2 }
548
- */ const renameKey = (obj, oldKey, newKey)=>{
549
- // 建立一個淺拷貝,避免修改原始物件
550
- const { [oldKey]: oldValue, ...rest } = obj;
551
- // 回傳新的物件:用新 key 存舊值,其他 key 保留
552
- return {
553
- ...rest,
554
- [newKey]: oldValue
555
- };
556
- };
557
-
558
- /**
559
- * 將嵌套物件的所有屬性設為指定的布林值
560
- * @param obj - 目標物件
561
- * @param boolValue - 布林值
562
- *
563
- * @example
564
- * const obj = { a: { b: 1, c: 2 }, d: 3 };
565
- * const result = setBooleanToNestedObject(obj, true);
566
- * console.log(result); // { a: { b: true, c: true }, d: true }
567
- */ const setBooleanToNestedObject = (obj, boolValue)=>Object.entries(obj).reduce((acc, [key, value])=>{
568
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
569
- // 如果是嵌套物件,遞歸處理
570
- acc[key] = setBooleanToNestedObject(value, boolValue);
571
- } else {
572
- // 如果是基本類型,設為布林值
573
- acc[key] = boolValue;
574
- }
575
- return acc;
576
- }, {});
577
- /**
578
- * 深度合併配置物件的通用工具
579
- *
580
- * @param defaultConfig - 預設配置
581
- * @param customConfig - 自訂配置
582
- *
583
- * @example
584
- * const defaultConfig = { a: true, b: { b1: true, b2: true, b3: false }, c: true, d: false };
585
- * mergeConfig(defaultConfig, { b: { b1: false }, d: true }); // { a: true, b: { b1: false, b2: true, b3: false }, c: true, d: true }
586
- * mergeConfig(defaultConfig, { b: false }); // { a: true, b: { b1: false, b2: false, b3: false }, c: true, d: false }
587
- * mergeConfig(defaultConfig, { b: true }); // { a: true, b: { b1: true, b2: true, b3: true }, c: true, d: false }
588
- */ const mergeConfig = (defaultConfig, customConfig = {})=>{
589
- // 深拷貝預設配置以避免修改原始物件
590
- const result = deepClone(defaultConfig);
591
- return Object.entries(customConfig).reduce((acc, [key, sourceValue])=>{
592
- const targetValue = acc[key];
593
- // 如果來源值為 null 或 undefined,跳過
594
- if (sourceValue === null || sourceValue === undefined) {
595
- return acc;
596
- }
597
- // 如果目標物件中對應的值是物件,且來源值是布林值
598
- // 這是特殊情況:用布林值覆蓋整個嵌套物件
599
- if (typeof targetValue === 'object' && targetValue !== null && !Array.isArray(targetValue) && typeof sourceValue === 'boolean') {
600
- // 將嵌套物件的所有屬性設為該布林值
601
- acc[key] = setBooleanToNestedObject(targetValue, sourceValue);
602
- } else if (typeof targetValue === 'object' && targetValue !== null && !Array.isArray(targetValue) && typeof sourceValue === 'object' && sourceValue !== null && !Array.isArray(sourceValue)) {
603
- acc[key] = mergeConfig(targetValue, sourceValue);
604
- } else {
605
- acc[key] = sourceValue;
606
- }
607
- return acc;
608
- }, result);
609
- };
610
-
611
- /**
612
- * debounce function
613
- *
614
- * @param {Function} fn function to be executed
615
- * @param {number} delay time to wait before executing the function
616
- *
617
- * @example
618
- * const debouncedFunction = debounce((a: number, b: number) => console.log(a + b), 1000);
619
- * debouncedFunction(1, 2);
620
- * debouncedFunction(3, 4);
621
- * // after 1 second
622
- * // 7
623
- */ const debounce = (fn, delay)=>{
624
- let timeout;
625
- // if (isAsync) {
626
- // return (...args: P[]) =>
627
- // new Promise((resolve) => {
628
- // if (timeout) {
629
- // clearTimeout(timeout);
630
- // }
631
- // timeout = setTimeout(() => {
632
- // resolve(fn(...args));
633
- // }, delay);
634
- // });
635
- // }
636
- return (...args)=>{
637
- if (timeout) {
638
- clearTimeout(timeout);
639
- }
640
- timeout = setTimeout(()=>{
641
- fn(...args);
642
- }, delay);
643
- };
644
- };
645
- /**
646
- * throttle function
647
- *
648
- * @param {Function} fn function to be executed
649
- * @param {number} delay time to wait before executing the function
650
- *
651
- * @example
652
- * const throttledFunction = throttle((a: number, b: number) => a + b, 1000);
653
- * throttledFunction(1, 2); // 3
654
- * throttledFunction(3, 4); // undefined
655
- * setTimeout(() => {
656
- * throttledFunction(5, 6); // 11
657
- * }, 2000);
658
- */ const throttle = (fn, delay)=>{
659
- let wait = false;
660
- return (...args)=>{
661
- if (wait) return undefined;
662
- const val = fn(...args);
663
- wait = true;
664
- setTimeout(()=>{
665
- wait = false;
666
- }, delay);
667
- return val;
668
- };
669
- };
670
-
671
- /**
672
- * Wait for a given amount of time
673
- * @param ms time to wait in milliseconds
674
- */ const wait = (ms)=>{
675
- };
676
-
677
- /**
678
- * 將單層物件轉換為 URLSearchParams 物件
679
- * - 會自動排除 null、undefined、空字串和空陣列的值
680
- * - 陣列會以逗號連接為字串
681
- *
682
- * @param obj - 要轉換的物件,只支援單層物件,其中值可以是 string、number、boolean、null、undefined 或字串陣列
683
- * @returns URLSearchParams 實例
684
- *
685
- * @example
686
- * const params = { a: '1', b: 123, c: false, d: ['1','2'], e: null, f: undefined, g: '', h: [] };
687
- * objectToSearchParams(params).toString(); // 'a=1&b=123&c=false&d=1%2C2'
688
- */ const objectToSearchParams = (obj)=>{
689
- const searchParams = new URLSearchParams();
690
- if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
691
- return searchParams;
692
- }
693
- Object.entries(omitByValue(obj, undefined, null, '', [])).forEach(([key, value])=>{
694
- // 如果是陣列,則以逗號連接
695
- const paramValue = Array.isArray(value) ? value.join(',') : String(value);
696
- searchParams.append(key, paramValue);
697
- });
698
- return searchParams;
699
- };
700
- /**
701
- * 將字串值轉換為指定的型別
702
- *
703
- * @param value - 要轉換的字串值
704
- * @param targetType - 目標型別
705
- * @returns 轉換後的值
706
- */ const convertValueByType = (value, targetType)=>{
707
- switch(targetType){
708
- case 'number':
709
- return value ? Number(value) : 0;
710
- case 'boolean':
711
- return value === 'true' || value === '1';
712
- case 'array':
713
- return value ? value.split(',') : [];
714
- case 'string':
715
- default:
716
- // 預設為字串,不需要轉換
717
- return value;
718
- }
719
- };
720
- /**
721
- * 將 URLSearchParams 或字串轉換為物件
722
- *
723
- * @param searchParams - 要轉換的搜尋參數字串或 URLSearchParams 實例
724
- * @param typeMap - 可選的型別轉換映射表,用於指定每個參數的目標型別
725
- * @returns
726
- *
727
- * @example
728
- * const queryString = 'a=1&b=123&c=true&d=1,2,3&e=false';
729
- * const result = searchParamsToObject(queryString);
730
- * // result: { a: '1', b: '123', c: 'true', d: '1,2,3', e: 'false' }
731
- * const result = searchParamsToObject(queryString, {
732
- * a: 'string',
733
- * b: 'number',
734
- * c: 'boolean',
735
- * d: 'array',
736
- * e: 'boolean',
737
- * });
738
- * // result: { a: '1', b: 123, c: true, d: ['1', '2', '3'], e: false }
739
- */ const searchParamsToObject = (searchParams, typeMap = {})=>{
740
- const searchParamsInstance = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
741
- const result = {};
742
- // 從 URLSearchParams 取得所有參數
743
- searchParamsInstance.forEach((value, key)=>{
744
- if (!key) {
745
- return;
746
- }
747
- const targetType = typeMap[key];
748
- result[key] = convertValueByType(value, targetType);
749
- });
750
- return result;
751
- };
752
8
 
753
9
  /**
754
10
  * convert CamelCase string to PascalCase string
@@ -1414,4 +670,4 @@ function mergeRefs(refs) {
1414
670
  return dayjs(endMonth, 'YYYYMM').subtract(1911, 'year').format('YYYYMM').substring(1);
1415
671
  };
1416
672
 
1417
- export { ByteSize, MimeTypeMap, OtherMimeType, adToRocEra, camelCase2PascalCase, camelCase2SnakeCase, camelString2PascalString, camelString2SnakeString, convertBytes, createDataContext, createEnumLikeObject, debounce, deepClone, deepMerge, extractEnumLikeObject, fakeApi, formatAmount, formatBytes, formatStarMask, generatePeriodArray, getCurrentPeriod, getMimeType, invariant, isChinese, isDateString, isDateTimeString, isEmail, isEnglish, isEqual, isNil, isNonZeroStart, isNumber, isNumberAtLeastN, isNumberN, isNumberNM, isServer, isTWMobile, isTWPhone, isTimeString, isValidPassword, maskString, mergeConfig, mergeRefs, objectToSearchParams, omit, omitByValue, parseFileInfoFromFilename, parseFilenameFromDisposition, pascalCase2CamelCase, pascalCase2SnakeCase, pascalString2CamelString, pascalString2SnakeString, pick, pickByValue, renameKey, rocEraToAd, searchParamsToObject, snakeCase2CamelCase, snakeCase2PascalCase, snakeString2CamelString, snakeString2PascalString, throttle, useValue, validTaxId, validateDateString, validateFileType, wait };
673
+ export { adToRocEra, camelCase2PascalCase, camelCase2SnakeCase, camelString2PascalString, camelString2SnakeString, createDataContext, formatAmount, formatBytes, formatStarMask, generatePeriodArray, getCurrentPeriod, isChinese, isDateString, isDateTimeString, isEmail, isEnglish, isNil, isNonZeroStart, isNumber, isNumberAtLeastN, isNumberN, isNumberNM, isTWMobile, isTWPhone, isTimeString, isValidPassword, maskString, mergeRefs, pascalCase2CamelCase, pascalCase2SnakeCase, pascalString2CamelString, pascalString2SnakeString, rocEraToAd, snakeCase2CamelCase, snakeCase2PascalCase, snakeString2CamelString, snakeString2PascalString, useValue, validTaxId, validateDateString };