@gateweb/react-utils 1.12.2 → 1.14.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/README.md CHANGED
@@ -1,74 +1,162 @@
1
- # react-utils
1
+ # @gateweb/react-utils
2
2
 
3
- **_react-utils_** is a collection of utility functions for GateWeb's React projects.
3
+ **`@gateweb/react-utils`** is a comprehensive, TypeScript-first utility library designed to streamline development in React projects at GateWeb. It provides a collection of robust, well-tested, and reusable functions and hooks, covering everything from date manipulation and type conversion to custom hooks and web APIs.
4
4
 
5
- ## Installation
5
+ [![npm version](https://img.shields.io/npm/v/@gateweb/react-utils.svg)](https://www.npmjs.com/package/@gateweb/react-utils)
6
+
7
+ ## ✨ Features
8
+
9
+ - **React Hooks**: A collection of useful hooks like `useCountdown` and `useValue`.
10
+ - **Date Utilities**: Powerful and flexible functions for handling dates and time periods, built on top of `dayjs`.
11
+ - **Core Helpers**: A wide range of utilities for type conversion (`bytes`, `searchParams`), case style formatting, object manipulation, and more.
12
+ - **Web APIs**: Simplified functions for common web tasks like file downloads (`download`) and managing browser storage (`webStorage`).
13
+ - **Validation**: A set of predefined regex patterns and validation functions for common data types.
14
+ - **TypeScript First**: Fully written in TypeScript, providing excellent type safety and autocompletion out of the box.
15
+ - **Lightweight & Tree-Shakable**: Built with `bunchee` to ensure minimal bundle size.
16
+
17
+ ## 📦 Installation
6
18
 
7
19
  ```bash
20
+ # With pnpm (recommended)
21
+ pnpm add @gateweb/react-utils
22
+
23
+ # With npm
8
24
  npm install @gateweb/react-utils
9
- # or
25
+
26
+ # With yarn
10
27
  yarn add @gateweb/react-utils
11
- # or
12
- pnpm add @gateweb/react-utils
13
28
  ```
14
29
 
15
- ## Usage
30
+ ## 🚀 Usage
31
+
32
+ Here are some examples of the most common utilities.
33
+
34
+ ### React Hooks
35
+
36
+ #### `useCountdown`
37
+
38
+ A hook to manage a countdown timer.
16
39
 
17
40
  ```tsx
18
- import { formatAmount } from '@gateweb/react-utils';
41
+ import { useCountdown } from '@gateweb/react-utils';
42
+
43
+ function MyComponent() {
44
+ const { count, start, stop, reset } = useCountdown({ initialValue: 60 });
45
+
46
+ return (
47
+ <div>
48
+ <p>Countdown: {count}</p>
49
+ <button onClick={start}>Start</button>
50
+ <button onClick={stop}>Stop</button>
51
+ <button onClick={reset}>Reset</button>
52
+ </div>
53
+ );
54
+ }
19
55
  ```
20
56
 
21
- ## How to Release a New Version
57
+ ### Date Utilities
58
+
59
+ #### `formatDate`
60
+
61
+ Format a date object or string into a custom format.
22
62
 
23
- ### Manually Bump the Version
63
+ ```ts
64
+ import { formatDate } from '@gateweb/react-utils';
24
65
 
25
- 1. Update the version in `package.json`
66
+ const formattedDate = formatDate(new Date(), 'YYYY-MM-DD');
67
+ console.log(formattedDate); // e.g., "2023-10-27"
68
+ ```
69
+
70
+ #### `getPeriod`
26
71
 
27
- ```diff
28
- # e.g. bump the version from 0.1.0 to 0.1.1
29
- {
30
- "name": "@gateweb/react-utils",
31
- - "version": "0.1.0"
32
- + "version": "0.1.1"
33
- }
34
- ```
72
+ Get a predefined date period, like "last 7 days".
35
73
 
36
- 2. Install the dependencies and build the package
74
+ ```ts
75
+ import { getPeriod } from '@gateweb/react-utils';
76
+
77
+ const last7Days = getPeriod('last_7_days');
78
+ console.log(last7Days); // { startDate: Dayjs, endDate: Dayjs }
79
+ ```
37
80
 
38
- ```sh
39
- pnpm install
40
- pnpm build
41
- ```
81
+ ### Core Utilities
82
+
83
+ #### `toCamelCase`
84
+
85
+ Convert a string from snake_case or kebab-case to camelCase.
86
+
87
+ ```ts
88
+ import { toCamelCase } from '@gateweb/react-utils';
89
+
90
+ const camel = toCamelCase('hello_world-example');
91
+ console.log(camel); // "helloWorldExample"
92
+ ```
93
+
94
+ #### `bytesToSize`
95
+
96
+ Convert bytes to a human-readable format (KB, MB, GB).
97
+
98
+ ```ts
99
+ import { bytesToSize } from '@gateweb/react-utils';
100
+
101
+ const size = bytesToSize(1024 * 1024 * 5); // 5MB
102
+ console.log(size); // "5 MB"
103
+ ```
104
+
105
+ ### Web APIs
106
+
107
+ #### `download`
108
+
109
+ A simple utility to trigger a file download in the browser.
110
+
111
+ ```ts
112
+ import { download } from '@gateweb/react-utils';
113
+
114
+ function handleDownload() {
115
+ const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
116
+ download(blob, 'hello.txt');
117
+ }
118
+ ```
42
119
 
43
- 3. login to npm
120
+ ## 🤝 Contributing
44
121
 
45
- ```sh
46
- # make sure you have an npm account
47
- pnpm login
48
- # npm notice Log in on https://registry.npmjs.org/
49
- # Login at:
50
- # https://www.npmjs.com/login?next=/login/cli/390e514d-7aa5-4ee7-a13a-b17e6dd64518
51
- # Press ENTER to open in the browser...
52
- ```
122
+ Contributions are welcome! To ensure a smooth development process, please follow these steps:
53
123
 
54
- 4. Publish the package
124
+ 1. **Fork & Clone**: Fork the repository and clone it to your local machine.
125
+ 2. **Set Up**: This project uses `pnpm` as the package manager. Install dependencies with:
126
+ ```bash
127
+ pnpm install
128
+ ```
129
+ 3. **Develop**: Create a new branch for your feature or bug fix.
130
+ 4. **Test**: Write tests for your changes and ensure all existing tests pass.
55
131
 
56
- ```sh
57
- pnpm publish --access public --no-git-checks
58
- ```
132
+ ```bash
133
+ # Run all tests
134
+ pnpm test
59
135
 
60
- 5. Check the published package on npmjs.com
136
+ # Run tests in watch mode
137
+ pnpm test:watch
138
+ ```
61
139
 
62
- [@gateweb/react-utils](https://www.npmjs.com/package/@gateweb/react-utils)
140
+ 5. **Submit a Pull Request**: Push your changes to your fork and open a pull request to the `main` branch. Your code will be automatically linted and formatted upon commit.
63
141
 
64
- ### Automatically Bump the Version
142
+ ## Publishing (For Maintainers)
65
143
 
66
- - When you merge a pull request to the `main` branch, the GitHub Action will automatically bump the version and publish the package to npm.
144
+ ### Manual Release
67
145
 
68
- - The version will follow the [Semantic Versioning](https://semver.org/) rules.
146
+ 1. Update the version in `package.json`.
147
+ 2. Install dependencies and build the package:
148
+ ```sh
149
+ pnpm install && pnpm build
150
+ ```
151
+ 3. Log in to npm:
152
+ ```sh
153
+ pnpm login
154
+ ```
155
+ 4. Publish the package:
156
+ ```sh
157
+ pnpm publish --access public --no-git-checks
158
+ ```
69
159
 
70
- ## Notes
160
+ ### Automatic Release
71
161
 
72
- - You should use `pnpm` to develop this package.
73
- - This package is written in TypeScript and supports TypeScript out of the box.
74
- - This package is built with [bunchee](https://github.com/huozhi/bunchee) which is a zero-config build tool for TypeScript packages based on Rollup.
162
+ When a pull request is merged into the `main` branch, the `release` GitHub Action will automatically bump the version, create a changelog, and publish the new version to npm. The version bump follows [Semantic Versioning](https.semver.org/) based on the commit messages (e.g., `feat:` for minor, `fix:` for patch).
@@ -404,7 +404,9 @@ declare const extractEnumLikeObject: <T extends Record<string, { [P in K]: any;
404
404
  *
405
405
  * @param obj 要處理的物件
406
406
  * @param name 生成的 enum 名稱
407
- * @param scene 要使用的條件 (參考 example)
407
+ *
408
+ * @remarks
409
+ * 若需多場景 label,請傳入第三參數 scene,詳細用法請見範例。
408
410
  *
409
411
  * @example
410
412
  *
@@ -419,7 +421,7 @@ declare const extractEnumLikeObject: <T extends Record<string, { [P in K]: any;
419
421
  *
420
422
  * // scenes 版本
421
423
  *
422
- * Status = { Enabled: { value: 'enabled', scenes: { webA: { label: '啟用' }, webB: { label: '激活' } } }, Disabled: { value: 'disabled', scenes: { webA: { label: '停用' }, webB: { label: '停止' }}}}
424
+ * const Status = { Enabled: { value: 'enabled', scenes: { webA: { label: '啟用' }, webB: { label: '激活' } } }, Disabled: { value: 'disabled', scenes: { webA: { label: '停用' }, webB: { label: '停止' }}}}
423
425
  * const { EnumStatusA, StatusAList, getStatusALabel } = createEnumLikeObject(Status, 'StatusA', 'webA');
424
426
  * console.log(EnumStatusA); // { Enabled: 'enabled', Disabled: 'disabled' }
425
427
  * console.log(StatusAList); // [ { key: 'Enabled', value: 'enabled', label: '啟用' }, { key: 'Disabled', value: 'disabled', label: '停用' }]
@@ -431,6 +433,7 @@ declare const extractEnumLikeObject: <T extends Record<string, { [P in K]: any;
431
433
  * console.log(getStatusBLabel('enabled')); // '激活'
432
434
  *
433
435
  * ```
436
+ *
434
437
  */
435
438
  declare function createEnumLikeObject<T extends Record<string, {
436
439
  value: any;
@@ -474,11 +477,33 @@ declare const fakeApi: <T>(returnValue: T, result?: boolean, time?: number) => P
474
477
  message: string;
475
478
  }>;
476
479
 
480
+ declare const MimeTypeMap: {
481
+ readonly jpeg: "image/jpeg";
482
+ readonly jpg: "image/jpeg";
483
+ readonly gif: "image/gif";
484
+ readonly png: "image/png";
485
+ readonly pdf: "application/pdf";
486
+ readonly zip: "application/zip";
487
+ readonly csv: "text/csv";
488
+ readonly ppt: "application/vnd.ms-powerpoint";
489
+ readonly pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation";
490
+ readonly xls: "application/vnd.ms-excel";
491
+ readonly xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
492
+ readonly doc: "application/msword";
493
+ readonly docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
494
+ readonly txt: "text/plain";
495
+ };
496
+ declare const OtherMimeType = "application/octet-stream";
497
+ type MimeTypeExtension = keyof typeof MimeTypeMap;
498
+ type MimeTypeValue = (typeof MimeTypeMap)[MimeTypeExtension] | typeof OtherMimeType;
499
+
477
500
  /**
478
- * 檢查檔案是否為合法的 MIME 類型
501
+ * 檢查檔案是否為合法的檔案類型
502
+ *
503
+ * `accepts` 可同時接受副檔名以及 MIME 類型
479
504
  *
480
505
  * @param file 檔案
481
- * @param accepts 允許的 MIME 類型
506
+ * @param accepts 允許的類型
482
507
  *
483
508
  * @example
484
509
  *
@@ -486,6 +511,7 @@ declare const fakeApi: <T>(returnValue: T, result?: boolean, time?: number) => P
486
511
  * validateFileType({ type: 'image/png' }, ['image/png', 'image/jpeg']) // true
487
512
  * validateFileType({ type: 'image/png' }, ['image/jpeg']) // false
488
513
  * validateFileType({ type: 'image/png' }, ['image/*']) // true
514
+ * validateFileType({ name: '圖片.png', type: 'image/png' }, ['.png']) // true
489
515
  * ```
490
516
  */
491
517
  declare const validateFileType: (file: File, accepts: string[]) => boolean;
@@ -511,8 +537,40 @@ declare const validateFileType: (file: File, accepts: string[]) => boolean;
511
537
  * getMimeType('xlsx') // 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
512
538
  * getMimeType('doc') // 'application/msword'
513
539
  * getMimeType('docx') // 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
540
+ *
541
+ * @deprecated use `parseFileInfoFromFilename` instead
542
+ */
543
+ declare const getMimeType: (fileName: string) => "image/jpeg" | "image/gif" | "image/png" | "application/pdf" | "application/zip" | "text/csv" | "application/vnd.ms-powerpoint" | "application/vnd.openxmlformats-officedocument.presentationml.presentation" | "application/vnd.ms-excel" | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | "application/msword" | "application/vnd.openxmlformats-officedocument.wordprocessingml.document" | "text/plain";
544
+ /**
545
+ * 用來解析後端在 response header content-disposition 的內容
546
+ *
547
+ * 一般來說格式會有以下兩種
548
+ *
549
+ * - Content-Disposition: attachment; filename="file name.jpg"
550
+ * - Content-Disposition: attachment; filename*=UTF-8''file%20name2.jpg
551
+ *
552
+ * 如果格式正確就會取得檔案名稱(包含副檔名),優先取 filename* 內的內容
553
+ *
554
+ * @param disposition Content-Disposition
555
+ *
556
+ * @example
557
+ *
558
+ * parseFilenameFromDisposition('attachment; filename="file name1.jpg') // file name.jpg
559
+ * parseFilenameFromDisposition('attachment; filename*=UTF-8''file%20name2.jpg') // file name2.jpg
560
+ * parseFilenameFromDisposition('attachment; filename="file name.jpg; filename*=UTF-8''file%20name2.jpg') // file name2.jpg
561
+ */
562
+ declare const parseFilenameFromDisposition: (disposition: string) => string | undefined;
563
+ /**
564
+ * 解析 `filename` 回傳檔名、副檔名、MIME type
565
+ *
566
+ * @param filename 檔案名稱
567
+ *
568
+ * @example
569
+ *
570
+ * parseFileInfoFromFilename('image.jpg') // ['image', 'jpg', 'image/jpeg']
571
+ * parseFileInfoFromFilename('image') // ['image', '', 'application/octet-stream']
514
572
  */
515
- declare const getMimeType: (fileName: string) => "image/jpeg" | "image/png" | "application/pdf" | "application/zip" | "text/csv" | "application/vnd.ms-excel" | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | "application/msword" | "application/vnd.openxmlformats-officedocument.wordprocessingml.document" | "text/plain" | "application/octet-stream";
573
+ declare const parseFileInfoFromFilename: (filename: string) => [string, string, MimeTypeValue];
516
574
 
517
575
  declare function invariant(condition: any, message?: string | (() => string)): asserts condition;
518
576
 
@@ -521,6 +579,23 @@ declare function invariant(condition: any, message?: string | (() => string)): a
521
579
  */
522
580
  declare const isServer: () => boolean;
523
581
 
582
+ type DeepPartialWithBooleanOverride<T> = {
583
+ [K in keyof T]?: T[K] extends object ? T[K] extends boolean ? T[K] : DeepPartialWithBooleanOverride<T[K]> | boolean : T[K];
584
+ };
585
+ /**
586
+ * 深度合併配置物件的通用工具
587
+ *
588
+ * @param defaultConfig - 預設配置
589
+ * @param customConfig - 自訂配置
590
+ *
591
+ * @example
592
+ * const defaultConfig = { a: true, b: { b1: true, b2: true, b3: false }, c: true, d: false };
593
+ * mergeConfig(defaultConfig, { b: { b1: false }, d: true }); // { a: true, b: { b1: false, b2: true, b3: false }, c: true, d: true }
594
+ * mergeConfig(defaultConfig, { b: false }); // { a: true, b: { b1: false, b2: false, b3: false }, c: true, d: false }
595
+ * mergeConfig(defaultConfig, { b: true }); // { a: true, b: { b1: true, b2: true, b3: true }, c: true, d: false }
596
+ */
597
+ declare const mergeConfig: <T extends Record<string, any>>(defaultConfig: T, customConfig?: DeepPartialWithBooleanOverride<T>) => T;
598
+
524
599
  /**
525
600
  * 將物件中的某些 key 排除
526
601
  *
@@ -616,6 +691,18 @@ type RequiredBy<T, K extends keyof T, RemoveUndefined extends boolean = false> =
616
691
  type PartialBy<T, K extends keyof T, RemoveUndefined extends boolean = false> = Omit<T, K> & {
617
692
  [P in K]?: RemoveUndefined extends true ? Exclude<T[P], undefined> : T[P];
618
693
  };
694
+ /**
695
+ * A utility function to deeply clone an object.
696
+ * @param obj - The object to clone.
697
+ *
698
+ * @example
699
+ *
700
+ * const original = { a: 1, b: { c: 2 } };
701
+ * const cloned = deepClone(original);
702
+ * console.log(cloned); // { a: 1, b: { c: 2 } }
703
+ *
704
+ */
705
+ declare const deepClone: <T>(obj: T) => T;
619
706
 
620
707
  /**
621
708
  * debounce function
@@ -928,6 +1015,30 @@ declare const validTaxId: (taxId: string) => boolean;
928
1015
  * validateDateString('20210201', 'YYYYMM') // false
929
1016
  */
930
1017
  declare const validateDateString: (dateString: string, format: string) => boolean;
1018
+ /**
1019
+ * 判斷 `value` 是否為 `null` 或 `undefined`
1020
+ *
1021
+ * @param value 值
1022
+ *
1023
+ * @example
1024
+ * isNil(null); // true
1025
+ * isNil(undefined); // true
1026
+ * isNil(0); // false
1027
+ * isNil(''); // false
1028
+ * isNil(false); // false
1029
+ * isNil({}); // false
1030
+ *
1031
+ * // TypeScript 型別縮窄應用
1032
+ * function example(input?: string | null) {
1033
+ * if (isNil(input)) {
1034
+ * // input 型別會自動縮窄成 null | undefined
1035
+ * return 'No value';
1036
+ * }
1037
+ * // input 型別自動為 string
1038
+ * return input.toUpperCase();
1039
+ * }
1040
+ */
1041
+ declare const isNil: (value: unknown) => value is null | undefined;
931
1042
 
932
1043
  type TQueryProps<Q> = {
933
1044
  /**
@@ -987,7 +1098,7 @@ declare const useQueryContext: <Q>() => <T>(selector: (state: TQueryState<Q>) =>
987
1098
  * and a Provider component for supplying context values.
988
1099
  *
989
1100
  * @template T - The value type for the context.
990
- * @returns {Object} An object containing:
1101
+ * @returns {object} An object containing:
991
1102
  * - useDataContext: A custom hook to access the context value. Throws an error if used outside the provider.
992
1103
  * - DataProvider: A Provider component to wrap your component tree and supply the context value.
993
1104
  *
@@ -1149,4 +1260,5 @@ declare const getLocalStorage: <T>(key: string, deCode?: boolean) => T | undefin
1149
1260
  */
1150
1261
  declare const setLocalStorage: (key: string, value: Record<string, any>, enCode?: boolean) => void;
1151
1262
 
1152
- export { ByteSize, type PartialBy, QueryProvider, type RequiredBy, type TCountdownActions, adToRocEra, camelCase2PascalCase, camelCase2SnakeCase, camelString2PascalString, camelString2SnakeString, convertBytes, createDataContext, createEnumLikeObject, debounce, deepMerge, downloadFile, extractEnumLikeObject, fakeApi, formatAmount, formatBytes, formatStarMask, generatePeriodArray, getCurrentPeriod, getLocalStorage, getMimeType, invariant, isChinese, isDateString, isDateTimeString, isEmail, isEnglish, isEqual, isNonZeroStart, isNumber, isNumberAtLeastN, isNumberN, isNumberNM, isServer, isTWMobile, isTWPhone, isTimeString, isValidPassword, maskString, mergeRefs, objectToSearchParams, omit, omitByValue, pascalCase2CamelCase, pascalCase2SnakeCase, pascalString2CamelString, pascalString2SnakeString, pick, pickByValue, rocEraToAd, searchParamsToObject, setLocalStorage, snakeCase2CamelCase, snakeCase2PascalCase, snakeString2CamelString, snakeString2PascalString, throttle, useCountdown, useQueryContext, useValue, validTaxId, validateDateString, validateFileType, wait };
1263
+ export { ByteSize, MimeTypeMap, OtherMimeType, QueryProvider, adToRocEra, camelCase2PascalCase, camelCase2SnakeCase, camelString2PascalString, camelString2SnakeString, convertBytes, createDataContext, createEnumLikeObject, debounce, deepClone, deepMerge, downloadFile, extractEnumLikeObject, fakeApi, formatAmount, formatBytes, formatStarMask, generatePeriodArray, getCurrentPeriod, getLocalStorage, getMimeType, invariant, isChinese, isDateString, isDateTimeString, isEmail, isEnglish, isEqual, isNil, isNonZeroStart, isNumber, isNumberAtLeastN, isNumberN, isNumberNM, isServer, isTWMobile, isTWPhone, isTimeString, isValidPassword, maskString, mergeConfig, mergeRefs, objectToSearchParams, omit, omitByValue, parseFileInfoFromFilename, parseFilenameFromDisposition, pascalCase2CamelCase, pascalCase2SnakeCase, pascalString2CamelString, pascalString2SnakeString, pick, pickByValue, rocEraToAd, searchParamsToObject, setLocalStorage, snakeCase2CamelCase, snakeCase2PascalCase, snakeString2CamelString, snakeString2PascalString, throttle, useCountdown, useQueryContext, useValue, validTaxId, validateDateString, validateFileType, wait };
1264
+ export type { MimeTypeExtension, MimeTypeValue, PartialBy, RequiredBy, TCountdownActions };