util-helpers 4.15.3 → 4.16.1

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 (102) hide show
  1. package/README.md +6 -5
  2. package/dist/util-helpers.js +491 -73
  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 +9 -13
  8. package/esm/calculateCursorPosition.js +2 -2
  9. package/esm/dataURLToBlob.js +7 -6
  10. package/esm/download.js +171 -0
  11. package/esm/fileReader.js +67 -0
  12. package/esm/index.js +6 -3
  13. package/esm/interface.doc.js +125 -0
  14. package/esm/isBankCard.js +1 -1
  15. package/esm/isBusinessLicense.js +1 -1
  16. package/esm/isChinese.js +3 -3
  17. package/esm/isHMCard.js +1 -1
  18. package/esm/isIdCard.js +2 -2
  19. package/esm/isPassport.js +1 -1
  20. package/esm/isPassword.js +2 -2
  21. package/esm/isSocialCreditCode.js +1 -1
  22. package/esm/isSwiftCode.js +1 -1
  23. package/esm/isTWCard.js +1 -1
  24. package/esm/isUrl.js +1 -1
  25. package/esm/isVehicle.js +1 -1
  26. package/esm/normalizeString.js +1 -1
  27. package/esm/numberToChinese.js +3 -2
  28. package/esm/parseIdCard.js +2 -2
  29. package/esm/safeDate.js +27 -10
  30. package/esm/setDataURLPrefix.js +2 -2
  31. package/esm/transformFieldNames.js +2 -3
  32. package/esm/utils/config.js +1 -1
  33. package/esm/utils/type/index.js +3 -1
  34. package/esm/utils/type/isArrayBuffer.js +25 -0
  35. package/esm/utils/type/isBlob.js +27 -0
  36. package/esm/validatePassword.js +1 -1
  37. package/lib/ajax.js +156 -0
  38. package/lib/blobToDataURL.js +9 -13
  39. package/lib/calculateCursorPosition.js +2 -2
  40. package/lib/dataURLToBlob.js +7 -6
  41. package/lib/download.js +176 -0
  42. package/lib/fileReader.js +74 -0
  43. package/lib/index.js +22 -1
  44. package/lib/interface.doc.js +127 -0
  45. package/lib/isBankCard.js +1 -1
  46. package/lib/isBusinessLicense.js +1 -1
  47. package/lib/isChinese.js +3 -3
  48. package/lib/isHMCard.js +1 -1
  49. package/lib/isIdCard.js +2 -2
  50. package/lib/isPassport.js +1 -1
  51. package/lib/isPassword.js +2 -2
  52. package/lib/isSocialCreditCode.js +1 -1
  53. package/lib/isSwiftCode.js +1 -1
  54. package/lib/isTWCard.js +1 -1
  55. package/lib/isUrl.js +1 -1
  56. package/lib/isVehicle.js +1 -1
  57. package/lib/normalizeString.js +1 -1
  58. package/lib/numberToChinese.js +3 -2
  59. package/lib/parseIdCard.js +2 -2
  60. package/lib/safeDate.js +28 -11
  61. package/lib/setDataURLPrefix.js +2 -2
  62. package/lib/transformFieldNames.js +1 -1
  63. package/lib/utils/config.js +1 -1
  64. package/lib/utils/type/index.js +14 -0
  65. package/lib/utils/type/isArrayBuffer.js +32 -0
  66. package/lib/utils/type/isBlob.js +34 -0
  67. package/lib/validatePassword.js +1 -1
  68. package/package.json +2 -2
  69. package/types/ajax.d.ts +121 -0
  70. package/types/blobToDataURL.d.ts +6 -2
  71. package/types/calculateCursorPosition.d.ts +2 -2
  72. package/types/dataURLToBlob.d.ts +1 -1
  73. package/types/download.d.ts +78 -0
  74. package/types/fileReader.d.ts +3 -0
  75. package/types/index.d.ts +4 -1
  76. package/types/isBankCard.d.ts +1 -1
  77. package/types/isBusinessLicense.d.ts +1 -1
  78. package/types/isChinese.d.ts +3 -3
  79. package/types/isHMCard.d.ts +1 -1
  80. package/types/isIdCard.d.ts +2 -2
  81. package/types/isPassport.d.ts +1 -1
  82. package/types/isPassword.d.ts +2 -2
  83. package/types/isSocialCreditCode.d.ts +1 -1
  84. package/types/isSwiftCode.d.ts +1 -1
  85. package/types/isTWCard.d.ts +1 -1
  86. package/types/isUrl.d.ts +1 -1
  87. package/types/isVehicle.d.ts +1 -1
  88. package/types/normalizeString.d.ts +1 -1
  89. package/types/numberToChinese.d.ts +3 -2
  90. package/types/parseIdCard.d.ts +3 -3
  91. package/types/safeDate.d.ts +3 -23
  92. package/types/setDataURLPrefix.d.ts +2 -2
  93. package/types/transformFieldNames.d.ts +2 -2
  94. package/types/utils/type/index.d.ts +21 -19
  95. package/types/utils/type/isArrayBuffer.d.ts +21 -0
  96. package/types/utils/type/isBlob.d.ts +23 -0
  97. package/types/validatePassword.d.ts +1 -1
  98. package/esm/transformFieldNames.doc.js +0 -35
  99. package/lib/transformFieldNames.doc.js +0 -42
  100. /package/esm/{transformFieldNames.type.js → interface.type.js} +0 -0
  101. /package/lib/{transformFieldNames.type.js → interface.type.js} +0 -0
  102. /package/types/{transformFieldNames.type.d.ts → interface.type.d.ts} +0 -0
