mazey 3.3.6 → 3.3.8

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