youtil 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
- # 1.0.0 (2022-11-14)
1
+ # CHANGELOG
2
+
3
+ ## 1.0.2 (2023-02-09)
4
+
5
+ * 增加`encodeHtml`、`decodeHtml`、`deepCopy`方法;
6
+
7
+ ## 1.0.1 (2023-02-09)
8
+
9
+ * js改ts;
10
+ * `main`修改为`dist/index.js`;
11
+ * 增加简单的单侧;
12
+
13
+ ## 1.0.0 (2022-11-14)
2
14
 
3
15
  * 初始化第一个版本;
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 小茗同学
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # feutil
1
+ # youtil
2
2
 
3
- 存放与框架(Vue、React等)、环境(Nodejs、Web等)无关的通用方法工具库。
3
+ 油梯,一个与框架(Vue、React等)、环境(Nodejs、Web等)无关的小巧、精简、实用的JavaScript工具库
@@ -0,0 +1,99 @@
1
+ interface IShowLoadingConfig {
2
+ hasMask?: boolean;
3
+ maskColor?: string;
4
+ cancelInline?: boolean;
5
+ onCancel?: Function;
6
+ id?: string;
7
+ }
8
+ declare const _default: {
9
+ /**
10
+ * 将日期格式化成指定格式的字符串
11
+ * @param date 要格式化的日期,不传时默认当前时间,也可以是一个时间戳
12
+ * @param fmt 目标字符串格式,支持的字符有:y,M,d,q,w,H,h,m,S,默认:yyyy-MM-dd HH:mm:ss
13
+ * @returns 返回格式化后的日期字符串
14
+ */
15
+ formatDate(date?: Date | number, fmt?: string): string;
16
+ /**
17
+ * 将字符串解析成日期
18
+ * @param str 输入的日期字符串,如'2014-09-13'
19
+ * @param fmt 字符串格式,默认'yyyy-MM-dd',支持如下:y、M、d、H、m、s、S,不支持w和q
20
+ * @returns 解析后的Date类型日期
21
+ */
22
+ parseDate(str: string, fmt?: string): Date;
23
+ /**
24
+ * 显示全局loading
25
+ * @param {*} text
26
+ * @param {*} seconds
27
+ * @param {*} options
28
+ */
29
+ showLoading(text?: string, seconds?: number, config?: IShowLoadingConfig): void;
30
+ hideLoading(): void;
31
+ /**
32
+ * 从URL中获取某个参数,如果不存在返回 undefined ,如果存在多个同名参数,返回第一个匹配值
33
+ * getParam('a', '?a=1&b=&c=3&c=33#abc') // '1'
34
+ * getParam('b', '?a=1&b=&c=3&c=33#abc') // ''
35
+ * getParam('c', '?a=1&b=&c=3&c=33#abc') // 3
36
+ * getParam('d', '?a=1&b=&c=3&c=33#abc') // undefined
37
+ * @param {*} name 参数名
38
+ * @param {*} url 要获取的URL,默认当前地址
39
+ */
40
+ getParam(name: string, url?: string): string;
41
+ /**
42
+ * 从URL中获取int参数
43
+ * @param {*} name 参数名
44
+ * @param {*} url 要获取的URL,默认当前地址
45
+ */
46
+ getParamInt(name: string, url?: string): number;
47
+ /**
48
+ * 获取某个URL的全部参数
49
+ * getParams('?a=1&b=2#cc') // {a: '1', b: '2'}
50
+ * @param url
51
+ * @returns 参数对象
52
+ */
53
+ getParams(url?: string): any;
54
+ /**
55
+ * 给URL设置参数,如果已经存在,替换之,兼容hash存在的情况
56
+ * setParam('a', '123', '?a=1&b=2&a=3#d') // '?a=123&b=2&a=123#d'
57
+ * setParam('d', '444', '?a=1&b=2&a=3#d') // '?a=1&b=2&a=3&d=444#d'
58
+ * @param {Object} name 参数名
59
+ * @param {Object} value 参数值
60
+ * @param {Object} url 如果不传默认当前页面URL
61
+ */
62
+ setParam(name: string, value: string | number, url?: string): string;
63
+ /**
64
+ * 删除URL中某个参数
65
+ * delParam('a', '?a=1&b=2&a=3#d') // '?b=2#d'
66
+ * delParam('b', '?a=1&b=2&a=3#d') // '?a=1&a=3#d'
67
+ * delParam('a', '?a=1#d') // '#d'
68
+ * @param name 参数名
69
+ * @param url 要删除的URL,默认当前页面URL
70
+ * @returns 处理完后的URL
71
+ */
72
+ delParam(name: string, url: string): string;
73
+ /**
74
+ * 休息一段时间,单位毫秒
75
+ * 示例:await sleep(200); // 休息200毫秒
76
+ * @param time 要休息的时间,单位毫秒,不传默认0
77
+ * @returns
78
+ */
79
+ sleep: (time?: number) => Promise<unknown>;
80
+ /**
81
+ * 基于JSON的简单深拷贝
82
+ * @param obj 要复制的对象,非对象格式会直接返回
83
+ * @returns
84
+ */
85
+ deepCopy: (obj: any) => any;
86
+ /**
87
+ * HTML编码,例如将 【"】 变成 【&quot;】
88
+ * @param {*} html 待编码的原始字符串
89
+ * @returns
90
+ */
91
+ encodeHtml(html: string): string;
92
+ /**
93
+ * HTML解码,例如将 【&quot;】 变成 【"】
94
+ * @param {*} html 已经被HTML编码过的字符串
95
+ * @returns
96
+ */
97
+ decodeHtml(html: string): string;
98
+ };
99
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,252 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = {
4
+ /**
5
+ * 将日期格式化成指定格式的字符串
6
+ * @param date 要格式化的日期,不传时默认当前时间,也可以是一个时间戳
7
+ * @param fmt 目标字符串格式,支持的字符有:y,M,d,q,w,H,h,m,S,默认:yyyy-MM-dd HH:mm:ss
8
+ * @returns 返回格式化后的日期字符串
9
+ */
10
+ formatDate(date, fmt) {
11
+ if (!date) {
12
+ return '';
13
+ }
14
+ date = typeof date === 'number' ? new Date(date) : date;
15
+ fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
16
+ const obj = {
17
+ y: date.getFullYear(),
18
+ M: date.getMonth() + 1,
19
+ d: date.getDate(),
20
+ q: Math.floor((date.getMonth() + 3) / 3),
21
+ w: date.getDay(),
22
+ H: date.getHours(),
23
+ h: date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
24
+ m: date.getMinutes(),
25
+ s: date.getSeconds(),
26
+ S: date.getMilliseconds(), // 毫秒
27
+ };
28
+ const week = ['天', '一', '二', '三', '四', '五', '六'];
29
+ // eslint-disable-next-line guard-for-in
30
+ for (const i in obj) {
31
+ fmt = fmt.replace(new RegExp(`${i}+`, 'g'), function (m) {
32
+ let val = `${obj[i]}`;
33
+ if (i === 'w') {
34
+ return (m.length > 2 ? '星期' : '周') + week[val];
35
+ }
36
+ for (let j = 0, len = val.length; j < m.length - len; j++) {
37
+ val = `0${val}`;
38
+ }
39
+ return m.length === 1 ? val : val.substring(val.length - m.length);
40
+ });
41
+ }
42
+ return fmt;
43
+ },
44
+ /**
45
+ * 将字符串解析成日期
46
+ * @param str 输入的日期字符串,如'2014-09-13'
47
+ * @param fmt 字符串格式,默认'yyyy-MM-dd',支持如下:y、M、d、H、m、s、S,不支持w和q
48
+ * @returns 解析后的Date类型日期
49
+ */
50
+ parseDate(str, fmt) {
51
+ fmt = fmt || 'yyyy-MM-dd';
52
+ const obj = { y: 0, M: 1, d: 0, H: 0, h: 0, m: 0, s: 0, S: 0 };
53
+ fmt.replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g, function (m, $1, $2, $3, $4) {
54
+ str = str.replace(new RegExp(`${$1}(\\d{${$2.length}})${$4}`), function (_m, _$1) {
55
+ obj[$3] = parseInt(_$1);
56
+ return '';
57
+ });
58
+ return '';
59
+ });
60
+ obj.M--; // 月份是从0开始的,所以要减去1
61
+ const date = new Date(obj.y, obj.M, obj.d, obj.H, obj.m, obj.s);
62
+ if (obj.S !== 0) {
63
+ date.setMilliseconds(obj.S); // 如果设置了毫秒
64
+ }
65
+ return date;
66
+ },
67
+ /**
68
+ * 显示全局loading
69
+ * @param {*} text
70
+ * @param {*} seconds
71
+ * @param {*} options
72
+ */
73
+ showLoading(text = '请稍候', seconds = 10, config = {}) {
74
+ const defaultConfig = {
75
+ hasMask: true,
76
+ maskColor: 'transparent',
77
+ onCancel: null,
78
+ cancelInline: false,
79
+ id: 'com_global_page_loading',
80
+ };
81
+ config = Object.assign({}, defaultConfig, config);
82
+ const { id } = config;
83
+ const timeoutKey = `_${id}_timeout`;
84
+ if (window[timeoutKey]) {
85
+ clearTimeout(window[timeoutKey]);
86
+ }
87
+ let dom = document.getElementById(id);
88
+ if (!dom) {
89
+ dom = document.createElement('div');
90
+ dom.id = id;
91
+ dom.className = id;
92
+ document.body.append(dom);
93
+ }
94
+ const styleId = `${id}_style`;
95
+ if (!document.getElementById(styleId)) {
96
+ const style = document.createElement('style');
97
+ style.id = styleId;
98
+ style.innerHTML = `
99
+ .${id} {
100
+ position: fixed;
101
+ top: calc(50vh - 60px);
102
+ left: calc(50vw - 60px);
103
+ width: 120px;
104
+ height: 120px;
105
+ z-index: 8000;
106
+ background: rgba(0, 0, 0, 0.6);
107
+ border-radius: 8px;
108
+ text-align: center;
109
+ color: white;
110
+ padding-top: 20px;
111
+ }
112
+ .${id} img {
113
+ width: 50px;
114
+ margin-bottom: 10px;
115
+ }`;
116
+ document.head.appendChild(style);
117
+ }
118
+ dom.innerHTML = `
119
+ ${config.hasMask ? `<div class="mask-wrapper" style="background-color: ${config.maskColor}"></div>` : ''}
120
+ <div class="loading-wrapper">
121
+ <div class="loading-content">
122
+ <img src="//img.alicdn.com/tfs/TB1bnUsQBLoK1RjSZFuXXXn0XXa-32-32.svg" alt="加载中">
123
+ <div>${text}${config.cancelInline ? ' ' : '</div>'}
124
+ ${config.onCancel ? '<a href="javascript:;" class="cancel">取消</a>' : ''}
125
+ ${config.cancelInline ? '</div>' : ''}
126
+ </div>
127
+ </div>`;
128
+ if (config.onCancel) {
129
+ const btn = dom.querySelector('.cancel');
130
+ btn && btn.addEventListener('click', () => {
131
+ this.hideLoading();
132
+ config.onCancel();
133
+ });
134
+ }
135
+ dom.style.display = 'block';
136
+ if (seconds > 0) {
137
+ window[timeoutKey] = setTimeout(() => {
138
+ this.hideLoading();
139
+ }, seconds * 1000);
140
+ }
141
+ },
142
+ // 隐藏全局loading
143
+ hideLoading() {
144
+ const id = 'com_global_page_loading';
145
+ const loading = document.getElementById(id);
146
+ if (loading) {
147
+ loading.style.display = 'none';
148
+ }
149
+ },
150
+ /**
151
+ * 从URL中获取某个参数,如果不存在返回 undefined ,如果存在多个同名参数,返回第一个匹配值
152
+ * getParam('a', '?a=1&b=&c=3&c=33#abc') // '1'
153
+ * getParam('b', '?a=1&b=&c=3&c=33#abc') // ''
154
+ * getParam('c', '?a=1&b=&c=3&c=33#abc') // 3
155
+ * getParam('d', '?a=1&b=&c=3&c=33#abc') // undefined
156
+ * @param {*} name 参数名
157
+ * @param {*} url 要获取的URL,默认当前地址
158
+ */
159
+ getParam(name, url = location.search) {
160
+ return (new RegExp(`(^|\\?|&)${name}=(.*?)(?=&|#|$)`, 'g').exec(url) || [])[2];
161
+ },
162
+ /**
163
+ * 从URL中获取int参数
164
+ * @param {*} name 参数名
165
+ * @param {*} url 要获取的URL,默认当前地址
166
+ */
167
+ getParamInt(name, url = location.search) {
168
+ return parseInt(this.getParam(name, url) || '0', 10);
169
+ },
170
+ /**
171
+ * 获取某个URL的全部参数
172
+ * getParams('?a=1&b=2#cc') // {a: '1', b: '2'}
173
+ * @param url
174
+ * @returns 参数对象
175
+ */
176
+ getParams(url = location.search) {
177
+ const search = ((url || '').split('?').pop() || '').split('#')[0] || '';
178
+ const params = {};
179
+ search.split('&').map(item => item.split('=')).forEach(([key, value]) => {
180
+ params[key] = value || '';
181
+ });
182
+ return params;
183
+ },
184
+ /**
185
+ * 给URL设置参数,如果已经存在,替换之,兼容hash存在的情况
186
+ * setParam('a', '123', '?a=1&b=2&a=3#d') // '?a=123&b=2&a=123#d'
187
+ * setParam('d', '444', '?a=1&b=2&a=3#d') // '?a=1&b=2&a=3&d=444#d'
188
+ * @param {Object} name 参数名
189
+ * @param {Object} value 参数值
190
+ * @param {Object} url 如果不传默认当前页面URL
191
+ */
192
+ setParam(name, value, url) {
193
+ url = url || `${location.pathname}${location.search}`;
194
+ // 如果参数已经存在,替换之
195
+ if (this.getParam(name, url) !== undefined) {
196
+ return url.replace(new RegExp(`(^|\\?|&)${name}=(.*?)(?=&|#|$)`, 'g'), `$1${name}=${value}`);
197
+ }
198
+ const [pathname, hash] = url.split('#'); // 处理存在hash的情况
199
+ return `${pathname}${pathname.indexOf('?') < 0 ? '?' : '&'}${name}=${value}${hash ? '#' : ''}${hash || ''}`;
200
+ },
201
+ /**
202
+ * 删除URL中某个参数
203
+ * delParam('a', '?a=1&b=2&a=3#d') // '?b=2#d'
204
+ * delParam('b', '?a=1&b=2&a=3#d') // '?a=1&a=3#d'
205
+ * delParam('a', '?a=1#d') // '#d'
206
+ * @param name 参数名
207
+ * @param url 要删除的URL,默认当前页面URL
208
+ * @returns 处理完后的URL
209
+ */
210
+ delParam(name, url) {
211
+ url = url || `${location.pathname}${location.search}`;
212
+ return url.replace(new RegExp(`(^|\\?|&)${name}=.*?(&|#|$)`, 'g'), (_m, $1, $2) => $2 === '&' ? $1 : $2);
213
+ },
214
+ /**
215
+ * 休息一段时间,单位毫秒
216
+ * 示例:await sleep(200); // 休息200毫秒
217
+ * @param time 要休息的时间,单位毫秒,不传默认0
218
+ * @returns
219
+ */
220
+ sleep: (time) => new Promise(resolve => setTimeout(resolve, time || 0)),
221
+ /**
222
+ * 基于JSON的简单深拷贝
223
+ * @param obj 要复制的对象,非对象格式会直接返回
224
+ * @returns
225
+ */
226
+ deepCopy: (obj) => {
227
+ if (!obj || typeof obj !== 'object') {
228
+ return obj;
229
+ }
230
+ return JSON.parse(JSON.stringify(obj));
231
+ },
232
+ /**
233
+ * HTML编码,例如将 【"】 变成 【&quot;】
234
+ * @param {*} html 待编码的原始字符串
235
+ * @returns
236
+ */
237
+ encodeHtml(html) {
238
+ const div = document.createElement('div');
239
+ div.innerText = html;
240
+ return div.innerHTML;
241
+ },
242
+ /**
243
+ * HTML解码,例如将 【&quot;】 变成 【"】
244
+ * @param {*} html 已经被HTML编码过的字符串
245
+ * @returns
246
+ */
247
+ decodeHtml(html) {
248
+ const div = document.createElement('div');
249
+ div.innerHTML = html;
250
+ return div.innerText;
251
+ },
252
+ };
package/package.json CHANGED
@@ -1,20 +1,25 @@
1
1
  {
2
2
  "name": "youtil",
3
- "version": "1.0.0",
4
- "description": "Front-ent util",
5
- "main": "src/index.js",
3
+ "version": "1.0.2",
4
+ "description": "油梯,一个与框架、环境无关的小巧、精简、实用的JavaScript工具库",
5
+ "main": "dist/index.js",
6
6
  "dependencies": {},
7
- "devDependencies": {},
7
+ "devDependencies": {
8
+ "jest": "^29.4.2",
9
+ "typescript": "^4.9.5"
10
+ },
8
11
  "scripts": {
9
- "test": "echo \"Error: no test specified\" && exit 1"
12
+ "test": "jest",
13
+ "build": "tsc -d",
14
+ "prepublishOnly": "npm run build"
10
15
  },
11
16
  "repository": {
12
17
  "type": "git",
13
18
  "url": "github.com/sxei/youtil"
14
19
  },
15
20
  "keywords": [
16
- "feutil"
21
+ "youtil"
17
22
  ],
18
23
  "author": "sxei",
19
- "license": "ISC"
20
- }
24
+ "license": "MIT"
25
+ }
package/src/index.js CHANGED
@@ -1,41 +1,46 @@
1
- export default {
1
+ "use strict";
2
+ exports.__esModule = true;
3
+ exports["default"] = {
2
4
  /**
3
5
  * 将日期格式化成指定格式的字符串
4
6
  * @param date 要格式化的日期,不传时默认当前时间,也可以是一个时间戳
5
7
  * @param fmt 目标字符串格式,支持的字符有:y,M,d,q,w,H,h,m,S,默认:yyyy-MM-dd HH:mm:ss
6
8
  * @returns 返回格式化后的日期字符串
7
9
  */
8
- formatDate(date, fmt) {
10
+ formatDate: function (date, fmt) {
9
11
  if (!date) {
10
12
  return '';
11
13
  }
12
14
  date = typeof date === 'number' ? new Date(date) : date;
13
15
  fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
14
- const obj = {
15
- y: date.getFullYear(), // 年份,注意必须用getFullYear
16
- M: date.getMonth() + 1, // 月份,注意是从0-11
17
- d: date.getDate(), // 日期
18
- q: Math.floor((date.getMonth() + 3) / 3), // 季度
19
- w: date.getDay(), // 星期,注意是0-6
20
- H: date.getHours(), // 24小时制
21
- h: date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 12小时制
22
- m: date.getMinutes(), // 分钟
23
- s: date.getSeconds(), // 秒
24
- S: date.getMilliseconds(), // 毫秒
16
+ var obj = {
17
+ y: date.getFullYear(),
18
+ M: date.getMonth() + 1,
19
+ d: date.getDate(),
20
+ q: Math.floor((date.getMonth() + 3) / 3),
21
+ w: date.getDay(),
22
+ H: date.getHours(),
23
+ h: date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
24
+ m: date.getMinutes(),
25
+ s: date.getSeconds(),
26
+ S: date.getMilliseconds()
25
27
  };
26
- const week = ['天', '一', '二', '三', '四', '五', '六'];
27
- // eslint-disable-next-line guard-for-in
28
- for (const i in obj) {
29
- fmt = fmt.replace(new RegExp(`${i}+`, 'g'), function (m) {
30
- let val = `${obj[i]}`;
28
+ var week = ['天', '一', '二', '三', '四', '五', '六'];
29
+ var _loop_1 = function (i) {
30
+ fmt = fmt.replace(new RegExp("".concat(i, "+"), 'g'), function (m) {
31
+ var val = "".concat(obj[i]);
31
32
  if (i === 'w') {
32
33
  return (m.length > 2 ? '星期' : '周') + week[val];
33
34
  }
34
- for (let j = 0, len = val.length; j < m.length - len; j++) {
35
- val = `0${val}`;
35
+ for (var j = 0, len = val.length; j < m.length - len; j++) {
36
+ val = "0".concat(val);
36
37
  }
37
38
  return m.length === 1 ? val : val.substring(val.length - m.length);
38
39
  });
40
+ };
41
+ // eslint-disable-next-line guard-for-in
42
+ for (var i in obj) {
43
+ _loop_1(i);
39
44
  }
40
45
  return fmt;
41
46
  },
@@ -45,18 +50,18 @@ export default {
45
50
  * @param fmt 字符串格式,默认'yyyy-MM-dd',支持如下:y、M、d、H、m、s、S,不支持w和q
46
51
  * @returns 解析后的Date类型日期
47
52
  */
48
- parseDate(str, fmt) {
53
+ parseDate: function (str, fmt) {
49
54
  fmt = fmt || 'yyyy-MM-dd';
50
- const obj = { y: 0, M: 1, d: 0, H: 0, h: 0, m: 0, s: 0, S: 0 };
55
+ var obj = { y: 0, M: 1, d: 0, H: 0, h: 0, m: 0, s: 0, S: 0 };
51
56
  fmt.replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g, function (m, $1, $2, $3, $4) {
52
- str = str.replace(new RegExp(`${$1}(\\d{${$2.length}})${$4}`), function (_m, _$1) {
57
+ str = str.replace(new RegExp("".concat($1, "(\\d{").concat($2.length, "})").concat($4)), function (_m, _$1) {
53
58
  obj[$3] = parseInt(_$1);
54
59
  return '';
55
60
  });
56
61
  return '';
57
62
  });
58
63
  obj.M--; // 月份是从0开始的,所以要减去1
59
- const date = new Date(obj.y, obj.M, obj.d, obj.H, obj.m, obj.s);
64
+ var date = new Date(obj.y, obj.M, obj.d, obj.H, obj.m, obj.s);
60
65
  if (obj.S !== 0) {
61
66
  date.setMilliseconds(obj.S); // 如果设置了毫秒
62
67
  }
@@ -68,79 +73,57 @@ export default {
68
73
  * @param {*} seconds
69
74
  * @param {*} options
70
75
  */
71
- showLoading(text = '请稍候', seconds = 10, config = {}) {
72
- const defaultConfig = {
76
+ showLoading: function (text, seconds, config) {
77
+ var _this = this;
78
+ if (text === void 0) { text = '请稍候'; }
79
+ if (seconds === void 0) { seconds = 10; }
80
+ if (config === void 0) { config = {}; }
81
+ var defaultConfig = {
73
82
  hasMask: true,
74
83
  maskColor: 'transparent',
75
84
  onCancel: null,
76
85
  cancelInline: false,
77
- id: 'com_global_page_loading',
86
+ id: 'com_global_page_loading'
78
87
  };
79
88
  config = Object.assign({}, defaultConfig, config);
80
- const { id } = config;
81
- const timeoutKey = `_${id}_timeout`;
89
+ var id = config.id;
90
+ var timeoutKey = "_".concat(id, "_timeout");
82
91
  if (window[timeoutKey]) {
83
92
  clearTimeout(window[timeoutKey]);
84
93
  }
85
- let dom = document.getElementById(id);
94
+ var dom = document.getElementById(id);
86
95
  if (!dom) {
87
96
  dom = document.createElement('div');
88
97
  dom.id = id;
89
98
  dom.className = id;
90
99
  document.body.append(dom);
91
100
  }
92
- const styleId = `${id}_style`;
101
+ var styleId = "".concat(id, "_style");
93
102
  if (!document.getElementById(styleId)) {
94
- const style = document.createElement('style');
103
+ var style = document.createElement('style');
95
104
  style.id = styleId;
96
- style.innerHTML = `
97
- .${id} {
98
- position: fixed;
99
- top: calc(50vh - 60px);
100
- left: calc(50vw - 60px);
101
- width: 120px;
102
- height: 120px;
103
- z-index: 8000;
104
- background: rgba(0, 0, 0, 0.6);
105
- border-radius: 8px;
106
- text-align: center;
107
- color: white;
108
- padding-top: 20px;
109
- }
110
- .${id} img {
111
- width: 50px;
112
- margin-bottom: 10px;
113
- }`;
105
+ style.innerHTML = "\n .".concat(id, " {\n position: fixed;\n top: calc(50vh - 60px);\n left: calc(50vw - 60px);\n width: 120px;\n height: 120px;\n z-index: 8000;\n background: rgba(0, 0, 0, 0.6);\n border-radius: 8px;\n text-align: center;\n color: white;\n padding-top: 20px;\n }\n .").concat(id, " img {\n width: 50px;\n margin-bottom: 10px;\n }");
114
106
  document.head.appendChild(style);
115
107
  }
116
- dom.innerHTML = `
117
- ${config.hasMask ? `<div class="mask-wrapper" style="background-color: ${config.maskColor}"></div>` : ''}
118
- <div class="loading-wrapper">
119
- <div class="loading-content">
120
- <img src="//img.alicdn.com/tfs/TB1bnUsQBLoK1RjSZFuXXXn0XXa-32-32.svg" alt="加载中">
121
- <div>${text}${config.cancelInline ? ' ' : '</div>'}
122
- ${config.onCancel ? '<a href="javascript:;" class="cancel">取消</a>' : ''}
123
- ${config.cancelInline ? '</div>' : ''}
124
- </div>
125
- </div>`;
108
+ dom.innerHTML = "\n ".concat(config.hasMask ? "<div class=\"mask-wrapper\" style=\"background-color: ".concat(config.maskColor, "\"></div>") : '', "\n <div class=\"loading-wrapper\">\n <div class=\"loading-content\">\n <img src=\"//img.alicdn.com/tfs/TB1bnUsQBLoK1RjSZFuXXXn0XXa-32-32.svg\" alt=\"\u52A0\u8F7D\u4E2D\">\n <div>").concat(text).concat(config.cancelInline ? ' ' : '</div>', "\n ").concat(config.onCancel ? '<a href="javascript:;" class="cancel">取消</a>' : '', "\n ").concat(config.cancelInline ? '</div>' : '', "\n </div>\n </div>");
126
109
  if (config.onCancel) {
127
- const btn = dom.querySelector('.cancel');
128
- btn && btn.addEventListener('click', () => {
129
- this.hideLoading();
110
+ var btn = dom.querySelector('.cancel');
111
+ btn && btn.addEventListener('click', function () {
112
+ _this.hideLoading();
130
113
  config.onCancel();
131
114
  });
132
115
  }
133
116
  dom.style.display = 'block';
134
117
  if (seconds > 0) {
135
- window[timeoutKey] = setTimeout(() => {
136
- this.hideLoading();
118
+ window[timeoutKey] = setTimeout(function () {
119
+ _this.hideLoading();
137
120
  }, seconds * 1000);
138
121
  }
139
122
  },
140
123
  // 隐藏全局loading
141
- hideLoading() {
142
- const id = 'com_global_page_loading';
143
- const loading = document.getElementById(id);
124
+ hideLoading: function () {
125
+ var id = 'com_global_page_loading';
126
+ var loading = document.getElementById(id);
144
127
  if (loading) {
145
128
  loading.style.display = 'none';
146
129
  }
@@ -154,27 +137,31 @@ export default {
154
137
  * @param {*} name 参数名
155
138
  * @param {*} url 要获取的URL,默认当前地址
156
139
  */
157
- getParam(name, url = location.search) {
158
- return (new RegExp(`(^|\\?|&)${name}=(.*?)(?=&|#|$)`, 'g').exec(url) || [])[2];
140
+ getParam: function (name, url) {
141
+ if (url === void 0) { url = location.search; }
142
+ return (new RegExp("(^|\\?|&)".concat(name, "=(.*?)(?=&|#|$)"), 'g').exec(url) || [])[2];
159
143
  },
160
144
  /**
161
145
  * 从URL中获取int参数
162
146
  * @param {*} name 参数名
163
147
  * @param {*} url 要获取的URL,默认当前地址
164
148
  */
165
- getParamInt(name, url = location.search) {
149
+ getParamInt: function (name, url) {
150
+ if (url === void 0) { url = location.search; }
166
151
  return parseInt(this.getParam(name, url) || '0', 10);
167
152
  },
168
153
  /**
169
154
  * 获取某个URL的全部参数
170
155
  * getParams('?a=1&b=2#cc') // {a: '1', b: '2'}
171
- * @param url
156
+ * @param url
172
157
  * @returns 参数对象
173
158
  */
174
- getParams(url = location.search) {
175
- const search = ((url || '').split('?').pop() || '').split('#')[0] || '';
176
- const params = {};
177
- search.split('&').map(item => item.split('=')).forEach(([key, value]) => {
159
+ getParams: function (url) {
160
+ if (url === void 0) { url = location.search; }
161
+ var search = ((url || '').split('?').pop() || '').split('#')[0] || '';
162
+ var params = {};
163
+ search.split('&').map(function (item) { return item.split('='); }).forEach(function (_a) {
164
+ var key = _a[0], value = _a[1];
178
165
  params[key] = value || '';
179
166
  });
180
167
  return params;
@@ -187,14 +174,14 @@ export default {
187
174
  * @param {Object} value 参数值
188
175
  * @param {Object} url 如果不传默认当前页面URL
189
176
  */
190
- setParam(name, value, url) {
191
- url = url || `${location.pathname}${location.search}`;
177
+ setParam: function (name, value, url) {
178
+ url = url || "".concat(location.pathname).concat(location.search);
192
179
  // 如果参数已经存在,替换之
193
180
  if (this.getParam(name, url) !== undefined) {
194
- return url.replace(new RegExp(`(^|\\?|&)${name}=(.*?)(?=&|#|$)`, 'g'), `$1${name}=${value}`);
181
+ return url.replace(new RegExp("(^|\\?|&)".concat(name, "=(.*?)(?=&|#|$)"), 'g'), "$1".concat(name, "=").concat(value));
195
182
  }
196
- const [pathname, hash] = url.split('#'); // 处理存在hash的情况
197
- return `${pathname}${pathname.indexOf('?') < 0 ? '?' : '&'}${name}=${value}${hash ? '#' : ''}${hash || ''}`;
183
+ var _a = url.split('#'), pathname = _a[0], hash = _a[1]; // 处理存在hash的情况
184
+ return "".concat(pathname).concat(pathname.indexOf('?') < 0 ? '?' : '&').concat(name, "=").concat(value).concat(hash ? '#' : '').concat(hash || '');
198
185
  },
199
186
  /**
200
187
  * 删除URL中某个参数
@@ -205,13 +192,15 @@ export default {
205
192
  * @param url 要删除的URL,默认当前页面URL
206
193
  * @returns 处理完后的URL
207
194
  */
208
- delParam(name, url) {
209
- url = url || `${location.pathname}${location.search}`;
210
- return url.replace(new RegExp(`(^|\\?|&)${name}=.*?(&|#|$)`, 'g'), (_m, $1, $2) => $2 === '&' ? $1 : $2);
195
+ delParam: function (name, url) {
196
+ url = url || "".concat(location.pathname).concat(location.search);
197
+ return url.replace(new RegExp("(^|\\?|&)".concat(name, "=.*?(&|#|$)"), 'g'), function (_m, $1, $2) { return $2 === '&' ? $1 : $2; });
211
198
  },
212
199
  /**
213
- * 延迟一段时间,单位毫秒
214
- * await sleep(200) // 休息200毫秒
200
+ * 休息一段时间,单位毫秒
201
+ * 示例:await sleep(200); // 休息200毫秒
202
+ * @param time 要休息的时间,单位毫秒,不传默认0
203
+ * @returns
215
204
  */
216
- sleep: (sec) => new Promise(resolve => setTimeout(resolve, sec)),
205
+ sleep: function (time) { return new Promise(function (resolve) { return setTimeout(resolve, time || 0); }); }
217
206
  };
package/src/index.ts ADDED
@@ -0,0 +1,257 @@
1
+ interface IShowLoadingConfig {
2
+ hasMask?: boolean;
3
+ maskColor?: string;
4
+ cancelInline?: boolean;
5
+ onCancel?: Function;
6
+ id?: string,
7
+ }
8
+ export default {
9
+ /**
10
+ * 将日期格式化成指定格式的字符串
11
+ * @param date 要格式化的日期,不传时默认当前时间,也可以是一个时间戳
12
+ * @param fmt 目标字符串格式,支持的字符有:y,M,d,q,w,H,h,m,S,默认:yyyy-MM-dd HH:mm:ss
13
+ * @returns 返回格式化后的日期字符串
14
+ */
15
+ formatDate(date?: Date | number, fmt?: string) {
16
+ if (!date) {
17
+ return '';
18
+ }
19
+ date = typeof date === 'number' ? new Date(date) : date;
20
+ fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
21
+ const obj: any = {
22
+ y: date.getFullYear(), // 年份,注意必须用getFullYear
23
+ M: date.getMonth() + 1, // 月份,注意是从0-11
24
+ d: date.getDate(), // 日期
25
+ q: Math.floor((date.getMonth() + 3) / 3), // 季度
26
+ w: date.getDay(), // 星期,注意是0-6
27
+ H: date.getHours(), // 24小时制
28
+ h: date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 12小时制
29
+ m: date.getMinutes(), // 分钟
30
+ s: date.getSeconds(), // 秒
31
+ S: date.getMilliseconds(), // 毫秒
32
+ };
33
+ const week: any = ['天', '一', '二', '三', '四', '五', '六'];
34
+ // eslint-disable-next-line guard-for-in
35
+ for (const i in obj) {
36
+ fmt = fmt.replace(new RegExp(`${i}+`, 'g'), function (m) {
37
+ let val = `${obj[i]}`;
38
+ if (i === 'w') {
39
+ return (m.length > 2 ? '星期' : '周') + week[val];
40
+ }
41
+ for (let j = 0, len = val.length; j < m.length - len; j++) {
42
+ val = `0${val}`;
43
+ }
44
+ return m.length === 1 ? val : val.substring(val.length - m.length);
45
+ });
46
+ }
47
+ return fmt;
48
+ },
49
+ /**
50
+ * 将字符串解析成日期
51
+ * @param str 输入的日期字符串,如'2014-09-13'
52
+ * @param fmt 字符串格式,默认'yyyy-MM-dd',支持如下:y、M、d、H、m、s、S,不支持w和q
53
+ * @returns 解析后的Date类型日期
54
+ */
55
+ parseDate(str: string, fmt?: string) {
56
+ fmt = fmt || 'yyyy-MM-dd';
57
+ const obj: any = { y: 0, M: 1, d: 0, H: 0, h: 0, m: 0, s: 0, S: 0 };
58
+ fmt.replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g, function (m, $1, $2, $3, $4) {
59
+ str = str.replace(new RegExp(`${$1}(\\d{${$2.length}})${$4}`), function (_m, _$1) {
60
+ obj[$3] = parseInt(_$1);
61
+ return '';
62
+ });
63
+ return '';
64
+ });
65
+ obj.M--; // 月份是从0开始的,所以要减去1
66
+ const date = new Date(obj.y, obj.M, obj.d, obj.H, obj.m, obj.s);
67
+ if (obj.S !== 0) {
68
+ date.setMilliseconds(obj.S); // 如果设置了毫秒
69
+ }
70
+ return date;
71
+ },
72
+ /**
73
+ * 显示全局loading
74
+ * @param {*} text
75
+ * @param {*} seconds
76
+ * @param {*} options
77
+ */
78
+ showLoading(text = '请稍候', seconds = 10, config: IShowLoadingConfig = {}) {
79
+ const defaultConfig: IShowLoadingConfig = {
80
+ hasMask: true,
81
+ maskColor: 'transparent',
82
+ onCancel: null,
83
+ cancelInline: false,
84
+ id: 'com_global_page_loading',
85
+ };
86
+ config = Object.assign({}, defaultConfig, config);
87
+ const { id } = config;
88
+ const timeoutKey = `_${id}_timeout`;
89
+ if ((window as any)[timeoutKey]) {
90
+ clearTimeout((window as any)[timeoutKey]);
91
+ }
92
+ let dom = document.getElementById(id);
93
+ if (!dom) {
94
+ dom = document.createElement('div');
95
+ dom.id = id;
96
+ dom.className = id;
97
+ document.body.append(dom);
98
+ }
99
+ const styleId = `${id}_style`;
100
+ if (!document.getElementById(styleId)) {
101
+ const style = document.createElement('style');
102
+ style.id = styleId;
103
+ style.innerHTML = `
104
+ .${id} {
105
+ position: fixed;
106
+ top: calc(50vh - 60px);
107
+ left: calc(50vw - 60px);
108
+ width: 120px;
109
+ height: 120px;
110
+ z-index: 8000;
111
+ background: rgba(0, 0, 0, 0.6);
112
+ border-radius: 8px;
113
+ text-align: center;
114
+ color: white;
115
+ padding-top: 20px;
116
+ }
117
+ .${id} img {
118
+ width: 50px;
119
+ margin-bottom: 10px;
120
+ }`;
121
+ document.head.appendChild(style);
122
+ }
123
+ dom.innerHTML = `
124
+ ${config.hasMask ? `<div class="mask-wrapper" style="background-color: ${config.maskColor}"></div>` : ''}
125
+ <div class="loading-wrapper">
126
+ <div class="loading-content">
127
+ <img src="//img.alicdn.com/tfs/TB1bnUsQBLoK1RjSZFuXXXn0XXa-32-32.svg" alt="加载中">
128
+ <div>${text}${config.cancelInline ? ' ' : '</div>'}
129
+ ${config.onCancel ? '<a href="javascript:;" class="cancel">取消</a>' : ''}
130
+ ${config.cancelInline ? '</div>' : ''}
131
+ </div>
132
+ </div>`;
133
+ if (config.onCancel) {
134
+ const btn = dom.querySelector('.cancel');
135
+ btn && btn.addEventListener('click', () => {
136
+ this.hideLoading();
137
+ config.onCancel();
138
+ });
139
+ }
140
+ dom.style.display = 'block';
141
+ if (seconds > 0) {
142
+ (window as any)[timeoutKey] = setTimeout(() => {
143
+ this.hideLoading();
144
+ }, seconds * 1000);
145
+ }
146
+ },
147
+ // 隐藏全局loading
148
+ hideLoading() {
149
+ const id = 'com_global_page_loading';
150
+ const loading = document.getElementById(id);
151
+ if (loading) {
152
+ loading.style.display = 'none';
153
+ }
154
+ },
155
+ /**
156
+ * 从URL中获取某个参数,如果不存在返回 undefined ,如果存在多个同名参数,返回第一个匹配值
157
+ * getParam('a', '?a=1&b=&c=3&c=33#abc') // '1'
158
+ * getParam('b', '?a=1&b=&c=3&c=33#abc') // ''
159
+ * getParam('c', '?a=1&b=&c=3&c=33#abc') // 3
160
+ * getParam('d', '?a=1&b=&c=3&c=33#abc') // undefined
161
+ * @param {*} name 参数名
162
+ * @param {*} url 要获取的URL,默认当前地址
163
+ */
164
+ getParam(name: string, url: string = location.search) {
165
+ return (new RegExp(`(^|\\?|&)${name}=(.*?)(?=&|#|$)`, 'g').exec(url) || [])[2];
166
+ },
167
+ /**
168
+ * 从URL中获取int参数
169
+ * @param {*} name 参数名
170
+ * @param {*} url 要获取的URL,默认当前地址
171
+ */
172
+ getParamInt(name: string, url: string = location.search) {
173
+ return parseInt(this.getParam(name, url) || '0', 10);
174
+ },
175
+ /**
176
+ * 获取某个URL的全部参数
177
+ * getParams('?a=1&b=2#cc') // {a: '1', b: '2'}
178
+ * @param url
179
+ * @returns 参数对象
180
+ */
181
+ getParams(url = location.search) {
182
+ const search = ((url || '').split('?').pop() || '').split('#')[0] || '';
183
+ const params: any = {};
184
+ search.split('&').map(item => item.split('=')).forEach(([key, value]) => {
185
+ params[key] = value || '';
186
+ });
187
+ return params;
188
+ },
189
+ /**
190
+ * 给URL设置参数,如果已经存在,替换之,兼容hash存在的情况
191
+ * setParam('a', '123', '?a=1&b=2&a=3#d') // '?a=123&b=2&a=123#d'
192
+ * setParam('d', '444', '?a=1&b=2&a=3#d') // '?a=1&b=2&a=3&d=444#d'
193
+ * @param {Object} name 参数名
194
+ * @param {Object} value 参数值
195
+ * @param {Object} url 如果不传默认当前页面URL
196
+ */
197
+ setParam(name: string, value: string | number, url?: string) {
198
+ url = url || `${location.pathname}${location.search}`;
199
+ // 如果参数已经存在,替换之
200
+ if (this.getParam(name, url) !== undefined) {
201
+ return url.replace(new RegExp(`(^|\\?|&)${name}=(.*?)(?=&|#|$)`, 'g'), `$1${name}=${value}`);
202
+ }
203
+ const [pathname, hash] = url.split('#'); // 处理存在hash的情况
204
+ return `${pathname}${pathname.indexOf('?') < 0 ? '?' : '&'}${name}=${value}${hash ? '#' : ''}${hash || ''}`;
205
+ },
206
+ /**
207
+ * 删除URL中某个参数
208
+ * delParam('a', '?a=1&b=2&a=3#d') // '?b=2#d'
209
+ * delParam('b', '?a=1&b=2&a=3#d') // '?a=1&a=3#d'
210
+ * delParam('a', '?a=1#d') // '#d'
211
+ * @param name 参数名
212
+ * @param url 要删除的URL,默认当前页面URL
213
+ * @returns 处理完后的URL
214
+ */
215
+ delParam(name: string, url: string) {
216
+ url = url || `${location.pathname}${location.search}`;
217
+ return url.replace(new RegExp(`(^|\\?|&)${name}=.*?(&|#|$)`, 'g'), (_m, $1, $2) => $2 === '&' ? $1 : $2);
218
+ },
219
+ /**
220
+ * 休息一段时间,单位毫秒
221
+ * 示例:await sleep(200); // 休息200毫秒
222
+ * @param time 要休息的时间,单位毫秒,不传默认0
223
+ * @returns
224
+ */
225
+ sleep: (time?: number) => new Promise(resolve => setTimeout(resolve, time || 0)),
226
+ /**
227
+ * 基于JSON的简单深拷贝
228
+ * @param obj 要复制的对象,非对象格式会直接返回
229
+ * @returns
230
+ */
231
+ deepCopy: (obj: any) => {
232
+ if (!obj || typeof obj !== 'object') {
233
+ return obj;
234
+ }
235
+ return JSON.parse(JSON.stringify(obj));
236
+ },
237
+ /**
238
+ * HTML编码,例如将 【"】 变成 【&quot;】
239
+ * @param {*} html 待编码的原始字符串
240
+ * @returns
241
+ */
242
+ encodeHtml(html: string) {
243
+ const div = document.createElement('div');
244
+ div.innerText = html;
245
+ return div.innerHTML;
246
+ },
247
+ /**
248
+ * HTML解码,例如将 【&quot;】 变成 【"】
249
+ * @param {*} html 已经被HTML编码过的字符串
250
+ * @returns
251
+ */
252
+ decodeHtml(html: string) {
253
+ const div = document.createElement('div');
254
+ div.innerHTML = html;
255
+ return div.innerText;
256
+ },
257
+ };
@@ -0,0 +1,14 @@
1
+ const youtil = require('../dist');
2
+ const { formatDate, getParam } = youtil.default;
3
+
4
+ test('formatDate', () => {
5
+ expect(formatDate(1675935902379)).toBe('2023-02-09 17:45:02');
6
+ expect(formatDate(1675935902379, 'yyyy-MM-dd')).toBe('2023-02-09');
7
+ });
8
+
9
+ test('getParam', () => {
10
+ expect(getParam('a', '?a=1&b=&c=3&c=33#abc')).toBe('1');
11
+ expect(getParam('b', '?a=1&b=&c=3&c=33#abc')).toBe('');
12
+ expect(getParam('c', '?a=1&b=&c=3&c=33#abc')).toBe('3');
13
+ expect(getParam('d', '?a=1&b=&c=3&c=33#abc')).toBe(undefined);
14
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2015",
4
+ "rootDir": "src",
5
+ "outDir": "dist",
6
+ "module": "CommonJS",
7
+ "noImplicitAny": true,
8
+ "skipLibCheck": true,
9
+ }
10
+ }