@karta.io/utils 1.0.0-alpha.2 → 1.0.0-alpha.21

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.cjs CHANGED
@@ -9,6 +9,7 @@ const core = require('@vueuse/core');
9
9
  const vueQuery = require('@tanstack/vue-query');
10
10
  const get = require('lodash/get.js');
11
11
  const has = require('lodash/has.js');
12
+ const union = require('lodash/union.js');
12
13
  const logdown = require('logdown');
13
14
  const dayjs = require('dayjs');
14
15
  const utc = require('dayjs/plugin/utc.js');
@@ -26,6 +27,7 @@ const camelCase__default = /*#__PURE__*/_interopDefaultCompat(camelCase);
26
27
  const snakeCase__default = /*#__PURE__*/_interopDefaultCompat(snakeCase);
27
28
  const get__default = /*#__PURE__*/_interopDefaultCompat(get);
28
29
  const has__default = /*#__PURE__*/_interopDefaultCompat(has);
30
+ const union__default = /*#__PURE__*/_interopDefaultCompat(union);
29
31
  const logdown__default = /*#__PURE__*/_interopDefaultCompat(logdown);
30
32
  const dayjs__default = /*#__PURE__*/_interopDefaultCompat(dayjs);
31
33
  const utc__default = /*#__PURE__*/_interopDefaultCompat(utc);
@@ -60,6 +62,20 @@ function camelizeKeys(object) {
60
62
  return object;
61
63
  }
62
64
 
