@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,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const reactivity = require('@vue/reactivity');
3
+ const vue = require('vue');
4
4
  const consola = require('consola');
5
5
  const esToolkit = require('es-toolkit');
6
6
  const elementPlus = require('element-plus');
@@ -50,9 +50,10 @@ function formatBytesConvert(oBytes, options = {}) {
50
50
  }
51
51
  const regex = /^\d{1,3}(,\d{3})*(\.\d+)?[a-zA-Z ]*$/;
52
52
  if (typeof oBytes === "string" && regex.test(oBytes)) {
53
- bytes = oBytes.replace(/,/g, "");
54
- if (is.isStringNumber(bytes) || is.isNumber(bytes) || getType(bytes) !== "string") {
55
- return parseDigitThounsands(bytes);
53
+ const normalizedBytes = oBytes.replace(/,/g, "");
54
+ bytes = normalizedBytes;
55
+ if (is.isStringNumber(normalizedBytes) || is.isNumber(normalizedBytes) || getType(normalizedBytes) !== "string") {
56
+ return parseDigitThounsands(normalizedBytes);
56
57
  }
57
58
  }
58
59
  const bytesRegex = /^(\d+(?:\.\d+)?)\s*([BKMGTPEZY]?B|Byte)$/i;
@@ -73,13 +74,13 @@ function formatBytesConvert(oBytes, options = {}) {
73
74
  }
74
75
  const match = bytes.match(bytesRegex);
75
76
  if (!match) {
76
- console.warn("Invalid bytes format. Please provide a valid bytes string, like '100GB'.");
77
+ consola.consola.warn("Invalid bytes format. Please provide a valid bytes string, like '100GB'.");
77
78
  return;
78
79
  }
79
80
  const size = parseFloat(match[1]);
80
81
  const unit = match[2].toUpperCase();
81
82
  if (!Object.prototype.hasOwnProperty.call(units, unit)) {
82
- console.warn(
83
+ consola.consola.warn(
83
84
  "Invalid bytes unit. Please provide a valid unit, like 'B', 'BYTE', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', or 'YB'."
84
85
  );
85
86
  return;
@@ -189,7 +190,7 @@ function formatImg(photoName, addPath = "", { basePath = "assets/images" } = {})
189
190
  const addLastSlash = addPath.endsWith("/") || !addPath ? addPath : `${addPath}/`;
190
191
  const addLastBasePathSlash = basePath.endsWith("/") || !basePath ? basePath : `${basePath}/`;
191
192
  const mergeSrc = `${addLastSlash}${photoName}`;
192
- return new URL(`../${addLastBasePathSlash}${mergeSrc}`, (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('shared/utils.CDpXB2JP.cjs', document.baseURI).href))).href;
193
+ return new URL(`../${addLastBasePathSlash}${mergeSrc}`, (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('shared/utils.BaNHAtTs.cjs', document.baseURI).href))).href;
193
194
  }
194
195
  function formatToFixed(value, options) {
195
196
  if (typeof options === "number") {
@@ -227,9 +228,8 @@ function formatTextToHtml(str) {
227
228
  if (!str || typeof str !== "string") {
228
229
  return str;
229
230
  }
230
- str = str.replace(/\n/g, "<br>");
231
- str = str.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
232
- return str;
231
+ const withBreaks = str.replace(/\n/g, "<br>");
232
+ return withBreaks.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
233
233
  }
234
234
 
235
235
  const DEFAULT_CONFIRM_BUTTON_CLASS = "s-message-box__confirm-btn";
@@ -243,7 +243,7 @@ function _getBrowserStorage(isSession = false) {
243
243
  }
244
244
  try {
245
245
  return isSession ? window.sessionStorage : window.localStorage;
246
- } catch (error) {
246
+ } catch {
247
247
  return null;
248
248
  }
249
249
  }
@@ -256,7 +256,7 @@ function _parseStorageValue(value) {
256
256
  if (typeof parsed !== "number") {
257
257
  return parsed;
258
258
  }
259
- } catch (error) {
259
+ } catch {
260
260
  }
261
261
  return value;
262
262
  }
