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