@zfqh/uview-x 0.0.0-stage → 0.0.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 (93) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/LICENSE +21 -0
  3. package/README.md +127 -3
  4. package/components/uv-badge/props.ts +83 -0
  5. package/components/uv-badge/uv-badge.vue +186 -0
  6. package/components/uv-button/props.ts +148 -0
  7. package/components/uv-button/uv-button.vue +565 -0
  8. package/components/uv-checkbox/props.ts +83 -0
  9. package/components/uv-checkbox/uv-checkbox.vue +403 -0
  10. package/components/uv-checkbox-group/props.ts +97 -0
  11. package/components/uv-checkbox-group/uv-checkbox-group.vue +163 -0
  12. package/components/uv-code/props.ts +48 -0
  13. package/components/uv-code/uv-code.vue +156 -0
  14. package/components/uv-dialog/props.ts +56 -0
  15. package/components/uv-dialog/uv-dialog.vue +492 -0
  16. package/components/uv-form/props.ts +59 -0
  17. package/components/uv-form/uv-form.vue +256 -0
  18. package/components/uv-form/valid.ts +1344 -0
  19. package/components/uv-form-item/props.ts +62 -0
  20. package/components/uv-form-item/uv-form-item.vue +335 -0
  21. package/components/uv-icon/icons.ts +161 -0
  22. package/components/uv-icon/props.ts +91 -0
  23. package/components/uv-icon/uv-icon.vue +204 -0
  24. package/components/uv-icon/uvicons.ttf +0 -0
  25. package/components/uv-input/props.ts +185 -0
  26. package/components/uv-input/uv-input.vue +431 -0
  27. package/components/uv-line/props.ts +42 -0
  28. package/components/uv-line/uv-line.vue +75 -0
  29. package/components/uv-line-progress/props.ts +43 -0
  30. package/components/uv-line-progress/uv-line-progress.vue +166 -0
  31. package/components/uv-loading-icon/props.ts +78 -0
  32. package/components/uv-loading-icon/uv-loading-icon.vue +226 -0
  33. package/components/uv-overlay/props.ts +38 -0
  34. package/components/uv-overlay/uv-overlay.vue +120 -0
  35. package/components/uv-popup/props.ts +101 -0
  36. package/components/uv-popup/uv-popup.vue +371 -0
  37. package/components/uv-safe-bottom/props.ts +18 -0
  38. package/components/uv-safe-bottom/uv-safe-bottom.vue +120 -0
  39. package/components/uv-status-bar/props.ts +22 -0
  40. package/components/uv-status-bar/uv-status-bar.vue +121 -0
  41. package/components/uv-tabs/props.ts +84 -0
  42. package/components/uv-tabs/uv-tabs.vue +432 -0
  43. package/components/uv-transition/props.ts +38 -0
  44. package/components/uv-transition/uv-transition.vue +170 -0
  45. package/hooks/index.ts +5 -0
  46. package/hooks/useDebounce.ts +35 -0
  47. package/hooks/useI18n.ts +95 -0
  48. package/hooks/useThrottle.ts +38 -0
  49. package/index.ts +23 -0
  50. package/libs/dayjs/index.ts +217 -0
  51. package/libs/index.ts +4 -0
  52. package/libs/luch-request/adapters/index.ts +133 -0
  53. package/libs/luch-request/core/InterceptorManager.ts +52 -0
  54. package/libs/luch-request/core/Request.ts +202 -0
  55. package/libs/luch-request/core/buildFullPath.ts +21 -0
  56. package/libs/luch-request/core/defaults.ts +34 -0
  57. package/libs/luch-request/core/dispatchRequest.ts +7 -0
  58. package/libs/luch-request/core/mergeConfig.ts +127 -0
  59. package/libs/luch-request/core/settle.ts +17 -0
  60. package/libs/luch-request/helpers/buildURL.ts +65 -0
  61. package/libs/luch-request/helpers/combineURLs.ts +15 -0
  62. package/libs/luch-request/helpers/isAbsoluteURL.ts +15 -0
  63. package/libs/luch-request/index.d.ts +197 -0
  64. package/libs/luch-request/index.ts +3 -0
  65. package/libs/luch-request/utils/clone.ts +265 -0
  66. package/libs/luch-request/utils.ts +136 -0
  67. package/locales/en.ts +78 -0
  68. package/locales/index.ts +169 -0
  69. package/locales/zh-Hans.ts +78 -0
  70. package/package.json +42 -4
  71. package/styles/color.scss +33 -0
  72. package/styles/common.scss +134 -0
  73. package/styles/components.scss +19 -0
  74. package/styles/index.scss +7 -0
  75. package/styles/theme.scss +44 -0
  76. package/styles/var.module.scss +32 -0
  77. package/styles/vue.scss +39 -0
  78. package/theme.scss +2 -0
  79. package/types/index.d.ts +66 -0
  80. package/utils/colorGradient.ts +139 -0
  81. package/utils/compat.ts +165 -0
  82. package/utils/compress.ts +34 -0
  83. package/utils/config.ts +95 -0
  84. package/utils/debounce.ts +7 -0
  85. package/utils/digit.ts +157 -0
  86. package/utils/function.ts +771 -0
  87. package/utils/http.ts +5 -0
  88. package/utils/index.ts +57 -0
  89. package/utils/locale.ts +296 -0
  90. package/utils/platform.ts +71 -0
  91. package/utils/route.ts +142 -0
  92. package/utils/test.ts +256 -0
  93. package/utils/throttle.ts +7 -0
