mazey 3.3.5 → 3.3.6
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/LICENSE +21 -21
- package/README.md +535 -568
- package/README_CN.md +334 -334
- package/examples/index.html +21 -21
- package/examples/index.ts +70 -50
- package/images/mazey-v1.4.39.svg +0 -0
- package/lib/index.cjs.js +2 -2
- package/lib/index.d.ts +0 -0
- package/lib/index.d.ts.map +0 -0
- package/lib/index.esm.js +2 -2
- package/lib/mazey.min.js +2 -2
- package/package.json +110 -109
- package/scripts/build-helper.js +17 -17
- package/scripts/dev.js +22 -19
- package/scripts/github-helper.js +110 -57
- package/scripts/release.js +7 -7
- package/scripts/webpack.config.dev.js +39 -39
- package/src/index.ts +1608 -1608
- package/src/{index.js → preview.js} +47 -47
- package/src/t.html +18 -0
package/src/index.ts
CHANGED
|
@@ -1,1608 +1,1608 @@
|
|
|
1
|
-
/* mazey */
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* @method calLongestCommonSubstring
|
|
5
|
-
* @description Computes the longest common substring of two strings.
|
|
6
|
-
* @param {string} aStr String
|
|
7
|
-
* @param {string} bStr String
|
|
8
|
-
* @returns {number} Length
|
|
9
|
-
*/
|
|
10
|
-
export function calLongestCommonSubstring(aStr: string, bStr: string): number {
|
|
11
|
-
const aLen = aStr.length;
|
|
12
|
-
const bLen = bStr.length;
|
|
13
|
-
// 创建二维数组并且深拷贝
|
|
14
|
-
const arr = deepCopyObject(new Array(aLen).fill(new Array(bLen).fill(0)));
|
|
15
|
-
for (let i = 0; i < aLen; ++i) {
|
|
16
|
-
for (let j = 0; j < bLen; ++j) {
|
|
17
|
-
if (aStr[i] === bStr[j]) {
|
|
18
|
-
let baseNum = 0;
|
|
19
|
-
if (i > 0 && j > 0) {
|
|
20
|
-
baseNum = arr[i - 1][j - 1];
|
|
21
|
-
}
|
|
22
|
-
arr[i][j] = baseNum + 1;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
// 二维数组转一维数组
|
|
27
|
-
const arr1 = Array.prototype.concat.apply([], arr);
|
|
28
|
-
// 获取最长公共子串
|
|
29
|
-
const maxLong = Math.max(...arr1);
|
|
30
|
-
return maxLong;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* @method calLongestCommonSubsequence
|
|
35
|
-
* @description 计算两个字符串的最长公共子序列
|
|
36
|
-
* @param {string} aStr 字符串
|
|
37
|
-
* @param {string} bStr 字符串
|
|
38
|
-
* @returns {number} 长度
|
|
39
|
-
*/
|
|
40
|
-
export function calLongestCommonSubsequence(aStr: string, bStr: string): number {
|
|
41
|
-
const aLen = aStr.length;
|
|
42
|
-
const bLen = bStr.length;
|
|
43
|
-
// 创建二维数组并且深拷贝
|
|
44
|
-
const arr = deepCopyObject(new Array(aLen).fill(new Array(bLen).fill(0)));
|
|
45
|
-
for (let i = 0; i < aLen; ++i) {
|
|
46
|
-
for (let j = 0; j < bLen; ++j) {
|
|
47
|
-
if (aStr[i] === bStr[j]) {
|
|
48
|
-
let baseNum = 0;
|
|
49
|
-
if (i > 0 && j > 0) {
|
|
50
|
-
baseNum = arr[i - 1][j - 1];
|
|
51
|
-
}
|
|
52
|
-
arr[i][j] = baseNum + 1;
|
|
53
|
-
} else {
|
|
54
|
-
let [leftValue, topValue] = [0, 0];
|
|
55
|
-
if (j > 0) {
|
|
56
|
-
leftValue = arr[i][j - 1];
|
|
57
|
-
}
|
|
58
|
-
if (i > 0) {
|
|
59
|
-
topValue = arr[i - 1][j];
|
|
60
|
-
}
|
|
61
|
-
arr[i][j] = Math.max(leftValue, topValue);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
// 二维数组转一维数组
|
|
66
|
-
const arr1 = Array.prototype.concat.apply([], arr);
|
|
67
|
-
// 获取最长公共子串
|
|
68
|
-
const maxLong = Math.max(...arr1);
|
|
69
|
-
return maxLong;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* @method getQueryParam
|
|
74
|
-
* @description Get the query param's value of the current Web URL(`location.search`).
|
|
75
|
-
* @param {string} param Query param.
|
|
76
|
-
* @returns {string} value
|
|
77
|
-
*/
|
|
78
|
-
export function getQueryParam(param: string): string {
|
|
79
|
-
const reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)');
|
|
80
|
-
const r = location.search.substr(1).match(reg);
|
|
81
|
-
if (r !== null) {
|
|
82
|
-
// return decodeURIComponent(unescape(r[2]));
|
|
83
|
-
return decodeURIComponent(r[2]);
|
|
84
|
-
}
|
|
85
|
-
return '';
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* @method getUrlParam
|
|
90
|
-
* @description Get the query param's value of the input URL.
|
|
91
|
-
* @param {string} url URL string.
|
|
92
|
-
* @param {string} param Query param.
|
|
93
|
-
* @returns {string} value
|
|
94
|
-
*/
|
|
95
|
-
export function getUrlParam(url: string, param: string): string | string[] {
|
|
96
|
-
const result: {
|
|
97
|
-
[key: string]: string | string[] | any;
|
|
98
|
-
} = {};
|
|
99
|
-
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
|
|
100
|
-
url.replace(/\??(\w+)=([^&]*)&?/g, function (a, k, v): any {
|
|
101
|
-
if (result[k] !== undefined) {
|
|
102
|
-
const t = result[k];
|
|
103
|
-
result[k] = [].concat(t, v);
|
|
104
|
-
} else {
|
|
105
|
-
result[k] = v;
|
|
106
|
-
}
|
|
107
|
-
});
|
|
108
|
-
// if (param === undefined) {
|
|
109
|
-
// return result;
|
|
110
|
-
// } else {
|
|
111
|
-
// return result[param] || '';
|
|
112
|
-
// }
|
|
113
|
-
return result[param] || '';
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* @method updateQueryParam
|
|
118
|
-
* @description Update the query param's value of the input URL.
|
|
119
|
-
* @param {string} url URL string.
|
|
120
|
-
* @param {string} param Query param.
|
|
121
|
-
* @param {string} value Param's value.
|
|
122
|
-
* @returns {string} URL.
|
|
123
|
-
*/
|
|
124
|
-
export function updateQueryParam(url: string, param: string, value: string): string {
|
|
125
|
-
const re = new RegExp('([?&])' + param + '=.*?(&|$)', 'i');
|
|
126
|
-
const separator = url.indexOf('?') !== -1 ? '&' : '?';
|
|
127
|
-
if (url.match(re)) {
|
|
128
|
-
return url.replace(re, '$1' + param + '=' + value + '$2');
|
|
129
|
-
} else {
|
|
130
|
-
return url + separator + param + '=' + value;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* @method getHashQueryParam
|
|
136
|
-
* @description Get the hash query param's value of the current Web URL(`location.hash`).
|
|
137
|
-
* @param {string} param Query param.
|
|
138
|
-
* @returns {string} value
|
|
139
|
-
*/
|
|
140
|
-
export function getHashQueryParam(param: string): string {
|
|
141
|
-
const hashs = location.hash.split('?');
|
|
142
|
-
if (hashs.length === 1) {
|
|
143
|
-
return '';
|
|
144
|
-
}
|
|
145
|
-
const reg = new RegExp(`(^|&)${param}=([^&]*)(&|$)`);
|
|
146
|
-
const ret = hashs[1].match(reg);
|
|
147
|
-
return ret ? ret[2] : '';
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* @method getDomain
|
|
152
|
-
* @description Get the domain of URL, and other params.
|
|
153
|
-
* @param {string} url
|
|
154
|
-
* @param {array} rules Object.keys(location), ['href', 'protocol', 'host', 'hostname', 'port', 'pathname', 'search', 'hash'], ['hostname', 'pathname'] = 'km.mazey.net/plugins/servlet/mobile'
|
|
155
|
-
*/
|
|
156
|
-
export function getDomain(url: string, rules = ['hostname']): string {
|
|
157
|
-
const aEl: any = document.createElement('a');
|
|
158
|
-
aEl.href = url;
|
|
159
|
-
return rules.reduce((ret, v) => {
|
|
160
|
-
ret += aEl[v];
|
|
161
|
-
return ret;
|
|
162
|
-
}, '');
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/**
|
|
166
|
-
* @method camelCaseToKebabCase
|
|
167
|
-
* @description Transfer CamelCase to KebabCase.
|
|
168
|
-
* @param {string} camelCase 'aBC' or 'ABC'
|
|
169
|
-
* @returns {string} 'a-b-c'
|
|
170
|
-
*/
|
|
171
|
-
export function camelCaseToKebabCase(camelCase: string): string {
|
|
172
|
-
const kebabCase = camelCase.replace(/([A-Z])/g, '-$1').toLowerCase();
|
|
173
|
-
return kebabCase[0] === '-' ? kebabCase.substr(1) : kebabCase;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* @method camelCase2Underscore
|
|
178
|
-
* @description Transfer CamelCase to Underscore.
|
|
179
|
-
* @param {string} camelCase 'aBC' or 'ABC'
|
|
180
|
-
* @returns {string} 'a_b_c'
|
|
181
|
-
*/
|
|
182
|
-
export function camelCase2Underscore(camelCase: string): string {
|
|
183
|
-
const kebabCase = camelCase.replace(/([A-Z])/g, '_$1').toLowerCase();
|
|
184
|
-
return kebabCase[0] === '_' ? kebabCase.substr(1) : kebabCase;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* @method mTrim
|
|
189
|
-
* @description Remove leading and trailing whitespace or specified characters from string.
|
|
190
|
-
* @param {string} str The string to trim.
|
|
191
|
-
* @returns {string} Trimmed string.
|
|
192
|
-
*/
|
|
193
|
-
export function mTrim(str: string): string {
|
|
194
|
-
str = str.replace(/^\s+/, ''); // 去除头部空格
|
|
195
|
-
let end = str.length - 1;
|
|
196
|
-
const ws = /\s/;
|
|
197
|
-
while (ws.test(str.charAt(end))) {
|
|
198
|
-
end--; // 最后一个非空格字符的索引
|
|
199
|
-
}
|
|
200
|
-
return str.slice(0, end + 1);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
/**
|
|
204
|
-
* @method newLine
|
|
205
|
-
* @description Make a newline of HTML.
|
|
206
|
-
* @param {string} str The string to make a newline.
|
|
207
|
-
* @returns {string} A newline with `br`.
|
|
208
|
-
*/
|
|
209
|
-
export function newLine(str: string): string {
|
|
210
|
-
if (!str) {
|
|
211
|
-
return '';
|
|
212
|
-
}
|
|
213
|
-
const reg = new RegExp('\\n', 'g');
|
|
214
|
-
return str.replace(reg, '<br />');
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* @method deepCopyObject
|
|
219
|
-
* @description Clone Object deeply.
|
|
220
|
-
* @param {object} obj The value to clone.
|
|
221
|
-
* @returns {object} Returns the deep cloned value.
|
|
222
|
-
*/
|
|
223
|
-
export function deepCopyObject(obj: any): any {
|
|
224
|
-
return JSON.parse(JSON.stringify(obj));
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* @method isJsonString
|
|
229
|
-
* @description Check whether it is a valid JSON string.
|
|
230
|
-
* @param {string} str The string to check.
|
|
231
|
-
* @returns {boolean} Return the result of checking.
|
|
232
|
-
*/
|
|
233
|
-
export function isJsonString(str: string): boolean {
|
|
234
|
-
try {
|
|
235
|
-
if (typeof JSON.parse(str) === 'object') {
|
|
236
|
-
return true;
|
|
237
|
-
}
|
|
238
|
-
} catch (e) {
|
|
239
|
-
/* pass */
|
|
240
|
-
}
|
|
241
|
-
return false;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
/**
|
|
245
|
-
* @method generateRndNum
|
|
246
|
-
* @description Produce a random string of number, `generateRndNum(7)` => '7658495'.
|
|
247
|
-
* @param {number} n Length
|
|
248
|
-
* @returns {string} Return the random string.
|
|
249
|
-
*/
|
|
250
|
-
export function generateRndNum(n = 5): string {
|
|
251
|
-
let ret = '';
|
|
252
|
-
while (n--) {
|
|
253
|
-
ret += Math.floor(Math.random() * 10);
|
|
254
|
-
}
|
|
255
|
-
return ret;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
/**
|
|
259
|
-
* @method generateUniqueNum
|
|
260
|
-
* @description 根据时间生成唯一标志的数字 mGenerateUniqueNum() => 1538324722364123。
|
|
261
|
-
* @param {number} n 随机数的长度
|
|
262
|
-
*/
|
|
263
|
-
export function generateUniqueNum(n = 3): string {
|
|
264
|
-
const [now, rnd] = [mNow(), generateRndNum(n || 3)];
|
|
265
|
-
return now + rnd;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* @method floatToPercent
|
|
270
|
-
* @description 浮点数转为百分比 0.2 => 20%。
|
|
271
|
-
* @param {number} num 浮点数
|
|
272
|
-
* @param {number} fixSize 保留几位浮点数
|
|
273
|
-
*/
|
|
274
|
-
export function floatToPercent(num: number, fixSize = 0): string {
|
|
275
|
-
let ret = '';
|
|
276
|
-
if (fixSize) {
|
|
277
|
-
ret = (num * 100).toFixed(fixSize);
|
|
278
|
-
} else {
|
|
279
|
-
ret = String(Math.floor(num * 100));
|
|
280
|
-
}
|
|
281
|
-
return `${ret}%`;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/**
|
|
285
|
-
* @method floatFixed
|
|
286
|
-
* @description 浮点数保留指定位。
|
|
287
|
-
*/
|
|
288
|
-
export function floatFixed(num: string, size = 0): string {
|
|
289
|
-
return parseFloat(num).toFixed(size);
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* @method cancelBubble
|
|
294
|
-
* @description 阻止冒泡。
|
|
295
|
-
*/
|
|
296
|
-
export function cancelBubble(e: any): void {
|
|
297
|
-
const ev = e || window.event;
|
|
298
|
-
if (ev.stopPropagation) {
|
|
299
|
-
// W3C
|
|
300
|
-
ev.stopPropagation();
|
|
301
|
-
} else {
|
|
302
|
-
// IE
|
|
303
|
-
ev.cancelBubble = true;
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/**
|
|
308
|
-
* @method hasClass
|
|
309
|
-
*/
|
|
310
|
-
export function hasClass(obj: any, cls: string): boolean {
|
|
311
|
-
const oriCls = obj.className; // 获取对象的class值
|
|
312
|
-
const oriClsArr = oriCls.split(/\s+/); // 分隔空格转换成数组
|
|
313
|
-
for (let i = 0; i < oriClsArr.length; i++) {
|
|
314
|
-
if (oriClsArr[i] === cls) {
|
|
315
|
-
return true; // 若匹配到class则返回True
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
return false; // 否则返回False
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
/**
|
|
322
|
-
* @method addClass
|
|
323
|
-
*/
|
|
324
|
-
export function addClass(obj: any, cls: string): void {
|
|
325
|
-
const oriCls = obj.className;
|
|
326
|
-
let space = '';
|
|
327
|
-
let newCls = ''; // 获取对象的class值
|
|
328
|
-
if (oriCls !== '') {
|
|
329
|
-
space = ' '; // 若原来的class不为空,跟一个空格
|
|
330
|
-
}
|
|
331
|
-
newCls = oriCls + space + cls; // 将新的class加进去
|
|
332
|
-
obj.className = newCls; // 替换新class
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
/**
|
|
336
|
-
* @method removeClass
|
|
337
|
-
*/
|
|
338
|
-
export function removeClass(obj: any, cls: string): void {
|
|
339
|
-
const oriCls = obj.className;
|
|
340
|
-
let newCls; // 获取对象的class值
|
|
341
|
-
newCls = ' ' + oriCls + ' '; // 前后加空格
|
|
342
|
-
newCls = newCls.replace(/(\s+)/gi, ' '); // 将多余的空格替换成一个空格
|
|
343
|
-
newCls = newCls.replace(' ' + cls + ' ', ' '); // 将加了前后空格的cls替换成空格' '
|
|
344
|
-
newCls = newCls.replace(/(^\s+)|(\s+$)/g, ''); // 去掉前后空格
|
|
345
|
-
obj.className = newCls;
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
/**
|
|
349
|
-
* EN: Throttle
|
|
350
|
-
*
|
|
351
|
-
* ZH: 节流
|
|
352
|
-
*
|
|
353
|
-
* Reference: [Lodash](https://lodash.com/docs/4.17.15#throttle)
|
|
354
|
-
*/
|
|
355
|
-
export function throttle(func: any, wait: number, options: { leading?: boolean; trailing?: boolean; } = {}): any {
|
|
356
|
-
options = Object.assign(
|
|
357
|
-
{},
|
|
358
|
-
options,
|
|
359
|
-
);
|
|
360
|
-
// timeout: setTimeout Handle
|
|
361
|
-
// previous: 上次时间戳
|
|
362
|
-
let context: any = null;
|
|
363
|
-
let args: any = null;
|
|
364
|
-
let timeout: any = null;
|
|
365
|
-
let [result, previous] = [null, 0];
|
|
366
|
-
// if (!options) {
|
|
367
|
-
// options = {};
|
|
368
|
-
// }
|
|
369
|
-
const later = function () {
|
|
370
|
-
previous = options.leading === false ? 0 : mNow();
|
|
371
|
-
timeout = null;
|
|
372
|
-
result = func.apply(context, args);
|
|
373
|
-
if (!timeout) {
|
|
374
|
-
context = args = null;
|
|
375
|
-
}
|
|
376
|
-
};
|
|
377
|
-
return function (...argRest: Array<any>) {
|
|
378
|
-
const now = mNow();
|
|
379
|
-
if (!previous && options.leading === false) {
|
|
380
|
-
previous = now;
|
|
381
|
-
}
|
|
382
|
-
const remaining = wait - (now - previous);
|
|
383
|
-
context = this;
|
|
384
|
-
args = argRest;
|
|
385
|
-
if (remaining <= 0 || remaining > wait) {
|
|
386
|
-
if (timeout) {
|
|
387
|
-
clearTimeout(timeout);
|
|
388
|
-
timeout = null;
|
|
389
|
-
}
|
|
390
|
-
previous = now;
|
|
391
|
-
result = func.apply(context, args);
|
|
392
|
-
if (!timeout) {
|
|
393
|
-
context = args = null;
|
|
394
|
-
}
|
|
395
|
-
} else if (!timeout && options.trailing !== false) {
|
|
396
|
-
timeout = setTimeout(later, remaining);
|
|
397
|
-
}
|
|
398
|
-
return result;
|
|
399
|
-
};
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* EN: Debounce
|
|
404
|
-
*
|
|
405
|
-
* ZH: 去抖
|
|
406
|
-
*
|
|
407
|
-
* Usage:
|
|
408
|
-
*
|
|
409
|
-
* ```
|
|
410
|
-
* const foo = debounce(() => {
|
|
411
|
-
* console.log('The debounced function will only be invoked in 1000 milliseconds, the other invoking will disappear during the wait time.');
|
|
412
|
-
* }, 1000, true);
|
|
413
|
-
* ```
|
|
414
|
-
*/
|
|
415
|
-
export function debounce(func: any, wait: number, immediate?: any): any {
|
|
416
|
-
let context: any = null;
|
|
417
|
-
let timeout: any = null;
|
|
418
|
-
let timestamp: any = null;
|
|
419
|
-
let args: any = null;
|
|
420
|
-
let [result] = [null];
|
|
421
|
-
const later = function () {
|
|
422
|
-
const last = mNow() - timestamp;
|
|
423
|
-
if (last < wait && last >= 0) {
|
|
424
|
-
timeout = setTimeout(later, wait - last);
|
|
425
|
-
} else {
|
|
426
|
-
timeout = null;
|
|
427
|
-
if (!immediate) {
|
|
428
|
-
result = func.apply(context, args);
|
|
429
|
-
if (!timeout) {
|
|
430
|
-
context = args = null;
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
};
|
|
435
|
-
return function (...argRest: Array<any>) {
|
|
436
|
-
context = this;
|
|
437
|
-
args = argRest;
|
|
438
|
-
timestamp = mNow();
|
|
439
|
-
const callNow = immediate && !timeout;
|
|
440
|
-
if (!timeout) {
|
|
441
|
-
timeout = setTimeout(later, wait);
|
|
442
|
-
}
|
|
443
|
-
if (callNow) {
|
|
444
|
-
result = func.apply(context, args);
|
|
445
|
-
context = args = null;
|
|
446
|
-
}
|
|
447
|
-
return result;
|
|
448
|
-
};
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
/**
|
|
452
|
-
* @method friendlyInterval
|
|
453
|
-
* @description 获取间隔时间。
|
|
454
|
-
* @param {number/Date} start 开始时间戳 1585325367122
|
|
455
|
-
* @param {number/Date} end 结束时间戳 1585325367122
|
|
456
|
-
* @param {string} options.type 返回类型 d: 2(天) text: 2 天 4 时...
|
|
457
|
-
* @returns {String/number} 取决于 type
|
|
458
|
-
*/
|
|
459
|
-
export function friendlyInterval(start = 0, end = 0, options: { type?: string; } = { type: 'd' }): number | string {
|
|
460
|
-
const { type } = options;
|
|
461
|
-
if (!isNumber(start)) start = new Date(start).getTime();
|
|
462
|
-
if (!isNumber(end)) end = new Date(end).getTime();
|
|
463
|
-
const t = end - start;
|
|
464
|
-
let ret = '';
|
|
465
|
-
let [d, h, m, s] = new Array(4).fill(0);
|
|
466
|
-
if (t >= 0) {
|
|
467
|
-
d = Math.floor(t / 1000 / 60 / 60 / 24);
|
|
468
|
-
h = Math.floor(t / 1000 / 60 / 60);
|
|
469
|
-
m = Math.floor(t / 1000 / 60);
|
|
470
|
-
s = Math.floor(t / 1000);
|
|
471
|
-
switch (type) {
|
|
472
|
-
case 'd':
|
|
473
|
-
ret = d;
|
|
474
|
-
break;
|
|
475
|
-
case 'text':
|
|
476
|
-
d = Math.floor(t / 1000 / 60 / 60 / 24);
|
|
477
|
-
h = Math.floor((t / 1000 / 60 / 60) % 24);
|
|
478
|
-
m = Math.floor((t / 1000 / 60) % 60);
|
|
479
|
-
s = Math.floor((t / 1000) % 60);
|
|
480
|
-
ret = d + ' 天 ' + h + ' 时 ' + m + ' 分 ' + s + ' 秒';
|
|
481
|
-
break;
|
|
482
|
-
default:
|
|
483
|
-
ret = s;
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
return ret;
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
/**
|
|
490
|
-
* @method isNumber
|
|
491
|
-
* @description 判断是否有效数字
|
|
492
|
-
* @param {*} num 被判断的值
|
|
493
|
-
* @param {boolean} options.isNaNAsNumber 是否 NaN 算数字(默认不算)
|
|
494
|
-
* @param {boolean} options.isUnFiniteAsNumber 是否 无限 算数字(默认不算)
|
|
495
|
-
* @returns {boolean} true 是数字
|
|
496
|
-
*/
|
|
497
|
-
export function isNumber(num: any, options: { isNaNAsNumber?: boolean; isUnFiniteAsNumber?: boolean; } = { isNaNAsNumber: false, isUnFiniteAsNumber: false }): boolean {
|
|
498
|
-
const { isNaNAsNumber, isUnFiniteAsNumber } = Object.assign(
|
|
499
|
-
{ isNaNAsNumber: false, isUnFiniteAsNumber: false },
|
|
500
|
-
options,
|
|
501
|
-
);
|
|
502
|
-
let ret = true;
|
|
503
|
-
// 数字类型
|
|
504
|
-
if (typeof num !== 'number') {
|
|
505
|
-
ret = false;
|
|
506
|
-
}
|
|
507
|
-
// 无限值
|
|
508
|
-
if (isUnFiniteAsNumber === false && !isFinite(num)) {
|
|
509
|
-
// console.log('1333');
|
|
510
|
-
ret = false;
|
|
511
|
-
}
|
|
512
|
-
// NaN
|
|
513
|
-
if (isNaNAsNumber === false && isNaN(num)) {
|
|
514
|
-
// console.log('2333');
|
|
515
|
-
ret = false;
|
|
516
|
-
}
|
|
517
|
-
return ret;
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
/**
|
|
521
|
-
* @method doFn
|
|
522
|
-
* @description 执行有效函数
|
|
523
|
-
* @param {function} fn 等待被执行的未知是否有效的函数
|
|
524
|
-
*/
|
|
525
|
-
export function doFn(fn: any, ...params: any[]): any {
|
|
526
|
-
let ret = null;
|
|
527
|
-
if (fn && typeof fn === 'function') {
|
|
528
|
-
ret = fn(...params);
|
|
529
|
-
}
|
|
530
|
-
return ret;
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
/**
|
|
534
|
-
* @method setSessionStorage
|
|
535
|
-
* @description 存储数据到 sessionStorage
|
|
536
|
-
* @param {string} key 键
|
|
537
|
-
* @param {string} value 值
|
|
538
|
-
*/
|
|
539
|
-
export function setSessionStorage(key: string, value: any = null): void {
|
|
540
|
-
if (key) {
|
|
541
|
-
sessionStorage.setItem(key, JSON.stringify(value));
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
/**
|
|
546
|
-
* @method getSessionStorage
|
|
547
|
-
* @description 存储数据到 sessionStorage
|
|
548
|
-
* @param {string} key 键
|
|
549
|
-
* @returns {*} 返回值
|
|
550
|
-
*/
|
|
551
|
-
export function getSessionStorage(key: string): any {
|
|
552
|
-
let ret = null;
|
|
553
|
-
if (key) {
|
|
554
|
-
const value = sessionStorage.getItem(key);
|
|
555
|
-
if (value) {
|
|
556
|
-
ret = JSON.parse(value);
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
return ret;
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
/**
|
|
563
|
-
* @method setLocalStorage
|
|
564
|
-
* @description 存储数据到 localStorage
|
|
565
|
-
* @param {string} key 键
|
|
566
|
-
* @param {string} value 值
|
|
567
|
-
*/
|
|
568
|
-
export function setLocalStorage(key: string, value: any = null): void {
|
|
569
|
-
if (key) {
|
|
570
|
-
localStorage.setItem(key, JSON.stringify(value));
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
/**
|
|
575
|
-
* @method getLocalStorage
|
|
576
|
-
* @description 存储数据到 localStorage
|
|
577
|
-
* @param {string} key 键
|
|
578
|
-
* @returns {*} 返回值
|
|
579
|
-
*/
|
|
580
|
-
export function getLocalStorage(key: string): any {
|
|
581
|
-
let ret = null;
|
|
582
|
-
if (key) {
|
|
583
|
-
const value = localStorage.getItem(key);
|
|
584
|
-
if (value) {
|
|
585
|
-
ret = JSON.parse(value);
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
return ret;
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
/**
|
|
592
|
-
* @method loadCSS
|
|
593
|
-
* @description 动态加载css文件
|
|
594
|
-
* @param {string} url -- css资源路径
|
|
595
|
-
* @param {string} options.id -- link标签id
|
|
596
|
-
* @returns {Promise<boolean>} true -- 加载成功
|
|
597
|
-
*/
|
|
598
|
-
export function loadCSS(url: string, options: { id?: string } = { id: '' }): Promise<boolean | Error | any> {
|
|
599
|
-
const { id } = options;
|
|
600
|
-
let success: (v: boolean) => void;
|
|
601
|
-
let fail: (v: Error) => void;
|
|
602
|
-
const status = new Promise((resolve, reject) => {
|
|
603
|
-
([success, fail] = [resolve, reject]);
|
|
604
|
-
});
|
|
605
|
-
// const tempCB = (typeof callback === 'function' ? callback : function () { });
|
|
606
|
-
const callback = function () {
|
|
607
|
-
// doFn(success, true);
|
|
608
|
-
success(true);
|
|
609
|
-
};
|
|
610
|
-
let node: any = document.createElement('link');
|
|
611
|
-
const supportOnload = 'onload' in node;
|
|
612
|
-
const isOldWebKit = +navigator.userAgent.replace(/.*(?:AppleWebKit|AndroidWebKit)\/?(\d+).*/i, '$1') < 536; // webkit旧内核做特殊处理
|
|
613
|
-
const protectNum = 300000; // 阈值10分钟,一秒钟执行pollCss 500次
|
|
614
|
-
|
|
615
|
-
node.rel = 'stylesheet';
|
|
616
|
-
node.type = 'text/css';
|
|
617
|
-
node.href = url;
|
|
618
|
-
if (typeof id !== 'undefined') {
|
|
619
|
-
node.id = id;
|
|
620
|
-
}
|
|
621
|
-
document.getElementsByTagName('head')[0].appendChild(node);
|
|
622
|
-
|
|
623
|
-
// for Old WebKit and Old Firefox
|
|
624
|
-
if (isOldWebKit || !supportOnload) {
|
|
625
|
-
// Begin after node insertion
|
|
626
|
-
setTimeout(function () {
|
|
627
|
-
pollCss(node, callback, 0);
|
|
628
|
-
}, 1);
|
|
629
|
-
return status;
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
if (supportOnload) {
|
|
633
|
-
node.onload = onload;
|
|
634
|
-
node.onerror = function () {
|
|
635
|
-
// 加载失败(404)
|
|
636
|
-
onload();
|
|
637
|
-
};
|
|
638
|
-
} else {
|
|
639
|
-
// todo: 和 !supportOnload 重复
|
|
640
|
-
node.onreadystatechange = function () {
|
|
641
|
-
if (/loaded|complete/.test(node.readyState)) {
|
|
642
|
-
onload();
|
|
643
|
-
}
|
|
644
|
-
};
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
function onload() {
|
|
648
|
-
// 确保只跑一次下载操作
|
|
649
|
-
node.onload = node.onerror = node.onreadystatechange = null;
|
|
650
|
-
|
|
651
|
-
// 清空node引用,在低版本IE,不清除会造成内存泄露
|
|
652
|
-
node = null;
|
|
653
|
-
|
|
654
|
-
callback();
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
// 循环判断css是否已加载成功
|
|
658
|
-
/*
|
|
659
|
-
* @param node -- link节点
|
|
660
|
-
* @param callback -- 回调函数
|
|
661
|
-
* @param step -- 计步器,避免无限循环
|
|
662
|
-
*/
|
|
663
|
-
function pollCss(node: any, callback: any, step: number) {
|
|
664
|
-
const sheet = node.sheet;
|
|
665
|
-
let isLoaded: any;
|
|
666
|
-
|
|
667
|
-
step += 1;
|
|
668
|
-
|
|
669
|
-
// 保护,大于10分钟,则不再轮询
|
|
670
|
-
if (step > protectNum) {
|
|
671
|
-
isLoaded = true;
|
|
672
|
-
|
|
673
|
-
// 清空node引用
|
|
674
|
-
node = null;
|
|
675
|
-
|
|
676
|
-
callback();
|
|
677
|
-
return;
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
if (isOldWebKit) {
|
|
681
|
-
// for WebKit < 536
|
|
682
|
-
if (sheet) {
|
|
683
|
-
isLoaded = true;
|
|
684
|
-
}
|
|
685
|
-
} else if (sheet) {
|
|
686
|
-
// for Firefox < 9.0
|
|
687
|
-
try {
|
|
688
|
-
if (sheet.cssRules) {
|
|
689
|
-
isLoaded = true;
|
|
690
|
-
}
|
|
691
|
-
} catch (ex) {
|
|
692
|
-
// 火狐特殊版本,通过特定值获知是否下载成功
|
|
693
|
-
// The value of `ex.name` is changed from "NS_ERROR_DOM_SECURITY_ERR"
|
|
694
|
-
// to "SecurityError" since Firefox 13.0. But Firefox is less than 9.0
|
|
695
|
-
// in here, So it is ok to just rely on "NS_ERROR_DOM_SECURITY_ERR"
|
|
696
|
-
if ((ex as any).name === 'NS_ERROR_DOM_SECURITY_ERR') {
|
|
697
|
-
isLoaded = true;
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
setTimeout(function () {
|
|
703
|
-
if (isLoaded) {
|
|
704
|
-
// 延迟20ms是为了给下载的样式留够渲染的时间
|
|
705
|
-
callback();
|
|
706
|
-
} else {
|
|
707
|
-
pollCss(node, callback, step);
|
|
708
|
-
}
|
|
709
|
-
}, 20);
|
|
710
|
-
}
|
|
711
|
-
return status;
|
|
712
|
-
}
|
|
713
|
-
|
|
714
|
-
/**
|
|
715
|
-
* @method loadScript
|
|
716
|
-
* @description 动态加载js文件
|
|
717
|
-
* @param {string} url -- js资源路径
|
|
718
|
-
* @param {string} options.id -- DOM ID
|
|
719
|
-
* @param {function} options.callback -- 加载后回调函数
|
|
720
|
-
* @param {number} options.timeout -- 超时时长
|
|
721
|
-
* @param {boolean} options.isDefer -- 是否添加 defer 标签
|
|
722
|
-
* @returns {Promise<boolean>} -- true 成功
|
|
723
|
-
*/
|
|
724
|
-
export function loadScript(url: string, options: {
|
|
725
|
-
id: string;
|
|
726
|
-
callback: (...params: any[]) => any;
|
|
727
|
-
timeout: number;
|
|
728
|
-
isDefer: boolean;
|
|
729
|
-
} = { id: '', callback: function () { /* pass */ }, timeout: 5000, isDefer: false }): Promise<boolean | string | Error> {
|
|
730
|
-
const { id, callback, timeout, isDefer } = Object.assign(
|
|
731
|
-
{ id: '', callback: function () { /* pass */ }, timeout: 5000, isDefer: false },
|
|
732
|
-
options,
|
|
733
|
-
);
|
|
734
|
-
let success: any = null;
|
|
735
|
-
let fail: any = null;
|
|
736
|
-
const script: any = document.createElement('script');
|
|
737
|
-
// 如果没有 script 标签,那么代码就不会运行。可以利用这一事实,在页面的第一个 script 标签上使用 insertBefore()。
|
|
738
|
-
const firstScript: any = document.getElementsByTagName('script')[0];
|
|
739
|
-
script.type = 'text/javascript';
|
|
740
|
-
if (isDefer) {
|
|
741
|
-
script.defer = 'defer';
|
|
742
|
-
}
|
|
743
|
-
if (id) {
|
|
744
|
-
script.id = id;
|
|
745
|
-
}
|
|
746
|
-
if (script.readyState) {
|
|
747
|
-
// IE
|
|
748
|
-
script.onreadystatechange = function () {
|
|
749
|
-
if (script.readyState === 'loaded' || script.readyState === 'complete') {
|
|
750
|
-
script.onreadystatechange = null;
|
|
751
|
-
doFn(callback);
|
|
752
|
-
doFn(success, true);
|
|
753
|
-
}
|
|
754
|
-
};
|
|
755
|
-
} else {
|
|
756
|
-
// Others
|
|
757
|
-
script.onload = function () {
|
|
758
|
-
doFn(callback);
|
|
759
|
-
doFn(success, true);
|
|
760
|
-
};
|
|
761
|
-
}
|
|
762
|
-
script.src = url;
|
|
763
|
-
firstScript && firstScript.parentNode.insertBefore(script, firstScript);
|
|
764
|
-
return new Promise((resolve, reject) => {
|
|
765
|
-
([success, fail] = [resolve, reject]);
|
|
766
|
-
if (timeout) {
|
|
767
|
-
setTimeout(fail.bind(null, Error('timeout')), timeout);
|
|
768
|
-
}
|
|
769
|
-
});
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
/**
|
|
773
|
-
* @method mNow
|
|
774
|
-
* @description 获取时间戳
|
|
775
|
-
*/
|
|
776
|
-
export function mNow(): number {
|
|
777
|
-
let ret = 0;
|
|
778
|
-
if (Date.now) {
|
|
779
|
-
ret = Date.now();
|
|
780
|
-
} else {
|
|
781
|
-
ret = new Date().getTime();
|
|
782
|
-
}
|
|
783
|
-
return ret;
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
/**
|
|
787
|
-
* @method setCookie
|
|
788
|
-
* @description 设置 Cookie
|
|
789
|
-
*/
|
|
790
|
-
export function setCookie(name: string, value: string, days: number, domain: string): void {
|
|
791
|
-
let domainParts, expires;
|
|
792
|
-
let date: any;
|
|
793
|
-
if (days) {
|
|
794
|
-
date = new Date();
|
|
795
|
-
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
|
|
796
|
-
expires = "; expires=" + date.toGMTString();
|
|
797
|
-
} else {
|
|
798
|
-
expires = "";
|
|
799
|
-
}
|
|
800
|
-
const host = location.host;
|
|
801
|
-
if (host.split('.').length === 1) {
|
|
802
|
-
// no "." in a domain - it's localhost or something similar
|
|
803
|
-
document.cookie = name + "=" + value + expires + "; path=/";
|
|
804
|
-
} else {
|
|
805
|
-
// Remember the cookie on all subdomains.
|
|
806
|
-
//
|
|
807
|
-
// Start with trying to set cookie to the top domain.
|
|
808
|
-
// (example: if user is on foo.com, try to set
|
|
809
|
-
// cookie to domain ".com")
|
|
810
|
-
//
|
|
811
|
-
// If the cookie will not be set, it means ".com"
|
|
812
|
-
// is a top level domain and we need to
|
|
813
|
-
// set the cookie to ".foo.com"
|
|
814
|
-
domainParts = host.split('.');
|
|
815
|
-
domainParts.shift();
|
|
816
|
-
domain = domain || ('.' + domainParts.join('.'));
|
|
817
|
-
document.cookie = name + "=" + value + expires + "; path=/; domain=" + domain;
|
|
818
|
-
// check if cookie was successfuly set to the given domain
|
|
819
|
-
// (otherwise it was a Top-Level Domain)
|
|
820
|
-
if (getCookie(name) === null || getCookie(name) !== value) {
|
|
821
|
-
// append "." to current domain
|
|
822
|
-
domain = domain || ('.' + host);
|
|
823
|
-
document.cookie = name + "=" + value + expires + "; path=/; domain=" + domain;
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
/**
|
|
829
|
-
* @method getCookie
|
|
830
|
-
* @description 获取 Cookie
|
|
831
|
-
*/
|
|
832
|
-
export function getCookie(name: string): string {
|
|
833
|
-
const nameEQ = name + "=";
|
|
834
|
-
const ca = document.cookie.split(';');
|
|
835
|
-
for (let i = 0; i < ca.length; i++) {
|
|
836
|
-
let c = ca[i];
|
|
837
|
-
while (c.charAt(0) == ' ') {
|
|
838
|
-
c = c.substring(1, c.length);
|
|
839
|
-
}
|
|
840
|
-
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
|
|
841
|
-
}
|
|
842
|
-
return '';
|
|
843
|
-
}
|
|
844
|
-
|
|
845
|
-
interface WebPerformance {
|
|
846
|
-
[key: string]: string | number;
|
|
847
|
-
}
|
|
848
|
-
|
|
849
|
-
/**
|
|
850
|
-
* @method getPerformance
|
|
851
|
-
* @description 获取页面加载相关的各项数据
|
|
852
|
-
* @param {boolean} camelCase -- true(默认) 以驼峰形式返回数据 false 以下划线形式返回数据
|
|
853
|
-
* @returns {Promise<object>} 加载数据
|
|
854
|
-
*/
|
|
855
|
-
export function getPerformance(camelCase = true): Promise<WebPerformance | Error> {
|
|
856
|
-
let success: (v: WebPerformance) => void;
|
|
857
|
-
let fail: (v: Error) => void;
|
|
858
|
-
const status: Promise<WebPerformance> = new Promise((resolve, reject) => {
|
|
859
|
-
([success, fail] = [resolve, reject]);
|
|
860
|
-
});
|
|
861
|
-
const timing = window.performance.timing;
|
|
862
|
-
const startTime = timing.navigationStart || timing.fetchStart;
|
|
863
|
-
let firstPaintTime: any;
|
|
864
|
-
let firstContentfulPaintTime: any;
|
|
865
|
-
// 是否已经形成数据(页面加载完成之后)
|
|
866
|
-
if (window.performance && window.performance.timing && window.performance.timing.loadEventEnd > 0) {
|
|
867
|
-
// console.log('created')
|
|
868
|
-
getTiming();
|
|
869
|
-
} else {
|
|
870
|
-
// console.log('creating')
|
|
871
|
-
window.addEventListener("load", function() {
|
|
872
|
-
//不能影响最后的时间计算
|
|
873
|
-
window.setTimeout(function() {
|
|
874
|
-
getTiming();
|
|
875
|
-
}, 0);
|
|
876
|
-
});
|
|
877
|
-
}
|
|
878
|
-
// performance
|
|
879
|
-
function getTiming() {
|
|
880
|
-
// 获取首次渲染时间
|
|
881
|
-
try {
|
|
882
|
-
if (window.performance && Boolean(window.performance.getEntriesByType)) {
|
|
883
|
-
const performance = window.performance;
|
|
884
|
-
const performanceEntries = performance.getEntriesByType('paint');
|
|
885
|
-
performanceEntries.forEach((performanceEntry, i, entries) => {
|
|
886
|
-
const startTime = Math.round(performanceEntry.startTime);
|
|
887
|
-
if (performanceEntry.name === 'first-paint')
|
|
888
|
-
firstPaintTime = startTime;
|
|
889
|
-
else if (performanceEntry.name === 'first-contentful-paint')
|
|
890
|
-
firstContentfulPaintTime = startTime;
|
|
891
|
-
});
|
|
892
|
-
} else {
|
|
893
|
-
console.error('paint');
|
|
894
|
-
}
|
|
895
|
-
} catch (e) {
|
|
896
|
-
console.error((e as any).message);
|
|
897
|
-
}
|
|
898
|
-
// 获取加载时间
|
|
899
|
-
if (
|
|
900
|
-
window.performance &&
|
|
901
|
-
typeof window.performance.getEntries === 'function'
|
|
902
|
-
) {
|
|
903
|
-
const performanceNavigationTiming: any =
|
|
904
|
-
(window.performance.getEntries() || [])[0] || {};
|
|
905
|
-
const data: any = {
|
|
906
|
-
// url: encodeURI(location.href),
|
|
907
|
-
// ua: navigator.userAgent,
|
|
908
|
-
os: getOS(),
|
|
909
|
-
osVersion: getOSVersion(),
|
|
910
|
-
deviceType: getDeviceType(),
|
|
911
|
-
network: getNetWork(),
|
|
912
|
-
screenDirection: getOrientationStatu(),
|
|
913
|
-
unloadTime: timing.unloadEventEnd - timing.unloadEventStart, //上个文档的卸载时间
|
|
914
|
-
redirectTime: timing.redirectEnd - timing.redirectStart, //*重定向时间
|
|
915
|
-
dnsTime: timing.domainLookupEnd - timing.domainLookupStart, //*DNS查询时间
|
|
916
|
-
tcpTime: timing.connectEnd - timing.connectStart, //*服务器连接时间
|
|
917
|
-
sslTime: getSSLTime(timing.connectEnd, timing.secureConnectionStart), //*ssl连接时间
|
|
918
|
-
responseTime: timing.responseStart - timing.requestStart, //*服务器响应时间
|
|
919
|
-
downloadTime: timing.responseEnd - timing.responseStart, //*网页下载时间
|
|
920
|
-
firstPaintTime: firstPaintTime, //*首次渲染时间
|
|
921
|
-
firstContentfulPaintTime: firstContentfulPaintTime, //*首次渲染内容时间
|
|
922
|
-
domreadyTime: timing.domContentLoadedEventStart - startTime || 0, //*dom ready时间(总和)
|
|
923
|
-
onloadTime: timing.loadEventStart - startTime || 0, //*onload时间(总和)
|
|
924
|
-
whiteTime: timing.responseStart - startTime, //*白屏时间
|
|
925
|
-
renderTime: timing.loadEventEnd - startTime || 0, //整个过程的时间之和
|
|
926
|
-
decodedBodySize: performanceNavigationTiming.decodedBodySize || '', //页面压缩前大小
|
|
927
|
-
encodedBodySize: performanceNavigationTiming.encodedBodySize || '', //页面压缩后大小
|
|
928
|
-
};
|
|
929
|
-
// 过滤异常数据
|
|
930
|
-
Object.keys(data).forEach(k => {
|
|
931
|
-
// 过滤掉 <0 的数据
|
|
932
|
-
if (isNumber(data[k]) && data[k] < 0) {
|
|
933
|
-
data[k] = 0;
|
|
934
|
-
}
|
|
935
|
-
});
|
|
936
|
-
// 过滤掉白屏时间 > onload 的数据
|
|
937
|
-
if (isNumber(data.whiteTime) && data.whiteTime > data.onloadTime) {
|
|
938
|
-
data.whiteTime = 0;
|
|
939
|
-
}
|
|
940
|
-
if (startTime > 0) {
|
|
941
|
-
let Underscore: any;
|
|
942
|
-
if (!camelCase) {
|
|
943
|
-
Object.keys(data).forEach(k => {
|
|
944
|
-
if (!Underscore) Underscore = {};
|
|
945
|
-
// console.log('camelCase2Underscore', k, data, )
|
|
946
|
-
Underscore[camelCase2Underscore(k)] = data[k];
|
|
947
|
-
});
|
|
948
|
-
}
|
|
949
|
-
success(Underscore || data);
|
|
950
|
-
} else {
|
|
951
|
-
fail(Error('startTime'));
|
|
952
|
-
}
|
|
953
|
-
} else {
|
|
954
|
-
fail(Error('getEntries'));
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
//获取当前操作系统
|
|
958
|
-
function getOS() {
|
|
959
|
-
let os;
|
|
960
|
-
if (navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1) {
|
|
961
|
-
os = 'android';
|
|
962
|
-
} else if (navigator.userAgent.indexOf('iPhone') > -1) {
|
|
963
|
-
os = 'ios';
|
|
964
|
-
} else if (navigator.userAgent.indexOf('Windows Phone') > -1) {
|
|
965
|
-
os = 'wp';
|
|
966
|
-
} else {
|
|
967
|
-
os = 'others';
|
|
968
|
-
}
|
|
969
|
-
return os;
|
|
970
|
-
}
|
|
971
|
-
// 获取操作系统版本
|
|
972
|
-
function getOSVersion() {
|
|
973
|
-
let OSVision: any;
|
|
974
|
-
const u = navigator.userAgent;
|
|
975
|
-
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //Android
|
|
976
|
-
const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
|
|
977
|
-
if (isAndroid) {
|
|
978
|
-
OSVision = (navigator.userAgent.split(';')[1].match(/\d+\.\d+/g) || [])[0];
|
|
979
|
-
}
|
|
980
|
-
if (isIOS) {
|
|
981
|
-
OSVision = (navigator.userAgent.split(';')[1].match(/(\d+)_(\d+)_?(\d+)?/) || [])[0];
|
|
982
|
-
}
|
|
983
|
-
return OSVision;
|
|
984
|
-
}
|
|
985
|
-
//获取设备类型
|
|
986
|
-
function getDeviceType() {
|
|
987
|
-
let deviceType;
|
|
988
|
-
const sUserAgent = navigator.userAgent.toLowerCase();
|
|
989
|
-
const bIsIpad = sUserAgent.match(/(ipad)/i) && 'ipad';
|
|
990
|
-
const bIsIphoneOs = sUserAgent.match(/iphone os/i) && 'iphone os';
|
|
991
|
-
const bIsMidp = sUserAgent.match(/midp/i) && 'midp';
|
|
992
|
-
const bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) && 'rv:1.2.3.4';
|
|
993
|
-
const bIsUc = sUserAgent.match(/ucweb/i) && 'ucweb';
|
|
994
|
-
const bIsAndroid = sUserAgent.match(/android/i) && 'android';
|
|
995
|
-
const bIsCE = sUserAgent.match(/windows ce/i) && 'windows ce';
|
|
996
|
-
const bIsWM = sUserAgent.match(/windows mobile/i) && 'windows mobile';
|
|
997
|
-
if (!(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM)) {
|
|
998
|
-
deviceType = 'pc'; //pc
|
|
999
|
-
} else if (bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
|
|
1000
|
-
deviceType = 'phone'; //phone
|
|
1001
|
-
} else if (bIsIpad) {
|
|
1002
|
-
deviceType = 'ipad'; //ipad
|
|
1003
|
-
} else {
|
|
1004
|
-
deviceType = undefined;
|
|
1005
|
-
}
|
|
1006
|
-
return deviceType;
|
|
1007
|
-
}
|
|
1008
|
-
// 获取网络状态
|
|
1009
|
-
function getNetWork() {
|
|
1010
|
-
let netWork: any;
|
|
1011
|
-
if ((navigator as any).connection && (navigator as any).connection.effectiveType) {
|
|
1012
|
-
switch ((navigator as any).connection.effectiveType) {
|
|
1013
|
-
case 'wifi':
|
|
1014
|
-
netWork = 'wifi'; // wifi
|
|
1015
|
-
break;
|
|
1016
|
-
case '4g':
|
|
1017
|
-
netWork = '4g'; // 4g
|
|
1018
|
-
break;
|
|
1019
|
-
case '2g':
|
|
1020
|
-
netWork = '2g'; // 2g
|
|
1021
|
-
break;
|
|
1022
|
-
case '3g':
|
|
1023
|
-
netWork = '3g'; // 3g
|
|
1024
|
-
break;
|
|
1025
|
-
case 'ethernet':
|
|
1026
|
-
netWork = 'ethernet'; // ethernet
|
|
1027
|
-
break;
|
|
1028
|
-
case 'default':
|
|
1029
|
-
netWork = undefined; // 未知
|
|
1030
|
-
break;
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
return netWork;
|
|
1034
|
-
}
|
|
1035
|
-
// 获取横竖屏状态
|
|
1036
|
-
function getOrientationStatu() {
|
|
1037
|
-
let orientationStatu: any;
|
|
1038
|
-
if (window.screen && window.screen.orientation && window.screen.orientation.angle) {
|
|
1039
|
-
if (window.screen.orientation.angle === 180 || window.screen.orientation.angle === 0) { // 竖屏
|
|
1040
|
-
orientationStatu = '|';
|
|
1041
|
-
}
|
|
1042
|
-
if (window.screen.orientation.angle === 90 || window.screen.orientation.angle === -90) { // 横屏
|
|
1043
|
-
orientationStatu = '-';
|
|
1044
|
-
}
|
|
1045
|
-
}
|
|
1046
|
-
return orientationStatu;
|
|
1047
|
-
}
|
|
1048
|
-
// 获取ssl连接时间
|
|
1049
|
-
function getSSLTime(connectEnd: any, secureConnectionStart: any) {
|
|
1050
|
-
let ssl_time: any;
|
|
1051
|
-
if (secureConnectionStart) {
|
|
1052
|
-
ssl_time = connectEnd - secureConnectionStart;
|
|
1053
|
-
}
|
|
1054
|
-
return ssl_time;
|
|
1055
|
-
}
|
|
1056
|
-
return status;
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
/**
|
|
1060
|
-
* @method inRate
|
|
1061
|
-
* @description 百分位概率
|
|
1062
|
-
* @param {number} rate -- 0.1 ~ 1 => 1% ~ 100%
|
|
1063
|
-
* @returns {boolean} true 命中
|
|
1064
|
-
*/
|
|
1065
|
-
export function inRate(rate: number): boolean {
|
|
1066
|
-
if(Math.random() < rate) {
|
|
1067
|
-
return true;
|
|
1068
|
-
}
|
|
1069
|
-
return false;
|
|
1070
|
-
}
|
|
1071
|
-
|
|
1072
|
-
/**
|
|
1073
|
-
* @method isSafePWAEnv
|
|
1074
|
-
* @description 判断是否是安全的 PWA 环境
|
|
1075
|
-
* @returns {boolean} true 是
|
|
1076
|
-
*/
|
|
1077
|
-
export function isSafePWAEnv(): boolean {
|
|
1078
|
-
// 判断是否支持 async await
|
|
1079
|
-
function isSupportAsyncAwait() {
|
|
1080
|
-
let isSupportAsyncAwaitFunc;
|
|
1081
|
-
try {
|
|
1082
|
-
// eval("func = async function(){};");
|
|
1083
|
-
const fn = new Function("return async function(){};");
|
|
1084
|
-
isSupportAsyncAwaitFunc = fn();
|
|
1085
|
-
// console.log('isSupportAsyncAwaitFunc', isSupportAsyncAwaitFunc);
|
|
1086
|
-
// 由于async函数的构造器不是全局对象,所以我们需要由下面代码来获取async函数的构造器
|
|
1087
|
-
// 具体可以查看以下MDN上有关于AsyncFunction的说明,
|
|
1088
|
-
// 地址:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction
|
|
1089
|
-
return Object.getPrototypeOf(isSupportAsyncAwaitFunc).constructor != null;
|
|
1090
|
-
} catch (e) {
|
|
1091
|
-
return false;
|
|
1092
|
-
}
|
|
1093
|
-
}
|
|
1094
|
-
// 判断是否支持 Promise
|
|
1095
|
-
function isSupportPromise() {
|
|
1096
|
-
if(typeof Promise !== "undefined" && Promise.toString().indexOf("[native code]") !== -1){
|
|
1097
|
-
return true;
|
|
1098
|
-
}
|
|
1099
|
-
return false;
|
|
1100
|
-
}
|
|
1101
|
-
// 浏览器信息
|
|
1102
|
-
const BrowserType = getBrowserInfo();
|
|
1103
|
-
if (
|
|
1104
|
-
('serviceWorker' in navigator) &&
|
|
1105
|
-
isSupportAsyncAwait() &&
|
|
1106
|
-
isSupportPromise() &&
|
|
1107
|
-
Boolean(window.fetch) &&
|
|
1108
|
-
Boolean(window.indexedDB) &&
|
|
1109
|
-
Boolean(window.caches) &&
|
|
1110
|
-
!BrowserType['shell']
|
|
1111
|
-
) {
|
|
1112
|
-
return true;
|
|
1113
|
-
}
|
|
1114
|
-
return false;
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
/**
|
|
1118
|
-
* EN: Browser Information
|
|
1119
|
-
*
|
|
1120
|
-
* ZH: 返回浏览器信息 https://github.com/JowayYoung/juejin-code/blob/master/browser-type.js
|
|
1121
|
-
*
|
|
1122
|
-
* ```
|
|
1123
|
-
* getBrowserInfo(); // {"engine":"webkit","engineVs":"537.36","platform":"desktop","supporter":"chrome","supporterVs":"85.0.4183.121","system":"windows","systemVs":"10"}
|
|
1124
|
-
* ```
|
|
1125
|
-
*
|
|
1126
|
-
* | Index | Field | Description |
|
|
1127
|
-
* | --- | --- | --- |
|
|
1128
|
-
* | System | system | android, ios, windows, macos, linux |
|
|
1129
|
-
* | System version | systemVs | windows: 2000, xp, 2003, vista, 7, 8, 8.1, 10 <br />macos: ... |
|
|
1130
|
-
* | Platform | platform | desktop, mobile |
|
|
1131
|
-
* | Engine | engine | webkit, gecko, presto, trident |
|
|
1132
|
-
* | Engine version | engineVs | - |
|
|
1133
|
-
* | Supporter | supporter | edge, opera, chrome, safari, firefox, iexplore |
|
|
1134
|
-
* | Supporter version | supporterVs | - |
|
|
1135
|
-
* | Shell | shell | (Optional) wechat, qq_browser, qq_app, uc, 360, 2345, sougou, liebao, maxthon, bilibili |
|
|
1136
|
-
* | Shell version | shellVs | (Optional) |
|
|
1137
|
-
* | Apple device type | appleType | (Optional) iphone, ipad, ipod, iwatch |
|
|
1138
|
-
*
|
|
1139
|
-
* Example: Determine the environment of the mobile QQ.
|
|
1140
|
-
*
|
|
1141
|
-
* ```
|
|
1142
|
-
* const { system, shell } = getBrowserInfo();
|
|
1143
|
-
* const isMobileQQ = ['android', 'ios'].includes(system) && ['qq_browser', 'qq_app'].includes(shell);
|
|
1144
|
-
* ```
|
|
1145
|
-
*
|
|
1146
|
-
* @returns 浏览器信息
|
|
1147
|
-
*/
|
|
1148
|
-
export function getBrowserInfo(): {
|
|
1149
|
-
engine: string; // webkit gecko presto trident
|
|
1150
|
-
engineVs: string;
|
|
1151
|
-
platform: string; // desktop mobile
|
|
1152
|
-
supporter: string; // chrome safari firefox opera iexplore edge
|
|
1153
|
-
supporterVs: string;
|
|
1154
|
-
system: string; // windows macos linux android ios
|
|
1155
|
-
systemVs: string;
|
|
1156
|
-
shell?: string; // wechat qq uc 360 2345 sougou liebao maxthon
|
|
1157
|
-
shellVs?: string;
|
|
1158
|
-
appleType?: string;
|
|
1159
|
-
} {
|
|
1160
|
-
try {
|
|
1161
|
-
// 权重:系统 + 系统版本 > 平台 > 内核 + 载体 + 内核版本 + 载体版本 > 外壳 + 外壳版本
|
|
1162
|
-
const ua: string = navigator.userAgent.toLowerCase();
|
|
1163
|
-
const testUa: (regexp: RegExp) => boolean = regexp => regexp.test(ua);
|
|
1164
|
-
const testVs: (regexp: RegExp) => string = regexp => {
|
|
1165
|
-
const matchRes = ua.match(regexp);
|
|
1166
|
-
let ret = '';
|
|
1167
|
-
if (matchRes) {
|
|
1168
|
-
ret = matchRes
|
|
1169
|
-
.toString()
|
|
1170
|
-
.replace(/[^0-9|_.]/g, "")
|
|
1171
|
-
.replace(/_/g, ".");
|
|
1172
|
-
}
|
|
1173
|
-
return ret;
|
|
1174
|
-
};
|
|
1175
|
-
// 系统
|
|
1176
|
-
let system = '';
|
|
1177
|
-
// Apple device type.
|
|
1178
|
-
let appleType = '';
|
|
1179
|
-
if (testUa(/windows|win32|win64|wow32|wow64/g)) {
|
|
1180
|
-
system = "windows"; // windows系统
|
|
1181
|
-
} else if (testUa(/macintosh|macintel/g)) {
|
|
1182
|
-
system = "macos"; // macos系统
|
|
1183
|
-
} else if (testUa(/x11/g)) {
|
|
1184
|
-
system = "linux"; // linux系统
|
|
1185
|
-
} else if (testUa(/android|adr/g)) {
|
|
1186
|
-
system = "android"; // android系统
|
|
1187
|
-
} else if (testUa(/ios|iphone|ipad|ipod|iwatch/g)) {
|
|
1188
|
-
system = "ios"; // ios系统
|
|
1189
|
-
if (testUa(/iphone/g)) {
|
|
1190
|
-
appleType = 'iphone';
|
|
1191
|
-
} else if (testUa(/ipad/g)) {
|
|
1192
|
-
appleType = 'ipad';
|
|
1193
|
-
} else if (testUa(/iwatch/g)) {
|
|
1194
|
-
appleType = 'iwatch';
|
|
1195
|
-
} else if (testUa(/ipod/g)) {
|
|
1196
|
-
appleType = 'ipod';
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
// 系统版本
|
|
1200
|
-
let systemVs = '';
|
|
1201
|
-
if (system === "windows") {
|
|
1202
|
-
if (testUa(/windows nt 5.0|windows 2000/g)) {
|
|
1203
|
-
systemVs = "2000";
|
|
1204
|
-
} else if (testUa(/windows nt 5.1|windows xp/g)) {
|
|
1205
|
-
systemVs = "xp";
|
|
1206
|
-
} else if (testUa(/windows nt 5.2|windows 2003/g)) {
|
|
1207
|
-
systemVs = "2003";
|
|
1208
|
-
} else if (testUa(/windows nt 6.0|windows vista/g)) {
|
|
1209
|
-
systemVs = "vista";
|
|
1210
|
-
} else if (testUa(/windows nt 6.1|windows 7/g)) {
|
|
1211
|
-
systemVs = "7";
|
|
1212
|
-
} else if (testUa(/windows nt 6.2|windows 8/g)) {
|
|
1213
|
-
systemVs = "8";
|
|
1214
|
-
} else if (testUa(/windows nt 6.3|windows 8.1/g)) {
|
|
1215
|
-
systemVs = "8.1";
|
|
1216
|
-
} else if (testUa(/windows nt 10.0|windows 10/g)) {
|
|
1217
|
-
systemVs = "10";
|
|
1218
|
-
}
|
|
1219
|
-
} else if (system === "macos") {
|
|
1220
|
-
systemVs = testVs(/os x [\d._]+/g);
|
|
1221
|
-
} else if (system === "android") {
|
|
1222
|
-
systemVs = testVs(/android [\d._]+/g);
|
|
1223
|
-
} else if (system === "ios") {
|
|
1224
|
-
systemVs = testVs(/os [\d._]+/g);
|
|
1225
|
-
}
|
|
1226
|
-
// 平台
|
|
1227
|
-
let platform = '';
|
|
1228
|
-
if (system === "windows" || system === "macos" || system === "linux") {
|
|
1229
|
-
platform = "desktop"; // 桌面端
|
|
1230
|
-
} else if (system === "android" || system === "ios" || testUa(/mobile/g)) {
|
|
1231
|
-
platform = "mobile"; // 移动端
|
|
1232
|
-
}
|
|
1233
|
-
// 内核和载体
|
|
1234
|
-
let engine = '';
|
|
1235
|
-
let supporter = '';
|
|
1236
|
-
if (testUa(/applewebkit/g)) {
|
|
1237
|
-
engine = "webkit"; // webkit内核
|
|
1238
|
-
if (testUa(/edge/g)) {
|
|
1239
|
-
supporter = "edge"; // edge浏览器
|
|
1240
|
-
} else if (testUa(/opr/g)) {
|
|
1241
|
-
supporter = "opera"; // opera浏览器
|
|
1242
|
-
} else if (testUa(/chrome/g)) {
|
|
1243
|
-
supporter = "chrome"; // chrome浏览器
|
|
1244
|
-
} else if (testUa(/safari/g)) {
|
|
1245
|
-
supporter = "safari"; // safari浏览器
|
|
1246
|
-
}
|
|
1247
|
-
} else if (testUa(/gecko/g) && testUa(/firefox/g)) {
|
|
1248
|
-
engine = "gecko"; // gecko内核
|
|
1249
|
-
supporter = "firefox"; // firefox浏览器
|
|
1250
|
-
} else if (testUa(/presto/g)) {
|
|
1251
|
-
engine = "presto"; // presto内核
|
|
1252
|
-
supporter = "opera"; // opera浏览器
|
|
1253
|
-
} else if (testUa(/trident|compatible|msie/g)) {
|
|
1254
|
-
engine = "trident"; // trident内核
|
|
1255
|
-
supporter = "iexplore"; // iexplore浏览器
|
|
1256
|
-
}
|
|
1257
|
-
// 内核版本
|
|
1258
|
-
let engineVs = '';
|
|
1259
|
-
if (engine === "webkit") {
|
|
1260
|
-
engineVs = testVs(/applewebkit\/[\d._]+/g);
|
|
1261
|
-
} else if (engine === "gecko") {
|
|
1262
|
-
engineVs = testVs(/gecko\/[\d._]+/g);
|
|
1263
|
-
} else if (engine === "presto") {
|
|
1264
|
-
engineVs = testVs(/presto\/[\d._]+/g);
|
|
1265
|
-
} else if (engine === "trident") {
|
|
1266
|
-
engineVs = testVs(/trident\/[\d._]+/g);
|
|
1267
|
-
}
|
|
1268
|
-
// 载体版本
|
|
1269
|
-
let supporterVs = '';
|
|
1270
|
-
if (supporter === "chrome") {
|
|
1271
|
-
supporterVs = testVs(/chrome\/[\d._]+/g);
|
|
1272
|
-
} else if (supporter === "safari") {
|
|
1273
|
-
supporterVs = testVs(/version\/[\d._]+/g);
|
|
1274
|
-
} else if (supporter === "firefox") {
|
|
1275
|
-
supporterVs = testVs(/firefox\/[\d._]+/g);
|
|
1276
|
-
} else if (supporter === "opera") {
|
|
1277
|
-
supporterVs = testVs(/opr\/[\d._]+/g);
|
|
1278
|
-
} else if (supporter === "iexplore") {
|
|
1279
|
-
supporterVs = testVs(/(msie [\d._]+)|(rv:[\d._]+)/g);
|
|
1280
|
-
} else if (supporter === "edge") {
|
|
1281
|
-
supporterVs = testVs(/edge\/[\d._]+/g);
|
|
1282
|
-
}
|
|
1283
|
-
// 外壳和外壳版本
|
|
1284
|
-
let shell = '';
|
|
1285
|
-
let shellVs = '';
|
|
1286
|
-
if (testUa(/micromessenger/g)) {
|
|
1287
|
-
shell = "wechat"; // 微信浏览器
|
|
1288
|
-
shellVs = testVs(/micromessenger\/[\d._]+/g);
|
|
1289
|
-
} else if (testUa(/qqbrowser/g)) {
|
|
1290
|
-
shell = "qq_browser"; // QQ Browser
|
|
1291
|
-
shellVs = testVs(/qqbrowser\/[\d._]+/g);
|
|
1292
|
-
} else if (testUa(/\sqq/g)) {
|
|
1293
|
-
shell = "qq_app"; // QQ APP
|
|
1294
|
-
} else if (testUa(/ucbrowser/g)) {
|
|
1295
|
-
shell = "uc"; // UC浏览器
|
|
1296
|
-
shellVs = testVs(/ucbrowser\/[\d._]+/g);
|
|
1297
|
-
} else if (testUa(/qihu 360se/g)) {
|
|
1298
|
-
shell = "360"; // 360浏览器(无版本)
|
|
1299
|
-
} else if (testUa(/2345explorer/g)) {
|
|
1300
|
-
shell = "2345"; // 2345浏览器
|
|
1301
|
-
shellVs = testVs(/2345explorer\/[\d._]+/g);
|
|
1302
|
-
} else if (testUa(/metasr/g)) {
|
|
1303
|
-
shell = "sougou"; // 搜狗浏览器(无版本)
|
|
1304
|
-
} else if (testUa(/lbbrowser/g)) {
|
|
1305
|
-
shell = "liebao"; // 猎豹浏览器(无版本)
|
|
1306
|
-
} else if (testUa(/maxthon/g)) {
|
|
1307
|
-
shell = "maxthon"; // 遨游浏览器
|
|
1308
|
-
shellVs = testVs(/maxthon\/[\d._]+/g);
|
|
1309
|
-
} else if (testUa(/biliapp/g)) {
|
|
1310
|
-
shell = "bilibili"; // 哔哩哔哩
|
|
1311
|
-
}
|
|
1312
|
-
return Object.assign({
|
|
1313
|
-
engine, // webkit gecko presto trident
|
|
1314
|
-
engineVs,
|
|
1315
|
-
platform, // desktop mobile
|
|
1316
|
-
supporter, // chrome safari firefox opera iexplore edge
|
|
1317
|
-
supporterVs,
|
|
1318
|
-
system, // windows macos linux android ios
|
|
1319
|
-
systemVs,
|
|
1320
|
-
}, {
|
|
1321
|
-
shell, // wechat qq uc 360 2345 sougou liebao maxthon
|
|
1322
|
-
shellVs,
|
|
1323
|
-
appleType,
|
|
1324
|
-
});
|
|
1325
|
-
} catch (err) {
|
|
1326
|
-
console.warn('mazey:', err);
|
|
1327
|
-
return {
|
|
1328
|
-
engine: '', // webkit gecko presto trident
|
|
1329
|
-
engineVs: '',
|
|
1330
|
-
platform: '', // desktop mobile
|
|
1331
|
-
supporter: '', // chrome safari firefox opera iexplore edge
|
|
1332
|
-
supporterVs: '',
|
|
1333
|
-
system: '', // windows macos linux android ios
|
|
1334
|
-
systemVs: '',
|
|
1335
|
-
};
|
|
1336
|
-
}
|
|
1337
|
-
}
|
|
1338
|
-
|
|
1339
|
-
/**
|
|
1340
|
-
* @method clearHtml
|
|
1341
|
-
* @description 去除HTML标签
|
|
1342
|
-
* @param {string} str 带html标签的字符串
|
|
1343
|
-
* @returns {string} 字符串
|
|
1344
|
-
*/
|
|
1345
|
-
export function clearHtml (str: string): string {
|
|
1346
|
-
return str.replace(/<\/?.+?>/g, '').replace(/[\r\n]/g, '');
|
|
1347
|
-
}
|
|
1348
|
-
|
|
1349
|
-
/**
|
|
1350
|
-
* @method cutCHSString
|
|
1351
|
-
* @description 截取字符串,中文算2个字节
|
|
1352
|
-
* @param {string} str 要截取的字符串
|
|
1353
|
-
* @param {number} len
|
|
1354
|
-
* @param {boolean} hasDot
|
|
1355
|
-
* @returnss {string} 返回截取后的字符串
|
|
1356
|
-
*/
|
|
1357
|
-
export function cutCHSString(str: string, len: number, hasDot = false): string {
|
|
1358
|
-
if (str == '' || !str) {
|
|
1359
|
-
return '';
|
|
1360
|
-
} else {
|
|
1361
|
-
let newLength = 0;
|
|
1362
|
-
let newStr = '';
|
|
1363
|
-
// eslint-disable-next-line no-control-regex
|
|
1364
|
-
const chineseRegex = /[^\x00-\xff]/g;
|
|
1365
|
-
let singleChar = '';
|
|
1366
|
-
const strLength = str.replace(chineseRegex, '**').length;
|
|
1367
|
-
for (let i = 0; i < strLength; i++) {
|
|
1368
|
-
singleChar = str.charAt(i).toString();
|
|
1369
|
-
if (singleChar.match(chineseRegex) != null) {
|
|
1370
|
-
newLength += 2;
|
|
1371
|
-
} else {
|
|
1372
|
-
newLength++;
|
|
1373
|
-
}
|
|
1374
|
-
if (newLength > len) {
|
|
1375
|
-
break;
|
|
1376
|
-
}
|
|
1377
|
-
newStr += singleChar;
|
|
1378
|
-
}
|
|
1379
|
-
|
|
1380
|
-
if (hasDot && strLength > len) {
|
|
1381
|
-
newStr += '...';
|
|
1382
|
-
}
|
|
1383
|
-
return newStr;
|
|
1384
|
-
}
|
|
1385
|
-
}
|
|
1386
|
-
|
|
1387
|
-
/**
|
|
1388
|
-
* @method windowLoaded
|
|
1389
|
-
* @description 页面加载完成
|
|
1390
|
-
* @param {number} timeout 超时时间 / 单位:秒
|
|
1391
|
-
* @returns {Promise<string>} document is loaded? 'complete' 'load' / 'timeout'
|
|
1392
|
-
*/
|
|
1393
|
-
export function windowLoaded(timeout = 90): Promise<string | Error> {
|
|
1394
|
-
let loaded: (value: string) => void = () => undefined;
|
|
1395
|
-
let loadFail: (value: Error) => void;
|
|
1396
|
-
const status = new Promise((resolve: (value: string) => void, reject: (value: Error) => void) => {
|
|
1397
|
-
loaded = resolve;
|
|
1398
|
-
loadFail = reject;
|
|
1399
|
-
});
|
|
1400
|
-
if (document.readyState === 'complete') {
|
|
1401
|
-
loaded('complete');
|
|
1402
|
-
} else {
|
|
1403
|
-
window.addEventListener('load', () => loaded('load'));
|
|
1404
|
-
}
|
|
1405
|
-
// 超过 timeout 秒后加载失败
|
|
1406
|
-
setTimeout(() => loadFail(Error('timeout')), timeout * 1000);
|
|
1407
|
-
return status;
|
|
1408
|
-
}
|
|
1409
|
-
|
|
1410
|
-
/**
|
|
1411
|
-
* EN: Add `<style>` in `<head>`.
|
|
1412
|
-
*
|
|
1413
|
-
* ZH: 添加样式标签; style: 样式标签内的字符串; id: `<style>` 标签的 `id`; 返回: 添加成功/失败.
|
|
1414
|
-
*
|
|
1415
|
-
* Example 1: Add the `<style>` with `id`, and repeated invoking will update the content instead of adding a new one.
|
|
1416
|
-
*
|
|
1417
|
-
* ```
|
|
1418
|
-
* addStyle(
|
|
1419
|
-
* `
|
|
1420
|
-
* body {
|
|
1421
|
-
* background-color: #333;
|
|
1422
|
-
* }
|
|
1423
|
-
* `,
|
|
1424
|
-
* {
|
|
1425
|
-
* id: 'test',
|
|
1426
|
-
* }
|
|
1427
|
-
* );
|
|
1428
|
-
* // <style id="test">
|
|
1429
|
-
* // body {
|
|
1430
|
-
* // background-color: #333;
|
|
1431
|
-
* // }
|
|
1432
|
-
* // </style>
|
|
1433
|
-
* ```
|
|
1434
|
-
*
|
|
1435
|
-
* Example 2: Add the `<style>` without `id`, and repeated invoking will adding a new one.
|
|
1436
|
-
*
|
|
1437
|
-
* ```
|
|
1438
|
-
* addStyle(
|
|
1439
|
-
* `
|
|
1440
|
-
* body {
|
|
1441
|
-
* background-color: #333;
|
|
1442
|
-
* }
|
|
1443
|
-
* `
|
|
1444
|
-
* );
|
|
1445
|
-
* // <style>
|
|
1446
|
-
* // body {
|
|
1447
|
-
* // background-color: #333;
|
|
1448
|
-
* // }
|
|
1449
|
-
* // </style>
|
|
1450
|
-
* ```
|
|
1451
|
-
*
|
|
1452
|
-
* @param style Style string.
|
|
1453
|
-
* @param options.id `id` in `<style>`
|
|
1454
|
-
* @returns Success/Fail
|
|
1455
|
-
*/
|
|
1456
|
-
export function addStyle(style: string, options: { id?: string; } = { id: '' }): boolean {
|
|
1457
|
-
// console.log('_ style', style);
|
|
1458
|
-
// console.log('_ options', options);
|
|
1459
|
-
if (!style) {
|
|
1460
|
-
return false;
|
|
1461
|
-
}
|
|
1462
|
-
// 创建 style 文档碎片
|
|
1463
|
-
const styleFrag = document.createDocumentFragment();
|
|
1464
|
-
let idDom: HTMLElement | null = null;
|
|
1465
|
-
let domId = '';
|
|
1466
|
-
// Custom Style
|
|
1467
|
-
const customStyle = document.createElement('style');
|
|
1468
|
-
// 如果需要 ID
|
|
1469
|
-
if (options.id) {
|
|
1470
|
-
domId = `${options.id}`;
|
|
1471
|
-
idDom = document.getElementById(domId);
|
|
1472
|
-
// 如果 Dom 不存在,插入 style
|
|
1473
|
-
if (!idDom) {
|
|
1474
|
-
customStyle.setAttribute('id', options.id);
|
|
1475
|
-
customStyle.innerHTML = style;
|
|
1476
|
-
styleFrag.appendChild(customStyle);
|
|
1477
|
-
document.head.appendChild(styleFrag);
|
|
1478
|
-
} else { // 如果 Dom 存在,直接更新
|
|
1479
|
-
idDom.innerHTML = style;
|
|
1480
|
-
}
|
|
1481
|
-
} else { // 不需要 ID,直接添加新标签
|
|
1482
|
-
customStyle.innerHTML = style;
|
|
1483
|
-
styleFrag.appendChild(customStyle);
|
|
1484
|
-
document.head.appendChild(styleFrag);
|
|
1485
|
-
}
|
|
1486
|
-
return true;
|
|
1487
|
-
}
|
|
1488
|
-
|
|
1489
|
-
/**
|
|
1490
|
-
* @method genCustomConsole
|
|
1491
|
-
* @description 生成自定义控制台打印
|
|
1492
|
-
* @param {string} prefix 前缀
|
|
1493
|
-
* @param {function} allowFn 允许打印的判断函数
|
|
1494
|
-
* @returns {object} 新实例
|
|
1495
|
-
*/
|
|
1496
|
-
export function genCustomConsole(prefix = ''): Console {
|
|
1497
|
-
const methods = ['log', 'info', 'warn', 'error'];
|
|
1498
|
-
const newConsole = Object.create(null);
|
|
1499
|
-
methods.forEach(method => {
|
|
1500
|
-
newConsole[method] = function (...argu: any) {
|
|
1501
|
-
if (prefix) {
|
|
1502
|
-
(console as any)[method](prefix, ...argu);
|
|
1503
|
-
} else {
|
|
1504
|
-
(console as any)[method](...argu);
|
|
1505
|
-
}
|
|
1506
|
-
};
|
|
1507
|
-
});
|
|
1508
|
-
return newConsole;
|
|
1509
|
-
}
|
|
1510
|
-
|
|
1511
|
-
/**
|
|
1512
|
-
* Verify the validity of axios response.
|
|
1513
|
-
*
|
|
1514
|
-
* Reference: [Handling Errors](https://axios-http.com/docs/handling_errors)
|
|
1515
|
-
*/
|
|
1516
|
-
export function zAxiosIsValidRes(res: any, options: {
|
|
1517
|
-
validStatusRange: number[];
|
|
1518
|
-
validCode: number[];
|
|
1519
|
-
} = {
|
|
1520
|
-
validStatusRange: [200, 300],
|
|
1521
|
-
validCode: [0],
|
|
1522
|
-
}): boolean {
|
|
1523
|
-
const { validStatusRange, validCode } = Object.assign(
|
|
1524
|
-
{
|
|
1525
|
-
validStatusRange: [200, 300],
|
|
1526
|
-
validCode: [0],
|
|
1527
|
-
},
|
|
1528
|
-
options,
|
|
1529
|
-
);
|
|
1530
|
-
if (validStatusRange.length !== 2) {
|
|
1531
|
-
console.error('valid validStatusRange is required');
|
|
1532
|
-
}
|
|
1533
|
-
let ret = false;
|
|
1534
|
-
if (res && res.status && validStatusRange.length === 2 && res.status >= validStatusRange[0] && res.status < validStatusRange[1]) {
|
|
1535
|
-
const resData = res.data;
|
|
1536
|
-
if (resData && validCode.includes(resData.code)) {
|
|
1537
|
-
ret = true;
|
|
1538
|
-
}
|
|
1539
|
-
}
|
|
1540
|
-
return ret;
|
|
1541
|
-
}
|
|
1542
|
-
|
|
1543
|
-
/**
|
|
1544
|
-
* Verify the validity of a non-empty array.
|
|
1545
|
-
*/
|
|
1546
|
-
export function isNonEmptyArray(arr: any[]): boolean {
|
|
1547
|
-
let ret = false;
|
|
1548
|
-
if (Array.isArray(arr) && arr.length) {
|
|
1549
|
-
ret = true;
|
|
1550
|
-
}
|
|
1551
|
-
return ret;
|
|
1552
|
-
}
|
|
1553
|
-
|
|
1554
|
-
/**
|
|
1555
|
-
* 语义化文件大小, 把字节转换成正常文件大小.
|
|
1556
|
-
*/
|
|
1557
|
-
export function getFileSize(size: number): string {
|
|
1558
|
-
const toCeilStr: (v: number) => string = n => String(Math.ceil(n));
|
|
1559
|
-
if (!size) return '';
|
|
1560
|
-
const num = 1024.0; // byte
|
|
1561
|
-
if (size < num) {
|
|
1562
|
-
return size + ' B';
|
|
1563
|
-
}
|
|
1564
|
-
if (size < Math.pow(num, 2)) {
|
|
1565
|
-
return toCeilStr(size / num) + ' KB';
|
|
1566
|
-
} // kb
|
|
1567
|
-
if (size < Math.pow(num, 3)) {
|
|
1568
|
-
return toCeilStr(size / Math.pow(num, 2)) + ' MB';
|
|
1569
|
-
} // M
|
|
1570
|
-
if (size < Math.pow(num, 4)) {
|
|
1571
|
-
return toCeilStr(size / Math.pow(num, 3)) + ' G';
|
|
1572
|
-
} // G
|
|
1573
|
-
return toCeilStr(size / Math.pow(num, 4)) + ' T';
|
|
1574
|
-
}
|
|
1575
|
-
|
|
1576
|
-
/**
|
|
1577
|
-
* Detect webp support.
|
|
1578
|
-
*
|
|
1579
|
-
* Reference: [Detect WEBP Support with JavaScript](https://davidwalsh.name/detect-webp)
|
|
1580
|
-
*/
|
|
1581
|
-
export function isSupportWebp(): Promise<boolean> {
|
|
1582
|
-
const fn = (resolve: (v: boolean) => void) => {
|
|
1583
|
-
const img = new Image();
|
|
1584
|
-
img.onload = () => {
|
|
1585
|
-
resolve(img.width > 0 && img.height > 0);
|
|
1586
|
-
};
|
|
1587
|
-
img.onerror = () => {
|
|
1588
|
-
resolve(false);
|
|
1589
|
-
};
|
|
1590
|
-
img.src = "data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=";
|
|
1591
|
-
};
|
|
1592
|
-
return new Promise(fn);
|
|
1593
|
-
}
|
|
1594
|
-
|
|
1595
|
-
/**
|
|
1596
|
-
* Generate a Hash Code from a string.
|
|
1597
|
-
*
|
|
1598
|
-
* Reference: [Generate a Hash from string in Javascript](https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery)
|
|
1599
|
-
*/
|
|
1600
|
-
export function genHashCode(str: string): number {
|
|
1601
|
-
let hash = 0, i, chr;
|
|
1602
|
-
for (i = 0; i < str.length; i++) {
|
|
1603
|
-
chr = str.charCodeAt(i);
|
|
1604
|
-
hash = ((hash << 5) - hash) + chr;
|
|
1605
|
-
hash |= 0;
|
|
1606
|
-
}
|
|
1607
|
-
return hash;
|
|
1608
|
-
}
|
|
1
|
+
/* mazey */
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @method calLongestCommonSubstring
|
|
5
|
+
* @description Computes the longest common substring of two strings.
|
|
6
|
+
* @param {string} aStr String
|
|
7
|
+
* @param {string} bStr String
|
|
8
|
+
* @returns {number} Length
|
|
9
|
+
*/
|
|
10
|
+
export function calLongestCommonSubstring(aStr: string, bStr: string): number {
|
|
11
|
+
const aLen = aStr.length;
|
|
12
|
+
const bLen = bStr.length;
|
|
13
|
+
// 创建二维数组并且深拷贝
|
|
14
|
+
const arr = deepCopyObject(new Array(aLen).fill(new Array(bLen).fill(0)));
|
|
15
|
+
for (let i = 0; i < aLen; ++i) {
|
|
16
|
+
for (let j = 0; j < bLen; ++j) {
|
|
17
|
+
if (aStr[i] === bStr[j]) {
|
|
18
|
+
let baseNum = 0;
|
|
19
|
+
if (i > 0 && j > 0) {
|
|
20
|
+
baseNum = arr[i - 1][j - 1];
|
|
21
|
+
}
|
|
22
|
+
arr[i][j] = baseNum + 1;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
// 二维数组转一维数组
|
|
27
|
+
const arr1 = Array.prototype.concat.apply([], arr);
|
|
28
|
+
// 获取最长公共子串
|
|
29
|
+
const maxLong = Math.max(...arr1);
|
|
30
|
+
return maxLong;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @method calLongestCommonSubsequence
|
|
35
|
+
* @description 计算两个字符串的最长公共子序列
|
|
36
|
+
* @param {string} aStr 字符串
|
|
37
|
+
* @param {string} bStr 字符串
|
|
38
|
+
* @returns {number} 长度
|
|
39
|
+
*/
|
|
40
|
+
export function calLongestCommonSubsequence(aStr: string, bStr: string): number {
|
|
41
|
+
const aLen = aStr.length;
|
|
42
|
+
const bLen = bStr.length;
|
|
43
|
+
// 创建二维数组并且深拷贝
|
|
44
|
+
const arr = deepCopyObject(new Array(aLen).fill(new Array(bLen).fill(0)));
|
|
45
|
+
for (let i = 0; i < aLen; ++i) {
|
|
46
|
+
for (let j = 0; j < bLen; ++j) {
|
|
47
|
+
if (aStr[i] === bStr[j]) {
|
|
48
|
+
let baseNum = 0;
|
|
49
|
+
if (i > 0 && j > 0) {
|
|
50
|
+
baseNum = arr[i - 1][j - 1];
|
|
51
|
+
}
|
|
52
|
+
arr[i][j] = baseNum + 1;
|
|
53
|
+
} else {
|
|
54
|
+
let [leftValue, topValue] = [0, 0];
|
|
55
|
+
if (j > 0) {
|
|
56
|
+
leftValue = arr[i][j - 1];
|
|
57
|
+
}
|
|
58
|
+
if (i > 0) {
|
|
59
|
+
topValue = arr[i - 1][j];
|
|
60
|
+
}
|
|
61
|
+
arr[i][j] = Math.max(leftValue, topValue);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// 二维数组转一维数组
|
|
66
|
+
const arr1 = Array.prototype.concat.apply([], arr);
|
|
67
|
+
// 获取最长公共子串
|
|
68
|
+
const maxLong = Math.max(...arr1);
|
|
69
|
+
return maxLong;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @method getQueryParam
|
|
74
|
+
* @description Get the query param's value of the current Web URL(`location.search`).
|
|
75
|
+
* @param {string} param Query param.
|
|
76
|
+
* @returns {string} value
|
|
77
|
+
*/
|
|
78
|
+
export function getQueryParam(param: string): string {
|
|
79
|
+
const reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)');
|
|
80
|
+
const r = location.search.substr(1).match(reg);
|
|
81
|
+
if (r !== null) {
|
|
82
|
+
// return decodeURIComponent(unescape(r[2]));
|
|
83
|
+
return decodeURIComponent(r[2]);
|
|
84
|
+
}
|
|
85
|
+
return '';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* @method getUrlParam
|
|
90
|
+
* @description Get the query param's value of the input URL.
|
|
91
|
+
* @param {string} url URL string.
|
|
92
|
+
* @param {string} param Query param.
|
|
93
|
+
* @returns {string} value
|
|
94
|
+
*/
|
|
95
|
+
export function getUrlParam(url: string, param: string): string | string[] {
|
|
96
|
+
const result: {
|
|
97
|
+
[key: string]: string | string[] | any;
|
|
98
|
+
} = {};
|
|
99
|
+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
|
|
100
|
+
url.replace(/\??(\w+)=([^&]*)&?/g, function (a, k, v): any {
|
|
101
|
+
if (result[k] !== undefined) {
|
|
102
|
+
const t = result[k];
|
|
103
|
+
result[k] = [].concat(t, v);
|
|
104
|
+
} else {
|
|
105
|
+
result[k] = v;
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
// if (param === undefined) {
|
|
109
|
+
// return result;
|
|
110
|
+
// } else {
|
|
111
|
+
// return result[param] || '';
|
|
112
|
+
// }
|
|
113
|
+
return result[param] || '';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* @method updateQueryParam
|
|
118
|
+
* @description Update the query param's value of the input URL.
|
|
119
|
+
* @param {string} url URL string.
|
|
120
|
+
* @param {string} param Query param.
|
|
121
|
+
* @param {string} value Param's value.
|
|
122
|
+
* @returns {string} URL.
|
|
123
|
+
*/
|
|
124
|
+
export function updateQueryParam(url: string, param: string, value: string): string {
|
|
125
|
+
const re = new RegExp('([?&])' + param + '=.*?(&|$)', 'i');
|
|
126
|
+
const separator = url.indexOf('?') !== -1 ? '&' : '?';
|
|
127
|
+
if (url.match(re)) {
|
|
128
|
+
return url.replace(re, '$1' + param + '=' + value + '$2');
|
|
129
|
+
} else {
|
|
130
|
+
return url + separator + param + '=' + value;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* @method getHashQueryParam
|
|
136
|
+
* @description Get the hash query param's value of the current Web URL(`location.hash`).
|
|
137
|
+
* @param {string} param Query param.
|
|
138
|
+
* @returns {string} value
|
|
139
|
+
*/
|
|
140
|
+
export function getHashQueryParam(param: string): string {
|
|
141
|
+
const hashs = location.hash.split('?');
|
|
142
|
+
if (hashs.length === 1) {
|
|
143
|
+
return '';
|
|
144
|
+
}
|
|
145
|
+
const reg = new RegExp(`(^|&)${param}=([^&]*)(&|$)`);
|
|
146
|
+
const ret = hashs[1].match(reg);
|
|
147
|
+
return ret ? ret[2] : '';
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* @method getDomain
|
|
152
|
+
* @description Get the domain of URL, and other params.
|
|
153
|
+
* @param {string} url
|
|
154
|
+
* @param {array} rules Object.keys(location), ['href', 'protocol', 'host', 'hostname', 'port', 'pathname', 'search', 'hash'], ['hostname', 'pathname'] = 'km.mazey.net/plugins/servlet/mobile'
|
|
155
|
+
*/
|
|
156
|
+
export function getDomain(url: string, rules = ['hostname']): string {
|
|
157
|
+
const aEl: any = document.createElement('a');
|
|
158
|
+
aEl.href = url;
|
|
159
|
+
return rules.reduce((ret, v) => {
|
|
160
|
+
ret += aEl[v];
|
|
161
|
+
return ret;
|
|
162
|
+
}, '');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* @method camelCaseToKebabCase
|
|
167
|
+
* @description Transfer CamelCase to KebabCase.
|
|
168
|
+
* @param {string} camelCase 'aBC' or 'ABC'
|
|
169
|
+
* @returns {string} 'a-b-c'
|
|
170
|
+
*/
|
|
171
|
+
export function camelCaseToKebabCase(camelCase: string): string {
|
|
172
|
+
const kebabCase = camelCase.replace(/([A-Z])/g, '-$1').toLowerCase();
|
|
173
|
+
return kebabCase[0] === '-' ? kebabCase.substr(1) : kebabCase;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* @method camelCase2Underscore
|
|
178
|
+
* @description Transfer CamelCase to Underscore.
|
|
179
|
+
* @param {string} camelCase 'aBC' or 'ABC'
|
|
180
|
+
* @returns {string} 'a_b_c'
|
|
181
|
+
*/
|
|
182
|
+
export function camelCase2Underscore(camelCase: string): string {
|
|
183
|
+
const kebabCase = camelCase.replace(/([A-Z])/g, '_$1').toLowerCase();
|
|
184
|
+
return kebabCase[0] === '_' ? kebabCase.substr(1) : kebabCase;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* @method mTrim
|
|
189
|
+
* @description Remove leading and trailing whitespace or specified characters from string.
|
|
190
|
+
* @param {string} str The string to trim.
|
|
191
|
+
* @returns {string} Trimmed string.
|
|
192
|
+
*/
|
|
193
|
+
export function mTrim(str: string): string {
|
|
194
|
+
str = str.replace(/^\s+/, ''); // 去除头部空格
|
|
195
|
+
let end = str.length - 1;
|
|
196
|
+
const ws = /\s/;
|
|
197
|
+
while (ws.test(str.charAt(end))) {
|
|
198
|
+
end--; // 最后一个非空格字符的索引
|
|
199
|
+
}
|
|
200
|
+
return str.slice(0, end + 1);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* @method newLine
|
|
205
|
+
* @description Make a newline of HTML.
|
|
206
|
+
* @param {string} str The string to make a newline.
|
|
207
|
+
* @returns {string} A newline with `br`.
|
|
208
|
+
*/
|
|
209
|
+
export function newLine(str: string): string {
|
|
210
|
+
if (!str) {
|
|
211
|
+
return '';
|
|
212
|
+
}
|
|
213
|
+
const reg = new RegExp('\\n', 'g');
|
|
214
|
+
return str.replace(reg, '<br />');
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* @method deepCopyObject
|
|
219
|
+
* @description Clone Object deeply.
|
|
220
|
+
* @param {object} obj The value to clone.
|
|
221
|
+
* @returns {object} Returns the deep cloned value.
|
|
222
|
+
*/
|
|
223
|
+
export function deepCopyObject(obj: any): any {
|
|
224
|
+
return JSON.parse(JSON.stringify(obj));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* @method isJsonString
|
|
229
|
+
* @description Check whether it is a valid JSON string.
|
|
230
|
+
* @param {string} str The string to check.
|
|
231
|
+
* @returns {boolean} Return the result of checking.
|
|
232
|
+
*/
|
|
233
|
+
export function isJsonString(str: string): boolean {
|
|
234
|
+
try {
|
|
235
|
+
if (typeof JSON.parse(str) === 'object') {
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
} catch (e) {
|
|
239
|
+
/* pass */
|
|
240
|
+
}
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* @method generateRndNum
|
|
246
|
+
* @description Produce a random string of number, `generateRndNum(7)` => '7658495'.
|
|
247
|
+
* @param {number} n Length
|
|
248
|
+
* @returns {string} Return the random string.
|
|
249
|
+
*/
|
|
250
|
+
export function generateRndNum(n = 5): string {
|
|
251
|
+
let ret = '';
|
|
252
|
+
while (n--) {
|
|
253
|
+
ret += Math.floor(Math.random() * 10);
|
|
254
|
+
}
|
|
255
|
+
return ret;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* @method generateUniqueNum
|
|
260
|
+
* @description 根据时间生成唯一标志的数字 mGenerateUniqueNum() => 1538324722364123。
|
|
261
|
+
* @param {number} n 随机数的长度
|
|
262
|
+
*/
|
|
263
|
+
export function generateUniqueNum(n = 3): string {
|
|
264
|
+
const [now, rnd] = [mNow(), generateRndNum(n || 3)];
|
|
265
|
+
return now + rnd;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* @method floatToPercent
|
|
270
|
+
* @description 浮点数转为百分比 0.2 => 20%。
|
|
271
|
+
* @param {number} num 浮点数
|
|
272
|
+
* @param {number} fixSize 保留几位浮点数
|
|
273
|
+
*/
|
|
274
|
+
export function floatToPercent(num: number, fixSize = 0): string {
|
|
275
|
+
let ret = '';
|
|
276
|
+
if (fixSize) {
|
|
277
|
+
ret = (num * 100).toFixed(fixSize);
|
|
278
|
+
} else {
|
|
279
|
+
ret = String(Math.floor(num * 100));
|
|
280
|
+
}
|
|
281
|
+
return `${ret}%`;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* @method floatFixed
|
|
286
|
+
* @description 浮点数保留指定位。
|
|
287
|
+
*/
|
|
288
|
+
export function floatFixed(num: string, size = 0): string {
|
|
289
|
+
return parseFloat(num).toFixed(size);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* @method cancelBubble
|
|
294
|
+
* @description 阻止冒泡。
|
|
295
|
+
*/
|
|
296
|
+
export function cancelBubble(e: any): void {
|
|
297
|
+
const ev = e || window.event;
|
|
298
|
+
if (ev.stopPropagation) {
|
|
299
|
+
// W3C
|
|
300
|
+
ev.stopPropagation();
|
|
301
|
+
} else {
|
|
302
|
+
// IE
|
|
303
|
+
ev.cancelBubble = true;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* @method hasClass
|
|
309
|
+
*/
|
|
310
|
+
export function hasClass(obj: any, cls: string): boolean {
|
|
311
|
+
const oriCls = obj.className; // 获取对象的class值
|
|
312
|
+
const oriClsArr = oriCls.split(/\s+/); // 分隔空格转换成数组
|
|
313
|
+
for (let i = 0; i < oriClsArr.length; i++) {
|
|
314
|
+
if (oriClsArr[i] === cls) {
|
|
315
|
+
return true; // 若匹配到class则返回True
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return false; // 否则返回False
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* @method addClass
|
|
323
|
+
*/
|
|
324
|
+
export function addClass(obj: any, cls: string): void {
|
|
325
|
+
const oriCls = obj.className;
|
|
326
|
+
let space = '';
|
|
327
|
+
let newCls = ''; // 获取对象的class值
|
|
328
|
+
if (oriCls !== '') {
|
|
329
|
+
space = ' '; // 若原来的class不为空,跟一个空格
|
|
330
|
+
}
|
|
331
|
+
newCls = oriCls + space + cls; // 将新的class加进去
|
|
332
|
+
obj.className = newCls; // 替换新class
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* @method removeClass
|
|
337
|
+
*/
|
|
338
|
+
export function removeClass(obj: any, cls: string): void {
|
|
339
|
+
const oriCls = obj.className;
|
|
340
|
+
let newCls; // 获取对象的class值
|
|
341
|
+
newCls = ' ' + oriCls + ' '; // 前后加空格
|
|
342
|
+
newCls = newCls.replace(/(\s+)/gi, ' '); // 将多余的空格替换成一个空格
|
|
343
|
+
newCls = newCls.replace(' ' + cls + ' ', ' '); // 将加了前后空格的cls替换成空格' '
|
|
344
|
+
newCls = newCls.replace(/(^\s+)|(\s+$)/g, ''); // 去掉前后空格
|
|
345
|
+
obj.className = newCls;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* EN: Throttle
|
|
350
|
+
*
|
|
351
|
+
* ZH: 节流
|
|
352
|
+
*
|
|
353
|
+
* Reference: [Lodash](https://lodash.com/docs/4.17.15#throttle)
|
|
354
|
+
*/
|
|
355
|
+
export function throttle(func: any, wait: number, options: { leading?: boolean; trailing?: boolean; } = {}): any {
|
|
356
|
+
options = Object.assign(
|
|
357
|
+
{},
|
|
358
|
+
options,
|
|
359
|
+
);
|
|
360
|
+
// timeout: setTimeout Handle
|
|
361
|
+
// previous: 上次时间戳
|
|
362
|
+
let context: any = null;
|
|
363
|
+
let args: any = null;
|
|
364
|
+
let timeout: any = null;
|
|
365
|
+
let [result, previous] = [null, 0];
|
|
366
|
+
// if (!options) {
|
|
367
|
+
// options = {};
|
|
368
|
+
// }
|
|
369
|
+
const later = function () {
|
|
370
|
+
previous = options.leading === false ? 0 : mNow();
|
|
371
|
+
timeout = null;
|
|
372
|
+
result = func.apply(context, args);
|
|
373
|
+
if (!timeout) {
|
|
374
|
+
context = args = null;
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
return function (...argRest: Array<any>) {
|
|
378
|
+
const now = mNow();
|
|
379
|
+
if (!previous && options.leading === false) {
|
|
380
|
+
previous = now;
|
|
381
|
+
}
|
|
382
|
+
const remaining = wait - (now - previous);
|
|
383
|
+
context = this;
|
|
384
|
+
args = argRest;
|
|
385
|
+
if (remaining <= 0 || remaining > wait) {
|
|
386
|
+
if (timeout) {
|
|
387
|
+
clearTimeout(timeout);
|
|
388
|
+
timeout = null;
|
|
389
|
+
}
|
|
390
|
+
previous = now;
|
|
391
|
+
result = func.apply(context, args);
|
|
392
|
+
if (!timeout) {
|
|
393
|
+
context = args = null;
|
|
394
|
+
}
|
|
395
|
+
} else if (!timeout && options.trailing !== false) {
|
|
396
|
+
timeout = setTimeout(later, remaining);
|
|
397
|
+
}
|
|
398
|
+
return result;
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* EN: Debounce
|
|
404
|
+
*
|
|
405
|
+
* ZH: 去抖
|
|
406
|
+
*
|
|
407
|
+
* Usage:
|
|
408
|
+
*
|
|
409
|
+
* ```
|
|
410
|
+
* const foo = debounce(() => {
|
|
411
|
+
* console.log('The debounced function will only be invoked in 1000 milliseconds, the other invoking will disappear during the wait time.');
|
|
412
|
+
* }, 1000, true);
|
|
413
|
+
* ```
|
|
414
|
+
*/
|
|
415
|
+
export function debounce(func: any, wait: number, immediate?: any): any {
|
|
416
|
+
let context: any = null;
|
|
417
|
+
let timeout: any = null;
|
|
418
|
+
let timestamp: any = null;
|
|
419
|
+
let args: any = null;
|
|
420
|
+
let [result] = [null];
|
|
421
|
+
const later = function () {
|
|
422
|
+
const last = mNow() - timestamp;
|
|
423
|
+
if (last < wait && last >= 0) {
|
|
424
|
+
timeout = setTimeout(later, wait - last);
|
|
425
|
+
} else {
|
|
426
|
+
timeout = null;
|
|
427
|
+
if (!immediate) {
|
|
428
|
+
result = func.apply(context, args);
|
|
429
|
+
if (!timeout) {
|
|
430
|
+
context = args = null;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
return function (...argRest: Array<any>) {
|
|
436
|
+
context = this;
|
|
437
|
+
args = argRest;
|
|
438
|
+
timestamp = mNow();
|
|
439
|
+
const callNow = immediate && !timeout;
|
|
440
|
+
if (!timeout) {
|
|
441
|
+
timeout = setTimeout(later, wait);
|
|
442
|
+
}
|
|
443
|
+
if (callNow) {
|
|
444
|
+
result = func.apply(context, args);
|
|
445
|
+
context = args = null;
|
|
446
|
+
}
|
|
447
|
+
return result;
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* @method friendlyInterval
|
|
453
|
+
* @description 获取间隔时间。
|
|
454
|
+
* @param {number/Date} start 开始时间戳 1585325367122
|
|
455
|
+
* @param {number/Date} end 结束时间戳 1585325367122
|
|
456
|
+
* @param {string} options.type 返回类型 d: 2(天) text: 2 天 4 时...
|
|
457
|
+
* @returns {String/number} 取决于 type
|
|
458
|
+
*/
|
|
459
|
+
export function friendlyInterval(start = 0, end = 0, options: { type?: string; } = { type: 'd' }): number | string {
|
|
460
|
+
const { type } = options;
|
|
461
|
+
if (!isNumber(start)) start = new Date(start).getTime();
|
|
462
|
+
if (!isNumber(end)) end = new Date(end).getTime();
|
|
463
|
+
const t = end - start;
|
|
464
|
+
let ret = '';
|
|
465
|
+
let [d, h, m, s] = new Array(4).fill(0);
|
|
466
|
+
if (t >= 0) {
|
|
467
|
+
d = Math.floor(t / 1000 / 60 / 60 / 24);
|
|
468
|
+
h = Math.floor(t / 1000 / 60 / 60);
|
|
469
|
+
m = Math.floor(t / 1000 / 60);
|
|
470
|
+
s = Math.floor(t / 1000);
|
|
471
|
+
switch (type) {
|
|
472
|
+
case 'd':
|
|
473
|
+
ret = d;
|
|
474
|
+
break;
|
|
475
|
+
case 'text':
|
|
476
|
+
d = Math.floor(t / 1000 / 60 / 60 / 24);
|
|
477
|
+
h = Math.floor((t / 1000 / 60 / 60) % 24);
|
|
478
|
+
m = Math.floor((t / 1000 / 60) % 60);
|
|
479
|
+
s = Math.floor((t / 1000) % 60);
|
|
480
|
+
ret = d + ' 天 ' + h + ' 时 ' + m + ' 分 ' + s + ' 秒';
|
|
481
|
+
break;
|
|
482
|
+
default:
|
|
483
|
+
ret = s;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return ret;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* @method isNumber
|
|
491
|
+
* @description 判断是否有效数字
|
|
492
|
+
* @param {*} num 被判断的值
|
|
493
|
+
* @param {boolean} options.isNaNAsNumber 是否 NaN 算数字(默认不算)
|
|
494
|
+
* @param {boolean} options.isUnFiniteAsNumber 是否 无限 算数字(默认不算)
|
|
495
|
+
* @returns {boolean} true 是数字
|
|
496
|
+
*/
|
|
497
|
+
export function isNumber(num: any, options: { isNaNAsNumber?: boolean; isUnFiniteAsNumber?: boolean; } = { isNaNAsNumber: false, isUnFiniteAsNumber: false }): boolean {
|
|
498
|
+
const { isNaNAsNumber, isUnFiniteAsNumber } = Object.assign(
|
|
499
|
+
{ isNaNAsNumber: false, isUnFiniteAsNumber: false },
|
|
500
|
+
options,
|
|
501
|
+
);
|
|
502
|
+
let ret = true;
|
|
503
|
+
// 数字类型
|
|
504
|
+
if (typeof num !== 'number') {
|
|
505
|
+
ret = false;
|
|
506
|
+
}
|
|
507
|
+
// 无限值
|
|
508
|
+
if (isUnFiniteAsNumber === false && !isFinite(num)) {
|
|
509
|
+
// console.log('1333');
|
|
510
|
+
ret = false;
|
|
511
|
+
}
|
|
512
|
+
// NaN
|
|
513
|
+
if (isNaNAsNumber === false && isNaN(num)) {
|
|
514
|
+
// console.log('2333');
|
|
515
|
+
ret = false;
|
|
516
|
+
}
|
|
517
|
+
return ret;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* @method doFn
|
|
522
|
+
* @description 执行有效函数
|
|
523
|
+
* @param {function} fn 等待被执行的未知是否有效的函数
|
|
524
|
+
*/
|
|
525
|
+
export function doFn(fn: any, ...params: any[]): any {
|
|
526
|
+
let ret = null;
|
|
527
|
+
if (fn && typeof fn === 'function') {
|
|
528
|
+
ret = fn(...params);
|
|
529
|
+
}
|
|
530
|
+
return ret;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* @method setSessionStorage
|
|
535
|
+
* @description 存储数据到 sessionStorage
|
|
536
|
+
* @param {string} key 键
|
|
537
|
+
* @param {string} value 值
|
|
538
|
+
*/
|
|
539
|
+
export function setSessionStorage(key: string, value: any = null): void {
|
|
540
|
+
if (key) {
|
|
541
|
+
sessionStorage.setItem(key, JSON.stringify(value));
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* @method getSessionStorage
|
|
547
|
+
* @description 存储数据到 sessionStorage
|
|
548
|
+
* @param {string} key 键
|
|
549
|
+
* @returns {*} 返回值
|
|
550
|
+
*/
|
|
551
|
+
export function getSessionStorage(key: string): any {
|
|
552
|
+
let ret = null;
|
|
553
|
+
if (key) {
|
|
554
|
+
const value = sessionStorage.getItem(key);
|
|
555
|
+
if (value) {
|
|
556
|
+
ret = JSON.parse(value);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return ret;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* @method setLocalStorage
|
|
564
|
+
* @description 存储数据到 localStorage
|
|
565
|
+
* @param {string} key 键
|
|
566
|
+
* @param {string} value 值
|
|
567
|
+
*/
|
|
568
|
+
export function setLocalStorage(key: string, value: any = null): void {
|
|
569
|
+
if (key) {
|
|
570
|
+
localStorage.setItem(key, JSON.stringify(value));
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* @method getLocalStorage
|
|
576
|
+
* @description 存储数据到 localStorage
|
|
577
|
+
* @param {string} key 键
|
|
578
|
+
* @returns {*} 返回值
|
|
579
|
+
*/
|
|
580
|
+
export function getLocalStorage(key: string): any {
|
|
581
|
+
let ret = null;
|
|
582
|
+
if (key) {
|
|
583
|
+
const value = localStorage.getItem(key);
|
|
584
|
+
if (value) {
|
|
585
|
+
ret = JSON.parse(value);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
return ret;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* @method loadCSS
|
|
593
|
+
* @description 动态加载css文件
|
|
594
|
+
* @param {string} url -- css资源路径
|
|
595
|
+
* @param {string} options.id -- link标签id
|
|
596
|
+
* @returns {Promise<boolean>} true -- 加载成功
|
|
597
|
+
*/
|
|
598
|
+
export function loadCSS(url: string, options: { id?: string } = { id: '' }): Promise<boolean | Error | any> {
|
|
599
|
+
const { id } = options;
|
|
600
|
+
let success: (v: boolean) => void;
|
|
601
|
+
let fail: (v: Error) => void;
|
|
602
|
+
const status = new Promise((resolve, reject) => {
|
|
603
|
+
([success, fail] = [resolve, reject]);
|
|
604
|
+
});
|
|
605
|
+
// const tempCB = (typeof callback === 'function' ? callback : function () { });
|
|
606
|
+
const callback = function () {
|
|
607
|
+
// doFn(success, true);
|
|
608
|
+
success(true);
|
|
609
|
+
};
|
|
610
|
+
let node: any = document.createElement('link');
|
|
611
|
+
const supportOnload = 'onload' in node;
|
|
612
|
+
const isOldWebKit = +navigator.userAgent.replace(/.*(?:AppleWebKit|AndroidWebKit)\/?(\d+).*/i, '$1') < 536; // webkit旧内核做特殊处理
|
|
613
|
+
const protectNum = 300000; // 阈值10分钟,一秒钟执行pollCss 500次
|
|
614
|
+
|
|
615
|
+
node.rel = 'stylesheet';
|
|
616
|
+
node.type = 'text/css';
|
|
617
|
+
node.href = url;
|
|
618
|
+
if (typeof id !== 'undefined') {
|
|
619
|
+
node.id = id;
|
|
620
|
+
}
|
|
621
|
+
document.getElementsByTagName('head')[0].appendChild(node);
|
|
622
|
+
|
|
623
|
+
// for Old WebKit and Old Firefox
|
|
624
|
+
if (isOldWebKit || !supportOnload) {
|
|
625
|
+
// Begin after node insertion
|
|
626
|
+
setTimeout(function () {
|
|
627
|
+
pollCss(node, callback, 0);
|
|
628
|
+
}, 1);
|
|
629
|
+
return status;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
if (supportOnload) {
|
|
633
|
+
node.onload = onload;
|
|
634
|
+
node.onerror = function () {
|
|
635
|
+
// 加载失败(404)
|
|
636
|
+
onload();
|
|
637
|
+
};
|
|
638
|
+
} else {
|
|
639
|
+
// todo: 和 !supportOnload 重复
|
|
640
|
+
node.onreadystatechange = function () {
|
|
641
|
+
if (/loaded|complete/.test(node.readyState)) {
|
|
642
|
+
onload();
|
|
643
|
+
}
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function onload() {
|
|
648
|
+
// 确保只跑一次下载操作
|
|
649
|
+
node.onload = node.onerror = node.onreadystatechange = null;
|
|
650
|
+
|
|
651
|
+
// 清空node引用,在低版本IE,不清除会造成内存泄露
|
|
652
|
+
node = null;
|
|
653
|
+
|
|
654
|
+
callback();
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// 循环判断css是否已加载成功
|
|
658
|
+
/*
|
|
659
|
+
* @param node -- link节点
|
|
660
|
+
* @param callback -- 回调函数
|
|
661
|
+
* @param step -- 计步器,避免无限循环
|
|
662
|
+
*/
|
|
663
|
+
function pollCss(node: any, callback: any, step: number) {
|
|
664
|
+
const sheet = node.sheet;
|
|
665
|
+
let isLoaded: any;
|
|
666
|
+
|
|
667
|
+
step += 1;
|
|
668
|
+
|
|
669
|
+
// 保护,大于10分钟,则不再轮询
|
|
670
|
+
if (step > protectNum) {
|
|
671
|
+
isLoaded = true;
|
|
672
|
+
|
|
673
|
+
// 清空node引用
|
|
674
|
+
node = null;
|
|
675
|
+
|
|
676
|
+
callback();
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
if (isOldWebKit) {
|
|
681
|
+
// for WebKit < 536
|
|
682
|
+
if (sheet) {
|
|
683
|
+
isLoaded = true;
|
|
684
|
+
}
|
|
685
|
+
} else if (sheet) {
|
|
686
|
+
// for Firefox < 9.0
|
|
687
|
+
try {
|
|
688
|
+
if (sheet.cssRules) {
|
|
689
|
+
isLoaded = true;
|
|
690
|
+
}
|
|
691
|
+
} catch (ex) {
|
|
692
|
+
// 火狐特殊版本,通过特定值获知是否下载成功
|
|
693
|
+
// The value of `ex.name` is changed from "NS_ERROR_DOM_SECURITY_ERR"
|
|
694
|
+
// to "SecurityError" since Firefox 13.0. But Firefox is less than 9.0
|
|
695
|
+
// in here, So it is ok to just rely on "NS_ERROR_DOM_SECURITY_ERR"
|
|
696
|
+
if ((ex as any).name === 'NS_ERROR_DOM_SECURITY_ERR') {
|
|
697
|
+
isLoaded = true;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
setTimeout(function () {
|
|
703
|
+
if (isLoaded) {
|
|
704
|
+
// 延迟20ms是为了给下载的样式留够渲染的时间
|
|
705
|
+
callback();
|
|
706
|
+
} else {
|
|
707
|
+
pollCss(node, callback, step);
|
|
708
|
+
}
|
|
709
|
+
}, 20);
|
|
710
|
+
}
|
|
711
|
+
return status;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* @method loadScript
|
|
716
|
+
* @description 动态加载js文件
|
|
717
|
+
* @param {string} url -- js资源路径
|
|
718
|
+
* @param {string} options.id -- DOM ID
|
|
719
|
+
* @param {function} options.callback -- 加载后回调函数
|
|
720
|
+
* @param {number} options.timeout -- 超时时长
|
|
721
|
+
* @param {boolean} options.isDefer -- 是否添加 defer 标签
|
|
722
|
+
* @returns {Promise<boolean>} -- true 成功
|
|
723
|
+
*/
|
|
724
|
+
export function loadScript(url: string, options: {
|
|
725
|
+
id: string;
|
|
726
|
+
callback: (...params: any[]) => any;
|
|
727
|
+
timeout: number;
|
|
728
|
+
isDefer: boolean;
|
|
729
|
+
} = { id: '', callback: function () { /* pass */ }, timeout: 5000, isDefer: false }): Promise<boolean | string | Error> {
|
|
730
|
+
const { id, callback, timeout, isDefer } = Object.assign(
|
|
731
|
+
{ id: '', callback: function () { /* pass */ }, timeout: 5000, isDefer: false },
|
|
732
|
+
options,
|
|
733
|
+
);
|
|
734
|
+
let success: any = null;
|
|
735
|
+
let fail: any = null;
|
|
736
|
+
const script: any = document.createElement('script');
|
|
737
|
+
// 如果没有 script 标签,那么代码就不会运行。可以利用这一事实,在页面的第一个 script 标签上使用 insertBefore()。
|
|
738
|
+
const firstScript: any = document.getElementsByTagName('script')[0];
|
|
739
|
+
script.type = 'text/javascript';
|
|
740
|
+
if (isDefer) {
|
|
741
|
+
script.defer = 'defer';
|
|
742
|
+
}
|
|
743
|
+
if (id) {
|
|
744
|
+
script.id = id;
|
|
745
|
+
}
|
|
746
|
+
if (script.readyState) {
|
|
747
|
+
// IE
|
|
748
|
+
script.onreadystatechange = function () {
|
|
749
|
+
if (script.readyState === 'loaded' || script.readyState === 'complete') {
|
|
750
|
+
script.onreadystatechange = null;
|
|
751
|
+
doFn(callback);
|
|
752
|
+
doFn(success, true);
|
|
753
|
+
}
|
|
754
|
+
};
|
|
755
|
+
} else {
|
|
756
|
+
// Others
|
|
757
|
+
script.onload = function () {
|
|
758
|
+
doFn(callback);
|
|
759
|
+
doFn(success, true);
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
script.src = url;
|
|
763
|
+
firstScript && firstScript.parentNode.insertBefore(script, firstScript);
|
|
764
|
+
return new Promise((resolve, reject) => {
|
|
765
|
+
([success, fail] = [resolve, reject]);
|
|
766
|
+
if (timeout) {
|
|
767
|
+
setTimeout(fail.bind(null, Error('timeout')), timeout);
|
|
768
|
+
}
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* @method mNow
|
|
774
|
+
* @description 获取时间戳
|
|
775
|
+
*/
|
|
776
|
+
export function mNow(): number {
|
|
777
|
+
let ret = 0;
|
|
778
|
+
if (Date.now) {
|
|
779
|
+
ret = Date.now();
|
|
780
|
+
} else {
|
|
781
|
+
ret = new Date().getTime();
|
|
782
|
+
}
|
|
783
|
+
return ret;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* @method setCookie
|
|
788
|
+
* @description 设置 Cookie
|
|
789
|
+
*/
|
|
790
|
+
export function setCookie(name: string, value: string, days: number, domain: string): void {
|
|
791
|
+
let domainParts, expires;
|
|
792
|
+
let date: any;
|
|
793
|
+
if (days) {
|
|
794
|
+
date = new Date();
|
|
795
|
+
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
|
|
796
|
+
expires = "; expires=" + date.toGMTString();
|
|
797
|
+
} else {
|
|
798
|
+
expires = "";
|
|
799
|
+
}
|
|
800
|
+
const host = location.host;
|
|
801
|
+
if (host.split('.').length === 1) {
|
|
802
|
+
// no "." in a domain - it's localhost or something similar
|
|
803
|
+
document.cookie = name + "=" + value + expires + "; path=/";
|
|
804
|
+
} else {
|
|
805
|
+
// Remember the cookie on all subdomains.
|
|
806
|
+
//
|
|
807
|
+
// Start with trying to set cookie to the top domain.
|
|
808
|
+
// (example: if user is on foo.com, try to set
|
|
809
|
+
// cookie to domain ".com")
|
|
810
|
+
//
|
|
811
|
+
// If the cookie will not be set, it means ".com"
|
|
812
|
+
// is a top level domain and we need to
|
|
813
|
+
// set the cookie to ".foo.com"
|
|
814
|
+
domainParts = host.split('.');
|
|
815
|
+
domainParts.shift();
|
|
816
|
+
domain = domain || ('.' + domainParts.join('.'));
|
|
817
|
+
document.cookie = name + "=" + value + expires + "; path=/; domain=" + domain;
|
|
818
|
+
// check if cookie was successfuly set to the given domain
|
|
819
|
+
// (otherwise it was a Top-Level Domain)
|
|
820
|
+
if (getCookie(name) === null || getCookie(name) !== value) {
|
|
821
|
+
// append "." to current domain
|
|
822
|
+
domain = domain || ('.' + host);
|
|
823
|
+
document.cookie = name + "=" + value + expires + "; path=/; domain=" + domain;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/**
|
|
829
|
+
* @method getCookie
|
|
830
|
+
* @description 获取 Cookie
|
|
831
|
+
*/
|
|
832
|
+
export function getCookie(name: string): string {
|
|
833
|
+
const nameEQ = name + "=";
|
|
834
|
+
const ca = document.cookie.split(';');
|
|
835
|
+
for (let i = 0; i < ca.length; i++) {
|
|
836
|
+
let c = ca[i];
|
|
837
|
+
while (c.charAt(0) == ' ') {
|
|
838
|
+
c = c.substring(1, c.length);
|
|
839
|
+
}
|
|
840
|
+
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
|
|
841
|
+
}
|
|
842
|
+
return '';
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
interface WebPerformance {
|
|
846
|
+
[key: string]: string | number;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* @method getPerformance
|
|
851
|
+
* @description 获取页面加载相关的各项数据
|
|
852
|
+
* @param {boolean} camelCase -- true(默认) 以驼峰形式返回数据 false 以下划线形式返回数据
|
|
853
|
+
* @returns {Promise<object>} 加载数据
|
|
854
|
+
*/
|
|
855
|
+
export function getPerformance(camelCase = true): Promise<WebPerformance | Error> {
|
|
856
|
+
let success: (v: WebPerformance) => void;
|
|
857
|
+
let fail: (v: Error) => void;
|
|
858
|
+
const status: Promise<WebPerformance> = new Promise((resolve, reject) => {
|
|
859
|
+
([success, fail] = [resolve, reject]);
|
|
860
|
+
});
|
|
861
|
+
const timing = window.performance.timing;
|
|
862
|
+
const startTime = timing.navigationStart || timing.fetchStart;
|
|
863
|
+
let firstPaintTime: any;
|
|
864
|
+
let firstContentfulPaintTime: any;
|
|
865
|
+
// 是否已经形成数据(页面加载完成之后)
|
|
866
|
+
if (window.performance && window.performance.timing && window.performance.timing.loadEventEnd > 0) {
|
|
867
|
+
// console.log('created')
|
|
868
|
+
getTiming();
|
|
869
|
+
} else {
|
|
870
|
+
// console.log('creating')
|
|
871
|
+
window.addEventListener("load", function() {
|
|
872
|
+
//不能影响最后的时间计算
|
|
873
|
+
window.setTimeout(function() {
|
|
874
|
+
getTiming();
|
|
875
|
+
}, 0);
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
// performance
|
|
879
|
+
function getTiming() {
|
|
880
|
+
// 获取首次渲染时间
|
|
881
|
+
try {
|
|
882
|
+
if (window.performance && Boolean(window.performance.getEntriesByType)) {
|
|
883
|
+
const performance = window.performance;
|
|
884
|
+
const performanceEntries = performance.getEntriesByType('paint');
|
|
885
|
+
performanceEntries.forEach((performanceEntry, i, entries) => {
|
|
886
|
+
const startTime = Math.round(performanceEntry.startTime);
|
|
887
|
+
if (performanceEntry.name === 'first-paint')
|
|
888
|
+
firstPaintTime = startTime;
|
|
889
|
+
else if (performanceEntry.name === 'first-contentful-paint')
|
|
890
|
+
firstContentfulPaintTime = startTime;
|
|
891
|
+
});
|
|
892
|
+
} else {
|
|
893
|
+
console.error('paint');
|
|
894
|
+
}
|
|
895
|
+
} catch (e) {
|
|
896
|
+
console.error((e as any).message);
|
|
897
|
+
}
|
|
898
|
+
// 获取加载时间
|
|
899
|
+
if (
|
|
900
|
+
window.performance &&
|
|
901
|
+
typeof window.performance.getEntries === 'function'
|
|
902
|
+
) {
|
|
903
|
+
const performanceNavigationTiming: any =
|
|
904
|
+
(window.performance.getEntries() || [])[0] || {};
|
|
905
|
+
const data: any = {
|
|
906
|
+
// url: encodeURI(location.href),
|
|
907
|
+
// ua: navigator.userAgent,
|
|
908
|
+
os: getOS(),
|
|
909
|
+
osVersion: getOSVersion(),
|
|
910
|
+
deviceType: getDeviceType(),
|
|
911
|
+
network: getNetWork(),
|
|
912
|
+
screenDirection: getOrientationStatu(),
|
|
913
|
+
unloadTime: timing.unloadEventEnd - timing.unloadEventStart, //上个文档的卸载时间
|
|
914
|
+
redirectTime: timing.redirectEnd - timing.redirectStart, //*重定向时间
|
|
915
|
+
dnsTime: timing.domainLookupEnd - timing.domainLookupStart, //*DNS查询时间
|
|
916
|
+
tcpTime: timing.connectEnd - timing.connectStart, //*服务器连接时间
|
|
917
|
+
sslTime: getSSLTime(timing.connectEnd, timing.secureConnectionStart), //*ssl连接时间
|
|
918
|
+
responseTime: timing.responseStart - timing.requestStart, //*服务器响应时间
|
|
919
|
+
downloadTime: timing.responseEnd - timing.responseStart, //*网页下载时间
|
|
920
|
+
firstPaintTime: firstPaintTime, //*首次渲染时间
|
|
921
|
+
firstContentfulPaintTime: firstContentfulPaintTime, //*首次渲染内容时间
|
|
922
|
+
domreadyTime: timing.domContentLoadedEventStart - startTime || 0, //*dom ready时间(总和)
|
|
923
|
+
onloadTime: timing.loadEventStart - startTime || 0, //*onload时间(总和)
|
|
924
|
+
whiteTime: timing.responseStart - startTime, //*白屏时间
|
|
925
|
+
renderTime: timing.loadEventEnd - startTime || 0, //整个过程的时间之和
|
|
926
|
+
decodedBodySize: performanceNavigationTiming.decodedBodySize || '', //页面压缩前大小
|
|
927
|
+
encodedBodySize: performanceNavigationTiming.encodedBodySize || '', //页面压缩后大小
|
|
928
|
+
};
|
|
929
|
+
// 过滤异常数据
|
|
930
|
+
Object.keys(data).forEach(k => {
|
|
931
|
+
// 过滤掉 <0 的数据
|
|
932
|
+
if (isNumber(data[k]) && data[k] < 0) {
|
|
933
|
+
data[k] = 0;
|
|
934
|
+
}
|
|
935
|
+
});
|
|
936
|
+
// 过滤掉白屏时间 > onload 的数据
|
|
937
|
+
if (isNumber(data.whiteTime) && data.whiteTime > data.onloadTime) {
|
|
938
|
+
data.whiteTime = 0;
|
|
939
|
+
}
|
|
940
|
+
if (startTime > 0) {
|
|
941
|
+
let Underscore: any;
|
|
942
|
+
if (!camelCase) {
|
|
943
|
+
Object.keys(data).forEach(k => {
|
|
944
|
+
if (!Underscore) Underscore = {};
|
|
945
|
+
// console.log('camelCase2Underscore', k, data, )
|
|
946
|
+
Underscore[camelCase2Underscore(k)] = data[k];
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
success(Underscore || data);
|
|
950
|
+
} else {
|
|
951
|
+
fail(Error('startTime'));
|
|
952
|
+
}
|
|
953
|
+
} else {
|
|
954
|
+
fail(Error('getEntries'));
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
//获取当前操作系统
|
|
958
|
+
function getOS() {
|
|
959
|
+
let os;
|
|
960
|
+
if (navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1) {
|
|
961
|
+
os = 'android';
|
|
962
|
+
} else if (navigator.userAgent.indexOf('iPhone') > -1) {
|
|
963
|
+
os = 'ios';
|
|
964
|
+
} else if (navigator.userAgent.indexOf('Windows Phone') > -1) {
|
|
965
|
+
os = 'wp';
|
|
966
|
+
} else {
|
|
967
|
+
os = 'others';
|
|
968
|
+
}
|
|
969
|
+
return os;
|
|
970
|
+
}
|
|
971
|
+
// 获取操作系统版本
|
|
972
|
+
function getOSVersion() {
|
|
973
|
+
let OSVision: any;
|
|
974
|
+
const u = navigator.userAgent;
|
|
975
|
+
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //Android
|
|
976
|
+
const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
|
|
977
|
+
if (isAndroid) {
|
|
978
|
+
OSVision = (navigator.userAgent.split(';')[1].match(/\d+\.\d+/g) || [])[0];
|
|
979
|
+
}
|
|
980
|
+
if (isIOS) {
|
|
981
|
+
OSVision = (navigator.userAgent.split(';')[1].match(/(\d+)_(\d+)_?(\d+)?/) || [])[0];
|
|
982
|
+
}
|
|
983
|
+
return OSVision;
|
|
984
|
+
}
|
|
985
|
+
//获取设备类型
|
|
986
|
+
function getDeviceType() {
|
|
987
|
+
let deviceType;
|
|
988
|
+
const sUserAgent = navigator.userAgent.toLowerCase();
|
|
989
|
+
const bIsIpad = sUserAgent.match(/(ipad)/i) && 'ipad';
|
|
990
|
+
const bIsIphoneOs = sUserAgent.match(/iphone os/i) && 'iphone os';
|
|
991
|
+
const bIsMidp = sUserAgent.match(/midp/i) && 'midp';
|
|
992
|
+
const bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) && 'rv:1.2.3.4';
|
|
993
|
+
const bIsUc = sUserAgent.match(/ucweb/i) && 'ucweb';
|
|
994
|
+
const bIsAndroid = sUserAgent.match(/android/i) && 'android';
|
|
995
|
+
const bIsCE = sUserAgent.match(/windows ce/i) && 'windows ce';
|
|
996
|
+
const bIsWM = sUserAgent.match(/windows mobile/i) && 'windows mobile';
|
|
997
|
+
if (!(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM)) {
|
|
998
|
+
deviceType = 'pc'; //pc
|
|
999
|
+
} else if (bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
|
|
1000
|
+
deviceType = 'phone'; //phone
|
|
1001
|
+
} else if (bIsIpad) {
|
|
1002
|
+
deviceType = 'ipad'; //ipad
|
|
1003
|
+
} else {
|
|
1004
|
+
deviceType = undefined;
|
|
1005
|
+
}
|
|
1006
|
+
return deviceType;
|
|
1007
|
+
}
|
|
1008
|
+
// 获取网络状态
|
|
1009
|
+
function getNetWork() {
|
|
1010
|
+
let netWork: any;
|
|
1011
|
+
if ((navigator as any).connection && (navigator as any).connection.effectiveType) {
|
|
1012
|
+
switch ((navigator as any).connection.effectiveType) {
|
|
1013
|
+
case 'wifi':
|
|
1014
|
+
netWork = 'wifi'; // wifi
|
|
1015
|
+
break;
|
|
1016
|
+
case '4g':
|
|
1017
|
+
netWork = '4g'; // 4g
|
|
1018
|
+
break;
|
|
1019
|
+
case '2g':
|
|
1020
|
+
netWork = '2g'; // 2g
|
|
1021
|
+
break;
|
|
1022
|
+
case '3g':
|
|
1023
|
+
netWork = '3g'; // 3g
|
|
1024
|
+
break;
|
|
1025
|
+
case 'ethernet':
|
|
1026
|
+
netWork = 'ethernet'; // ethernet
|
|
1027
|
+
break;
|
|
1028
|
+
case 'default':
|
|
1029
|
+
netWork = undefined; // 未知
|
|
1030
|
+
break;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
return netWork;
|
|
1034
|
+
}
|
|
1035
|
+
// 获取横竖屏状态
|
|
1036
|
+
function getOrientationStatu() {
|
|
1037
|
+
let orientationStatu: any;
|
|
1038
|
+
if (window.screen && window.screen.orientation && window.screen.orientation.angle) {
|
|
1039
|
+
if (window.screen.orientation.angle === 180 || window.screen.orientation.angle === 0) { // 竖屏
|
|
1040
|
+
orientationStatu = '|';
|
|
1041
|
+
}
|
|
1042
|
+
if (window.screen.orientation.angle === 90 || window.screen.orientation.angle === -90) { // 横屏
|
|
1043
|
+
orientationStatu = '-';
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
return orientationStatu;
|
|
1047
|
+
}
|
|
1048
|
+
// 获取ssl连接时间
|
|
1049
|
+
function getSSLTime(connectEnd: any, secureConnectionStart: any) {
|
|
1050
|
+
let ssl_time: any;
|
|
1051
|
+
if (secureConnectionStart) {
|
|
1052
|
+
ssl_time = connectEnd - secureConnectionStart;
|
|
1053
|
+
}
|
|
1054
|
+
return ssl_time;
|
|
1055
|
+
}
|
|
1056
|
+
return status;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
/**
|
|
1060
|
+
* @method inRate
|
|
1061
|
+
* @description 百分位概率
|
|
1062
|
+
* @param {number} rate -- 0.1 ~ 1 => 1% ~ 100%
|
|
1063
|
+
* @returns {boolean} true 命中
|
|
1064
|
+
*/
|
|
1065
|
+
export function inRate(rate: number): boolean {
|
|
1066
|
+
if(Math.random() < rate) {
|
|
1067
|
+
return true;
|
|
1068
|
+
}
|
|
1069
|
+
return false;
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/**
|
|
1073
|
+
* @method isSafePWAEnv
|
|
1074
|
+
* @description 判断是否是安全的 PWA 环境
|
|
1075
|
+
* @returns {boolean} true 是
|
|
1076
|
+
*/
|
|
1077
|
+
export function isSafePWAEnv(): boolean {
|
|
1078
|
+
// 判断是否支持 async await
|
|
1079
|
+
function isSupportAsyncAwait() {
|
|
1080
|
+
let isSupportAsyncAwaitFunc;
|
|
1081
|
+
try {
|
|
1082
|
+
// eval("func = async function(){};");
|
|
1083
|
+
const fn = new Function("return async function(){};");
|
|
1084
|
+
isSupportAsyncAwaitFunc = fn();
|
|
1085
|
+
// console.log('isSupportAsyncAwaitFunc', isSupportAsyncAwaitFunc);
|
|
1086
|
+
// 由于async函数的构造器不是全局对象,所以我们需要由下面代码来获取async函数的构造器
|
|
1087
|
+
// 具体可以查看以下MDN上有关于AsyncFunction的说明,
|
|
1088
|
+
// 地址:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction
|
|
1089
|
+
return Object.getPrototypeOf(isSupportAsyncAwaitFunc).constructor != null;
|
|
1090
|
+
} catch (e) {
|
|
1091
|
+
return false;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
// 判断是否支持 Promise
|
|
1095
|
+
function isSupportPromise() {
|
|
1096
|
+
if(typeof Promise !== "undefined" && Promise.toString().indexOf("[native code]") !== -1){
|
|
1097
|
+
return true;
|
|
1098
|
+
}
|
|
1099
|
+
return false;
|
|
1100
|
+
}
|
|
1101
|
+
// 浏览器信息
|
|
1102
|
+
const BrowserType = getBrowserInfo();
|
|
1103
|
+
if (
|
|
1104
|
+
('serviceWorker' in navigator) &&
|
|
1105
|
+
isSupportAsyncAwait() &&
|
|
1106
|
+
isSupportPromise() &&
|
|
1107
|
+
Boolean(window.fetch) &&
|
|
1108
|
+
Boolean(window.indexedDB) &&
|
|
1109
|
+
Boolean(window.caches) &&
|
|
1110
|
+
!BrowserType['shell']
|
|
1111
|
+
) {
|
|
1112
|
+
return true;
|
|
1113
|
+
}
|
|
1114
|
+
return false;
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
/**
|
|
1118
|
+
* EN: Browser Information
|
|
1119
|
+
*
|
|
1120
|
+
* ZH: 返回浏览器信息 https://github.com/JowayYoung/juejin-code/blob/master/browser-type.js
|
|
1121
|
+
*
|
|
1122
|
+
* ```
|
|
1123
|
+
* getBrowserInfo(); // {"engine":"webkit","engineVs":"537.36","platform":"desktop","supporter":"chrome","supporterVs":"85.0.4183.121","system":"windows","systemVs":"10"}
|
|
1124
|
+
* ```
|
|
1125
|
+
*
|
|
1126
|
+
* | Index | Field | Description |
|
|
1127
|
+
* | --- | --- | --- |
|
|
1128
|
+
* | System | system | android, ios, windows, macos, linux |
|
|
1129
|
+
* | System version | systemVs | windows: 2000, xp, 2003, vista, 7, 8, 8.1, 10 <br />macos: ... |
|
|
1130
|
+
* | Platform | platform | desktop, mobile |
|
|
1131
|
+
* | Engine | engine | webkit, gecko, presto, trident |
|
|
1132
|
+
* | Engine version | engineVs | - |
|
|
1133
|
+
* | Supporter | supporter | edge, opera, chrome, safari, firefox, iexplore |
|
|
1134
|
+
* | Supporter version | supporterVs | - |
|
|
1135
|
+
* | Shell | shell | (Optional) wechat, qq_browser, qq_app, uc, 360, 2345, sougou, liebao, maxthon, bilibili |
|
|
1136
|
+
* | Shell version | shellVs | (Optional) |
|
|
1137
|
+
* | Apple device type | appleType | (Optional) iphone, ipad, ipod, iwatch |
|
|
1138
|
+
*
|
|
1139
|
+
* Example: Determine the environment of the mobile QQ.
|
|
1140
|
+
*
|
|
1141
|
+
* ```
|
|
1142
|
+
* const { system, shell } = getBrowserInfo();
|
|
1143
|
+
* const isMobileQQ = ['android', 'ios'].includes(system) && ['qq_browser', 'qq_app'].includes(shell);
|
|
1144
|
+
* ```
|
|
1145
|
+
*
|
|
1146
|
+
* @returns 浏览器信息
|
|
1147
|
+
*/
|
|
1148
|
+
export function getBrowserInfo(): {
|
|
1149
|
+
engine: string; // webkit gecko presto trident
|
|
1150
|
+
engineVs: string;
|
|
1151
|
+
platform: string; // desktop mobile
|
|
1152
|
+
supporter: string; // chrome safari firefox opera iexplore edge
|
|
1153
|
+
supporterVs: string;
|
|
1154
|
+
system: string; // windows macos linux android ios
|
|
1155
|
+
systemVs: string;
|
|
1156
|
+
shell?: string; // wechat qq uc 360 2345 sougou liebao maxthon
|
|
1157
|
+
shellVs?: string;
|
|
1158
|
+
appleType?: string;
|
|
1159
|
+
} {
|
|
1160
|
+
try {
|
|
1161
|
+
// 权重:系统 + 系统版本 > 平台 > 内核 + 载体 + 内核版本 + 载体版本 > 外壳 + 外壳版本
|
|
1162
|
+
const ua: string = navigator.userAgent.toLowerCase();
|
|
1163
|
+
const testUa: (regexp: RegExp) => boolean = regexp => regexp.test(ua);
|
|
1164
|
+
const testVs: (regexp: RegExp) => string = regexp => {
|
|
1165
|
+
const matchRes = ua.match(regexp);
|
|
1166
|
+
let ret = '';
|
|
1167
|
+
if (matchRes) {
|
|
1168
|
+
ret = matchRes
|
|
1169
|
+
.toString()
|
|
1170
|
+
.replace(/[^0-9|_.]/g, "")
|
|
1171
|
+
.replace(/_/g, ".");
|
|
1172
|
+
}
|
|
1173
|
+
return ret;
|
|
1174
|
+
};
|
|
1175
|
+
// 系统
|
|
1176
|
+
let system = '';
|
|
1177
|
+
// Apple device type.
|
|
1178
|
+
let appleType = '';
|
|
1179
|
+
if (testUa(/windows|win32|win64|wow32|wow64/g)) {
|
|
1180
|
+
system = "windows"; // windows系统
|
|
1181
|
+
} else if (testUa(/macintosh|macintel/g)) {
|
|
1182
|
+
system = "macos"; // macos系统
|
|
1183
|
+
} else if (testUa(/x11/g)) {
|
|
1184
|
+
system = "linux"; // linux系统
|
|
1185
|
+
} else if (testUa(/android|adr/g)) {
|
|
1186
|
+
system = "android"; // android系统
|
|
1187
|
+
} else if (testUa(/ios|iphone|ipad|ipod|iwatch/g)) {
|
|
1188
|
+
system = "ios"; // ios系统
|
|
1189
|
+
if (testUa(/iphone/g)) {
|
|
1190
|
+
appleType = 'iphone';
|
|
1191
|
+
} else if (testUa(/ipad/g)) {
|
|
1192
|
+
appleType = 'ipad';
|
|
1193
|
+
} else if (testUa(/iwatch/g)) {
|
|
1194
|
+
appleType = 'iwatch';
|
|
1195
|
+
} else if (testUa(/ipod/g)) {
|
|
1196
|
+
appleType = 'ipod';
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
// 系统版本
|
|
1200
|
+
let systemVs = '';
|
|
1201
|
+
if (system === "windows") {
|
|
1202
|
+
if (testUa(/windows nt 5.0|windows 2000/g)) {
|
|
1203
|
+
systemVs = "2000";
|
|
1204
|
+
} else if (testUa(/windows nt 5.1|windows xp/g)) {
|
|
1205
|
+
systemVs = "xp";
|
|
1206
|
+
} else if (testUa(/windows nt 5.2|windows 2003/g)) {
|
|
1207
|
+
systemVs = "2003";
|
|
1208
|
+
} else if (testUa(/windows nt 6.0|windows vista/g)) {
|
|
1209
|
+
systemVs = "vista";
|
|
1210
|
+
} else if (testUa(/windows nt 6.1|windows 7/g)) {
|
|
1211
|
+
systemVs = "7";
|
|
1212
|
+
} else if (testUa(/windows nt 6.2|windows 8/g)) {
|
|
1213
|
+
systemVs = "8";
|
|
1214
|
+
} else if (testUa(/windows nt 6.3|windows 8.1/g)) {
|
|
1215
|
+
systemVs = "8.1";
|
|
1216
|
+
} else if (testUa(/windows nt 10.0|windows 10/g)) {
|
|
1217
|
+
systemVs = "10";
|
|
1218
|
+
}
|
|
1219
|
+
} else if (system === "macos") {
|
|
1220
|
+
systemVs = testVs(/os x [\d._]+/g);
|
|
1221
|
+
} else if (system === "android") {
|
|
1222
|
+
systemVs = testVs(/android [\d._]+/g);
|
|
1223
|
+
} else if (system === "ios") {
|
|
1224
|
+
systemVs = testVs(/os [\d._]+/g);
|
|
1225
|
+
}
|
|
1226
|
+
// 平台
|
|
1227
|
+
let platform = '';
|
|
1228
|
+
if (system === "windows" || system === "macos" || system === "linux") {
|
|
1229
|
+
platform = "desktop"; // 桌面端
|
|
1230
|
+
} else if (system === "android" || system === "ios" || testUa(/mobile/g)) {
|
|
1231
|
+
platform = "mobile"; // 移动端
|
|
1232
|
+
}
|
|
1233
|
+
// 内核和载体
|
|
1234
|
+
let engine = '';
|
|
1235
|
+
let supporter = '';
|
|
1236
|
+
if (testUa(/applewebkit/g)) {
|
|
1237
|
+
engine = "webkit"; // webkit内核
|
|
1238
|
+
if (testUa(/edge/g)) {
|
|
1239
|
+
supporter = "edge"; // edge浏览器
|
|
1240
|
+
} else if (testUa(/opr/g)) {
|
|
1241
|
+
supporter = "opera"; // opera浏览器
|
|
1242
|
+
} else if (testUa(/chrome/g)) {
|
|
1243
|
+
supporter = "chrome"; // chrome浏览器
|
|
1244
|
+
} else if (testUa(/safari/g)) {
|
|
1245
|
+
supporter = "safari"; // safari浏览器
|
|
1246
|
+
}
|
|
1247
|
+
} else if (testUa(/gecko/g) && testUa(/firefox/g)) {
|
|
1248
|
+
engine = "gecko"; // gecko内核
|
|
1249
|
+
supporter = "firefox"; // firefox浏览器
|
|
1250
|
+
} else if (testUa(/presto/g)) {
|
|
1251
|
+
engine = "presto"; // presto内核
|
|
1252
|
+
supporter = "opera"; // opera浏览器
|
|
1253
|
+
} else if (testUa(/trident|compatible|msie/g)) {
|
|
1254
|
+
engine = "trident"; // trident内核
|
|
1255
|
+
supporter = "iexplore"; // iexplore浏览器
|
|
1256
|
+
}
|
|
1257
|
+
// 内核版本
|
|
1258
|
+
let engineVs = '';
|
|
1259
|
+
if (engine === "webkit") {
|
|
1260
|
+
engineVs = testVs(/applewebkit\/[\d._]+/g);
|
|
1261
|
+
} else if (engine === "gecko") {
|
|
1262
|
+
engineVs = testVs(/gecko\/[\d._]+/g);
|
|
1263
|
+
} else if (engine === "presto") {
|
|
1264
|
+
engineVs = testVs(/presto\/[\d._]+/g);
|
|
1265
|
+
} else if (engine === "trident") {
|
|
1266
|
+
engineVs = testVs(/trident\/[\d._]+/g);
|
|
1267
|
+
}
|
|
1268
|
+
// 载体版本
|
|
1269
|
+
let supporterVs = '';
|
|
1270
|
+
if (supporter === "chrome") {
|
|
1271
|
+
supporterVs = testVs(/chrome\/[\d._]+/g);
|
|
1272
|
+
} else if (supporter === "safari") {
|
|
1273
|
+
supporterVs = testVs(/version\/[\d._]+/g);
|
|
1274
|
+
} else if (supporter === "firefox") {
|
|
1275
|
+
supporterVs = testVs(/firefox\/[\d._]+/g);
|
|
1276
|
+
} else if (supporter === "opera") {
|
|
1277
|
+
supporterVs = testVs(/opr\/[\d._]+/g);
|
|
1278
|
+
} else if (supporter === "iexplore") {
|
|
1279
|
+
supporterVs = testVs(/(msie [\d._]+)|(rv:[\d._]+)/g);
|
|
1280
|
+
} else if (supporter === "edge") {
|
|
1281
|
+
supporterVs = testVs(/edge\/[\d._]+/g);
|
|
1282
|
+
}
|
|
1283
|
+
// 外壳和外壳版本
|
|
1284
|
+
let shell = '';
|
|
1285
|
+
let shellVs = '';
|
|
1286
|
+
if (testUa(/micromessenger/g)) {
|
|
1287
|
+
shell = "wechat"; // 微信浏览器
|
|
1288
|
+
shellVs = testVs(/micromessenger\/[\d._]+/g);
|
|
1289
|
+
} else if (testUa(/qqbrowser/g)) {
|
|
1290
|
+
shell = "qq_browser"; // QQ Browser
|
|
1291
|
+
shellVs = testVs(/qqbrowser\/[\d._]+/g);
|
|
1292
|
+
} else if (testUa(/\sqq/g)) {
|
|
1293
|
+
shell = "qq_app"; // QQ APP
|
|
1294
|
+
} else if (testUa(/ucbrowser/g)) {
|
|
1295
|
+
shell = "uc"; // UC浏览器
|
|
1296
|
+
shellVs = testVs(/ucbrowser\/[\d._]+/g);
|
|
1297
|
+
} else if (testUa(/qihu 360se/g)) {
|
|
1298
|
+
shell = "360"; // 360浏览器(无版本)
|
|
1299
|
+
} else if (testUa(/2345explorer/g)) {
|
|
1300
|
+
shell = "2345"; // 2345浏览器
|
|
1301
|
+
shellVs = testVs(/2345explorer\/[\d._]+/g);
|
|
1302
|
+
} else if (testUa(/metasr/g)) {
|
|
1303
|
+
shell = "sougou"; // 搜狗浏览器(无版本)
|
|
1304
|
+
} else if (testUa(/lbbrowser/g)) {
|
|
1305
|
+
shell = "liebao"; // 猎豹浏览器(无版本)
|
|
1306
|
+
} else if (testUa(/maxthon/g)) {
|
|
1307
|
+
shell = "maxthon"; // 遨游浏览器
|
|
1308
|
+
shellVs = testVs(/maxthon\/[\d._]+/g);
|
|
1309
|
+
} else if (testUa(/biliapp/g)) {
|
|
1310
|
+
shell = "bilibili"; // 哔哩哔哩
|
|
1311
|
+
}
|
|
1312
|
+
return Object.assign({
|
|
1313
|
+
engine, // webkit gecko presto trident
|
|
1314
|
+
engineVs,
|
|
1315
|
+
platform, // desktop mobile
|
|
1316
|
+
supporter, // chrome safari firefox opera iexplore edge
|
|
1317
|
+
supporterVs,
|
|
1318
|
+
system, // windows macos linux android ios
|
|
1319
|
+
systemVs,
|
|
1320
|
+
}, {
|
|
1321
|
+
shell, // wechat qq uc 360 2345 sougou liebao maxthon
|
|
1322
|
+
shellVs,
|
|
1323
|
+
appleType,
|
|
1324
|
+
});
|
|
1325
|
+
} catch (err) {
|
|
1326
|
+
console.warn('mazey:', err);
|
|
1327
|
+
return {
|
|
1328
|
+
engine: '', // webkit gecko presto trident
|
|
1329
|
+
engineVs: '',
|
|
1330
|
+
platform: '', // desktop mobile
|
|
1331
|
+
supporter: '', // chrome safari firefox opera iexplore edge
|
|
1332
|
+
supporterVs: '',
|
|
1333
|
+
system: '', // windows macos linux android ios
|
|
1334
|
+
systemVs: '',
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
/**
|
|
1340
|
+
* @method clearHtml
|
|
1341
|
+
* @description 去除HTML标签
|
|
1342
|
+
* @param {string} str 带html标签的字符串
|
|
1343
|
+
* @returns {string} 字符串
|
|
1344
|
+
*/
|
|
1345
|
+
export function clearHtml (str: string): string {
|
|
1346
|
+
return str.replace(/<\/?.+?>/g, '').replace(/[\r\n]/g, '');
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
/**
|
|
1350
|
+
* @method cutCHSString
|
|
1351
|
+
* @description 截取字符串,中文算2个字节
|
|
1352
|
+
* @param {string} str 要截取的字符串
|
|
1353
|
+
* @param {number} len
|
|
1354
|
+
* @param {boolean} hasDot
|
|
1355
|
+
* @returnss {string} 返回截取后的字符串
|
|
1356
|
+
*/
|
|
1357
|
+
export function cutCHSString(str: string, len: number, hasDot = false): string {
|
|
1358
|
+
if (str == '' || !str) {
|
|
1359
|
+
return '';
|
|
1360
|
+
} else {
|
|
1361
|
+
let newLength = 0;
|
|
1362
|
+
let newStr = '';
|
|
1363
|
+
// eslint-disable-next-line no-control-regex
|
|
1364
|
+
const chineseRegex = /[^\x00-\xff]/g;
|
|
1365
|
+
let singleChar = '';
|
|
1366
|
+
const strLength = str.replace(chineseRegex, '**').length;
|
|
1367
|
+
for (let i = 0; i < strLength; i++) {
|
|
1368
|
+
singleChar = str.charAt(i).toString();
|
|
1369
|
+
if (singleChar.match(chineseRegex) != null) {
|
|
1370
|
+
newLength += 2;
|
|
1371
|
+
} else {
|
|
1372
|
+
newLength++;
|
|
1373
|
+
}
|
|
1374
|
+
if (newLength > len) {
|
|
1375
|
+
break;
|
|
1376
|
+
}
|
|
1377
|
+
newStr += singleChar;
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
if (hasDot && strLength > len) {
|
|
1381
|
+
newStr += '...';
|
|
1382
|
+
}
|
|
1383
|
+
return newStr;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
/**
|
|
1388
|
+
* @method windowLoaded
|
|
1389
|
+
* @description 页面加载完成
|
|
1390
|
+
* @param {number} timeout 超时时间 / 单位:秒
|
|
1391
|
+
* @returns {Promise<string>} document is loaded? 'complete' 'load' / 'timeout'
|
|
1392
|
+
*/
|
|
1393
|
+
export function windowLoaded(timeout = 90): Promise<string | Error> {
|
|
1394
|
+
let loaded: (value: string) => void = () => undefined;
|
|
1395
|
+
let loadFail: (value: Error) => void;
|
|
1396
|
+
const status = new Promise((resolve: (value: string) => void, reject: (value: Error) => void) => {
|
|
1397
|
+
loaded = resolve;
|
|
1398
|
+
loadFail = reject;
|
|
1399
|
+
});
|
|
1400
|
+
if (document.readyState === 'complete') {
|
|
1401
|
+
loaded('complete');
|
|
1402
|
+
} else {
|
|
1403
|
+
window.addEventListener('load', () => loaded('load'));
|
|
1404
|
+
}
|
|
1405
|
+
// 超过 timeout 秒后加载失败
|
|
1406
|
+
setTimeout(() => loadFail(Error('timeout')), timeout * 1000);
|
|
1407
|
+
return status;
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
/**
|
|
1411
|
+
* EN: Add `<style>` in `<head>`.
|
|
1412
|
+
*
|
|
1413
|
+
* ZH: 添加样式标签; style: 样式标签内的字符串; id: `<style>` 标签的 `id`; 返回: 添加成功/失败.
|
|
1414
|
+
*
|
|
1415
|
+
* Example 1: Add the `<style>` with `id`, and repeated invoking will update the content instead of adding a new one.
|
|
1416
|
+
*
|
|
1417
|
+
* ```
|
|
1418
|
+
* addStyle(
|
|
1419
|
+
* `
|
|
1420
|
+
* body {
|
|
1421
|
+
* background-color: #333;
|
|
1422
|
+
* }
|
|
1423
|
+
* `,
|
|
1424
|
+
* {
|
|
1425
|
+
* id: 'test',
|
|
1426
|
+
* }
|
|
1427
|
+
* );
|
|
1428
|
+
* // <style id="test">
|
|
1429
|
+
* // body {
|
|
1430
|
+
* // background-color: #333;
|
|
1431
|
+
* // }
|
|
1432
|
+
* // </style>
|
|
1433
|
+
* ```
|
|
1434
|
+
*
|
|
1435
|
+
* Example 2: Add the `<style>` without `id`, and repeated invoking will adding a new one.
|
|
1436
|
+
*
|
|
1437
|
+
* ```
|
|
1438
|
+
* addStyle(
|
|
1439
|
+
* `
|
|
1440
|
+
* body {
|
|
1441
|
+
* background-color: #333;
|
|
1442
|
+
* }
|
|
1443
|
+
* `
|
|
1444
|
+
* );
|
|
1445
|
+
* // <style>
|
|
1446
|
+
* // body {
|
|
1447
|
+
* // background-color: #333;
|
|
1448
|
+
* // }
|
|
1449
|
+
* // </style>
|
|
1450
|
+
* ```
|
|
1451
|
+
*
|
|
1452
|
+
* @param style Style string.
|
|
1453
|
+
* @param options.id `id` in `<style>`
|
|
1454
|
+
* @returns Success/Fail
|
|
1455
|
+
*/
|
|
1456
|
+
export function addStyle(style: string, options: { id?: string; } = { id: '' }): boolean {
|
|
1457
|
+
// console.log('_ style', style);
|
|
1458
|
+
// console.log('_ options', options);
|
|
1459
|
+
if (!style) {
|
|
1460
|
+
return false;
|
|
1461
|
+
}
|
|
1462
|
+
// 创建 style 文档碎片
|
|
1463
|
+
const styleFrag = document.createDocumentFragment();
|
|
1464
|
+
let idDom: HTMLElement | null = null;
|
|
1465
|
+
let domId = '';
|
|
1466
|
+
// Custom Style
|
|
1467
|
+
const customStyle = document.createElement('style');
|
|
1468
|
+
// 如果需要 ID
|
|
1469
|
+
if (options.id) {
|
|
1470
|
+
domId = `${options.id}`;
|
|
1471
|
+
idDom = document.getElementById(domId);
|
|
1472
|
+
// 如果 Dom 不存在,插入 style
|
|
1473
|
+
if (!idDom) {
|
|
1474
|
+
customStyle.setAttribute('id', options.id);
|
|
1475
|
+
customStyle.innerHTML = style;
|
|
1476
|
+
styleFrag.appendChild(customStyle);
|
|
1477
|
+
document.head.appendChild(styleFrag);
|
|
1478
|
+
} else { // 如果 Dom 存在,直接更新
|
|
1479
|
+
idDom.innerHTML = style;
|
|
1480
|
+
}
|
|
1481
|
+
} else { // 不需要 ID,直接添加新标签
|
|
1482
|
+
customStyle.innerHTML = style;
|
|
1483
|
+
styleFrag.appendChild(customStyle);
|
|
1484
|
+
document.head.appendChild(styleFrag);
|
|
1485
|
+
}
|
|
1486
|
+
return true;
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
/**
|
|
1490
|
+
* @method genCustomConsole
|
|
1491
|
+
* @description 生成自定义控制台打印
|
|
1492
|
+
* @param {string} prefix 前缀
|
|
1493
|
+
* @param {function} allowFn 允许打印的判断函数
|
|
1494
|
+
* @returns {object} 新实例
|
|
1495
|
+
*/
|
|
1496
|
+
export function genCustomConsole(prefix = ''): Console {
|
|
1497
|
+
const methods = ['log', 'info', 'warn', 'error'];
|
|
1498
|
+
const newConsole = Object.create(null);
|
|
1499
|
+
methods.forEach(method => {
|
|
1500
|
+
newConsole[method] = function (...argu: any) {
|
|
1501
|
+
if (prefix) {
|
|
1502
|
+
(console as any)[method](prefix, ...argu);
|
|
1503
|
+
} else {
|
|
1504
|
+
(console as any)[method](...argu);
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
});
|
|
1508
|
+
return newConsole;
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
/**
|
|
1512
|
+
* Verify the validity of axios response.
|
|
1513
|
+
*
|
|
1514
|
+
* Reference: [Handling Errors](https://axios-http.com/docs/handling_errors)
|
|
1515
|
+
*/
|
|
1516
|
+
export function zAxiosIsValidRes(res: any, options: {
|
|
1517
|
+
validStatusRange: number[];
|
|
1518
|
+
validCode: number[];
|
|
1519
|
+
} = {
|
|
1520
|
+
validStatusRange: [200, 300],
|
|
1521
|
+
validCode: [0],
|
|
1522
|
+
}): boolean {
|
|
1523
|
+
const { validStatusRange, validCode } = Object.assign(
|
|
1524
|
+
{
|
|
1525
|
+
validStatusRange: [200, 300],
|
|
1526
|
+
validCode: [0],
|
|
1527
|
+
},
|
|
1528
|
+
options,
|
|
1529
|
+
);
|
|
1530
|
+
if (validStatusRange.length !== 2) {
|
|
1531
|
+
console.error('valid validStatusRange is required');
|
|
1532
|
+
}
|
|
1533
|
+
let ret = false;
|
|
1534
|
+
if (res && res.status && validStatusRange.length === 2 && res.status >= validStatusRange[0] && res.status < validStatusRange[1]) {
|
|
1535
|
+
const resData = res.data;
|
|
1536
|
+
if (resData && validCode.includes(resData.code)) {
|
|
1537
|
+
ret = true;
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
return ret;
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
/**
|
|
1544
|
+
* Verify the validity of a non-empty array.
|
|
1545
|
+
*/
|
|
1546
|
+
export function isNonEmptyArray(arr: any[]): boolean {
|
|
1547
|
+
let ret = false;
|
|
1548
|
+
if (Array.isArray(arr) && arr.length) {
|
|
1549
|
+
ret = true;
|
|
1550
|
+
}
|
|
1551
|
+
return ret;
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
/**
|
|
1555
|
+
* 语义化文件大小, 把字节转换成正常文件大小.
|
|
1556
|
+
*/
|
|
1557
|
+
export function getFileSize(size: number): string {
|
|
1558
|
+
const toCeilStr: (v: number) => string = n => String(Math.ceil(n));
|
|
1559
|
+
if (!size) return '';
|
|
1560
|
+
const num = 1024.0; // byte
|
|
1561
|
+
if (size < num) {
|
|
1562
|
+
return size + ' B';
|
|
1563
|
+
}
|
|
1564
|
+
if (size < Math.pow(num, 2)) {
|
|
1565
|
+
return toCeilStr(size / num) + ' KB';
|
|
1566
|
+
} // kb
|
|
1567
|
+
if (size < Math.pow(num, 3)) {
|
|
1568
|
+
return toCeilStr(size / Math.pow(num, 2)) + ' MB';
|
|
1569
|
+
} // M
|
|
1570
|
+
if (size < Math.pow(num, 4)) {
|
|
1571
|
+
return toCeilStr(size / Math.pow(num, 3)) + ' G';
|
|
1572
|
+
} // G
|
|
1573
|
+
return toCeilStr(size / Math.pow(num, 4)) + ' T';
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
/**
|
|
1577
|
+
* Detect webp support.
|
|
1578
|
+
*
|
|
1579
|
+
* Reference: [Detect WEBP Support with JavaScript](https://davidwalsh.name/detect-webp)
|
|
1580
|
+
*/
|
|
1581
|
+
export function isSupportWebp(): Promise<boolean> {
|
|
1582
|
+
const fn = (resolve: (v: boolean) => void) => {
|
|
1583
|
+
const img = new Image();
|
|
1584
|
+
img.onload = () => {
|
|
1585
|
+
resolve(img.width > 0 && img.height > 0);
|
|
1586
|
+
};
|
|
1587
|
+
img.onerror = () => {
|
|
1588
|
+
resolve(false);
|
|
1589
|
+
};
|
|
1590
|
+
img.src = "data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=";
|
|
1591
|
+
};
|
|
1592
|
+
return new Promise(fn);
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
/**
|
|
1596
|
+
* Generate a Hash Code from a string.
|
|
1597
|
+
*
|
|
1598
|
+
* Reference: [Generate a Hash from string in Javascript](https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery)
|
|
1599
|
+
*/
|
|
1600
|
+
export function genHashCode(str: string): number {
|
|
1601
|
+
let hash = 0, i, chr;
|
|
1602
|
+
for (i = 0; i < str.length; i++) {
|
|
1603
|
+
chr = str.charCodeAt(i);
|
|
1604
|
+
hash = ((hash << 5) - hash) + chr;
|
|
1605
|
+
hash |= 0;
|
|
1606
|
+
}
|
|
1607
|
+
return hash;
|
|
1608
|
+
}
|