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