@sybz-components/utils 0.0.8 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { isRef, unref, toRaw } from '@vue/reactivity';
1
+ import { isRef, unref, toRaw } from 'vue';
2
2
  import { consola } from 'consola';
3
3
  import { cloneDeep } from 'es-toolkit';
4
4
  import { ElMessage, ElMessageBox } from 'element-plus';
@@ -47,9 +47,10 @@ function formatBytesConvert(oBytes, options = {}) {
47
47
  }
48
48
  const regex = /^\d{1,3}(,\d{3})*(\.\d+)?[a-zA-Z ]*$/;
49
49
  if (typeof oBytes === "string" && regex.test(oBytes)) {
50
- bytes = oBytes.replace(/,/g, "");
51
- if (isStringNumber(bytes) || isNumber(bytes) || getType(bytes) !== "string") {
52
- return parseDigitThounsands(bytes);
50
+ const normalizedBytes = oBytes.replace(/,/g, "");
51
+ bytes = normalizedBytes;
52
+ if (isStringNumber(normalizedBytes) || isNumber(normalizedBytes) || getType(normalizedBytes) !== "string") {
53
+ return parseDigitThounsands(normalizedBytes);
53
54
  }
54
55
  }
55
56
  const bytesRegex = /^(\d+(?:\.\d+)?)\s*([BKMGTPEZY]?B|Byte)$/i;
@@ -70,13 +71,13 @@ function formatBytesConvert(oBytes, options = {}) {
70
71
  }
71
72
  const match = bytes.match(bytesRegex);
72
73
  if (!match) {
73
- console.warn("Invalid bytes format. Please provide a valid bytes string, like '100GB'.");
74
+ consola.warn("Invalid bytes format. Please provide a valid bytes string, like '100GB'.");
74
75
  return;
75
76
  }
76
77
  const size = parseFloat(match[1]);
77
78
  const unit = match[2].toUpperCase();
78
79
  if (!Object.prototype.hasOwnProperty.call(units, unit)) {
79
- console.warn(
80
+ consola.warn(
80
81
  "Invalid bytes unit. Please provide a valid unit, like 'B', 'BYTE', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', or 'YB'."
81
82
  );
82
83
  return;
@@ -224,9 +225,8 @@ function formatTextToHtml(str) {
224
225
  if (!str || typeof str !== "string") {
225
226
  return str;
226
227
  }
227
- str = str.replace(/\n/g, "<br>");
228
- str = str.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
229
- return str;
228
+ const withBreaks = str.replace(/\n/g, "<br>");
229
+ return withBreaks.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
230
230
  }
231
231
 
232
232
  const DEFAULT_CONFIRM_BUTTON_CLASS = "s-message-box__confirm-btn";
@@ -240,7 +240,7 @@ function _getBrowserStorage(isSession = false) {
240
240
  }
241
241
  try {
242
242
  return isSession ? window.sessionStorage : window.localStorage;
243
- } catch (error) {
243
+ } catch {
244
244
  return null;
245
245
  }
246
246
  }
@@ -253,7 +253,7 @@ function _parseStorageValue(value) {
253
253
  if (typeof parsed !== "number") {
254
254
  return parsed;
255
255
  }
256
- } catch (error) {
256
+ } catch {
257
257
  }
258
258
  return value;
259
259
  }
@@ -335,8 +335,8 @@ function clearStorage(str = "") {
335
335
  sessionStorageRef?.clear();
336
336
  localStorageRef?.clear();
337
337
  }
338
- if (!isEmpty(str) && getType(str) !== "object") {
339
- let strArr = Array.isArray(str) ? str : [str];
338
+ if (typeof str === "string" || Array.isArray(str)) {
339
+ const strArr = Array.isArray(str) ? str : [str];
340
340
  for (let i = 0; i < strArr.length; i++) {
341
341
  sessionStorageRef?.removeItem(strArr[i]);
342
342
  localStorageRef?.removeItem(strArr[i]);
@@ -344,16 +344,18 @@ function clearStorage(str = "") {
344
344
  }
345
345
  if (_isObjectWithExclude(str)) {
346
346
  if (!isEmpty(str.exclude) && getType(str) === "object") {
347
- let sessionStorageObj = {};
348
- let localStorageObj = {};
347
+ const sessionStorageObj = {};
348
+ const localStorageObj = {};
349
349
  for (const key in str.exclude) {
350
350
  if (Object.prototype.hasOwnProperty.call(str.exclude, key)) {
351
351
  const name = str.exclude[key];
352
- if (getStorage(name)) {
353
- localStorageObj[name] = getStorage(name);
352
+ const localValue = getStorage(name);
353
+ const sessionValue = getStorage(name, true);
354
+ if (localValue !== null) {
355
+ localStorageObj[name] = localValue;
354
356
  }
355
- if (getStorage(name, true)) {
356
- sessionStorageObj[name] = getStorage(name, true);
357
+ if (sessionValue !== null) {
358
+ sessionStorageObj[name] = sessionValue;
357
359
  }
358
360
  }
359
361
  }
@@ -369,9 +371,9 @@ function clearStorage(str = "") {
369
371
  }
370
372
  }
371
373
  function _isObjectWithExclude(obj) {
372
- return typeof obj === "object" && obj !== null && "exclude" in obj && typeof obj.exclude === "object";
374
+ return typeof obj === "object" && obj !== null && "exclude" in obj && Array.isArray(obj.exclude);
373
375
  }
374
- function validForm(ref, { message = "\u8868\u5355\u6821\u9A8C\u9519\u8BEF, \u8BF7\u68C0\u67E5", detail = false, showMessage = true } = {}) {
376
+ function validateForm(ref, { message = "\u8868\u5355\u6821\u9A8C\u9519\u8BEF, \u8BF7\u68C0\u67E5", detail = false, showMessage = true } = {}) {
375
377
  return new Promise((resolve, reject) => {
376
378
  unref(ref).validate((valid, status) => {
377
379
  if (valid) {
@@ -429,7 +431,7 @@ function isEmpty(data, strict = true) {
429
431
  return false;
430
432
  }
431
433
  function merge(obj1, obj2) {
432
- let merged = { ...obj1, ...obj2 };
434
+ const merged = { ...obj1, ...obj2 };
433
435
  for (let key in merged) {
434
436
  if (!isEmpty(obj1[key]) && !isEmpty(obj2[key])) {
435
437
  merged[key] = obj2[key];
@@ -442,20 +444,18 @@ function merge(obj1, obj2) {
442
444
  return merged;
443
445
  }
444
446
  function clone(data, times = 1) {
445
- if (isRef(data)) {
446
- data = unref(data);
447
- }
448
- if (getType(data) !== "array") {
449
- return cloneDeep(data);
447
+ const rawData = isRef(data) ? unref(data) : data;
448
+ if (!Array.isArray(rawData)) {
449
+ return cloneDeep(rawData);
450
450
  }
451
- const clonedData = cloneDeep(data);
451
+ const clonedData = cloneDeep(rawData);
452
452
  const result = [];
453
453
  for (let i = 0; i < times; i++) {
454
454
  result.push(...clonedData);
455
455
  }
456
456
  return result;
457
457
  }
458
- function uuid(type = "", length = 4, options = {}) {
458
+ function mockValue(type = "", length = 4, options = {}) {
459
459
  const { emailStr = "@qq.com", timeStr = "{y}-{m}-{d} {h}:{i}:{s}", startStr = "", optionsIndex = null } = options;
460
460
  function isRef2(obj) {
461
461
  return obj && typeof obj === "object" && obj._isRef === true;
@@ -487,11 +487,11 @@ function uuid(type = "", length = 4, options = {}) {
487
487
  return result;
488
488
  }
489
489
  if (type === "email") {
490
- result = uuid(startStr, length) + emailStr;
490
+ result = mockValue(startStr, length) + emailStr;
491
491
  return result;
492
492
  }
493
493
  if (type === "time") {
494
- return uuid(startStr, length, options) + " " + formatTime(/* @__PURE__ */ new Date(), timeStr);
494
+ return mockValue(startStr, length, options) + " " + formatTime(/* @__PURE__ */ new Date(), timeStr);
495
495
  }
496
496
  if (type === "number") {
497
497
  const numChars = "123456789";
@@ -521,12 +521,12 @@ function getType(type) {
521
521
  return typeof type;
522
522
  }
523
523
  }
524
- function sleep(delay = 0, fn) {
524
+ function delay(delay2 = 0, fn) {
525
525
  return new Promise(
526
526
  (resolve) => setTimeout(() => {
527
527
  fn?.();
528
528
  resolve();
529
- }, delay)
529
+ }, delay2)
530
530
  );
531
531
  }
532
532
  function validateTrigger(type = "required", rules = {}, pureValid = false) {
@@ -622,18 +622,18 @@ function validate(type = "required", rules = {}, pureValid = false) {
622
622
  );
623
623
  }
624
624
  if (type === "between" /* BETWEEN */) {
625
- let min = rulesObject.min;
626
- let max = rulesObject.max;
625
+ let minValue = rulesObject.min ?? "";
626
+ let maxValue = rulesObject.max ?? "";
627
627
  const validateBetween = (rule, value, callback) => {
628
628
  let validFlag = /^-?[0-9]+$/.test(value);
629
629
  if (!validFlag) {
630
630
  callback(new Error("\u8BF7\u8F93\u5165\u6570\u5B57"));
631
631
  }
632
- if (value < min && min !== void 0) {
633
- callback(new Error(`\u6570\u5B57\u4E0D\u80FD\u5C0F\u4E8E${min}`));
632
+ if (!isEmpty(minValue) && value < minValue) {
633
+ callback(new Error(`\u6570\u5B57\u4E0D\u80FD\u5C0F\u4E8E${minValue}`));
634
634
  }
635
- if (value > max && max !== void 0) {
636
- callback(new Error(`\u6570\u5B57\u4E0D\u80FD\u5927\u4E8E${max}`));
635
+ if (!isEmpty(maxValue) && value > maxValue && maxValue !== void 0) {
636
+ callback(new Error(`\u6570\u5B57\u4E0D\u80FD\u5927\u4E8E${maxValue}`));
637
637
  }
638
638
  callback();
639
639
  };
@@ -696,6 +696,7 @@ function validate(type = "required", rules = {}, pureValid = false) {
696
696
  trigger
697
697
  };
698
698
  }
699
+ return {};
699
700
  }
700
701
  const copy = (text, toastParams = {}) => {
701
702
  const textarea = document.createElement("textarea");
@@ -706,14 +707,14 @@ const copy = (text, toastParams = {}) => {
706
707
  document.execCommand("copy");
707
708
  document.body.removeChild(textarea);
708
709
  if (!toastParams.hideToast) {
709
- const { hideToast, ...toastOptions } = toastParams;
710
+ const { hideToast: _hideToast, ...toastOptions } = toastParams;
710
711
  $toast(text + "\u590D\u5236\u6210\u529F", toastOptions);
711
712
  return true;
712
713
  }
713
714
  return true;
714
715
  };
715
716
  function log(variableStr, variable, otherInfo = "") {
716
- const stack = new Error().stack.split("\n")[2].trim();
717
+ const stack = new Error().stack?.split("\n")[2]?.trim() ?? "";
717
718
  const matchResult = stack.match(/\((.*):(\d+):(\d+)\)/);
718
719
  let fileInfo = "";
719
720
  try {
@@ -721,11 +722,11 @@ function log(variableStr, variable, otherInfo = "") {
721
722
  const lineNumber = matchResult[2];
722
723
  fileInfo = `vscode://file${JSON.parse(otherInfo)}:${lineNumber}`;
723
724
  }
724
- } catch (error) {
725
+ } catch {
725
726
  fileInfo = otherInfo;
726
727
  }
727
728
  if (isRef(variable)) {
728
- let unrefVariable = unref(variable);
729
+ const unrefVariable = unref(variable);
729
730
  _log(toRaw(unrefVariable));
730
731
  } else {
731
732
  _log(variable);
@@ -755,7 +756,7 @@ function random(min = 0, max = 10) {
755
756
  return Math.floor(Math.random() * (max - min + 1)) + min;
756
757
  }
757
758
  function toLine(text, connect = "-") {
758
- let translateText = text.replace(/([A-Z])/g, (match, p1, offset, origin) => {
759
+ let translateText = text.replace(/([A-Z])/g, (match, _letter, offset) => {
759
760
  if (offset === 0) {
760
761
  return `${match.toLocaleLowerCase()}`;
761
762
  } else {
@@ -781,18 +782,18 @@ function processWidth(initValue, isBase = false) {
781
782
  }
782
783
  return isBase ? res : { width: res };
783
784
  }
784
- function throttle(fn, delay = 1e3) {
785
+ function throttle(fn, delay2 = 1e3) {
785
786
  let last = 0;
786
787
  let timer = void 0;
787
788
  return function(...args) {
788
789
  let context = this;
789
790
  let now = +/* @__PURE__ */ new Date();
790
- if (now - last < delay) {
791
+ if (now - last < delay2) {
791
792
  clearTimeout(timer);
792
793
  timer = setTimeout(function() {
793
794
  last = now;
794
795
  fn.apply(context, args);
795
- }, delay);
796
+ }, delay2);
796
797
  } else {
797
798
  last = now;
798
799
  fn.apply(context, args);
@@ -804,7 +805,7 @@ async function tryCatch(task, sendLoading) {
804
805
  if (isRef(sendLoading)) {
805
806
  sendLoading.value = value;
806
807
  } else if (sendLoading !== void 0 && sendLoading !== null) {
807
- console.warn("Cannot modify non-ref sendLoading directly!");
808
+ consola.warn("Cannot modify non-ref sendLoading directly!");
808
809
  }
809
810
  };
810
811
  updateLoading(true);
@@ -817,7 +818,7 @@ async function tryCatch(task, sendLoading) {
817
818
  updateLoading(false);
818
819
  }
819
820
  }
820
- function debounce(func, delay = 500, immediate, resultCallback) {
821
+ function debounce(func, delay2 = 500, immediate, resultCallback) {
821
822
  let timer = null;
822
823
  let isInvoke = false;
823
824
  const _debounce = function(...args) {
@@ -843,7 +844,7 @@ function debounce(func, delay = 500, immediate, resultCallback) {
843
844
  }
844
845
  isInvoke = false;
845
846
  timer = null;
846
- }, delay);
847
+ }, delay2);
847
848
  }
848
849
  });
849
850
  };
@@ -907,7 +908,7 @@ function _resolveAppendTarget(appendTo) {
907
908
  try {
908
909
  const selector = rawSelector.startsWith("#") || rawSelector.startsWith(".") || rawSelector.startsWith("[") ? rawSelector : `#${rawSelector}`;
909
910
  return document.querySelector(selector) || appendTo;
910
- } catch (error) {
911
+ } catch {
911
912
  return appendTo;
912
913
  }
913
914
  }
@@ -926,10 +927,14 @@ function _resolveAppContext(appContext) {
926
927
  if (appContext) {
927
928
  return appContext;
928
929
  }
930
+ const installWithContext = ElMessageBox.install;
931
+ const messageBoxWithContext = ElMessageBox;
932
+ const elementPlusContext = installWithContext?.context || messageBoxWithContext._context || null;
929
933
  if (typeof document === "undefined") {
930
- return ElMessageBox.install?.context || ElMessageBox._context;
934
+ return elementPlusContext;
931
935
  }
932
- return ElMessageBox.install?.context || ElMessageBox._context || document.querySelector("#app")?._vue_app?._context;
936
+ const appRoot = document.querySelector("#app");
937
+ return elementPlusContext || appRoot?._vue_app?._context || null;
933
938
  }
934
939
  function getVariable(propertyName, fallback = "") {
935
940
  if (typeof document === "undefined") {
@@ -941,11 +946,11 @@ function getVariable(propertyName, fallback = "") {
941
946
  const DEFAULT_BUILD_TIME_FALLBACK = "\u672A\u6CE8\u5165";
942
947
  function getUtilsBuildTime(fallback = DEFAULT_BUILD_TIME_FALLBACK) {
943
948
  {
944
- return "2026-06-18 15:18:56";
949
+ return "2026-07-01 13:13:26";
945
950
  }
946
951
  }
947
952
  function test() {
948
953
  return `build time: ${getUtilsBuildTime()}`;
949
954
  }
950
955
 
951
- export { $toast as $, formatDurationTime as A, formatImg as B, formatTextToHtml as C, formatThousands as D, formatTime as E, formatToFixed as F, clone as a, confirm as b, clearStorage as c, copy as d, debounce as e, getType as f, getStorage as g, getUtilsBuildTime as h, getVariable as i, isEmpty as j, sleep as k, log as l, merge as m, throttle as n, toLine as o, processWidth as p, tryCatch as q, random as r, setStorage as s, test as t, uuid as u, validForm as v, validate as w, validateTrigger as x, formatBytes as y, formatBytesConvert as z };
956
+ export { $toast as $, formatDurationTime as A, formatImg as B, formatTextToHtml as C, formatThousands as D, formatTime as E, formatToFixed as F, clone as a, confirm as b, clearStorage as c, copy as d, debounce as e, delay as f, getStorage as g, getType as h, getUtilsBuildTime as i, getVariable as j, isEmpty as k, log as l, merge as m, mockValue as n, throttle as o, processWidth as p, toLine as q, random as r, setStorage as s, test as t, tryCatch as u, validate as v, validateForm as w, validateTrigger as x, formatBytes as y, formatBytesConvert as z };
package/dist/ws.cjs CHANGED
@@ -134,7 +134,7 @@ class WS {
134
134
  try {
135
135
  const res = JSON.parse(data.data);
136
136
  callback(res);
137
- } catch (err) {
137
+ } catch {
138
138
  callback(data);
139
139
  }
140
140
  };
package/dist/ws.mjs CHANGED
@@ -128,7 +128,7 @@ class WS {
128
128
  try {
129
129
  const res = JSON.parse(data.data);
130
130
  callback(res);
131
- } catch (err) {
131
+ } catch {
132
132
  callback(data);
133
133
  }
134
134
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sybz-components/utils",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "description": "utils of sybz-components",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
package/dist/test.cjs DELETED
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- function onlyTest() {
4
- return "test";
5
- }
6
-
7
- exports.onlyTest = onlyTest;
package/dist/test.d.cts DELETED
@@ -1,14 +0,0 @@
1
- /**
2
- * 返回当前测试占位字符串。
3
- *
4
- * 这个方法主要用于确认工具函数导出链路是否正常。
5
- *
6
- * @returns 固定字符串 `test`。
7
- *
8
- * @example
9
- * onlyTest()
10
- * // => 'test'
11
- */
12
- declare function onlyTest(): string;
13
-
14
- export { onlyTest };
package/dist/test.d.mts DELETED
@@ -1,14 +0,0 @@
1
- /**
2
- * 返回当前测试占位字符串。
3
- *
4
- * 这个方法主要用于确认工具函数导出链路是否正常。
5
- *
6
- * @returns 固定字符串 `test`。
7
- *
8
- * @example
9
- * onlyTest()
10
- * // => 'test'
11
- */
12
- declare function onlyTest(): string;
13
-
14
- export { onlyTest };
package/dist/test.d.ts DELETED
@@ -1,14 +0,0 @@
1
- /**
2
- * 返回当前测试占位字符串。
3
- *
4
- * 这个方法主要用于确认工具函数导出链路是否正常。
5
- *
6
- * @returns 固定字符串 `test`。
7
- *
8
- * @example
9
- * onlyTest()
10
- * // => 'test'
11
- */
12
- declare function onlyTest(): string;
13
-
14
- export { onlyTest };
package/dist/test.mjs DELETED
@@ -1,5 +0,0 @@
1
- function onlyTest() {
2
- return "test";
3
- }
4
-
5
- export { onlyTest };