@karta.io/utils 1.0.0-alpha.1 → 1.0.0-alpha.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.
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))
@@ -75,6 +91,15 @@ function formatMoney(value, currency = commonData.CURRENCY_DEFAULT, options = {}
75
91
  return formatter.format(convertedValue);
76
92
  }
77
93
 
94
+ function genHash(hashLength) {
95
+ const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
96
+ let result = "";
97
+ for (let i = 0; i < hashLength; i++) {
98
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
99
+ }
100
+ return result;
101
+ }
102
+
78
103
  function genRandomNumber(min, max) {
79
104
  return Math.floor(Math.random() * (max - min + 1)) + min;
80
105
  }
@@ -135,6 +160,23 @@ function isEmptyObject(object) {
135
160
  return !object || !Object.keys(object).length;
136
161
  }
137
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
+
138
180
  function validateNumber(value, defaultValue) {
139
181
  if (value === "")
140
182
  return defaultValue;
@@ -371,12 +413,17 @@ function useAsyncMultiselect({
371
413
  });
372
414
  const search = vue.ref("");
373
415
  const { call, abort } = useAbortController(apiMethod);
374
- const loadWAC = () => call({
375
- page: reactiveData.page,
376
- search: reactiveData.search,
377
- ...reactiveData.selectedValues?.length && { includedIds: reactiveData.selectedValues },
378
- ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
379
- });
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
+ };
380
427
  const { data, isFetching, isLoading } = vueQuery.useQuery({
381
428
  queryKey: [queryKey, reactiveData],
382
429
  queryFn: loadWAC
@@ -779,6 +826,219 @@ function useGlobalScroll() {
779
826
  };
780
827
  }
781
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
+ vue.onMounted(() => {
842
+ appContext = vue.getCurrentInstance()?.appContext;
843
+ });
844
+ const open = ({
845
+ layer = 0,
846
+ component,
847
+ props
848
+ }) => {
849
+ const uuid = genUUID();
850
+ const createComponent = () => {
851
+ const newProps = {
852
+ ...props,
853
+ layer
854
+ };
855
+ const el2 = document.createElement("div");
856
+ const vnode2 = vue.createVNode(component, {
857
+ ...newProps,
858
+ modelValue: true,
859
+ uuid
860
+ });
861
+ vnode2.appContext = { ...appContext };
862
+ if (!vnode2?.props?.["onUpdate:modelValue"]) {
863
+ vnode2.props["onUpdate:modelValue"] = (value) => {
864
+ if (vnode2 && vnode2.component) {
865
+ vnode2.component.props.modelValue = value;
866
+ if (!value && (dialogs.length === 1 || layer === 0) && isGlobalScrollLocked.value) {
867
+ unlockGlobalScroll();
868
+ }
869
+ }
870
+ };
871
+ }
872
+ vnode2.close = () => {
873
+ if (vnode2 && vnode2.component) {
874
+ vnode2.component.props.modelValue = false;
875
+ }
876
+ };
877
+ vnode2.props.onDestroy = () => {
878
+ vue.render(null, el2);
879
+ dialogs = dialogs.filter((dialog) => dialog.uuid !== uuid);
880
+ logger.info("Dialogs after destroy", dialogs);
881
+ };
882
+ const name = vnode2?.type?.name ?? "Unknown component";
883
+ const newDialog2 = {
884
+ uuid,
885
+ name,
886
+ vnode: vnode2,
887
+ layer
888
+ };
889
+ logger.log(`Open new dialog: "${name}"`);
890
+ if (!isGlobalScrollLocked.value) {
891
+ lockGlobalScroll();
892
+ }
893
+ return {
894
+ vnode: vnode2,
895
+ el: el2,
896
+ newDialog: newDialog2
897
+ };
898
+ };
899
+ if (!dialogs.length) {
900
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
901
+ vue.render(vnode2, el2);
902
+ dialogs = [newDialog2];
903
+ logger.info("Dialogs after open", dialogs);
904
+ return uuid;
905
+ }
906
+ if (layer === 0) {
907
+ closeAll();
908
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
909
+ vue.render(vnode2, el2);
910
+ dialogs = [newDialog2];
911
+ logger.info("Dialogs after open", dialogs);
912
+ return uuid;
913
+ }
914
+ if (!dialogs.some((dialog) => dialog.layer === layer)) {
915
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
916
+ vue.render(vnode2, el2);
917
+ dialogs = [...dialogs, newDialog2];
918
+ logger.info("Dialogs after open", dialogs);
919
+ return uuid;
920
+ }
921
+ const dialogOnCurrentLayer = dialogs.find((dialog) => dialog.layer === layer);
922
+ close(dialogOnCurrentLayer?.uuid || "");
923
+ const { vnode, el, newDialog } = createComponent();
924
+ vue.render(vnode, el);
925
+ dialogs = [...dialogs, newDialog];
926
+ logger.info("Dialogs after open", dialogs);
927
+ return uuid;
928
+ };
929
+ const close = (uuid) => {
930
+ const dialog = dialogs.find((item) => item.uuid === uuid);
931
+ logger.log(`Close dialog: "${uuid}"`);
932
+ if ((dialogs.length === 1 || dialog.layer === 0) && isGlobalScrollLocked.value) {
933
+ unlockGlobalScroll();
934
+ }
935
+ dialog?.vnode.close();
936
+ };
937
+ const closeAll = () => {
938
+ dialogs.forEach((dialog) => {
939
+ dialog?.vnode.close();
940
+ });
941
+ if (isGlobalScrollLocked.value) {
942
+ unlockGlobalScroll();
943
+ }
944
+ };
945
+ const getInstance = (uuid) => {
946
+ return dialogs.find((item) => item.uuid === uuid)?.vnode;
947
+ };
948
+ const isOnTop = (uuid) => {
949
+ if (!dialogs.length)
950
+ return false;
951
+ const dialogsSorted = [...dialogs].sort((a, b) => b.layer - a.layer);
952
+ return dialogsSorted[0].uuid === uuid;
953
+ };
954
+ const showConfirm = (text = CONFIRM_TEXT) => {
955
+ return window.confirm(text);
956
+ };
957
+ const openByHash = ({
958
+ layer = 0,
959
+ component,
960
+ props
961
+ }) => {
962
+ const data = {
963
+ name: component.name,
964
+ layer,
965
+ props
966
+ };
967
+ router.push({
968
+ name: route.name || void 0,
969
+ query: route.query,
970
+ hash: `#${window.btoa(JSON.stringify(data))}`
971
+ });
972
+ };
973
+ const watchHash = ({
974
+ component,
975
+ events
976
+ }) => {
977
+ logger.info(`start watching route.hash for dialog *${component.name}*`);
978
+ const stopWatch = vue.watch(
979
+ () => route.hash,
980
+ async (newHash) => {
981
+ if (!newHash) {
982
+ closeAll();
983
+ return;
984
+ }
985
+ let dataFromHash;
986
+ try {
987
+ dataFromHash = JSON.parse(window.atob(newHash.slice(1)));
988
+ } catch (error) {
989
+ logger.error("*watchHash* cant parse hash");
990
+ }
991
+ if (typeof dataFromHash !== "object")
992
+ return;
993
+ if (!dataFromHash.name) {
994
+ logger.error("*watchHash* cant find component name in hash");
995
+ return;
996
+ }
997
+ if (dataFromHash.name !== component.name)
998
+ return;
999
+ logger.info("*watchHash* data from hash", dataFromHash);
1000
+ await vue.nextTick();
1001
+ open({
1002
+ component,
1003
+ layer: dataFromHash.layer || 0,
1004
+ props: {
1005
+ "onUpdate:modelValue": (value) => {
1006
+ if (value)
1007
+ return;
1008
+ router.push({
1009
+ name: route.name || void 0,
1010
+ query: route.query,
1011
+ hash: void 0
1012
+ });
1013
+ },
1014
+ ...dataFromHash.props,
1015
+ ...events
1016
+ }
1017
+ });
1018
+ },
1019
+ { immediate: true }
1020
+ );
1021
+ const stopWatchHash = () => {
1022
+ logger.info(`stop watching route.hash for dialog *${component.name}*`);
1023
+ stopWatch();
1024
+ };
1025
+ vue.onBeforeUnmount(() => {
1026
+ stopWatchHash();
1027
+ });
1028
+ return stopWatchHash;
1029
+ };
1030
+ return {
1031
+ open,
1032
+ getInstance,
1033
+ close,
1034
+ closeAll,
1035
+ showConfirm,
1036
+ isOnTop,
1037
+ openByHash,
1038
+ watchHash
1039
+ };
1040
+ }
1041
+
782
1042
  const QS_STRINGIFY_PARAMS = {
783
1043
  arrayFormat: "comma",
784
1044
  encode: false,
@@ -1149,7 +1409,9 @@ function isStrictLength(value = 3, message) {
1149
1409
  exports.AppComponentsResolver = AppComponentsResolver;
1150
1410
  exports.UiComponentsResolver = UiComponentsResolver;
1151
1411
  exports.camelizeKeys = camelizeKeys;
1412
+ exports.convertEnumToOptions = convertEnumToOptions;
1152
1413
  exports.formatMoney = formatMoney;
1414
+ exports.genHash = genHash;
1153
1415
  exports.genRandomNumber = genRandomNumber;
1154
1416
  exports.genUUID = genUUID;
1155
1417
  exports.getCardNumber = getCardNumber;
@@ -1167,6 +1429,7 @@ exports.isStrictLength = isStrictLength;
1167
1429
  exports.isTypeEmail = isTypeEmail;
1168
1430
  exports.isTypeNumber = isTypeNumber;
1169
1431
  exports.isTypeUrl = isTypeUrl;
1432
+ exports.mapDataObjectForFilters = mapDataObjectForFilters;
1170
1433
  exports.parsePhone = parsePhone;
1171
1434
  exports.snakelizeKeys = snakelizeKeys;
1172
1435
  exports.unformatNumber = unformatNumber;
@@ -1178,6 +1441,7 @@ exports.useBreakpoint = useBreakpoint;
1178
1441
  exports.useClassName = useClassName;
1179
1442
  exports.useDayjs = useDayjs;
1180
1443
  exports.useDetectBrowser = useDetectBrowser;
1444
+ exports.useDialog = useDialog;
1181
1445
  exports.useFilters = useFilters;
1182
1446
  exports.useGlobalScroll = useGlobalScroll;
1183
1447
  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,11 +25,21 @@ 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
  }
31
39
  declare function formatMoney(value: string | number | null | undefined, currency?: string, options?: Options$2): string;
32
40
 
41
+ declare function genHash(hashLength: number): string;
42
+
33
43
  declare function genRandomNumber(min: number, max: number): number;
34
44
 
35
45
  declare function genUUID(): string;
@@ -50,6 +60,16 @@ declare function isElementIgnored({ ignoredClasses, event, }?: {
50
60
 
51
61
  declare function isEmptyObject(object: object): boolean;
52
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
+
53
73
  declare function getPaginationParams({ page, limit, }: {
54
74
  page: string | number;
55
75
  limit: string | number;
@@ -224,6 +244,31 @@ type VersionsList = {
224
244
  };
225
245
  declare function useDetectBrowser(versions: VersionsList, userAgent?: any): BrowserInfo;
226
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
+
227
272
  declare function useGlobalScroll(): {
228
273
  isLocked: vue.Ref<boolean>;
229
274
  lock: () => void;
@@ -262,6 +307,9 @@ declare function useLogger(scope: string, options?: Options): logdown.Logger;
262
307
  interface VNodeCustom extends VNode {
263
308
  close(): void;
264
309
  }
310
+ /**
311
+ * @deprecated use useDialog
312
+ */
265
313
  declare function usePanel(): {
266
314
  open: ({ layer, component, props, }: {
267
315
  component: Component;
@@ -298,4 +346,4 @@ declare function isTypeUrl(message?: string): RuleItem;
298
346
  declare function isTypeNumber(value?: number, message?: string): RuleItem;
299
347
  declare function isStrictLength(value?: number, message?: string): RuleItem;
300
348
 
301
- export { AppComponentsResolver, BrowserInfo, Dictionary, ResponseError, UiComponentsResolver, VersionsList, camelizeKeys, formatMoney, 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))
@@ -58,6 +73,15 @@ function formatMoney(value, currency = CURRENCY_DEFAULT, options = {}) {
58
73
  return formatter.format(convertedValue);
59
74
  }
60
75
 
76
+ function genHash(hashLength) {
77
+ const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
78
+ let result = "";
79
+ for (let i = 0; i < hashLength; i++) {
80
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
81
+ }
82
+ return result;
83
+ }
84
+
61
85
  function genRandomNumber(min, max) {
62
86
  return Math.floor(Math.random() * (max - min + 1)) + min;
63
87
  }
@@ -118,6 +142,23 @@ function isEmptyObject(object) {
118
142
  return !object || !Object.keys(object).length;
119
143
  }
120
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
+
121
162
  function validateNumber(value, defaultValue) {
122
163
  if (value === "")
123
164
  return defaultValue;
@@ -354,12 +395,17 @@ function useAsyncMultiselect({
354
395
  });
355
396
  const search = ref("");
356
397
  const { call, abort } = useAbortController(apiMethod);
357
- const loadWAC = () => call({
358
- page: reactiveData.page,
359
- search: reactiveData.search,
360
- ...reactiveData.selectedValues?.length && { includedIds: reactiveData.selectedValues },
361
- ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
362
- });
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
+ };
363
409
  const { data, isFetching, isLoading } = useQuery({
364
410
  queryKey: [queryKey, reactiveData],
365
411
  queryFn: loadWAC
@@ -762,6 +808,219 @@ function useGlobalScroll() {
762
808
  };
763
809
  }
764
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
+ onMounted(() => {
824
+ appContext = getCurrentInstance()?.appContext;
825
+ });
826
+ const open = ({
827
+ layer = 0,
828
+ component,
829
+ props
830
+ }) => {
831
+ const uuid = genUUID();
832
+ const createComponent = () => {
833
+ const newProps = {
834
+ ...props,
835
+ layer
836
+ };
837
+ const el2 = document.createElement("div");
838
+ const vnode2 = createVNode(component, {
839
+ ...newProps,
840
+ modelValue: true,
841
+ uuid
842
+ });
843
+ vnode2.appContext = { ...appContext };
844
+ if (!vnode2?.props?.["onUpdate:modelValue"]) {
845
+ vnode2.props["onUpdate:modelValue"] = (value) => {
846
+ if (vnode2 && vnode2.component) {
847
+ vnode2.component.props.modelValue = value;
848
+ if (!value && (dialogs.length === 1 || layer === 0) && isGlobalScrollLocked.value) {
849
+ unlockGlobalScroll();
850
+ }
851
+ }
852
+ };
853
+ }
854
+ vnode2.close = () => {
855
+ if (vnode2 && vnode2.component) {
856
+ vnode2.component.props.modelValue = false;
857
+ }
858
+ };
859
+ vnode2.props.onDestroy = () => {
860
+ render(null, el2);
861
+ dialogs = dialogs.filter((dialog) => dialog.uuid !== uuid);
862
+ logger.info("Dialogs after destroy", dialogs);
863
+ };
864
+ const name = vnode2?.type?.name ?? "Unknown component";
865
+ const newDialog2 = {
866
+ uuid,
867
+ name,
868
+ vnode: vnode2,
869
+ layer
870
+ };
871
+ logger.log(`Open new dialog: "${name}"`);
872
+ if (!isGlobalScrollLocked.value) {
873
+ lockGlobalScroll();
874
+ }
875
+ return {
876
+ vnode: vnode2,
877
+ el: el2,
878
+ newDialog: newDialog2
879
+ };
880
+ };
881
+ if (!dialogs.length) {
882
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
883
+ render(vnode2, el2);
884
+ dialogs = [newDialog2];
885
+ logger.info("Dialogs after open", dialogs);
886
+ return uuid;
887
+ }
888
+ if (layer === 0) {
889
+ closeAll();
890
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
891
+ render(vnode2, el2);
892
+ dialogs = [newDialog2];
893
+ logger.info("Dialogs after open", dialogs);
894
+ return uuid;
895
+ }
896
+ if (!dialogs.some((dialog) => dialog.layer === layer)) {
897
+ const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
898
+ render(vnode2, el2);
899
+ dialogs = [...dialogs, newDialog2];
900
+ logger.info("Dialogs after open", dialogs);
901
+ return uuid;
902
+ }
903
+ const dialogOnCurrentLayer = dialogs.find((dialog) => dialog.layer === layer);
904
+ close(dialogOnCurrentLayer?.uuid || "");
905
+ const { vnode, el, newDialog } = createComponent();
906
+ render(vnode, el);
907
+ dialogs = [...dialogs, newDialog];
908
+ logger.info("Dialogs after open", dialogs);
909
+ return uuid;
910
+ };
911
+ const close = (uuid) => {
912
+ const dialog = dialogs.find((item) => item.uuid === uuid);
913
+ logger.log(`Close dialog: "${uuid}"`);
914
+ if ((dialogs.length === 1 || dialog.layer === 0) && isGlobalScrollLocked.value) {
915
+ unlockGlobalScroll();
916
+ }
917
+ dialog?.vnode.close();
918
+ };
919
+ const closeAll = () => {
920
+ dialogs.forEach((dialog) => {
921
+ dialog?.vnode.close();
922
+ });
923
+ if (isGlobalScrollLocked.value) {
924
+ unlockGlobalScroll();
925
+ }
926
+ };
927
+ const getInstance = (uuid) => {
928
+ return dialogs.find((item) => item.uuid === uuid)?.vnode;
929
+ };
930
+ const isOnTop = (uuid) => {
931
+ if (!dialogs.length)
932
+ return false;
933
+ const dialogsSorted = [...dialogs].sort((a, b) => b.layer - a.layer);
934
+ return dialogsSorted[0].uuid === uuid;
935
+ };
936
+ const showConfirm = (text = CONFIRM_TEXT) => {
937
+ return window.confirm(text);
938
+ };
939
+ const openByHash = ({
940
+ layer = 0,
941
+ component,
942
+ props
943
+ }) => {
944
+ const data = {
945
+ name: component.name,
946
+ layer,
947
+ props
948
+ };
949
+ router.push({
950
+ name: route.name || void 0,
951
+ query: route.query,
952
+ hash: `#${window.btoa(JSON.stringify(data))}`
953
+ });
954
+ };
955
+ const watchHash = ({
956
+ component,
957
+ events
958
+ }) => {
959
+ logger.info(`start watching route.hash for dialog *${component.name}*`);
960
+ const stopWatch = watch(
961
+ () => route.hash,
962
+ async (newHash) => {
963
+ if (!newHash) {
964
+ closeAll();
965
+ return;
966
+ }
967
+ let dataFromHash;
968
+ try {
969
+ dataFromHash = JSON.parse(window.atob(newHash.slice(1)));
970
+ } catch (error) {
971
+ logger.error("*watchHash* cant parse hash");
972
+ }
973
+ if (typeof dataFromHash !== "object")
974
+ return;
975
+ if (!dataFromHash.name) {
976
+ logger.error("*watchHash* cant find component name in hash");
977
+ return;
978
+ }
979
+ if (dataFromHash.name !== component.name)
980
+ return;
981
+ logger.info("*watchHash* data from hash", dataFromHash);
982
+ await nextTick();
983
+ open({
984
+ component,
985
+ layer: dataFromHash.layer || 0,
986
+ props: {
987
+ "onUpdate:modelValue": (value) => {
988
+ if (value)
989
+ return;
990
+ router.push({
991
+ name: route.name || void 0,
992
+ query: route.query,
993
+ hash: void 0
994
+ });
995
+ },
996
+ ...dataFromHash.props,
997
+ ...events
998
+ }
999
+ });
1000
+ },
1001
+ { immediate: true }
1002
+ );
1003
+ const stopWatchHash = () => {
1004
+ logger.info(`stop watching route.hash for dialog *${component.name}*`);
1005
+ stopWatch();
1006
+ };
1007
+ onBeforeUnmount(() => {
1008
+ stopWatchHash();
1009
+ });
1010
+ return stopWatchHash;
1011
+ };
1012
+ return {
1013
+ open,
1014
+ getInstance,
1015
+ close,
1016
+ closeAll,
1017
+ showConfirm,
1018
+ isOnTop,
1019
+ openByHash,
1020
+ watchHash
1021
+ };
1022
+ }
1023
+
765
1024
  const QS_STRINGIFY_PARAMS = {
766
1025
  arrayFormat: "comma",
767
1026
  encode: false,
@@ -1129,4 +1388,4 @@ function isStrictLength(value = 3, message) {
1129
1388
  };
1130
1389
  }
1131
1390
 
1132
- export { AppComponentsResolver, UiComponentsResolver, camelizeKeys, formatMoney, 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 };
1391
+ 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.1",
3
+ "version": "1.0.0-alpha.10",
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.1",
27
+ "@karta.io/common-data": "^1.0.0-alpha.10",
28
28
  "@tanstack/vue-query": "4.33.1",
29
29
  "@vueuse/core": "10.3.0",
30
30
  "async-validator": "4.2.5",