mazey 3.1.0 → 3.2.0

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