util-helpers 4.15.3 → 4.16.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.
Files changed (53) hide show
  1. package/README.md +6 -5
  2. package/dist/util-helpers.js +452 -48
  3. package/dist/util-helpers.js.map +1 -1
  4. package/dist/util-helpers.min.js +1 -1
  5. package/dist/util-helpers.min.js.map +1 -1
  6. package/esm/ajax.js +149 -0
  7. package/esm/blobToDataURL.js +8 -12
  8. package/esm/dataURLToBlob.js +6 -5
  9. package/esm/download.js +156 -0
  10. package/esm/fileReader.js +67 -0
  11. package/esm/index.js +4 -1
  12. package/esm/interface.doc.js +124 -0
  13. package/esm/numberToChinese.js +3 -2
  14. package/esm/parseIdCard.js +1 -1
  15. package/esm/safeDate.js +26 -9
  16. package/esm/transformFieldNames.js +2 -3
  17. package/esm/utils/config.js +1 -1
  18. package/esm/utils/type/index.js +3 -1
  19. package/esm/utils/type/isArrayBuffer.js +25 -0
  20. package/esm/utils/type/isBlob.js +27 -0
  21. package/lib/ajax.js +156 -0
  22. package/lib/blobToDataURL.js +8 -12
  23. package/lib/dataURLToBlob.js +6 -5
  24. package/lib/download.js +161 -0
  25. package/lib/fileReader.js +74 -0
  26. package/lib/index.js +22 -1
  27. package/lib/interface.doc.js +126 -0
  28. package/lib/numberToChinese.js +3 -2
  29. package/lib/parseIdCard.js +1 -1
  30. package/lib/safeDate.js +27 -10
  31. package/lib/transformFieldNames.js +1 -1
  32. package/lib/utils/config.js +1 -1
  33. package/lib/utils/type/index.js +14 -0
  34. package/lib/utils/type/isArrayBuffer.js +32 -0
  35. package/lib/utils/type/isBlob.js +34 -0
  36. package/package.json +2 -2
  37. package/types/ajax.d.ts +121 -0
  38. package/types/blobToDataURL.d.ts +5 -1
  39. package/types/download.d.ts +77 -0
  40. package/types/fileReader.d.ts +3 -0
  41. package/types/index.d.ts +4 -1
  42. package/types/numberToChinese.d.ts +3 -2
  43. package/types/parseIdCard.d.ts +2 -2
  44. package/types/safeDate.d.ts +3 -23
  45. package/types/transformFieldNames.d.ts +2 -2
  46. package/types/utils/type/index.d.ts +21 -19
  47. package/types/utils/type/isArrayBuffer.d.ts +21 -0
  48. package/types/utils/type/isBlob.d.ts +23 -0
  49. package/esm/transformFieldNames.doc.js +0 -35
  50. package/lib/transformFieldNames.doc.js +0 -42
  51. /package/esm/{transformFieldNames.type.js → interface.type.js} +0 -0
  52. /package/lib/{transformFieldNames.type.js → interface.type.js} +0 -0
  53. /package/types/{transformFieldNames.type.d.ts → interface.type.d.ts} +0 -0