65
+ const OPTIONS_DEFAULT = {
66
+ labelType: "value"
67
+ };
68
+ function convertEnumToOptions(obj, options) {
69
+ const newOptions = {
70
+ ...OPTIONS_DEFAULT,
71
+ ...options
72
+ };
73
+ return Object.entries(obj).map(([key, value]) => ({
74
+ value,
75
+ label: newOptions.labelType === "key" ? key : value
76
+ }));
77
+ }
78
+
63
79
  function formatMoney(value, currency = commonData.CURRENCY_DEFAULT, options = {}) {
64
80
  const convertedValue = Number(value);
65
81
  if (value === null || Number.isNaN(convertedValue))
@@ -144,6 +160,23 @@ function isEmptyObject(object) {
144
160
  return !object || !Object.keys(object).length;
145
161
  }
146
162
 
163
+ const optionsDefault = {
164
+ labelKey: "title",
165
+ valueKey: "",
166
+ excludedItems: []
167
+ };
168
+ function mapDataObjectForFilters(data, options) {
169
+ const newOptions = {
170
+ ...optionsDefault,
171
+ ...options
172
+ };
173
+ const { labelKey, valueKey, excludedItems } = newOptions;
174
+ return Object.entries(data).filter(([key]) => !excludedItems.includes(key)).map(([key, value]) => ({
175
+ label: value?.[labelKey] || "Unknown label",
176
+ value: value?.[valueKey] || key
177
+ }));
178
+ }
179
+
147
180
  function validateNumber(value, defaultValue) {
148
181
  if (value === "")
149
182
  return defaultValue;
@@ -380,12 +413,17 @@ function useAsyncMultiselect({
380
413
  });
381
414
  const search = vue.ref("");
382
415
  const { call, abort } = useAbortController(apiMethod);
383
- const loadWAC = () => call({
384
- page: reactiveData.page,
385
- search: reactiveData.search,
386
- ...reactiveData.selectedValues?.length && { includedIds: reactiveData.selectedValues },
387
- ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
388
- });
416
+ const loadWAC = () => {
417
+ const includedIdsBySelectedValues = reactiveData.selectedValues ?? [];
418
+ const includedIdsByParams = JSON.parse(reactiveData.params || {})?.includedIds ?? [];
419
+ const includedIds = union__default(includedIdsBySelectedValues, includedIdsByParams);
420
+ return call({
421
+ page: reactiveData.page,
422
+ search: reactiveData.search,
423
+ ...reactiveData.params && { ...JSON.parse(reactiveData.params) },
424
+ ...includedIds.length && { includedIds }
425
+ });
426
+ };
389
427
  const { data, isFetching, isLoading } = vueQuery.useQuery({
390
428
  queryKey: [queryKey, reactiveData],
391
429
  queryFn: loadWAC
@@ -788,6 +826,240 @@ function useGlobalScroll() {
788
826
  };
789
827
  }
790
828
 
829
+ const CONFIRM_TEXT = "Are you sure you want to close? \nAll changes will be lost.";
830
+ let dialogs = [];
831
+ function useDialog() {
832
+ let appContext;
833
+ const logger = useLogger("use-dialog");
834
+ const {
835
+ isLocked: isGlobalScrollLocked,
836
+ lock: lockGlobalScroll,
837
+ unlock: unlockGlobalScroll
838
+ } = useGlobalScroll();
839
+ const route = vueRouter.useRoute();
840
+ const router = vueRouter.useRouter();
841
+ const HASH_PREFIX = "#ud_";
842
+ const parseHash = (hash, componentName) => {
843
+ if (!hash)
844
+ return void 0;
845
+ if (!hash.includes(HASH_PREFIX))
846
+ return void 0;
847
+ let dataFromHash;
848
+ try {
849
+ dataFromHash = JSON.parse(window.atob(hash.slice(HASH_PREFIX.length)));
850
+ } catch (error) {
851
+ logger.warn("*parseHash* cant parse hash");
852
+ }
853
+ if (typeof dataFromHash !== "object")
854
+ return void 0;
855
+ if (!dataFromHash.name) {
856
+ logger.warn("*parseHash* cant find component name in hash");
857
+ return void 0;
858
+ }
859
+ if (dataFromHash.name !== componentName)
860
+ return void 0;
861
+ return dataFromHash;
862
+ };
863
+ const clearHash = () => {
864
+ router.push({
865
+ name: route.name || void 0,
866
+ query: route.query,
867
+ hash: void 0
868
+ });
869
+ };
870
+ vue.onMounted(() => {
871
+ appContext = vue.getCurrentInstance()?.appContext;
872
+ });
873
+ const open = ({
874
+ layer = 0,
875
+ component,
876
+ props
877
+ }) => {
878
+ const uuid = genUUID();
879
+ const createComponent = () => {
880
+ const newProps = {
881
+ ...props,
882
+ layer
883
+ };
884
+ const el2 = document.createElement("div");
885
+ const vnode2 = vue.createVNode(component, {
886
+ ...newProps,
887
+ modelValue: true,
888
+ uuid
889
+ });
890
+ vnode2.appContext = { ...appContext };
891
+ if (!vnode2?.props?.["onUpdate:modelValue"]) {
892
+ vnode2.props["onUpdate:modelValue"] = (value) => {
893
+ if (vnode2 && vnode2.component) {
894
+ vnode2.component.props.modelValue = value;
895
+ if (!value && route?.hash) {
896
+ const dataFromHash = parseHash(route.hash, component.name);
897
+ if (dataFromHash)
898
+ clearHash();
899
+ }
900
+ if (!value && (dialogs.length === 1 || layer === 0) && isGlobalScrollLocked.value) {
901
+ unlockGlobalScroll();
902
+ }
903
+ }
904
+ };
905
+ }
906
+ vnode2.close = () => {
907
+ if (!vnode2 || !vnode2.component)
908
+ return;
909
+ vnode2.component.props.modelValue = false;
910
+ if (!route?.hash)
911
+ return;
912
+ const dataFromHash = parseHash(route.hash, component.name);
913
+ if (dataFromHash)
914
+ clearHash();
915
+ };
916
+ vnode2.props.onDestroy = () => {
917
+ vue.render(null, el2);
918
+ dialogs = dialogs.filter((dialog) => dialog.uuid !== uuid);
919
+ logger.info("Dialogs after destroy", dialogs);
920
+ };
921
+ const name = vnode2?.type?.name ?? "Unknown component";
922
+ const newDialog2 = {
923
+ uuid,
924
+ name,
925
+ vnode: vnode2,
926
+ layer
927
+ };
928
+ logger.log(`Open new dialog: "${name}"`);
929
+ if (!isGlobalScrollLocked.value) {
930
+ lockGlobalScroll();
931
+ }
932
+ return {
933
+ vnode: vnode2,
934
+ el: el2,
935
+ newDialog: newDialog2
936
+ };
937
+ };
938
+ if (!dialogs.length) {
939
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
940
+ vue.render(vnode2, el2);
941
+ dialogs = [newDialog2];
942
+ logger.info("Dialogs after open", dialogs);
943
+ return uuid;
944
+ }
945
+ if (layer === 0) {
946
+ closeAll();
947
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
948
+ vue.render(vnode2, el2);
949
+ dialogs = [newDialog2];
950
+ logger.info("Dialogs after open", dialogs);
951
+ return uuid;
952
+ }
953
+ if (!dialogs.some((dialog) => dialog.layer === layer)) {
954
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
955
+ vue.render(vnode2, el2);
956
+ dialogs = [...dialogs, newDialog2];
957
+ logger.info("Dialogs after open", dialogs);
958
+ return uuid;
959
+ }
960
+ const dialogOnCurrentLayer = dialogs.find((dialog) => dialog.layer === layer);
961
+ close(dialogOnCurrentLayer?.uuid || "");
962
+ const { vnode, el, newDialog } = createComponent();
963
+ vue.render(vnode, el);
964
+ dialogs = [...dialogs, newDialog];
965
+ logger.info("Dialogs after open", dialogs);
966
+ return uuid;
967
+ };
968
+ const close = (uuid) => {
969
+ const dialog = dialogs.find((item) => item.uuid === uuid);
970
+ logger.log(`Close dialog: "${uuid}"`);
971
+ if ((dialogs.length === 1 || dialog.layer === 0) && isGlobalScrollLocked.value) {
972
+ unlockGlobalScroll();
973
+ }
974
+ dialog?.vnode.close();
975
+ };
976
+ const closeAll = () => {
977
+ dialogs.forEach((dialog) => {
978
+ dialog?.vnode.close();
979
+ });
980
+ if (isGlobalScrollLocked.value) {
981
+ unlockGlobalScroll();
982
+ }
983
+ };
984
+ const getInstance = (uuid) => {
985
+ return dialogs.find((item) => item.uuid === uuid)?.vnode;
986
+ };
987
+ const isOnTop = (uuid) => {
988
+ if (!dialogs.length)
989
+ return false;
990
+ const dialogsSorted = [...dialogs].sort((a, b) => b.layer - a.layer);
991
+ return dialogsSorted[0].uuid === uuid;
992
+ };
993
+ const showConfirm = (text = CONFIRM_TEXT) => {
994
+ return window.confirm(text);
995
+ };
996
+ const openByHash = ({
997
+ layer = 0,
998
+ component,
999
+ props
1000
+ }) => {
1001
+ const data = {
1002
+ name: component.name,
1003
+ layer,
1004
+ props
1005
+ };
1006
+ router.push({
1007
+ name: route.name || void 0,
1008
+ query: route.query,
1009
+ hash: `${HASH_PREFIX}${window.btoa(JSON.stringify(data))}`
1010
+ });
1011
+ };
1012
+ const watchHash = ({
1013
+ component,
1014
+ events
1015
+ }) => {
1016
+ logger.info(`start watching route.hash for dialog *${component.name}*`);
1017
+ const stopWatch = vue.watch(
1018
+ () => route.hash,
1019
+ async (newHash) => {
1020
+ if (!newHash) {
1021
+ if (!dialogs.length)
1022
+ return;
1023
+ closeAll();
1024
+ return;
1025
+ }
1026
+ const dataFromHash = parseHash(newHash, component.name);
1027
+ if (!dataFromHash)
1028
+ return;
1029
+ logger.info("*watchHash* data from hash", dataFromHash);
1030
+ await vue.nextTick();
1031
+ open({
1032
+ component,
1033
+ layer: dataFromHash.layer || 0,
1034
+ props: {
1035
+ ...dataFromHash.props,
1036
+ ...events
1037
+ }
1038
+ });
1039
+ },
1040
+ { immediate: true }
1041
+ );
1042
+ const stopWatchHash = () => {
1043
+ logger.info(`stop watching route.hash for dialog *${component.name}*`);
1044
+ stopWatch();
1045
+ };
1046
+ vue.onBeforeUnmount(() => {
1047
+ stopWatchHash();
1048
+ });
1049
+ return stopWatchHash;
1050
+ };
1051
+ return {
1052
+ open,
1053
+ getInstance,
1054
+ close,
1055
+ closeAll,
1056
+ showConfirm,
1057
+ isOnTop,
1058
+ openByHash,
1059
+ watchHash
1060
+ };
1061
+ }
1062
+
791
1063
  const QS_STRINGIFY_PARAMS = {
792
1064
  arrayFormat: "comma",
793
1065
  encode: false,
@@ -1158,6 +1430,7 @@ function isStrictLength(value = 3, message) {
1158
1430
  exports.AppComponentsResolver = AppComponentsResolver;
1159
1431
  exports.UiComponentsResolver = UiComponentsResolver;
1160
1432
  exports.camelizeKeys = camelizeKeys;
1433
+ exports.convertEnumToOptions = convertEnumToOptions;
1161
1434
  exports.formatMoney = formatMoney;
1162
1435
  exports.genHash = genHash;
1163
1436
  exports.genRandomNumber = genRandomNumber;
@@ -1177,6 +1450,7 @@ exports.isStrictLength = isStrictLength;
1177
1450
  exports.isTypeEmail = isTypeEmail;
1178
1451
  exports.isTypeNumber = isTypeNumber;
1179
1452
  exports.isTypeUrl = isTypeUrl;
1453
+ exports.mapDataObjectForFilters = mapDataObjectForFilters;
1180
1454
  exports.parsePhone = parsePhone;
1181
1455
  exports.snakelizeKeys = snakelizeKeys;
1182
1456
  exports.unformatNumber = unformatNumber;
@@ -1188,6 +1462,7 @@ exports.useBreakpoint = useBreakpoint;
1188
1462
  exports.useClassName = useClassName;
1189
1463
  exports.useDayjs = useDayjs;
1190
1464
  exports.useDetectBrowser = useDetectBrowser;
1465
+ exports.useDialog = useDialog;
1191
1466
  exports.useFilters = useFilters;
1192
1467
  exports.useGlobalScroll = useGlobalScroll;
1193
1468
  exports.useLogger = useLogger;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as vue from 'vue';
2
- import { MaybeRef, Ref, Component, EmitsOptions, VNode } from 'vue';
2
+ import { MaybeRef, Component, EmitsOptions, VNode, Ref } from 'vue';
3
3
  import { AxiosRequestConfig } from 'axios';
4
4
  export { AxiosError as HttpError, AxiosPromise as HttpPromise, AxiosRequestConfig as HttpRequestConfig, AxiosResponse as HttpResponse } from 'axios';
5
5
  import { MaybeRef as MaybeRef$1 } from '@vueuse/core';
@@ -25,6 +25,14 @@ interface ResponseError {
25
25
 
26
26
  declare function camelizeKeys(object: Dictionary): Dictionary;
27
27
 
28
+ interface Options$3 {
29
+ labelType: 'key' | 'value';
30
+ }
31
+ declare function convertEnumToOptions(obj: any, options?: Options$3): {
32
+ value: unknown;
33
+ label: unknown;
34
+ }[];
35
+
28
36
  interface Options$2 extends Intl.NumberFormatOptions {
29
37
  locale?: string;
30
38
  }
@@ -52,6 +60,16 @@ declare function isElementIgnored({ ignoredClasses, event, }?: {
52
60
 
53
61
  declare function isEmptyObject(object: object): boolean;
54
62
 
63
+ interface MapOptions {
64
+ labelKey?: string;
65
+ valueKey?: string;
66
+ excludedItems?: any[];
67
+ }
68
+ declare function mapDataObjectForFilters<T extends Record<string, any>>(data: T, options?: MapOptions): {
69
+ label: string;
70
+ value: any;
71
+ }[];
72
+
55
73
  declare function getPaginationParams({ page, limit, }: {
56
74
  page: string | number;
57
75
  limit: string | number;
@@ -226,6 +244,31 @@ type VersionsList = {
226
244
  };
227
245
  declare function useDetectBrowser(versions: VersionsList, userAgent?: any): BrowserInfo;
228
246
 
247
+ interface VNodeCustom$1 extends VNode {
248
+ close(): void;
249
+ }
250
+ declare function useDialog(): {
251
+ open: ({ layer, component, props, }: {
252
+ component: Component;
253
+ props?: any;
254
+ layer?: number;
255
+ }) => string;
256
+ getInstance: (uuid: string) => VNodeCustom$1;
257
+ close: (uuid: string) => void;
258
+ closeAll: () => void;
259
+ showConfirm: (text?: string) => boolean;
260
+ isOnTop: (uuid: string) => boolean;
261
+ openByHash: ({ layer, component, props, }: {
262
+ component: Component;
263
+ props?: any;
264
+ layer?: number;
265
+ }) => void;
266
+ watchHash: ({ component, events, }: {
267
+ component: Component;
268
+ events?: EmitsOptions;
269
+ }) => any;
270
+ };
271
+
229
272
  declare function useGlobalScroll(): {
230
273
  isLocked: vue.Ref<boolean>;
231
274
  lock: () => void;
@@ -264,6 +307,9 @@ declare function useLogger(scope: string, options?: Options): logdown.Logger;
264
307
  interface VNodeCustom extends VNode {
265
308
  close(): void;
266
309
  }
310
+ /**
311
+ * @deprecated use useDialog
312
+ */
267
313
  declare function usePanel(): {
268
314
  open: ({ layer, component, props, }: {
269
315
  component: Component;
@@ -300,4 +346,4 @@ declare function isTypeUrl(message?: string): RuleItem;
300
346
  declare function isTypeNumber(value?: number, message?: string): RuleItem;
301
347
  declare function isStrictLength(value?: number, message?: string): RuleItem;
302
348
 
303
- export { AppComponentsResolver, BrowserInfo, Dictionary, ResponseError, UiComponentsResolver, VersionsList, camelizeKeys, formatMoney, genHash, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, isMax, isMin, isRequired, isStrictLength, isTypeEmail, isTypeNumber, isTypeUrl, parsePhone, snakelizeKeys, unformatNumber, useAbortController, useAsyncItems, useAsyncMultiselect, useAsyncSelect, useBreakpoint, useClassName, useDayjs, useDetectBrowser, useFilters, useGlobalScroll, useLogger, usePanel, validateNumber, validatePhone };
349
+ export { AppComponentsResolver, BrowserInfo, Dictionary, ResponseError, UiComponentsResolver, VersionsList, 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 };
package/dist/index.mjs CHANGED
@@ -7,6 +7,7 @@ import { toValue, useDebounceFn, useBreakpoints } from '@vueuse/core';
7
7
  import { useQuery, useQueryClient } from '@tanstack/vue-query';
8
8
  import get from 'lodash/get.js';
9
9
  import has from 'lodash/has.js';
10
+ import union from 'lodash/union.js';
10
11
  import logdown from 'logdown';
11
12
  import dayjs from 'dayjs';
12
13
  import utc from 'dayjs/plugin/utc.js';
@@ -15,7 +16,7 @@ import updateLocale from 'dayjs/plugin/updateLocale.js';
15
16
  import isToday from 'dayjs/plugin/isToday.js';
16
17
  import customParseFormat from 'dayjs/plugin/customParseFormat.js';
17
18
  import { detect } from 'detect-browser';
18
- import { useRouter, useRoute } from 'vue-router';
19
+ import { useRoute, useRouter } from 'vue-router';
19
20
  import qs from 'qs';
20
21
 
21
22
  function AppComponentsResolver(options = {}) {
@@ -43,6 +44,20 @@ function camelizeKeys(object) {
43
44
  return object;
44
45
  }
45
46
 
47
+ const OPTIONS_DEFAULT = {
48
+ labelType: "value"
49
+ };
50
+ function convertEnumToOptions(obj, options) {
51
+ const newOptions = {
52
+ ...OPTIONS_DEFAULT,
53
+ ...options
54
+ };
55
+ return Object.entries(obj).map(([key, value]) => ({
56
+ value,
57
+ label: newOptions.labelType === "key" ? key : value
58
+ }));
59
+ }
60
+
46
61
  function formatMoney(value, currency = CURRENCY_DEFAULT, options = {}) {
47
62
  const convertedValue = Number(value);
48
63
  if (value === null || Number.isNaN(convertedValue))
@@ -127,6 +142,23 @@ function isEmptyObject(object) {
127
142
  return !object || !Object.keys(object).length;
128
143
  }
129
144
 
145
+ const optionsDefault = {
146
+ labelKey: "title",
147
+ valueKey: "",
148
+ excludedItems: []
149
+ };
150
+ function mapDataObjectForFilters(data, options) {
151
+ const newOptions = {
152
+ ...optionsDefault,
153
+ ...options
154
+ };
155
+ const { labelKey, valueKey, excludedItems } = newOptions;
156
+ return Object.entries(data).filter(([key]) => !excludedItems.includes(key)).map(([key, value]) => ({
157
+ label: value?.[labelKey] || "Unknown label",
158
+ value: value?.[valueKey] || key
159
+ }));
160
+ }
161
+
130
162
  function validateNumber(value, defaultValue) {
131
163
  if (value === "")
132
164
  return defaultValue;
@@ -363,12 +395,17 @@ function useAsyncMultiselect({
363
395
  });
364
396
  const search = ref("");
365
397
  const { call, abort } = useAbortController(apiMethod);
366
- const loadWAC = () => call({
367
- page: reactiveData.page,
368
- search: reactiveData.search,
369
- ...reactiveData.selectedValues?.length && { includedIds: reactiveData.selectedValues },
370
- ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
371
- });
398
+ const loadWAC = () => {
399
+ const includedIdsBySelectedValues = reactiveData.selectedValues ?? [];
400
+ const includedIdsByParams = JSON.parse(reactiveData.params || {})?.includedIds ?? [];
401
+ const includedIds = union(includedIdsBySelectedValues, includedIdsByParams);
402
+ return call({
403
+ page: reactiveData.page,
404
+ search: reactiveData.search,
405
+ ...reactiveData.params && { ...JSON.parse(reactiveData.params) },
406
+ ...includedIds.length && { includedIds }
407
+ });
408
+ };
372
409
  const { data, isFetching, isLoading } = useQuery({
373
410
  queryKey: [queryKey, reactiveData],
374
411
  queryFn: loadWAC
@@ -771,6 +808,240 @@ function useGlobalScroll() {
771
808
  };
772
809
  }
773
810
 
811
+ const CONFIRM_TEXT = "Are you sure you want to close? \nAll changes will be lost.";
812
+ let dialogs = [];
813
+ function useDialog() {
814
+ let appContext;
815
+ const logger = useLogger("use-dialog");
816
+ const {
817
+ isLocked: isGlobalScrollLocked,
818
+ lock: lockGlobalScroll,
819
+ unlock: unlockGlobalScroll
820
+ } = useGlobalScroll();
821
+ const route = useRoute();
822
+ const router = useRouter();
823
+ const HASH_PREFIX = "#ud_";
824
+ const parseHash = (hash, componentName) => {
825
+ if (!hash)
826
+ return void 0;
827
+ if (!hash.includes(HASH_PREFIX))
828
+ return void 0;
829
+ let dataFromHash;
830
+ try {
831
+ dataFromHash = JSON.parse(window.atob(hash.slice(HASH_PREFIX.length)));
832
+ } catch (error) {
833
+ logger.warn("*parseHash* cant parse hash");
834
+ }
835
+ if (typeof dataFromHash !== "object")
836
+ return void 0;
837
+ if (!dataFromHash.name) {
838
+ logger.warn("*parseHash* cant find component name in hash");
839
+ return void 0;
840
+ }
841
+ if (dataFromHash.name !== componentName)
842
+ return void 0;
843
+ return dataFromHash;
844
+ };
845
+ const clearHash = () => {
846
+ router.push({
847
+ name: route.name || void 0,
848
+ query: route.query,
849
+ hash: void 0
850
+ });
851
+ };
852
+ onMounted(() => {
853
+ appContext = getCurrentInstance()?.appContext;
854
+ });
855
+ const open = ({
856
+ layer = 0,
857
+ component,
858
+ props
859
+ }) => {
860
+ const uuid = genUUID();
861
+ const createComponent = () => {
862
+ const newProps = {
863
+ ...props,
864
+ layer
865
+ };
866
+ const el2 = document.createElement("div");
867
+ const vnode2 = createVNode(component, {
868
+ ...newProps,
869
+ modelValue: true,
870
+ uuid
871
+ });
872
+ vnode2.appContext = { ...appContext };
873
+ if (!vnode2?.props?.["onUpdate:modelValue"]) {
874
+ vnode2.props["onUpdate:modelValue"] = (value) => {
875
+ if (vnode2 && vnode2.component) {
876
+ vnode2.component.props.modelValue = value;
877
+ if (!value && route?.hash) {
878
+ const dataFromHash = parseHash(route.hash, component.name);
879
+ if (dataFromHash)
880
+ clearHash();
881
+ }
882
+ if (!value && (dialogs.length === 1 || layer === 0) && isGlobalScrollLocked.value) {
883
+ unlockGlobalScroll();
884
+ }
885
+ }
886
+ };
887
+ }
888
+ vnode2.close = () => {
889
+ if (!vnode2 || !vnode2.component)
890
+ return;
891
+ vnode2.component.props.modelValue = false;
892
+ if (!route?.hash)
893
+ return;
894
+ const dataFromHash = parseHash(route.hash, component.name);
895
+ if (dataFromHash)
896
+ clearHash();
897
+ };
898
+ vnode2.props.onDestroy = () => {
899
+ render(null, el2);
900
+ dialogs = dialogs.filter((dialog) => dialog.uuid !== uuid);
901
+ logger.info("Dialogs after destroy", dialogs);
902
+ };
903
+ const name = vnode2?.type?.name ?? "Unknown component";
904
+ const newDialog2 = {
905
+ uuid,
906
+ name,
907
+ vnode: vnode2,
908
+ layer
909
+ };
910
+ logger.log(`Open new dialog: "${name}"`);
911
+ if (!isGlobalScrollLocked.value) {
912
+ lockGlobalScroll();
913
+ }
914
+ return {
915
+ vnode: vnode2,
916
+ el: el2,
917
+ newDialog: newDialog2
918
+ };
919
+ };
920
+ if (!dialogs.length) {
921
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
922
+ render(vnode2, el2);
923
+ dialogs = [newDialog2];
924
+ logger.info("Dialogs after open", dialogs);
925
+ return uuid;
926
+ }
927
+ if (layer === 0) {
928
+ closeAll();
929
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
930
+ render(vnode2, el2);
931
+ dialogs = [newDialog2];
932
+ logger.info("Dialogs after open", dialogs);
933
+ return uuid;
934
+ }
935
+ if (!dialogs.some((dialog) => dialog.layer === layer)) {
936
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
937
+ render(vnode2, el2);
938
+ dialogs = [...dialogs, newDialog2];
939
+ logger.info("Dialogs after open", dialogs);
940
+ return uuid;
941
+ }
942
+ const dialogOnCurrentLayer = dialogs.find((dialog) => dialog.layer === layer);
943
+ close(dialogOnCurrentLayer?.uuid || "");
944
+ const { vnode, el, newDialog } = createComponent();
945
+ render(vnode, el);
946
+ dialogs = [...dialogs, newDialog];
947
+ logger.info("Dialogs after open", dialogs);
948
+ return uuid;
949
+ };
950
+ const close = (uuid) => {
951
+ const dialog = dialogs.find((item) => item.uuid === uuid);
952
+ logger.log(`Close dialog: "${uuid}"`);
953
+ if ((dialogs.length === 1 || dialog.layer === 0) && isGlobalScrollLocked.value) {
954
+ unlockGlobalScroll();
955
+ }
956
+ dialog?.vnode.close();
957
+ };
958
+ const closeAll = () => {
959
+ dialogs.forEach((dialog) => {
960
+ dialog?.vnode.close();
961
+ });
962
+ if (isGlobalScrollLocked.value) {
963
+ unlockGlobalScroll();
964
+ }
965
+ };
966
+ const getInstance = (uuid) => {
967
+ return dialogs.find((item) => item.uuid === uuid)?.vnode;
968
+ };
969
+ const isOnTop = (uuid) => {
970
+ if (!dialogs.length)
971
+ return false;
972
+ const dialogsSorted = [...dialogs].sort((a, b) => b.layer - a.layer);
973
+ return dialogsSorted[0].uuid === uuid;
974
+ };
975
+ const showConfirm = (text = CONFIRM_TEXT) => {
976
+ return window.confirm(text);
977
+ };
978
+ const openByHash = ({
979
+ layer = 0,
980
+ component,
981
+ props
982
+ }) => {
983
+ const data = {
984
+ name: component.name,
985
+ layer,
986
+ props
987
+ };
988
+ router.push({
989
+ name: route.name || void 0,
990
+ query: route.query,
991
+ hash: `${HASH_PREFIX}${window.btoa(JSON.stringify(data))}`
992
+ });
993
+ };
994
+ const watchHash = ({
995
+ component,
996
+ events
997
+ }) => {
998
+ logger.info(`start watching route.hash for dialog *${component.name}*`);
999
+ const stopWatch = watch(
1000
+ () => route.hash,
1001
+ async (newHash) => {
1002
+ if (!newHash) {
1003
+ if (!dialogs.length)
1004
+ return;
1005
+ closeAll();
1006
+ return;
1007
+ }
1008
+ const dataFromHash = parseHash(newHash, component.name);
1009
+ if (!dataFromHash)
1010
+ return;
1011
+ logger.info("*watchHash* data from hash", dataFromHash);
1012
+ await nextTick();
1013
+ open({
1014
+ component,
1015
+ layer: dataFromHash.layer || 0,
1016
+ props: {
1017
+ ...dataFromHash.props,
1018
+ ...events
1019
+ }
1020
+ });
1021
+ },
1022
+ { immediate: true }
1023
+ );
1024
+ const stopWatchHash = () => {
1025
+ logger.info(`stop watching route.hash for dialog *${component.name}*`);
1026
+ stopWatch();
1027
+ };
1028
+ onBeforeUnmount(() => {
1029
+ stopWatchHash();
1030
+ });
1031
+ return stopWatchHash;
1032
+ };
1033
+ return {
1034
+ open,
1035
+ getInstance,
1036
+ close,
1037
+ closeAll,
1038
+ showConfirm,
1039
+ isOnTop,
1040
+ openByHash,
1041
+ watchHash
1042
+ };
1043
+ }
1044
+
774
1045
  const QS_STRINGIFY_PARAMS = {
775
1046
  arrayFormat: "comma",
776
1047
  encode: false,
@@ -1138,4 +1409,4 @@ function isStrictLength(value = 3, message) {
1138
1409
  };
1139
1410
  }
1140
1411
 
1141
- export { AppComponentsResolver, UiComponentsResolver, camelizeKeys, formatMoney, genHash, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, isMax, isMin, isRequired, isStrictLength, isTypeEmail, isTypeNumber, isTypeUrl, parsePhone, snakelizeKeys, unformatNumber, useAbortController, useAsyncItems, useAsyncMultiselect, useAsyncSelect, useBreakpoint, useClassName, useDayjs, useDetectBrowser, useFilters, useGlobalScroll, useLogger, usePanel, validateNumber, validatePhone };
1412
+ 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@karta.io/utils",
3
- "version": "1.0.0-alpha.2",
3
+ "version": "1.0.0-alpha.21",
4
4
  "description": "karta.io utils for admin and application",
5
5
  "author": "Vitaly Blokhin <karambafe@gmail.com>",
6
6
  "homepage": "",
@@ -24,7 +24,7 @@
24
24
  "vue": "3.3.x"
25
25
  },
26
26
  "dependencies": {
27
- "@karta.io/common-data": "^1.0.0-alpha.2",
27
+ "@karta.io/common-data": "^1.0.0-alpha.21",
28
28
  "@tanstack/vue-query": "4.33.1",
29
29
  "@vueuse/core": "10.3.0",
30
30
  "async-validator": "4.2.5",