@oeos-components/utils 0.0.2 → 0.0.4

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.
package/dist/index.mjs CHANGED
@@ -1,74 +1,759 @@
1
- import { createJiti } from "../../../node_modules/.pnpm/jiti@2.5.1/node_modules/jiti/lib/jiti.mjs";
1
+ import { unref, isRef, toRaw } from '@vue/reactivity';
2
+ import { cloneDeep } from 'lodash-es';
3
+ import { consola } from 'consola';
4
+ import { ElMessage, ElMessageBox } from 'element-plus';
2
5
 
3
- const jiti = createJiti(import.meta.url, {
4
- "interopDefault": true,
5
- "alias": {
6
- "@oeos-components/utils": "/Users/andy/cyrd/oeos-components/packages/utils"
7
- },
8
- "transformOptions": {
9
- "babel": {
10
- "plugins": []
6
+ const isString = (val) => typeof val === "string";
7
+ const isStringNumber = (val) => {
8
+ if (!isString(val)) {
9
+ return false;
10
+ }
11
+ return !Number.isNaN(Number(val));
12
+ };
13
+ const isNumber = (val) => typeof val === "number";
14
+ function $toast(message, type = "success", otherParams = {}) {
15
+ const map = {
16
+ s: "success",
17
+ i: "info",
18
+ e: "error",
19
+ w: "warning"
20
+ };
21
+ if (getType(message) === "object") {
22
+ if (message.clodeAll) {
23
+ ElMessage.closeAll();
11
24
  }
25
+ ElMessage(message);
26
+ return;
12
27
  }
13
- })
14
-
15
- /** @type {import("/Users/andy/cyrd/oeos-components/packages/utils/src/index")} */
16
- const _module = await jiti.import("/Users/andy/cyrd/oeos-components/packages/utils/src/index.ts");
28
+ if (getType(type) === "object") {
29
+ if (type.clodeAll) {
30
+ ElMessage.closeAll();
31
+ }
32
+ ElMessage({
33
+ message,
34
+ type: "success",
35
+ ...type
36
+ });
37
+ return;
38
+ }
39
+ if (otherParams.closeAll) {
40
+ ElMessage.closeAll();
41
+ }
42
+ ElMessage({
43
+ message,
44
+ type: map[type] || type,
45
+ ...otherParams
46
+ });
47
+ }
48
+ $toast.success = (message, otherParams = {}) => $toast(message, "success", otherParams);
49
+ $toast.info = (message, otherParams = {}) => $toast(message, "info", otherParams);
50
+ $toast.error = (message, otherParams = {}) => $toast(message, "error", otherParams);
51
+ $toast.warning = (message, otherParams = {}) => $toast(message, "warning", otherParams);
52
+ function setStorage(storageName, params, isSession = false) {
53
+ let handleParams;
54
+ if (typeof params === "number" || typeof params === "string") {
55
+ handleParams = params;
56
+ } else {
57
+ handleParams = JSON.stringify(params);
58
+ }
59
+ if (isSession) {
60
+ sessionStorage.setItem(storageName, handleParams);
61
+ } else {
62
+ localStorage.setItem(storageName, handleParams);
63
+ }
64
+ }
65
+ function getStorage(data, isSession = false) {
66
+ let getLocalData = "";
67
+ let getSessionData = "";
68
+ if (isSession) {
69
+ getSessionData = sessionStorage.getItem(data);
70
+ } else {
71
+ getLocalData = localStorage.getItem(data);
72
+ }
73
+ if (getLocalData) {
74
+ try {
75
+ if (typeof JSON.parse(getLocalData) !== "number") {
76
+ getLocalData = JSON.parse(getLocalData);
77
+ }
78
+ } catch (e) {
79
+ }
80
+ return getLocalData;
81
+ } else if (getSessionData) {
82
+ try {
83
+ if (typeof JSON.parse(getSessionData) !== "number") {
84
+ getSessionData = JSON.parse(getSessionData);
85
+ }
86
+ } catch (e) {
87
+ }
88
+ return getSessionData;
89
+ }
90
+ return null;
91
+ }
92
+ function clearStorage(str = "") {
93
+ if (isEmpty(str)) {
94
+ sessionStorage.clear();
95
+ localStorage.clear();
96
+ }
97
+ if (notEmpty(str) && getType(str) !== "object") {
98
+ let strArr = Array.isArray(str) ? str : [str];
99
+ for (let i = 0; i < strArr.length; i++) {
100
+ sessionStorage.removeItem(strArr[i]);
101
+ localStorage.removeItem(strArr[i]);
102
+ }
103
+ }
104
+ if (_isObjectWithExclude(str)) {
105
+ if (notEmpty(str.exclude) && getType(str) === "object") {
106
+ let sessionStorageObj = {};
107
+ let localStorageObj = {};
108
+ for (const key in str.exclude) {
109
+ if (Object.prototype.hasOwnProperty.call(str.exclude, key)) {
110
+ const name = str.exclude[key];
111
+ if (getStorage(name)) {
112
+ localStorageObj[name] = getStorage(name);
113
+ }
114
+ if (getStorage(name, true)) {
115
+ sessionStorageObj[name] = getStorage(name, true);
116
+ }
117
+ }
118
+ }
119
+ sessionStorage.clear();
120
+ localStorage.clear();
121
+ for (const key in sessionStorageObj) {
122
+ setStorage(key, sessionStorageObj[key], true);
123
+ }
124
+ for (const key in localStorageObj) {
125
+ setStorage(key, localStorageObj[key]);
126
+ }
127
+ }
128
+ }
129
+ }
130
+ function _isObjectWithExclude(obj) {
131
+ return typeof obj === "object" && obj !== null && "exclude" in obj && typeof obj.exclude === "object";
132
+ }
133
+ function validForm(ref, { message = "\u8868\u5355\u6821\u9A8C\u9519\u8BEF, \u8BF7\u68C0\u67E5", detail = false, showMessage = true } = {}) {
134
+ return new Promise((resolve, reject) => {
135
+ unref(ref).validate((valid, status) => {
136
+ if (valid) {
137
+ resolve(status);
138
+ } else {
139
+ if (message && showMessage) {
140
+ let errorText = Object.keys(status);
141
+ let toastMessage = message;
142
+ if (detail) {
143
+ toastMessage = message + errorText.join(",");
144
+ }
145
+ $toast(toastMessage, "e");
146
+ }
147
+ reject(status);
148
+ }
149
+ });
150
+ });
151
+ }
152
+ function isEmpty(data) {
153
+ if (isRef(data)) {
154
+ data = unref(data);
155
+ }
156
+ if (data instanceof Date) {
157
+ return isNaN(data.getTime());
158
+ }
159
+ switch (typeof data) {
160
+ case "undefined":
161
+ return true;
162
+ case "string":
163
+ if (data.trim().length === 0) return true;
164
+ break;
165
+ case "boolean":
166
+ if (!data) return true;
167
+ break;
168
+ case "number":
169
+ if (0 === data) return true;
170
+ break;
171
+ case "object":
172
+ if (null === data) return true;
173
+ if (void 0 !== data.length && data.length === 0) return true;
174
+ for (var k in data) {
175
+ return false;
176
+ }
177
+ return true;
178
+ }
179
+ return false;
180
+ }
181
+ function notEmpty(v) {
182
+ return !isEmpty(v);
183
+ }
184
+ function merge(obj1, obj2) {
185
+ let merged = { ...obj1, ...obj2 };
186
+ for (let key in merged) {
187
+ if (!isEmpty(obj1[key]) && !isEmpty(obj2[key])) {
188
+ merged[key] = obj2[key];
189
+ } else if (isEmpty(obj1[key]) && !isEmpty(obj2[key])) {
190
+ merged[key] = obj2[key];
191
+ } else if (!isEmpty(obj1[key]) && isEmpty(obj2[key])) {
192
+ merged[key] = obj1[key];
193
+ }
194
+ }
195
+ return merged;
196
+ }
197
+ function clone(data, times = 1) {
198
+ if (isRef(data)) {
199
+ data = unref(data);
200
+ }
201
+ if (getType(data) !== "array") {
202
+ return cloneDeep(data);
203
+ }
204
+ const clonedData = cloneDeep(data);
205
+ const result = [];
206
+ for (let i = 0; i < times; i++) {
207
+ result.push(...clonedData);
208
+ }
209
+ return result;
210
+ }
211
+ function formatTime(time, cFormat = "{y}-{m}-{d} {h}:{i}:{s}") {
212
+ if (!time) {
213
+ return time;
214
+ }
215
+ let date;
216
+ if (typeof time === "object") {
217
+ date = time;
218
+ } else {
219
+ if (("" + time).length === 10) time = parseInt(time) * 1e3;
220
+ date = new Date(time);
221
+ }
222
+ const formatObj = {
223
+ y: date.getFullYear(),
224
+ m: date.getMonth() + 1,
225
+ d: date.getDate(),
226
+ h: date.getHours(),
227
+ i: date.getMinutes(),
228
+ s: date.getSeconds(),
229
+ a: date.getDay()
230
+ };
231
+ const time_str = cFormat.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
232
+ let value = formatObj[key];
233
+ if (key === "a") {
234
+ return ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D"][value];
235
+ }
236
+ if (result.length > 0 && value < 10) {
237
+ value = "0" + value;
238
+ }
239
+ return value || 0;
240
+ });
241
+ return time_str;
242
+ }
243
+ function formatDurationTime(timestamp, cFormat = "{d} \u5929 {h} \u65F6 {i} \u5206 {s} \u79D2") {
244
+ const secondsPerMinute = 60;
245
+ const minutesPerHour = 60;
246
+ const hoursPerDay = 24;
247
+ let totalSeconds = Math.floor(timestamp / 1e3);
248
+ let days = 0;
249
+ if (cFormat.indexOf("d") !== -1) {
250
+ days = Math.floor(totalSeconds / (secondsPerMinute * minutesPerHour * hoursPerDay));
251
+ totalSeconds %= secondsPerMinute * minutesPerHour * hoursPerDay;
252
+ }
253
+ let hours = Math.floor(totalSeconds / (secondsPerMinute * minutesPerHour));
254
+ totalSeconds %= secondsPerMinute * minutesPerHour;
255
+ let minutes = Math.floor(totalSeconds / secondsPerMinute);
256
+ let seconds = totalSeconds % secondsPerMinute;
257
+ const formatObj = {
258
+ d: days,
259
+ h: hours,
260
+ i: minutes,
261
+ s: seconds
262
+ };
263
+ let parseFormat = cFormat;
264
+ if (days === 0) {
265
+ parseFormat = cFormat.match(/{h}.*/g)[0];
266
+ if (hours === 0) {
267
+ parseFormat = cFormat.match(/{i}.*/g)[0];
268
+ if (minutes === 0) {
269
+ parseFormat = cFormat.match(/{s}.*/g)[0];
270
+ }
271
+ }
272
+ }
273
+ const time_str = parseFormat.replace(/{(y|m|d|h|i|s)+}/g, (result, key) => {
274
+ let value = formatObj[key];
275
+ if (result.length > 0 && value < 10 && value != 0) {
276
+ value = "0" + value;
277
+ }
278
+ return value || "00";
279
+ });
280
+ return time_str;
281
+ }
282
+ function uuid(type = "", length = 4, { emailStr = "@qq.com", timeStr = "{m}-{d} {h}:{i}:{s}", startStr = "", optionsIndex = null } = {}) {
283
+ let randomStr = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
284
+ let res = type;
285
+ if (isRef(type)) {
286
+ type = unref(type);
287
+ }
288
+ if (getType(type) === "array" && type.length > 0) {
289
+ let randNum = random(0, type.length - 1);
290
+ if (!length) {
291
+ return type[optionsIndex ?? randNum];
292
+ }
293
+ return type[optionsIndex ?? randNum][length === 4 ? "value" : length];
294
+ }
295
+ if (type === "phone") {
296
+ let prefixArray = new Array("130", "131", "132", "133", "135", "136", "137", "138", "170", "187", "189");
297
+ let i = parseInt(Math.random() * 10);
298
+ let res2 = prefixArray[i];
299
+ for (var j = 0; j < 8; j++) {
300
+ res2 += Math.floor(Math.random() * 10);
301
+ }
302
+ return res2;
303
+ }
304
+ if (type === "email") {
305
+ return uuid(startStr, length) + emailStr;
306
+ }
307
+ if (type === "time") {
308
+ return uuid(startStr, length) + " " + formatTime(/* @__PURE__ */ new Date(), timeStr);
309
+ }
310
+ if (type === "number") {
311
+ let randomStr2 = "123456789";
312
+ let res2 = "";
313
+ for (let i = length; i > 0; --i) {
314
+ res2 += randomStr2[Math.floor(Math.random() * randomStr2.length)];
315
+ }
316
+ return Number(res2);
317
+ }
318
+ if (type === "ip") {
319
+ let randomNum = random(1, 99);
320
+ return `10.0.11.` + randomNum;
321
+ }
322
+ if (type === "port") {
323
+ let randomNum = random(1, 65535);
324
+ return randomNum;
325
+ }
326
+ for (let i = length; i > 0; --i) {
327
+ res += randomStr[Math.floor(Math.random() * randomStr.length)];
328
+ }
329
+ return res;
330
+ }
331
+ function getType(type) {
332
+ if (typeof type === "object") {
333
+ const objType = Object.prototype.toString.call(type).slice(8, -1).toLowerCase();
334
+ return objType;
335
+ } else {
336
+ return typeof type;
337
+ }
338
+ }
339
+ function sleep(delay = 0, fn) {
340
+ return new Promise(
341
+ (resolve) => setTimeout(() => {
342
+ fn?.();
343
+ resolve();
344
+ }, delay)
345
+ );
346
+ }
347
+ function validate(type = "required", rules = {}, pureValid = false) {
348
+ if (getType(type) === "object") {
349
+ pureValid = rules || false;
350
+ rules = type;
351
+ type = "required";
352
+ }
353
+ let trigger = rules.trigger || [];
354
+ const typeMaps = ["required", "pwd", "number", "mobile", "between", "length", "same", "ip", "port", "custom"];
355
+ let parseRequired = rules.required ?? true;
356
+ if (!typeMaps.includes(type)) {
357
+ return {
358
+ required: parseRequired,
359
+ message: type,
360
+ trigger
361
+ };
362
+ }
363
+ if (type === "required") {
364
+ return {
365
+ required: parseRequired,
366
+ message: rules.message ?? "\u8BF7\u8F93\u5165",
367
+ trigger
368
+ };
369
+ }
370
+ if (type === "password") {
371
+ const validateName = (rule, value, callback) => {
372
+ let validFlag = /^[a-zA-Z0-9_-]+$/.test(value);
373
+ if (!validFlag) {
374
+ callback(new Error(rules.message || "\u5BC6\u7801\u53EA\u80FD\u7531\u82F1\u6587\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u4E2D\u5212\u7EBF\u7EC4\u6210"));
375
+ } else {
376
+ callback();
377
+ }
378
+ };
379
+ return {
380
+ validator: validateName,
381
+ trigger
382
+ };
383
+ }
384
+ if (type === "positive" || type === "number") {
385
+ return _validValue(rules, "\u8BF7\u8F93\u5165\u6B63\u6574\u6570", pureValid, /^[1-9]+\d*$/);
386
+ }
387
+ if (type === "zeroPositive") {
388
+ return _validValue(rules, "\u8BF7\u8F93\u5165\u975E\u8D1F\u6574\u6570", pureValid, /^(0|[1-9]+\d*)$/);
389
+ }
390
+ if (type === "integer") {
391
+ return _validValue(rules, "\u8BF7\u8F93\u5165\u6574\u6570", pureValid, /^(0|[-]?[1-9]\d*)$/);
392
+ }
393
+ if (type === "decimal") {
394
+ return _validValue(rules, "\u8BF7\u8F93\u5165\u975E\u8D1F\u6570\u5B57, \u5305\u542B\u5C0F\u6570\u4E14\u6700\u591A2\u4F4D", pureValid, /(0|[1-9]\d*)(\.\d{1, 2})?|0\.\d{1,2}/);
395
+ }
396
+ if (type === "mobile") {
397
+ return _validValue(rules, "\u8BF7\u8F93\u5165\u6B63\u786E\u7684\u624B\u673A\u53F7", pureValid, /^[1][0-9]{10}$/);
398
+ }
399
+ if (type === "ip") {
400
+ return _validValue(
401
+ rules,
402
+ "\u8BF7\u8F93\u5165\u6B63\u786E\u7684ip\u5730\u5740",
403
+ pureValid,
404
+ /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
405
+ );
406
+ }
407
+ if (type === "between") {
408
+ let min = rules.min || 1;
409
+ let max = rules.max || 10;
410
+ const validateBetween = (rule, value, callback) => {
411
+ let validFlag = /^[0-9]+$/.test(value);
412
+ if (!validFlag) {
413
+ callback(new Error("\u8BF7\u8F93\u5165\u6570\u5B57"));
414
+ }
415
+ if (value < min) {
416
+ callback(new Error(`\u6570\u5B57\u4E0D\u80FD\u5C0F\u4E8E${min}`));
417
+ }
418
+ if (value > max) {
419
+ callback(new Error(`\u6570\u5B57\u4E0D\u80FD\u5927\u4E8E${max}`));
420
+ }
421
+ callback();
422
+ };
423
+ return {
424
+ validator: validateBetween,
425
+ trigger,
426
+ required: parseRequired
427
+ };
428
+ }
429
+ if (type === "length") {
430
+ return {
431
+ min: rules.min,
432
+ max: rules.max,
433
+ message: rules.message ?? `\u8BF7\u8F93\u5165${rules.min}\u5230${rules.max}\u4E2A\u5B57\u7B26`,
434
+ trigger,
435
+ required: parseRequired
436
+ };
437
+ }
438
+ if (type === "port") {
439
+ return _validValue(
440
+ rules,
441
+ "\u8BF7\u8F93\u51651-65535\u7684\u7AEF\u53E3\u53F7",
442
+ pureValid,
443
+ /^([1-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-5][0-5][0-3][0-5])$/
444
+ );
445
+ }
446
+ if (type === "same") {
447
+ const validateSame = (rule, value, callback) => {
448
+ let isSame = value === rules.value;
449
+ if (!isSame) {
450
+ const errMessage = rules.message || "\u5BC6\u7801\u548C\u786E\u8BA4\u5BC6\u7801\u8981\u4E00\u81F4";
451
+ callback(new Error(errMessage));
452
+ }
453
+ if (parseRequired && !value) {
454
+ callback(new Error(rules.message || "\u8BF7\u8F93\u5165"));
455
+ }
456
+ callback();
457
+ };
458
+ let res = {
459
+ validator: validateSame,
460
+ trigger,
461
+ required: parseRequired
462
+ };
463
+ return res;
464
+ }
465
+ if (type === "custom") {
466
+ if (pureValid) {
467
+ return _validValue(rules.value, rules.message, pureValid, rules.reg);
468
+ } else {
469
+ return _validValue(rules, rules.message, pureValid, rules.reg);
470
+ }
471
+ }
472
+ function _validValue(rules2, msg, pureValid2, reg) {
473
+ if (pureValid2 === true) {
474
+ return reg.test(rules2);
475
+ }
476
+ const validatePhone = (rule, value, callback) => {
477
+ let validFlag = reg.test(value);
478
+ if (!validFlag) {
479
+ callback(new Error(rules2.message ?? msg));
480
+ } else {
481
+ callback();
482
+ }
483
+ };
484
+ return {
485
+ validator: validatePhone,
486
+ required: rules2.required ?? true,
487
+ trigger
488
+ };
489
+ }
490
+ }
491
+ async function asyncWrapper(func, ...args) {
492
+ try {
493
+ const res = await func(...args);
494
+ return { res };
495
+ } catch (err) {
496
+ return { err };
497
+ }
498
+ }
499
+ function formatImg(photoName, addPath = "", { basePath = "assets/images" } = {}) {
500
+ if (photoName.startsWith("http") || photoName.startsWith("https")) {
501
+ return photoName;
502
+ }
503
+ if (photoName.indexOf(".") === -1) {
504
+ photoName = photoName + ".png";
505
+ }
506
+ const addLastSlash = addPath.endsWith("/") || !addPath ? addPath : `${addPath}/`;
507
+ const addLastBasePathSlash = basePath.endsWith("/") || !basePath ? basePath : `${basePath}/`;
508
+ let mergeSrc = `${addLastSlash}${photoName}`;
509
+ let res = new URL(`../${addLastBasePathSlash}${mergeSrc}`, import.meta.url).href;
510
+ return res;
511
+ }
512
+ const copy = (text, toastParams = {}) => {
513
+ const textarea = document.createElement("textarea");
514
+ textarea.value = text;
515
+ textarea.style.position = "fixed";
516
+ document.body.appendChild(textarea);
517
+ textarea.select();
518
+ document.execCommand("copy");
519
+ document.body.removeChild(textarea);
520
+ if (!toastParams.hideToast) {
521
+ $toast(text + "\u590D\u5236\u6210\u529F", toastParams);
522
+ }
523
+ };
524
+ function formatThousands(number) {
525
+ let matches = ("" + number).match(/^([\d,]+)(\.?)(\d+)?(\D+)?$/);
526
+ if (!matches) {
527
+ return number;
528
+ }
529
+ let numericString = matches[1].replace(/\D/g, "");
530
+ let decimalString = matches[3] ? `.${matches[3]}` : "";
531
+ let unit = matches[4] || "";
532
+ let numberWithSeparator = numericString.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
533
+ return `${numberWithSeparator}${decimalString}${unit}`;
534
+ }
535
+ function log(variableStr, variable, otherInfo = "") {
536
+ const stack = new Error().stack.split("\n")[2].trim();
537
+ const matchResult = stack.match(/\((.*):(\d+):(\d+)\)/);
538
+ let fileInfo = "";
539
+ try {
540
+ if (matchResult && otherInfo) {
541
+ const lineNumber = matchResult[2];
542
+ fileInfo = `vscode://file${JSON.parse(otherInfo)}:${lineNumber}`;
543
+ }
544
+ } catch (error) {
545
+ fileInfo = otherInfo;
546
+ }
547
+ if (isRef(variable)) {
548
+ let unrefVariable = unref(variable);
549
+ _log(toRaw(unrefVariable));
550
+ } else {
551
+ _log(variable);
552
+ }
553
+ function _log(consoleData) {
554
+ if (getType2(consoleData) === "object" || getType2(consoleData) === "array") {
555
+ consola.log(
556
+ `%c${variableStr} `,
557
+ "background:#fff; color: blue;font-size: 0.8em",
558
+ JSON.stringify(consoleData, null, " "),
559
+ `${fileInfo}`
560
+ );
561
+ } else {
562
+ consola.log(`%c${variableStr} `, "background:#fff; color: blue;font-size: 0.8em", consoleData, `${fileInfo}`);
563
+ }
564
+ }
565
+ function getType2(type) {
566
+ if (typeof type === "object") {
567
+ const objType = Object.prototype.toString.call(type).slice(8, -1).toLowerCase();
568
+ return objType;
569
+ } else {
570
+ return typeof type;
571
+ }
572
+ }
573
+ }
574
+ function random(min = 0, max = 10) {
575
+ return Math.floor(Math.random() * (max - min + 1)) + min;
576
+ }
577
+ function toLine(text, connect = "-") {
578
+ let translateText = text.replace(/([A-Z])/g, (match, p1, offset, origin) => {
579
+ if (offset === 0) {
580
+ return `${match.toLocaleLowerCase()}`;
581
+ } else {
582
+ return `${connect}${match.toLocaleLowerCase()}`;
583
+ }
584
+ }).toLocaleLowerCase();
585
+ return translateText;
586
+ }
587
+ function processWidth(initValue, isBase = false) {
588
+ let value = unref(initValue);
589
+ let res = "";
590
+ if (!value) {
591
+ return isBase ? value : {};
592
+ } else if (typeof value === "number") {
593
+ value = String(value);
594
+ }
595
+ if (value === "") {
596
+ return isBase ? value : {};
597
+ } else if (typeof value === "string" && !isNaN(value)) {
598
+ res = value + "px";
599
+ } else if (typeof value === "string" && /^[0-9]+(\.[0-9]+)?(px|%|em|rem|vw|vh|ch)*$/.test(value)) {
600
+ res = value;
601
+ } else {
602
+ console.warn(`${value} is Invalid unit provided`);
603
+ return value;
604
+ }
605
+ if (isBase) {
606
+ return res;
607
+ }
608
+ return { width: res };
609
+ }
610
+ function toFixed(value, options = {}) {
611
+ if (typeof options === "number") {
612
+ options = { digit: options };
613
+ }
614
+ let { digit = 2, prefix = "", suffix = "", unit = true } = options;
615
+ let matches = ("" + value).match(/^([\d,]+)(\.?)(\d+)?(\D+)?$/);
616
+ if (!matches) {
617
+ return value;
618
+ }
619
+ let numericString = matches[1].replace(/\D/g, "");
620
+ let decimalString = matches[3] ? `.${matches[3]}` : "";
621
+ let finalUnit = matches[4] || "";
622
+ let res = numericString;
623
+ if (isStringNumber(numericString) || isNumber(numericString)) {
624
+ res = Number(numericString + decimalString).toFixed(digit);
625
+ }
626
+ if (!unit) {
627
+ finalUnit = "";
628
+ }
629
+ return `${prefix}${res}${finalUnit}${suffix}`;
630
+ }
631
+ function formatBytes(bytes, { toFixed: toFixed2 = 2, thousands = true } = {}) {
632
+ if (isStringNumber(bytes) || isNumber(bytes)) {
633
+ bytes = Number(bytes);
634
+ } else {
635
+ return bytes;
636
+ }
637
+ if (bytes <= 0) {
638
+ return bytes.toFixed(toFixed2) + " B";
639
+ }
640
+ const k = 1024;
641
+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
642
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
643
+ let res = (bytes / Math.pow(k, i)).toFixed(toFixed2) + " " + sizes[i];
644
+ if (thousands) {
645
+ res = formatThousands(res);
646
+ }
647
+ return res;
648
+ }
649
+ function formatBytesConvert(oBytes, { thounsand = false, toFixed: toFixed2 = 0 } = {}) {
650
+ if (isStringNumber(oBytes) || isNumber(oBytes) || getType(oBytes) !== "string") {
651
+ return oBytes;
652
+ }
653
+ if (!oBytes) {
654
+ return oBytes;
655
+ }
656
+ const regex = /^\d{1,3}(,\d{3})*(\.\d+)?[a-zA-Z ]*$/;
657
+ let bytes = oBytes;
658
+ if (regex.test(oBytes)) {
659
+ bytes = oBytes.replace(/,/g, "");
660
+ if (isStringNumber(bytes) || isNumber(bytes) || getType(bytes) !== "string") {
661
+ return bytes;
662
+ }
663
+ }
664
+ const bytesRegex = /^(\d+(?:\.\d+)?)\s*([BKMGTPEZY]?B|Byte)$/i;
665
+ const units = {
666
+ B: 1,
667
+ BYTE: 1,
668
+ KB: 1024,
669
+ MB: 1024 ** 2,
670
+ GB: 1024 ** 3,
671
+ TB: 1024 ** 4,
672
+ PB: 1024 ** 5,
673
+ EB: 1024 ** 6,
674
+ ZB: 1024 ** 7,
675
+ YB: 1024 ** 8
676
+ };
677
+ const match = bytes.match(bytesRegex);
678
+ if (!match) {
679
+ console.warn("Invalid bytes format. Please provide a valid bytes string, like '100GB'.");
680
+ return;
681
+ }
682
+ const size = parseFloat(match[1]);
683
+ const unit = match[2].toUpperCase();
684
+ if (!units.hasOwnProperty(unit)) {
685
+ console.warn(
686
+ "Invalid bytes unit. Please provide a valid unit, like 'B', 'BYTE', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', or 'YB'."
687
+ );
688
+ return;
689
+ }
690
+ let finalRes = size * units[unit];
691
+ if (toFixed2) {
692
+ finalRes = parseFloat(finalRes.toFixed(toFixed2));
693
+ }
694
+ if (thounsand) {
695
+ finalRes = formatThousands(finalRes);
696
+ }
697
+ return finalRes;
698
+ }
699
+ function throttle(fn, delay = 1e3) {
700
+ let last = 0;
701
+ let timer = null;
702
+ return function() {
703
+ let context = this;
704
+ let args = arguments;
705
+ let now = +/* @__PURE__ */ new Date();
706
+ if (now - last < delay) {
707
+ clearTimeout(timer);
708
+ timer = setTimeout(function() {
709
+ last = now;
710
+ fn.apply(context, args);
711
+ }, delay);
712
+ } else {
713
+ last = now;
714
+ fn.apply(context, args);
715
+ }
716
+ };
717
+ }
718
+ function debounce(fn, delay = 1e3) {
719
+ let timer = null;
720
+ return function() {
721
+ if (timer) {
722
+ clearTimeout(timer);
723
+ }
724
+ timer = setTimeout(() => {
725
+ fn.apply(this, arguments);
726
+ timer = null;
727
+ }, delay);
728
+ };
729
+ }
730
+ function confirm(message, options) {
731
+ const resolvedMessage = typeof message === "function" ? message() : message;
732
+ const elContext = ElMessageBox.install?.context || ElMessageBox._context || document.querySelector("#app")?._vue_app?._context;
733
+ const mergeOptions = {
734
+ title: "\u63D0\u793A",
735
+ draggable: true,
736
+ showCancelButton: false,
737
+ confirmButtonText: "\u786E\u5B9A",
738
+ dangerouslyUseHTMLString: true,
739
+ // 允许 HTML
740
+ appContext: elContext,
741
+ // 强制注入 Element Plus 的上下文
742
+ ...options
743
+ };
744
+ return ElMessageBox.confirm(resolvedMessage, mergeOptions);
745
+ }
746
+ function formatNewLines(str) {
747
+ if (!str || typeof str !== "string") {
748
+ return str;
749
+ }
750
+ str = str.replace(/\n/g, "<br>");
751
+ str = str.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
752
+ return str;
753
+ }
754
+ function getVariable(propertyName) {
755
+ let res = getComputedStyle(document.documentElement).getPropertyValue(propertyName).trim();
756
+ return res;
757
+ }
17
758
 
