@karta.io/utils 1.0.0-beta.5 → 1.0.0-beta.50

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,10 +1,11 @@
1
1
  import camelCase from 'lodash/camelCase.js';
2
+ import flatMap from 'lodash/flatMap.js';
2
3
  import { CURRENCY_DEFAULT, BREAKPOINTS } from '@karta.io/common-data';
3
4
  import { parsePhoneNumberFromString } from 'libphonenumber-js';
4
5
  import snakeCase from 'lodash/snakeCase.js';
5
- import { computed, ref, watch, reactive, isRef, nextTick, onBeforeUnmount, onMounted, getCurrentInstance, render, createVNode } from 'vue';
6
- import { toValue, useDebounceFn, useBreakpoints } from '@vueuse/core';
6
+ import { toValue, computed, ref, watch, reactive, isRef, nextTick, onBeforeUnmount, onMounted, getCurrentInstance, render, createVNode } from 'vue';
7
7
  import { useQuery, useQueryClient } from '@tanstack/vue-query';
8
+ import { useDebounceFn, useBreakpoints } from '@vueuse/core';
8
9
  import get from 'lodash/get.js';
9
10
  import has from 'lodash/has.js';
10
11
  import union from 'lodash/union.js';
@@ -24,14 +25,16 @@ function AppComponentsResolver(options = {}) {
24
25
  return (name) => {
25
26
  const componentName = prefix && name.startsWith(prefix) ? name.substring(prefix.length) : name;
26
27
  const isAppComponent = componentName.startsWith("App");
27
- if (isAppComponent)
28
+ if (isAppComponent) {
28
29
  return { name: componentName, from: "@karta.io/app-components" };
30
+ }
29
31
  };
30
32
  }
31
33
 
32
34
  function camelizeKeys(object) {
33
- if (Array.isArray(object))
35
+ if (Array.isArray(object)) {
34
36
  return object.map((v) => camelizeKeys(v));
37
+ }
35
38
  if (object !== null && object.constructor === Object) {
36
39
  return Object.keys(object).reduce(
37
40
  (result, key) => ({
@@ -58,13 +61,113 @@ function convertEnumToOptions(obj, options) {
58
61
  }));
59
62
  }
60
63
 
64
+ class EnrichError extends Error {
65
+ constructor(data) {
66
+ super(data.message);
67
+ Object.assign(this, data);
68
+ }
69
+ }
70
+
71
+ function isHtml(data) {
72
+ try {
73
+ if (typeof DOMParser !== "undefined") {
74
+ const parser = new DOMParser();
75
+ const doc = parser.parseFromString(data, "text/html");
76
+ return Array.from(doc.body.childNodes).some(
77
+ (node) => node.nodeType === Node.ELEMENT_NODE
78
+ );
79
+ }
80
+ const htmlPattern = /<\/?[a-z][\s\S]*>/i;
81
+ return htmlPattern.test(data);
82
+ } catch (_) {
83
+ return false;
84
+ }
85
+ }
86
+
87
+ function getStatusMessage(status) {
88
+ let message = "";
89
+ switch (status) {
90
+ case 200:
91
+ message = "All done. Request successfully executed";
92
+ break;
93
+ case 201:
94
+ message = "Data successfully created";
95
+ break;
96
+ case 400:
97
+ message = "Bad request";
98
+ break;
99
+ case 401:
100
+ message = "Need auth";
101
+ break;
102
+ case 404:
103
+ message = "Not found";
104
+ break;
105
+ case 500:
106
+ message = "Something wrong. Internal server error";
107
+ break;
108
+ case 501:
109
+ message = "501: Not implemented";
110
+ break;
111
+ case 502:
112
+ message = "502: Bad gateway";
113
+ break;
114
+ case 503:
115
+ message = "Service unavailable. Try again later";
116
+ break;
117
+ default:
118
+ message = "Something wrong. Client default error message";
119
+ break;
120
+ }
121
+ return message;
122
+ }
123
+ function formatErrorDataMessage(data) {
124
+ if (!data) return "";
125
+ return Object.values(data).reduce((accum, current) => {
126
+ if (current && typeof current === "string")
127
+ return accum ? `${accum} | ${current}` : current;
128
+ if (Array.isArray(current) && current.length) {
129
+ const value = `${flatMap(current).join(" | ")}`;
130
+ return accum ? `${accum} | ${value}` : value;
131
+ }
132
+ return accum;
133
+ }, "");
134
+ }
135
+ function formatErrorForNotify(error) {
136
+ if (!error) return;
137
+ if (error.status >= 400 && error.status < 500) {
138
+ let message = "";
139
+ if (!error.data || typeof error.data === "string" && isHtml(error.data)) {
140
+ message = error.statusMessage || error.message || getStatusMessage(error.status);
141
+ } else if (typeof error.data === "string" && !isHtml(error.data)) {
142
+ message = error.data;
143
+ } else {
144
+ message = formatErrorDataMessage(error.data);
145
+ }
146
+ return {
147
+ title: "Request error",
148
+ message
149
+ };
150
+ }
151
+ if (error.status >= 500) {
152
+ return {
153
+ title: "Internal server error",
154
+ message: error.statusMessage || error.message || getStatusMessage(error.status)
155
+ };
156
+ }
157
+ if (error instanceof Error) {
158
+ return {
159
+ title: "Internal client error",
160
+ message: error.message
161
+ };
162
+ }
163
+ }
164
+
61
165
  function formatMoney(value, currency = CURRENCY_DEFAULT, options = {}) {
62
166
  const { locale = "en-US", defaultValue = 0, ...otherOptions } = options;
63
167
  try {
64
168
  let convertedValue = Number(value);
65
169
  if (value === null || Number.isNaN(convertedValue)) {
66
- if (defaultValue === "")
67
- return defaultValue;
170
+ if (defaultValue === "") return defaultValue;
68
171
  convertedValue = Number(defaultValue);
69
172
  }
70
173
  const formatter = new Intl.NumberFormat(locale, {
@@ -75,7 +178,7 @@ function formatMoney(value, currency = CURRENCY_DEFAULT, options = {}) {
75
178
  ...otherOptions
76
179
  });
77
180
  return formatter.format(convertedValue);
78
- } catch (error) {
181
+ } catch (_error) {
79
182
  return defaultValue;
80
183
  }
81
184
  }
@@ -105,7 +208,7 @@ function genUUID() {
105
208
  r = (d2 + r) % 16 | 0;
106
209
  d2 = Math.floor(d2 / 16);
107
210
  }
108
- return (c == "x" ? r : r & 7 | 8).toString(16);
211
+ return (c === "x" ? r : r & 7 | 8).toString(16);
109
212
  });
110
213
  }
