hy-app 0.6.4 → 0.6.6

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 (106) hide show
  1. package/attributes.json +1 -1
  2. package/components/hy-address-picker/hy-address-picker.vue +249 -249
  3. package/components/hy-address-picker/props.ts +103 -103
  4. package/components/hy-button/hy-button.vue +320 -289
  5. package/components/hy-button/props.ts +143 -143
  6. package/components/hy-button/typing.d.ts +43 -35
  7. package/components/hy-calendar/header.vue +58 -58
  8. package/components/hy-calendar/hy-calendar.vue +8 -6
  9. package/components/hy-calendar/month.vue +402 -402
  10. package/components/hy-calendar/props.ts +169 -169
  11. package/components/hy-calendar/typing.d.ts +47 -45
  12. package/components/hy-cell-item/hy-cell-item.vue +161 -161
  13. package/components/hy-cell-item/props.ts +59 -59
  14. package/components/hy-check-button/hy-check-button.vue +135 -135
  15. package/components/hy-code-input/hy-code-input.vue +231 -231
  16. package/components/hy-code-input/props.ts +90 -90
  17. package/components/hy-config-provider/hy-config-provider.vue +53 -53
  18. package/components/hy-config-provider/props.ts +30 -30
  19. package/components/hy-coupon/hy-coupon.vue +183 -183
  20. package/components/hy-coupon/props.ts +108 -108
  21. package/components/hy-datetime-picker/hy-datetime-picker.vue +41 -55
  22. package/components/hy-datetime-picker/props.ts +144 -144
  23. package/components/hy-datetime-picker/typing.d.ts +2 -0
  24. package/components/hy-divider/props.ts +83 -83
  25. package/components/hy-empty/icon.ts +72 -72
  26. package/components/hy-folding-panel/hy-folding-panel-group.vue +162 -162
  27. package/components/hy-form/hy-form.vue +220 -220
  28. package/components/hy-icon/hy-icon.vue +112 -112
  29. package/components/hy-index-bar/hy-index-bar.vue +185 -185
  30. package/components/hy-index-bar/index.scss +64 -64
  31. package/components/hy-index-bar/props.ts +94 -94
  32. package/components/hy-index-bar/typing.d.ts +36 -36
  33. package/components/hy-input/hy-input.vue +333 -333
  34. package/components/hy-input/props.ts +186 -186
  35. package/components/hy-modal/hy-modal.vue +211 -211
  36. package/components/hy-modal/props.ts +94 -94
  37. package/components/hy-modal/typing.d.ts +16 -16
  38. package/components/hy-notice-bar/hy-row-notice.vue +121 -121
  39. package/components/hy-notify/hy-notify.vue +174 -174
  40. package/components/hy-number-step/hy-number-step.vue +367 -367
  41. package/components/hy-overlay/hy-overlay.vue +61 -61
  42. package/components/hy-overlay/props.ts +38 -38
  43. package/components/hy-pagination/hy-pagination.vue +136 -136
  44. package/components/hy-pagination/props.ts +58 -58
  45. package/components/hy-parse/hy-parse.vue +550 -550
  46. package/components/hy-parse/node/node.vue +781 -781
  47. package/components/hy-parse/parser.js +1455 -1455
  48. package/components/hy-parse/props.ts +19 -19
  49. package/components/hy-parse/typing.d.ts +68 -68
  50. package/components/hy-picker/hy-picker.vue +435 -435
  51. package/components/hy-picker/props.ts +122 -122
  52. package/components/hy-picker/typing.d.ts +38 -38
  53. package/components/hy-qrcode/props.ts +72 -72
  54. package/components/hy-qrcode/qrcode.js.bak +1433 -1433
  55. package/components/hy-radio/props.ts +97 -97
  56. package/components/hy-read-more/props.ts +48 -48
  57. package/components/hy-search/props.ts +133 -133
  58. package/components/hy-signature/canvasHelper.ts +51 -51
  59. package/components/hy-signature/props.ts +121 -121
  60. package/components/hy-skeleton/hy-skeleton.vue +142 -142
  61. package/components/hy-skeleton/props.ts +46 -46
  62. package/components/hy-skeleton/typing.d.ts +31 -31
  63. package/components/hy-steps/hy-steps.vue +275 -275
  64. package/components/hy-steps/typing.d.ts +25 -25
  65. package/components/hy-swiper/hy-swiper.vue +3 -3
  66. package/components/hy-swiper/index.scss +5 -5
  67. package/components/hy-swiper/props.ts +0 -1
  68. package/components/hy-table/hy-table.vue +630 -630
  69. package/components/hy-table/props.ts +62 -62
  70. package/components/hy-table/typing.d.ts +29 -29
  71. package/components/hy-tabs/hy-tabs.vue +336 -335
  72. package/components/hy-tabs/props.ts +84 -77
  73. package/components/hy-tag/hy-tag.vue +173 -173
  74. package/components/hy-tag/props.ts +89 -89
  75. package/components/hy-text/hy-text.vue +237 -237
  76. package/components/hy-text/props.ts +115 -115
  77. package/components/hy-textarea/hy-textarea.vue +198 -198
  78. package/components/hy-toast/hy-toast.vue +200 -200
  79. package/components/hy-toast/props.ts +3 -3
  80. package/components/hy-transition/hy-transition.vue +157 -157
  81. package/components/hy-transition/props.ts +32 -32
  82. package/components/hy-upload/hy-upload.vue +384 -384
  83. package/components/hy-watermark/hy-watermark.vue +1058 -1058
  84. package/components/hy-watermark/props.ts +109 -109
  85. package/global.d.ts +94 -94
  86. package/libs/api/http.ts +119 -119
  87. package/libs/composables/index.ts +8 -8
  88. package/libs/composables/useMessage.ts +149 -149
  89. package/libs/composables/useToast.ts +45 -45
  90. package/libs/composables/useTranslate.ts +10 -10
  91. package/libs/css/_config.scss +5 -5
  92. package/libs/index.ts +8 -8
  93. package/libs/locale/index.ts +32 -32
  94. package/libs/locale/lang/en-US.ts +84 -84
  95. package/libs/locale/lang/zh-CN.ts +87 -87
  96. package/libs/typing/index.ts +2 -2
  97. package/libs/typing/modules/common.d.ts +139 -139
  98. package/libs/typing/modules/form.ts +176 -176
  99. package/libs/typing/modules/http.d.ts +19 -19
  100. package/libs/typing/modules/index.d.ts +12 -12
  101. package/libs/utils/inside.ts +340 -340
  102. package/libs/utils/inspect.ts +140 -140
  103. package/libs/utils/utils.ts +525 -525
  104. package/package.json +81 -81
  105. package/tags.json +1 -1
  106. package/web-types.json +1 -1
