hy-app 0.5.12 → 0.5.14

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.
@@ -1,521 +1,503 @@
1
- import Base64 from "./base64";
2
- import type { CSSProperties } from "vue";
3
- import { error, isNumber } from "./index";
4
- let base64: any = new Base64();
5
-
6
- /**
7
- * 加密函数
8
- * @param {any} data 对象
9
- * @return { string } 加密字符串
10
- * */
11
- function encryptData(data: Record<string, any> | string): string {
12
- return base64.encode(JSON.stringify(data));
13
- }
14
-
15
- /**
16
- * 解密函数
17
- * @param {string} encryptedVal 加密字符串
18
- * @returns { any | any[] } 解码的数据
19
- * */
20
- function decryptData(encryptedVal: string): Record<string, any> {
21
- return JSON.parse(base64.decode(encryptedVal.toString()));
22
- }
23
-
24
- /**
25
- *用于解密使用 AES 加密算法加密的数据
26
- */
27
-
28
- // const decrypt = (sessionKey: string, encryptedData: string, iv: string) => {
29
- // console.log(CryptoJS)
30
- // let key = CryptoJS.enc.Base64.parse(sessionKey)
31
- // let ivv = CryptoJS.enc.Base64.parse(iv)
32
- // let decrypt = CryptoJS.AES.decrypt(encryptedData, key, {
33
- // iv: ivv,
34
- // mode: CryptoJS.mode.CBC,
35
- // padding: CryptoJS.pad.Pkcs7
36
- // })
37
- // return JSON.parse(base64.decode(CryptoJS.enc.Base64.stringify(decrypt)))
38
- // }
39
-
40
- /**
41
- * @description 添加单位,如果有rpx,upx,%,px等单位结尾或者值为auto,直接返回,否则加上px单位结尾
42
- * @param {String|Number} value 需要添加单位的值
43
- * @param {String} unit 添加的单位名 比如px
44
- * @returns {String}
45
- */
46
- const addUnit = (
47
- value: string | number = "auto",
48
- unit: string = "",
49
- ): string => {
50
- if (!unit) {
51
- unit = "px";
52
- }
53
- if (unit == "rpx" && isNumber(String(value))) {
54
- value = Number(value) * 2;
55
- }
56
- value = String(value);
57
- // 用内置验证规则中的number判断是否为数值
58
- return isNumber(value) ? `${value}${unit}` : value;
59
- };
60
-
61
- /**
62
- * @description 日期的月或日补零操作
63
- * @param {String | Number} value 需要补零的值
64
- * @returns {String}
65
- */
66
- const padZero = (value: string | number): string => {
67
- return `00${value}`.slice(-2);
68
- };
69
-
70
- /**
71
- * @description 后面补零
72
- * @param {String | Number} value 需要补零的值
73
- * @param {Number} length 多少位
74
- * @returns {String}
75
- */
76
- const addZero = (value: string | number, length: number): string => {
77
- if (value === undefined || value === null) return "";
78
- let val = value.toString();
79
- if (length > val.length) {
80
- val += "0".repeat(length - val.length);
81
- } else {
82
- val = val.slice(0, length);
83
- }
84
- return val;
85
- };
86
-
87
- /**
88
- * @description 清空对象里面的值
89
- * @param val 任意类型的值
90
- * */
91
- const clearVal = (val: any) => {
92
- const type = typeof val;
93
- const isArray = val instanceof Array;
94
- switch (type) {
95
- case "string":
96
- return "";
97
- case "number":
98
- return 0;
99
- case "boolean":
100
- return false;
101
- case "undefined":
102
- return null;
103
- case "object":
104
- if (!val) return null;
105
- if (isArray) {
106
- val.map((item) => {
107
- clearVal(item);
108
- });
109
- return val;
110
- } else {
111
- Object.keys(val).map((k) => {
112
- val[k] = clearVal(val[k]);
113
- });
114
- return val;
115
- }
116
- default:
117
- return "";
118
- }
119
- };
120
-
121
- /**
122
- * 时间戳格式化
123
- * @param timestamp 时间戳或者时间格式,例:1702051200000、Sat Apr 06 2024 11:35:56 GMT+0800 (中国标准时间)
124
- * @param fmt 例:yyyy-MM-dd HH:mm:ss / yyyy-MM-dd
125
- * @return date 例:2023-12-09
126
- */
127
- const formatTime = (
128
- timestamp: number | string,
129
- fmt: string = "yyyy-MM-dd HH:mm:ss",
130
- ): string => {
131
- let date: any;
132
- if (timestamp) {
133
- date = new Date(timestamp) ? new Date(timestamp) : timestamp;
134
- let ret;
135
- const opt: any = {
136
- "y+": date.getFullYear().toString(), //年
137
- "M+": (date.getMonth() + 1).toString(), //月
138
- "d+": date.getDate().toString(), //日
139
- "H+": date.getHours().toString(), //时
140
- "m+": date.getMinutes().toString(), //分
141
- "s+": date.getSeconds().toString(), //秒
142
- //如果有其他格式字符需求可以继续添加,必须转化为字符串
143
- };
144
- for (let k in opt) {
145
- ret = new RegExp("(" + k + ")").exec(fmt);
146
- if (ret) {
147
- fmt = fmt.replace(
148
- ret[1],
149
- ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"),
150
- );
151
- }
152
- }
153
- return fmt;
154
- }
155
- return date;
156
- };
157
-
158
- /**
159
- * @description 时间戳或年月日格式转为多久之前
160
- * @param {String|Number} timestamp 时间戳/年月日格式
161
- * @param {String|Boolean} format
162
- * 格式化规则如果为时间格式字符串,超出一定时间范围,返回固定的时间格式;
163
- * 如果为布尔值false,无论什么时间,都返回多久以前的格式
164
- * @returns {string} 转化后的内容
165
- */
166
- const formatTimeToString = (
167
- timestamp: string | number,
168
- format: string | boolean = "yyyy-mm-dd",
169
- ): string => {
170
- const now = new Date();
171
- const oneYear = new Date(now.getFullYear(), 0, 1).getTime(); // 当年一月一号时间戳
172
-
173
- if (timestamp == null) timestamp = Number(now);
174
- timestamp =
175
- typeof timestamp === "string"
176
- ? parseInt(timestamp)
177
- : new Date(timestamp).getTime();
178
- // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
179
- if (timestamp.toString().length == 10) timestamp *= 1000;
180
- let timer = now.getTime() - timestamp;
181
- timer = parseInt(String(timer / 1000));
182
- // 如果小于5分钟,则返回"刚刚",其他以此类推
183
- let tips = "";
184
- switch (true) {
185
- case timer < 300:
186
- tips = "刚刚";
187
- break;
188
- case timer >= 300 && timer < 3600:
189
- tips = `${parseInt(String(timer / 60))}分钟前`;
190
- break;
191
- case timer >= 3600 && timer < 86400:
192
- tips = `${parseInt(String(timer / 3600))}小时前`;
193
- break;
194
- case timer >= 86400 && timer < 2592000:
195
- tips = `${parseInt(String(timer / 86400))}天前`;
196
- break;
197
- default:
198
- // 如果format为false,则无论什么时间戳,都显示xx之前
199
- if (format === false) {
200
- if (timer >= 2592000 && timer < 365 * 86400) {
201
- tips = `${parseInt(String(timer / (86400 * 30)))}个月前`;
202
- } else {
203
- tips = `${parseInt(String(timer / (86400 * 365)))}年前`;
204
- }
205
- } else {
206
- if (timestamp > oneYear) {
207
- formatTime(timestamp, "MM-dd");
208
- } else {
209
- tips =
210
- format === true
211
- ? formatTime(timestamp, "yyyy-MM-dd")
212
- : formatTime(timestamp, format);
213
- }
214
- }
215
- }
216
- return tips;
217
- };
218
-
219
- /**
220
- * @description 本地图片转base64方法(兼容APP、H5、小程序)
221
- * @param {string} path 图片本地路径
222
- * @returns Promise对象
223
- */
224
- const imageToBase64 = (path: string) => {
225
- return new Promise((resolve, reject) => {
226
- // #ifdef APP-PLUS
227
- plus.io.resolveLocalFileSystemURL(path, (entry: any) => {
228
- entry.file((file: any) => {
229
- let fileReader = new plus.io.FileReader();
230
- fileReader.readAsDataURL(file);
231
- fileReader.onloadend = (evt: any) => {
232
- let base64 = evt.target.result.split(",")[1];
233
- resolve(base64);
234
- };
235
- });
236
- });
237
- // #endif
238
- // #ifdef H5
239
- uni.request({
240
- url: path,
241
- responseType: "arraybuffer",
242
- success: (res: UniApp.RequestSuccessCallbackResult) => {
243
- resolve(uni.arrayBufferToBase64(res.data as ArrayBuffer));
244
- },
245
- });
246
- // #endif
247
- // #ifdef MP-WEIXIN
248
- uni.getFileSystemManager().readFile({
249
- filePath: path,
250
- encoding: "base64",
251
- success: (res) => {
252
- resolve(res.data);
253
- },
254
- });
255
- // #endif
256
- });
257
- };
258
-
259
- /**
260
- * 函数防抖:一段实现执行多次,只执行最后一次
261
- * @param {void} fn 回调函数
262
- * @param {number} wait 节流时间
263
- * @returns {void}
264
- * @constructor
265
- */
266
- let timeout: ReturnType<typeof setTimeout> | null = null;
267
- function debounce<T extends (...args: any[]) => void>(
268
- fn: T,
269
- wait: number = 500,
270
- immediate: boolean = false,
271
- ) {
272
- // 清除定时器
273
- if (timeout !== null) clearTimeout(timeout);
274
- // 立即执行,此类情况一般用不到
275
- if (immediate) {
276
- const callNow = !timeout;
277
- timeout = setTimeout(() => {
278
- timeout = null;
279
- }, wait);
280
- if (callNow) typeof fn === "function" && fn();
281
- } else {
282
- // 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法
283
- timeout = setTimeout(() => {
284
- typeof fn === "function" && fn();
285
- }, wait);
286
- }
287
- }
288
-
289
- let timer: ReturnType<typeof setTimeout> | null = null;
290
- let flag: boolean | undefined;
291
- /**
292
- * 函数节流: 一段时间执行一次
293
- * @param {void} fn 回调函数
294
- * @param {number} wait 节流等待时间
295
- * @param {boolean} immediate 是否立马执行
296
- * @returns {void}
297
- * @constructor
298
- */
299
- const throttle = (
300
- fn: Function,
301
- wait: number = 500,
302
- immediate: boolean = true,
303
- ): void => {
304
- if (immediate) {
305
- if (!flag) {
306
- flag = true;
307
- // 如果是立即执行,则在wait毫秒内开始时执行
308
- typeof fn === "function" && fn();
309
- timer = setTimeout(() => {
310
- flag = false;
311
- }, wait);
312
- }
313
- } else if (!flag) {
314
- flag = true;
315
- // 如果是非立即执行,则在wait毫秒内的结束处执行
316
- timer = setTimeout(() => {
317
- flag = false;
318
- typeof fn === "function" && fn();
319
- }, wait);
320
- }
321
- };
322
-
323
- /**
324
- * 递归拷贝对象
325
- * @param {object} source 对象或数组
326
- * @returns 深拷贝的数组和对象
327
- * */
328
- const deepClone = (source: any) => {
329
- if (!source && typeof source !== "object") {
330
- throw new Error("该值不存在或者不是个对象");
331
- }
332
- const targetObj: any = source.constructor === Array ? [] : {};
333
- Object.keys(source).forEach((keys) => {
334
- if (source[keys] && typeof source[keys] === "object") {
335
- targetObj[keys] = deepClone(source[keys]);
336
- } else {
337
- targetObj[keys] = source[keys];
338
- }
339
- });
340
- return targetObj;
341
- };
342
-
343
- /**
344
- * 字节转化(b/KB/MB/GB)单位
345
- * @param {number} bytes 字节
346
- * @returns {string} 返回单位大小
347
- * */
348
- const bytesToSize = (bytes: number) => {
349
- const sizes = ["b", "KB", "MB", "GB", "TB"];
350
- if (bytes === 0) {
351
- return "0b";
352
- }
353
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
354
- if (i === 0) {
355
- return `${bytes}${sizes[i]}`;
356
- }
357
- return `${(bytes / 1024 ** i).toFixed(1)}${sizes[i]}`;
358
- };
359
-
360
- /**
361
- * @description 将对象转换为 URL 查询参数字符串
362
- * @param params - 要转换的对象
363
- * @returns 转换后的查询参数字符串
364
- */
365
- const objectToUrlParams = (params: Record<string, any>): string => {
366
- return Object.entries(params)
367
- .filter(([key, value]) => value !== undefined && value !== null) // 过滤掉值为 undefined 或 null 的项
368
- .map(([key, value]) => {
369
- // 对值进行编码以确保 URL 安全
370
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
371
- })
372
- .join("&"); // 使用 & 拼接所有参数
373
- };
374
-
375
- /**
376
- * @description 地址栏参数转换对象
377
- * @param paramStr - 字符串参数
378
- * @returns 返回转换对象
379
- */
380
- const urlParamsToObject = (paramStr: string): AnyObject => {
381
- const params: AnyObject = {};
382
- // 去掉字符串两端的可能的空格
383
- paramStr = paramStr.trim();
384
- // 如果字符串以?开头,去掉它
385
- if (paramStr.startsWith("?")) {
386
- paramStr = paramStr.substring(1);
387
- }
388
- // 按&分割字符串,得到键值对数组
389
- const pairs = paramStr.split("&");
390
- for (let i = 0; i < pairs.length; i++) {
391
- const pair = pairs[i];
392
- // 按=分割键值对
393
- const [key, ...valueParts] = pair.split("=");
394
- const value = valueParts.join("=");
395
- // 将键值对存入对象
396
- params[decodeURIComponent(key)] = decodeURIComponent(value);
397
- }
398
- return params;
399
- };
400
-
401
- /**
402
- * 获取 [min,max]的随机数
403
- * Math.floor(Math.random()*10) 可均衡获取 0 到 9 的随机整数
404
- * @param min 最小值
405
- * @param max 最大值
406
- * @returns {Number} string 随机数
407
- */
408
- const random = (min: number | string, max: number | string): number => {
409
- min = Number(min);
410
- max = Number(max);
411
- return Math.floor(Math.random() * (max - min + 1) + min) || 0;
412
- };
413
-
414
- const range = (min = 0, max = 0, value = 0) => {
415
- return Math.max(min, Math.min(max, Number(value)));
416
- };
417
-
418
- export type RectResultType<T extends boolean> = T extends true
419
- ? UniApp.NodeInfo[]
420
- : UniApp.NodeInfo;
421
- /**
422
- * 查询节点信息
423
- * 目前此方法在支付宝小程序中无法获取组件跟接点的尺寸,为支付宝的bug(2020-07-21)
424
- * 解决办法为在组件根部再套一个没有任何作用的view元素
425
- * @param selector 元素类名或id
426
- * @param all 是否获取多个相同元素数值
427
- * @param ins 在微信小程序里,因为utils文件里面获取不到instance值所以必须通过ins这个传过来【注意,(支付宝小程序无效)】
428
- * @param useFields 是否使用 fields 方法获取节点信息
429
- */
430
- const getRect = <T extends boolean>(
431
- selector: string,
432
- all?: T,
433
- ins?: any,
434
- useFields?: boolean,
435
- ): Promise<RectResultType<T>> => {
436
- return new Promise<RectResultType<T>>((resolve, reject) => {
437
- let query: UniNamespace.SelectorQuery | null = null;
438
- if (ins) {
439
- // TODO: 在微信小程序里,因为utils文件里面获取不到instance值所以必须通过ins这个传过来
440
- query = uni.createSelectorQuery().in(ins);
441
- } else {
442
- query = uni.createSelectorQuery();
443
- }
444
- const method = all ? "selectAll" : "select";
445
-
446
- const callback = (rect: UniApp.NodeInfo | UniApp.NodeInfo[]) => {
447
- if (all && Array.isArray(rect) && rect.length > 0) {
448
- resolve(rect as RectResultType<T>);
449
- } else if (!all && rect) {
450
- resolve(rect as RectResultType<T>);
451
- } else {
452
- error(`调用getRect方法,没有找到${selector}对应的元素内容`);
453
- reject(new Error("No nodes found"));
454
- }
455
- };
456
-
457
- if (useFields) {
458
- query[method](selector)
459
- .fields({ size: true, node: true }, callback)
460
- .exec();
461
- } else {
462
- query[method](selector).boundingClientRect(callback).exec();
463
- }
464
- });
465
- };
466
-
467
- /**
468
- * @description 用于获取用户传递值的px值 如果用户传递了"xxpx"或者"xxrpx",取出其数值部分,如果是"xxxrpx"还需要用过uni.rpx2px进行转换
469
- * @param {number|string} value 用户传递值的px值
470
- * @param {boolean} unit
471
- * @returns {number|string}
472
- */
473
- function getPx(value: string | number, unit: true): string;
474
- function getPx(value: string | number, unit?: false): number;
475
- function getPx(value: string | number, unit: boolean = false): string | number {
476
- if (isNumber(value) || typeof value === "number") {
477
- return unit ? `${value}px` : Number(value);
478
- }
479
- // 如果带有rpx,先取出其数值部分,再转为px值
480
- if (/(rpx|upx)$/.test(value)) {
481
- return unit
482
- ? `${uni.rpx2px(parseInt(value))}px`
483
- : Number(uni.rpx2px(parseInt(value)));
484
- } else if (/(px)$/.test(value)) {
485
- return unit ? value : Number(value.replace("px", ""));
486
- } else {
487
- return unit ? `${parseInt(value)}px` : Number(value);
488
- }
489
- }
490
-
491
- /**
492
- * @description 对象转换字符串,用在于style样式上
493
- * */
494
- const formatObject = (obj: CSSProperties) => {
495
- return Object.entries(obj)
496
- .map(([key, value]) => `${key.toUpperCase()}: ${value}`)
497
- .join("; ");
498
- };
499
-
500
- export {
501
- encryptData,
502
- decryptData,
503
- addUnit,
504
- padZero,
505
- addZero,
506
- clearVal,
507
- formatTime,
508
- formatTimeToString,
509
- imageToBase64,
510
- debounce,
511
- throttle,
512
- deepClone,
513
- bytesToSize,
514
- objectToUrlParams,
515
- urlParamsToObject,
516
- random,
517
- range,
518
- getRect,
519
- getPx,
520
- formatObject,
521
- };
1
+ import Base64 from './base64'
2
+ import type { CSSProperties } from 'vue'
3
+ import { error, isNumber } from './index'
4
+ let base64: any = new Base64()
5
+
6
+ /**
7
+ * 加密函数
8
+ * @param {any} data 对象
9
+ * @return { string } 加密字符串
10
+ * */
11
+ function encryptData(data: Record<string, any> | string): string {
12
+ return base64.encode(JSON.stringify(data))
13
+ }
14
+
15
+ /**
16
+ * 解密函数
17
+ * @param {string} encryptedVal 加密字符串
18
+ * @returns { any | any[] } 解码的数据
19
+ * */
20
+ function decryptData(encryptedVal: string): Record<string, any> {
21
+ return JSON.parse(base64.decode(encryptedVal.toString()))
22
+ }
23
+
24
+ /**
25
+ *用于解密使用 AES 加密算法加密的数据
26
+ */
27
+
28
+ // const decrypt = (sessionKey: string, encryptedData: string, iv: string) => {
29
+ // console.log(CryptoJS)
30
+ // let key = CryptoJS.enc.Base64.parse(sessionKey)
31
+ // let ivv = CryptoJS.enc.Base64.parse(iv)
32
+ // let decrypt = CryptoJS.AES.decrypt(encryptedData, key, {
33
+ // iv: ivv,
34
+ // mode: CryptoJS.mode.CBC,
35
+ // padding: CryptoJS.pad.Pkcs7
36
+ // })
37
+ // return JSON.parse(base64.decode(CryptoJS.enc.Base64.stringify(decrypt)))
38
+ // }
39
+
40
+ /**
41
+ * @description 添加单位,如果有rpx,upx,%,px等单位结尾或者值为auto,直接返回,否则加上px单位结尾
42
+ * @param {String|Number} value 需要添加单位的值
43
+ * @param {String} unit 添加的单位名 比如px
44
+ * @returns {String}
45
+ */
46
+ const addUnit = (value: string | number = 'auto', unit: string = ''): string => {
47
+ if (!unit) {
48
+ unit = 'px'
49
+ }
50
+ if (unit == 'rpx' && isNumber(String(value))) {
51
+ value = Number(value) * 2
52
+ }
53
+ value = String(value)
54
+ // 用内置验证规则中的number判断是否为数值
55
+ return isNumber(value) ? `${value}${unit}` : value
56
+ }
57
+
58
+ /**
59
+ * @description 日期的月或日补零操作
60
+ * @param {String | Number} value 需要补零的值
61
+ * @returns {String}
62
+ */
63
+ const padZero = (value: string | number): string => {
64
+ return `00${value}`.slice(-2)
65
+ }
66
+
67
+ /**
68
+ * @description 后面补零
69
+ * @param {String | Number} value 需要补零的值
70
+ * @param {Number} length 多少位
71
+ * @returns {String}
72
+ */
73
+ const addZero = (value: string | number, length: number): string => {
74
+ if (value === undefined || value === null) return ''
75
+ let val = value.toString()
76
+ if (length > val.length) {
77
+ val += '0'.repeat(length - val.length)
78
+ } else {
79
+ val = val.slice(0, length)
80
+ }
81
+ return val
82
+ }
83
+
84
+ /**
85
+ * @description 清空对象里面的值
86
+ * @param val 任意类型的值
87
+ * */
88
+ const clearVal = (val: any) => {
89
+ const type = typeof val
90
+ const isArray = val instanceof Array
91
+ switch (type) {
92
+ case 'string':
93
+ return ''
94
+ case 'number':
95
+ return 0
96
+ case 'boolean':
97
+ return false
98
+ case 'undefined':
99
+ return null
100
+ case 'object':
101
+ if (!val) return null
102
+ if (isArray) {
103
+ val.map((item) => {
104
+ clearVal(item)
105
+ })
106
+ return val
107
+ } else {
108
+ Object.keys(val).map((k) => {
109
+ val[k] = clearVal(val[k])
110
+ })
111
+ return val
112
+ }
113
+ default:
114
+ return ''
115
+ }
116
+ }
117
+
118
+ /**
119
+ * 时间戳格式化
120
+ * @param timestamp 时间戳或者时间格式,例:1702051200000、Sat Apr 06 2024 11:35:56 GMT+0800 (中国标准时间)
121
+ * @param fmt 例:yyyy-MM-dd HH:mm:ss / yyyy-MM-dd
122
+ * @return date 例:2023-12-09
123
+ */
124
+ const formatTime = (timestamp: number | string, fmt: string = 'yyyy-MM-dd HH:mm:ss'): string => {
125
+ let date: any
126
+ if (timestamp) {
127
+ date = new Date(timestamp) ? new Date(timestamp) : timestamp
128
+ let ret
129
+ const opt: any = {
130
+ 'y+': date.getFullYear().toString(), //年
131
+ 'M+': (date.getMonth() + 1).toString(), //月
132
+ 'd+': date.getDate().toString(), //日
133
+ 'H+': date.getHours().toString(), //时
134
+ 'm+': date.getMinutes().toString(), //分
135
+ 's+': date.getSeconds().toString() //秒
136
+ //如果有其他格式字符需求可以继续添加,必须转化为字符串
137
+ }
138
+ for (let k in opt) {
139
+ ret = new RegExp('(' + k + ')').exec(fmt)
140
+ if (ret) {
141
+ fmt = fmt.replace(
142
+ ret[1],
143
+ ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
144
+ )
145
+ }
146
+ }
147
+ return fmt
148
+ }
149
+ return date
150
+ }
151
+
152
+ /**
153
+ * @description 时间戳或年月日格式转为多久之前
154
+ * @param {String|Number} timestamp 时间戳/年月日格式
155
+ * @param {String|Boolean} format
156
+ * 格式化规则如果为时间格式字符串,超出一定时间范围,返回固定的时间格式;
157
+ * 如果为布尔值false,无论什么时间,都返回多久以前的格式
158
+ * @returns {string} 转化后的内容
159
+ */
160
+ const formatTimeToString = (
161
+ timestamp: string | number,
162
+ format: string | boolean = 'yyyy-mm-dd'
163
+ ): string => {
164
+ const now = new Date()
165
+ const oneYear = new Date(now.getFullYear(), 0, 1).getTime() // 当年一月一号时间戳
166
+
167
+ if (timestamp == null) timestamp = Number(now)
168
+ timestamp = typeof timestamp === 'string' ? parseInt(timestamp) : new Date(timestamp).getTime()
169
+ // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
170
+ if (timestamp.toString().length == 10) timestamp *= 1000
171
+ let timer = now.getTime() - timestamp
172
+ timer = parseInt(String(timer / 1000))
173
+ // 如果小于5分钟,则返回"刚刚",其他以此类推
174
+ let tips = ''
175
+ switch (true) {
176
+ case timer < 300:
177
+ tips = '刚刚'
178
+ break
179
+ case timer >= 300 && timer < 3600:
180
+ tips = `${parseInt(String(timer / 60))}分钟前`
181
+ break
182
+ case timer >= 3600 && timer < 86400:
183
+ tips = `${parseInt(String(timer / 3600))}小时前`
184
+ break
185
+ case timer >= 86400 && timer < 2592000:
186
+ tips = `${parseInt(String(timer / 86400))}天前`
187
+ break
188
+ default:
189
+ // 如果format为false,则无论什么时间戳,都显示xx之前
190
+ if (format === false) {
191
+ if (timer >= 2592000 && timer < 365 * 86400) {
192
+ tips = `${parseInt(String(timer / (86400 * 30)))}个月前`
193
+ } else {
194
+ tips = `${parseInt(String(timer / (86400 * 365)))}年前`
195
+ }
196
+ } else {
197
+ if (timestamp > oneYear) {
198
+ formatTime(timestamp, 'MM-dd')
199
+ } else {
200
+ tips =
201
+ format === true
202
+ ? formatTime(timestamp, 'yyyy-MM-dd')
203
+ : formatTime(timestamp, format)
204
+ }
205
+ }
206
+ }
207
+ return tips
208
+ }
209
+
210
+ /**
211
+ * @description 本地图片转base64方法(兼容APP、H5、小程序)
212
+ * @param {string} path 图片本地路径
213
+ * @returns Promise对象
214
+ */
215
+ const imageToBase64 = (path: string) => {
216
+ return new Promise((resolve, reject) => {
217
+ // #ifdef APP-PLUS
218
+ plus.io.resolveLocalFileSystemURL(path, (entry: any) => {
219
+ entry.file((file: any) => {
220
+ let fileReader = new plus.io.FileReader()
221
+ fileReader.readAsDataURL(file)
222
+ fileReader.onloadend = (evt: any) => {
223
+ let base64 = evt.target.result.split(',')[1]
224
+ resolve(base64)
225
+ }
226
+ })
227
+ })
228
+ // #endif
229
+ // #ifdef H5
230
+ uni.request({
231
+ url: path,
232
+ responseType: 'arraybuffer',
233
+ success: (res: UniApp.RequestSuccessCallbackResult) => {
234
+ resolve(uni.arrayBufferToBase64(res.data as ArrayBuffer))
235
+ }
236
+ })
237
+ // #endif
238
+ // #ifdef MP-WEIXIN
239
+ uni.getFileSystemManager().readFile({
240
+ filePath: path,
241
+ encoding: 'base64',
242
+ success: (res) => {
243
+ resolve(res.data)
244
+ }
245
+ })
246
+ // #endif
247
+ })
248
+ }
249
+
250
+ /**
251
+ * 函数防抖:一段实现执行多次,只执行最后一次
252
+ * @param {void} fn 回调函数
253
+ * @param {number} wait 节流时间
254
+ * @returns {void}
255
+ * @constructor
256
+ */
257
+ let timeout: ReturnType<typeof setTimeout> | null = null
258
+ function debounce<T extends (...args: any[]) => void>(
259
+ fn: T,
260
+ wait: number = 500,
261
+ immediate: boolean = false
262
+ ) {
263
+ // 清除定时器
264
+ if (timeout !== null) clearTimeout(timeout)
265
+ // 立即执行,此类情况一般用不到
266
+ if (immediate) {
267
+ const callNow = !timeout
268
+ timeout = setTimeout(() => {
269
+ timeout = null
270
+ }, wait)
271
+ if (callNow) typeof fn === 'function' && fn()
272
+ } else {
273
+ // 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法
274
+ timeout = setTimeout(() => {
275
+ typeof fn === 'function' && fn()
276
+ }, wait)
277
+ }
278
+ }
279
+
280
+ let timer: ReturnType<typeof setTimeout> | null = null
281
+ let flag: boolean | undefined
282
+ /**
283
+ * 函数节流: 一段时间执行一次
284
+ * @param {void} fn 回调函数
285
+ * @param {number} wait 节流等待时间
286
+ * @param {boolean} immediate 是否立马执行
287
+ * @returns {void}
288
+ * @constructor
289
+ */
290
+ const throttle = (fn: Function, wait: number = 500, immediate: boolean = true): void => {
291
+ if (immediate) {
292
+ if (!flag) {
293
+ flag = true
294
+ // 如果是立即执行,则在wait毫秒内开始时执行
295
+ typeof fn === 'function' && fn()
296
+ timer = setTimeout(() => {
297
+ flag = false
298
+ }, wait)
299
+ }
300
+ } else if (!flag) {
301
+ flag = true
302
+ // 如果是非立即执行,则在wait毫秒内的结束处执行
303
+ timer = setTimeout(() => {
304
+ flag = false
305
+ typeof fn === 'function' && fn()
306
+ }, wait)
307
+ }
308
+ }
309
+
310
+ /**
311
+ * 递归拷贝对象
312
+ * @param {object} source 对象或数组
313
+ * @returns 深拷贝的数组和对象
314
+ * */
315
+ const deepClone = (source: any) => {
316
+ if (!source && typeof source !== 'object') {
317
+ throw new Error('该值不存在或者不是个对象')
318
+ }
319
+ const targetObj: any = source.constructor === Array ? [] : {}
320
+ Object.keys(source).forEach((keys) => {
321
+ if (source[keys] && typeof source[keys] === 'object') {
322
+ targetObj[keys] = deepClone(source[keys])
323
+ } else {
324
+ targetObj[keys] = source[keys]
325
+ }
326
+ })
327
+ return targetObj
328
+ }
329
+
330
+ /**
331
+ * 字节转化(b/KB/MB/GB)单位
332
+ * @param {number} bytes 字节
333
+ * @returns {string} 返回单位大小
334
+ * */
335
+ const bytesToSize = (bytes: number) => {
336
+ const sizes = ['b', 'KB', 'MB', 'GB', 'TB']
337
+ if (bytes === 0) {
338
+ return '0b'
339
+ }
340
+ const i = Math.floor(Math.log(bytes) / Math.log(1024))
341
+ if (i === 0) {
342
+ return `${bytes}${sizes[i]}`
343
+ }
344
+ return `${(bytes / 1024 ** i).toFixed(1)}${sizes[i]}`
345
+ }
346
+
347
+ /**
348
+ * @description 将对象转换为 URL 查询参数字符串
349
+ * @param params - 要转换的对象
350
+ * @returns 转换后的查询参数字符串
351
+ */
352
+ const objectToUrlParams = (params: Record<string, any>): string => {
353
+ return Object.entries(params)
354
+ .filter(([key, value]) => value !== undefined && value !== null) // 过滤掉值为 undefined 或 null 的项
355
+ .map(([key, value]) => {
356
+ // 对值进行编码以确保 URL 安全
357
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
358
+ })
359
+ .join('&') // 使用 & 拼接所有参数
360
+ }
361
+
362
+ /**
363
+ * @description 地址栏参数转换对象
364
+ * @param paramStr - 字符串参数
365
+ * @returns 返回转换对象
366
+ */
367
+ const urlParamsToObject = (paramStr: string): AnyObject => {
368
+ const params: AnyObject = {}
369
+ // 去掉字符串两端的可能的空格
370
+ paramStr = paramStr.trim()
371
+ // 如果字符串以?开头,去掉它
372
+ if (paramStr.startsWith('?')) {
373
+ paramStr = paramStr.substring(1)
374
+ }
375
+ // 按&分割字符串,得到键值对数组
376
+ const pairs = paramStr.split('&')
377
+ for (let i = 0; i < pairs.length; i++) {
378
+ const pair = pairs[i]
379
+ // 按=分割键值对
380
+ const [key, ...valueParts] = pair.split('=')
381
+ const value = valueParts.join('=')
382
+ // 将键值对存入对象
383
+ params[decodeURIComponent(key)] = decodeURIComponent(value)
384
+ }
385
+ return params
386
+ }
387
+
388
+ /**
389
+ * 获取 [min,max]的随机数
390
+ * Math.floor(Math.random()*10) 可均衡获取 0 9 的随机整数
391
+ * @param min 最小值
392
+ * @param max 最大值
393
+ * @returns {Number} string 随机数
394
+ */
395
+ const random = (min: number | string, max: number | string): number => {
396
+ min = Number(min)
397
+ max = Number(max)
398
+ return Math.floor(Math.random() * (max - min + 1) + min) || 0
399
+ }
400
+
401
+ const range = (min = 0, max = 0, value = 0) => {
402
+ return Math.max(min, Math.min(max, Number(value)))
403
+ }
404
+
405
+ export type RectResultType<T extends boolean> = T extends true ? UniApp.NodeInfo[] : UniApp.NodeInfo
406
+ /**
407
+ * 查询节点信息
408
+ * 目前此方法在支付宝小程序中无法获取组件跟接点的尺寸,为支付宝的bug(2020-07-21)
409
+ * 解决办法为在组件根部再套一个没有任何作用的view元素
410
+ * @param selector 元素类名或id
411
+ * @param all 是否获取多个相同元素数值
412
+ * @param ins 在微信小程序里,因为utils文件里面获取不到instance值所以必须通过ins这个传过来【注意,(支付宝小程序无效)】
413
+ * @param useFields 是否使用 fields 方法获取节点信息
414
+ */
415
+ const getRect = <T extends boolean>(
416
+ selector: string,
417
+ all?: T,
418
+ ins?: any,
419
+ useFields?: boolean
420
+ ): Promise<RectResultType<T>> => {
421
+ return new Promise<RectResultType<T>>((resolve, reject) => {
422
+ let query: UniNamespace.SelectorQuery | null = null
423
+ if (ins) {
424
+ // TODO: 在微信小程序里,因为utils文件里面获取不到instance值所以必须通过ins这个传过来
425
+ query = uni.createSelectorQuery().in(ins)
426
+ } else {
427
+ query = uni.createSelectorQuery()
428
+ }
429
+ const method = all ? 'selectAll' : 'select'
430
+
431
+ const callback = (rect: UniApp.NodeInfo | UniApp.NodeInfo[]) => {
432
+ console.log(rect, 'rect')
433
+ if (all && Array.isArray(rect) && rect.length > 0) {
434
+ resolve(rect as RectResultType<T>)
435
+ } else if (!all && rect) {
436
+ resolve(rect as RectResultType<T>)
437
+ } else {
438
+ error(`调用getRect方法,没有找到${selector}对应的元素内容`)
439
+ reject(new Error('No nodes found'))
440
+ }
441
+ }
442
+
443
+ if (useFields) {
444
+ query[method](selector).fields({ size: true, node: true }, callback).exec()
445
+ } else {
446
+ query[method](selector).boundingClientRect(callback).exec()
447
+ }
448
+ })
449
+ }
450
+
451
+ /**
452
+ * @description 用于获取用户传递值的px值 如果用户传递了"xxpx"或者"xxrpx",取出其数值部分,如果是"xxxrpx"还需要用过uni.rpx2px进行转换
453
+ * @param {number|string} value 用户传递值的px值
454
+ * @param {boolean} unit
455
+ * @returns {number|string}
456
+ */
457
+ function getPx(value: string | number, unit: true): string
458
+ function getPx(value: string | number, unit?: false): number
459
+ function getPx(value: string | number, unit: boolean = false): string | number {
460
+ if (isNumber(value) || typeof value === 'number') {
461
+ return unit ? `${value}px` : Number(value)
462
+ }
463
+ // 如果带有rpx,先取出其数值部分,再转为px值
464
+ if (/(rpx|upx)$/.test(value)) {
465
+ return unit ? `${uni.rpx2px(parseInt(value))}px` : Number(uni.rpx2px(parseInt(value)))
466
+ } else if (/(px)$/.test(value)) {
467
+ return unit ? value : Number(value.replace('px', ''))
468
+ } else {
469
+ return unit ? `${parseInt(value)}px` : Number(value)
470
+ }
471
+ }
472
+
473
+ /**
474
+ * @description 对象转换字符串,用在于style样式上
475
+ * */
476
+ const formatObject = (obj: CSSProperties) => {
477
+ return Object.entries(obj)
478
+ .map(([key, value]) => `${key.toUpperCase()}: ${value}`)
479
+ .join('; ')
480
+ }
481
+
482
+ export {
483
+ encryptData,
484
+ decryptData,
485
+ addUnit,
486
+ padZero,
487
+ addZero,
488
+ clearVal,
489
+ formatTime,
490
+ formatTimeToString,
491
+ imageToBase64,
492
+ debounce,
493
+ throttle,
494
+ deepClone,
495
+ bytesToSize,
496
+ objectToUrlParams,
497
+ urlParamsToObject,
498
+ random,
499
+ range,
500
+ getRect,
501
+ getPx,
502
+ formatObject
503
+ }