@gateweb/react-utils 1.17.0 → 2.1.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,899 @@
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
+ * 深度走訪物件/陣列,將指定鍵名且值為字串的欄位遮罩為固定字串(預設 "******")。
492
+ *
493
+ * - 預設僅遮罩鍵名等於 `password` 的欄位(區分大小寫)
494
+ * - 可傳入「字串鍵名」或「函式選擇器」來自訂要遮罩的欄位
495
+ * - 僅在值為字串時遮罩,其他型別維持原樣
496
+ * - 不變更輸入參考;回傳全新的資料結構
497
+ * - 函式選擇器會收到 `key`、`value` 與 `path`(到該鍵的路徑,陣列用索引)
498
+ * - 支援巢狀物件與陣列
499
+ *
500
+ * @param input - 來源資料
501
+ * @param mask - 遮罩字串,預設為 "******"
502
+ * @param selector - 欄位選擇器,字串或函式,預設 'password'
503
+ * @returns 回傳遮罩後的新資料
504
+ *
505
+ * @example
506
+ * const input = { password: 'secret', user: { password: 'abc' }, list: [{ password: 'x' }, { ok: 1 }] };
507
+ * const output = maskPasswords(input);
508
+ * // { password: '******', user: { password: '******' }, list: [{ password: '******' }, { ok: 1 }] }
509
+ *
510
+ * // 指定鍵名
511
+ * maskPasswords({ secret: 'xxx' }, '***', 'secret'); // { secret: '***' }
512
+ *
513
+ * // 使用函式選擇器(鍵名包含 'pass' 都遮)
514
+ * maskPasswords({ password: 'a', passcode: 'b' }, '***', (k) => k.includes('pass')); // { password: '***', passcode: '***' }
515
+ */ const maskPasswords = (input, mask = '******', selector = 'password')=>{
516
+ const isObject = (val)=>val !== null && typeof val === 'object' && !Array.isArray(val) && !(val instanceof Date);
517
+ const shouldMask = (key, value, path)=>{
518
+ if (typeof selector === 'string') {
519
+ return key === selector && typeof value === 'string';
520
+ }
521
+ return selector(key, value, path) && typeof value === 'string';
522
+ };
523
+ const walk = (val, path)=>{
524
+ if (val === null || val === undefined) return val;
525
+ if (Array.isArray(val)) {
526
+ return val.map((item, idx)=>walk(item, [
527
+ ...path,
528
+ idx
529
+ ]));
530
+ }
531
+ if (val instanceof Date) {
532
+ return new Date(val.getTime());
533
+ }
534
+ if (isObject(val)) {
535
+ const result = Object.entries(val).reduce((acc, [key, v])=>{
536
+ const nextPath = [
537
+ ...path,
538
+ key
539
+ ];
540
+ if (shouldMask(key, v, nextPath)) {
541
+ return {
542
+ ...acc,
543
+ [key]: mask
544
+ };
545
+ }
546
+ return {
547
+ ...acc,
548
+ [key]: walk(v, nextPath)
549
+ };
550
+ }, {});
551
+ return result;
552
+ }
553
+ return val;
554
+ };
555
+ return walk(input, []);
556
+ };
557
+
558
+ /**
559
+ * 將物件中的某些 key 排除
560
+ *
561
+ * @param object 原始物件
562
+ * @param keys 要排除的 key
563
+ *
564
+ * @example
565
+ * const a = { a: 1, b: 2, c: 3, d: 4 };
566
+ * const b = omit(a, 'a', 'b'); // { c: 3, d: 4 }
567
+ */ const omit = (object, ...keys)=>Object.keys(object).reduce((acc, cur)=>{
568
+ if (keys.includes(cur)) {
569
+ return acc;
570
+ }
571
+ return {
572
+ ...acc,
573
+ [cur]: object[cur]
574
+ };
575
+ }, {});
576
+ /**
577
+ * 將物件中的某些 value 排除
578
+ *
579
+ * @param object 原始物件
580
+ * @param values 要排除的 value
581
+ *
582
+ * @example
583
+ * const a = { a: undefined, b: null, c: 3, d: 4, e: [] };
584
+ * const b = omitByValue(a, undefined, null, []); // { c: 3, d: 4 }
585
+ */ const omitByValue = (object, ...values)=>Object.entries(object).reduce((acc, [key, value])=>{
586
+ // 使用深度比較檢查值是否應該被排除
587
+ const shouldOmit = values.some((excludeValue)=>isEqual(value, excludeValue));
588
+ if (shouldOmit) {
589
+ return acc;
590
+ }
591
+ return {
592
+ ...acc,
593
+ [key]: value
594
+ };
595
+ }, {});
596
+ /**
597
+ * extract the object fields by the given keys
598
+ *
599
+ * @param object - the object to pick fields from
600
+ * @param keys - the keys to pick
601
+ *
602
+ * @example
603
+ *
604
+ * const a = { a: 1, b: 2, c: 3, d: 4 };
605
+ * const b = pick(a, 'a', 'b'); // { a: 1, b: 2 }
606
+ */ const pick = (object, ...keys)=>keys.reduce((acc, cur)=>({
607
+ ...acc,
608
+ [cur]: object[cur]
609
+ }), {});
610
+ /**
611
+ * extract the object fields by the given values
612
+ *
613
+ * @param object - the object to pick fields from
614
+ * @param values - the values to pick
615
+ *
616
+ * @example
617
+ *
618
+ * const a = { a: 1, b: 2, c: 3, d: 4, e: [] };
619
+ * const b = pickByValue(a, 1, 2, []); // { a: 1, b: 2, e: [] }
620
+ */ const pickByValue = (object, ...values)=>Object.entries(object).reduce((acc, [key, value])=>{
621
+ // 使用深度比較檢查值是否應該被選擇
622
+ const shouldPick = values.some((pickValue)=>isEqual(value, pickValue));
623
+ if (shouldPick) {
624
+ return {
625
+ ...acc,
626
+ [key]: value
627
+ };
628
+ }
629
+ return acc;
630
+ }, {});
631
+ const isObject = (value)=>value !== null && typeof value === 'object';
632
+ /**
633
+ * merge two objects deeply
634
+ *
635
+ * @param target - the target object
636
+ * @param source - the source object
637
+ *
638
+ * @example
639
+ *
640
+ * const obja = { a: { a1: { a11: 'value 1', a12: 'value 2' }, a2: 'value 3' }, b: 'value 4' };
641
+ * const objb = { a: { a1: { a13: 'value 5', a14: 'value 6' }, a3: 'value 7' }};
642
+ *
643
+ * 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' }
644
+ *
645
+ */ const deepMerge = (target, source)=>Object.entries(source).reduce((acc, [key, value])=>{
646
+ if (isObject(value)) {
647
+ acc[key] = key in target && isObject(target[key]) ? deepMerge(target[key], value) : value;
648
+ } else {
649
+ acc[key] = value;
650
+ }
651
+ return acc;
652
+ }, {
653
+ ...target
654
+ });
655
+ /**
656
+ * A utility function to deeply clone an object.
657
+ * @param obj - The object to clone.
658
+ *
659
+ * @example
660
+ *
661
+ * const original = { a: 1, b: { c: 2 } };
662
+ * const cloned = deepClone(original);
663
+ * console.log(cloned); // { a: 1, b: { c: 2 } }
664
+ *
665
+ */ const deepClone = (obj)=>{
666
+ if (obj === null || typeof obj !== 'object') {
667
+ return obj;
668
+ }
669
+ if (obj instanceof Date) {
670
+ return new Date(obj.getTime());
671
+ }
672
+ if (Array.isArray(obj)) {
673
+ return obj.map((item)=>deepClone(item));
674
+ }
675
+ const cloned = Object.keys(obj).reduce((acc, key)=>{
676
+ acc[key] = deepClone(obj[key]);
677
+ return acc;
678
+ }, {});
679
+ return cloned;
680
+ };
681
+ /**
682
+ * A utility function to rename a key in an object.
683
+ *
684
+ * @param obj - The object to modify.
685
+ * @param oldKey - The key to rename.
686
+ * @param newKey - The new key name.
687
+ *
688
+ * @example
689
+ *
690
+ * const obj = { a: 1, b: 2 };
691
+ * const newObj = renameKey(obj, 'a', 'c');
692
+ * console.log(newObj); // { c: 1, b: 2 }
693
+ */ const renameKey = (obj, oldKey, newKey)=>{
694
+ // 建立一個淺拷貝,避免修改原始物件
695
+ const { [oldKey]: oldValue, ...rest } = obj;
696
+ // 回傳新的物件:用新 key 存舊值,其他 key 保留
697
+ return {
698
+ ...rest,
699
+ [newKey]: oldValue
700
+ };
701
+ };
702
+
703
+ /**
704
+ * 將嵌套物件的所有屬性設為指定的布林值
705
+ * @param obj - 目標物件
706
+ * @param boolValue - 布林值
707
+ *
708
+ * @example
709
+ * const obj = { a: { b: 1, c: 2 }, d: 3 };
710
+ * const result = setBooleanToNestedObject(obj, true);
711
+ * console.log(result); // { a: { b: true, c: true }, d: true }
712
+ */ const setBooleanToNestedObject = (obj, boolValue)=>Object.entries(obj).reduce((acc, [key, value])=>{
713
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
714
+ // 如果是嵌套物件,遞歸處理
715
+ acc[key] = setBooleanToNestedObject(value, boolValue);
716
+ } else {
717
+ // 如果是基本類型,設為布林值
718
+ acc[key] = boolValue;
719
+ }
720
+ return acc;
721
+ }, {});
722
+ /**
723
+ * 深度合併配置物件的通用工具
724
+ *
725
+ * @param defaultConfig - 預設配置
726
+ * @param customConfig - 自訂配置
727
+ *
728
+ * @example
729
+ * const defaultConfig = { a: true, b: { b1: true, b2: true, b3: false }, c: true, d: false };
730
+ * mergeConfig(defaultConfig, { b: { b1: false }, d: true }); // { a: true, b: { b1: false, b2: true, b3: false }, c: true, d: true }
731
+ * mergeConfig(defaultConfig, { b: false }); // { a: true, b: { b1: false, b2: false, b3: false }, c: true, d: false }
732
+ * mergeConfig(defaultConfig, { b: true }); // { a: true, b: { b1: true, b2: true, b3: true }, c: true, d: false }
733
+ */ const mergeConfig = (defaultConfig, customConfig = {})=>{
734
+ // 深拷貝預設配置以避免修改原始物件
735
+ const result = deepClone(defaultConfig);
736
+ return Object.entries(customConfig).reduce((acc, [key, sourceValue])=>{
737
+ const targetValue = acc[key];
738
+ // 如果來源值為 null 或 undefined,跳過
739
+ if (sourceValue === null || sourceValue === undefined) {
740
+ return acc;
741
+ }
742
+ // 如果目標物件中對應的值是物件,且來源值是布林值
743
+ // 這是特殊情況:用布林值覆蓋整個嵌套物件
744
+ if (typeof targetValue === 'object' && targetValue !== null && !Array.isArray(targetValue) && typeof sourceValue === 'boolean') {
745
+ // 將嵌套物件的所有屬性設為該布林值
746
+ acc[key] = setBooleanToNestedObject(targetValue, sourceValue);
747
+ } else if (typeof targetValue === 'object' && targetValue !== null && !Array.isArray(targetValue) && typeof sourceValue === 'object' && sourceValue !== null && !Array.isArray(sourceValue)) {
748
+ acc[key] = mergeConfig(targetValue, sourceValue);
749
+ } else {
750
+ acc[key] = sourceValue;
751
+ }
752
+ return acc;
753
+ }, result);
754
+ };
755
+
756
+ /**
757
+ * debounce function
758
+ *
759
+ * @param {Function} fn function to be executed
760
+ * @param {number} delay time to wait before executing the function
761
+ *
762
+ * @example
763
+ * const debouncedFunction = debounce((a: number, b: number) => console.log(a + b), 1000);
764
+ * debouncedFunction(1, 2);
765
+ * debouncedFunction(3, 4);
766
+ * // after 1 second
767
+ * // 7
768
+ */ const debounce = (fn, delay)=>{
769
+ let timeout;
770
+ // if (isAsync) {
771
+ // return (...args: P[]) =>
772
+ // new Promise((resolve) => {
773
+ // if (timeout) {
774
+ // clearTimeout(timeout);
775
+ // }
776
+ // timeout = setTimeout(() => {
777
+ // resolve(fn(...args));
778
+ // }, delay);
779
+ // });
780
+ // }
781
+ return (...args)=>{
782
+ if (timeout) {
783
+ clearTimeout(timeout);
784
+ }
785
+ timeout = setTimeout(()=>{
786
+ fn(...args);
787
+ }, delay);
788
+ };
789
+ };
790
+ /**
791
+ * throttle function
792
+ *
793
+ * @param {Function} fn function to be executed
794
+ * @param {number} delay time to wait before executing the function
795
+ *
796
+ * @example
797
+ * const throttledFunction = throttle((a: number, b: number) => a + b, 1000);
798
+ * throttledFunction(1, 2); // 3
799
+ * throttledFunction(3, 4); // undefined
800
+ * setTimeout(() => {
801
+ * throttledFunction(5, 6); // 11
802
+ * }, 2000);
803
+ */ const throttle = (fn, delay)=>{
804
+ let wait = false;
805
+ return (...args)=>{
806
+ if (wait) return undefined;
807
+ const val = fn(...args);
808
+ wait = true;
809
+ setTimeout(()=>{
810
+ wait = false;
811
+ }, delay);
812
+ return val;
813
+ };
814
+ };
815
+
816
+ /**
817
+ * Wait for a given amount of time
818
+ * @param ms time to wait in milliseconds
819
+ */ const wait = (ms)=>{
820
+ };
821
+
822
+ /**
823
+ * 將單層物件轉換為 URLSearchParams 物件
824
+ * - 會自動排除 null、undefined、空字串和空陣列的值
825
+ * - 陣列會以逗號連接為字串
826
+ *
827
+ * @param obj - 要轉換的物件,只支援單層物件,其中值可以是 string、number、boolean、null、undefined 或字串陣列
828
+ * @returns URLSearchParams 實例
829
+ *
830
+ * @example
831
+ * const params = { a: '1', b: 123, c: false, d: ['1','2'], e: null, f: undefined, g: '', h: [] };
832
+ * objectToSearchParams(params).toString(); // 'a=1&b=123&c=false&d=1%2C2'
833
+ */ const objectToSearchParams = (obj)=>{
834
+ const searchParams = new URLSearchParams();
835
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
836
+ return searchParams;
837
+ }
838
+ Object.entries(omitByValue(obj, undefined, null, '', [])).forEach(([key, value])=>{
839
+ // 如果是陣列,則以逗號連接
840
+ const paramValue = Array.isArray(value) ? value.join(',') : String(value);
841
+ searchParams.append(key, paramValue);
842
+ });
843
+ return searchParams;
844
+ };
845
+ /**
846
+ * 將字串值轉換為指定的型別
847
+ *
848
+ * @param value - 要轉換的字串值
849
+ * @param targetType - 目標型別
850
+ * @returns 轉換後的值
851
+ */ const convertValueByType = (value, targetType)=>{
852
+ switch(targetType){
853
+ case 'number':
854
+ return value ? Number(value) : 0;
855
+ case 'boolean':
856
+ return value === 'true' || value === '1';
857
+ case 'array':
858
+ return value ? value.split(',') : [];
859
+ case 'string':
860
+ default:
861
+ // 預設為字串,不需要轉換
862
+ return value;
863
+ }
864
+ };
865
+ /**
866
+ * 將 URLSearchParams 或字串轉換為物件
867
+ *
868
+ * @param searchParams - 要轉換的搜尋參數字串或 URLSearchParams 實例
869
+ * @param typeMap - 可選的型別轉換映射表,用於指定每個參數的目標型別
870
+ * @returns
871
+ *
872
+ * @example
873
+ * const queryString = 'a=1&b=123&c=true&d=1,2,3&e=false';
874
+ * const result = searchParamsToObject(queryString);
875
+ * // result: { a: '1', b: '123', c: 'true', d: '1,2,3', e: 'false' }
876
+ * const result = searchParamsToObject(queryString, {
877
+ * a: 'string',
878
+ * b: 'number',
879
+ * c: 'boolean',
880
+ * d: 'array',
881
+ * e: 'boolean',
882
+ * });
883
+ * // result: { a: '1', b: 123, c: true, d: ['1', '2', '3'], e: false }
884
+ */ const searchParamsToObject = (searchParams, typeMap = {})=>{
885
+ const searchParamsInstance = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
886
+ const result = {};
887
+ // 從 URLSearchParams 取得所有參數
888
+ searchParamsInstance.forEach((value, key)=>{
889
+ if (!key) {
890
+ return;
891
+ }
892
+ const targetType = typeMap[key];
893
+ result[key] = convertValueByType(value, targetType);
894
+ });
895
+ return result;
896
+ };
8
897
 
9
898
  /**
10
899
  * convert CamelCase string to PascalCase string
@@ -495,100 +1384,6 @@ const FILE_SIZE_UNITS = [
495
1384
  * }
496
1385
  */ const isNil = (value)=>value === null || value === undefined;
497
1386
 
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
1387
  /**
593
1388
  * 民國年轉西元年
594
1389
  * @param dateString 日期字串
@@ -670,4 +1465,4 @@ function mergeRefs(refs) {
670
1465
  return dayjs(endMonth, 'YYYYMM').subtract(1911, 'year').format('YYYYMM').substring(1);
671
1466
  };
672
1467
 
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 };
1468
+ 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, maskPasswords, 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 };