├── .babelrc
├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .github
└── workflows
│ └── CI.yml
├── .gitignore
├── .prettierignore
├── .prettierrc.js
├── .vscode
├── extensions.json
└── settings.json
├── CHANGELOG.md
├── LICENSE
├── README.md
├── api-extractor.json
├── commitlint.config.js
├── docs
├── .nojekyll
├── CHANGELOG.md
├── README.md
├── _sidebar.md
├── contribution-guide.md
├── cookie.md
├── copy.md
├── dateTime.md
├── idb.md
├── index.html
├── layout.md
├── ldb.md
├── quickstart.md
├── sw.js
└── utils.md
├── gulpfile.ts
├── jest.config.js
├── package.json
├── rollup.config.ts
├── scripts
└── release.sh
├── src
├── cookie.ts
├── copy.ts
├── dateTime.ts
├── index.ts
├── indexedDB.ts
├── layout.ts
├── localDB.ts
└── utils.ts
├── test
├── cookie.test.ts
├── dateTime.test.ts
├── localDB.test.ts
└── utils.test.ts
├── tsconfig.eslint.json
├── tsconfig.json
└── yarn.lock
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | [
4 | "@babel/preset-env",
5 | {
6 | "modules": false
7 | }
8 | ]
9 | ]
10 | }
11 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # editorconfig.org
2 | root = true
3 |
4 | [*]
5 | indent_style = space
6 | indent_size = 4
7 | end_of_line = lf
8 | charset = utf-8
9 | trim_trailing_whitespace = true
10 | insert_final_newline = true
11 |
12 | [*.md]
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | dist/
2 | lib/
3 | node_modules/
4 | public/
5 | config/
6 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: [require.resolve('ko-lint-config/.eslintrc')],
3 | rules: {
4 | 'no-console': 0,
5 | 'no-param-reassign': 0, // 函数的入参再次赋值
6 | },
7 | };
8 |
--------------------------------------------------------------------------------
/.github/workflows/CI.yml:
--------------------------------------------------------------------------------
1 | # This is a basic workflow to help you get started with Actions
2 |
3 | name: CI
4 |
5 | # Triggers the workflow on push or pull request events but only for the master branch
6 | on:
7 | push:
8 | branches: [master]
9 | pull_request:
10 | branches: [master]
11 |
12 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel
13 | jobs:
14 | setup:
15 | runs-on: ubuntu-latest
16 | steps:
17 | - name: Checkout code
18 | uses: actions/checkout@v4
19 |
20 | - name: Cache yarn.lock
21 | uses: actions/cache@v4
22 | with:
23 | path: package-temp-dir
24 | key: lock-${{ github.sha }}
25 |
26 | - name: Create yarn.lock
27 | run: yarn generate-lock-entry
28 |
29 | - name: Hack for single file
30 | run: |
31 | if [ ! -d "package-temp-dir" ]; then
32 | mkdir package-temp-dir
33 | fi
34 | cp yarn.lock package-temp-dir
35 | - name: Cache node_modules
36 | id: node_modules_cache_id
37 | uses: actions/cache@v4
38 | with:
39 | path: node_modules
40 | key: node_modules-${{ hashFiles('**/package-temp-dir/yarn.lock') }}
41 |
42 | - name: Install dependencies
43 | if: steps.node_modules_cache_id.outputs.cache-hit != 'true'
44 | run: yarn
45 |
46 | prettier:
47 | needs: [setup]
48 | runs-on: ubuntu-latest
49 | steps:
50 | - uses: actions/checkout@v2
51 |
52 | - name: Restore cache from yarn.lock
53 | uses: actions/cache@v4
54 | with:
55 | path: package-temp-dir
56 | key: lock-${{ github.sha }}
57 |
58 | - name: Restore cache from node_modules
59 | uses: actions/cache@v4
60 | with:
61 | path: node_modules
62 | key: node_modules-${{ hashFiles('**/package-temp-dir/yarn.lock') }}
63 |
64 | - name: Prettier check
65 | run: yarn prettier
66 |
67 | eslint:
68 | needs: [setup]
69 | runs-on: ubuntu-latest
70 | steps:
71 | - uses: actions/checkout@v2
72 |
73 | - name: Restore cache from yarn.lock
74 | uses: actions/cache@v4
75 | with:
76 | path: package-temp-dir
77 | key: lock-${{ github.sha }}
78 |
79 | - name: Restore cache from node_modules
80 | uses: actions/cache@v4
81 | with:
82 | path: node_modules
83 | key: node_modules-${{ hashFiles('**/package-temp-dir/yarn.lock') }}
84 |
85 | - name: Eslint check
86 | run: yarn eslint
87 |
88 | test:
89 | needs: [setup]
90 | runs-on: ubuntu-latest
91 | steps:
92 | - uses: actions/checkout@v2
93 |
94 | - name: Restore cache from yarn.lock
95 | uses: actions/cache@v4
96 | with:
97 | path: package-temp-dir
98 | key: lock-${{ github.sha }}
99 |
100 | - name: Restore cache from node_modules
101 | uses: actions/cache@v4
102 | with:
103 | path: node_modules
104 | key: node_modules-${{ hashFiles('**/package-temp-dir/yarn.lock') }}
105 |
106 | - name: Setup timezone
107 | uses: zcong1993/setup-timezone@master
108 | with:
109 | timezone: Asia/Shanghai
110 |
111 | - name: Unit Test
112 | run: yarn test
113 |
114 | build:
115 | runs-on: ubuntu-latest
116 | needs: [setup, prettier, eslint, test]
117 | steps:
118 | - uses: actions/checkout@v2
119 |
120 | - name: Restore cache from yarn.lock
121 | uses: actions/cache@v4
122 | with:
123 | path: package-temp-dir
124 | key: lock-${{ github.sha }}
125 |
126 | - name: Restore cache from node_modules
127 | uses: actions/cache@v4
128 | with:
129 | path: node_modules
130 | key: node_modules-${{ hashFiles('**/package-temp-dir/yarn.lock') }}
131 |
132 | - name: Build test
133 | run: yarn build
134 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 |
9 | # Diagnostic reports (https://nodejs.org/api/report.html)
10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 | *.lcov
24 |
25 | # nyc test coverage
26 | .nyc_output
27 |
28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
29 | .grunt
30 |
31 | # Bower dependency directory (https://bower.io/)
32 | bower_components
33 |
34 | # node-waf configuration
35 | .lock-wscript
36 |
37 | # Compiled binary addons (https://nodejs.org/api/addons.html)
38 | build/Release
39 |
40 | # Dependency directories
41 | node_modules/
42 | jspm_packages/
43 |
44 | # TypeScript v1 declaration files
45 | typings/
46 |
47 | # TypeScript cache
48 | *.tsbuildinfo
49 |
50 | # Optional npm cache directory
51 | .npm
52 |
53 | # Optional eslint cache
54 | .eslintcache
55 |
56 | # Microbundle cache
57 | .rpt2_cache/
58 | .rts2_cache_cjs/
59 | .rts2_cache_es/
60 | .rts2_cache_umd/
61 |
62 | # Optional REPL history
63 | .node_repl_history
64 |
65 | # Output of 'npm pack'
66 | *.tgz
67 |
68 | # Yarn Integrity file
69 | .yarn-integrity
70 |
71 | # dotenv environment variables file
72 | .env
73 | .env.test
74 |
75 | # parcel-bundler cache (https://parceljs.org/)
76 | .cache
77 |
78 | # Next.js build output
79 | .next
80 |
81 | # Nuxt.js build / generate output
82 | .nuxt
83 | dist
84 |
85 | # Gatsby files
86 | .cache/
87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js
88 | # https://nextjs.org/blog/next-9-1#public-directory-support
89 | # public
90 |
91 | # vuepress build output
92 | .vuepress/dist
93 |
94 | # Serverless directories
95 | .serverless/
96 |
97 | # FuseBox cache
98 | .fusebox/
99 |
100 | # DynamoDB Local files
101 | .dynamodb/
102 |
103 | # TernJS port file
104 | .tern-port
105 |
106 | lib
107 | temp
108 |
109 | # ide
110 | # .vscode
111 | .idea
112 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | .vscode
2 |
--------------------------------------------------------------------------------
/.prettierrc.js:
--------------------------------------------------------------------------------
1 | const prettier = require('ko-lint-config/.prettierrc');
2 |
3 | module.exports = {
4 | ...prettier,
5 | };
6 |
--------------------------------------------------------------------------------
/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": [
3 | "dbaeumer.vscode-eslint",
4 | "stylelint.vscode-stylelint",
5 | "esbenp.prettier-vscode",
6 | "streetsidesoftware.code-spell-checker"
7 | ]
8 | }
9 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "cSpell.words": [
3 | "aggr",
4 | "antd",
5 | "changeissueurl",
6 | "consts",
7 | "dtinsight",
8 | "Echart",
9 | "Echarts",
10 | "hoverable",
11 | "Popconfirm",
12 | "postchangelog",
13 | "Sider",
14 | "sonarcube",
15 | "stylelint"
16 | ],
17 | "editor.formatOnSave": false,
18 | "editor.codeActionsOnSave": {
19 | "source.fixAll.eslint": true,
20 | "source.fixAll.stylelint": true
21 | },
22 | "editor.defaultFormatter": "esbenp.prettier-vscode",
23 | "files.trimTrailingWhitespace": true,
24 | "files.insertFinalNewline": true,
25 | "[typescriptreact]": {
26 | "editor.defaultFormatter": "vscode.typescript-language-features"
27 | },
28 | "[javascriptreact]": {
29 | "editor.defaultFormatter": "esbenp.prettier-vscode"
30 | },
31 | "[javascript]": {
32 | "editor.defaultFormatter": "esbenp.prettier-vscode"
33 | },
34 | "[typescript]": {
35 | "editor.defaultFormatter": "esbenp.prettier-vscode"
36 | },
37 | "[scss]": {
38 | "editor.defaultFormatter": "stylelint.vscode-stylelint"
39 | },
40 | "stylelint.validate": ["css", "less", "postcss", "scss"],
41 | "stylelint.snippet": ["css", "less", "postcss", "scss"]
42 | }
43 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4 |
5 | ## [1.5.0](https://github.com/DTStack/dt-utils/compare/v1.4.0...v1.5.0) (2023-11-20)
6 |
7 |
8 | ### Features
9 |
10 | * **downloaddata:** add headers for fetch in downLoadData ([#98](https://github.com/DTStack/dt-utils/issues/98)) ([81a7f67](https://github.com/DTStack/dt-utils/commit/81a7f6781685ef4106c88d06630851071d48ff8b)), closes [#97](https://github.com/DTStack/dt-utils/issues/97)
11 |
12 |
13 | ### Bug Fixes
14 |
15 | * **downloaddata:** add headers for fetch in downLoadData ([#98](https://github.com/DTStack/dt-utils/issues/98)) ([416cfe6](https://github.com/DTStack/dt-utils/commit/416cfe606a07e328a9d4e7a26f01c04bd61b4ac1)), closes [#97](https://github.com/DTStack/dt-utils/issues/97)
16 |
17 | ## [1.4.0](https://github.com/DTStack/dt-utils/compare/v1.3.0...v1.4.0) (2023-11-16)
18 |
19 |
20 | ### Features
21 |
22 | * **utils:** add getUrlPathname and getUrlQueryParams for router ([#88](https://github.com/DTStack/dt-utils/issues/88)) ([78b243d](https://github.com/DTStack/dt-utils/commit/78b243d7cc22c0dac5af6e9105a0a1470ff5db55))
23 |
24 |
25 | ### Bug Fixes
26 |
27 | * [#90](https://github.com/DTStack/dt-utils/issues/90) optimize getParameterByName's return ([#91](https://github.com/DTStack/dt-utils/issues/91)) ([1158b6b](https://github.com/DTStack/dt-utils/commit/1158b6b66075772bc60ef619ab989db6e7799ca7))
28 | * [#92](https://github.com/DTStack/dt-utils/issues/92) optimize getQueryParameters's return ([#93](https://github.com/DTStack/dt-utils/issues/93)) ([fb6b482](https://github.com/DTStack/dt-utils/commit/fb6b482223a2f54c3274d907aee8cba24945878e))
29 | * [#95](https://github.com/DTStack/dt-utils/issues/95) sideEffects should be boolean false ([#96](https://github.com/DTStack/dt-utils/issues/96)) ([b87e664](https://github.com/DTStack/dt-utils/commit/b87e6643e974d2cda74372fc66e70b831896e1ba))
30 | * add DOM.Iterable lib in tsconfig ([#94](https://github.com/DTStack/dt-utils/issues/94)) ([ea98f18](https://github.com/DTStack/dt-utils/commit/ea98f189187b4111ee43c795ed39fcbbab32b7b9))
31 |
32 | ## [1.3.0](https://github.com/DTStack/dt-utils/compare/v1.2.0...v1.3.0) (2023-09-15)
33 |
34 |
35 | ### Features
36 |
37 | * allow cookiesStr params for getCookie ([#86](https://github.com/DTStack/dt-utils/issues/86)) ([7b3e6ae](https://github.com/DTStack/dt-utils/commit/7b3e6aea4494e8f257a162679d18ba3165573c0c))
38 |
39 | ## [1.2.0](https://github.com/DTStack/dt-utils/compare/v1.1.0...v1.2.0) (2023-08-24)
40 |
41 |
42 | ### Features
43 |
44 | * [#64](https://github.com/DTStack/dt-utils/issues/64) localDB add remove function ([d4c80bb](https://github.com/DTStack/dt-utils/commit/d4c80bb06a32569b84554e852018a4b178ff2526))
45 | * getThousandth get '' return '0' ([bde6994](https://github.com/DTStack/dt-utils/commit/bde69946b4a0181b07e9204d197df98b45117175))
46 |
47 |
48 | ### Bug Fixes
49 |
50 | * [#82](https://github.com/DTStack/dt-utils/issues/82) optimize localStorage's get and set function ([53d8978](https://github.com/DTStack/dt-utils/commit/53d8978d136f5ae80366f998c7922c546747caa9))
51 | * **#80:** example Change the edge matching rule of the browser to edg ([5808bc0](https://github.com/DTStack/dt-utils/commit/5808bc05f948da9a18291346dcd8e92d01186844)), closes [#80](https://github.com/DTStack/dt-utils/issues/80)
52 | * cookie ts type completion ([09c0196](https://github.com/DTStack/dt-utils/commit/09c019668c8bfec2a58d142c06aeb3f829924987))
53 | * fix cant download json ([a4fb84e](https://github.com/DTStack/dt-utils/commit/a4fb84e34690c02c09080b251888787ede4f6d5e))
54 |
55 | ### [1.1.2](https://github.com/DTStack/dt-utils/compare/v1.1.0...v1.1.2) (2022-08-16)
56 |
57 |
58 | ### Features
59 |
60 | * [#64](https://github.com/DTStack/dt-utils/issues/64) localDB add remove function ([d4c80bb](https://github.com/DTStack/dt-utils/commit/d4c80bb06a32569b84554e852018a4b178ff2526))
61 | * getThousandth get '' return '0' ([bde6994](https://github.com/DTStack/dt-utils/commit/bde69946b4a0181b07e9204d197df98b45117175))
62 |
63 |
64 | ### Bug Fixes
65 |
66 | * fix cant download json ([a4fb84e](https://github.com/DTStack/dt-utils/commit/a4fb84e34690c02c09080b251888787ede4f6d5e))
67 |
68 | ### [1.1.1](https://github.com/DTStack/dt-utils/compare/v1.1.0...v1.1.1) (2022-02-22)
69 |
70 |
71 | ### Bug Fixes
72 |
73 | * fix cant download json ([a4fb84e](https://github.com/DTStack/dt-utils/commit/a4fb84e34690c02c09080b251888787ede4f6d5e))
74 |
75 | ## [1.1.0](https://github.com/DTStack/dt-utils/compare/v1.0.9...v1.1.0) (2021-12-09)
76 |
77 |
78 | ### Features
79 |
80 | * add three Base64 related methods ([afbe638](https://github.com/DTStack/dt-utils/commit/afbe6386f701a39ef388044c758a929e3f3559af))
81 |
82 |
83 | ### Bug Fixes
84 |
85 | * return '0' when num is null or undefined ([421aaf1](https://github.com/DTStack/dt-utils/commit/421aaf12a27be7f8160019beb35edf60530cffa9))
86 |
87 | ### [1.0.9](https://github.com/DTStack/dt-utils/compare/v1.0.8...v1.0.9) (2021-11-25)
88 |
89 |
90 | ### Features
91 |
92 | * add getThousandth to utils ([a79e797](https://github.com/DTStack/dt-utils/commit/a79e79755f944e5df7d0d7b61ac64803cd169725))
93 |
94 | ### [1.0.8](https://github.com/DTStack/dt-utils/compare/v1.0.7...v1.0.8) (2021-10-26)
95 |
96 |
97 | ### Features
98 |
99 | * add getAllCookies ([889e1ec](https://github.com/DTStack/dt-utils/commit/889e1ec9272d206c046f9dd58ef7ee46bb5e3289))
100 |
101 | ### [1.0.7](https://github.com/DTStack/dt-utils/compare/v1.0.6...v1.0.7) (2021-10-25)
102 |
103 |
104 | ### Features
105 |
106 | * add download data ([c376a00](https://github.com/DTStack/dt-utils/commit/c376a00eb571006fc3949b47f09d237ab39c08b1))
107 | * add judge status ([228c3ec](https://github.com/DTStack/dt-utils/commit/228c3ec4d371b42849218d6796b7701668b34995))
108 | * add return ([29f3c2a](https://github.com/DTStack/dt-utils/commit/29f3c2a55e8c8452bc4ba5428ac0518e779dfb15))
109 | * update info and ts ([75efdfc](https://github.com/DTStack/dt-utils/commit/75efdfcc4dcca74e13aa5562d78f6f76ec8b8009))
110 | * update let to const ([854d1f0](https://github.com/DTStack/dt-utils/commit/854d1f080213b489769077b36617567499197b7f))
111 | * update lint ([3f9dcc5](https://github.com/DTStack/dt-utils/commit/3f9dcc5d64bccb360882b8ed306498e3e632873a))
112 |
113 | ### [1.0.6](https://github.com/DTStack/dt-utils/compare/v1.0.5...v1.0.6) (2021-09-27)
114 |
115 |
116 | ### Features
117 |
118 | * change log and contribution guide ([b42740d](https://github.com/DTStack/dt-utils/commit/b42740d48db1460356debba41348f05cb79095b5))
119 | * remove path root changelog ([65ce7ac](https://github.com/DTStack/dt-utils/commit/65ce7ac69831cc73bad40279ef2a45f98d8e5be4))
120 |
121 | ## [1.0.5](https://github.com/DTStack/dt-utils/compare/v1.0.4...v1.0.5) (2021-09-18)
122 |
123 |
124 | ### Bug Fixes
125 |
126 | * eslint ([6a78ddd](https://github.com/DTStack/dt-utils/commit/6a78ddd4ecbe4704596844e02de803187f2e5ee4))
127 | * replace this ([a99d283](https://github.com/DTStack/dt-utils/commit/a99d283433e1030853d62f1ed1061d2b5f99d32c))
128 | * test lint config ([5cd30ca](https://github.com/DTStack/dt-utils/commit/5cd30ca4c031d0b1417ffad701a262b79ec30ea8))
129 |
130 |
131 | ### Features
132 |
133 | * add mergeObj fn ([af13b81](https://github.com/DTStack/dt-utils/commit/af13b8190173a12059bb384faa3c60aebc224612))
134 | * change trim, delete trimlr, add trimAll ([6792dd3](https://github.com/DTStack/dt-utils/commit/6792dd39f98d9e6c61d87b0461c83dcb8677cfeb))
135 | * delete removeAllSpaces, please use trimAll ([bcbfdf8](https://github.com/DTStack/dt-utils/commit/bcbfdf8059046f258b390e1bcc3331f3741c8e85))
136 |
137 |
138 |
139 | ## [1.0.4](https://github.com/DTStack/dt-utils/compare/v1.0.3...v1.0.4) (2021-09-10)
140 |
141 |
142 | ### Bug Fixes
143 |
144 | * export CopyUtils and sort export by document ([95f684b](https://github.com/DTStack/dt-utils/commit/95f684b9ee07597d56eafc11a157ff353461c9b9))
145 |
146 |
147 | ### Features
148 |
149 | * add a time formatting method file ([65c2356](https://github.com/DTStack/dt-utils/commit/65c2356789ed70991d2c295b685c2967f59752e1))
150 | * add formatSecond method ([eab731c](https://github.com/DTStack/dt-utils/commit/eab731c6a499c1ad54b2e75d99fc7b4a17129a0e))
151 | * add isEmpty methods ([2baed54](https://github.com/DTStack/dt-utils/commit/2baed54ddf5e992e183f6bf828e7e389b9cebb19))
152 | * add isObj methods ([02dc937](https://github.com/DTStack/dt-utils/commit/02dc9379e7437418f18a41637c6798ce067163d8))
153 | * add removeEmpty doc ([7bcf98f](https://github.com/DTStack/dt-utils/commit/7bcf98f53f181b7f3a1d03b92b519650a4750cdf))
154 | * add removeEmpty methods ([8c0c56f](https://github.com/DTStack/dt-utils/commit/8c0c56f9ab4a4924a287fc947f871197c4c8a604))
155 | * add removeEmpty unit test ([1b8f1cc](https://github.com/DTStack/dt-utils/commit/1b8f1ccb0b7f0d01042af3d8a5ca01e9380aa498))
156 | * add transformArray methods ([25d616b](https://github.com/DTStack/dt-utils/commit/25d616b96e4e77b6f03f3ba8467e6b761c585a4f))
157 | * add transformArray ts ([808f574](https://github.com/DTStack/dt-utils/commit/808f5745c96096472afd439cb094ccb5525c7d87))
158 | * release sh ([af1a323](https://github.com/DTStack/dt-utils/commit/af1a3238c3dc50b5ed3fb7ee2a0c570d9317d958))
159 | * transformArray define generic parameters ([3a8641c](https://github.com/DTStack/dt-utils/commit/3a8641c8647d8bcdf6f69834b73f513b98ce5723))
160 | * update cookie methods ([062d17c](https://github.com/DTStack/dt-utils/commit/062d17c2d14d77e8af38067c7d7c34a372960310))
161 |
162 |
163 |
164 | ## [1.0.3](https://github.com/DTStack/dt-utils/compare/v1.0.2...v1.0.3) (2021-04-06)
165 |
166 |
167 | ### Features
168 |
169 | * **utils:** add utils and modify docs ([7b951b2](https://github.com/DTStack/dt-utils/commit/7b951b2c87f7e4a2edac7c0da3ddd0ec46bdc0c6))
170 | * **utils:** modify the document directory ([494c2e8](https://github.com/DTStack/dt-utils/commit/494c2e876cfd5dcd16e31dff4147a736213ea054))
171 |
172 |
173 |
174 | ## [1.0.2](https://github.com/DTStack/dt-utils/compare/v1.0.1...v1.0.2) (2021-04-01)
175 |
176 |
177 |
178 | ## [1.0.1](https://github.com/DTStack/dt-utils/compare/v1.0.0...v1.0.1) (2021-01-20)
179 |
180 |
181 | ### Features
182 |
183 | * **docs:** 补充介绍文档 ([3b2ba81](https://github.com/DTStack/dt-utils/commit/3b2ba81ec99969fcc3fa9062d2efebdc1a087a14))
184 | * **package:** update package dev dependencies ([3cf5655](https://github.com/DTStack/dt-utils/commit/3cf56550b07b69a84ee4409b55a225f1ba9b724f))
185 | * **publish:** update name ([a12a55e](https://github.com/DTStack/dt-utils/commit/a12a55ebba599e8d3f6c7d7c308e4d3ed9e5d518))
186 | * **test:** add test for utils ([931244c](https://github.com/DTStack/dt-utils/commit/931244cb458134d9e0aa843c06a1ceb29fb87686))
187 |
188 |
189 |
190 | # [1.0.0](https://github.com/DTStack/dt-utils/compare/c243c4577b82636456478c63941477fcb693041b...v1.0.0) (2020-07-20)
191 |
192 |
193 | ### Features
194 |
195 | * add to complete ([1b438f8](https://github.com/DTStack/dt-utils/commit/1b438f8d7d7c8366ac1572dc63d4401bf14d8d8e))
196 | * **change:** 更新同步changelog ([a88614c](https://github.com/DTStack/dt-utils/commit/a88614c6a20d52dd1750fc0599d1c33aa1ed40a3))
197 | * **clip:** 组合发布包 ([bed32df](https://github.com/DTStack/dt-utils/commit/bed32df4f308b5c7d0eced97c5f5903c3ca2aaf5))
198 | * **commit:** 优化commit规范 ([c243c45](https://github.com/DTStack/dt-utils/commit/c243c4577b82636456478c63941477fcb693041b))
199 | * **docs:** 修改docs changelog ([b51c2ea](https://github.com/DTStack/dt-utils/commit/b51c2ea538edea15388d9b23147b123dc2d2d258))
200 | * **docs:** 测试文件名修改 ([becdb58](https://github.com/DTStack/dt-utils/commit/becdb58820f30b937c20c9a7a339ae2a2a673005))
201 | * **docs:** 添加提交校验 ([1f1aeac](https://github.com/DTStack/dt-utils/commit/1f1aeac4ea325c0f9ad814f75e697dc1489c156b))
202 | * **docs:** 补充utils文档说明 ([68fed39](https://github.com/DTStack/dt-utils/commit/68fed39ea2897398503023f3b4d3bd21c18dd127))
203 | * **docs:** 调整文档目录结构 ([f53f5d2](https://github.com/DTStack/dt-utils/commit/f53f5d2d24491acba58ef6af977dae31a4866f26))
204 | * **doc:** 调整目录 ([1017768](https://github.com/DTStack/dt-utils/commit/1017768c860b61e44945d4c87e98f4fb3fc13df9))
205 | * **layout:** update layout api and docs ([bc07cfc](https://github.com/DTStack/dt-utils/commit/bc07cfcd3704443cbd6d1564f1dabefe0627b8b8))
206 | * modify the document ([1118f2e](https://github.com/DTStack/dt-utils/commit/1118f2ee7f5c70bf7f2fd49594711be7b93bc709))
207 | * **package:** update package.json for init ([6e95646](https://github.com/DTStack/dt-utils/commit/6e9564697e6617bc67c1132cc70415a10df8c173))
208 | * **test:** add test utils for jest ([e950d12](https://github.com/DTStack/dt-utils/commit/e950d127330cb3b2ce6a00154b05324558e23b70))
209 | * **优化:** 优化文档目录调整结构 ([548f338](https://github.com/DTStack/dt-utils/commit/548f338e80e910aa249de0e9b3a18d35096a3db2))
210 | * **补充文档:** 添加工具函数文档说明 ([10c95ef](https://github.com/DTStack/dt-utils/commit/10c95efb2a73bed3d83b28312d69ca9aa6b77bbd))
211 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DTStack/dt-utils/cdac32a61744aabfb169a7741e236c40e475f5f0/LICENSE
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # dt-utils | CHANGELOG
2 | 工具库
3 | ## 安装依赖
4 | ```bash
5 | npm install @dtinsight/dt-utils
6 | yarn add @dtinsight/dt-utils
7 | pnpm install @dtinsight/dt-utils
8 | ```
9 | ## 文档地址
10 | - [在线文档](https://dtstack.github.io/dt-utils/)
11 |
12 | ## 使用
13 |
14 | ````js
15 | import { Utils, Cookie, DateTime, Layout, CopyUtils, LocalIndexedDB, LocalDB } from '@dtinsight/dt-utils';
16 | ````
17 |
18 |
19 | # 贡献指南
20 |
21 | 欢迎大家参与贡献,本文将指导你如何贡献一份自己的力量,在提 issue 或者 pull request 之前,请花几分钟来阅读这篇指南。
22 |
23 |
24 | ## 分支管理
25 |
26 | 我们长期维护 master 分支,在创建分支前,请先了解一下分支规范。
27 |
28 | + **master**: 主干分支,用于发包
29 |
30 | + **feat**: 新特性分支
31 |
32 | + **fix**: 常规 bug 修复分支
33 |
34 |
35 | ## 新增功能
36 |
37 | 如需开发功能,请遵循以下流程:
38 |
39 | 1、请 `fork` 本项目,`clone` 自己的仓库,按照上述分支定义从 `master` 分支新建 `feat` 分支进行开发,分支命名用下划线加上版本号,如:`feat_1.x_xxx`
40 |
41 | 2、`feat` 分支开发完毕后请向相应人员提 PR,期望合入 `master` 分支,待相应人员 review 代码后合入
42 |
43 |
44 | ## Bugs
45 |
46 | 我们使用 GitHub issues 来做 bug 追踪。
47 |
48 | 如果你在使用中发现了 bug,请给我们提 issue。如果你想自行修复这个问题,请遵循以下流程:
49 |
50 | 1、请从 **master** 分支中新建 **fix** 分支进行修复,分支命名用下划线加上版本号,如:**hotfix_1.x_xxx**
51 |
52 | 2、相关问题修复完毕后请向相应人员提 PR,期望合入**master** 分支,待相应人员 review 代码后合入
53 |
54 |
55 | ## 第一次贡献
56 |
57 | 如果你还不清楚怎么在 GitHub 上提 Pull Request ,可以阅读下面这篇文章来学习:
58 |
59 | [如何优雅地在 GitHub 上贡献代码](https://segmentfault.com/a/1190000000736629)
60 |
61 | 如果你打算开始处理一个 issue,请先检查一下 issue 下面的留言以确保没有别人正在处理这个 issue。如果当前没有人在处理的话你可以留言告知其他人你将会处理这个 issue,以免别人重复劳动。
62 |
--------------------------------------------------------------------------------
/api-extractor.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
3 | "mainEntryPointFilePath": "./lib/index.d.ts",
4 | "bundledPackages": [],
5 | "apiReport": {
6 | "enabled": false,
7 | "reportFolder": "./lib/"
8 | },
9 | "docModel": {
10 | "enabled": true
11 | },
12 | "dtsRollup": {
13 | "enabled": true,
14 | "untrimmedFilePath": "./lib/index.d.ts"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/commitlint.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: [
3 | './node_modules/vue-cli-plugin-commitlint/lib/lint',
4 | '@commitlint/config-conventional',
5 | ],
6 | };
7 |
--------------------------------------------------------------------------------
/docs/.nojekyll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DTStack/dt-utils/cdac32a61744aabfb169a7741e236c40e475f5f0/docs/.nojekyll
--------------------------------------------------------------------------------
/docs/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # 工具库更新日志
2 |
3 | ## [1.1.2](https://github.com/DTStack/dt-utils/compare/v1.1.0...v1.1.2) (2022-08-16)
4 |
5 |
6 | ### Bug Fixes
7 |
8 | * fix cant download json ([a4fb84e](https://github.com/DTStack/dt-utils/commit/a4fb84e34690c02c09080b251888787ede4f6d5e))
9 |
10 |
11 | ### Features
12 |
13 | * [#64](https://github.com/DTStack/dt-utils/issues/64) localDB add remove function ([d4c80bb](https://github.com/DTStack/dt-utils/commit/d4c80bb06a32569b84554e852018a4b178ff2526))
14 | * getThousandth get '' return '0' ([bde6994](https://github.com/DTStack/dt-utils/commit/bde69946b4a0181b07e9204d197df98b45117175))
15 |
16 |
17 |
18 | # [1.1.0](https://github.com/DTStack/dt-utils/compare/v1.0.9...v1.1.0) (2021-12-09)
19 |
20 |
21 | ### Bug Fixes
22 |
23 | * return '0' when num is null or undefined ([421aaf1](https://github.com/DTStack/dt-utils/commit/421aaf12a27be7f8160019beb35edf60530cffa9))
24 |
25 |
26 | ### Features
27 |
28 | * add three Base64 related methods ([afbe638](https://github.com/DTStack/dt-utils/commit/afbe6386f701a39ef388044c758a929e3f3559af))
29 |
30 |
31 |
32 | ## [1.0.9](https://github.com/DTStack/dt-utils/compare/v1.0.8...v1.0.9) (2021-11-25)
33 |
34 |
35 | ### Features
36 |
37 | * add getThousandth to utils ([a79e797](https://github.com/DTStack/dt-utils/commit/a79e79755f944e5df7d0d7b61ac64803cd169725))
38 |
39 |
40 |
41 | ## [1.0.8](https://github.com/DTStack/dt-utils/compare/v1.0.7...v1.0.8) (2021-10-26)
42 |
43 |
44 | ### Features
45 |
46 | * add getAllCookies ([889e1ec](https://github.com/DTStack/dt-utils/commit/889e1ec9272d206c046f9dd58ef7ee46bb5e3289))
47 |
48 |
49 |
50 | ## [1.0.7](https://github.com/DTStack/dt-utils/compare/v1.0.6...v1.0.7) (2021-10-25)
51 |
52 |
53 | ### Features
54 |
55 | * add download data ([c376a00](https://github.com/DTStack/dt-utils/commit/c376a00eb571006fc3949b47f09d237ab39c08b1))
56 | * add judge status ([228c3ec](https://github.com/DTStack/dt-utils/commit/228c3ec4d371b42849218d6796b7701668b34995))
57 | * add return ([29f3c2a](https://github.com/DTStack/dt-utils/commit/29f3c2a55e8c8452bc4ba5428ac0518e779dfb15))
58 | * change log and contribution guide ([b42740d](https://github.com/DTStack/dt-utils/commit/b42740d48db1460356debba41348f05cb79095b5))
59 | * remove path root changelog ([65ce7ac](https://github.com/DTStack/dt-utils/commit/65ce7ac69831cc73bad40279ef2a45f98d8e5be4))
60 | * update info and ts ([75efdfc](https://github.com/DTStack/dt-utils/commit/75efdfcc4dcca74e13aa5562d78f6f76ec8b8009))
61 | * update let to const ([854d1f0](https://github.com/DTStack/dt-utils/commit/854d1f080213b489769077b36617567499197b7f))
62 | * update lint ([3f9dcc5](https://github.com/DTStack/dt-utils/commit/3f9dcc5d64bccb360882b8ed306498e3e632873a))
63 |
64 |
65 |
66 | ## [1.0.5](https://github.com/DTStack/dt-utils/compare/v1.0.4...v1.0.5) (2021-09-18)
67 |
68 |
69 | ### Bug Fixes
70 |
71 | * eslint ([6a78ddd](https://github.com/DTStack/dt-utils/commit/6a78ddd4ecbe4704596844e02de803187f2e5ee4))
72 | * replace this ([a99d283](https://github.com/DTStack/dt-utils/commit/a99d283433e1030853d62f1ed1061d2b5f99d32c))
73 | * test lint config ([5cd30ca](https://github.com/DTStack/dt-utils/commit/5cd30ca4c031d0b1417ffad701a262b79ec30ea8))
74 |
75 |
76 | ### Features
77 |
78 | * add mergeObj fn ([af13b81](https://github.com/DTStack/dt-utils/commit/af13b8190173a12059bb384faa3c60aebc224612))
79 | * change trim, delete trimlr, add trimAll ([6792dd3](https://github.com/DTStack/dt-utils/commit/6792dd39f98d9e6c61d87b0461c83dcb8677cfeb))
80 | * delete removeAllSpaces, please use trimAll ([bcbfdf8](https://github.com/DTStack/dt-utils/commit/bcbfdf8059046f258b390e1bcc3331f3741c8e85))
81 |
82 |
83 |
84 | ## [1.0.4](https://github.com/DTStack/dt-utils/compare/v1.0.3...v1.0.4) (2021-09-10)
85 |
86 |
87 | ### Bug Fixes
88 |
89 | * export CopyUtils and sort export by document ([95f684b](https://github.com/DTStack/dt-utils/commit/95f684b9ee07597d56eafc11a157ff353461c9b9))
90 |
91 |
92 | ### Features
93 |
94 | * add a time formatting method file ([65c2356](https://github.com/DTStack/dt-utils/commit/65c2356789ed70991d2c295b685c2967f59752e1))
95 | * add formatSecond method ([eab731c](https://github.com/DTStack/dt-utils/commit/eab731c6a499c1ad54b2e75d99fc7b4a17129a0e))
96 | * add isEmpty methods ([2baed54](https://github.com/DTStack/dt-utils/commit/2baed54ddf5e992e183f6bf828e7e389b9cebb19))
97 | * add isObj methods ([02dc937](https://github.com/DTStack/dt-utils/commit/02dc9379e7437418f18a41637c6798ce067163d8))
98 | * add removeEmpty doc ([7bcf98f](https://github.com/DTStack/dt-utils/commit/7bcf98f53f181b7f3a1d03b92b519650a4750cdf))
99 | * add removeEmpty methods ([8c0c56f](https://github.com/DTStack/dt-utils/commit/8c0c56f9ab4a4924a287fc947f871197c4c8a604))
100 | * add removeEmpty unit test ([1b8f1cc](https://github.com/DTStack/dt-utils/commit/1b8f1ccb0b7f0d01042af3d8a5ca01e9380aa498))
101 | * add transformArray methods ([25d616b](https://github.com/DTStack/dt-utils/commit/25d616b96e4e77b6f03f3ba8467e6b761c585a4f))
102 | * add transformArray ts ([808f574](https://github.com/DTStack/dt-utils/commit/808f5745c96096472afd439cb094ccb5525c7d87))
103 | * release sh ([af1a323](https://github.com/DTStack/dt-utils/commit/af1a3238c3dc50b5ed3fb7ee2a0c570d9317d958))
104 | * transformArray define generic parameters ([3a8641c](https://github.com/DTStack/dt-utils/commit/3a8641c8647d8bcdf6f69834b73f513b98ce5723))
105 | * update cookie methods ([062d17c](https://github.com/DTStack/dt-utils/commit/062d17c2d14d77e8af38067c7d7c34a372960310))
106 |
107 |
108 |
109 | ## [1.0.3](https://github.com/DTStack/dt-utils/compare/v1.0.2...v1.0.3) (2021-04-06)
110 |
111 |
112 | ### Features
113 |
114 | * **utils:** add utils and modify docs ([7b951b2](https://github.com/DTStack/dt-utils/commit/7b951b2c87f7e4a2edac7c0da3ddd0ec46bdc0c6))
115 | * **utils:** modify the document directory ([494c2e8](https://github.com/DTStack/dt-utils/commit/494c2e876cfd5dcd16e31dff4147a736213ea054))
116 |
117 |
118 |
119 | ## [1.0.2](https://github.com/DTStack/dt-utils/compare/v1.0.1...v1.0.2) (2021-04-01)
120 |
121 |
122 |
123 | ## [1.0.1](https://github.com/DTStack/dt-utils/compare/v1.0.0...v1.0.1) (2021-01-20)
124 |
125 |
126 | ### Features
127 |
128 | * **docs:** 补充介绍文档 ([3b2ba81](https://github.com/DTStack/dt-utils/commit/3b2ba81ec99969fcc3fa9062d2efebdc1a087a14))
129 | * **package:** update package dev dependencies ([3cf5655](https://github.com/DTStack/dt-utils/commit/3cf56550b07b69a84ee4409b55a225f1ba9b724f))
130 | * **publish:** update name ([a12a55e](https://github.com/DTStack/dt-utils/commit/a12a55ebba599e8d3f6c7d7c308e4d3ed9e5d518))
131 | * **test:** add test for utils ([931244c](https://github.com/DTStack/dt-utils/commit/931244cb458134d9e0aa843c06a1ceb29fb87686))
132 |
133 |
134 |
135 | # [1.0.0](https://github.com/DTStack/dt-utils/compare/c243c4577b82636456478c63941477fcb693041b...v1.0.0) (2020-07-20)
136 |
137 |
138 | ### Features
139 |
140 | * **补充文档:** 添加工具函数文档说明 ([10c95ef](https://github.com/DTStack/dt-utils/commit/10c95efb2a73bed3d83b28312d69ca9aa6b77bbd))
141 | * **优化:** 优化文档目录调整结构 ([548f338](https://github.com/DTStack/dt-utils/commit/548f338e80e910aa249de0e9b3a18d35096a3db2))
142 | * add to complete ([1b438f8](https://github.com/DTStack/dt-utils/commit/1b438f8d7d7c8366ac1572dc63d4401bf14d8d8e))
143 | * **change:** 更新同步changelog ([a88614c](https://github.com/DTStack/dt-utils/commit/a88614c6a20d52dd1750fc0599d1c33aa1ed40a3))
144 | * **clip:** 组合发布包 ([bed32df](https://github.com/DTStack/dt-utils/commit/bed32df4f308b5c7d0eced97c5f5903c3ca2aaf5))
145 | * **commit:** 优化commit规范 ([c243c45](https://github.com/DTStack/dt-utils/commit/c243c4577b82636456478c63941477fcb693041b))
146 | * **doc:** 调整目录 ([1017768](https://github.com/DTStack/dt-utils/commit/1017768c860b61e44945d4c87e98f4fb3fc13df9))
147 | * **docs:** 补充utils文档说明 ([68fed39](https://github.com/DTStack/dt-utils/commit/68fed39ea2897398503023f3b4d3bd21c18dd127))
148 | * **docs:** 测试文件名修改 ([becdb58](https://github.com/DTStack/dt-utils/commit/becdb58820f30b937c20c9a7a339ae2a2a673005))
149 | * **docs:** 调整文档目录结构 ([f53f5d2](https://github.com/DTStack/dt-utils/commit/f53f5d2d24491acba58ef6af977dae31a4866f26))
150 | * **docs:** 添加提交校验 ([1f1aeac](https://github.com/DTStack/dt-utils/commit/1f1aeac4ea325c0f9ad814f75e697dc1489c156b))
151 | * **docs:** 修改docs changelog ([b51c2ea](https://github.com/DTStack/dt-utils/commit/b51c2ea538edea15388d9b23147b123dc2d2d258))
152 | * **layout:** update layout api and docs ([bc07cfc](https://github.com/DTStack/dt-utils/commit/bc07cfcd3704443cbd6d1564f1dabefe0627b8b8))
153 | * modify the document ([1118f2e](https://github.com/DTStack/dt-utils/commit/1118f2ee7f5c70bf7f2fd49594711be7b93bc709))
154 | * **package:** update package.json for init ([6e95646](https://github.com/DTStack/dt-utils/commit/6e9564697e6617bc67c1132cc70415a10df8c173))
155 | * **test:** add test utils for jest ([e950d12](https://github.com/DTStack/dt-utils/commit/e950d127330cb3b2ce6a00154b05324558e23b70))
156 |
157 |
158 |
159 |
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
1 | # @dtinsight/dt-utils
2 | 袋鼠云实用工具库,日常开发场景中常用功能函数分装、存储相关功能函数分装,具有统一性、模块化等特点
3 |
--------------------------------------------------------------------------------
/docs/_sidebar.md:
--------------------------------------------------------------------------------
1 |
2 | - [快速开始](quickstart.md)
3 | - [Utils](utils.md)
4 | - [Cookie](cookie.md)
5 | - [DateTime](dateTime.md)
6 | - [Layout](layout.md)
7 | - [CopyUtils](copy.md)
8 | - [IndexedDB](idb.md)
9 | - [LocalDB](ldb.md)
10 | - [贡献指南](contribution-guide.md)
11 | - [更新日志](CHANGELOG.md)
12 |
--------------------------------------------------------------------------------
/docs/contribution-guide.md:
--------------------------------------------------------------------------------
1 | # 贡献指南
2 |
3 | 欢迎大家参与贡献,本文将指导你如何贡献一份自己的力量,在提 issue 或者 pull request 之前,请花几分钟来阅读这篇指南。
4 |
5 |
6 | ## 分支管理
7 |
8 | 我们长期维护 master, release 分支,在创建分支前,请先了解一下分支规范。
9 |
10 | + **master**: 主干分支,用于发包
11 |
12 | + **release**: 预发包分支
13 |
14 | + **feat**: 新特性分支
15 |
16 | + **fix**: 常规 bug 修复分支
17 |
18 |
19 | ## 新增功能
20 |
21 | 如需开发功能,请遵循以下流程:
22 |
23 | 1、请 `fork` 本项目,`clone` 自己的仓库,按照上述分支定义从 `master` 分支新建 `feat` 分支进行开发,分支命名用下划线加上版本号、功能名,如:`feat_1.x_xxx`
24 |
25 | 2、`feat` 分支开发完毕后,本地执行 `yarn lint` 命令,再执行 `yarn test` 命令,均通过后向相应人员提 PR,期望合入 `release` 分支,待相应人员 review 代码后合入
26 |
27 |
28 | ## Bugs
29 |
30 | 我们使用 GitHub issues 来做 bug 追踪。
31 |
32 | 如果你在使用中发现了 bug,请给我们提 issue。如果你想自行修复这个问题,请遵循以下流程:
33 |
34 | 1、请从 **master** 分支中新建 **fix** 分支进行修复,分支命名用下划线加上版本号,如:**hotfix_1.x_xxx**
35 |
36 | 2、相关问题修复完毕后请向相应人员提 PR,期望合入**release** 分支,待相应人员 review 代码后合入
37 |
38 |
39 | ## 第一次贡献
40 |
41 | 如果你还不清楚怎么在 GitHub 上提 Pull Request ,可以阅读下面这篇文章来学习:
42 |
43 | [如何优雅地在 GitHub 上贡献代码](https://segmentfault.com/a/1190000000736629)
44 |
45 | 如果你打算开始处理一个 issue,请先检查一下 issue 下面的留言以确保没有别人正在处理这个 issue。如果当前没有人在处理的话你可以留言告知其他人你将会处理这个 issue,以免别人重复劳动。
46 |
--------------------------------------------------------------------------------
/docs/cookie.md:
--------------------------------------------------------------------------------
1 | # 操作Cookie
2 | ````js
3 | import { Cookie } from '@dtinsight/dt-utils'
4 | ````
5 |
6 | ## getCookie
7 | 原生 JavaScript 获取 cookie 值,根据传入参数制定
8 | ```js
9 | Cookie.getCookie(name: string)
10 | ```
11 |
12 | ## getAllCookies
13 | 获取全部 cookie
14 | ```js
15 | Cookie.getAllCookies()
16 | ```
17 |
18 | ## deleteCookie
19 | 删除指定的Cookie值
20 | ```js
21 | Cookie.deleteCookie(name: string, domain?: string, path?: string)
22 | ```
23 |
24 | ## deleteAllCookies
25 | 删除所有Cookie值
26 | ```js
27 | Cookie.deleteAllCookies(domain: string, path: string)
28 | ```
29 |
30 | ## setCookie
31 | 创建Cookie值
32 | ```js
33 | Cookie.setCookie(name: string, value: string | number | object | boolean, days?: number)
34 | ```
35 |
--------------------------------------------------------------------------------
/docs/copy.md:
--------------------------------------------------------------------------------
1 | # Copy工具类
2 | ````js
3 | import { CopyUtils } from '@dtinsight/dt-utils';
4 |
5 | ````
6 | ### 使用
7 | ````js
8 | const instance = new CopyUtils();
9 | instance.copy(value, callback);
10 | ````
11 |
12 |
--------------------------------------------------------------------------------
/docs/dateTime.md:
--------------------------------------------------------------------------------
1 | # DateTime
2 |
3 | 导入
4 |
5 | ```js
6 | import { DateTime } from "@dtinsight/dt-utils";
7 | ```
8 |
9 | ## formatDateTime
10 |
11 | 返回 `YYYY-MM-DD HH:mm:ss` 格式化的字符串
12 |
13 | ```js
14 | DateTime.formatDateTime(1627457470000);
15 | ```
16 |
17 | ## formatDate
18 |
19 | 返回 `YYYY-MM-DD` 格式化的字符串
20 |
21 | ```js
22 | DateTime.formatDate(1627457470000);
23 | ```
24 |
25 | ## formatDateHours
26 |
27 | 返回 `YYYY-MM-DD HH:mm` 格式化的字符串
28 |
29 | ```js
30 | DateTime.formatDateHours(1627457470000);
31 | ```
32 |
33 | ## formatDayHours
34 |
35 | 返回 `MM-DD HH:mm` 格式化的字符串
36 |
37 | ```js
38 | DateTime.formatDayHours(1627457470000);
39 | ```
40 |
41 | ## formatHours
42 |
43 | 返回 `HH:mm` 格式化的字符串
44 |
45 | ```js
46 | DateTime.formatHours(1627457470000);
47 | ```
48 |
49 | ## formatMinute
50 |
51 | 返回 `HH:mm:ss` 格式化的字符串
52 |
53 | ```js
54 | DateTime.formatMinute(1627457470000);
55 | ```
56 |
57 | ## formatSecond
58 |
59 | 把秒数转换成 3h5m11s 的格式
60 |
61 | ```js
62 | DateTime.formatSecond(11111); // 3h5m11s
63 | DateTime.formatSecond(111); // 1m51s
64 | DateTime.formatSecond(11); // 11s
65 | ```
--------------------------------------------------------------------------------
/docs/idb.md:
--------------------------------------------------------------------------------
1 | # indexedDb
2 |
3 | ````js
4 | import { LocalIndexedDB } from '@dtinsight/dt-utils'
5 | ````
6 | **基本概念**
7 | IndexedDB是实现数据持久存储在用户浏览器中的方法。因为它使您可以创建具有丰富查询功能的Web应用程序,而不管网络是否可用,所以这些应用程序可以联机和脱机运行。LocalIndexedDB对于存储大量数据的应用程序(例如,借阅库中的DVD目录)和不需要持久的Internet连接即可工作的应用程序(例如,邮件客户端,任务列表和记事本)
8 |
9 | ### 基本模式
10 | > LocalIndexedDB方法实现的基本模式分为5点
11 | + 打开一个数据库。
12 | + 在数据库中创建一个对象存储。
13 | + 启动一个事务并请求执行一些数据库操作,例如添加或检索数据。
14 | + 通过侦听正确的DOM事件来等待操作完成。
15 | + 对结果做一些事情(可以在请求对象上找到)。
16 |
17 | ## open
18 | 该方法实现打开一个数据库,返回一个promise对象
19 |
20 | 我们开始整个过程是这样的:
21 | ### 打开数据库
22 | ```js
23 | const request = LocalIndexedDB.open(数据库名, 数据库版本);
24 | ```
25 | 该open()函数的调用将返回一个IDBOpenDBRequest对象,open函数的结果是一个实例 IDBDatabase
26 | ### 生成处理程序
27 | 该对象具有您作为事件处理的结果(成功)或错误值。IndexedDB中的大多数其他异步函数执行相同的操作-返回IDBRequest 带有结果或错误的对象,然后我们处理一下错误。
28 | ```js
29 | request.onsuccess = function(event) {
30 | // Do something with request.result!
31 | };
32 | request.onupgradeneeded = function(event) {
33 | // 当创建新数据库或增加现有数据库的版本号
34 | }
35 | request.onblocked = function(event) {
36 | // 当open()使用比数据库的实际版本更高的版本进行调用时,所有其他打开的数据库必须先明确确认该请求,然后才能开始对数据库进行更改
37 | };
38 | request.onerror = function(event) {
39 | // Do something with request.errorCode!
40 | };
41 | ```
42 | ## set
43 | set通过键值添加数据内容
44 | ```js
45 | set (key: string, value: any)
46 | ```
47 | ## get
48 | get通过键值得到数据内容
49 | ```js
50 | get (key: string)
51 | ```
52 | ## add
53 | add方法添加数据库值的键
54 | ```js
55 | add (value: any, key?: string)
56 | ```
57 | ## delete
58 | delete通过键值删除数据内容
59 | ```js
60 | delete (key: string)
61 | ```
62 | ## clear
63 | clear清除所有内容
64 | ```js
65 | clear()
66 | ```
67 | ## getObjectStore
68 | > 定义事务模式
69 |
70 | 要读取现有对象存储的记录,事务可以处于readonly或readwrite模式。要更改现有的对象库,事务必须处于readwrite模式。您使用打开此类交易IDBDatabase.transaction。该方法接受两个参数:(storeNames范围,定义为要访问的对象存储的数组)和事务的mode(readonly或readwrite)。该方法返回一个包含该IDBIndex.objectStore方法的事务对象,可用于访问对象存储。默认情况下,如果未指定任何模式,则事务将以readonly模式打开。
71 |
72 |
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | dt-utils
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
50 |
55 |
56 |
57 |
58 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/docs/layout.md:
--------------------------------------------------------------------------------
1 | # 布局相关
2 | 导入
3 | ````js
4 | import { Layout } from '@dtinsight/dt-utils';
5 | ````
6 | ## pageWidth
7 | 获取页面宽度
8 | ```js
9 | Layout.pageWidth()
10 | ```
11 | ## pageHeight
12 | 获取页面高度
13 | ```js
14 | Layout.pageHeight()
15 | ```
--------------------------------------------------------------------------------
/docs/ldb.md:
--------------------------------------------------------------------------------
1 | # LocalDB
2 |
3 | 导入
4 | ````js
5 | import { LocalDB } from '@dtinsight/dt-utils';
6 | ````
7 | 功能
8 |
9 | 封装 localStorage,增加对 JSON 对象的转换,方法声明 LocalDB 对象定义相关方法
10 |
11 | ## set
12 | 按 key 存贮数据 value 到 localStorage
13 |
14 | ### 参数
15 | (key, value)
16 | 存贮数据的唯一标识,所要存贮的数据
17 | ### 返回值
18 | 无
19 | ### eg:
20 | ```js
21 | set(key: string | number, value: any) {
22 | if (value === null || value === undefined) {
23 | delete window.localStorage[key];
24 | } else {
25 | const val = typeof value === 'object' ? JSON.stringify(value) : value;
26 | window.localStorage[key] = val;
27 | }
28 | }
29 | ```
30 |
31 | ## get
32 | 通过 key 从 localStorage 获取数据
33 |
34 | ### 参数
35 | key:获取数据的唯一标识
36 | ### 返回值
37 | 返回空,字符串或者对象
38 |
39 | ### eg:
40 | ```js
41 | get(key: string | number) {
42 | const str = window.localStorage[key] || '';
43 | try {
44 | return Utils.isJSONStr(str) ? JSON.parse(str) : str;
45 | } catch (error) {
46 | return str;
47 | }
48 | }
49 | ```
50 |
51 | ## remove
52 | 通过 key 从 localStorage 删除数据
53 |
54 | ### 参数
55 | key:删除数据的唯一标识
56 |
57 | ## clear
58 | 清空 localStorage
59 | ### 参数
60 | 无
61 | ### 返回值
62 | 无
63 | ````js
64 | LocalDB.clear()
65 | ````
66 |
--------------------------------------------------------------------------------
/docs/quickstart.md:
--------------------------------------------------------------------------------
1 | # 快速开始
2 |
3 | ## 安装包
4 | ```bash
5 | npm install @dtinsight/dt-utils
6 | yarn add @dtinsight/dt-utils
7 | ```
8 | ## 使用
9 |
10 | ````js
11 | import { Utils,Cookie,Layout,CopyUtils,LocalIndexedDB,LocalDB } from '@dtinsight/dt-utils';
12 | ````
13 |
14 | ## Package Managers
15 | JavaScript @dtinsight/dt-utils supports npm and yarn under the name @dtinsight/dt-utils. Module Loaders
16 |
17 | ## Module Loaders
18 | JavaScript @dtinsight/dt-utils can also be loaded as an AMD, ES6 module.
19 |
--------------------------------------------------------------------------------
/docs/sw.js:
--------------------------------------------------------------------------------
1 | /* ===========================================================
2 | * docsify sw.js
3 | * ===========================================================
4 | * Copyright 2016 @huxpro
5 | * Licensed under Apache 2.0
6 | * Register service worker.
7 | * ========================================================== */
8 |
9 | const RUNTIME = 'docsify';
10 | const HOSTNAME_WHITELIST = [
11 | self.location.hostname,
12 | 'fonts.gstatic.com',
13 | 'fonts.googleapis.com',
14 | 'cdn.jsdelivr.net',
15 | ];
16 |
17 | // The Util Function to hack URLs of intercepted requests
18 | const getFixedUrl = (req) => {
19 | const now = Date.now();
20 | const url = new URL(req.url);
21 |
22 | // 1. fixed http URL
23 | // Just keep syncing with location.protocol
24 | // fetch(httpURL) belongs to active mixed content.
25 | // And fetch(httpRequest) is not supported yet.
26 | url.protocol = self.location.protocol;
27 |
28 | // 2. add query for caching-busting.
29 | // Github Pages served with Cache-Control: max-age=600
30 | // max-age on mutable content is error-prone, with SW life of bugs can even extend.
31 | // Until cache mode of Fetch API landed, we have to workaround cache-busting with query string.
32 | // Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190
33 | if (url.hostname === self.location.hostname) {
34 | url.search += (url.search ? '&' : '?') + 'cache-bust=' + now;
35 | }
36 | return url.href;
37 | };
38 |
39 | /**
40 | * @Lifecycle Activate
41 | * New one activated when old isnt being used.
42 | *
43 | * waitUntil(): activating ====> activated
44 | */
45 | self.addEventListener('activate', (event) => {
46 | event.waitUntil(self.clients.claim());
47 | });
48 |
49 | /**
50 | * @Functional Fetch
51 | * All network requests are being intercepted here.
52 | *
53 | * void respondWith(Promise r)
54 | */
55 | self.addEventListener('fetch', (event) => {
56 | // Skip some of cross-origin requests, like those for Google Analytics.
57 | if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) {
58 | // Stale-while-revalidate
59 | // similar to HTTP's stale-while-revalidate: https://www.mnot.net/blog/2007/12/12/stale
60 | // Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1
61 | const cached = caches.match(event.request);
62 | const fixedUrl = getFixedUrl(event.request);
63 | const fetched = fetch(fixedUrl, { cache: 'no-store' });
64 | const fetchedCopy = fetched.then((resp) => resp.clone());
65 |
66 | // Call respondWith() with whatever we get first.
67 | // If the fetch fails (e.g disconnected), wait for the cache.
68 | // If there’s nothing in cache, wait for the fetch.
69 | // If neither yields a response, return offline pages.
70 | event.respondWith(
71 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
72 | Promise.race([fetched.catch((_) => cached), cached])
73 | .then((resp) => resp || fetched)
74 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
75 | .catch((_) => {
76 | /* eat any errors */
77 | })
78 | );
79 |
80 | // Update the cache with the version we fetched (only for ok status)
81 | event.waitUntil(
82 | Promise.all([fetchedCopy, caches.open(RUNTIME)])
83 | .then(([response, cache]) => response.ok && cache.put(event.request, response))
84 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
85 | .catch((_) => {
86 | /* eat any errors */
87 | })
88 | );
89 | }
90 | });
91 |
--------------------------------------------------------------------------------
/docs/utils.md:
--------------------------------------------------------------------------------
1 | # Utils
2 | 导入
3 | ````js
4 | import { Utils } from '@dtinsight/dt-utils';
5 | ````
6 |
7 | ## browserCheck
8 | 浏览器类型和版本检测
9 |
10 | `true`表示通过兼容性检测,`false`表示不通过兼容性检测
11 |
12 | ```js
13 | Utils.browserCheck(); // boolean
14 | ```
15 | ## checkExist
16 | 检查属性是否存在
17 | ```js
18 | Utils.checkExist()
19 | ```
20 | 例如:
21 | ```js
22 | Utils.checkExist('') // false
23 | Utils.checkExist(null) // false
24 | Utils.checkExist(undefined) // false
25 | ```
26 | ## isMacOs
27 | 判断设备是否是 Mac
28 | ```js
29 | Utils.isMacOs(); //boolean
30 | ```
31 | ## isWindows
32 | 判断设备是否是 Windows
33 | ```js
34 | Utils.isWindows(); //boolean
35 | ```
36 | ## isMobileDevice
37 | 判断设备是否是移动设备
38 | ```js
39 | Utils.isMobileDevice(); //boolean
40 | ```
41 | ## isPhoneNumber
42 | 判断是否是手机号
43 | ````js
44 |
45 | Utils.isPhoneNumber('15688723782333') // false
46 |
47 | ````
48 | ## isJSONStr
49 | 判断是否是 JSON string
50 | ```js
51 | Utils.isJSONStr (str: string): boolean
52 | ```
53 | 例如:
54 | ```js
55 | Utils.isJSONStr('name') // false
56 | ```
57 | ## isFunction
58 | 判断是否是函数
59 | ````js
60 |
61 | Utils.isFunction([]) // false
62 | Utils.isFunction(()=>{}) // true
63 |
64 | ````
65 | ## isEqualArr
66 | 简单地判断数组是否相等
67 | ```js
68 | Utils.isEqualArr (arr1: any[], arr2: any[]): boolean
69 | ```
70 | 例如:
71 | ```js
72 | Utils.isEqualArr([1,2,3], [1,2,3]) // true
73 | Utils.isEqualArr([1,2,3],[1,3,2]) // true
74 | ```
75 |
76 | ## isEqual
77 | 简单地判断对象是否相等
78 | ```js
79 | Utils.isEqual (a: any, b: any): boolean
80 | ```
81 | 例如:
82 | ```js
83 | Utils.isEqual({name:'sichen'},{name:'sichen'}) // true
84 | ```
85 | ## getParameterByName
86 | 根据参数名获取 URL 数据
87 |
88 | ```js
89 | /**
90 | * 获取图片的Base64格式
91 | * @param {[type]} name [description]
92 | * @param {[type]} url [description] 可选参数,默认当前域
93 | */
94 | Utils.getParameterByName(); //boolean
95 | ```
96 |
97 | 例如:
98 | ```js
99 | Utils.getParameterByName('name','http://baidu.com?name='1'); // 1
100 | Utils.getParameterByName('name'); // 1
101 | ```
102 | ## getBase64
103 | 获取图片的 Base64 格式
104 |
105 | ```js
106 | /**
107 | * 获取图片的Base64格式
108 | * @param {[type]} img [description]
109 | * @param {Function} callback [description]
110 | */
111 | Utils.getBase64(img,callback);
112 | ```
113 | ## getCssText
114 | 样式对象转 css style 风格转字符串
115 |
116 | ````js
117 | /**
118 | * @param {Record} [object={}]
119 | * @returns String
120 | */
121 | Utils.getCssText(object: Record = {});
122 | ````
123 | 例如:
124 |
125 | ````js
126 | let styles = {
127 | height:'100px',
128 | width:'100px',
129 | color:'red'
130 | }
131 | Utils.getCssText(styles); // 'height:100px;width:100px;color:red;'
132 | ````
133 | ## generateAKey
134 | 生成一个随机 key
135 |
136 | 例如:
137 | ```js
138 | Utils.generateAKey(): string // "1594806665598655835"
139 | ```
140 |
141 |
142 | ## getRandomStr
143 | 随机生成一串 len 位同时包含数字、大小写字母的字符串
144 | ```js
145 | Utils.getRandomStr (len: number): string
146 | ```
147 | 例如:
148 | ```js
149 | Utils.getRandomStr(10) // "5vK6vT6sL8"
150 | ```
151 | ## getStrlen
152 | 计算字符串长度(英文占 1 个字符,中文汉字占 2 个字符)
153 |
154 | ```` js
155 | /**
156 | *
157 | * 计算字符串长度(英文占1个字符,中文汉字占2个字符)
158 | * @param {*} str
159 | * @returns number
160 | */
161 | Utils.getStrlen('上岁数1232');//10
162 |
163 | ````
164 | ## trim
165 | 去除前后空格
166 | ```js
167 | /**
168 | * @returns string
169 | */
170 | Utils.trim (str: string)
171 | ```
172 | 例如:
173 | ```js
174 | Utils.trim(' 12 3 1 23 ') // "12 3 1 23"
175 | ```
176 | ## trimAll
177 | 去除所有空格
178 | ```js
179 | /**
180 | * @returns string
181 | */
182 | Utils.trimAll (str: string)
183 | ```
184 | 例如:
185 | ```js
186 | Utils.trimAll(' 12 3 1 23 ') // "123123"
187 | ```
188 |
189 | ## getThousandth
190 | 转换为千分位
191 | ```js
192 | Utils.getThousandth (str: number | string): string
193 | ```
194 | 例如:
195 | ```js
196 | Utils.getThousandth('') // "0"
197 | Utils.getThousandth('1234567') // "1,234,567"
198 | Utils.getThousandth(1234.56789) // "1,234.56789"
199 | ```
200 |
201 | ## textOverflowExchange
202 | 文字溢出转换
203 | ```js
204 | Utils.textOverflowExchange (str: string, num: number): string
205 | ```
206 | 例如:
207 | ```js
208 | Utils.textOverflowExchange('my name is sichen', 10) // "my name is..."
209 | ```
210 |
211 | ## percent
212 | 百分比转换
213 |
214 | ````js
215 | /**
216 | * @param {[type]} num [description]
217 | * @param {[type]} precision [description]
218 | */
219 | Utils.percent(num: number, precision?: number);
220 | ````
221 | 例如:
222 |
223 | ````js
224 | Utils.percent(1); // 100%
225 | Utils.percent(0.5); // 50%
226 | Utils.percent(0.54); // 54%
227 | Utils.percent(0.54321); // 54.32%
228 | Utils.percent(0.54321,1); // 54.3%
229 | Utils.percent(0.54321,2); // 54.32%
230 | Utils.percent(0.54321,3); // 54.321%
231 | ````
232 |
233 | ## convertBytes
234 | 转换 Byte 转换为小于 1024 值最大单位
235 | ```js
236 | Utils.convertBytes (value: number): string
237 | ```
238 | 例如:
239 | ```js
240 | Utils.convertBytes(102) // 102 B
241 | Utils.convertBytes(1024) // 1 KB
242 | Utils.convertBytes(1024*1024) // 1 MB
243 | ```
244 | ## jsonFormat
245 | Json 格式化
246 |
247 | ```js
248 | // 格式化内容: text
249 | // 格式化占位符: space
250 | Utils.jsonFormat (text: string, space?: number)
251 | ```
252 |
253 | ## sortByCompareFunctions
254 | 多函数排序,匹配到 0 为止
255 | ```js
256 | Utils.sortByCompareFunctions (arr: any[], ...compareFunctions: any[])
257 | ```
258 |
259 | ## exchangeOrder
260 | 转换排序字段
261 | ```js
262 | Utils.exchangeOrder (order: string): string {
263 | switch (order) {
264 | case 'ascend':
265 | return 'asc';
266 | case 'descend':
267 | return 'desc';
268 | default:
269 | return undefined;
270 | }
271 | }
272 | ```
273 | 例如:
274 | ```js
275 | Utils.exchangeOrder('ascend') // 'asc'
276 | Utils.exchangeOrder('descend') // 'desc'
277 | Utils.exchangeOrder('abc') // undefined
278 | ```
279 |
280 |
281 | ## shouldRender
282 | ```js
283 | Utils.shouldRender (targetComponent: any):boolean
284 | ```
285 | ## transformArray
286 | 一维数组根据指定位数转换成二维数组
287 | ```js
288 | Utils.transformArray (arr: T[], num: number): T[][]
289 | ```
290 | 例如:
291 | ```js
292 | Utils.transformArray(['1', '2', '3', '4'], 2) // [['1', '2'], ['3', '4']]
293 | ```
294 | ## isEmpty
295 | 判空
296 | ```js
297 | Utils.isEmpty (data?: any): boolean
298 | ```
299 | 例如:
300 | ```js
301 | Utils.isEmpty('') // true
302 | Utils.isEmpty(null) // true
303 | Utils.isEmpty(undefined) // true
304 | Utils.isEmpty([]) // true
305 | Utils.isEmpty({}) // true
306 | Utils.isEmpty('123') // false
307 | ```
308 | ## isObj
309 | 判断是否为对象
310 | ```js
311 | Utils.isObj (obj?: any): boolean
312 | ```
313 | 例如:
314 | ```js
315 | Utils.isObj({}) // true
316 | Utils.isObj('123') // false
317 | ```
318 | ## removeEmpty
319 | 剔除对象中 value 为'',null,undefined,[]的元素
320 | ```js
321 | Utils.removeEmpty (obj?: any): any
322 | ```
323 | 例如:
324 | ```js
325 | Utils.removeEmpty({ a: 'test', b: undefined, c: { d: undefined } }) // { a: 'test', c: {} }
326 | ```
327 |
328 | ## mergeDeep
329 |
330 | 将两个对象进行深拷贝合并,对象内的同名对象也进行一次深拷贝合并
331 | 如果 obj2 存在 _isMergeAtom 属性,则直接使用 obj2,不再与 obj1 合并
332 |
333 | ```js
334 | Utils.mergeDeep(
335 | { a: 123, b: 321, innerObj: { a: 123, c: 456 } },
336 | { a: 'cover', c: 456, innerObj: { a: 'cover', b: 321 } }
337 | )
338 | // { a: 'cover', b: 321, c: 456, innerObj: { a: 'cover', b: 321, c: 456 } }
339 | ```
340 | ## downloadData
341 | 处理下载文件
342 | 如果不传文件名fileName,会从`response`的`Content-disposition`读取
343 |
344 | ```js
345 | const headers = new Header();
346 | headers.set('X-Project-ID', 111);
347 | downLoadData({
348 | url: 'downloadUrl',
349 | payload: { a: 1, b: 2 },
350 | headers,
351 | fileName: 'test.pdf',
352 | successCallback: () => message.info('下载成功'),
353 | errorCallback: () => message.error('下载失败'),
354 | finallyCallback: () => this.setState({ visible: false })
355 | })
356 | ```
357 |
358 | ## isUtf8
359 | 判断字符串格式是否为 utf-8
360 |
361 | `true`表示格式为 utf-8,`false`表示格式为非 utf-8 格式
362 |
363 | ```js
364 | Utils.isUtf8('test'); // boolean
365 | ```
366 |
367 | ## utf16to8
368 | 结合上一方法使用,先判断字符串格式是否为 utf-8,不是的话,将其转为 utf-8
369 |
370 | 返回值为 utf-8 格式的字符串
371 |
372 | ```js
373 | Utils.utf16to8('test'); // string
374 | ```
375 |
376 | ## base64Encode
377 | 结合上一方法使用,先判断字符串格式是否为 utf-8,不是的话,将其转为 utf-8,然后将其进行 base64 加密
378 |
379 | 返回值为 utf-8 格式的字符串
380 |
381 | ```js
382 | Utils.base64Encode('test'); // string
383 | ```
384 |
385 | ## generateFullUrlPath
386 | 传入地址和 url 参数生成完整的 url 地址
387 | ```js
388 | Utils.generateFullUrlPath('/test/getUrlPathname', { a: 1, b: 2 }); // /test/getUrlPathname?a=1&b=2
389 | Utils.generateFullUrlPath('/test/getUrlPathname', { a: 1, b: undefined }); // /test/getUrlPathname?a=1&b=undefined
390 | Utils.generateFullUrlPath('/test/getUrlPathname', { a: 1, b: null }); // /test/getUrlPathname?a=1&b=null
391 | Utils.generateFullUrlPath('/test/getUrlPathname', { a: 1, b: '' }); // /test/getUrlPathname?a=1&b=
392 | ```
393 |
394 | ## getQueryParameters
395 | 根据传入的 search,返回对象
396 | ```js
397 | Utils.getQueryParameters('?a=1&b=2'); // { a: '1', b: '2' }
398 | Utils.getQueryParameters('?a=1&b=undefined'); // { a: '1', b: 'undefined' }
399 | Utils.getQueryParameters('?a=1&b=null'); // { a: '1', b: 'null' }
400 | ```
401 |
--------------------------------------------------------------------------------
/gulpfile.ts:
--------------------------------------------------------------------------------
1 | import { series } from 'gulp';
2 | import path from 'path';
3 | import fse from 'fs-extra';
4 | import chalk from 'chalk';
5 | import { rollup } from 'rollup';
6 | import { Extractor, ExtractorConfig, ExtractorResult } from '@microsoft/api-extractor';
7 | import conventionalChangelog from 'conventional-changelog';
8 | import rollupConfig from './rollup.config';
9 |
10 | interface TaskFunc {
11 | (cb: Function): void;
12 | }
13 |
14 | const log = {
15 | progress: (text: string) => {
16 | console.log(chalk.green(text));
17 | },
18 | error: (text: string) => {
19 | console.log(chalk.red(text));
20 | },
21 | };
22 |
23 | const paths = {
24 | root: path.join(__dirname, '/'),
25 | lib: path.join(__dirname, '/lib'),
26 | docs: path.join(__dirname, '/docs'),
27 | };
28 |
29 | // 删除 lib 文件
30 | const clearLibFile: TaskFunc = async (cb) => {
31 | fse.removeSync(paths.lib);
32 | log.progress('Deleted lib file');
33 | cb();
34 | };
35 |
36 | // rollup 打包
37 | const buildByRollup: TaskFunc = async (cb) => {
38 | const inputOptions = {
39 | input: rollupConfig.input,
40 | external: rollupConfig.external,
41 | plugins: rollupConfig.plugins,
42 | };
43 | const outOptions = rollupConfig.output;
44 | const bundle = await rollup(inputOptions);
45 |
46 | // 写入需要遍历输出配置
47 | if (Array.isArray(outOptions)) {
48 | outOptions.forEach(async (outOption) => {
49 | await bundle.write(outOption);
50 | });
51 | cb();
52 | log.progress('Rollup built successfully');
53 | }
54 | };
55 |
56 | // api-extractor 整理 .d.ts 文件
57 | const apiExtractorGenerate: TaskFunc = async (cb) => {
58 | const apiExtractorJsonPath: string = path.join(__dirname, './api-extractor.json');
59 | // 加载并解析 api-extractor.json 文件
60 | const extractorConfig: ExtractorConfig = await ExtractorConfig.loadFileAndPrepare(
61 | apiExtractorJsonPath
62 | );
63 | // 判断是否存在 index.d.ts 文件,这里必须异步先访问一边,不然后面找不到会报错
64 | const isExist: boolean = await fse.pathExists(extractorConfig.mainEntryPointFilePath);
65 |
66 | if (!isExist) {
67 | log.error('API Extractor not find index.d.ts');
68 | return;
69 | }
70 |
71 | // 调用 API
72 | const extractorResult: ExtractorResult = await Extractor.invoke(extractorConfig, {
73 | localBuild: true,
74 | // 在输出中显示信息
75 | showVerboseMessages: true,
76 | });
77 |
78 | if (extractorResult.succeeded) {
79 | // 删除多余的 .d.ts 文件
80 | const libFiles: string[] = await fse.readdir(paths.lib);
81 | libFiles.forEach(async (file) => {
82 | if (file.endsWith('.d.ts') && !file.includes('index')) {
83 | await fse.remove(path.join(paths.lib, file));
84 | }
85 | });
86 | log.progress('API Extractor completed successfully');
87 | cb();
88 | } else {
89 | log.error(
90 | `API Extractor completed with ${extractorResult.errorCount} errors` +
91 | ` and ${extractorResult.warningCount} warnings`
92 | );
93 | }
94 | };
95 |
96 | const complete: TaskFunc = (cb) => {
97 | log.progress('---- end ----');
98 | cb();
99 | };
100 |
101 | // 构建过程
102 | // 1. 删除 lib 文件夹
103 | // 2. rollup 打包
104 | // 3. api-extractor 生成统一的声明文件, 删除多余的声明文件
105 | // 4. 完成
106 | export const build = series(clearLibFile, buildByRollup, apiExtractorGenerate, complete);
107 |
108 | // 自定义生成 changelog
109 | export const changelog: TaskFunc = async (cb) => {
110 | // const changelogPath: string = path.join(paths.root, 'CHANGELOG.md');
111 | const changelogDocPath: string = path.join(paths.docs, 'CHANGELOG.md');
112 | // 对命令 conventional-changelog -p angular -i CHANGELOG.md -w -r 0
113 | const changelogPipe = await conventionalChangelog({
114 | preset: 'angular',
115 | releaseCount: 0,
116 | });
117 | changelogPipe.setEncoding('utf8');
118 |
119 | const resultArray = ['# 工具库更新日志\n\n'];
120 | changelogPipe.on('data', (chunk) => {
121 | // 原来的 commits 路径是进入提交列表
122 | resultArray.push(chunk.replace(/\/commits\//g, '/commit/'));
123 | });
124 | changelogPipe.on('end', async () => {
125 | // await fse.createWriteStream(changelogPath).write(resultArray.join(''));
126 | await fse.createWriteStream(changelogDocPath).write(resultArray.join(''));
127 | cb();
128 | });
129 | };
130 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | preset: 'ts-jest',
3 | globals: {
4 | 'ts-jest': {
5 | isolatedModules: true,
6 | },
7 | },
8 | testPathIgnorePatterns: ['/node_modules/'],
9 | testMatch: [
10 | '**/__tests__/**/(*.)+(spec|test).[jt]s?(x)',
11 | '**/test/**/(*.)+(spec|test).[jt]s?(x)',
12 | ],
13 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
14 | };
15 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@dtinsight/dt-utils",
3 | "version": "1.5.0",
4 | "description": "袋鼠云前端常用工具库",
5 | "main": "lib/index.js",
6 | "module": "lib/index.esm.js",
7 | "typings": "lib/index.d.js",
8 | "files": [
9 | "lib",
10 | "LICENSE",
11 | "CHANGELOG.md",
12 | "README.md"
13 | ],
14 | "sideEffects": false,
15 | "repository": {
16 | "type": "git",
17 | "url": "git+https://github.com/DTStack/dt-utils.git"
18 | },
19 | "author": "linhe",
20 | "license": "MIT",
21 | "bugs": {
22 | "url": "https://github.com/DTStack/dt-utils/issues"
23 | },
24 | "homepage": "https://dtstack.github.io/dt-utils/",
25 | "scripts": {
26 | "build": "gulp build",
27 | "api": "api-extractor run",
28 | "prettier": "npx prettier --check **/*.{js,json,ts}",
29 | "prettier:fix": "npx prettier --write **/*.{js,json,ts}",
30 | "eslint": "npx eslint --ext .js,.ts ./src ./test",
31 | "eslint:fix": "npx eslint --fix --ext .js,.ts ./src ./test",
32 | "changelog": "gulp changelog",
33 | "docs": "docsify serve docs",
34 | "test": "jest --no-chche",
35 | "release": "./scripts/release.sh",
36 | "prepublishOnly": "yarn eslint & yarn test & yarn changelog & yarn build"
37 | },
38 | "devDependencies": {
39 | "@babel/preset-env": "^7.7.7",
40 | "@commitlint/config-conventional": "^9.1.1",
41 | "@microsoft/api-extractor": "^7.7.0",
42 | "@types/fs-extra": "^8.0.1",
43 | "@types/gulp": "^4.0.6",
44 | "@types/jest": "^24.0.24",
45 | "@types/node": "^17.0.21",
46 | "chalk": "^3.0.0",
47 | "commitizen": "^4.0.3",
48 | "commitlint": "^8.2.0",
49 | "conventional-changelog-cli": "^2.0.31",
50 | "docsify-cli": "^4.4.1",
51 | "fs-extra": "^8.1.0",
52 | "gulp": "^4.0.2",
53 | "husky": "^3.1.0",
54 | "jest": "^24.9.0",
55 | "ko-lint-config": "^2.2.18",
56 | "lint-staged": "^9.5.0",
57 | "right-pad": "^1.0.1",
58 | "rollup": "^1.27.14",
59 | "rollup-plugin-babel": "^4.3.3",
60 | "rollup-plugin-commonjs": "^10.1.0",
61 | "rollup-plugin-node-resolve": "^5.2.0",
62 | "rollup-plugin-typescript2": "^0.25.3",
63 | "ts-jest": "^24.2.0",
64 | "ts-node": "^8.5.4",
65 | "typescript": "^3.7.4",
66 | "vue-cli-plugin-commitlint": "^1.0.4"
67 | },
68 | "dependencies": {
69 | "dayjs": "^1.10.6",
70 | "lodash": "^4.17.21",
71 | "standard-version": "^9.3.1"
72 | },
73 | "config": {
74 | "commitizen": {
75 | "path": "./node_modules/vue-cli-plugin-commitlint/lib/cz"
76 | }
77 | },
78 | "husky": {
79 | "hooks": {
80 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
81 | "pre-commit": "lint-staged & jest -u"
82 | }
83 | },
84 | "lint-staged": {
85 | "*.{.ts,.js}": [
86 | "eslint",
87 | "git add"
88 | ]
89 | },
90 | "directories": {
91 | "doc": "docs",
92 | "lib": "lib",
93 | "test": "test"
94 | },
95 | "keywords": [
96 | "uitls"
97 | ]
98 | }
99 |
--------------------------------------------------------------------------------
/rollup.config.ts:
--------------------------------------------------------------------------------
1 | import path from 'path';
2 | import { RollupOptions } from 'rollup';
3 | import rollupTypescript from 'rollup-plugin-typescript2';
4 | import babel from 'rollup-plugin-babel';
5 | import resolve from 'rollup-plugin-node-resolve';
6 | import commonjs from 'rollup-plugin-commonjs';
7 | import { DEFAULT_EXTENSIONS } from '@babel/core';
8 |
9 | import pkg from './package.json';
10 |
11 | const paths = {
12 | input: path.join(__dirname, '/src/index.ts'),
13 | output: path.join(__dirname, '/lib'),
14 | };
15 |
16 | // rollup 配置项
17 | const rollupConfig: RollupOptions = {
18 | input: paths.input,
19 | output: [
20 | // 输出 commonjs 规范的代码
21 | {
22 | file: path.join(paths.output, 'index.js'),
23 | format: 'cjs',
24 | name: pkg.name,
25 | },
26 | // 输出 es 规范的代码
27 | {
28 | file: path.join(paths.output, 'index.esm.js'),
29 | format: 'es',
30 | name: pkg.name,
31 | },
32 | ],
33 | // external: ['lodash'], // 指出应将哪些模块视为外部模块,如 Peer dependencies 中的依赖
34 | // plugins 需要注意引用顺序
35 | plugins: [
36 | // 使得 rollup 支持 commonjs 规范,识别 commonjs 规范的依赖
37 | commonjs(),
38 |
39 | // 配合 commnjs 解析第三方模块
40 | resolve({
41 | // 将自定义选项传递给解析插件
42 | customResolveOptions: {
43 | moduleDirectory: 'node_modules',
44 | },
45 | }),
46 | rollupTypescript(),
47 | babel({
48 | runtimeHelpers: true,
49 | // 只转换源代码,不运行外部依赖
50 | exclude: 'node_modules/**',
51 | // babel 默认不支持 ts 需要手动添加
52 | extensions: [...DEFAULT_EXTENSIONS, '.ts'],
53 | }),
54 | ],
55 | };
56 |
57 | export default rollupConfig;
58 |
--------------------------------------------------------------------------------
/scripts/release.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | while [[ "$#" > 0 ]]; do case $1 in
4 | -r|--release) release="$2"; shift;;
5 | -b|--branch) branch="$2"; shift;;
6 | *) echo "Unknown parameter passed: $1"; exit 1;;
7 | esac; shift; done
8 |
9 | # Default as minor, the argument major, minor or patch:
10 | if [ -z "$release" ]; then
11 | release="minor";
12 | fi
13 |
14 | # Default release branch is master
15 | if [ -z "$branch" ] ; then
16 | branch="master";
17 | fi;
18 |
19 |
20 | echo "Branch is $branch"
21 | echo "Release as $release"
22 |
23 | # Tag prefix
24 | prefix="v"
25 | git pull origin $branch
26 | echo "Current pull origin $branch."
27 |
28 |
29 | echo "yarn prepublishOnly"
30 | yarn prepublishOnly
31 |
32 |
33 | # Auto generate version number and tag
34 | standard-version -r $release --tag-prefix $prefix --infile CHANGELOG.md
35 |
36 | # git push --follow-tags origin $branch
37 |
38 | echo "Release finished."
39 |
40 |
41 |
--------------------------------------------------------------------------------
/src/cookie.ts:
--------------------------------------------------------------------------------
1 | const cookie = {
2 | /**
3 | * 原生 JavaScript 获取 cookie 值
4 | * @param name
5 | */
6 | getCookie(name: string, cookiesStr: string = document.cookie) {
7 | const arr = cookiesStr.match(new RegExp('(^| )' + name + '=([^;]*)(;|$)'));
8 | if (arr != null) {
9 | try {
10 | return unescape(decodeURI(arr[2]));
11 | } catch (error) {
12 | return arr[2];
13 | }
14 | }
15 | return null;
16 | },
17 |
18 | // 获取全部 cookie
19 | getAllCookies() {
20 | const cookies: {
21 | [key in string]: string;
22 | } = {};
23 | try {
24 | document.cookie.split('; ').forEach((item) => {
25 | const msg = item.split('=');
26 | cookies[msg[0]] = msg[1];
27 | });
28 | } catch {
29 | throw new Error('Cookie解析失败,请检查Cookie格式!');
30 | }
31 | return cookies;
32 | },
33 |
34 | deleteCookie(name: string, domain?: string, path?: string) {
35 | const d = new Date(0);
36 | const domainTemp = domain ? `; domain=${domain}` : '';
37 | const pathTemp = path || '/';
38 | document.cookie =
39 | name + '=; expires=' + d.toUTCString() + domainTemp + '; path=' + pathTemp;
40 | },
41 |
42 | deleteAllCookies(domain: string, path: string) {
43 | const cookies = document.cookie.split(';');
44 | for (let i = 0; i < cookies.length; i++) {
45 | if (cookies[i]) {
46 | this.deleteCookie(cookies[i].split('=')[0], domain, path);
47 | }
48 | }
49 | },
50 |
51 | setCookie(
52 | name: string,
53 | value: string | number | object | boolean,
54 | days?: number,
55 | domainStr?: string,
56 | path = '/'
57 | ) {
58 | let expires = '';
59 | if (days) {
60 | const date = new Date();
61 | date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
62 | expires = '; expires=' + date.toUTCString();
63 | }
64 | let domain = '';
65 | if (domainStr) {
66 | domain = '; domain=' + domainStr;
67 | }
68 | document.cookie = name + '=' + value + expires + domain + '; path=' + path;
69 | },
70 | };
71 |
72 | export default cookie;
73 |
--------------------------------------------------------------------------------
/src/copy.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Copy工具类
3 | *
4 | * 使用方法:
5 | * import CopyUtils from 'copy.js';
6 | * const instance = new CopyUtils();
7 | * instance.copy(value, callback);
8 | */
9 | export default class CopyUtils {
10 | fakeHandlerCallback: any;
11 | fakeHandler: any = null;
12 | fakeElem: any;
13 |
14 | copy(value: any, callback?: Function) {
15 | this.removeFake();
16 |
17 | this.fakeHandlerCallback = () => this.removeFake();
18 | this.fakeHandler = document.body.addEventListener('click', this.fakeHandlerCallback);
19 |
20 | this.fakeElem = document.createElement('textarea');
21 | // Prevent zooming on iOS
22 | this.fakeElem.style.fontSize = '12pt';
23 |
24 | // Reset box model
25 | this.fakeElem.style.border = '0';
26 | this.fakeElem.style.padding = '0';
27 | this.fakeElem.style.margin = '0';
28 |
29 | // Move element out of screen horizontally
30 | this.fakeElem.style.position = 'absolute';
31 | this.fakeElem.style.left = '-9999px';
32 |
33 | // Move element to the same position vertically
34 | const yPosition = window.pageYOffset || document.documentElement.scrollTop;
35 | this.fakeElem.style.top = `${yPosition}px`;
36 |
37 | this.fakeElem.setAttribute('readonly', '');
38 | this.fakeElem.value = value;
39 |
40 | document.body.appendChild(this.fakeElem);
41 | this.fakeElem.select();
42 |
43 | this.copyText(callback);
44 | }
45 |
46 | removeFake() {
47 | if (this.fakeHandler) {
48 | document.body.removeEventListener('click', this.fakeHandlerCallback);
49 | this.fakeHandler = null;
50 | this.fakeHandlerCallback = null;
51 | }
52 |
53 | if (this.fakeElem) {
54 | document.body.removeChild(this.fakeElem);
55 | this.fakeElem = null;
56 | }
57 | }
58 |
59 | copyText(callback?: Function) {
60 | let succeeded;
61 |
62 | try {
63 | succeeded = document.execCommand('copy');
64 | } catch (err) {
65 | succeeded = false;
66 | }
67 | if (callback) callback(succeeded);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/dateTime.ts:
--------------------------------------------------------------------------------
1 | /** :
2 | * @description: 时间格式化
3 | * @author: Created by 景明 on 2021-08-26 15:57:25
4 | */
5 |
6 | import dayjs from 'dayjs';
7 |
8 | /**
9 | * 时间处理
10 | */
11 | const dateTime = {
12 | /**
13 | * 返回 YYYY-MM-DD HH:mm:ss 格式化的字符串
14 | * @param {string | number | Date} timeData
15 | * @return {string}
16 | */
17 | formatDateTime(timeData: string | number | Date) {
18 | return dayjs(timeData).format('YYYY-MM-DD HH:mm:ss');
19 | },
20 | /**
21 | * 返回 YYYY-MM-DD 格式化的字符串
22 | * @param {string | number | Date} timeData
23 | * @return {string}
24 | */
25 | formatDate(timeData: string | number | Date) {
26 | return dayjs(timeData).format('YYYY-MM-DD');
27 | },
28 | /**
29 | * 返回 YYYY-MM-DD HH:mm 格式化的字符串
30 | * @param {string | number | Date} timeData
31 | * @return {string}
32 | */
33 | formatDateHours(timeData: string | number | Date) {
34 | return dayjs(timeData).format('YYYY-MM-DD HH:mm');
35 | },
36 | /**
37 | * 返回 MM-DD HH:mm 格式化的字符串
38 | * @param {string | number | Date} timeData
39 | * @return {string}
40 | */
41 | formatDayHours(timeData: string | number | Date) {
42 | return dayjs(timeData).format('MM-DD HH:mm');
43 | },
44 | /**
45 | * 返回 HH:mm 格式化的字符串
46 | * @param {string | number | Date} timeData
47 | * @return {string}
48 | */
49 | formatHours(timeData: string | number | Date) {
50 | return dayjs(timeData).format('HH:mm');
51 | },
52 | /**
53 | * 返回 HH:mm:ss 格式化的字符串
54 | * @param {string | number | Date} timeData
55 | * @return {string}
56 | */
57 | formatMinute(timeData: string | number | Date) {
58 | return dayjs(timeData).format('HH:mm:ss');
59 | },
60 | /**
61 | * 把秒转换成 HH[h]mm[m]ss[s] 的格式
62 | * @param {number} secondTime 秒
63 | * @return {string}
64 | */
65 | formatSecond(secondTime = 0) {
66 | let second = 0;
67 | let minute = 0;
68 | let hour = 0;
69 |
70 | function _formatHour(timestap: number) {
71 | hour = Math.floor(timestap / 3600);
72 | return timestap - hour * 3600;
73 | }
74 | function _formatMinute(timestap: number) {
75 | minute = Math.floor(timestap / 60);
76 | return timestap - minute * 60;
77 | }
78 | function _formatSecond(timestap: number) {
79 | second = timestap;
80 | return second;
81 | }
82 | _formatSecond(_formatMinute(_formatHour(secondTime)));
83 | return (
84 | `${hour ? hour + 'h' : ''}${minute ? minute + 'm' : ''}${second ? second + 's' : ''}` ||
85 | '0s'
86 | );
87 | },
88 | };
89 |
90 | export default dateTime;
91 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | export { default as Utils } from './utils';
2 | export { default as Cookie } from './cookie';
3 | export { default as DateTime } from './dateTime';
4 | export { default as Layout } from './layout';
5 | export { default as CopyUtils } from './copy';
6 | export { default as LocalIndexedDB } from './indexedDB';
7 | export { default as LocalDB } from './localDB';
8 |
--------------------------------------------------------------------------------
/src/indexedDB.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Usage: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
3 | * Compatibility: https://caniuse.com/#feat=indexeddb
4 | */
5 |
6 | declare let window: any;
7 |
8 | class LocalIndexedDB {
9 | private _db!: IDBDatabase;
10 | private _version!: number;
11 | private _database!: string;
12 | private _storeName!: string;
13 | private _openLog!: boolean;
14 |
15 | /**
16 | * Constructor a new indexedDB object
17 | * @param database database name
18 | * @param version database version
19 | * @param storeName store object name
20 | * @param openLog - 是否打印 indexedDB 变化
21 | */
22 | constructor(database: string, version: number, storeName: string, openLog = false) {
23 | if (!('indexedDB' in window)) {
24 | console.log("This browser doesn't support IndexedDB");
25 | } else {
26 | this._storeName = storeName;
27 | this._version = version;
28 | this._database = database;
29 | this._openLog = openLog;
30 | }
31 | }
32 |
33 | /**
34 | * Open the database indicated in constructor function.
35 | * This method return a Promise object which success will resolve db instance.
36 | */
37 | public open() {
38 | return new Promise((resolve, reject) => {
39 | try {
40 | const self = this;
41 | if (self._db) {
42 | return resolve(self._db);
43 | }
44 |
45 | // If exist the same version database, there need upgrade an new version database,
46 | // because of the same version can't trigger onupgradeneeded event which will occur
47 | // object stores was not found exception.
48 | const request = indexedDB.open(self._database, self._version);
49 |
50 | request.onsuccess = function () {
51 | self._db = request.result;
52 | self._db.onversionchange = (event: any) => {
53 | console.log('onversionchange', event);
54 | };
55 | resolve(request.result);
56 | console.log('Open indexedDB success!');
57 | };
58 |
59 | // onupgradeneeded -> transaction.oncomplete -> onsuccess
60 | request.onupgradeneeded = function (e: any) {
61 | console.log('openDb.onupgradeneeded', e);
62 | self._db = request.result;
63 | if (!self._db.objectStoreNames.contains(self._storeName)) {
64 | const objectStore = self._db.createObjectStore(self._storeName);
65 | objectStore.transaction.oncomplete = function () {
66 | resolve(request.result);
67 | };
68 | }
69 | };
70 |
71 | request.onblocked = function (e: any) {
72 | console.log('openDb onblocked', e);
73 | };
74 |
75 | request.onerror = function (e: Event) {
76 | console.log('Maybe you not allow my web app to use IndexedDB!');
77 | reject(e);
78 | };
79 | } catch (e) {
80 | console.error(e);
81 | reject(e);
82 | }
83 | });
84 | }
85 |
86 | private getObjectStore(storeName: string, mode: IDBTransactionMode) {
87 | if (this._db) {
88 | const transaction = this._db.transaction([storeName], mode);
89 | return transaction.objectStore(storeName);
90 | }
91 | return null;
92 | }
93 |
94 | public add(value: any, key?: string) {
95 | return this.wrapStoreOperationPromise(function (store: IDBObjectStore) {
96 | return store.add(value, key);
97 | });
98 | }
99 |
100 | /**
101 | * Set a value to store object by key
102 | * @param key the key of store object
103 | * @param value the value of store object
104 | */
105 | public set(key: string, value: any) {
106 | this.log('IndexedDB set', key, value);
107 | return this.wrapStoreOperationPromise(function (store: IDBObjectStore) {
108 | return store.put(value, key);
109 | });
110 | }
111 |
112 | /**
113 | * Get the value with the given key
114 | * @param key the key of store object
115 | */
116 | public get(key: string) {
117 | this.log('IndexedDB get', key);
118 | return this.wrapStoreOperationPromise(function (store: IDBObjectStore) {
119 | return store.get(key);
120 | });
121 | }
122 |
123 | /**
124 | * Delete records in store with the given key
125 | * @param key the key of store object
126 | */
127 | public delete(key: string) {
128 | return this.wrapStoreOperationPromise(function (store: IDBObjectStore) {
129 | return store.delete(key);
130 | });
131 | }
132 |
133 | /**
134 | * Delete all data in store object
135 | */
136 | public clear() {
137 | return this.wrapStoreOperationPromise(function (store: IDBObjectStore) {
138 | return store.clear();
139 | });
140 | }
141 |
142 | /**
143 | * Get the store object
144 | */
145 | public getStore() {
146 | return this.getObjectStore(this._storeName, 'readwrite');
147 | }
148 |
149 | /**
150 | * Wrap the database request result as promise object
151 | * @param operate A function which operate store
152 | */
153 | public wrapStoreOperationPromise(
154 | operate: (store: IDBObjectStore) => IDBRequest
155 | ): Promise {
156 | return new Promise((resolve, reject) => {
157 | try {
158 | const store = this.getObjectStore(this._storeName, 'readwrite');
159 | if (store) {
160 | const req = operate(store);
161 | req.onsuccess = (evt: any) => resolve(evt.target.result);
162 | req.onerror = (evt: any) => reject(evt);
163 | }
164 | } catch (e) {
165 | console.error(e);
166 | reject(e);
167 | }
168 | });
169 | }
170 |
171 | private log(...args: any) {
172 | if (this._openLog) {
173 | console.log(...args);
174 | }
175 | }
176 | }
177 |
178 | export default LocalIndexedDB;
179 |
--------------------------------------------------------------------------------
/src/layout.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * 树形布局计算
3 | */
4 | const layout = {
5 | /**
6 | * 获取页面宽度
7 | * @return {[type]} [description]
8 | */
9 | pageWidth() {
10 | return Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
11 | },
12 |
13 | /**
14 | * 获取页面高度
15 | * @return {[type]} [description]
16 | */
17 | pageHeight() {
18 | return Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
19 | },
20 | };
21 | export default layout;
22 |
--------------------------------------------------------------------------------
/src/localDB.ts:
--------------------------------------------------------------------------------
1 | import Utils from './utils';
2 |
3 | /**
4 | * 封装 localStorage
5 | * 增加对 JSON 对象的转换
6 | * @return {[type]} [description]
7 | */
8 | const localDB = {
9 | /**
10 | * 按 key 存贮数据 value 到 localStorage
11 | * @param {String} key 存贮数据的唯一标识
12 | * @param {String, Object} value 所要存贮的数据
13 | */
14 | set(key: string | number, value: any) {
15 | if (value === null || value === undefined) {
16 | delete window.localStorage[key];
17 | } else {
18 | const val = typeof value === 'object' ? JSON.stringify(value) : value;
19 | window.localStorage[key] = val;
20 | }
21 | },
22 |
23 | /**
24 | * 通过 key 从 localStorage 获取数据
25 | * @param {String} key 获取数据的唯一标识
26 | * @return {String, Object} 返回空、字符串或者对象
27 | */
28 | get(key: string | number) {
29 | const str = window.localStorage[key] || '';
30 | try {
31 | return Utils.isJSONStr(str) ? JSON.parse(str) : str;
32 | } catch (error) {
33 | return str;
34 | }
35 | },
36 |
37 | /**
38 | * 通过 key 从 localStorage 删除数据
39 | * @param {String} key 删除数据的唯一标识
40 | */
41 | remove(key: string | number) {
42 | delete window.localStorage[key];
43 | },
44 |
45 | /**
46 | * 清空 localStorage
47 | * @return 无返回 NULL
48 | */
49 | clear() {
50 | window.localStorage.clear();
51 | },
52 | };
53 |
54 | export default localDB;
55 |
--------------------------------------------------------------------------------
/src/utils.ts:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-unused-expressions */
2 | /* eslint-disable no-cond-assign */
3 | import _ from 'lodash';
4 |
5 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
6 | declare let APP: any;
7 | interface BrowserInter {
8 | chrome?: string;
9 | ie?: string;
10 | edge?: string;
11 | firefox?: string;
12 | safari?: string;
13 | opera?: string;
14 | }
15 | export interface DownloadParams {
16 | url: string;
17 | fileName?: string;
18 | payload?: object;
19 | headers?: HeadersInit;
20 | finallyCallback?: () => void;
21 | successCallback?: (res: Response) => void;
22 | errorCallback: (res: Response) => void;
23 | }
24 |
25 | const utils = {
26 | /**
27 | * @description 浏览器类型和版本检测
28 | * @returns {Boolean} `true`表示通过兼容性检测,`false`表示不通过兼容性检测
29 | */
30 | browserCheck() {
31 | const Sys: BrowserInter = {};
32 | if (utils.isMobileDevice()) {
33 | return true;
34 | } // 忽略移动设备
35 | const ua = navigator.userAgent.toLowerCase();
36 | let s;
37 | // prettier-ignore
38 | (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? Sys.ie = s[1]
39 | : (s = ua.match(/msie ([\d\.]+)/)) ? Sys.ie = s[1]
40 | : (s = ua.match(/edge?\/([\d\.]+)/)) ? Sys.edge = s[1]
41 | : (s = ua.match(/firefox\/([\d\.]+)/)) ? Sys.firefox = s[1]
42 | : (s = ua.match(/(?:opera|opr).([\d\.]+)/)) ? Sys.opera = s[1]
43 | : (s = ua.match(/chrome\/([\d\.]+)/)) ? Sys.chrome = s[1]
44 | : (s = ua.match(/version\/([\d\.]+).*safari/)) ? Sys.safari = s[1] : 0;
45 | if (
46 | (Sys.chrome && parseInt(Sys.chrome.split('.')[0], 10) >= 66) ||
47 | Sys.firefox ||
48 | Sys.edge
49 | ) {
50 | return true;
51 | }
52 | return false;
53 | },
54 | checkExist(prop: any) {
55 | return prop !== undefined && prop !== null && prop !== '';
56 | },
57 | /**
58 | * 转换 Byte 转换为小于1024值最大单位
59 | * @param value 'B' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' 转换原始值
60 | */
61 | convertBytes(value: number) {
62 | let valueTemp = value;
63 | const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
64 | let i = 0;
65 | while (valueTemp >= 1024) {
66 | valueTemp = Number((valueTemp / 1024).toFixed(2));
67 | i++;
68 | }
69 | return `${valueTemp} ${units[i]}`;
70 | },
71 | isMacOs() {
72 | return navigator.userAgent.indexOf('Macintosh') > -1;
73 | },
74 |
75 | isWindows() {
76 | return navigator.userAgent.indexOf('Windows') > -1;
77 | },
78 | isMobileDevice() {
79 | return (
80 | typeof window.orientation !== 'undefined' ||
81 | navigator.userAgent.indexOf('IEMobile') !== -1
82 | );
83 | },
84 | /**
85 | * 根据参数名获取URL数据
86 | * @param {[type]} name [description]
87 | * @param {[type]} url [description]
88 | */
89 | getParameterByName(name: string, url?: string) {
90 | let urlTemp = url;
91 | if (!urlTemp) {
92 | urlTemp = window.location.href;
93 | }
94 | const nameTemp = name.replace(/[\[\]]/g, '\\$&');
95 | const regex = new RegExp('[?&]' + nameTemp + '(=([^]*)|&|#|$)');
96 |
97 | const results = regex.exec(urlTemp);
98 | if (!results) {
99 | return null;
100 | }
101 | if (!results[2]) {
102 | return '';
103 | }
104 |
105 | const paramValue = decodeURIComponent(results[2].replace(/\+/g, ' '));
106 | if (paramValue === 'null') {
107 | return null;
108 | }
109 | if (paramValue === 'undefined') {
110 | return undefined;
111 | }
112 | return paramValue;
113 | },
114 | /**
115 | *
116 | * @param pathname 地址
117 | * @param queryParams url参数
118 | * @returns 两者生成的完整url地址
119 | */
120 | generateFullUrlPath(pathname: string, queryParams = {}) {
121 | const params = new URLSearchParams(queryParams);
122 | const queryString = params.toString();
123 | return pathname + (queryString ? `?${queryString}` : '');
124 | },
125 | /**
126 | *
127 | * @param search location.search
128 | * @returns query 参数
129 | */
130 | getQueryParameters(search: string) {
131 | const searchParams = new URLSearchParams(search);
132 | const paramValue = Object.fromEntries(searchParams.entries());
133 | for (const key in paramValue) {
134 | if (paramValue[key] === 'null') {
135 | (paramValue[key] as any) = null;
136 | }
137 | if (paramValue[key] === 'undefined') {
138 | (paramValue[key] as any) = undefined;
139 | }
140 | }
141 |
142 | return paramValue;
143 | },
144 | /**
145 | * 获取图片的Base64格式
146 | * @param {[type]} img [description]
147 | * @param {Function} callback [description]
148 | */
149 | getBase64(img: any, callback: (img: any) => void) {
150 | const reader = new FileReader();
151 | reader.addEventListener('load', () => callback(reader.result));
152 | reader.readAsDataURL(img);
153 | },
154 |
155 | /**
156 | * 百分比转换
157 | * @param {[type]} num [description]
158 | * @param {[type]} precision [description]
159 | */
160 | percent(num: number, precision?: number) {
161 | let numTemp = num;
162 | if (!numTemp || numTemp === Infinity) {
163 | return 0 + '%';
164 | }
165 | if (numTemp > 1) {
166 | numTemp = 1;
167 | }
168 | let precisionTemp = precision || 2;
169 | precisionTemp = Math.pow(10, precisionTemp);
170 | return Math.round(numTemp * precisionTemp * 100) / precisionTemp + '%';
171 | },
172 | /**
173 | *
174 | *
175 | * @param {Record} [object={}]
176 | * @returns
177 | */
178 | getCssText(object: Record = {}) {
179 | let str = '';
180 | for (const attr in object) {
181 | if (object.hasOwnProperty(attr)) {
182 | str += attr + ':' + object[attr] + ';';
183 | }
184 | }
185 | return str;
186 | },
187 |
188 | /**
189 | * @description: 去除字符串前后空格
190 | * @param: str 带有空格的字符串
191 | * @returns: 返回去除前后空格的字符串
192 | */
193 | trim(str: string) {
194 | if (typeof str !== 'string') return str;
195 | return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
196 | },
197 |
198 | /**
199 | * @description: 去除字符串的所有空格
200 | * @param: str 带有空格的字符串
201 | * @returns: 返回去除所有空格的字符串
202 | */
203 | trimAll(str: string) {
204 | if (typeof str !== 'string') return str;
205 | return str.replace(/\s/g, '');
206 | },
207 |
208 | // 转换为千分位
209 | getThousandth(num: string | number) {
210 | let numTemp = num;
211 | if (numTemp === null || numTemp === undefined || numTemp === '') return '0';
212 | numTemp = `${num}`;
213 | const [integer, decimal] = numTemp.split('.');
214 | return `${integer.replace(/(\d)(?=(\d{3})+$)/g, '$1,')}${decimal ? `.${decimal}` : ''}`;
215 | },
216 |
217 | // 文字溢出转换
218 | textOverflowExchange(text: string, length: number) {
219 | if (text && text.length > length) {
220 | return text.substring(0, length) + '...';
221 | }
222 | return text;
223 | },
224 | /**
225 | * json格式化
226 | * @param {格式化内容} text
227 | * @param {格式化占位符} space
228 | */
229 | jsonFormat(text: string, space?: number) {
230 | if (!text) {
231 | return text;
232 | }
233 | try {
234 | const json = JSON.parse(text);
235 | const output = JSON.stringify(json, null, space || 2);
236 |
237 | return output;
238 | } catch (e) {
239 | return null;
240 | }
241 | },
242 | /**
243 | * 多函数排序,匹配到0为止
244 | */
245 | sortByCompareFunctions(arr: any[], ...compareFunctions: any[]) {
246 | arr.sort((a, b) => {
247 | let result = 0;
248 | for (const func of compareFunctions) {
249 | result = func(a, b);
250 | if (result !== 0) {
251 | return result;
252 | }
253 | }
254 | return result;
255 | });
256 | },
257 | /**
258 | * 转换排序字段
259 | */
260 | exchangeOrder(order: string) {
261 | switch (order) {
262 | case 'ascend':
263 | return 'asc';
264 | case 'descend':
265 | return 'desc';
266 | default:
267 | return undefined;
268 | }
269 | },
270 | /**
271 | * 生成一个key
272 | */
273 | generateAKey() {
274 | return '' + new Date().getTime() + ~~(Math.random() * 1000000);
275 | },
276 |
277 | /**
278 | * 判断是否是JSON string
279 | * @param {String} str 所要验证的字符串
280 | * @return {Boolean} 是否是JSON字符串
281 | */
282 | isJSONStr(str: string) {
283 | const strTemp = utils.trim(str);
284 | return (
285 | (strTemp.charAt(0) === '{' && strTemp.charAt(strTemp.length - 1) === '}') ||
286 | (strTemp.charAt(0) === '[' && strTemp.charAt(strTemp.length - 1) === ']')
287 | );
288 | },
289 | /**
290 | *
291 | * 校验手机
292 | * @param {*} tel
293 | * @returns
294 | */
295 | isPhoneNumber(tel: string) {
296 | const reg = /^0?1[3|4|5|6|7|8][0-9]\d{8}$/;
297 | return reg.test(tel);
298 | },
299 | /**
300 | * 判断是否是函数
301 | *
302 | * @param {*} arg
303 | * @returns
304 | */
305 | isFunction(arg: any) {
306 | if (arg) {
307 | // eslint-disable-next-line no-constant-condition
308 | if (typeof /./ !== 'function') {
309 | return typeof arg === 'function';
310 | } else {
311 | return Object.prototype.toString.call(arg) === '[object Function]';
312 | }
313 | }
314 | return false;
315 | },
316 | /**
317 | * 随机生成一串6位同时包含数字、大小写字母的字符串
318 | * @param len number
319 | */
320 | getRandomStr(len: number): string {
321 | const numChar = '0123456789';
322 | const lowerCaseChar = 'abcdefghijklmnopqrstuvwxyz';
323 | const upperCaseChar = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
324 | function getChar(baseChar: string) {
325 | const randomIndex = Math.random() * (baseChar.length - 1);
326 | return baseChar.charAt(randomIndex);
327 | }
328 | let currentChar = 'num';
329 | let str = '';
330 | for (let i = 0; i < len; i++) {
331 | if (currentChar === 'num') {
332 | str += getChar(numChar);
333 | currentChar = 'lower';
334 | } else if (currentChar === 'lower') {
335 | str += getChar(lowerCaseChar);
336 | currentChar = 'upper';
337 | } else if (currentChar === 'upper') {
338 | str += getChar(upperCaseChar);
339 | currentChar = 'num';
340 | }
341 | }
342 | return str;
343 | },
344 | /**
345 | * simply judge whether the array is equal
346 | * @param arr1
347 | * @param arr2
348 | * @returns arr1 === arr2
349 | */
350 | isEqualArr(arr1: string[], arr2: string[]): boolean {
351 | const toString = JSON.stringify;
352 | return toString(arr1.sort()) === toString(arr2.sort());
353 | },
354 | /**
355 | *
356 | *
357 | * @param {*} a
358 | * @param {*} b
359 | * @returns boolean
360 | */
361 | isEqual(a: any, b: any): boolean {
362 | for (const key in a) {
363 | if (
364 | {}.hasOwnProperty.call(a, key) &&
365 | (!{}.hasOwnProperty.call(b, key) || a[key] !== b[key])
366 | ) {
367 | return false;
368 | }
369 | }
370 | for (const key in b) {
371 | if ({}.hasOwnProperty.call(b, key) && !{}.hasOwnProperty.call(a, key)) {
372 | return false;
373 | }
374 | }
375 | return true;
376 | },
377 | /**
378 | *
379 | *
380 | * @param {*} targetComponent
381 | */
382 | shouldRender(targetComponent: any) {
383 | targetComponent.prototype.shouldComponentUpdate = function (props: any, state: any) {
384 | return !utils.isEqual(this.state, state) || !utils.isEqual(this.props, props);
385 | };
386 | },
387 | /**
388 | *
389 | * 计算字符串长度(英文占1个字符,中文汉字占2个字符)
390 | * @param {*} str
391 | * @returns number
392 | */
393 | getStrlen(str: string) {
394 | let len = 0;
395 | for (let i = 0; i < str.length; i++) {
396 | const c = str.charCodeAt(i);
397 | // 单字节加1
398 | if ((c >= 0x0001 && c <= 0x007e) || (c >= 0xff60 && c <= 0xff9f)) {
399 | len++;
400 | } else {
401 | len += 2;
402 | }
403 | }
404 | return len;
405 | },
406 | transformArray(arr: T[], num: number): T[][] {
407 | const length = arr.length;
408 | const res: T[][] = [];
409 | let i = 0;
410 | while (i * num < length) {
411 | res.push(arr.slice(i * num, (i + 1) * num));
412 | i++;
413 | }
414 | return res;
415 | },
416 | isEmpty(data?: any) {
417 | if (data === '') return true;
418 | if (data === null) return true;
419 | if (data === undefined) return true;
420 | if (Array.prototype.isPrototypeOf(data) && data.length === 0) return true;
421 | if (Object.prototype.isPrototypeOf(data) && Object.keys(data).length === 0) return true;
422 | return false;
423 | },
424 | isObj(obj?: any) {
425 | return Object.prototype.toString.call(obj) === '[object Object]';
426 | },
427 | removeEmpty(obj?: any) {
428 | if (!obj || !utils.isObj(obj)) return;
429 | Object.entries(obj).forEach(([key, val]) => {
430 | if (val && utils.isObj(val)) utils.removeEmpty(val);
431 | else if (utils.isEmpty(val)) delete obj[key];
432 | });
433 | return obj;
434 | },
435 | mergeDeep(object1: Record, object2: Record) {
436 | if (object1 == null || object2 == null) {
437 | return object1 || object2;
438 | } else if (!_.isPlainObject(object1) || !_.isPlainObject(object2)) {
439 | return object2;
440 | } else if (object1 === object2) {
441 | return object2;
442 | } else {
443 | if ('_isMergeAtom' in object2) {
444 | const isMergeAtom = object2._isMergeAtom;
445 | delete object2._isMergeAtom;
446 |
447 | if (isMergeAtom) {
448 | return object2;
449 | }
450 | }
451 | const obj = {
452 | ...object1,
453 | };
454 | _.forEach(object2, (value, key) => {
455 | if (key in object1) {
456 | obj[key] = utils.mergeDeep(object1[key], value);
457 | } else {
458 | obj[key] = value;
459 | }
460 | });
461 |
462 | return obj;
463 | }
464 | },
465 | /**
466 | * 下载文件
467 | * @param {string} url 请求地址
468 | * @param {string} fileName 输出名字,如果不传就是后端写入文件名
469 | * @param {object} payload 请求数据
470 | * @param {function} successCallback 导出正确的回调函数,处理一些message展示
471 | * @param {function} errorCallback 导出失败的回调函数
472 | * @param {function} finallyCallback 成功/失败都会执行回调函数,例如控制一些visible显示隐藏
473 | * */
474 | downLoadData(params: DownloadParams) {
475 | const { url, payload, headers, finallyCallback, successCallback, errorCallback } = params;
476 | fetch(url, { method: 'POST', body: JSON.stringify(payload), headers })
477 | .then((response) => {
478 | if (response.status !== 200) return errorCallback(response);
479 | const contentType = response.headers.get('Content-type') || '';
480 | if (contentType.includes('application/json')) return errorCallback(response);
481 | let { fileName } = params;
482 | if (!fileName) {
483 | const disposition = response.headers.get('Content-disposition') || '';
484 | fileName = disposition.split('filename=')[1];
485 | }
486 | response.blob().then((blob) => {
487 | const href = URL.createObjectURL(blob);
488 | const dom = document.createElement('a');
489 | dom.setAttribute('href', href);
490 | dom.setAttribute('download', decodeURIComponent(fileName || ''));
491 | dom.click();
492 | URL.revokeObjectURL(href);
493 | successCallback && successCallback(response);
494 | });
495 | })
496 | .finally(() => {
497 | finallyCallback && finallyCallback();
498 | });
499 | },
500 | isUtf8(s: string) {
501 | const lastnames = ['ä', 'å', 'æ', 'ç', 'è', 'é'];
502 | lastnames.forEach((element) => {
503 | if (s && s.indexOf(element) > -1) {
504 | return false;
505 | }
506 | });
507 | return true;
508 | },
509 | utf16to8(str: string) {
510 | if (typeof str !== 'string') return str;
511 | if (!this.isUtf8(str)) return str;
512 | let out: string, i: number, c: number;
513 | out = '';
514 | const len = str.length || 0;
515 | for (i = 0; i < len; i++) {
516 | c = str.charCodeAt(i);
517 | if (c >= 0x0001 && c <= 0x007f) {
518 | out += str.charAt(i);
519 | } else if (c > 0x07ff) {
520 | out += String.fromCharCode(0xe0 | ((c >> 12) & 0x0f));
521 | out += String.fromCharCode(0x80 | ((c >> 6) & 0x3f));
522 | out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));
523 | } else {
524 | out += String.fromCharCode(0xc0 | ((c >> 6) & 0x1f));
525 | out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));
526 | }
527 | }
528 | return out;
529 | },
530 | base64Encode(value: string) {
531 | let result = value;
532 | if (!result) {
533 | return result;
534 | }
535 | try {
536 | result = btoa(this.utf16to8(value));
537 | } catch (err) {
538 | console.log(err);
539 | }
540 | return result;
541 | },
542 | };
543 | export default utils;
544 |
--------------------------------------------------------------------------------
/test/cookie.test.ts:
--------------------------------------------------------------------------------
1 | import cookie from '../src/cookie';
2 |
3 | type TCookie = {
4 | name?: string;
5 | value?: string;
6 | expires?: string;
7 | domain?: string;
8 | path?: string;
9 | };
10 |
11 | let cookies: TCookie[] = [];
12 |
13 | Object.defineProperty(window.document, 'cookie', {
14 | get() {
15 | return cookies.map(({ name, value }) => `${name}=${value}`).join('; ');
16 | },
17 | set(value: string) {
18 | const innerAttrs = ['path', 'domain', 'expires'];
19 | const attrs = value.split(';').map((attr) => attr.trim());
20 | const cookie: TCookie = {};
21 | attrs.forEach((attrStr) => {
22 | const [key, val] = attrStr.split('=');
23 | if (!innerAttrs.includes(key.toLocaleLowerCase())) {
24 | cookie['name'] = key;
25 | cookie['value'] = val;
26 | } else {
27 | cookie[key.toLocaleLowerCase()] = val;
28 | }
29 | });
30 | cookie.path = cookie.path || '/';
31 | const oldCookieIndex = cookies.findIndex(
32 | ({ name, domain, path }) =>
33 | name === cookie.name && domain === cookie.domain && path === cookie.path
34 | );
35 | const isDelete = cookie.expires && new Date(cookie.expires).getTime() <= Date.now();
36 | if (oldCookieIndex !== -1) {
37 | isDelete
38 | ? cookies.splice(oldCookieIndex, 1)
39 | : cookies.splice(oldCookieIndex, 1, cookie);
40 | } else {
41 | !isDelete && cookies.push(cookie);
42 | }
43 | },
44 | });
45 |
46 | describe('test cookie utils', () => {
47 | beforeEach(() => {
48 | cookies = [];
49 | });
50 |
51 | test('should get cookie value with name', () => {
52 | document.cookie = 'a=1; domain=; path=/';
53 | expect(cookie.getCookie('a')).toBe('1');
54 | expect(cookie.getCookie('a', 'a=2; c=3;')).toBe('2');
55 | });
56 |
57 | test('should return all cookies object', () => {
58 | document.cookie = 'a=1; domain=; path=/';
59 | document.cookie = 'b=2; domain=; path=/';
60 | expect(cookie.getAllCookies()).toEqual({ a: '1', b: '2' });
61 | });
62 |
63 | test('should support set cookie', () => {
64 | cookie.setCookie('a', '1');
65 | expect(cookie.getCookie('a')).toBe('1');
66 |
67 | const day = 3;
68 | cookie.setCookie('b', '2', day, 'test');
69 | const foundCookie = cookies.find((item) => item.name === 'b' && item.domain === 'test');
70 | expect(foundCookie).not.toBeUndefined();
71 |
72 | const expires = new Date(foundCookie!.expires as string).getTime();
73 | const expiresNow = new Date(Date.now() + day * 24 * 60 * 60 * 1000).getTime();
74 | expect(expires).toBeLessThan(expiresNow);
75 | });
76 |
77 | test('should support delete cookie', () => {
78 | cookie.setCookie('a', 1);
79 | cookie.deleteCookie('a');
80 | expect(cookie.getCookie('a')).toBeNull();
81 |
82 | cookie.setCookie('b', 1, 3, 'test', '/test');
83 | cookie.deleteCookie('b');
84 | expect(cookie.getCookie('b')).not.toBeNull();
85 | cookie.deleteCookie('b', 'test', '/test');
86 | expect(cookie.getCookie('b')).toBeNull();
87 | });
88 |
89 | test('should suppport delete all cookies', () => {
90 | cookie.setCookie('a', 1, 3, 'test', '/');
91 | cookie.setCookie('b', 2, 3, 'test', '/');
92 | cookie.deleteAllCookies('', '/');
93 | expect(cookie.getAllCookies()).not.toEqual({});
94 | cookie.deleteAllCookies('test', '/');
95 | expect(cookie.getAllCookies()).toEqual({});
96 | });
97 | });
98 |
--------------------------------------------------------------------------------
/test/dateTime.test.ts:
--------------------------------------------------------------------------------
1 | import DateTime from '../src/dateTime';
2 | const {
3 | formatDate,
4 | formatDateHours,
5 | formatDateTime,
6 | formatDayHours,
7 | formatHours,
8 | formatMinute,
9 | formatSecond,
10 | } = DateTime;
11 |
12 | describe('utils.dateTime', () => {
13 | test('formatDate timestamp to YYYY-MM-DD', () => {
14 | const dateTime = 1627457470000;
15 | const expected = '2021-07-28';
16 | const newVal = formatDate(dateTime);
17 | expect(newVal).toEqual(expected);
18 | });
19 | test('formatDate string to YYYY-MM-DD', () => {
20 | const dateTime = '2021-07-28';
21 | const expected = '2021-07-28';
22 | const newVal = formatDate(dateTime);
23 | expect(newVal).toEqual(expected);
24 | });
25 | test('formatDate number to YYYY-MM-DD', () => {
26 | const dateTime = 11111111111;
27 | const expected = '1970-05-09';
28 | const newVal = formatDate(dateTime);
29 | expect(newVal).toEqual(expected);
30 | });
31 | test('formatDateHours timestamp to YYYY-MM-DD HH:mm', () => {
32 | const dateTime = 1627457470000;
33 | const expected = '2021-07-28 15:31';
34 | const newVal = formatDateHours(dateTime);
35 | expect(newVal).toEqual(expected);
36 | });
37 | test('formatDateHours string to YYYY-MM-DD HH:mm', () => {
38 | const dateTime = '2021-07-28 15:31';
39 | const expected = '2021-07-28 15:31';
40 | const newVal = formatDateHours(dateTime);
41 | expect(newVal).toEqual(expected);
42 | });
43 | test('formatDateHours number to YYYY-MM-DD HH:mm', () => {
44 | const dateTime = 11111111111;
45 | const expected = '1970-05-09 22:25';
46 | const newVal = formatDateHours(dateTime);
47 | expect(newVal).toEqual(expected);
48 | });
49 | test('formatDateTime timestamp to YYYY-MM-DD HH:mm:ss', () => {
50 | const dateTime = 1627457470000;
51 | const expected = '2021-07-28 15:31:10';
52 | const newVal = formatDateTime(dateTime);
53 | expect(newVal).toEqual(expected);
54 | });
55 | test('formatDateTime string to YYYY-MM-DD HH:mm:ss', () => {
56 | const dateTime = '2021-07-28 15:31:10';
57 | const expected = '2021-07-28 15:31:10';
58 | const newVal = formatDateTime(dateTime);
59 | expect(newVal).toEqual(expected);
60 | });
61 | test('formatDateTime number to YYYY-MM-DD HH:mm:ss', () => {
62 | const dateTime = 11111111111;
63 | const expected = '1970-05-09 22:25:11';
64 | const newVal = formatDateTime(dateTime);
65 | expect(newVal).toEqual(expected);
66 | });
67 | test('formatDayHours timestamp to MM-DD HH:mm', () => {
68 | const dateTime = 1627457470000;
69 | const expected = '07-28 15:31';
70 | const newVal = formatDayHours(dateTime);
71 | expect(newVal).toEqual(expected);
72 | });
73 | test('formatDayHours string to MM-DD HH:mm', () => {
74 | const dateTime = '07-28 15:31';
75 | const expected = '07-28 15:31';
76 | const newVal = formatDayHours(dateTime);
77 | expect(newVal).toEqual(expected);
78 | });
79 | test('formatDayHours number to MM-DD HH:mm', () => {
80 | const dateTime = 11111111111;
81 | const expected = '05-09 22:25';
82 | const newVal = formatDayHours(dateTime);
83 | expect(newVal).toEqual(expected);
84 | });
85 | test('formatHours timestamp to HH:mm', () => {
86 | const dateTime = 1627457470000;
87 | const expected = '15:31';
88 | const newVal = formatHours(dateTime);
89 | expect(newVal).toEqual(expected);
90 | });
91 | test('formatHours string to HH:mm', () => {
92 | const dateTime = '07-28 15:31';
93 | const expected = '15:31';
94 | const newVal = formatHours(dateTime);
95 | expect(newVal).toEqual(expected);
96 | });
97 | test('formatHours number to HH:mm', () => {
98 | const dateTime = 11111111111;
99 | const expected = '22:25';
100 | const newVal = formatHours(dateTime);
101 | expect(newVal).toEqual(expected);
102 | });
103 | test('formatMinute timestamp to HH:mm:ss', () => {
104 | const dateTime = 1627457470000;
105 | const expected = '15:31:10';
106 | const newVal = formatMinute(dateTime);
107 | expect(newVal).toEqual(expected);
108 | });
109 | test('formatMinute string to HH:mm:ss', () => {
110 | const dateTime = '08-22 15:31:10';
111 | const expected = '15:31:10';
112 | const newVal = formatMinute(dateTime);
113 | expect(newVal).toEqual(expected);
114 | });
115 | test('formatMinute number to HH:mm:ss', () => {
116 | const dateTime = 11111111111;
117 | const expected = '22:25:11';
118 | const newVal = formatMinute(dateTime);
119 | expect(newVal).toEqual(expected);
120 | });
121 | test('formatSecond number to HH[h]mm[m]ss[s]', () => {
122 | const dateTime = 11111;
123 | const expected = '3h5m11s';
124 | const newVal = formatSecond(dateTime);
125 | expect(newVal).toEqual(expected);
126 | });
127 | test('formatSecond number to mm[m]ss[s]', () => {
128 | const dateTime = 111;
129 | const expected = '1m51s';
130 | const newVal = formatSecond(dateTime);
131 | expect(newVal).toEqual(expected);
132 | });
133 | test('formatSecond number to ss[s]', () => {
134 | const dateTime = 11;
135 | const expected = '11s';
136 | const newVal = formatSecond(dateTime);
137 | expect(newVal).toEqual(expected);
138 | });
139 | });
140 |
--------------------------------------------------------------------------------
/test/localDB.test.ts:
--------------------------------------------------------------------------------
1 | // storage.test.js
2 |
3 | import LocalDB from '../src/localDB';
4 |
5 | const fakeLocalStorage = (function () {
6 | let store = {};
7 |
8 | return {
9 | store,
10 | getItem: function (key) {
11 | return this[key] || null;
12 | },
13 | setItem: function (key, value) {
14 | this[key] = value.toString();
15 | },
16 | removeItem: function (key) {
17 | delete this[key];
18 | },
19 | clear: function () {
20 | store = {};
21 | },
22 | };
23 | })();
24 |
25 | describe('utils.LocalDB', () => {
26 | beforeAll(() => {
27 | const localSProxy = new Proxy(fakeLocalStorage, {
28 | get: function (target, property) {
29 | if (target.store[property]) {
30 | return target.store[property];
31 | }
32 | return target[property];
33 | },
34 | });
35 | Object.defineProperty(window, 'localStorage', {
36 | value: localSProxy,
37 | });
38 | });
39 |
40 | test('get the key to the string storage', () => {
41 | window.localStorage.setItem('loglevel:webpack-dev-server', 'SILENT');
42 | const value = LocalDB.get('loglevel:webpack-dev-server');
43 | const expected = 'SILENT';
44 | expect(value).toEqual(expected);
45 | });
46 | test('get the key to the json string storage', () => {
47 | window.localStorage.setItem('jsonStr', '{"string":1}');
48 | const value = LocalDB.get('jsonStr');
49 | const expected = {
50 | string: 1,
51 | };
52 | expect(value).toEqual(expected);
53 | });
54 | test('get the key to the json string storage', () => {
55 | window.localStorage.setItem('jsonStr', '{"string":1');
56 | const value = LocalDB.get('jsonStr');
57 | expect(value).toEqual('{"string":1');
58 | });
59 | test('remove the key', () => {
60 | window.localStorage.setItem('name', 'Tom');
61 | LocalDB.remove('name');
62 | const value = LocalDB.get('name');
63 | expect(value).toEqual('');
64 | });
65 | });
66 |
--------------------------------------------------------------------------------
/test/utils.test.ts:
--------------------------------------------------------------------------------
1 | import * as assert from 'assert';
2 | import Utils from '../src/utils';
3 |
4 | const {
5 | convertBytes,
6 | checkExist,
7 | getCssText,
8 | trim,
9 | trimAll,
10 | isMacOs,
11 | isWindows,
12 | isMobileDevice,
13 | getParameterByName,
14 | percent,
15 | getThousandth,
16 | textOverflowExchange,
17 | exchangeOrder,
18 | isEqualArr,
19 | isEmpty,
20 | isObj,
21 | transformArray,
22 | removeEmpty,
23 | mergeDeep,
24 | generateFullUrlPath,
25 | getQueryParameters,
26 | } = Utils;
27 |
28 | describe('utils.convertBytes', () => {
29 | test('convert byte to unit B', () => {
30 | const byte = 10.24;
31 | const expected = '10.24 B';
32 | const newVal = convertBytes(byte);
33 | expect(newVal).toEqual(expected);
34 | });
35 | test('convert byte to unit KB', () => {
36 | const byte = 1024;
37 | const expected = '1 KB';
38 | const newVal = convertBytes(byte);
39 | expect(newVal).toEqual(expected);
40 | });
41 | test('convert byte to unit MB', () => {
42 | const byte = 10241024;
43 | const expected = '9.77 MB';
44 | const newVal = convertBytes(byte);
45 | expect(newVal).toEqual(expected);
46 | });
47 | test('convert byte to unit GB', () => {
48 | const byte = 3029021814;
49 | const expected = '2.82 GB';
50 | const newVal = convertBytes(byte);
51 | expect(newVal).toEqual(expected);
52 | });
53 | test('convert byte to unit TB', () => {
54 | const byte = 1184380146909; // 1024 * 5;
55 | const expected = '1.08 TB';
56 | const newVal = convertBytes(byte);
57 | expect(newVal).toEqual(expected);
58 | });
59 | test('convert byte to unit PB', () => {
60 | const byte = 1125899906842624;
61 | const expected = '1 PB';
62 | const newVal = convertBytes(byte);
63 | expect(newVal).toEqual(expected);
64 | });
65 | });
66 | describe('utils:', () => {
67 | test('isMacOs=>false', () => {
68 | assert.strictEqual(isMacOs(), false);
69 | });
70 | test('isWindows=>false', () => {
71 | assert.strictEqual(isWindows(), false);
72 | });
73 | test('isMobileDevice=>false', () => {
74 | assert.strictEqual(isMobileDevice(), false);
75 | });
76 | test('getParameterByName()=>张三', () => {
77 | assert.strictEqual(
78 | getParameterByName('name', 'http://gitlab.prod.dtstack.cn?name=张三'),
79 | '张三'
80 | );
81 | });
82 | test('getParameterByName()=>null', () => {
83 | assert.strictEqual(
84 | getParameterByName('name', 'http://gitlab.prod.dtstack.cn?name=null'),
85 | null
86 | );
87 | });
88 | test('getParameterByName()=>undefined', () => {
89 | assert.strictEqual(
90 | getParameterByName('name', 'http://gitlab.prod.dtstack.cn?name=undefined'),
91 | undefined
92 | );
93 | });
94 | test('percent(1)=>100%', () => {
95 | assert.strictEqual(percent(1), '100%');
96 | });
97 | test('percent(0.5)=>50%', () => {
98 | assert.strictEqual(percent(0.5), '50%');
99 | });
100 | test('percent(0.54321,1)=>50%', () => {
101 | assert.strictEqual(percent(0.54321, 1), '54.3%');
102 | });
103 |
104 | test('getThousandth("")', () => {
105 | assert.strictEqual(getThousandth(''), '0');
106 | });
107 | test('getThousandth(null)', () => {
108 | assert.strictEqual(getThousandth(null), '0');
109 | });
110 | test('getThousandth(undefined)', () => {
111 | assert.strictEqual(getThousandth(undefined), '0');
112 | });
113 | test('getThousandth(123456)', () => {
114 | assert.strictEqual(getThousandth(123456), '123,456');
115 | });
116 | test("getThousandth('123456')", () => {
117 | assert.strictEqual(getThousandth('123456'), '123,456');
118 | });
119 | test('getThousandth(1234567)', () => {
120 | assert.strictEqual(getThousandth(1234567), '1,234,567');
121 | });
122 | test("getThousandth('1234567')", () => {
123 | assert.strictEqual(getThousandth('1234567'), '1,234,567');
124 | });
125 | test('getThousandth(1234.56789)', () => {
126 | assert.strictEqual(getThousandth(1234.56789), '1,234.56789');
127 | });
128 | test("getThousandth('1234.56789')", () => {
129 | assert.strictEqual(getThousandth('1234.56789'), '1,234.56789');
130 | });
131 |
132 | test('textOverflowExchange(\'my name is linhe\')=>"my name is..."', () => {
133 | assert.strictEqual(textOverflowExchange('my name is linhe', 10), 'my name is...');
134 | });
135 | test("exchangeOrder('ascend')=>asc", () => {
136 | assert.strictEqual(exchangeOrder('ascend'), 'asc');
137 | });
138 | test("exchangeOrder('descend')=>desc", () => {
139 | assert.strictEqual(exchangeOrder('descend'), 'desc');
140 | });
141 | test('isEqualArr([1,2,3],[1,2,3])=>true', () => {
142 | assert.strictEqual(isEqualArr(['1', '2', '3'], ['1', '2', '3']), true);
143 | });
144 | /**
145 | * checkExist
146 | */
147 | describe('checkExist', () => {
148 | test(' undefined => false ', () => {
149 | assert.strictEqual(checkExist(undefined), false);
150 | });
151 | test(" '' => false ", () => {
152 | assert.strictEqual(checkExist(''), false);
153 | });
154 | test(' null => false ', () => {
155 | assert.strictEqual(checkExist(null), false);
156 | });
157 | test(' name => false ', () => {
158 | assert.strictEqual(checkExist('name'), true);
159 | });
160 | });
161 | /**
162 | * getCssText
163 | */
164 | describe('getCssText', () => {
165 | test(" {height:'100px',width:'100px'} => height:100px;width:100px; ", () => {
166 | assert.strictEqual(
167 | getCssText({ height: '100px', width: '100px' }),
168 | 'height:100px;width:100px;'
169 | );
170 | });
171 | });
172 |
173 | /**
174 | * trim
175 | */
176 | describe('trim', () => {
177 | test("' 张三 '=> 张三 ", () => {
178 | assert.strictEqual(trim(' 张三 '), '张三');
179 | });
180 | test("' 张三'=> 张三 ", () => {
181 | assert.strictEqual(trim(' 张三'), '张三');
182 | });
183 | test("'张三 '=> 张三", () => {
184 | assert.strictEqual(trim('张三 '), '张三');
185 | });
186 | test("'张 三'=> 张三", () => {
187 | assert.strictEqual(trim('张 三'), '张 三');
188 | });
189 | });
190 |
191 | /**
192 | * trimAll
193 | */
194 | describe('trimAll', () => {
195 | test(' . 12 3 => .123', () => {
196 | assert.strictEqual(trimAll(' . 12 3 '), '.123');
197 | });
198 | test(' . 12 3 => .123', () => {
199 | assert.strictEqual(trimAll(' . 12 3'), '.123');
200 | });
201 | test('. 12 3 => .123', () => {
202 | assert.strictEqual(trimAll('. 12 3'), '.123');
203 | });
204 | });
205 |
206 | describe('transformArray Test', () => {
207 | test('return the two-dimensional array', () => {
208 | const arr = ['1', '2', '3', '4', '5', '6'];
209 | expect(transformArray(arr, 2)).toEqual([
210 | ['1', '2'],
211 | ['3', '4'],
212 | ['5', '6'],
213 | ]);
214 | });
215 | });
216 |
217 | describe('IsEmpty Test', () => {
218 | test('return true if value is empty string', () => {
219 | expect(isEmpty('')).toBeTruthy();
220 | });
221 |
222 | test('return true if value is null', () => {
223 | expect(isEmpty(null)).toBeTruthy();
224 | });
225 |
226 | test('return true if value is undefined', () => {
227 | expect(isEmpty(undefined)).toBeTruthy();
228 | });
229 |
230 | test('return true if value is empty array', () => {
231 | expect(isEmpty([])).toBeTruthy();
232 | });
233 |
234 | test('return true if value is empty object', () => {
235 | expect(isEmpty({})).toBeTruthy();
236 | });
237 |
238 | test('return false if value is other conditions', () => {
239 | expect(isEmpty('123')).toBeFalsy();
240 | expect(isEmpty([1])).toBeFalsy();
241 | expect(isEmpty({ id: 1 })).toBeFalsy();
242 | });
243 | });
244 |
245 | describe('isObj Test', () => {
246 | test('return true if value is object', () => {
247 | expect(isObj({})).toBeTruthy();
248 | });
249 | test('return false if value is not object', () => {
250 | expect(isObj('123')).toBeFalsy();
251 | });
252 | });
253 |
254 | describe('removeEmpty Test', () => {
255 | test('return null if value is not obj', () => {
256 | expect(removeEmpty('123')).toBeUndefined();
257 | });
258 | test('return processed data if object includes undefined', () => {
259 | expect(removeEmpty({ a: 'test', b: undefined, c: { d: undefined } })).toEqual({
260 | a: 'test',
261 | c: {},
262 | });
263 | });
264 | });
265 | describe('mergeDeep test', () => {
266 | test('basic var', () => {
267 | expect(mergeDeep({ a: 123, c: 321 }, { a: 'cover', b: 456 })).toEqual({
268 | a: 'cover',
269 | b: 456,
270 | c: 321,
271 | });
272 | });
273 | test('complex var', () => {
274 | expect(
275 | mergeDeep(
276 | { a: 123, b: 321, innerObj: { a: 123, c: 456 } },
277 | { a: 'cover', c: 456, innerObj: { a: 'cover', b: 321 } }
278 | )
279 | ).toEqual({
280 | a: 'cover',
281 | b: 321,
282 | c: 456,
283 | innerObj: { a: 'cover', b: 321, c: 456 },
284 | });
285 | });
286 | test('empty var', () => {
287 | expect(mergeDeep(null, null)).toEqual(null);
288 | expect(mergeDeep({ name: 1 }, null)).toEqual({ name: 1 });
289 | expect(mergeDeep(null, { name: 2 })).toEqual({ name: 2 });
290 | });
291 | test('_isMergeAtom case', () => {
292 | expect(
293 | mergeDeep({ a: 123, c: 321 }, { a: 'cover', b: 456, _isMergeAtom: true })
294 | ).toEqual({ a: 'cover', b: 456 });
295 | });
296 | });
297 | describe('generateFullUrlPath test', () => {
298 | expect(generateFullUrlPath('/test/getUrlPathname', { a: 1, b: 2 })).toEqual(
299 | '/test/getUrlPathname?a=1&b=2'
300 | );
301 | expect(generateFullUrlPath('/test/getUrlPathname', { a: 1, b: undefined })).toEqual(
302 | '/test/getUrlPathname?a=1&b=undefined'
303 | );
304 | expect(generateFullUrlPath('/test/getUrlPathname', { a: 1, b: null })).toEqual(
305 | '/test/getUrlPathname?a=1&b=null'
306 | );
307 | expect(generateFullUrlPath('/test/getUrlPathname', { a: 1, b: '' })).toEqual(
308 | '/test/getUrlPathname?a=1&b='
309 | );
310 | });
311 | describe('getQueryParameters test', () => {
312 | expect(
313 | getQueryParameters(
314 | '?metaType=1&tabsKey=&tableId=1&dataSourceType=1&name=t_dtinsight_test'
315 | )
316 | ).toEqual({
317 | dataSourceType: '1',
318 | metaType: '1',
319 | name: 't_dtinsight_test',
320 | tableId: '1',
321 | tabsKey: '',
322 | });
323 | expect(getQueryParameters('?a=1&b=2')).toEqual({ a: '1', b: '2' });
324 | expect(getQueryParameters('?a=1&b=undefined')).toEqual({
325 | a: '1',
326 | b: undefined,
327 | });
328 | expect(getQueryParameters('?a=1&b=null')).toEqual({ a: '1', b: null });
329 | });
330 | });
331 |
--------------------------------------------------------------------------------
/tsconfig.eslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": ".",
4 | "resolveJsonModule": true
5 | },
6 | "include": ["**/*.ts", "**/*.js"]
7 | }
8 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* 基础配置 */
4 | "target": "esnext",
5 | "lib": ["dom", "DOM.Iterable", "esnext"],
6 | "removeComments": false,
7 | "declaration": true,
8 | "sourceMap": true,
9 |
10 | /* 强类型检查配置 */
11 | "strict": true,
12 | "noImplicitAny": false,
13 |
14 | /* 模块分析配置 */
15 | "baseUrl": ".",
16 | "outDir": "./lib",
17 | "esModuleInterop": true,
18 | "moduleResolution": "node",
19 | "resolveJsonModule": true
20 | },
21 | "include": ["src"]
22 | }
23 |
--------------------------------------------------------------------------------