18
- export const isString = _module.isString;
19
- export const isStringNumber = _module.isStringNumber;
20
- export const isNumber = _module.isNumber;
21
- export const $toast = _module.$toast;
22
- export const type = _module.type;
23
- export const otherParams = _module.otherParams;
24
- export const setStorage = _module.setStorage;
25
- export const params = _module.params;
26
- export const isSession = _module.isSession;
27
- export const getStorage = _module.getStorage;
28
- export const clearStorage = _module.clearStorage;
29
- export const validForm = _module.validForm;
30
- export const detail = _module.detail;
31
- export const showMessage = _module.showMessage;
32
- export const isEmpty = _module.isEmpty;
33
- export const notEmpty = _module.notEmpty;
34
- export const merge = _module.merge;
35
- export const obj2 = _module.obj2;
36
- export const clone = _module.clone;
37
- export const times = _module.times;
38
- export const formatTime = _module.formatTime;
39
- export const cFormat = _module.cFormat;
40
- export const formatDurationTime = _module.formatDurationTime;
41
- export const uuid = _module.uuid;
42
- export const getType = _module.getType;
43
- export const sleep = _module.sleep;
44
- export const fn = _module.fn;
45
- export const validate = _module.validate;
46
- export const rules = _module.rules;
47
- export const pureValid = _module.pureValid;
48
- export const asyncWrapper = _module.asyncWrapper;
49
- export const formatImg = _module.formatImg;
50
- export const addPath = _module.addPath;
51
- export const copy = _module.copy;
52
- export const toastParams = _module.toastParams;
53
- export const formatThousands = _module.formatThousands;
54
- export const log = _module.log;
55
- export const variable = _module.variable;
56
- export const otherInfo = _module.otherInfo;
57
- export const random = _module.random;
58
- export const max = _module.max;
59
- export const toLine = _module.toLine;
60
- export const connect = _module.connect;
61
- export const processWidth = _module.processWidth;
62
- export const isBase = _module.isBase;
63
- export const toFixed = _module.toFixed;
64
- export const digits = _module.digits;
65
- export const formatBytes = _module.formatBytes;
66
- export const thousands = _module.thousands;
67
- export const formatBytesConvert = _module.formatBytesConvert;
68
- export const throttle = _module.throttle;
69
- export const delay = _module.delay;
70
- export const debounce = _module.debounce;
71
- export const confirm = _module.confirm;
72
- export const options = _module.options;
73
- export const formatNewLines = _module.formatNewLines;
74
- export const getVariable = _module.getVariable;
759
+ export { $toast, asyncWrapper, clearStorage, clone, confirm, copy, debounce, formatBytes, formatBytesConvert, formatDurationTime, formatImg, formatNewLines, formatThousands, formatTime, getStorage, getType, getVariable, isEmpty, isNumber, isString, isStringNumber, log, merge, notEmpty, processWidth, random, setStorage, sleep, throttle, toFixed, toLine, uuid, validForm, validate };