package/esm/ajax.js ADDED
@@ -0,0 +1,149 @@
1
+ import _typeof from "@babel/runtime/helpers/typeof";
2
+ /**
3
+ * @typedef {XMLHttpRequest['onloadstart']} XMLHttpRequestEvent XMLHttpRequest 事件对象
4
+ */
5
+
6
+ /**
7
+ * @see {@link https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
8
+ * @typedef {Object} AjaxOptions ajax配置项
9
+ * @property {string} [method="get"] 创建请求时使用的方法
10
+ * @property {Document | XMLHttpRequestBodyInit | null} [data=null] 请求体被发送的数据
11
+ * @property {Object.<string, string>} [headers] 自定义请求头
12
+ * @property {XMLHttpRequestResponseType} [responseType] 响应类型
13
+ * @property {number} [timeout] 请求超时的毫秒数
14
+ * @property {boolean} [withCredentials=false] 跨域请求时是否需要使用凭证
15
+ * @property {boolean} [async=true] 是否异步执行操作
16
+ * @property {string|null} [user=null] 用户名,用于认证用途
17
+ * @property {string|null} [password=null] 密码,用于认证用途
18
+ * @property {XMLHttpRequestEvent} [onLoadStart] 接收到响应数据时触发
19
+ * @property {XMLHttpRequestEvent} [onProgress] 请求接收到更多数据时,周期性地触发
20
+ * @property {XMLHttpRequestEvent} [onAbort] 当 request 被停止时触发,例如当程序调用 XMLHttpRequest.abort() 时
21
+ * @property {XMLHttpRequestEvent} [onTimeout] 在预设时间内没有接收到响应时触发
22
+ * @property {XMLHttpRequestEvent} [onError] 当 request 遭遇错误时触发
23
+ * @property {XMLHttpRequestEvent} [onLoad] 请求成功完成时触发
24
+ * @property {XMLHttpRequestEvent} [onLoadEnd] 请求结束时触发,无论请求成功 (load) 还是失败 (abort 或 error)
25
+ */
26
+
27
+ /**
28
+ * 请求<br/><br/>
29
+ *
30
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端。</em>
31
+ *
32
+ * @static
33
+ * @alias module:Other.ajax
34
+ * @since 4.16.0
35
+ * @see {@link https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
36
+ * @param {string} url 地址
37
+ * @param {AjaxOptions} [options] 配置项
38
+ * @returns {Promise<ProgressEvent<EventTarget>>}
39
+ * @example
40
+ * ajax('/somefile').then(res=>{
41
+ * // do something
42
+ * });
43
+ *
44
+ * ajax('/api', { method: 'post' }).then(res=>{
45
+ * // do something
46
+ * });
47
+ */
48
+ function ajax(url, options) {
49
+ var _ref = options || {},
50
+ _ref$method = _ref.method,
51
+ method = _ref$method === void 0 ? 'get' : _ref$method,
52
+ _ref$data = _ref.data,
53
+ data = _ref$data === void 0 ? null : _ref$data,
54
+ timeout = _ref.timeout,
55
+ headers = _ref.headers,
56
+ _ref$withCredentials = _ref.withCredentials,
57
+ withCredentials = _ref$withCredentials === void 0 ? false : _ref$withCredentials,
58
+ _ref$async = _ref.async,
59
+ async = _ref$async === void 0 ? true : _ref$async,
60
+ _ref$user = _ref.user,
61
+ user = _ref$user === void 0 ? null : _ref$user,
62
+ _ref$password = _ref.password,
63
+ password = _ref$password === void 0 ? null : _ref$password,
64
+ responseType = _ref.responseType,
65
+ onAbort = _ref.onAbort,
66
+ onError = _ref.onError,
67
+ onLoad = _ref.onLoad,
68
+ onLoadEnd = _ref.onLoadEnd,
69
+ onLoadStart = _ref.onLoadStart,
70
+ onProgress = _ref.onProgress,
71
+ onTimeout = _ref.onTimeout;
72
+ return new Promise(function (resolve, reject) {
73
+ var xhr = new XMLHttpRequest();
74
+ xhr.open(method.toLowerCase(), url, async, user, password);
75
+
76
+ // 设置请求超时
77
+ if (typeof timeout === 'number' && timeout > 0) {
78
+ xhr.timeout = timeout;
79
+ }
80
+
81
+ // 跨域请求时是否需要使用凭证
82
+ xhr.withCredentials = withCredentials;
83
+
84
+ // 设置响应类型
85
+ if (responseType) {
86
+ xhr.responseType = responseType;
87
+ }
88
+
89
+ // 设置请求头
90
+ if (_typeof(headers) === 'object') {
91
+ Object.keys(headers).map(function (item) {
92
+ xhr.setRequestHeader(item, headers[item]);
93
+ });
94
+ }
95
+
96
+ /**
97
+ * 请求成功异步调用
98
+ * @param {XMLHttpRequestEvent} [cb] 回调方法
99
+ */
100
+ var wrapSuccess = function wrapSuccess(cb) {
101
+ /**
102
+ * 内部方法
103
+ * @param {ProgressEvent<EventTarget>} e 事件对象
104
+ */
105
+ return function (e) {
106
+ resolve(e);
107
+ cb === null || cb === void 0 ? void 0 : cb.call(xhr, e);
108
+ };
109
+ };
110
+
111
+ /**
112
+ * 请求失败(中断/超时/失败)处理
113
+ * @param {XMLHttpRequestEvent} [cb] 回调方法
114
+ */
115
+ var wrapError = function wrapError(cb) {
116
+ /**
117
+ * 内部方法
118
+ * @param {ProgressEvent<EventTarget>} e 事件对象
119
+ */
120
+ return function (e) {
121
+ reject(e);
122
+ cb === null || cb === void 0 ? void 0 : cb.call(xhr, e);
123
+ };
124
+ };
125
+
126
+ // 事件处理
127
+ /**@type {Object.<keyof XMLHttpRequestEventTargetEventMap, XMLHttpRequestEvent | undefined>} */
128
+ var events = {
129
+ loadstart: onLoadStart,
130
+ progress: onProgress,
131
+ abort: wrapError(onAbort),
132
+ timeout: wrapError(onTimeout),
133
+ error: wrapError(onError),
134
+ load: wrapSuccess(onLoad),
135
+ loadend: onLoadEnd
136
+ };
137
+ /**@type {(keyof XMLHttpRequestEventTargetEventMap)[]} */
138
+ // @ts-ignore
139
+ var eventNames = Object.keys(events);
140
+ eventNames.map(function (item) {
141
+ var func = events[item];
142
+ if (func) {
143
+ xhr.addEventListener(item, func);
144
+ }
145
+ });
146
+ xhr.send(data);
147
+ });
148
+ }
149
+ export default ajax;
@@ -2,13 +2,19 @@
2
2
  // 方法1:将file或者blob类型文件转成base64数据,再作为src赋值给img标签
