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