@@ -1,525 +1,525 @@
1
- import Base64 from './base64'
2
- import type { CSSProperties } from 'vue'
3
- import { error, isNumber, isObject } 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
- /**
406
- * 查询节点信息
407
- * 目前此方法在支付宝小程序中无法获取组件跟接点的尺寸,为支付宝的bug(2020-07-21)
408
- * 解决办法为在组件根部再套一个没有任何作用的view元素
409
- * @param selector 元素类名或id
410
- * @param all 是否获取多个相同元素数值
411
- * @param ins 在微信小程序里,因为utils文件里面获取不到instance值所以必须通过ins这个传过来【注意,(支付宝小程序无效)】
412
- * @param useFields 是否使用 fields 方法获取节点信息
413
- */
414
- const getRect = <T extends boolean>(
415
- selector: string,
416
- all?: T,
417
- ins?: any,
418
- useFields?: boolean
419
- ): Promise<HyUtils.RectResultType<T>> => {
420
- return new Promise<HyUtils.RectResultType<T>>((resolve, reject) => {
421
- let query: UniNamespace.SelectorQuery | null = null
422
- if (ins) {
423
- // TODO: 在微信小程序里,因为utils文件里面获取不到instance值所以必须通过ins这个传过来
424
- query = uni.createSelectorQuery().in(ins)
425
- } else {
426
- query = uni.createSelectorQuery()
427
- }
428
- const method = all ? 'selectAll' : 'select'
429
-
430
- const callback = (rect: UniApp.NodeInfo | UniApp.NodeInfo[]) => {
431
- if (all && Array.isArray(rect) && rect.length > 0) {
432
- resolve(rect as HyUtils.RectResultType<T>)
433
- } else if (!all && rect) {
434
- resolve(rect as HyUtils.RectResultType<T>)
435
- } else {
436
- error(`调用getRect方法,没有找到${selector}对应的元素内容`)
437
- reject(new Error('No nodes found'))
438
- }
439
- }
440
-
441
- if (useFields) {
442
- query[method](selector).fields({ size: true, node: true }, callback).exec()
443
- } else {
444
- query[method](selector).boundingClientRect(callback).exec()
445
- }
446
- })
447
- }
448
-
449
- /**
450
- * @description 用于获取用户传递值的px值 如果用户传递了"xxpx"或者"xxrpx",取出其数值部分,如果是"xxxrpx"还需要用过uni.rpx2px进行转换
451
- * @param {number|string} value 用户传递值的px值
452
- * @param {boolean} unit
453
- * @returns {number|string}
454
- */
455
- function getPx(value: string | number, unit: true): string
456
- function getPx(value: string | number, unit?: false): number
457
- function getPx(value: string | number, unit: boolean = false): string | number {
458
- if (isNumber(value) || typeof value === 'number') {
459
- return unit ? `${value}px` : Number(value)
460
- }
461
- // 如果带有rpx,先取出其数值部分,再转为px值
462
- if (/(rpx|upx)$/.test(value)) {
463
- return unit ? `${uni.rpx2px(parseInt(value))}px` : Number(uni.rpx2px(parseInt(value)))
464
- } else if (/(px)$/.test(value)) {
465
- return unit ? value : Number(value.replace('px', ''))
466
- } else {
467
- return unit ? `${parseInt(value)}px` : Number(value)
468
- }
469
- }
470
-
471
- /**
472
- * @description 对象转换字符串,用在于style样式上
473
- * */
474
- const formatObject = (obj: CSSProperties) => {
475
- return Object.entries(obj)
476
- .map(([key, value]) => `${key.toUpperCase()}: ${value}`)
477
- .join('; ')
478
- }
479
-
480
- /**
481
- * 深度合并两个对象
482
- * @param target 目标对象
483
- * @param source 源对象
484
- * @returns 合并后的对象
485
- */
486
- function deepMerge(
487
- target: HyUtils.DeepMergeable,
488
- source: HyUtils.DeepMergeable
489
- ): HyUtils.DeepMergeable {
490
- Object.keys(source).forEach((key) => {
491
- const targetValue = target[key]
492
- const newObjValue = source[key]
493
- if (isObject(targetValue) && isObject(newObjValue)) {
494
- deepMerge(targetValue, newObjValue)
495
- } else {
496
- target[key] = newObjValue
497
- }
498
- })
499
-
500
- return target
501
- }
502
-
503
- export {
504
- encryptData,
505
- decryptData,
506
- addUnit,
507
- padZero,
508
- addZero,
509
- clearVal,
510
- formatTime,
511
- formatTimeToString,
512
- imageToBase64,
513
- debounce,
514
- throttle,
515
- deepClone,
516
- bytesToSize,
517
- objectToUrlParams,
518
- urlParamsToObject,
519
- random,
520
- range,
521
- getRect,
522
- getPx,
523
- formatObject,
524
- deepMerge
525
- }
1
+ import Base64 from './base64'
2
+ import type { CSSProperties } from 'vue'
3
+ import { error, isNumber, isObject } 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
+ /**
406
+ * 查询节点信息
407
+ * 目前此方法在支付宝小程序中无法获取组件跟接点的尺寸,为支付宝的bug(2020-07-21)
408
+ * 解决办法为在组件根部再套一个没有任何作用的view元素
409
+ * @param selector 元素类名或id
410
+ * @param all 是否获取多个相同元素数值
411
+ * @param ins 在微信小程序里,因为utils文件里面获取不到instance值所以必须通过ins这个传过来【注意,(支付宝小程序无效)】
412
+ * @param useFields 是否使用 fields 方法获取节点信息
413
+ */
414
+ const getRect = <T extends boolean>(
415
+ selector: string,
416
+ all?: T,
417
+ ins?: any,
418
+ useFields?: boolean
419
+ ): Promise<HyUtils.RectResultType<T>> => {
420
+ return new Promise<HyUtils.RectResultType<T>>((resolve, reject) => {
421
+ let query: UniNamespace.SelectorQuery | null = null
422
+ if (ins) {
423
+ // TODO: 在微信小程序里,因为utils文件里面获取不到instance值所以必须通过ins这个传过来
424
+ query = uni.createSelectorQuery().in(ins)
425
+ } else {
426
+ query = uni.createSelectorQuery()
427
+ }
428
+ const method = all ? 'selectAll' : 'select'
429
+
430
+ const callback = (rect: UniApp.NodeInfo | UniApp.NodeInfo[]) => {
431
+ if (all && Array.isArray(rect) && rect.length > 0) {
432
+ resolve(rect as HyUtils.RectResultType<T>)
433
+ } else if (!all && rect) {
434
+ resolve(rect as HyUtils.RectResultType<T>)
435
+ } else {
436
+ error(`调用getRect方法,没有找到${selector}对应的元素内容`)
437
+ reject(new Error('No nodes found'))
438
+ }
439
+ }
440
+
441
+ if (useFields) {
442
+ query[method](selector).fields({ size: true, node: true }, callback).exec()
443
+ } else {
444
+ query[method](selector).boundingClientRect(callback).exec()
445
+ }
446
+ })
447
+ }
448
+
449
+ /**
450
+ * @description 用于获取用户传递值的px值 如果用户传递了"xxpx"或者"xxrpx",取出其数值部分,如果是"xxxrpx"还需要用过uni.rpx2px进行转换
451
+ * @param {number|string} value 用户传递值的px值
452
+ * @param {boolean} unit
453
+ * @returns {number|string}
454
+ */
455
+ function getPx(value: string | number, unit: true): string
456
+ function getPx(value: string | number, unit?: false): number
457
+ function getPx(value: string | number, unit: boolean = false): string | number {
458
+ if (isNumber(value) || typeof value === 'number') {
459
+ return unit ? `${value}px` : Number(value)
460
+ }
461
+ // 如果带有rpx,先取出其数值部分,再转为px值
462
+ if (/(rpx|upx)$/.test(value)) {
463
+ return unit ? `${uni.rpx2px(parseInt(value))}px` : Number(uni.rpx2px(parseInt(value)))
464
+ } else if (/(px)$/.test(value)) {
465
+ return unit ? value : Number(value.replace('px', ''))
466
+ } else {
467
+ return unit ? `${parseInt(value)}px` : Number(value)
468
+ }
469
+ }
470
+
471
+ /**
472
+ * @description 对象转换字符串,用在于style样式上
473
+ * */
474
+ const formatObject = (obj: CSSProperties) => {
475
+ return Object.entries(obj)
476
+ .map(([key, value]) => `${key.toUpperCase()}: ${value}`)
477
+ .join('; ')
478
+ }
479
+
480
+ /**
481
+ * 深度合并两个对象
482
+ * @param target 目标对象
483
+ * @param source 源对象
484
+ * @returns 合并后的对象
485
+ */
486
+ function deepMerge(
487
+ target: HyUtils.DeepMergeable,
488
+ source: HyUtils.DeepMergeable
489
+ ): HyUtils.DeepMergeable {
490
+ Object.keys(source).forEach((key) => {
491
+ const targetValue = target[key]
492
+ const newObjValue = source[key]
493
+ if (isObject(targetValue) && isObject(newObjValue)) {
494
+ deepMerge(targetValue, newObjValue)
495
+ } else {
496
+ target[key] = newObjValue
497
+ }
498
+ })
499
+
500
+ return target
501
+ }
502
+
503
+ export {
504
+ encryptData,
505
+ decryptData,
506
+ addUnit,
507
+ padZero,
508
+ addZero,
509
+ clearVal,
510
+ formatTime,
511
+ formatTimeToString,
512
+ imageToBase64,
513
+ debounce,
514
+ throttle,
515
+ deepClone,
516
+ bytesToSize,
517
+ objectToUrlParams,
518
+ urlParamsToObject,
519
+ random,
520
+ range,
521
+ getRect,
522
+ getPx,
523
+ formatObject,
524
+ deepMerge
525
+ }