@@ -0,0 +1,771 @@
1
+ import { number, empty } from './test';
2
+ import { round } from './digit';
3
+ import config from './config';
4
+ import type { UviewXColor, UviewXConfig, UviewXProps } from './config';
5
+ import { appTranslate } from './locale';
6
+ /**
7
+ * @description 如果value小于min,取min;如果value大于max,取max
8
+ * @param {number} min
9
+ * @param {number} max
10
+ * @param {number} value
11
+ */
12
+ export function range(min: number = 0, max: number = 0, value: number = 0): number {
13
+ return Math.max(min, Math.min(max, Number(value)));
14
+ }
15
+
16
+ /**
17
+ * @description 用于获取用户传递值的px值 如果用户传递了"xxpx"或者"xxrpx",取出其数值部分,如果是"xxxrpx"还需要用过uni.upx2px进行转换
18
+ * @param {number|string} value 用户传递值的px值
19
+ * @param {boolean} unit
20
+ * @returns {number|string}
21
+ */
22
+ export function getPx(value: number | string, unit = false): number | string {
23
+ if (number(value)) {
24
+ return unit ? `${value}px` : Number(value);
25
+ }
26
+ // 如果带有rpx,先取出其数值部分,再转为px值
27
+ if (/(rpx|upx)$/.test(String(value))) {
28
+ return unit ? `${uni.upx2px(parseInt(String(value)))}px` : Number(uni.upx2px(parseInt(String(value))));
29
+ }
30
+ return unit ? `${parseInt(String(value))}px` : parseInt(String(value));
31
+ }
32
+
33
+ /**
34
+ * @description 延时执行;可传入 Promise 或返回 Promise 的函数,等待其完成且至少延时 time 毫秒
35
+ * 例如:await sleep(20) 将阻塞 20ms;await sleep(300, Promise.resolve('ok')) 至少 300ms 后得到 'ok'
36
+ * @param {number} time 延时时间 单位ms 毫秒
37
+ * @param {Promise|Function} fn 可选,Promise 或返回 Promise 的函数
38
+ * @returns {Promise} 返回 promise(未传 fn 时 resolve null)
39
+ */
40
+ export function sleep<T = any>(time = 1000, fn: Promise<T> | (() => Promise<T>) | null = null): Promise<T> {
41
+ return new Promise<T>((resolve, reject) => {
42
+ const start = fn ? Date.now() : 0;
43
+ const settle = (settler: (value: any) => void, value: any) => {
44
+ const diff = fn ? Date.now() - start : 0;
45
+ if (diff < time) {
46
+ setTimeout(() => {
47
+ settler(value);
48
+ }, time - diff);
49
+ } else {
50
+ settler(value);
51
+ }
52
+ };
53
+ let task: Promise<T> | null = null;
54
+ if (typeof fn === 'function') {
55
+ task = fn();
56
+ } else {
57
+ task = fn;
58
+ }
59
+ if (task) {
60
+ task
61
+ .then((value) => {
62
+ settle(resolve, value);
63
+ })
64
+ .catch((error) => {
65
+ settle(reject, error);
66
+ });
67
+ } else {
68
+ settle(resolve, null);
69
+ }
70
+ });
71
+ }
72
+ /**
73
+ * @description 运行期判断平台
74
+ * @returns {string} 返回所在平台(小写)
75
+ * @link 运行期判断平台 https://uniapp.dcloud.io/frame?id=判断平台
76
+ */
77
+ export function os(): string {
78
+ try {
79
+ const device: any = uni.getDeviceInfo();
80
+ return String(device?.osName || device?.platform || 'unknown').toLowerCase();
81
+ } catch (e) {
82
+ try {
83
+ return uni.getSystemInfoSync().platform.toLowerCase();
84
+ } catch (err) {
85
+ return 'unknown';
86
+ }
87
+ }
88
+ }
89
+ /**
90
+ * @description 获取系统信息同步接口
91
+ * @link 获取系统信息同步接口 https://uniapp.dcloud.io/api/system/info?id=getsysteminfosync
92
+ */
93
+ export function sys(): Record<string, any> {
94
+ const info: any = {};
95
+ try {
96
+ if (typeof uni.getWindowInfo === 'function') {
97
+ Object.assign(info, uni.getWindowInfo());
98
+ }
99
+ } catch (e) {}
100
+ try {
101
+ if (typeof uni.getDeviceInfo === 'function') {
102
+ Object.assign(info, uni.getDeviceInfo());
103
+ }
104
+ } catch (e) {}
105
+ try {
106
+ if (typeof uni.getAppBaseInfo === 'function') {
107
+ Object.assign(info, uni.getAppBaseInfo());
108
+ }
109
+ } catch (e) {}
110
+ if (info.statusBarHeight === undefined) {
111
+ try {
112
+ Object.assign(info, uni.getSystemInfoSync());
113
+ } catch (e) {}
114
+ }
115
+ return info;
116
+ }
117
+
118
+ /**
119
+ * @description 取一个区间数
120
+ * @param {Number} min 最小值
121
+ * @param {Number} max 最大值
122
+ */
123
+ export function random(min: number, max: number): number {
124
+ if (min >= 0 && max > 0 && max >= min) {
125
+ const gab = max - min + 1;
126
+ return Math.floor(Math.random() * gab + min);
127
+ }
128
+ return 0;
129
+ }
130
+
131
+ /**
132
+ * @param {Number} len uuid的长度
133
+ * @param {Boolean} firstU 将返回的首字母置为"u"
134
+ * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
135
+ */
136
+ export function guid(len = 32, firstU = true, radix: number | null = null): string {
137
+ const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
138
+ const uuid = [];
139
+ radix = radix || chars.length;
140
+
141
+ if (len) {
142
+ // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
143
+ for (let i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
144
+ } else {
145
+ let r;
146
+ // rfc4122标准要求返回的uuid中,某些位为固定的字符
147
+ uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
148
+ uuid[14] = '4';
149
+
150
+ for (let i = 0; i < 36; i++) {
151
+ if (!uuid[i]) {
152
+ r = 0 | (Math.random() * 16);
153
+ uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
154
+ }
155
+ }
156
+ }
157
+ // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
158
+ if (firstU) {
159
+ uuid.shift();
160
+ return `u${uuid.join('')}`;
161
+ }
162
+ return uuid.join('');
163
+ }
164
+
165
+ /**
166
+ * @description 获取父组件的参数,因为支付宝小程序不支持provide/inject的写法
167
+ this.$parent在非H5中,可以准确获取到父组件,但是在H5中,需要多次this.$parent.$parent.xxx
168
+ 这里默认值等于undefined有它的含义,因为最顶层元素(组件)的$parent就是undefined,意味着不传name
169
+ 值(默认为undefined),就是查找最顶层的$parent
170
+ * @param {string|undefined} name 父组件的参数名
171
+ */
172
+ export function $parent(this: any, name?: string): any | false {
173
+ let parent = this.$parent;
174
+ // 通过while历遍,这里主要是为了H5需要多层解析的问题
175
+ while (parent) {
176
+ // 父组件
177
+ if (parent.$options && parent.$options.name !== name) {
178
+ // 如果组件的name不相等,继续上一级寻找
179
+ parent = parent.$parent;
180
+ } else {
181
+ return parent;
182
+ }
183
+ }
184
+ return false;
185
+ }
186
+
187
+ /**
188
+ * @description 样式转换
189
+ * 对象转字符串,或者字符串转对象
190
+ * @param {object | string} customStyle 需要转换的目标
191
+ * @param {String} target 转换的目的,object-转为对象,string-转为字符串
192
+ * @returns {object|string}
193
+ */
194
+ export function addStyle(
195
+ customStyle: string | Record<string, any>,
196
+ target: 'object' | 'string' = 'object',
197
+ ): Record<string, any> | string {
198
+ // 字符串转字符串,对象转对象情形,直接返回
199
+ if (
200
+ empty(customStyle) ||
201
+ (typeof customStyle === 'object' && target === 'object') ||
202
+ (target === 'string' && typeof customStyle === 'string')
203
+ ) {
204
+ return customStyle;
205
+ }
206
+ // 字符串转对象
207
+ if (target === 'object') {
208
+ // 去除字符串样式中的两端空格(中间的空格不能去掉,比如padding: 20px 0如果去掉了就错了),空格是无用的
209
+ const styleText = trim(String(customStyle));
210
+ // 根据";"将字符串转为数组形式
211
+ const styleArray = styleText.split(';');
212
+ const style: Record<string, any> = {};
213
+ // 历遍数组,拼接成对象
214
+ for (let i = 0; i < styleArray.length; i++) {
215
+ // 'font-size:20px;color:red;',如此最后字符串有";"的话,会导致styleArray最后一个元素为空字符串,这里需要过滤
216
+ if (styleArray[i]) {
217
+ const item = styleArray[i].split(':');
218
+ style[trim(item[0])] = trim(item[1]);
219
+ }
220
+ }
221
+ return style;
222
+ }
223
+ // 这里为对象转字符串形式
224
+ const styleObject = customStyle as Record<string, any>;
225
+ let string = '';
226
+ for (const i in styleObject) {
227
+ // 驼峰转为中划线的形式,否则css内联样式,无法识别驼峰样式属性名
228
+ const key = i.replace(/([A-Z])/g, '-$1').toLowerCase();
229
+ string += `${key}:${styleObject[i]};`;
230
+ }
231
+ // 去除两端空格
232
+ return trim(string);
233
+ }
234
+
235
+ /**
236
+ * @description 添加单位,如果有rpx,upx,%,px等单位结尾或者值为auto,直接返回,否则加上px单位结尾
237
+ * @param {string|number} value 需要添加单位的值
238
+ * @param {string} unit 添加的单位名 比如px
239
+ */
240
+ export function addUnit(value: string | number = 'auto', unit: string = config.unit): string {
241
+ value = String(value);
242
+ // 用uvui内置验证规则中的number判断是否为数值
243
+ return number(value) ? `${value}${unit}` : value;
244
+ }
245
+
246
+ /**
247
+ * @description 深度克隆
248
+ * @param {object} obj 需要深度克隆的对象
249
+ * @param cache 缓存
250
+ * @returns {*} 克隆后的对象或者原值(不是对象)
251
+ */
252
+ export function deepClone<T>(obj: T, cache: WeakMap<object, any> = new WeakMap()): T {
253
+ if (obj === null || typeof obj !== 'object') return obj;
254
+ if (cache.has(obj)) return cache.get(obj);
255
+ let clone;
256
+ if (obj instanceof Date) {
257
+ clone = new Date(obj.getTime());
258
+ } else if (obj instanceof RegExp) {
259
+ clone = new RegExp(obj);
260
+ } else if (obj instanceof Map) {
261
+ clone = new Map(Array.from(obj, ([key, value]) => [key, deepClone(value, cache)]));
262
+ } else if (obj instanceof Set) {
263
+ clone = new Set(Array.from(obj, (value) => deepClone(value, cache)));
264
+ } else if (Array.isArray(obj)) {
265
+ clone = obj.map((value) => deepClone(value, cache));
266
+ } else if (Object.prototype.toString.call(obj) === '[object Object]') {
267
+ clone = Object.create(Object.getPrototypeOf(obj));
268
+ cache.set(obj, clone);
269
+ for (const [key, value] of Object.entries(obj)) {
270
+ clone[key] = deepClone(value, cache);
271
+ }
272
+ } else {
273
+ clone = Object.assign({}, obj);
274
+ }
275
+ cache.set(obj, clone);
276
+ return clone;
277
+ }
278
+
279
+ /**
280
+ * @description JS对象深度合并
281
+ * @param {object} target 需要拷贝的对象
282
+ * @param {object} source 拷贝的来源对象
283
+ * @returns {object|boolean} 深度合并后的对象或者false(入参有不是对象)
284
+ */
285
+ export function deepMerge<T extends object>(target: T = {} as T, source: Partial<T> = {}): T {
286
+ target = deepClone(target);
287
+ if (typeof target !== 'object' || target === null || typeof source !== 'object' || source === null) return target;
288
+ const merged: Record<string, any> = Array.isArray(target)
289
+ ? (target.slice() as unknown as Record<string, any>)
290
+ : Object.assign({}, target);
291
+ const sourceRecord = source as Record<string, any>;
292
+ for (const prop in sourceRecord) {
293
+ if (!Object.prototype.hasOwnProperty.call(sourceRecord, prop)) continue;
294
+ const sourceValue = sourceRecord[prop];
295
+ const targetValue = merged[prop];
296
+ if (sourceValue instanceof Date) {
297
+ merged[prop] = new Date(sourceValue);
298
+ } else if (sourceValue instanceof RegExp) {
299
+ merged[prop] = new RegExp(sourceValue);
300
+ } else if (sourceValue instanceof Map) {
301
+ merged[prop] = new Map(sourceValue);
302
+ } else if (sourceValue instanceof Set) {
303
+ merged[prop] = new Set(sourceValue);
304
+ } else if (typeof sourceValue === 'object' && sourceValue !== null) {
305
+ merged[prop] = deepMerge(targetValue, sourceValue);
306
+ } else {
307
+ merged[prop] = sourceValue;
308
+ }
309
+ }
310
+ return merged as T;
311
+ }
312
+
313
+ /**
314
+ * @description error提示
315
+ * @param {*} err 错误内容
316
+ */
317
+ export function error(err: string | Error): void {
318
+ // 开发环境才提示,生产环境不会提示
319
+ if (process.env.NODE_ENV === 'development') {
320
+ console.error(`uvui提示:${err}`);
321
+ }
322
+ }
323
+
324
+ /**
325
+ * @description 打乱数组
326
+ * @param {array} array 需要打乱的数组
327
+ * @returns {array} 打乱后的数组
328
+ */
329
+ export function randomArray<T>(array: T[] = []): T[] {
330
+ // 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0
331
+ return array.sort(() => Math.random() - 0.5);
332
+ }
333
+
334
+ // padStart 的 polyfill,因为某些机型或情况,还无法支持es7的padStart,比如电脑版的微信小程序
335
+ // 所以这里做一个兼容polyfill的兼容处理
336
+ if (!String.prototype.padStart) {
337
+ // 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解
338
+ String.prototype.padStart = function (maxLength, fillString = ' ') {
339
+ if (Object.prototype.toString.call(fillString) !== '[object String]') {
340
+ throw new TypeError('fillString must be String');
341
+ }
342
+ const str = this;
343
+ // 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉
344
+ if (str.length >= maxLength) return String(str);
345
+
346
+ const fillLength = maxLength - str.length;
347
+ let times = Math.ceil(fillLength / fillString.length);
348
+ while ((times >>= 1)) {
349
+ fillString += fillString;
350
+ if (times === 1) {
351
+ fillString += fillString;
352
+ }
353
+ }
354
+ return fillString.slice(0, fillLength) + str;
355
+ };
356
+ }
357
+
358
+ /**
359
+ * @description 格式化时间
360
+ * @param {String|Number} dateTime 需要格式化的时间戳
361
+ * @param {String} fmt 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd
362
+ * @returns {string} 返回格式化后的字符串
363
+ */
364
+ export function timeFormat(dateTime: string | number | Date | null = null, formatStr = 'yyyy-mm-dd'): string {
365
+ let date: Date;
366
+ // 若传入时间为假值,则取当前时间
367
+ if (!dateTime) {
368
+ date = new Date();
369
+ }
370
+ // 若为unix秒时间戳,则转为毫秒时间戳(逻辑有点奇怪,但不敢改,以保证历史兼容)
371
+ else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
372
+ date = new Date(Number(dateTime) * 1000);
373
+ }
374
+ // 若用户传入字符串格式时间戳,new Date无法解析,需做兼容
375
+ else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
376
+ date = new Date(Number(dateTime));
377
+ }
378
+ // 处理平台性差异,在Safari/Webkit中,new Date仅支持/作为分割符的字符串时间
379
+ // 处理 '2022-07-10 01:02:03',跳过 '2022-07-10T01:02:03'
380
+ else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) {
381
+ date = new Date(dateTime.replace(/-/g, '/'));
382
+ }
383
+ // 其他都认为符合 RFC 2822 规范
384
+ else {
385
+ date = new Date(dateTime);
386
+ }
387
+
388
+ const timeSource: Record<string, string> = {
389
+ y: date.getFullYear().toString(), // 年
390
+ m: (date.getMonth() + 1).toString().padStart(2, '0'), // 月
391
+ d: date.getDate().toString().padStart(2, '0'), // 日
392
+ h: date.getHours().toString().padStart(2, '0'), // 时
393
+ M: date.getMinutes().toString().padStart(2, '0'), // 分
394
+ s: date.getSeconds().toString().padStart(2, '0'), // 秒
395
+ // 有其他格式化字符需求可以继续添加,必须转化成字符串
396
+ };
397
+
398
+ for (const key in timeSource) {
399
+ const [ret] = new RegExp(`${key}+`).exec(formatStr) || [];
400
+ if (ret) {
401
+ // 年可能只需展示两位
402
+ const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0;
403
+ formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex));
404
+ }
405
+ }
406
+
407
+ return formatStr;
408
+ }
409
+
410
+ /**
411
+ * @description 时间戳转为多久之前
412
+ * @param {String|Number} timestamp 时间戳
413
+ * @param {String|Boolean} format
414
+ * 格式化规则如果为时间格式字符串,超出一定时间范围,返回固定的时间格式;
415
+ * 如果为布尔值false,无论什么时间,都返回多久以前的格式
416
+ * @returns {string} 转化后的内容
417
+ */
418
+ export function timeFrom(timestamp: string | number | null = null, format: string | false = 'yyyy-mm-dd'): string {
419
+ if (timestamp == null) timestamp = Date.now();
420
+ let timestampValue = parseInt(String(timestamp));
421
+ // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
422
+ if (timestampValue.toString().length == 10) timestampValue *= 1000;
423
+ let timer = Date.now() - timestampValue;
424
+ timer = parseInt(String(timer / 1000));
425
+ // 如果小于5分钟,则返回"刚刚",其他以此类推(文案走组件内置 i18n,支持用户覆盖)
426
+ let tips = '';
427
+ switch (true) {
428
+ case timer < 300:
429
+ tips = appTranslate('uv.time.justNow');
430
+ break;
431
+ case timer >= 300 && timer < 3600:
432
+ tips = appTranslate('uv.time.minutesAgo', { n: parseInt(String(timer / 60)) });
433
+ break;
434
+ case timer >= 3600 && timer < 86400:
435
+ tips = appTranslate('uv.time.hoursAgo', { n: parseInt(String(timer / 3600)) });
436
+ break;
437
+ case timer >= 86400 && timer < 2592000:
438
+ tips = appTranslate('uv.time.daysAgo', { n: parseInt(String(timer / 86400)) });
439
+ break;
440
+ default:
441
+ // 如果format为false,则无论什么时间戳,都显示xx之前
442
+ if (format === false) {
443
+ if (timer >= 2592000 && timer < 365 * 86400) {
444
+ tips = appTranslate('uv.time.monthsAgo', { n: parseInt(String(timer / (86400 * 30))) });
445
+ } else {
446
+ tips = appTranslate('uv.time.yearsAgo', { n: parseInt(String(timer / (86400 * 365))) });
447
+ }
448
+ } else {
449
+ tips = timeFormat(timestampValue, format);
450
+ }
451
+ }
452
+ return tips;
453
+ }
454
+
455
+ /**
456
+ * @description 去除空格
457
+ * @param String str 需要去除空格的字符串
458
+ * @param String pos both(左右)|left|right|all 默认both
459
+ */
460
+ export function trim(str: string, pos: 'both' | 'left' | 'right' | 'all' = 'both'): string {
461
+ str = String(str);
462
+ if (pos == 'both') {
463
+ return str.replace(/^\s+|\s+$/g, '');
464
+ }
465
+ if (pos == 'left') {
466
+ return str.replace(/^\s*/, '');
467
+ }
468
+ if (pos == 'right') {
469
+ return str.replace(/(\s*$)/g, '');
470
+ }
471
+ if (pos == 'all') {
472
+ return str.replace(/\s+/g, '');
473
+ }
474
+ return str;
475
+ }
476
+
477
+ /**
478
+ * @description 对象转url参数
479
+ * @param {object} data,对象
480
+ * @param {Boolean} isPrefix,是否自动加上"?"
481
+ * @param {string} arrayFormat 规则 indices|brackets|repeat|comma
482
+ */
483
+ export function queryParams(
484
+ data: Record<string, any> = {},
485
+ isPrefix = true,
486
+ arrayFormat: 'indices' | 'brackets' | 'repeat' | 'comma' = 'brackets',
487
+ ): string {
488
+ const prefix = isPrefix ? '?' : '';
489
+ const _result = [];
490
+ if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets';
491
+ for (const key in data) {
492
+ const value = data[key];
493
+ // 去掉为空的参数
494
+ if (['', undefined, null].indexOf(value) >= 0) {
495
+ continue;
496
+ }
497
+ // 如果值为数组,另行处理
498
+ if (value.constructor === Array) {
499
+ // e.g. {ids: [1, 2, 3]}
500
+ switch (arrayFormat) {
501
+ case 'indices':
502
+ // 结果: ids[0]=1&ids[1]=2&ids[2]=3
503
+ for (let i = 0; i < value.length; i++) {
504
+ _result.push(`${key}[${i}]=${value[i]}`);
505
+ }
506
+ break;
507
+ case 'brackets':
508
+ // 结果: ids[]=1&ids[]=2&ids[]=3
509
+ value.forEach((_value) => {
510
+ _result.push(`${key}[]=${_value}`);
511
+ });
512
+ break;
513
+ case 'repeat':
514
+ // 结果: ids=1&ids=2&ids=3
515
+ value.forEach((_value) => {
516
+ _result.push(`${key}=${_value}`);
517
+ });
518
+ break;
519
+ case 'comma':
520
+ // 结果: ids=1,2,3
521
+ let commaStr = '';
522
+ value.forEach((_value) => {
523
+ commaStr += (commaStr ? ',' : '') + _value;
524
+ });
525
+ _result.push(`${key}=${commaStr}`);
526
+ break;
527
+ default:
528
+ value.forEach((_value) => {
529
+ _result.push(`${key}[]=${_value}`);
530
+ });
531
+ }
532
+ } else {
533
+ _result.push(`${key}=${value}`);
534
+ }
535
+ }
536
+ return _result.length ? prefix + _result.join('&') : '';
537
+ }
538
+
539
+ /**
540
+ * 显示消息提示框
541
+ * @param {String} title 提示的内容,长度与 icon 取值有关。
542
+ * @param {Number} duration 提示的延迟时间,单位毫秒,默认:2000
543
+ */
544
+ export function toast(title: string, duration = 2000): void {
545
+ uni.showToast({
546
+ title: String(title),
547
+ icon: 'none',
548
+ duration,
549
+ });
550
+ }
551
+
552
+ /**
553
+ * @description 根据主题type值,获取对应的图标
554
+ * @param {String} type 主题名称,primary|info|error|warning|success
555
+ * @param {boolean} fill 是否使用fill填充实体的图标
556
+ */
557
+ export function type2icon(type = 'success', fill = false): string {
558
+ // 如果非预置值,默认为success
559
+ if (['primary', 'info', 'error', 'warning', 'success'].indexOf(type) == -1) type = 'success';
560
+ let iconName = '';
561
+ // 目前(2019-12-12),info和primary使用同一个图标
562
+ switch (type) {
563
+ case 'primary':
564
+ iconName = 'info-circle';
565
+ break;
566
+ case 'info':
567
+ iconName = 'info-circle';
568
+ break;
569
+ case 'error':
570
+ iconName = 'close-circle';
571
+ break;
572
+ case 'warning':
573
+ iconName = 'error-circle';
574
+ break;
575
+ case 'success':
576
+ iconName = 'checkmark-circle';
577
+ break;
578
+ default:
579
+ iconName = 'checkmark-circle';
580
+ }
581
+ // 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的
582
+ if (fill) iconName += '-fill';
583
+ return iconName;
584
+ }
585
+
586
+ /**
587
+ * @description 数字格式化
588
+ * @param {number|string} number 要格式化的数字
589
+ * @param {number} decimals 保留几位小数
590
+ * @param {string} decimalPoint 小数点符号
591
+ * @param {string} thousandsSeparator 千分位符号
592
+ * @returns {string} 格式化后的数字
593
+ */
594
+ export function priceFormat(
595
+ number: number | string,
596
+ decimals = 0,
597
+ decimalPoint = '.',
598
+ thousandsSeparator = ',',
599
+ ): string {
600
+ number = `${number}`.replace(/[^0-9+-Ee.]/g, '');
601
+ const n = !isFinite(+number) ? 0 : +number;
602
+ const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
603
+ const sep = typeof thousandsSeparator === 'undefined' ? ',' : thousandsSeparator;
604
+ const dec = typeof decimalPoint === 'undefined' ? '.' : decimalPoint;
605
+
606
+ const parts = (prec ? round(n, prec) + '' : `${Math.round(n)}`).split('.');
607
+ const re = /(-?\d+)(\d{3})/;
608
+ while (re.test(parts[0])) {
609
+ parts[0] = parts[0].replace(re, `$1${sep}$2`);
610
+ }
611
+
612
+ if ((parts[1] || '').length < prec) {
613
+ parts[1] = parts[1] || '';
614
+ parts[1] += new Array(prec - parts[1].length + 1).join('0');
615
+ }
616
+ return parts.join(dec);
617
+ }
618
+
619
+ /**
620
+ * @description 获取duration值
621
+ * 如果带有ms或者s直接返回,如果大于一定值,认为是ms单位,小于一定值,认为是s单位
622
+ * 比如以30位阈值,那么300大于30,可以理解为用户想要的是300ms,而不是想花300s去执行一个动画
623
+ * @param {String|number} value 比如: "1s"|"100ms"|1|100
624
+ * @param {boolean} unit 提示: 如果是false 默认返回number
625
+ * @return {string|number}
626
+ */
627
+ export function getDuration(value: number | string, unit = true): string | number {
628
+ const valueNum = parseInt(String(value));
629
+ if (unit) {
630
+ if (/s$/.test(String(value))) return value;
631
+ return Number(value) > 30 ? `${value}ms` : `${value}s`;
632
+ }
633
+ if (/ms$/.test(String(value))) return valueNum;
634
+ if (/s$/.test(String(value))) return valueNum > 30 ? valueNum : valueNum * 1000;
635
+ return valueNum;
636
+ }
637
+
638
+ /**
639
+ * @description 日期的月或日补零操作
640
+ * @param {String} value 需要补零的值
641
+ */
642
+ export function padZero(value: string | number): string {
643
+ return `00${value}`.slice(-2);
644
+ }
645
+
646
+ /**
647
+ * @description 在uv-form的子组件内容发生变化,或者失去焦点时,尝试通知uv-form执行校验方法
648
+ * @param {*} instance
649
+ * @param {*} event
650
+ */
651
+ export function formValidate(instance: any, event?: any): void {
652
+ const formItem = $parent.call(instance, 'uv-form-item');
653
+ const form = $parent.call(instance, 'uv-form');
654
+ // 如果发生变化的input或者textarea等,其父组件中有uv-form-item或者uv-form等,就执行form的validate方法
655
+ // 同时将form-item的pros传递给form,让其进行精确对象验证
656
+ if (formItem && form) {
657
+ form.validateField(formItem.prop, () => {}, event);
658
+ }
659
+ }
660
+
661
+ /**
662
+ * @description 获取某个对象下的属性,用于通过类似'a.b.c'的形式去获取一个对象的的属性的形式
663
+ * @param {object} obj 对象
664
+ * @param {string} key 需要获取的属性字段
665
+ * @returns {*}
666
+ */
667
+ export function getProperty(obj: Record<string, any> | null | undefined, key: string): any {
668
+ if (!obj) {
669
+ return;
670
+ }
671
+ if (typeof key !== 'string' || key === '') {
672
+ return '';
673
+ }
674
+ if (key.indexOf('.') !== -1) {
675
+ const keys = key.split('.');
676
+ let firstObj = obj[keys[0]] || {};
677
+
678
+ for (let i = 1; i < keys.length; i++) {
679
+ if (firstObj) {
680
+ firstObj = firstObj[keys[i]];
681
+ }
682
+ }
683
+ return firstObj;
684
+ }
685
+ return obj[key];
686
+ }
687
+
688
+ /**
689
+ * @description 设置对象的属性值,如果'a.b.c'的形式进行设置
690
+ * @param {object} obj 对象
691
+ * @param {string} key 需要设置的属性
692
+ * @param {string} value 设置的值
693
+ */
694
+ export function setProperty(obj: Record<string, any> | null | undefined, key: string, value: any): void {
695
+ if (!obj) {
696
+ return;
697
+ }
698
+ // 递归赋值
699
+ const inFn = function (_obj: Record<string, any>, keys: string[], v: any): void {
700
+ // 最后一个属性key
701
+ if (keys.length === 1) {
702
+ _obj[keys[0]] = v;
703
+ return;
704
+ }
705
+ // 0~length-1个key
706
+ while (keys.length > 1) {
707
+ const k = keys[0];
708
+ if (!_obj[k] || typeof _obj[k] !== 'object') {
709
+ _obj[k] = {};
710
+ }
711
+ const key = keys.shift();
712
+ // 自调用判断是否存在属性,不存在则自动创建对象
713
+ inFn(_obj[k], keys, v);
714
+ }
715
+ };
716
+
717
+ if (typeof key !== 'string' || key === '') {
718
+ } else if (key.indexOf('.') !== -1) {
719
+ // 支持多层级赋值操作
720
+ const keys = key.split('.');
721
+ inFn(obj, keys, value);
722
+ } else {
723
+ obj[key] = value;
724
+ }
725
+ }
726
+
727
+ /**
728
+ * @description 获取当前页面路径
729
+ */
730
+ export function page(): string {
731
+ const pages = getCurrentPages();
732
+ const route = pages[pages.length - 1]?.route;
733
+ // 某些特殊情况下(比如页面进行redirectTo时的一些时机),pages可能为空数组
734
+ return `/${route ? route : ''}`;
735
+ }
736
+
737
+ /**
738
+ * @description 获取当前路由栈实例数组
739
+ */
740
+ export function pages(): ReturnType<typeof getCurrentPages> {
741
+ const pages = getCurrentPages();
742
+ return pages;
743
+ }
744
+
745
+ /**
746
+ * 获取页面历史栈指定层实例
747
+ * @param back {number} [0] - 0或者负数,表示获取历史栈的哪一层,0表示获取当前页面实例,-1 表示获取上一个页面实例。默认0。
748
+ */
749
+ export function getHistoryPage(back = 0): ReturnType<typeof getCurrentPages>[number] | undefined {
750
+ const pages = getCurrentPages();
751
+ const len = pages.length;
752
+ return pages[len - 1 + back];
753
+ }
754
+
755
+ /**
756
+ * @description 修改 uview-x 运行时内置属性值
757
+ * @param {object} config 修改内置 config 属性
758
+ * @param {object} color 修改内置 color 属性
759
+ */
760
+ export interface SetConfigOptions {
761
+ config?: Partial<UviewXConfig>;
762
+ color?: Partial<UviewXColor>;
763
+ props?: UviewXProps;
764
+ }
765
+
766
+ export function setConfig({ config: configPatch = {}, color = {}, props = {} }: SetConfigOptions = {}): void {
767
+ const merged = deepMerge(config, configPatch);
768
+ Object.assign(config, merged);
769
+ config.color = deepMerge(config.color, color);
770
+ config.props = deepMerge(config.props, props);
771
+ }