111
214
 
@@ -124,8 +227,7 @@ function getCardNumber(number, options) {
124
227
  }
125
228
 
126
229
  function getCountryFromPhone(phone) {
127
- if (!phone)
128
- return "";
230
+ if (!phone) return "";
129
231
  const replacedPhone = phone.replace(/[a-zA-Z]/g, "");
130
232
  const phoneNumber = parsePhoneNumberFromString(replacedPhone);
131
233
  return phoneNumber?.country ?? "";
@@ -167,8 +269,7 @@ function mapDataObjectForFilters(data, options) {
167
269
  }
168
270
 
169
271
  function validateNumber(value, defaultValue) {
170
- if (value === "")
171
- return defaultValue;
272
+ if (value === "") return defaultValue;
172
273
  return Number.isNaN(Number(value)) ? defaultValue : Number(value);
173
274
  }
174
275
 
@@ -185,7 +286,9 @@ function getPaginationParams({
185
286
  offset: validatedPage * validatedLimit - validatedLimit
186
287
  };
187
288
  }
188
- function getPaginationLimit({ limit }) {
289
+ function getPaginationLimit({
290
+ limit
291
+ }) {
189
292
  return validateNumber(limit, LIMIT_DEFAULT);
190
293
  }
191
294
  function getPaginationOffset({
@@ -204,18 +307,19 @@ function getPaginationPages({
204
307
  }
205
308
 
206
309
  function parsePhone(phone) {
207
- if (!phone || typeof phone !== "string")
208
- return "";
310
+ if (!phone || typeof phone !== "string") return "";
209
311
  const replacedPhone = phone.replace(/[a-zA-Z]/g, "");
210
- if (replacedPhone.length === 1 && replacedPhone !== "+")
312
+ if (replacedPhone.length === 1 && replacedPhone !== "+") {
211
313
  return `+${replacedPhone}`;
314
+ }
212
315
  const phoneNumber = parsePhoneNumberFromString(replacedPhone);
213
316
  return phoneNumber ? phoneNumber.formatInternational() : replacedPhone;
214
317
  }
215
318
 
216
319
  function snakelizeKeys(prop) {
217
- if (Array.isArray(prop))
320
+ if (Array.isArray(prop)) {
218
321
  return prop.map((item) => snakelizeKeys(item));
322
+ }
219
323
  if (prop !== null && prop !== void 0 && prop.constructor === Object) {
220
324
  return Object.keys(prop).reduce(
221
325
  (accum, current) => ({
@@ -231,8 +335,7 @@ function snakelizeKeys(prop) {
231
335
  const LOCALE_RU = "ru-RU";
232
336
  const LOCALE_EN = "en-US";
233
337
  function unformatNumber(value) {
234
- if (!value || typeof value !== "string")
235
- return value;
338
+ if (!value || typeof value !== "string") return value;
236
339
  const string = value.trim();
237
340
  let locale;
238
341
  const spaceIndex = string.lastIndexOf(" ");
@@ -242,23 +345,18 @@ function unformatNumber(value) {
242
345
  const hasComma = commaIndex !== -1;
243
346
  const hasDot = dotIndex !== -1;
244
347
  const commasCount = (string.match(/,/g) || []).length;
245
- if (!Number.isNaN(Number(string)))
246
- return Number(string);
247
- if (hasSpace && hasComma && commaIndex > spaceIndex)
248
- locale = LOCALE_RU;
249
- if (hasSpace && !hasComma && !hasDot)
250
- locale = LOCALE_RU;
251
- if (hasComma && hasDot && dotIndex > commaIndex)
252
- locale = LOCALE_EN;
253
- if (hasComma && !hasSpace && !hasDot && commasCount > 1)
254
- locale = LOCALE_EN;
348
+ if (!Number.isNaN(Number(string))) return Number(string);
349
+ if (hasSpace && hasComma && commaIndex > spaceIndex) locale = LOCALE_RU;
350
+ if (hasSpace && !hasComma && !hasDot) locale = LOCALE_RU;
351
+ if (hasComma && hasDot && dotIndex > commaIndex) locale = LOCALE_EN;
352
+ if (hasComma && !hasSpace && !hasDot && commasCount > 1) locale = LOCALE_EN;
255
353
  if (commasCount === 1 && !hasSpace && !hasDot) {
256
354
  locale = string.length - 1 - commaIndex === 3 ? LOCALE_EN : LOCALE_RU;
257
355
  }
258
- if (locale === LOCALE_RU)
356
+ if (locale === LOCALE_RU) {
259
357
  return Number(string.replaceAll(" ", "").replace(",", "."));
260
- if (locale === LOCALE_EN)
261
- return Number(string.replaceAll(",", ""));
358
+ }
359
+ if (locale === LOCALE_EN) return Number(string.replaceAll(",", ""));
262
360
  return value;
263
361
  }
264
362
 
@@ -267,8 +365,9 @@ function UiComponentsResolver(options = {}) {
267
365
  return (name) => {
268
366
  const componentName = prefix && name.startsWith(prefix) ? name.substring(prefix.length) : name;
269
367
  const isUiComponent = componentName.startsWith("Ui");
270
- if (isUiComponent)
368
+ if (isUiComponent) {
271
369
  return { name: componentName, from: "@karta.io/ui-components" };
370
+ }
272
371
  };
273
372
  }
274
373
 
@@ -276,8 +375,7 @@ function useAbortController(callback) {
276
375
  let controller = null;
277
376
  return {
278
377
  async call(...args) {
279
- if (controller)
280
- controller.abort();
378
+ if (controller) controller.abort();
281
379
  controller = new AbortController();
282
380
  let response;
283
381
  if (args.length > 0) {
@@ -293,8 +391,7 @@ function useAbortController(callback) {
293
391
  return response;
294
392
  },
295
393
  abort() {
296
- if (!controller)
297
- return;
394
+ if (!controller) return;
298
395
  controller.abort();
299
396
  controller = null;
300
397
  },
@@ -316,13 +413,14 @@ function useAsyncItems({
316
413
  queryKey: getQueryKey(),
317
414
  queryFn: () => call(toValue(params), config)
318
415
  });
319
- const items = computed(() => data.value?.results || []);
416
+ const items = computed(
417
+ () => data.value?.results || []
418
+ );
320
419
  const count = ref(0);
321
420
  watch(
322
421
  data,
323
422
  (newValue) => {
324
- if (newValue === void 0 || newValue.count === void 0)
325
- return;
423
+ if (newValue === void 0 || newValue.count === void 0) return;
326
424
  count.value = newValue.count;
327
425
  },
328
426
  { immediate: true }
@@ -349,23 +447,18 @@ function useAsyncItems({
349
447
  }
350
448
 
351
449
  function isEnabled(options) {
352
- if (options?.debug !== void 0)
353
- return options.debug;
450
+ if (options?.debug !== void 0) return options.debug;
354
451
  const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
355
452
  if (isBrowser) {
356
453
  const debug = localStorage.getItem("debug");
357
- if (debug === "true")
358
- return true;
359
- if (debug === "false")
360
- return false;
454
+ if (debug === "true") return true;
455
+ if (debug === "false") return false;
361
456
  }
362
457
  const isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
363
458
  if (isNode) {
364
459
  const debug = process.env.NODE_DEBUG;
365
- if (debug === "true")
366
- return true;
367
- if (debug === "false")
368
- return false;
460
+ if (debug === "true") return true;
461
+ if (debug === "false") return false;
369
462
  }
370
463
  return false;
371
464
  }
@@ -393,7 +486,12 @@ function useAsyncMultiselect({
393
486
  color: "#b54708",
394
487
  debug: true
395
488
  });
396
- const paramsForLogger = { queryKey, dataItemsKey, dataItemIdKey, dataCountKey };
489
+ const paramsForLogger = {
490
+ queryKey,
491
+ dataItemsKey,
492
+ dataItemIdKey,
493
+ dataCountKey
494
+ };
397
495
  const reactiveData = reactive({
398
496
  search: "",
399
497
  page: 1,
@@ -423,8 +521,7 @@ function useAsyncMultiselect({
423
521
  watch(
424
522
  data,
425
523
  (newValue) => {
426
- if (!newValue)
427
- return;
524
+ if (!newValue) return;
428
525
  if (!has(newValue, dataItemsKey)) {
429
526
  logger.warn(
430
527
  `Unable to find key *"${dataItemsKey}"* (property "dataItemsKey") in data object from API.`,
@@ -439,8 +536,9 @@ function useAsyncMultiselect({
439
536
  );
440
537
  return;
441
538
  }
442
- if (!get(newValue, dataItemsKey) || get(newValue, dataCountKey) === void 0)
539
+ if (!get(newValue, dataItemsKey) || get(newValue, dataCountKey) === void 0) {
443
540
  return;
541
+ }
444
542
  count.value = get(newValue, dataCountKey, 0);
445
543
  const newItems = get(newValue, dataItemsKey);
446
544
  itemsByPages.value = {
@@ -469,10 +567,10 @@ function useAsyncMultiselect({
469
567
  { immediate: true }
470
568
  );
471
569
  const items = computed(() => {
472
- if (!itemsByPages.value)
473
- return selectedItemsCached.value;
474
- if (!Object.keys(itemsByPages.value).length)
570
+ if (!itemsByPages.value) return selectedItemsCached.value;
571
+ if (!Object.keys(itemsByPages.value).length) {
475
572
  return selectedItemsCached.value;
573
+ }
476
574
  const itemsByPagesAsArray = Object.values(itemsByPages.value).reduce(
477
575
  (acc, item) => [...acc, ...item],
478
576
  []
@@ -485,10 +583,8 @@ function useAsyncMultiselect({
485
583
  return [...itemsAsMap.values()];
486
584
  });
487
585
  const options = computed(() => {
488
- if (!items.value.length)
489
- return [];
490
- if (!mapOptionCallback)
491
- return this.items.value;
586
+ if (!items.value.length) return [];
587
+ if (!mapOptionCallback) return items.value;
492
588
  return items.value.map(mapOptionCallback);
493
589
  });
494
590
  const hasNextPage = computed(() => count.value > items.value.length);
@@ -507,6 +603,28 @@ function useAsyncMultiselect({
507
603
  search.value = value;
508
604
  updateSearchWithDebounce(value);
509
605
  };
606
+ const queryClient = useQueryClient();
607
+ const refetch = () => {
608
+ if (reactiveData.page !== 1) {
609
+ queryClient.invalidateQueries({
610
+ queryKey: [queryKey],
611
+ refetchType: "none"
612
+ });
613
+ loadPage(1);
614
+ } else {
615
+ queryClient.invalidateQueries({
616
+ queryKey: [queryKey]
617
+ });
618
+ }
619
+ };
620
+ const reload = () => {
621
+ if (reactiveData.page !== 1) {
622
+ queryClient.removeQueries({ queryKey: [queryKey] });
623
+ loadPage(1);
624
+ } else {
625
+ queryClient.resetQueries({ queryKey: [queryKey] });
626
+ }
627
+ };
510
628
  if (isRef(selectedValues)) {
511
629
  watch(selectedValues, async (newSelectedValues) => {
512
630
  if (!newSelectedValues.length) {
@@ -547,7 +665,9 @@ function useAsyncMultiselect({
547
665
  isFetching,
548
666
  isLoading,
549
667
  loadPage,
550
- updateSearch
668
+ updateSearch,
669
+ refetch,
670
+ reload
551
671
  };
552
672
  }
553
673
 
@@ -579,7 +699,9 @@ function useAsyncSelect({
579
699
  const loadWAC = () => call({
580
700
  page: reactiveData.page,
581
701
  search: reactiveData.search,
582
- ...reactiveData.selectedValue && { includedIds: [reactiveData.selectedValue] },
702
+ ...reactiveData.selectedValue && {
703
+ includedIds: [reactiveData.selectedValue]
704
+ },
583
705
  ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
584
706
  });
585
707
  const { data, isFetching, isLoading } = useQuery({
@@ -591,8 +713,7 @@ function useAsyncSelect({
591
713
  watch(
592
714
  data,
593
715
  (newValue) => {
594
- if (!newValue)
595
- return;
716
+ if (!newValue) return;
596
717
  if (!has(newValue, dataItemsKey)) {
597
718
  logger.warn(
598
719
  `Unable to find key *"${dataItemsKey}"* (property "dataItemsKey") in data object from API.`,
@@ -607,8 +728,9 @@ function useAsyncSelect({
607
728
  );
608
729
  return;
609
730
  }
610
- if (!get(newValue, dataItemsKey) || get(newValue, dataCountKey) === void 0)
731
+ if (!get(newValue, dataItemsKey) || get(newValue, dataCountKey) === void 0) {
611
732
  return;
733
+ }
612
734
  count.value = get(newValue, dataCountKey, 0);
613
735
  const newItems = get(newValue, dataItemsKey);
614
736
  itemsByPages.value = {
@@ -625,20 +747,16 @@ function useAsyncSelect({
625
747
  { immediate: true }
626
748
  );
627
749
  const items = computed(() => {
628
- if (!itemsByPages.value)
629
- return [];
630
- if (!Object.keys(itemsByPages.value).length)
631
- return [];
750
+ if (!itemsByPages.value) return [];
751
+ if (!Object.keys(itemsByPages.value).length) return [];
632
752
  return Object.values(itemsByPages.value).reduce(
633
753
  (acc, item) => [...acc, ...item],
634
754
  []
635
755
  );
636
756
  });
637
757
  const options = computed(() => {
638
- if (!items.value.length)
639
- return [];
640
- if (!mapOptionCallback)
641
- return this.items.value;
758
+ if (!items.value.length) return [];
759
+ if (!mapOptionCallback) return items.value;
642
760
  return items.value.map(mapOptionCallback);
643
761
  });
644
762
  const hasNextPage = computed(() => count.value > items.value.length);
@@ -653,6 +771,28 @@ function useAsyncSelect({
653
771
  search.value = value;
654
772
  updateSearchWithDebounce(value);
655
773
  };
774
+ const queryClient = useQueryClient();
775
+ const refetch = () => {
776
+ if (reactiveData.page !== 1) {
777
+ queryClient.invalidateQueries({
778
+ queryKey: [queryKey],
779
+ refetchType: "none"
780
+ });
781
+ loadPage(1);
782
+ } else {
783
+ queryClient.invalidateQueries({
784
+ queryKey: [queryKey]
785
+ });
786
+ }
787
+ };
788
+ const reload = () => {
789
+ if (reactiveData.page !== 1) {
790
+ queryClient.removeQueries({ queryKey: [queryKey] });
791
+ loadPage(1);
792
+ } else {
793
+ queryClient.resetQueries({ queryKey: [queryKey] });
794
+ }
795
+ };
656
796
  if (isRef(selectedValue)) {
657
797
  watch(selectedValue, (newSelectedValue) => {
658
798
  reactiveData.page = 1;
@@ -676,20 +816,22 @@ function useAsyncSelect({
676
816
  isFetching,
677
817
  isLoading,
678
818
  loadPage,
679
- updateSearch
819
+ updateSearch,
820
+ refetch,
821
+ reload
680
822
  };
681
823
  }
682
824
 
683
825
  function useBreakpoint() {
684
826
  const breakpoints = useBreakpoints(BREAKPOINTS);
685
827
  const isMobile = breakpoints.smaller("sm");
686
- const isDesktop = breakpoints.greater("md");
687
- const isGreaterXxs = breakpoints.greater("xxs");
688
- const isGreaterXs = breakpoints.greater("xs");
689
- const isGreaterSm = breakpoints.greater("sm");
690
- const isGreaterMd = breakpoints.greater("md");
691
- const isGreaterLg = breakpoints.greater("lg");
692
- const isGreaterXl = breakpoints.greater("xl");
828
+ const isDesktop = breakpoints.greaterOrEqual("md");
829
+ const isGreaterXxs = breakpoints.greaterOrEqual("xxs");
830
+ const isGreaterXs = breakpoints.greaterOrEqual("xs");
831
+ const isGreaterSm = breakpoints.greaterOrEqual("sm");
832
+ const isGreaterMd = breakpoints.greaterOrEqual("md");
833
+ const isGreaterLg = breakpoints.greaterOrEqual("lg");
834
+ const isGreaterXl = breakpoints.greaterOrEqual("xl");
693
835
  return {
694
836
  isMobile,
695
837
  isDesktop,
@@ -704,14 +846,10 @@ function useBreakpoint() {
704
846
 
705
847
  function _bem(block, blockSuffix, element, modifier, modifierValue) {
706
848
  let cls = block;
707
- if (blockSuffix)
708
- cls += `-${blockSuffix}`;
709
- if (element)
710
- cls += `__${element}`;
711
- if (modifier)
712
- cls += `_${modifier}`;
713
- if (modifierValue)
714
- cls += `_${modifierValue}`;
849
+ if (blockSuffix) cls += `-${blockSuffix}`;
850
+ if (element) cls += `__${element}`;
851
+ if (modifier) cls += `_${modifier}`;
852
+ if (modifierValue) cls += `_${modifierValue}`;
715
853
  return cls;
716
854
  }
717
855
  function useClassName(block) {
@@ -722,8 +860,7 @@ function useClassName(block) {
722
860
  const mv = (modifier, modifierValue, condition = true) => modifier && modifierValue && condition ? _bem(block, "", "", modifier, modifierValue) : "";
723
861
  const cssVar = (object) => {
724
862
  const styles = {};
725
- for (const key in object)
726
- styles[`--${block}-${key}`] = object[key];
863
+ for (const key in object) styles[`--${block}-${key}`] = object[key];
727
864
  return styles;
728
865
  };
729
866
  const cssVarName = (name) => `--${block}-${name}`;
@@ -748,15 +885,16 @@ function useDayjs(timezone) {
748
885
  dayjs.updateLocale("en", {
749
886
  weekStart: 1
750
887
  });
751
- if (!timezone)
752
- return dayjs;
888
+ if (!timezone) return dayjs;
753
889
  const dayjsExtended = (date, format, locale, strict) => dayjs(date, format, locale, strict).tz(timezone);
754
890
  return dayjsExtended;
755
891
  }
756
892
 
757
893
  function parseVersion(version) {
758
894
  if (typeof version !== "string" && typeof version !== "number") {
759
- throw new TypeError("Browser version must be type of string, number or negative boolean");
895
+ throw new TypeError(
896
+ "Browser version must be type of string, number or negative boolean"
897
+ );
760
898
  }
761
899
  const [major, minor = 0, patch = 0, build = 0] = typeof version === "string" ? version.split(".").map(Number) : [version];
762
900
  return {
@@ -768,8 +906,7 @@ function parseVersion(version) {
768
906
  }
769
907
  function isVersionLower(minimum, target) {
770
908
  for (const k of ["major", "minor", "patch"]) {
771
- if (minimum[k] !== target[k])
772
- return minimum[k] > target[k];
909
+ if (minimum[k] !== target[k]) return minimum[k] > target[k];
773
910
  }
774
911
  return minimum.build > target.build;
775
912
  }
@@ -817,9 +954,20 @@ function useGlobalScroll() {
817
954
 
818
955
  const CONFIRM_TEXT = "Are you sure you want to close? \nAll changes will be lost.";
819
956
  let dialogs = [];
820
- function useDialog() {
821
- let appContext;
957
+ const HASH_PREFIX = "#ud_";
958
+ function useDialog(options) {
822
959
  const logger = useLogger("use-dialog");
960
+ let hashPrefix = HASH_PREFIX;
961
+ if (options?.hashPrefix) {
962
+ if (options.hashPrefix.charAt(0) === "#") {
963
+ hashPrefix = options?.hashPrefix;
964
+ } else {
965
+ logger.warn(
966
+ `*hashPrefix* must start with "#". The default prefix "${HASH_PREFIX}" will be used`
967
+ );
968
+ }
969
+ }
970
+ let appContext;
823
971
  const {
824
972
  isLocked: isGlobalScrollLocked,
825
973
  lock: lockGlobalScroll,
@@ -827,26 +975,33 @@ function useDialog() {
827
975
  } = useGlobalScroll();
828
976
  const route = useRoute();
829
977
  const router = useRouter();
830
- const HASH_PREFIX = "#ud_";
978
+ const genHash = ({
979
+ layer = 0,
980
+ componentName,
981
+ props
982
+ }) => {
983
+ const data = {
984
+ name: componentName,
985
+ layer,
986
+ props
987
+ };
988
+ return `${hashPrefix}${window.btoa(JSON.stringify(data))}`;
989
+ };
831
990
  const parseHash = (hash, componentName) => {
832
- if (!hash)
833
- return void 0;
834
- if (!hash.includes(HASH_PREFIX))
835
- return void 0;
991
+ if (!hash) return void 0;
992
+ if (!hash.includes(hashPrefix)) return void 0;
836
993
  let dataFromHash;
837
994
  try {
838
- dataFromHash = JSON.parse(window.atob(hash.slice(HASH_PREFIX.length)));
839
- } catch (error) {
995
+ dataFromHash = JSON.parse(window.atob(hash.slice(hashPrefix.length)));
996
+ } catch (_error) {
840
997
  logger.warn("*parseHash* cant parse hash");
841
998
  }
842
- if (typeof dataFromHash !== "object")
843
- return void 0;
999
+ if (typeof dataFromHash !== "object") return void 0;
844
1000
  if (!dataFromHash.name) {
845
1001
  logger.warn("*parseHash* cant find component name in hash");
846
1002
  return void 0;
847
1003
  }
848
- if (dataFromHash.name !== componentName)
849
- return void 0;
1004
+ if (dataFromHash.name !== componentName) return void 0;
850
1005
  return dataFromHash;
851
1006
  };
852
1007
  const clearHash = () => {
@@ -883,8 +1038,7 @@ function useDialog() {
883
1038
  vnode2.component.props.modelValue = value;
884
1039
  if (!value && route?.hash) {
885
1040
  const dataFromHash = parseHash(route.hash, component.name);
886
- if (dataFromHash)
887
- clearHash();
1041
+ if (dataFromHash?.layer === layer) clearHash();
888
1042
  }
889
1043
  if (!value && (dialogs.length === 1 || layer === 0) && isGlobalScrollLocked.value) {
890
1044
  unlockGlobalScroll();
@@ -893,14 +1047,11 @@ function useDialog() {
893
1047
  };
894
1048
  }
895
1049
  vnode2.close = () => {
896
- if (!vnode2 || !vnode2.component)
897
- return;
1050
+ if (!vnode2 || !vnode2.component) return;
898
1051
  vnode2.component.props.modelValue = false;
899
- if (!route?.hash)
900
- return;
1052
+ if (!route?.hash) return;
901
1053
  const dataFromHash = parseHash(route.hash, component.name);
902
- if (dataFromHash)
903
- clearHash();
1054
+ if (dataFromHash?.layer === layer) clearHash();
904
1055
  };
905
1056
  vnode2.props.onDestroy = () => {
906
1057
  render(null, el2);
@@ -973,9 +1124,12 @@ function useDialog() {
973
1124
  const getInstance = (uuid) => {
974
1125
  return dialogs.find((item) => item.uuid === uuid)?.vnode;
975
1126
  };
1127
+ const getLayer = (uuid) => {
1128
+ if (!dialogs.length) return 0;
1129
+ return dialogs.find((dialog) => dialog.uuid === uuid)?.layer || 0;
1130
+ };
976
1131
  const isOnTop = (uuid) => {
977
- if (!dialogs.length)
978
- return false;
1132
+ if (!dialogs.length) return false;
979
1133
  const dialogsSorted = [...dialogs].sort((a, b) => b.layer - a.layer);
980
1134
  return dialogsSorted[0].uuid === uuid;
981
1135
  };
@@ -987,15 +1141,10 @@ function useDialog() {
987
1141
  component,
988
1142
  props
989
1143
  }) => {
990
- const data = {
991
- name: component.name,
992
- layer,
993
- props
994
- };
995
1144
  router.push({
996
1145
  name: route.name || void 0,
997
1146
  query: route.query,
998
- hash: `${HASH_PREFIX}${window.btoa(JSON.stringify(data))}`
1147
+ hash: genHash({ layer, props, componentName: component.name })
999
1148
  });
1000
1149
  };
1001
1150
  const watchHash = ({
@@ -1007,14 +1156,12 @@ function useDialog() {
1007
1156
  () => route.hash,
1008
1157
  async (newHash) => {
1009
1158
  if (!newHash) {
1010
- if (!dialogs.length)
1011
- return;
1159
+ if (!dialogs.length) return;
1012
1160
  closeAll();
1013
1161
  return;
1014
1162
  }
1015
1163
  const dataFromHash = parseHash(newHash, component.name);
1016
- if (!dataFromHash)
1017
- return;
1164
+ if (!dataFromHash) return;
1018
1165
  logger.info("*watchHash* data from hash", dataFromHash);
1019
1166
  await nextTick();
1020
1167
  open({
@@ -1040,10 +1187,14 @@ function useDialog() {
1040
1187
  return {
1041
1188
  open,
1042
1189
  getInstance,
1190
+ getLayer,
1043
1191
  close,
1044
1192
  closeAll,
1045
1193
  showConfirm,
1046
1194
  isOnTop,
1195
+ genHash,
1196
+ parseHash,
1197
+ clearHash,
1047
1198
  openByHash,
1048
1199
  watchHash
1049
1200
  };
@@ -1056,46 +1207,47 @@ const QS_STRINGIFY_PARAMS = {
1056
1207
  addQueryPrefix: true
1057
1208
  };
1058
1209
  const isOpen = ref(false);
1059
- function useFilters({
1060
- config,
1061
- initialFilters
1062
- }) {
1210
+ function useFilters({ config, initialFilters }) {
1063
1211
  const router = useRouter();
1064
1212
  const route = useRoute();
1065
1213
  const parseRouteQuery = (query) => qs.parse(query ?? route.query);
1066
1214
  const filtersFromQuery = computed(() => {
1067
1215
  const parsedRouteQuery = parseRouteQuery();
1068
- if (!parsedRouteQuery.filters)
1069
- return void 0;
1070
- return Object.entries(config).reduce((accum, [currentKey, currentValue]) => {
1071
- if (!parsedRouteQuery.filters[currentKey])
1072
- return accum;
1073
- if (currentValue.type === "ARRAY" /* Array */) {
1074
- const splitValues = parsedRouteQuery.filters[currentKey].split(",");
1075
- const checkedValue = currentValue?.possibleValues ? splitValues.filter((k) => currentValue?.possibleValues?.includes(k)) : splitValues;
1076
- if (!checkedValue?.length)
1077
- return accum;
1216
+ if (!parsedRouteQuery.filters) return void 0;
1217
+ return Object.entries(config).reduce(
1218
+ (accum, [currentKey, currentValue]) => {
1219
+ if (!parsedRouteQuery.filters[currentKey]) return accum;
1220
+ if (currentValue.type === "ARRAY" /* Array */) {
1221
+ const splitValues = parsedRouteQuery.filters[currentKey].split(",");
1222
+ const checkedValue = currentValue?.possibleValues ? splitValues.filter(
1223
+ (k) => currentValue?.possibleValues?.includes(k)
1224
+ ) : splitValues;
1225
+ if (!checkedValue?.length) return accum;
1226
+ return {
1227
+ ...accum,
1228
+ [currentKey]: checkedValue
1229
+ };
1230
+ }
1078
1231
  return {
1079
1232
  ...accum,
1080
- [currentKey]: checkedValue
1233
+ [currentKey]: parsedRouteQuery.filters[currentKey]
1081
1234
  };
1082
- }
1083
- return {
1084
- ...accum,
1085
- [currentKey]: parsedRouteQuery.filters[currentKey]
1086
- };
1087
- }, {});
1235
+ },
1236
+ {}
1237
+ );
1088
1238
  });
1089
1239
  const filtersCount = computed(
1090
1240
  () => filtersFromQuery.value ? Object.keys(filtersFromQuery.value).length : 0
1091
1241
  );
1092
1242
  const setQueryFromFilters = (filters) => {
1093
1243
  const parsedRouteQuery = parseRouteQuery();
1094
- const filteredValue = Object.entries(filters).reduce((accum, [currentKey, currentValue]) => {
1095
- if (!currentValue?.length)
1096
- return accum;
1097
- return { ...accum, [currentKey]: currentValue };
1098
- }, {});
1244
+ const filteredValue = Object.entries(filters).reduce(
1245
+ (accum, [currentKey, currentValue]) => {
1246
+ if (!currentValue?.length) return accum;
1247
+ return { ...accum, [currentKey]: currentValue };
1248
+ },
1249
+ {}
1250
+ );
1099
1251
  const query = qs.stringify(
1100
1252
  {
1101
1253
  ...parsedRouteQuery,
@@ -1104,7 +1256,7 @@ function useFilters({
1104
1256
  },
1105
1257
  QS_STRINGIFY_PARAMS
1106
1258
  );
1107
- router.push(query);
1259
+ router.push(query.replaceAll("#", ""));
1108
1260
  };
1109
1261
  const getValidatedParams = (query) => {
1110
1262
  const parsedRouteQuery = parseRouteQuery(query);
@@ -1132,12 +1284,15 @@ function useFilters({
1132
1284
  });
1133
1285
  };
1134
1286
  const updateMany = (filters) => {
1135
- const newFilters = Object.entries(filters).reduce((accum, [currentKey, currentValue]) => {
1136
- return {
1137
- ...accum,
1138
- [currentKey]: currentValue ? String(currentValue) : void 0
1139
- };
1140
- }, {});
1287
+ const newFilters = Object.entries(filters).reduce(
1288
+ (accum, [currentKey, currentValue]) => {
1289
+ return {
1290
+ ...accum,
1291
+ [currentKey]: currentValue ? String(currentValue) : void 0
1292
+ };
1293
+ },
1294
+ {}
1295
+ );
1141
1296
  setQueryFromFilters({
1142
1297
  ...filtersModel.value,
1143
1298
  ...newFilters
@@ -1313,17 +1468,15 @@ function usePanel() {
1313
1468
  let dataFromHash;
1314
1469
  try {
1315
1470
  dataFromHash = JSON.parse(window.atob(newHash.slice(1)));
1316
- } catch (error) {
1471
+ } catch (_error) {
1317
1472
  logger.error("*watchHash* cant parse hash");
1318
1473
  }
1319
- if (typeof dataFromHash !== "object")
1320
- return;
1474
+ if (typeof dataFromHash !== "object") return;
1321
1475
  if (!dataFromHash.name) {
1322
1476
  logger.error("*watchHash* cant find component name in hash");
1323
1477
  return;
1324
1478
  }
1325
- if (dataFromHash.name !== component.name)
1326
- return;
1479
+ if (dataFromHash.name !== component.name) return;
1327
1480
  logger.info("*watchHash* data from hash", dataFromHash);
1328
1481
  await nextTick();
1329
1482
  open({
@@ -1331,8 +1484,7 @@ function usePanel() {
1331
1484
  layer: dataFromHash.layer || 0,
1332
1485
  props: {
1333
1486
  "onUpdate:modelValue": (value) => {
1334
- if (value)
1335
- return;
1487
+ if (value) return;
1336
1488
  router.push({
1337
1489
  name: route.name || void 0,
1338
1490
  query: route.query,
@@ -1366,8 +1518,7 @@ function usePanel() {
1366
1518
  }
1367
1519
 
1368
1520
  function validatePhone(rule, value) {
1369
- if (!value)
1370
- return true;
1521
+ if (!value) return true;
1371
1522
  const phoneNumber = parsePhoneNumberFromString(value);
1372
1523
  return phoneNumber ? phoneNumber.isValid() : false;
1373
1524
  }
@@ -1416,4 +1567,4 @@ function isStrictLength(value = 3, message) {
1416
1567
  };
1417
1568
  }
1418
1569
 
1419
- export { AppComponentsResolver, UiComponentsResolver, camelizeKeys, convertEnumToOptions, formatMoney, genHash, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, isMax, isMin, isRequired, isStrictLength, isTypeEmail, isTypeNumber, isTypeUrl, mapDataObjectForFilters, parsePhone, snakelizeKeys, unformatNumber, useAbortController, useAsyncItems, useAsyncMultiselect, useAsyncSelect, useBreakpoint, useClassName, useDayjs, useDetectBrowser, useDialog, useFilters, useGlobalScroll, useLogger, usePanel, validateNumber, validatePhone };
1570
+ export { AppComponentsResolver, EnrichError, UiComponentsResolver, camelizeKeys, convertEnumToOptions, formatErrorDataMessage, formatErrorForNotify, formatMoney, genHash, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, getStatusMessage, isElementIgnored, isEmptyObject, isHtml, isMax, isMin, isRequired, isStrictLength, isTypeEmail, isTypeNumber, isTypeUrl, mapDataObjectForFilters, parsePhone, snakelizeKeys, unformatNumber, useAbortController, useAsyncItems, useAsyncMultiselect, useAsyncSelect, useBreakpoint, useClassName, useDayjs, useDetectBrowser, useDialog, useFilters, useGlobalScroll, useLogger, usePanel, validateNumber, validatePhone };