package/README.md CHANGED
@@ -53,11 +53,9 @@ formatBankCard('6228480402564890018', { spaceMark: '-' }); // 6228-4804-0256-489
53
53
  - [blobToDataURL](https://doly-dev.github.io/util-helpers/module-Processor.html#.blobToDataURL) - 将 Blob 或 File 对象转成 data:URL 格式的 Base64 字符串
54
54
  - [bytesToSize](https://doly-dev.github.io/util-helpers/module-Processor.html#.bytesToSize) - 字节转换为存储单位
55
55
  - [dataURLToBlob](https://doly-dev.github.io/util-helpers/module-Processor.html#.dataURLToBlob) - 将 DataURL 转为 Blob 对象
56
- - [filterTree](https://doly-dev.github.io/util-helpers/module-Processor.html#.filterTree) - 过滤树节点
57
56
  - [formatMoney](https://doly-dev.github.io/util-helpers/module-Processor.html#.formatMoney) - 格式化金额
58
57
  - [formatMobile](https://doly-dev.github.io/util-helpers/module-Processor.html#.formatMobile) - 格式化手机号码
59
58
  - [formatBankCard](https://doly-dev.github.io/util-helpers/module-Processor.html#.formatBankCard) - 格式化银行卡
60
- - [listToTree](https://doly-dev.github.io/util-helpers/module-Processor.html#.listToTree) - 列表数据转树结构
61
59
  - [normalizeString](https://doly-dev.github.io/util-helpers/module-Processor.html#.normalizeString) - 规整化字符串,如果值为 `undefined` `null` 转为 '',如果不是字符串类型则转为字符串
62
60
  - [numberToChinese](https://doly-dev.github.io/util-helpers/module-Processor.html#.numberToChinese) - 数字转中文数字
63
61
  - [padZero](https://doly-dev.github.io/util-helpers/module-Processor.html#.padZero) - 前置补零
@@ -65,6 +63,12 @@ formatBankCard('6228480402564890018', { spaceMark: '-' }); // 6228-4804-0256-489
65
63
  - [replaceChar](https://doly-dev.github.io/util-helpers/module-Processor.html#.replaceChar) - 替换字符,应用场景如:脱敏
66
64
  - [safeDate](https://doly-dev.github.io/util-helpers/module-Processor.html#.safeDate) - 创建一个 Date 实例,同 new Date
67
65
  - [setDataURLPrefix](https://doly-dev.github.io/util-helpers/module-Processor.html#.setDataURLPrefix) - 设置 DataURL 前缀、MIME 类型、base64 标识
66
+ - 树结构数据操作
67
+ - [findTreeNode](https://doly-dev.github.io/util-helpers/module-Other.html#.findTreeNode) - 查找树结构数据节点
68
+ - [findTreeNodes](https://doly-dev.github.io/util-helpers/module-Other.html#.findTreeNodes) - 查找树结构数据多个节点
69
+ - [findTreeSelect](https://doly-dev.github.io/util-helpers/module-Other.html#.findTreeSelect) - 查找包含当前节点的所有父级节点
70
+ - [filterTree](https://doly-dev.github.io/util-helpers/module-Processor.html#.filterTree) - 过滤树节点
71
+ - [listToTree](https://doly-dev.github.io/util-helpers/module-Processor.html#.listToTree) - 列表数据转树结构
68
72
  - [transformFieldNames](https://doly-dev.github.io/util-helpers/module-Processor.html#.transformFieldNames) - 转换字段名
69
73
  - [treeToList](https://doly-dev.github.io/util-helpers/module-Processor.html#.treeToList) - 树结构转列表数据
70
74
  - 数据验证
@@ -92,9 +96,6 @@ formatBankCard('6228480402564890018', { spaceMark: '-' }); // 6228-4804-0256-489
92
96
  - [validatePassword](https://doly-dev.github.io/util-helpers/module-Validator.html#.validatePassword) - 验证密码
93
97
  - 其他
94
98
  - [calculateCursorPosition](https://doly-dev.github.io/util-helpers/module-Other.html#.calculateCursorPosition) - 计算光标位置
95
- - [findTreeNode](https://doly-dev.github.io/util-helpers/module-Other.html#.findTreeNode) - 查找树结构数据节点
96
- - [findTreeNodes](https://doly-dev.github.io/util-helpers/module-Other.html#.findTreeNodes) - 查找树结构数据多个节点
97
- - [findTreeSelect](https://doly-dev.github.io/util-helpers/module-Other.html#.findTreeSelect) - 查找包含当前节点的所有父级节点
98
99
  - [randomString](https://doly-dev.github.io/util-helpers/module-Other.html#.randomString) - 随机字符串
99
100
  - [strlen](https://doly-dev.github.io/util-helpers/module-Other.html#.strlen) - 字符长度
100
101
  - [waitTime](https://doly-dev.github.io/util-helpers/module-Other.html#.waitTime) - 等待时间返回 Promise
@@ -537,7 +537,7 @@
537
537
  }
538
538
 
539
539
  // eslint-disable-next-line no-undef
540
- var version = "4.15.3";
540
+ var version = "4.16.0";
541
541
 
542
542
  /**
543
543
  * 打印警告信息
@@ -1542,6 +1542,31 @@
1542
1542
  // 最小安全数字
1543
1543
  var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
1544
1544
 
1545
+ /**
1546
+ * 检查值是否为Blob对象<br/><br/>
1547
+ *
1548
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端。</em>
1549
+ *
1550
+ * @static
1551
+ * @alias module:Type.isBlob
1552
+ * @since 4.16.0
1553
+ * @param {*} value 检查值
1554
+ * @returns {boolean} 是否为Blob对象
1555
+ * @example
1556
+ *
1557
+ * isBlob(new Blob(['a']))
1558
+ * // => true
1559
+ *
1560
+ * isBlob({})
1561
+ * // => false
1562
+ *
1563
+ * isBlob('2012')
1564
+ * // => false
1565
+ */
1566
+ function isBlob(value) {
1567
+ return isType(value, 'Blob');
1568
+ }
1569
+
1545
1570
  /**
1546
1571
  * 检查值是否为Object
1547
1572
  *
@@ -2215,8 +2240,9 @@
2215
2240
  }
2216
2241
 
2217
2242
  /**
2218
- * 数字转中文数字
2219
- * 不在安全数字 -9007199254740991~9007199254740991 内,处理会有异常
2243
+ * 数字转中文数字<br/><br/>
2244
+ *
2245
+ * 如果数字不在安全数字 -9007199254740991~9007199254740991 范围内,处理会有异常。
2220
2246
  *
2221
2247
  * @static
2222
2248
  * @alias module:Processor.numberToChinese
@@ -2423,7 +2449,7 @@
2423
2449
  * @since 4.0.0
2424
2450
  * @see 参考 {@link https://baike.baidu.com/item/居民身份证号码|居民身份证号码}
2425
2451
  * @param {string} id 身份证号码,支持15位
2426
- * @returns {null|IdCardInfo} null 或 省份、生日、性别,省/市/区/年/月/日/性别编码
2452
+ * @returns {IdCardInfo | null} 省份、生日、性别,省/市/区/年/月/日/性别编码。如果解析失败将返回 null
2427
2453
  * @example
2428
2454
  *
2429
2455
  * parseIdCard('123456789123456'); // null
@@ -2485,37 +2511,63 @@
2485
2511
  };
2486
2512
  }
2487
2513
 
2488
- // file、blob文件如何预览图片?
2489
- // 方法1:将file或者blob类型文件转成base64数据,再作为src赋值给img标签
2490
- // 方法2:使用 window.URL.createObjectURL(blob) 为blob、file 创建一个指向该参数对象的URL
2514
+ var FileReaderMethodMap = {
2515
+ arrayBuffer: 'readAsArrayBuffer',
2516
+ binaryString: 'readAsBinaryString',
2517
+ dataURL: 'readAsDataURL',
2518
+ text: 'readAsText'
2519
+ };
2520
+
2521
+ /**
2522
+ * @overload
2523
+ * @param {Blob} blob
2524
+ * @param {'arrayBuffer'} type
2525
+ * @returns {Promise<ArrayBuffer>}
2526
+ */
2527
+
2528
+ /**
2529
+ * @overload
2530
+ * @param {Blob} blob
2531
+ * @param {'binaryString'|'binaryString'|'dataURL'|'text'} [type='dataURL']
2532
+ * @returns {Promise<string>}
2533
+ */
2491
2534
 
2492
2535
  /**
2493
- * Blob 或 File 对象转成 data:URL 格式的 Base64 字符串。
2536
+ * 读取 Blob 或 File 对象<br/><br/>
2537
+ *
2538
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端。</em>
2494
2539
  *
2495
2540
  * @static
2496
- * @alias module:Processor.blobToDataURL
2497
- * @see 参考 {@link https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader/readAsDataURL|FileReader.readAsDataURL()}
2498
- * @since 4.1.0
2541
+ * @alias module:Processor.fileReader
2542
+ * @see 参考 {@link https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader|FileReader}
2543
+ * @since 4.16.0
2499
2544
  * @param {Blob} blob Blob 或 File 对象
2500
- * @returns {Promise<string>} data:URL 格式的 Base64 字符串。
2545
+ * @param {'arrayBuffer'|'binaryString'|'dataURL'|'text'} [type='dataURL'] Blob File 对象
2546
+ * @returns {Promise<string|ArrayBuffer>} 文件的内容
2501
2547
  * @example
2502
2548
  * const aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // 一个包含DOMString的数组
2503
2549
  * const htmlBlob = new Blob(aFileParts, { type: 'text/html' }); // 得到 blob
2504
2550
  *
2505
- * blobToDataURL(htmlBlob).then(data=>{
2551
+ * fileReader(htmlBlob).then(data=>{
2506
2552
  * console.log(data); // data:text/html;base64,PGEgaWQ9ImEiPjxiIGlkPSJiIj5oZXkhPC9iPjwvYT4=
2507
2553
  * });
2508
2554
  *
2509
2555
  * const textBlob = new Blob(aFileParts, { type: 'text/plain' });
2510
2556
  *
2511
- * blobToDataURL(textBlob).then(data=>{
2512
- * console.log(data); // data:text/plain;base64,PGEgaWQ9ImEiPjxiIGlkPSJiIj5oZXkhPC9iPjwvYT4=
2557
+ * fileReader(textBlob, 'text').then(data=>{
2558
+ * console.log(data); // <a id="a"><b id="b">hey!</b></a>
2513
2559
  * });
2514
2560
  */
2515
- function blobToDataURL(blob) {
2561
+ function fileReader(blob) {
2562
+ var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'dataURL';
2563
+ var method = FileReaderMethodMap[type];
2564
+ if (!method) {
2565
+ method = FileReaderMethodMap.dataURL;
2566
+ }
2516
2567
  return new Promise(function (resolve, reject) {
2517
2568
  var reader = new FileReader();
2518
- reader.readAsDataURL(blob);
2569
+ // @ts-ignore
2570
+ reader[method](blob);
2519
2571
  // @ts-ignore
2520
2572
  reader.onload = function () {
2521
2573
  return resolve(reader.result);
@@ -2526,6 +2578,39 @@
2526
2578
  });
2527
2579
  }
2528
2580
 
2581
+ // file、blob文件如何预览图片?
2582
+
2583
+ /**
2584
+ * 将 Blob 或 File 对象转成 data:URL 格式的 Base64 字符串<br/><br/>
2585
+ *
2586
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端。</em>
2587
+ *
2588
+ * @static
2589
+ * @alias module:Processor.blobToDataURL
2590
+ * @see 参考 {@link https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader/readAsDataURL|FileReader.readAsDataURL()}
2591
+ * @since 4.1.0
2592
+ * @ignore
2593
+ * @deprecated 请使用 `fileReader` 方法
2594
+ * @param {Blob} blob Blob 或 File 对象
2595
+ * @returns {Promise<string>} data:URL 格式的 Base64 字符串。
2596
+ * @example
2597
+ * const aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // 一个包含DOMString的数组
2598
+ * const htmlBlob = new Blob(aFileParts, { type: 'text/html' }); // 得到 blob
2599
+ *
2600
+ * blobToDataURL(htmlBlob).then(data=>{
2601
+ * console.log(data); // data:text/html;base64,PGEgaWQ9ImEiPjxiIGlkPSJiIj5oZXkhPC9iPjwvYT4=
2602
+ * });
2603
+ *
2604
+ * const textBlob = new Blob(aFileParts, { type: 'text/plain' });
2605
+ *
2606
+ * blobToDataURL(textBlob).then(data=>{
2607
+ * console.log(data); // data:text/plain;base64,PGEgaWQ9ImEiPjxiIGlkPSJiIj5oZXkhPC9iPjwvYT4=
2608
+ * });
2609
+ */
2610
+ function blobToDataURL(blob) {
2611
+ return fileReader(blob);
2612
+ }
2613
+
2529
2614
  /**
2530
2615
  * 将 DataURL 转为 Blob 对象
2531
2616
  *
@@ -2540,17 +2625,18 @@
2540
2625
  * dataURLToBlob(dataurl); // Blob {size: 32, type: 'text/html'}
2541
2626
  */
2542
2627
  function dataURLToBlob(dataurl) {
2543
- var arr = dataurl.split(',');
2544
- // @ts-ignore
2545
- var mime = arr[0].match(/:(.*?);/)[1];
2546
- var bstr = atob(arr[1]);
2628
+ var parts = dataurl.split(',');
2629
+ var meta = parts[0].substring(5).split(';');
2630
+ var type = meta[0];
2631
+ var decoder = meta.indexOf('base64') !== -1 ? atob : decodeURIComponent;
2632
+ var bstr = decoder(parts[1]);
2547
2633
  var n = bstr.length;
2548
2634
  var u8arr = new Uint8Array(n);
2549
2635
  while (n--) {
2550
2636
  u8arr[n] = bstr.charCodeAt(n);
2551
2637
  }
2552
2638
  return new Blob([u8arr], {
2553
- type: mime
2639
+ type: type
2554
2640
  });
2555
2641
  }
2556
2642
 
@@ -2584,11 +2670,34 @@
2584
2670
  return "data:".concat(mimetype).concat(base64 ? ';base64' : '', ",").concat(data);
2585
2671
  }
2586
2672
 
2587
- // TODO: 函数重载,类型参照 Date
2673
+ /**
2674
+ * @overload
2675
+ * @return {Date}
2676
+ */
2677
+
2678
+ /**
2679
+ * @overload
2680
+ * @param {number | string | Date} value Unix时间戳、时间戳字符串 dateString 、Date 日期对象
2681
+ * @return {Date}
2682
+ */
2683
+
2684
+ /**
2685
+ * @overload
2686
+ * @param {number} year 表示年份的整数值。0 到 99 会被映射至 1900 年至 1999 年,其他值代表实际年份。
2687
+ * @param {number} monthIndex 表示月份的整数值,从 0(1 月)到 11(12 月)。
2688
+ * @param {number} [date] 表示一个月中的第几天的整数值,从 1 开始。默认值为 1。
2689
+ * @param {number} [hours] 表示一天中的小时数的整数值 (24 小时制)。默认值为 0(午夜)。
2690
+ * @param {number} [minutes] 表示一个完整时间(如 01:10:00)中的分钟部分的整数值。默认值为 0。
2691
+ * @param {number} [seconds] 表示一个完整时间(如 01:10:00)中的秒部分的整数值。默认值为 0。
2692
+ * @param {number} [ms] 表示一个完整时间的毫秒部分的整数值。默认值为 0。
2693
+ * @return {Date}
2694
+ */
2588
2695
 
2589
2696
  /**
2590
- * 创建一个 Date 实例日期对象,同 new Date() 。<br/>
2591
- * 规避了苹果设备浏览器不支持部分格式(YYYY-MM-DD HH-mm 或 YYYY.MM.DD)。
2697
+ * 创建一个 Date 实例日期对象,同 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date#%E5%8F%82%E6%95%B0">new Date()</a> <br/><br/>
2698
+ *
2699
+ * 规避了苹果设备浏览器不支持部分格式(例如,YYYY-MM-DD HH-mm 或 YYYY.MM.DD)。<br/>
2700
+ * 如果参数为 undefined 正常返回 Date 。
2592
2701
  *
2593
2702
  * @static
2594
2703
  * @alias module:Processor.safeDate
@@ -2605,8 +2714,6 @@
2605
2714
  * safeDate('2022.1.1 11:11'); // Sat Jan 01 2022 11:11:00 GMT+0800 (中国标准时间)
2606
2715
  * safeDate(99, 1); // Mon Feb 01 1999 00:00:00 GMT+0800 (中国标准时间)
2607
2716
  * safeDate(1646711233171); // Tue Mar 08 2022 11:47:13 GMT+0800 (中国标准时间)
2608
- *
2609
- *
2610
2717
  */
2611
2718
  function safeDate(value) {
2612
2719
  var safeValue = typeof value === 'string' ? value.replace(/[\\.-]/g, '/') : value;
@@ -2617,9 +2724,7 @@
2617
2724
  // @ts-ignore
2618
2725
  return _construct(Date, [safeValue].concat(args));
2619
2726
  }
2620
-
2621
- // @ts-ignore
2622
- return isNil(safeValue) ? new Date() : new Date(safeValue);
2727
+ return typeof safeValue === 'undefined' ? new Date() : new Date(safeValue);
2623
2728
  }
2624
2729
 
2625
2730
  /**
@@ -2896,29 +3001,150 @@
2896
3001
  }
2897
3002
 
2898
3003
  /**
2899
- * 等待时间返回 Promise 。常用于异步方法中延时。
2900
- *
3004
+ * @typedef {XMLHttpRequest['onloadstart']} XMLHttpRequestEvent XMLHttpRequest 事件对象
3005
+ */
3006
+
3007
+ /**
3008
+ * @see {@link https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
3009
+ * @typedef {Object} AjaxOptions ajax配置项
3010
+ * @property {string} [method="get"] 创建请求时使用的方法
3011
+ * @property {Document | XMLHttpRequestBodyInit | null} [data=null] 请求体被发送的数据
3012
+ * @property {Object.<string, string>} [headers] 自定义请求头
3013
+ * @property {XMLHttpRequestResponseType} [responseType] 响应类型
3014
+ * @property {number} [timeout] 请求超时的毫秒数
3015
+ * @property {boolean} [withCredentials=false] 跨域请求时是否需要使用凭证
3016
+ * @property {boolean} [async=true] 是否异步执行操作
3017
+ * @property {string|null} [user=null] 用户名,用于认证用途
3018
+ * @property {string|null} [password=null] 密码,用于认证用途
3019
+ * @property {XMLHttpRequestEvent} [onLoadStart] 接收到响应数据时触发
3020
+ * @property {XMLHttpRequestEvent} [onProgress] 请求接收到更多数据时,周期性地触发
3021
+ * @property {XMLHttpRequestEvent} [onAbort] 当 request 被停止时触发,例如当程序调用 XMLHttpRequest.abort() 时
3022
+ * @property {XMLHttpRequestEvent} [onTimeout] 在预设时间内没有接收到响应时触发
3023
+ * @property {XMLHttpRequestEvent} [onError] 当 request 遭遇错误时触发
3024
+ * @property {XMLHttpRequestEvent} [onLoad] 请求成功完成时触发
3025
+ * @property {XMLHttpRequestEvent} [onLoadEnd] 请求结束时触发,无论请求成功 (load) 还是失败 (abort 或 error)
3026
+ */
3027
+
3028
+ /**
3029
+ * 请求<br/><br/>
3030
+ *
3031
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端。</em>
3032
+ *
2901
3033
  * @static
2902
- * @alias module:Other.waitTime
2903
- * @since 4.2.0
2904
- * @param {number} [time=1000] 延时时间,单位毫秒
2905
- * @returns {Promise<void>}
3034
+ * @alias module:Other.ajax
3035
+ * @since 4.16.0
3036
+ * @see {@link https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
3037
+ * @param {string} url 地址
3038
+ * @param {AjaxOptions} [options] 配置项
3039
+ * @returns {Promise<ProgressEvent<EventTarget>>}
2906
3040
  * @example
2907
- *
2908
- * const test = async ()=>{
2909
- * await waitTime();
2910
- * // do something
2911
- * }
2912
- *
2913
- * waitTime(500).then(()=>{
3041
+ * ajax('/somefile').then(res=>{
2914
3042
  * // do something
2915
3043
  * });
2916
3044
  *
3045
+ * ajax('/api', { method: 'post' }).then(res=>{
3046
+ * // do something
3047
+ * });
2917
3048
  */
2918
- function waitTime() {
2919
- var time = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1000;
2920
- return new Promise(function (resolve) {
2921
- setTimeout(resolve, time);
3049
+ function ajax(url, options) {
3050
+ var _ref = options || {},
3051
+ _ref$method = _ref.method,
3052
+ method = _ref$method === void 0 ? 'get' : _ref$method,
3053
+ _ref$data = _ref.data,
3054
+ data = _ref$data === void 0 ? null : _ref$data,
3055
+ timeout = _ref.timeout,
3056
+ headers = _ref.headers,
3057
+ _ref$withCredentials = _ref.withCredentials,
3058
+ withCredentials = _ref$withCredentials === void 0 ? false : _ref$withCredentials,
3059
+ _ref$async = _ref.async,
3060
+ async = _ref$async === void 0 ? true : _ref$async,
3061
+ _ref$user = _ref.user,
3062
+ user = _ref$user === void 0 ? null : _ref$user,
3063
+ _ref$password = _ref.password,
3064
+ password = _ref$password === void 0 ? null : _ref$password,
3065
+ responseType = _ref.responseType,
3066
+ onAbort = _ref.onAbort,
3067
+ onError = _ref.onError,
3068
+ onLoad = _ref.onLoad,
3069
+ onLoadEnd = _ref.onLoadEnd,
3070
+ onLoadStart = _ref.onLoadStart,
3071
+ onProgress = _ref.onProgress,
3072
+ onTimeout = _ref.onTimeout;
3073
+ return new Promise(function (resolve, reject) {
3074
+ var xhr = new XMLHttpRequest();
3075
+ xhr.open(method.toLowerCase(), url, async, user, password);
3076
+
3077
+ // 设置请求超时
3078
+ if (typeof timeout === 'number' && timeout > 0) {
3079
+ xhr.timeout = timeout;
3080
+ }
3081
+
3082
+ // 跨域请求时是否需要使用凭证
3083
+ xhr.withCredentials = withCredentials;
3084
+
3085
+ // 设置响应类型
3086
+ if (responseType) {
3087
+ xhr.responseType = responseType;
3088
+ }
3089
+
3090
+ // 设置请求头
3091
+ if (_typeof(headers) === 'object') {
3092
+ Object.keys(headers).map(function (item) {
3093
+ xhr.setRequestHeader(item, headers[item]);
3094
+ });
3095
+ }
3096
+
3097
+ /**
3098
+ * 请求成功异步调用
3099
+ * @param {XMLHttpRequestEvent} [cb] 回调方法
3100
+ */
3101
+ var wrapSuccess = function wrapSuccess(cb) {
3102
+ /**
3103
+ * 内部方法
3104
+ * @param {ProgressEvent<EventTarget>} e 事件对象
3105
+ */
3106
+ return function (e) {
3107
+ resolve(e);
3108
+ cb === null || cb === void 0 ? void 0 : cb.call(xhr, e);
3109
+ };
3110
+ };
3111
+
3112
+ /**
3113
+ * 请求失败(中断/超时/失败)处理
3114
+ * @param {XMLHttpRequestEvent} [cb] 回调方法
3115
+ */
3116
+ var wrapError = function wrapError(cb) {
3117
+ /**
3118
+ * 内部方法
3119
+ * @param {ProgressEvent<EventTarget>} e 事件对象
3120
+ */
3121
+ return function (e) {
3122
+ reject(e);
3123
+ cb === null || cb === void 0 ? void 0 : cb.call(xhr, e);
3124
+ };
3125
+ };
3126
+
3127
+ // 事件处理
3128
+ /**@type {Object.<keyof XMLHttpRequestEventTargetEventMap, XMLHttpRequestEvent | undefined>} */
3129
+ var events = {
3130
+ loadstart: onLoadStart,
3131
+ progress: onProgress,
3132
+ abort: wrapError(onAbort),
3133
+ timeout: wrapError(onTimeout),
3134
+ error: wrapError(onError),
3135
+ load: wrapSuccess(onLoad),
3136
+ loadend: onLoadEnd
3137
+ };
3138
+ /**@type {(keyof XMLHttpRequestEventTargetEventMap)[]} */
3139
+ // @ts-ignore
3140
+ var eventNames = Object.keys(events);
3141
+ eventNames.map(function (item) {
3142
+ var func = events[item];
3143
+ if (func) {
3144
+ xhr.addEventListener(item, func);
3145
+ }
3146
+ });
3147
+ xhr.send(data);
2922
3148
  });
2923
3149
  }
2924
3150
 
@@ -2975,6 +3201,154 @@
2975
3201
  return pos;
2976
3202
  }
2977
3203
 
3204
+ /**
3205
+ * 下载文件
3206
+ *
3207
+ * @param {string} blobUrl blob 地址
3208
+ * @param {string} [fileName] 文件名称
3209
+ */
3210
+ function saver(blobUrl, fileName) {
3211
+ var anchor = document.createElement('a');
3212
+ // anchor.href = decodeURIComponent(blobUrl);
3213
+ anchor.href = blobUrl;
3214
+ anchor.style.display = 'none';
3215
+ anchor.setAttribute('download', fileName || '');
3216
+
3217
+ /**
3218
+ * 处理点击事件,防止事件冒泡到 body/html 的点击事件。
3219
+ *
3220
+ * @param {MouseEvent} e 鼠标事件对象
3221
+ */
3222
+ function handleClick(e) {
3223
+ e.stopPropagation();
3224
+ anchor.removeEventListener('click', handleClick);
3225
+ }
3226
+ anchor.addEventListener('click', handleClick);
3227
+ document.body.appendChild(anchor);
3228
+ anchor.click();
3229
+ document.body.removeChild(anchor);
3230
+ }
3231
+
3232
+ /**
3233
+ * @typedef {import('./ajax.js').AjaxOptions} AjaxOptions ajax 配置项
3234
+ */
3235
+
3236
+ /**
3237
+ * @callback TransformRequest
3238
+ * @param {AjaxOptions} options ajax 配置项
3239
+ * @returns {AjaxOptions}
3240
+ */
3241
+
3242
+ /**
3243
+ * @callback TransformResponse
3244
+ * @param {Blob} res 响应的Blob对象。如果你通过 transformRequest 修改了 responseType ,该参数将是该类型响应值。
3245
+ * @returns {Blob}
3246
+ */
3247
+
3248
+ /**
3249
+ * @typedef {Object} DownloadOptions 下载配置项
3250
+ * @property {string} [options.fileName] 文件名称
3251
+ * @property {string} [options.type] MIME 类型
3252
+ * @property {'url'|'text'} [options.dataType] 手动设置数据类型,默认会根据传入的数据判断类型,主要是为了区分 url 和 text 。<br/>如果你要下载的文本是 url ,请设置 'text' ;如果你要下载的 url 是绝对/相对路径,请设置 'url' 。
3253
+ * @property {TransformRequest} [options.transformRequest] 请求前触发,XHR 对象或配置调整
3254
+ * @property {TransformResponse} [options.transformResponse] 请求成功后触发,在传递给 then/catch 前,允许修改响应数据
3255
+ */
3256
+
3257
+ /**
3258
+ * 下载<br/><br/>
3259
+ *
3260
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端,兼容 IE10+ 和现代浏览器。</em>
3261
+ *
3262
+ * @static
3263
+ * @alias module:Other.download
3264
+ * @since 4.16.0
3265
+ * @see {@link https://zh.wikipedia.org/wiki/多用途互聯網郵件擴展|多用途互联网邮件扩展}
3266
+ * @param {string|Blob|ArrayBuffer|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|BigInt64Array|BigUint64Array} data 字符串、blob数据或url地址
3267
+ * @param {string|DownloadOptions} [options] 文件名称 或 配置项
3268
+ * @returns {Promise<void>}
3269
+ * @example
3270
+ * // 文本
3271
+ * download('hello world', 'text.txt');
3272
+ *
3273
+ * // 远程文件
3274
+ * download('/xxx.jpg', { dataType: 'url' });
3275
+ *
3276
+ * // blob文件
3277
+ * download(new Blob(['hello world']), 'text.txt');
3278
+ *
3279
+ */
3280
+ function download(data, options) {
3281
+ var config = _typeof(options) === 'object' ? options : {};
3282
+ if (typeof options === 'string') {
3283
+ config.fileName = options;
3284
+ }
3285
+ var fileName = config.fileName,
3286
+ type = config.type,
3287
+ dataType = config.dataType,
3288
+ transformRequest = config.transformRequest,
3289
+ transformResponse = config.transformResponse;
3290
+
3291
+ /** @type {Blob|undefined} */
3292
+ var payload;
3293
+
3294
+ // dataURLs、blob url、url、string
3295
+ if (typeof data === 'string') {
3296
+ if (!dataType && /^blob:.*?\/.*/.test(data)) {
3297
+ // blob url
3298
+ saver(data, fileName);
3299
+ return Promise.resolve();
3300
+ } else if (!dataType && /^data:([\w+-]+\/[\w+.-]+)?[,;]/.test(data)) {
3301
+ // dataURLs
3302
+ payload = dataURLToBlob(data);
3303
+ } else if (dataType === 'url' || !dataType && isUrl(data)) {
3304
+ // url
3305
+ /** @type {AjaxOptions} */
3306
+ var defaultAjaxOptions = {
3307
+ responseType: 'blob'
3308
+ };
3309
+ // 请求前配置调整
3310
+ var ajaxOptions = typeof transformRequest === 'function' ? transformRequest(defaultAjaxOptions) : defaultAjaxOptions;
3311
+ return ajax(data, ajaxOptions).then(function (e) {
3312
+ /** @type {Blob} */
3313
+ // @ts-ignore
3314
+ // 响应结果调整
3315
+ var res = typeof transformResponse === 'function' ? transformResponse(e.target.response) : e.target.response;
3316
+ var currentFileName = fileName || data.split("?")[0].split("#")[0].split("/").pop();
3317
+ return download(res, {
3318
+ fileName: currentFileName,
3319
+ type: type || (isBlob(res) ? res.type : undefined)
3320
+ });
3321
+ });
3322
+ } else {
3323
+ // string
3324
+ payload = new Blob([data], {
3325
+ type: type || 'text/plain'
3326
+ });
3327
+ }
3328
+ } else if (isBlob(data)) {
3329
+ // @ts-ignore
3330
+ payload = data;
3331
+ }
3332
+
3333
+ // html、TypedArray
3334
+ if (!(payload instanceof Blob)) {
3335
+ payload = new Blob([data], {
3336
+ type: type
3337
+ });
3338
+ }
3339
+
3340
+ // @ts-ignore
3341
+ if (navigator.msSaveBlob) {
3342
+ // @ts-ignore
3343
+ navigator.msSaveBlob(payload, fileName || 'download');
3344
+ } else {
3345
+ var url = URL.createObjectURL(payload);
3346
+ saver(url, fileName);
3347
+ URL.revokeObjectURL(url);
3348
+ }
3349
+ return Promise.resolve();
3350
+ }
3351
+
2978
3352
  var numberChars = '0123456789';
2979
3353
  var letterChars = 'abcdefghijklmnopqrstuvwxyz';
2980
3354
  var defaultChars = numberChars + letterChars + letterChars.toUpperCase();
@@ -3053,6 +3427,33 @@
3053
3427
  return len;
3054
3428
  }
3055
3429
 
3430
+ /**
3431
+ * 等待时间返回 Promise 。常用于异步方法中延时。
3432
+ *
3433
+ * @static
3434
+ * @alias module:Other.waitTime
3435
+ * @since 4.2.0
3436
+ * @param {number} [time=1000] 延时时间,单位毫秒
3437
+ * @returns {Promise<void>}
3438
+ * @example
3439
+ *
3440
+ * const test = async ()=>{
3441
+ * await waitTime();
3442
+ * // do something
3443
+ * }
3444
+ *
3445
+ * waitTime(500).then(()=>{
3446
+ * // do something
3447
+ * });
3448
+ *
3449
+ */
3450
+ function waitTime() {
3451
+ var time = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1000;
3452
+ return new Promise(function (resolve) {
3453
+ setTimeout(resolve, time);
3454
+ });
3455
+ }
3456
+
3056
3457
  /**
3057
3458
  * 转换字段名,返回一个转换字段后的值,不改变原值。
3058
3459
  *
@@ -3066,7 +3467,7 @@
3066
3467
  * @param {F} fieldNames 字段名映射
3067
3468
  * @param {C} [childrenField] 子级数据字段名
3068
3469
  * @param {'spread'|'self'} [nodeAssign='spread'] 节点赋值方式。spread表示使用展开运算符创建新值,self表示使用自身对象。
3069
- * @returns {import('./transformFieldNames.type.js').TransformFieldNames<D, F, C>}
3470
+ * @returns {import('./interface.type.js').TransformFieldNames<D, F, C>}
3070
3471
  * @example
3071
3472
  *
3072
3473
  * const options = [{code: '1', name: 'one'},{code:'2', name:'two'}];
@@ -3586,11 +3987,14 @@
3586
3987
  return internalFindTreeSelect(tree, predicate, childrenField);
3587
3988
  }
3588
3989
 
3990
+ exports.ajax = ajax;
3589
3991
  exports.blobToDataURL = blobToDataURL;
3590
3992
  exports.bytesToSize = bytesToSize;
3591
3993
  exports.calculateCursorPosition = calculateCursorPosition;
3592
3994
  exports.dataURLToBlob = dataURLToBlob;
3593
3995
  exports.divide = divide;
3996
+ exports.download = download;
3997
+ exports.fileReader = fileReader;
3594
3998
  exports.filterTree = filterTree;
3595
3999
  exports.findTreeNode = findTreeNode;
3596
4000
  exports.findTreeNodes = findTreeNodes;