@karta.io/utils 1.0.0-alpha.0 → 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
@@ -5,10 +5,11 @@ const commonData = require('@karta.io/common-data');
5
5
  const libphonenumberJs = require('libphonenumber-js');
6
6
  const snakeCase = require('lodash/snakeCase.js');
7
7
  const vue = require('vue');
8
- const vueQuery = require('@tanstack/vue-query');
9
8
  const core = require('@vueuse/core');
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;
@@ -273,6 +315,50 @@ function useAbortController(callback) {
273
315
  };
274
316
  }
275
317
 
318
+ function useAsyncItems({
319
+ apiMethod,
320
+ queryKey,
321
+ params,
322
+ config = void 0
323
+ }) {
324
+ const getQueryKey = () => [queryKey, params];
325
+ const { call, abort } = useAbortController(apiMethod);
326
+ const { isLoading, isFetching, isError, data, error } = vueQuery.useQuery({
327
+ queryKey: getQueryKey(),
328
+ queryFn: () => call(core.toValue(params), config)
329
+ });
330
+ const items = vue.computed(() => data.value?.results || []);
331
+ const count = vue.ref(0);
332
+ vue.watch(
333
+ data,
334
+ (newValue) => {
335
+ if (newValue === void 0 || newValue.count === void 0)
336
+ return;
337
+ count.value = newValue.count;
338
+ },
339
+ { immediate: true }
340
+ );
341
+ const queryClient = vueQuery.useQueryClient();
342
+ const refetch = () => {
343
+ queryClient.invalidateQueries({ queryKey: getQueryKey() });
344
+ };
345
+ const reload = () => {
346
+ queryClient.resetQueries({ queryKey: getQueryKey() });
347
+ };
348
+ return {
349
+ isLoading,
350
+ isFetching,
351
+ isError,
352
+ data,
353
+ error,
354
+ items,
355
+ count,
356
+ refetch,
357
+ reload,
358
+ abort
359
+ };
360
+ }
361
+
276
362
  function isEnabled(options) {
277
363
  if (options?.debug !== void 0)
278
364
  return options.debug;
@@ -327,12 +413,17 @@ function useAsyncMultiselect({
327
413
  });
328
414
  const search = vue.ref("");
329
415
  const { call, abort } = useAbortController(apiMethod);
330
- const loadWAC = () => call({
331
- page: reactiveData.page,
332
- search: reactiveData.search,
333
- ...reactiveData.selectedValues?.length && { includedIds: reactiveData.selectedValues },
334
- ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
335
- });
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
+ };
336
427
  const { data, isFetching, isLoading } = vueQuery.useQuery({
337
428
  queryKey: [queryKey, reactiveData],
338
429
  queryFn: loadWAC
@@ -735,6 +826,219 @@ function useGlobalScroll() {
735
826
  };
736
827
  }
737
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
+
738
1042
  const QS_STRINGIFY_PARAMS = {
739
1043
  arrayFormat: "comma",
740
1044
  encode: false,
@@ -1105,7 +1409,9 @@ function isStrictLength(value = 3, message) {
1105
1409
  exports.AppComponentsResolver = AppComponentsResolver;
1106
1410
  exports.UiComponentsResolver = UiComponentsResolver;
1107
1411
  exports.camelizeKeys = camelizeKeys;
1412
+ exports.convertEnumToOptions = convertEnumToOptions;
1108
1413
  exports.formatMoney = formatMoney;
1414
+ exports.genHash = genHash;
1109
1415
  exports.genRandomNumber = genRandomNumber;
1110
1416
  exports.genUUID = genUUID;
1111
1417
  exports.getCardNumber = getCardNumber;
@@ -1123,16 +1429,19 @@ exports.isStrictLength = isStrictLength;
1123
1429
  exports.isTypeEmail = isTypeEmail;
1124
1430
  exports.isTypeNumber = isTypeNumber;
1125
1431
  exports.isTypeUrl = isTypeUrl;
1432
+ exports.mapDataObjectForFilters = mapDataObjectForFilters;
1126
1433
  exports.parsePhone = parsePhone;
1127
1434
  exports.snakelizeKeys = snakelizeKeys;
1128
1435
  exports.unformatNumber = unformatNumber;
1129
1436
  exports.useAbortController = useAbortController;
1437
+ exports.useAsyncItems = useAsyncItems;
1130
1438
  exports.useAsyncMultiselect = useAsyncMultiselect;
1131
1439
  exports.useAsyncSelect = useAsyncSelect;
1132
1440
  exports.useBreakpoint = useBreakpoint;
1133
1441
  exports.useClassName = useClassName;
1134
1442
  exports.useDayjs = useDayjs;
1135
1443
  exports.useDetectBrowser = useDetectBrowser;
1444
+ exports.useDialog = useDialog;
1136
1445
  exports.useFilters = useFilters;
1137
1446
  exports.useGlobalScroll = useGlobalScroll;
1138
1447
  exports.useLogger = useLogger;
package/dist/index.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import * as vue from 'vue';
2
- import { Ref, Component, EmitsOptions, VNode } from 'vue';
3
- import { MaybeRef } from '@vueuse/core';
2
+ import { MaybeRef, Component, EmitsOptions, VNode, Ref } from 'vue';
3
+ import { AxiosRequestConfig } from 'axios';
4
+ export { AxiosError as HttpError, AxiosPromise as HttpPromise, AxiosRequestConfig as HttpRequestConfig, AxiosResponse as HttpResponse } from 'axios';
5
+ import { MaybeRef as MaybeRef$1 } from '@vueuse/core';
4
6
  import dayjs from 'dayjs';
5
7
  import { Browser } from 'detect-browser';
6
8
  import logdown from 'logdown';
7
9
  import { RuleItem } from 'async-validator';
8
- export { AxiosError as HttpError, AxiosPromise as HttpPromise, AxiosRequestConfig as HttpRequestConfig, AxiosResponse as HttpResponse } from 'axios';
9
10
 
10
11
  interface AppComponentsResolverOptions {
11
12
  prefix?: string;
@@ -24,11 +25,21 @@ interface ResponseError {
24
25
 
25
26
  declare function camelizeKeys(object: Dictionary): Dictionary;
26
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
+
27
36
  interface Options$2 extends Intl.NumberFormatOptions {
28
37
  locale?: string;
29
38
  }
30
39
  declare function formatMoney(value: string | number | null | undefined, currency?: string, options?: Options$2): string;
31
40
 
41
+ declare function genHash(hashLength: number): string;
42
+
32
43
  declare function genRandomNumber(min: number, max: number): number;
33
44
 
34
45
  declare function genUUID(): string;
@@ -49,6 +60,16 @@ declare function isElementIgnored({ ignoredClasses, event, }?: {
49
60
 
50
61
  declare function isEmptyObject(object: object): boolean;
51
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
+
52
73
  declare function getPaginationParams({ page, limit, }: {
53
74
  page: string | number;
54
75
  limit: string | number;
@@ -106,6 +127,24 @@ declare function useAbortController<T extends (...args: any[]) => any>(callback:
106
127
  isAborted(error: ResponseError): boolean;
107
128
  };
108
129
 
130
+ declare function useAsyncItems<T extends (...args: any[]) => any>({ apiMethod, queryKey, params, config, }: {
131
+ apiMethod: T;
132
+ queryKey: string;
133
+ params: MaybeRef<Parameters<T>[0]>;
134
+ config?: AxiosRequestConfig;
135
+ }): {
136
+ isLoading: vue.Ref<false> | vue.Ref<true>;
137
+ isFetching: vue.Ref<boolean>;
138
+ isError: vue.Ref<false> | vue.Ref<true>;
139
+ data: vue.Ref<any>;
140
+ error: vue.Ref<unknown>;
141
+ items: vue.ComputedRef<Awaited<ReturnType<T>>["results"]>;
142
+ count: vue.Ref<number>;
143
+ refetch: () => void;
144
+ reload: () => void;
145
+ abort: () => void;
146
+ };
147
+
109
148
  interface ReactiveData$1 {
110
149
  search: string;
111
150
  page: number;
@@ -115,8 +154,8 @@ interface ReactiveData$1 {
115
154
  declare function useAsyncMultiselect<T extends (...args: any[]) => any, K extends (params: any) => any>({ apiMethod, mapOptionCallback, selectedValues, params, queryKey, dataItemsKey, dataItemIdKey, dataCountKey, delay, onUpdated, }: {
116
155
  apiMethod: T;
117
156
  mapOptionCallback?: K;
118
- selectedValues?: MaybeRef<Parameters<T>[0]['includedIds']>;
119
- params?: MaybeRef<Partial<Parameters<T>[0]>>;
157
+ selectedValues?: MaybeRef$1<Parameters<T>[0]['includedIds']>;
158
+ params?: MaybeRef$1<Partial<Parameters<T>[0]>>;
120
159
  queryKey: string;
121
160
  dataItemsKey?: string;
122
161
  dataItemIdKey?: string;
@@ -143,8 +182,8 @@ interface ReactiveData {
143
182
  declare function useAsyncSelect<T extends (...args: any[]) => any, K extends (params: any) => any>({ apiMethod, mapOptionCallback, selectedValue, params, queryKey, dataItemsKey, dataCountKey, delay, onUpdated, }: {
144
183
  apiMethod: T;
145
184
  mapOptionCallback?: K;
146
- selectedValue?: MaybeRef<Parameters<T>[0]['includedIds']>;
147
- params?: MaybeRef<Partial<Parameters<T>[0]>>;
185
+ selectedValue?: MaybeRef$1<Parameters<T>[0]['includedIds']>;
186
+ params?: MaybeRef$1<Partial<Parameters<T>[0]>>;
148
187
  queryKey: string;
149
188
  dataItemsKey?: string;
150
189
  dataCountKey?: string;
@@ -205,6 +244,31 @@ type VersionsList = {
205
244
  };
206
245
  declare function useDetectBrowser(versions: VersionsList, userAgent?: any): BrowserInfo;
207
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
+
208
272
  declare function useGlobalScroll(): {
209
273
  isLocked: vue.Ref<boolean>;
210
274
  lock: () => void;
@@ -243,6 +307,9 @@ declare function useLogger(scope: string, options?: Options): logdown.Logger;
243
307
  interface VNodeCustom extends VNode {
244
308
  close(): void;
245
309
  }
310
+ /**
311
+ * @deprecated use useDialog
312
+ */
246
313
  declare function usePanel(): {
247
314
  open: ({ layer, component, props, }: {
248
315
  component: Component;
@@ -279,4 +346,4 @@ declare function isTypeUrl(message?: string): RuleItem;
279
346
  declare function isTypeNumber(value?: number, message?: string): RuleItem;
280
347
  declare function isStrictLength(value?: number, message?: string): RuleItem;
281
348
 
282
- 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, 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
@@ -2,11 +2,12 @@ import camelCase from 'lodash/camelCase.js';
2
2
  import { CURRENCY_DEFAULT, BREAKPOINTS } from '@karta.io/common-data';
3
3
  import { parsePhoneNumberFromString } from 'libphonenumber-js';
4
4
  import snakeCase from 'lodash/snakeCase.js';
5
- import { reactive, ref, watch, computed, isRef, nextTick, onBeforeUnmount, onMounted, getCurrentInstance, render, createVNode } from 'vue';
6
- import { useQuery } from '@tanstack/vue-query';
5
+ import { computed, ref, watch, reactive, isRef, nextTick, onBeforeUnmount, onMounted, getCurrentInstance, render, createVNode } from 'vue';
7
6
  import { toValue, useDebounceFn, useBreakpoints } from '@vueuse/core';
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;
@@ -256,6 +297,50 @@ function useAbortController(callback) {
256
297
  };
257
298
  }
258
299
 
300
+ function useAsyncItems({
301
+ apiMethod,
302
+ queryKey,
303
+ params,
304
+ config = void 0
305
+ }) {
306
+ const getQueryKey = () => [queryKey, params];
307
+ const { call, abort } = useAbortController(apiMethod);
308
+ const { isLoading, isFetching, isError, data, error } = useQuery({
309
+ queryKey: getQueryKey(),
310
+ queryFn: () => call(toValue(params), config)
311
+ });
312
+ const items = computed(() => data.value?.results || []);
313
+ const count = ref(0);
314
+ watch(
315
+ data,
316
+ (newValue) => {
317
+ if (newValue === void 0 || newValue.count === void 0)
318
+ return;
319
+ count.value = newValue.count;
320
+ },
321
+ { immediate: true }
322
+ );
323
+ const queryClient = useQueryClient();
324
+ const refetch = () => {
325
+ queryClient.invalidateQueries({ queryKey: getQueryKey() });
326
+ };
327
+ const reload = () => {
328
+ queryClient.resetQueries({ queryKey: getQueryKey() });
329
+ };
330
+ return {
331
+ isLoading,
332
+ isFetching,
333
+ isError,
334
+ data,
335
+ error,
336
+ items,
337
+ count,
338
+ refetch,
339
+ reload,
340
+ abort
341
+ };
342
+ }
343
+
259
344
  function isEnabled(options) {
260
345
  if (options?.debug !== void 0)
261
346
  return options.debug;
@@ -310,12 +395,17 @@ function useAsyncMultiselect({
310
395
  });
311
396
  const search = ref("");
312
397
  const { call, abort } = useAbortController(apiMethod);
313
- const loadWAC = () => call({
314
- page: reactiveData.page,
315
- search: reactiveData.search,
316
- ...reactiveData.selectedValues?.length && { includedIds: reactiveData.selectedValues },
317
- ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
318
- });
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
+ };
319
409
  const { data, isFetching, isLoading } = useQuery({
320
410
  queryKey: [queryKey, reactiveData],
321
411
  queryFn: loadWAC
@@ -718,6 +808,219 @@ function useGlobalScroll() {
718
808
  };
719
809
  }
720
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
+
721
1024
  const QS_STRINGIFY_PARAMS = {
722
1025
  arrayFormat: "comma",
723
1026
  encode: false,
@@ -1085,4 +1388,4 @@ function isStrictLength(value = 3, message) {
1085
1388
  };
1086
1389
  }
1087
1390
 
1088
- 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, 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.0",
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.0",
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",