@@ -338,8 +338,8 @@ function clearStorage(str = "") {
338
338
  sessionStorageRef?.clear();
339
339
  localStorageRef?.clear();
340
340
  }
341
- if (!isEmpty(str) && getType(str) !== "object") {
342
- let strArr = Array.isArray(str) ? str : [str];
341
+ if (typeof str === "string" || Array.isArray(str)) {
342
+ const strArr = Array.isArray(str) ? str : [str];
343
343
  for (let i = 0; i < strArr.length; i++) {
344
344
  sessionStorageRef?.removeItem(strArr[i]);
345
345
  localStorageRef?.removeItem(strArr[i]);
@@ -347,16 +347,18 @@ function clearStorage(str = "") {
347
347
  }
348
348
  if (_isObjectWithExclude(str)) {
349
349
  if (!isEmpty(str.exclude) && getType(str) === "object") {
350
- let sessionStorageObj = {};
351
- let localStorageObj = {};
350
+ const sessionStorageObj = {};
351
+ const localStorageObj = {};
352
352
  for (const key in str.exclude) {
353
353
  if (Object.prototype.hasOwnProperty.call(str.exclude, key)) {
354
354
  const name = str.exclude[key];
355
- if (getStorage(name)) {
356
- localStorageObj[name] = getStorage(name);
355
+ const localValue = getStorage(name);
356
+ const sessionValue = getStorage(name, true);
357
+ if (localValue !== null) {
358
+ localStorageObj[name] = localValue;
357
359
  }
358
- if (getStorage(name, true)) {
359
- sessionStorageObj[name] = getStorage(name, true);
360
+ if (sessionValue !== null) {
361
+ sessionStorageObj[name] = sessionValue;
360
362
  }
361
363
  }
362
364
  }
@@ -372,11 +374,11 @@ function clearStorage(str = "") {
372
374
  }
373
375
  }
374
376
  function _isObjectWithExclude(obj) {
375
- return typeof obj === "object" && obj !== null && "exclude" in obj && typeof obj.exclude === "object";
377
+ return typeof obj === "object" && obj !== null && "exclude" in obj && Array.isArray(obj.exclude);
376
378
  }
377
- function validForm(ref, { message = "\u8868\u5355\u6821\u9A8C\u9519\u8BEF, \u8BF7\u68C0\u67E5", detail = false, showMessage = true } = {}) {
379
+ function validateForm(ref, { message = "\u8868\u5355\u6821\u9A8C\u9519\u8BEF, \u8BF7\u68C0\u67E5", detail = false, showMessage = true } = {}) {
378
380
  return new Promise((resolve, reject) => {
379
- reactivity.unref(ref).validate((valid, status) => {
381
+ vue.unref(ref).validate((valid, status) => {
380
382
  if (valid) {
381
383
  resolve(status);
382
384
  } else {
@@ -401,8 +403,8 @@ function isPlainObject(data) {
401
403
  return proto === Object.prototype || proto === null;
402
404
  }
403
405
  function isEmpty(data, strict = true) {
404
- if (reactivity.isRef(data)) {
405
- data = reactivity.unref(data);
406
+ if (vue.isRef(data)) {
407
+ data = vue.unref(data);
406
408
  }
407
409
  if (data == null) return true;
408
410
  if (data instanceof Date) {
@@ -432,7 +434,7 @@ function isEmpty(data, strict = true) {
432
434
  return false;
433
435
  }
434
436
  function merge(obj1, obj2) {
435
- let merged = { ...obj1, ...obj2 };
437
+ const merged = { ...obj1, ...obj2 };
436
438
  for (let key in merged) {
437
439
  if (!isEmpty(obj1[key]) && !isEmpty(obj2[key])) {
438
440
  merged[key] = obj2[key];
@@ -445,20 +447,18 @@ function merge(obj1, obj2) {
445
447
  return merged;
446
448
  }
447
449
  function clone(data, times = 1) {
448
- if (reactivity.isRef(data)) {
449
- data = reactivity.unref(data);
450
+ const rawData = vue.isRef(data) ? vue.unref(data) : data;
451
+ if (!Array.isArray(rawData)) {
452
+ return esToolkit.cloneDeep(rawData);
450
453
  }
451
- if (getType(data) !== "array") {
452
- return esToolkit.cloneDeep(data);
453
- }
454
- const clonedData = esToolkit.cloneDeep(data);
454
+ const clonedData = esToolkit.cloneDeep(rawData);
455
455
  const result = [];
456
456
  for (let i = 0; i < times; i++) {
457
457
  result.push(...clonedData);
458
458
  }
459
459
  return result;
460
460
  }
461
- function uuid(type = "", length = 4, options = {}) {
461
+ function mockValue(type = "", length = 4, options = {}) {
462
462
  const { emailStr = "@qq.com", timeStr = "{y}-{m}-{d} {h}:{i}:{s}", startStr = "", optionsIndex = null } = options;
463
463
  function isRef2(obj) {
464
464
  return obj && typeof obj === "object" && obj._isRef === true;
@@ -490,11 +490,11 @@ function uuid(type = "", length = 4, options = {}) {
490
490
  return result;
491
491
  }
492
492
  if (type === "email") {
493
- result = uuid(startStr, length) + emailStr;
493
+ result = mockValue(startStr, length) + emailStr;
494
494
  return result;
495
495
  }
496
496
  if (type === "time") {
497
- return uuid(startStr, length, options) + " " + formatTime(/* @__PURE__ */ new Date(), timeStr);
497
+ return mockValue(startStr, length, options) + " " + formatTime(/* @__PURE__ */ new Date(), timeStr);
498
498
  }
499
499
  if (type === "number") {
500
500
  const numChars = "123456789";
@@ -524,12 +524,12 @@ function getType(type) {
524
524
  return typeof type;
525
525
  }
526
526
  }
527
- function sleep(delay = 0, fn) {
527
+ function delay(delay2 = 0, fn) {
528
528
  return new Promise(
529
529
  (resolve) => setTimeout(() => {
530
530
  fn?.();
531
531
  resolve();
532
- }, delay)
532
+ }, delay2)
533
533
  );
534
534
  }
535
535
  function validateTrigger(type = "required", rules = {}, pureValid = false) {
@@ -625,18 +625,18 @@ function validate(type = "required", rules = {}, pureValid = false) {
625
625
  );
626
626
  }
627
627
  if (type === "between" /* BETWEEN */) {
628
- let min = rulesObject.min;
629
- let max = rulesObject.max;
628
+ let minValue = rulesObject.min ?? "";
629
+ let maxValue = rulesObject.max ?? "";
630
630
  const validateBetween = (rule, value, callback) => {
631
631
  let validFlag = /^-?[0-9]+$/.test(value);
632
632
  if (!validFlag) {
633
633
  callback(new Error("\u8BF7\u8F93\u5165\u6570\u5B57"));
634
634
  }
635
- if (value < min && min !== void 0) {
636
- callback(new Error(`\u6570\u5B57\u4E0D\u80FD\u5C0F\u4E8E${min}`));
635
+ if (!isEmpty(minValue) && value < minValue) {
636
+ callback(new Error(`\u6570\u5B57\u4E0D\u80FD\u5C0F\u4E8E${minValue}`));
637
637
  }
638
- if (value > max && max !== void 0) {
639
- callback(new Error(`\u6570\u5B57\u4E0D\u80FD\u5927\u4E8E${max}`));
638
+ if (!isEmpty(maxValue) && value > maxValue && maxValue !== void 0) {
639
+ callback(new Error(`\u6570\u5B57\u4E0D\u80FD\u5927\u4E8E${maxValue}`));
640
640
  }
641
641
  callback();
642
642
  };
@@ -699,6 +699,7 @@ function validate(type = "required", rules = {}, pureValid = false) {
699
699
  trigger
700
700
  };
701
701
  }
702
+ return {};
702
703
  }
703
704
  const copy = (text, toastParams = {}) => {
704
705
  const textarea = document.createElement("textarea");
@@ -709,14 +710,14 @@ const copy = (text, toastParams = {}) => {
709
710
  document.execCommand("copy");
710
711
  document.body.removeChild(textarea);
711
712
  if (!toastParams.hideToast) {
712
- const { hideToast, ...toastOptions } = toastParams;
713
+ const { hideToast: _hideToast, ...toastOptions } = toastParams;
713
714
  $toast(text + "\u590D\u5236\u6210\u529F", toastOptions);
714
715
  return true;
715
716
  }
716
717
  return true;
717
718
  };
718
719
  function log(variableStr, variable, otherInfo = "") {
719
- const stack = new Error().stack.split("\n")[2].trim();
720
+ const stack = new Error().stack?.split("\n")[2]?.trim() ?? "";
720
721
  const matchResult = stack.match(/\((.*):(\d+):(\d+)\)/);
721
722
  let fileInfo = "";
722
723
  try {
@@ -724,12 +725,12 @@ function log(variableStr, variable, otherInfo = "") {
724
725
  const lineNumber = matchResult[2];
725
726
  fileInfo = `vscode://file${JSON.parse(otherInfo)}:${lineNumber}`;
726
727
  }
727
- } catch (error) {
728
+ } catch {
728
729
  fileInfo = otherInfo;
729
730
  }
730
- if (reactivity.isRef(variable)) {
731
- let unrefVariable = reactivity.unref(variable);
732
- _log(reactivity.toRaw(unrefVariable));
731
+ if (vue.isRef(variable)) {
732
+ const unrefVariable = vue.unref(variable);
733
+ _log(vue.toRaw(unrefVariable));
733
734
  } else {
734
735
  _log(variable);
735
736
  }
@@ -758,7 +759,7 @@ function random(min = 0, max = 10) {
758
759
  return Math.floor(Math.random() * (max - min + 1)) + min;
759
760
  }
760
761
  function toLine(text, connect = "-") {
761
- let translateText = text.replace(/([A-Z])/g, (match, p1, offset, origin) => {
762
+ let translateText = text.replace(/([A-Z])/g, (match, _letter, offset) => {
762
763
  if (offset === 0) {
763
764
  return `${match.toLocaleLowerCase()}`;
764
765
  } else {
@@ -769,7 +770,7 @@ function toLine(text, connect = "-") {
769
770
  }
770
771
  const _CSS_UNIT_RE = /^[0-9]+(\.[0-9]+)?(px|%|em|rem|vw|vh|ch)$/;
771
772
  function processWidth(initValue, isBase = false) {
772
- const raw = reactivity.unref(initValue);
773
+ const raw = vue.unref(initValue);
773
774
  if (!raw) {
774
775
  return isBase ? "" : {};
775
776
  }
@@ -784,18 +785,18 @@ function processWidth(initValue, isBase = false) {
784
785
  }
785
786
  return isBase ? res : { width: res };
786
787
  }
787
- function throttle(fn, delay = 1e3) {
788
+ function throttle(fn, delay2 = 1e3) {
788
789
  let last = 0;
789
790
  let timer = void 0;
790
791
  return function(...args) {
791
792
  let context = this;
792
793
  let now = +/* @__PURE__ */ new Date();
793
- if (now - last < delay) {
794
+ if (now - last < delay2) {
794
795
  clearTimeout(timer);
795
796
  timer = setTimeout(function() {
796
797
  last = now;
797
798
  fn.apply(context, args);
798
- }, delay);
799
+ }, delay2);
799
800
  } else {
800
801
  last = now;
801
802
  fn.apply(context, args);
@@ -804,10 +805,10 @@ function throttle(fn, delay = 1e3) {
804
805
  }
805
806
  async function tryCatch(task, sendLoading) {
806
807
  const updateLoading = (value) => {
807
- if (reactivity.isRef(sendLoading)) {
808
+ if (vue.isRef(sendLoading)) {
808
809
  sendLoading.value = value;
809
810
  } else if (sendLoading !== void 0 && sendLoading !== null) {
810
- console.warn("Cannot modify non-ref sendLoading directly!");
811
+ consola.consola.warn("Cannot modify non-ref sendLoading directly!");
811
812
  }
812
813
  };
813
814
  updateLoading(true);
@@ -820,7 +821,7 @@ async function tryCatch(task, sendLoading) {
820
821
  updateLoading(false);
821
822
  }
822
823
  }
823
- function debounce(func, delay = 500, immediate, resultCallback) {
824
+ function debounce(func, delay2 = 500, immediate, resultCallback) {
824
825
  let timer = null;
825
826
  let isInvoke = false;
826
827
  const _debounce = function(...args) {
@@ -846,7 +847,7 @@ function debounce(func, delay = 500, immediate, resultCallback) {
846
847
  }
847
848
  isInvoke = false;
848
849
  timer = null;
849
- }, delay);
850
+ }, delay2);
850
851
  }
851
852
  });
852
853
  };
@@ -910,7 +911,7 @@ function _resolveAppendTarget(appendTo) {
910
911
  try {
911
912
  const selector = rawSelector.startsWith("#") || rawSelector.startsWith(".") || rawSelector.startsWith("[") ? rawSelector : `#${rawSelector}`;
912
913
  return document.querySelector(selector) || appendTo;
913
- } catch (error) {
914
+ } catch {
914
915
  return appendTo;
915
916
  }
916
917
  }
@@ -929,10 +930,14 @@ function _resolveAppContext(appContext) {
929
930
  if (appContext) {
930
931
  return appContext;
931
932
  }
933
+ const installWithContext = elementPlus.ElMessageBox.install;
934
+ const messageBoxWithContext = elementPlus.ElMessageBox;
935
+ const elementPlusContext = installWithContext?.context || messageBoxWithContext._context || null;
932
936
  if (typeof document === "undefined") {
933
- return elementPlus.ElMessageBox.install?.context || elementPlus.ElMessageBox._context;
937
+ return elementPlusContext;
934
938
  }
935
- return elementPlus.ElMessageBox.install?.context || elementPlus.ElMessageBox._context || document.querySelector("#app")?._vue_app?._context;
939
+ const appRoot = document.querySelector("#app");
940
+ return elementPlusContext || appRoot?._vue_app?._context || null;
936
941
  }
937
942
  function getVariable(propertyName, fallback = "") {
938
943
  if (typeof document === "undefined") {
@@ -944,7 +949,7 @@ function getVariable(propertyName, fallback = "") {
944
949
  const DEFAULT_BUILD_TIME_FALLBACK = "\u672A\u6CE8\u5165";
945
950
  function getUtilsBuildTime(fallback = DEFAULT_BUILD_TIME_FALLBACK) {
946
951
  {
947
- return "2026-06-18 15:18:56";
952
+ return "2026-07-01 13:13:26";
948
953
  }
949
954
  }
950
955
  function test() {
@@ -957,6 +962,7 @@ exports.clone = clone;
957
962
  exports.confirm = confirm;
958
963
  exports.copy = copy;
959
964
  exports.debounce = debounce;
965
+ exports.delay = delay;
960
966
  exports.formatBytes = formatBytes;
961
967
  exports.formatBytesConvert = formatBytesConvert;
962
968
  exports.formatDurationTime = formatDurationTime;
@@ -972,15 +978,14 @@ exports.getVariable = getVariable;
972
978
  exports.isEmpty = isEmpty;
973
979
  exports.log = log;
974
980
  exports.merge = merge;
981
+ exports.mockValue = mockValue;
975
982
  exports.processWidth = processWidth;
976
983
  exports.random = random;
977
984
  exports.setStorage = setStorage;
978
- exports.sleep = sleep;
979
985
  exports.test = test;
980
986
  exports.throttle = throttle;
981
987
  exports.toLine = toLine;
982
988
  exports.tryCatch = tryCatch;
983
- exports.uuid = uuid;
984
- exports.validForm = validForm;
985
989
  exports.validate = validate;
990
+ exports.validateForm = validateForm;
986
991
  exports.validateTrigger = validateTrigger;