3
3
  // 方法2:使用 window.URL.createObjectURL(blob) 为blob、file 创建一个指向该参数对象的URL
4
4
 
5
+ import fileReader from "./fileReader";
6
+
5
7
  /**
6
- * 将 Blob 或 File 对象转成 data:URL 格式的 Base64 字符串。
8
+ * 将 Blob 或 File 对象转成 data:URL 格式的 Base64 字符串<br/><br/>
9
+ *
10
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端。</em>
7
11
  *
12
+ * @ignore
8
13
  * @static
9
14
  * @alias module:Processor.blobToDataURL
10
- * @see 参考 {@link https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader/readAsDataURL|FileReader.readAsDataURL()}
11
15
  * @since 4.1.0
16
+ * @see {@link https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader/readAsDataURL|FileReader.readAsDataURL()}
17
+ * @deprecated 请使用 `fileReader` 方法
12
18
  * @param {Blob} blob Blob 或 File 对象
13
19
  * @returns {Promise<string>} data:URL 格式的 Base64 字符串。
14
20
  * @example
@@ -26,16 +32,6 @@
26
32
  * });
27
33
  */
28
34
  function blobToDataURL(blob) {
29
- return new Promise(function (resolve, reject) {
30
- var reader = new FileReader();
31
- reader.readAsDataURL(blob);
32
- // @ts-ignore
33
- reader.onload = function () {
34
- return resolve(reader.result);
35
- };
36
- reader.onerror = function (error) {
37
- return reject(error);
38
- };
39
- });
35
+ return fileReader(blob);
40
36
  }
41
37
  export default blobToDataURL;
@@ -8,8 +8,8 @@ import normalizeString from './normalizeString';
8
8
  * @static
9
9
  * @alias module:Other.calculateCursorPosition
10
10
  * @since 4.6.0
11
- * @see h5示例 {@link https://2950v9.csb.app/|点击查看}
12
- * @see react示例 {@link https://33ccy9.csb.app/|点击查看}
11
+ * @see {@link https://2950v9.csb.app/|h5示例}
12
+ * @see {@link https://33ccy9.csb.app/|react示例}
13
13
  * @param {number} prevPos 赋值前的光标位置,onChange/onInput的光标位置 e.target.selectionEnd
14
14
  * @param {string} prevCtrlValue 上一个格式化后的值
15
15
  * @param {string} rawValue 当前输入原值
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * @static
5
5
  * @alias module:Processor.dataURLToBlob
6
- * @see 参考 {@link https://developer.mozilla.org/zh-CN/docs/Glossary/Base64|Base64}
7
6
  * @since 4.1.0
7
+ * @see {@link https://developer.mozilla.org/zh-CN/docs/Glossary/Base64|Base64}
8
8
  * @param {string} dataurl data: 协议的URL
9
9
  * @returns {Blob} Blob 对象
10
10
  * @example
@@ -12,17 +12,18 @@
12
12
  * dataURLToBlob(dataurl); // Blob {size: 32, type: 'text/html'}
13
13
  */
14
14
  function dataURLToBlob(dataurl) {
15
- var arr = dataurl.split(',');
16
- // @ts-ignore
17
- var mime = arr[0].match(/:(.*?);/)[1];
18
- var bstr = atob(arr[1]);
15
+ var parts = dataurl.split(',');
16
+ var meta = parts[0].substring(5).split(';');
17
+ var type = meta[0];
18
+ var decoder = meta.indexOf('base64') !== -1 ? atob : decodeURIComponent;
19
+ var bstr = decoder(parts[1]);
19
20
  var n = bstr.length;
20
21
  var u8arr = new Uint8Array(n);
21
22
  while (n--) {
22
23
  u8arr[n] = bstr.charCodeAt(n);
23
24
  }
24
25
  return new Blob([u8arr], {
25
- type: mime
26
+ type: type
26
27
  });
27
28
  }
28
29
  export default dataURLToBlob;
@@ -0,0 +1,171 @@
1
+ import _typeof from "@babel/runtime/helpers/typeof";
2
+ // 如果修改文档,请同步修改 interface.doc.js
3
+
4
+ import dataURLToBlob from "./dataURLToBlob";
5
+ import isUrl from "./isUrl";
6
+ import ajax from "./ajax";
7
+ import { isBlob } from "./utils/type";
8
+ import isPromiseLike from "./isPromiseLike";
9
+
10
+ /**
11
+ * 下载文件
12
+ *
13
+ * @param {string} blobUrl blob 地址
14
+ * @param {string} [fileName] 文件名称
15
+ */
16
+ function saver(blobUrl, fileName) {
17
+ var anchor = document.createElement('a');
18
+ // anchor.href = decodeURIComponent(blobUrl);
19
+ anchor.href = blobUrl;
20
+ anchor.style.display = 'none';
21
+ anchor.setAttribute('download', fileName || '');
22
+
23
+ /**
24
+ * 处理点击事件,防止事件冒泡到 body/html 的点击事件。
25
+ *
26
+ * @param {MouseEvent} e 鼠标事件对象
27
+ */
28
+ function handleClick(e) {
29
+ e.stopPropagation();
30
+ anchor.removeEventListener('click', handleClick);
31
+ }
32
+ anchor.addEventListener('click', handleClick);
33
+ document.body.appendChild(anchor);
34
+ anchor.click();
35
+ document.body.removeChild(anchor);
36
+ }
37
+
38
+ /**
39
+ * @typedef {import('./ajax.js').AjaxOptions} AjaxOptions ajax 配置项
40
+ */
41
+
42
+ /**
43
+ * @callback TransformRequest
44
+ * @param {AjaxOptions} options ajax 配置项
45
+ * @returns {AjaxOptions | Promise<AjaxOptions>}
46
+ */
47
+
48
+ /**
49
+ * @callback TransformResponse
50
+ * @param {Blob} res 响应的Blob对象。如果你通过 transformRequest 修改了 responseType ,该参数将是该类型响应值。
51
+ * @returns {Blob | Promise<Blob>}
52
+ */
53
+
54
+ /**
55
+ * @typedef {Object} DownloadOptions 下载配置项
56
+ * @property {string} [options.fileName] 文件名称
57
+ * @property {string} [options.type] MIME 类型
58
+ * @property {'url'|'text'} [options.dataType] 手动设置数据类型,默认会根据传入的数据判断类型,主要是为了区分 url 和 text 。<br/>如果你要下载的文本是 url ,请设置 'text' ;如果你要下载的 url 是绝对/相对路径,请设置 'url' 。
59
+ * @property {TransformRequest} [options.transformRequest] 请求前触发,XHR 对象或配置调整
60
+ * @property {TransformResponse} [options.transformResponse] 请求成功后触发,在传递给 then/catch 前,允许修改响应数据
61
+ */
62
+
63
+ /**
64
+ * 下载<br/><br/>
65
+ *
66
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端,兼容 IE10+ 和现代浏览器。</em>
67
+ *
68
+ * @static
69
+ * @alias module:Other.download
70
+ * @since 4.16.0
71
+ * @see {@link https://zh.wikipedia.org/wiki/多用途互聯網郵件擴展|MIME}
72
+ * @see {@link https://9ykc9s.csb.app/|在线示例}
73
+ * @param {string|Blob|ArrayBuffer|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|BigInt64Array|BigUint64Array} data 字符串、blob数据或url地址
74
+ * @param {string|DownloadOptions} [options] 文件名称 或 配置项
75
+ * @returns {Promise<void>}
76
+ * @example
77
+ * // 文本
78
+ * download('hello world', 'text.txt');
79
+ *
80
+ * // 远程文件
81
+ * download('/xxx.jpg', { dataType: 'url' });
82
+ *
83
+ * // blob文件
84
+ * download(new Blob(['hello world']), 'text.txt');
85
+ *
86
+ */
87
+ function download(data, options) {
88
+ var config = _typeof(options) === 'object' ? options : {};
89
+ if (typeof options === 'string') {
90
+ config.fileName = options;
91
+ }
92
+ var fileName = config.fileName,
93
+ type = config.type,
94
+ dataType = config.dataType,
95
+ transformRequest = config.transformRequest,
96
+ transformResponse = config.transformResponse;
97
+
98
+ /** @type {Blob|undefined} */
99
+ var payload;
100
+
101
+ // dataURLs、blob url、url、string
102
+ if (typeof data === 'string') {
103
+ if (!dataType && /^blob:.*?\/.*/.test(data)) {
104
+ // blob url
105
+ saver(data, fileName);
106
+ return Promise.resolve();
107
+ } else if (!dataType && /^data:([\w+-]+\/[\w+.-]+)?[,;]/.test(data)) {
108
+ // dataURLs
109
+ payload = dataURLToBlob(data);
110
+ } else if (dataType === 'url' || !dataType && isUrl(data)) {
111
+ // url
112
+ // 包装为异步方法
113
+ /** @type {(opts: AjaxOptions)=>Promise<AjaxOptions>} */
114
+ var asyncTransformRequest = function asyncTransformRequest(opts) {
115
+ // 请求前配置调整
116
+ var tempOptions = typeof transformRequest === 'function' ? transformRequest(opts) : opts;
117
+ // @ts-ignore
118
+ return isPromiseLike(tempOptions) ? tempOptions : Promise.resolve(tempOptions);
119
+ };
120
+ /** @type {(res: Blob)=>Promise<Blob>} */
121
+ var asyncTransformResponse = function asyncTransformResponse(res) {
122
+ var tempRes = typeof transformResponse === 'function' ? transformResponse(res) : res;
123
+ // @ts-ignore
124
+ return isPromiseLike(tempRes) ? tempRes : Promise.resolve(tempRes);
125
+ };
126
+
127
+ // 此处如果使用 async/await 语法糖,编译后的umd代码过大
128
+ return asyncTransformRequest({
129
+ responseType: 'blob'
130
+ }).then(function (ajaxOptions) {
131
+ return ajax(data, ajaxOptions).then(function (e) {
132
+ // @ts-ignore
133
+ return asyncTransformResponse(e.target.response).then(function (res) {
134
+ var currentFileName = fileName || data.split("?")[0].split("#")[0].split("/").pop();
135
+ return download(res, {
136
+ fileName: currentFileName,
137
+ type: type || (isBlob(res) ? res.type : undefined)
138
+ });
139
+ });
140
+ });
141
+ });
142
+ } else {
143
+ // string
144
+ payload = new Blob([data], {
145
+ type: type || 'text/plain'
146
+ });
147
+ }
148
+ } else if (isBlob(data)) {
149
+ // @ts-ignore
150
+ payload = data;
151
+ }
152
+
153
+ // html、TypedArray
154
+ if (!(payload instanceof Blob)) {
155
+ payload = new Blob([data], {
156
+ type: type
157
+ });
158
+ }
159
+
160
+ // @ts-ignore
161
+ if (navigator.msSaveBlob) {
162
+ // @ts-ignore
163
+ navigator.msSaveBlob(payload, fileName || 'download');
164
+ } else {
165
+ var url = URL.createObjectURL(payload);
166
+ saver(url, fileName);
167
+ URL.revokeObjectURL(url);
168
+ }
169
+ return Promise.resolve();
170
+ }
171
+ export default download;
@@ -0,0 +1,67 @@
1
+ var FileReaderMethodMap = {
2
+ arrayBuffer: 'readAsArrayBuffer',
3
+ binaryString: 'readAsBinaryString',
4
+ dataURL: 'readAsDataURL',
5
+ text: 'readAsText'
6
+ };
7
+
8
+ /**
9
+ * @overload
10
+ * @param {Blob} blob
11
+ * @param {'arrayBuffer'} type
12
+ * @returns {Promise<ArrayBuffer>}
13
+ */
14
+
15
+ /**
16
+ * @overload
17
+ * @param {Blob} blob
18
+ * @param {'binaryString'|'binaryString'|'dataURL'|'text'} [type='dataURL']
19
+ * @returns {Promise<string>}
20
+ */
21
+
22
+ /**
23
+ * 读取 Blob 或 File 对象,可以将 Blob 转为 Base64/String/ArrayBuffer<br/><br/>
24
+ *
25
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端。</em>
26
+ *
27
+ * @static
28
+ * @alias module:Processor.fileReader
29
+ * @see {@link https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader|FileReader}
30
+ * @since 4.16.0
31
+ * @param {Blob} blob Blob 或 File 对象
32
+ * @param {'arrayBuffer'|'binaryString'|'dataURL'|'text'} [type='dataURL'] Blob 或 File 对象
33
+ * @returns {Promise<string|ArrayBuffer>} 文件的内容
34
+ * @example
35
+ * const aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // 一个包含DOMString的数组
36
+ * const htmlBlob = new Blob(aFileParts, { type: 'text/html' }); // 得到 blob
37
+ *
38
+ * fileReader(htmlBlob).then(data=>{
39
+ * console.log(data); // data:text/html;base64,PGEgaWQ9ImEiPjxiIGlkPSJiIj5oZXkhPC9iPjwvYT4=
40
+ * });
41
+ *
42
+ * const textBlob = new Blob(aFileParts, { type: 'text/plain' });
43
+ *
44
+ * fileReader(textBlob, 'text').then(data=>{
45
+ * console.log(data); // <a id="a"><b id="b">hey!</b></a>
46
+ * });
47
+ */
48
+ function fileReader(blob) {
49
+ var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'dataURL';
50
+ var method = FileReaderMethodMap[type];
51
+ if (!method) {
52
+ method = FileReaderMethodMap.dataURL;
53
+ }
54
+ return new Promise(function (resolve, reject) {
55
+ var reader = new FileReader();
56
+ // @ts-ignore
57
+ reader[method](blob);
58
+ // @ts-ignore
59
+ reader.onload = function () {
60
+ return resolve(reader.result);
61
+ };
62
+ reader.onerror = function (error) {
63
+ return reject(error);
64
+ };
65
+ });
66
+ }
67
+ export default fileReader;
package/esm/index.js CHANGED
@@ -40,6 +40,7 @@ export { default as numberToChinese } from './numberToChinese';
40
40
  export { default as bytesToSize } from './bytesToSize';
41
41
  export { default as parseIdCard } from './parseIdCard';
42
42
  export { default as blobToDataURL } from './blobToDataURL';
43
+ export { default as fileReader } from './fileReader';
43
44
  export { default as dataURLToBlob } from './dataURLToBlob';
44
45
  export { default as setDataURLPrefix } from './setDataURLPrefix';
45
46
  export { default as normalizeString } from './normalizeString';
@@ -52,8 +53,8 @@ export { default as padZero } from './padZero';
52
53
  *
53
54
  * @module Math
54
55
  * @since 3.1.0
55
- * @see 参考 {@link https://github.com/camsong/blog/issues/9|JavaScript 浮点数陷阱及解法}
56
- * @see 参考 {@link https://2zbuy.csb.app/|JS浮点数计算测试}
56
+ * @see {@link https://github.com/camsong/blog/issues/9|JavaScript 浮点数陷阱及解法}
57
+ * @see {@link https://2zbuy.csb.app/|JS浮点数计算测试}
57
58
  * @example
58
59
  * // 从 4.12.0 版本开始,规范了有效数值。(注意:4.12.3 对有效数值重新定义)
59
60
  * // 有效数值即能通过 Number(value) 转为数字,且不能为 NaN 。
@@ -98,10 +99,12 @@ export { default as round } from './round';
98
99
  * @module Other
99
100
  * @since 4.2.0
100
101
  */
101
- export { default as waitTime } from './waitTime';
102
+ export { default as ajax } from './ajax';
102
103
  export { default as calculateCursorPosition } from './calculateCursorPosition';
104
+ export { default as download } from './download';
103
105
  export { default as randomString } from './randomString';
104
106
  export { default as strlen } from './strlen';
107
+ export { default as waitTime } from './waitTime';
105
108
 
106
109
  /**
107
110
  * 树结构数据查询、过滤、转换等处理方法
@@ -0,0 +1,125 @@
1
+ /* eslint-disable no-unused-vars */
2
+ // 该文件用于 jsdoc 生成文件。因为一些 typescript 语法, jsdoc 不支持,导致生成文档报错。
3
+
4
+ /**
5
+ * 转换字段名,返回一个转换字段后的值,不改变原值。
6
+ *
7
+ * @static
8
+ * @alias module:Tree.transformFieldNames
9
+ * @since 4.14.0
10
+ * @param {object[]} data 对象数组。如果是树结构数据,需要指定第三个参数 childrenField
11
+ * @param {object} fieldNames 字段名映射
12
+ * @param {string} [childrenField] 子级数据字段名
13
+ * @param {'spread'|'self'} [nodeAssign='spread'] 节点赋值方式。spread表示使用展开运算符创建新值,self表示使用自身对象。
14
+ * @returns {object[]}
15
+ * @example
16
+ *
17
+ * const options = [{code: '1', name: 'one'},{code:'2', name:'two'}];
18
+ * const newOptions = transformFieldNames(options, {label: 'name', value: 'code'});
19
+ * // [{value: '1', label: 'one'},{value:'2', label:'two'}]
20
+ *
21
+ * // 嵌套数据,指定子级字段名 children
22
+ * const options2 = [{code: '1', name: 'one'},{code:'2', name:'two', children: [{code:'2-1', name:'two-one', children: [{code: '2-1-1', name:'two-one-one'}]}]}];
23
+ * const newOptions2 = transformFieldNames(options2, {label: 'name', value: 'code'}, 'children');
24
+ * // [{value: '1', label: 'one'},{value:'2', label:'two', children: [{value: '2-1', label:'two-one', children: [{value: '2-1-1', label:'two-one-one'}]}]}]
25
+ *
26
+ * const options3 = [{code: '1', name: 'one'},{code:'2', name:'two', childs: [{code:'2-1', name:'two-one'}]}];
27
+ * const newOptions3 = transformFieldNames(options3, {label: 'name', value: 'code'}, 'childs');
28
+ * // [{value: '1', label: 'one'},{value:'2', label:'two', childs: [{value: '2-1', label:'two-one'}]}]
29
+ *
30
+ * // 嵌套数据,并替换子集字段名
31
+ * const newOptions4 = transformFieldNames(options3, {label: 'name', value: 'code', children: 'childs'}, 'childs');
32
+ * // [{value: '1', label: 'one'},{value:'2', label:'two', children: [{value: '2-1', label:'two-one'}]}]
33
+ */
34
+ function transformFieldNames(data, fieldNames, childrenField) {}
35
+
36
+ /**
37
+ * @see {@link https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
38
+ * @typedef {Object} AjaxOptions ajax配置项
39
+ * @property {string} [method="get"] 创建请求时使用的方法
40
+ * @property {*} [data=null] 请求体被发送的数据
41
+ * @property {object} [headers] 自定义请求头
42
+ * @property {string} [responseType] 响应类型
43
+ * @property {number} [timeout] 请求超时的毫秒数
44
+ * @property {boolean} [withCredentials=false] 跨域请求时是否需要使用凭证
45
+ * @property {boolean} [async=true] 是否异步执行操作
46
+ * @property {string|null} [user=null] 用户名,用于认证用途
47
+ * @property {string|null} [password=null] 密码,用于认证用途
48
+ * @property {function} [onLoadStart] 接收到响应数据时触发
49
+ * @property {function} [onProgress] 请求接收到更多数据时,周期性地触发
50
+ * @property {function} [onAbort] 当 request 被停止时触发,例如当程序调用 XMLHttpRequest.abort() 时
51
+ * @property {function} [onTimeout] 在预设时间内没有接收到响应时触发
52
+ * @property {function} [onError] 当 request 遭遇错误时触发
53
+ * @property {function} [onLoad] 请求成功完成时触发
54
+ * @property {function} [onLoadEnd] 请求结束时触发,无论请求成功 (load) 还是失败 (abort 或 error)
55
+ */
56
+
57
+ /**
58
+ * 请求<br/><br/>
59
+ *
60
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端。</em>
61
+ *
62
+ * @static
63
+ * @alias module:Other.ajax
64
+ * @since 4.16.0
65
+ * @see {@link https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
66
+ * @param {string} url 地址
67
+ * @param {AjaxOptions} [options] 配置项
68
+ * @returns {Promise<object>} XHR 事件对象
69
+ * @example
70
+ * ajax('/somefile').then(res=>{
71
+ * // do something
72
+ * });
73
+ *
74
+ * ajax('/api', { method: 'post' }).then(res=>{
75
+ * // do something
76
+ * });
77
+ */
78
+ function ajax(url, options) {}
79
+
80
+ /**
81
+ * @callback TransformRequest
82
+ * @param {AjaxOptions} options ajax 配置项
83
+ * @returns {AjaxOptions | Promise<AjaxOptions>}
84
+ */
85
+
86
+ /**
87
+ * @callback TransformResponse
88
+ * @param {Blob} res 响应的Blob对象。如果你通过 transformRequest 修改了 responseType ,该参数将是该类型响应值。
89
+ * @returns {Blob | Promise<Blob>}
90
+ */
91
+
92
+ /**
93
+ * @typedef {Object} DownloadOptions 下载配置项
94
+ * @property {string} [options.fileName] 文件名称
95
+ * @property {string} [options.type] MIME 类型
96
+ * @property {'url'|'text'} [options.dataType] 手动设置数据类型,默认会根据传入的数据判断类型,主要是为了区分 url 和 text 。<br/>如果你要下载的文本是 url ,请设置 'text' ;如果你要下载的 url 是绝对/相对路径,请设置 'url' 。
97
+ * @property {TransformRequest} [options.transformRequest] 请求前触发,XHR 对象或配置调整
98
+ * @property {TransformResponse} [options.transformResponse] 请求成功后触发,在传递给 then/catch 前,允许修改响应数据
99
+ */
100
+
101
+ /**
102
+ * 下载<br/><br/>
103
+ *
104
+ * <em style="font-weight: bold;">注意:该方法仅适用于浏览器端,兼容 IE10+ 和现代浏览器。</em>
105
+ *
106
+ * @static
107
+ * @alias module:Other.download
108
+ * @since 4.16.0
109
+ * @see {@link https://zh.wikipedia.org/wiki/多用途互聯網郵件擴展|MIME}
110
+ * @see {@link https://9ykc9s.csb.app/|在线示例}
111
+ * @param {string|Blob|TypedArray} data 字符串、blob数据或url地址
112
+ * @param {string|DownloadOptions} [options] 文件名称 或 配置项
113
+ * @returns {Promise<void>}
114
+ * @example
115
+ * // 文本
116
+ * download('hello world', 'text.txt');
117
+ *
118
+ * // 远程文件
119
+ * download('/xxx.jpg', { dataType: 'url' });
120
+ *
121
+ * // blob文件
122
+ * download(new Blob(['hello world']), 'text.txt');
123
+ *
124
+ */
125
+ function download(data, fileName, options) {}
package/esm/isBankCard.js CHANGED
@@ -28,8 +28,8 @@ function sumCheckCode(numStr) {
28
28
  *
29
29
  * @static
30
30
  * @alias module:Validator.isBankCard
31
- * @see 参考 {@link https://kf.qq.com/faq/170112ABnm6b170112FvquAn.html|常用银行账号位数参考}
32
31
  * @since 1.1.0
32
+ * @see {@link https://kf.qq.com/faq/170112ABnm6b170112FvquAn.html|常用银行账号位数参考}
33
33
  * @param {*} value 要检测的值
34
34
  * @param {Object} [options] 配置项
35
35
  * @param {boolean} [options.loose=false] 宽松模式,8~30位数字
@@ -38,8 +38,8 @@ function sumCheckCode(preCode) {
38
38
  *
39
39
  * @static
40
40
  * @alias module:Validator.isBusinessLicense
41
- * @see 参考 {@link https://wenku.baidu.com/view/19873704cc1755270722087c.html|GS15—2006 工商行政管理市场主体注册号编制规则}
42
41
  * @since 3.5.0
42
+ * @see {@link https://wenku.baidu.com/view/19873704cc1755270722087c.html|GS15—2006 工商行政管理市场主体注册号编制规则}
43
43
  * @param {*} value 要检测的值
44
44
  * @param {Object} [options] 配置项
45
45
  * @param {boolean} [options.checkCode=true] 是否校验最后一位校验码,如果为false,不校验校验位。
package/esm/isChinese.js CHANGED
@@ -32,9 +32,9 @@ var supportRegExpUnicode = RegExp.prototype.hasOwnProperty('unicode');
32
32
  * @static
33
33
  * @alias module:Validator.isChinese
34
34
  * @since 1.1.0
35
- * @see 参考 {@link http://www.unicode.org/reports/tr38/#BlockListing|4.4 Listing of Characters Covered by the Unihan Database}
36
- * @see 参考 {@link https://zh.wikipedia.org/wiki/Unicode字符平面映射|Unicode字符平面映射}
37
- * @see 参考 {@link https://zh.wikipedia.org/wiki/Unicode區段|Unicode区段}
35
+ * @see {@link http://www.unicode.org/reports/tr38/#BlockListing|4.4 Listing of Characters Covered by the Unihan Database}
36
+ * @see {@link https://zh.wikipedia.org/wiki/Unicode字符平面映射|Unicode字符平面映射}
37
+ * @see {@link https://zh.wikipedia.org/wiki/Unicode區段|Unicode区段}
38
38
  * @param {*} value 要检测的值
39
39
  * @param {Object} [options] 配置项
40
40
  * @param {boolean} [options.loose=false] 宽松模式。如果为true,只要包含中文即为true
package/esm/isHMCard.js CHANGED
@@ -9,7 +9,7 @@ var regHMCard = /^[hm]{1}([0-9]{10}|[0-9]{8})$/i;
9
9
  * @static
10
10
  * @alias module:Validator.isHMCard
11
11
  * @since 4.0.0
12
- * @see 参考 {@link https://zh.wikipedia.org/wiki/港澳居民来往内地通行证|港澳居民来往内地通行证}
12
+ * @see {@link https://zh.wikipedia.org/wiki/港澳居民来往内地通行证|港澳居民来往内地通行证}
13
13
  * @param {*} value 要检测的值
14
14
  * @returns {boolean} 是否为港澳居民来往内地通行证
15
15
  * @example