@karta.io/utils 0.34.1 → 0.35.1

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,7 +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');
8
9
  const core = require('@vueuse/core');
10
+ const get = require('lodash/get.js');
11
+ const has = require('lodash/has.js');
12
+ const logdown = require('logdown');
9
13
  const dayjs = require('dayjs');
10
14
  const utc = require('dayjs/plugin/utc.js');
11
15
  const tz = require('dayjs/plugin/timezone.js');
@@ -13,19 +17,20 @@ const updateLocale = require('dayjs/plugin/updateLocale.js');
13
17
  const isToday = require('dayjs/plugin/isToday.js');
14
18
  const customParseFormat = require('dayjs/plugin/customParseFormat.js');
15
19
  const detectBrowser = require('detect-browser');
16
- const logdown = require('logdown');
17
20
 
18
21
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
19
22
 
20
23
  const camelCase__default = /*#__PURE__*/_interopDefaultCompat(camelCase);
21
24
  const snakeCase__default = /*#__PURE__*/_interopDefaultCompat(snakeCase);
25
+ const get__default = /*#__PURE__*/_interopDefaultCompat(get);
26
+ const has__default = /*#__PURE__*/_interopDefaultCompat(has);
27
+ const logdown__default = /*#__PURE__*/_interopDefaultCompat(logdown);
22
28
  const dayjs__default = /*#__PURE__*/_interopDefaultCompat(dayjs);
23
29
  const utc__default = /*#__PURE__*/_interopDefaultCompat(utc);
24
30
  const tz__default = /*#__PURE__*/_interopDefaultCompat(tz);
25
31
  const updateLocale__default = /*#__PURE__*/_interopDefaultCompat(updateLocale);
26
32
  const isToday__default = /*#__PURE__*/_interopDefaultCompat(isToday);
27
33
  const customParseFormat__default = /*#__PURE__*/_interopDefaultCompat(customParseFormat);
28
- const logdown__default = /*#__PURE__*/_interopDefaultCompat(logdown);
29
34
 
30
35
  function camelizeKeys(object) {
31
36
  if (Array.isArray(object))
@@ -268,128 +273,326 @@ function useAbortController(callback) {
268
273
  };
269
274
  }
270
275
 
276
+ function isEnabled(options) {
277
+ if (options?.debug !== void 0)
278
+ return options.debug;
279
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
280
+ if (isBrowser) {
281
+ const debug = localStorage.getItem("debug");
282
+ if (debug === "true")
283
+ return true;
284
+ if (debug === "false")
285
+ return false;
286
+ }
287
+ const isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
288
+ if (isNode) {
289
+ const debug = process.env.NODE_DEBUG;
290
+ if (debug === "true")
291
+ return true;
292
+ if (debug === "false")
293
+ return false;
294
+ }
295
+ return false;
296
+ }
297
+ function useLogger(scope, options) {
298
+ const prefix = options?.tag ? `[${scope.toUpperCase()}.${options.tag}]:` : `[${scope.toUpperCase()}]:`;
299
+ const logger = logdown__default(prefix, { prefixColor: options?.color });
300
+ logger.state.isEnabled = isEnabled(options);
301
+ return logger;
302
+ }
303
+
271
304
  function useAsyncMultiselect({
272
305
  apiMethod,
273
- mapResultCallback,
274
- selectedValues,
275
- params = void 0
306
+ mapOptionCallback = void 0,
307
+ selectedValues = void 0,
308
+ params = void 0,
309
+ queryKey,
310
+ dataItemsKey = "results",
311
+ dataItemIdKey = "id",
312
+ dataCountKey = "count",
313
+ delay = 300,
314
+ onUpdated = void 0
276
315
  }) {
277
- const items = vue.ref(/* @__PURE__ */ new Map());
278
- const loading = vue.ref(false);
279
- const search = vue.ref("");
316
+ const logger = useLogger("UTILS", {
317
+ tag: "useAsyncMultiselect",
318
+ color: "#b54708",
319
+ debug: true
320
+ });
321
+ const paramsForLogger = { queryKey, dataItemsKey, dataItemIdKey, dataCountKey };
322
+ const reactiveData = vue.reactive({
323
+ search: "",
324
+ page: 1,
325
+ selectedValues: core.toValue(selectedValues),
326
+ params: JSON.stringify(core.toValue(params))
327
+ });
328
+ const { call, abort } = useAbortController(apiMethod);
329
+ const loadWAC = () => call({
330
+ page: reactiveData.page,
331
+ search: reactiveData.search,
332
+ ...reactiveData.selectedValues?.length && { includedIds: reactiveData.selectedValues },
333
+ ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
334
+ });
335
+ const { data, isFetching, isLoading } = vueQuery.useQuery({
336
+ queryKey: [queryKey, reactiveData],
337
+ queryFn: loadWAC
338
+ });
339
+ const itemsByPages = vue.ref(null);
280
340
  const count = vue.ref(0);
281
- const page = vue.ref(1);
282
- const options = vue.computed(() => [...items.value.values()]);
283
- const hasNextPage = vue.computed(() => count.value > items.value.size);
284
- const { call: apiMethodWAC, abort, isAborted } = useAbortController(apiMethod);
285
- const handleSearch = async (value) => {
286
- if (search.value === value)
287
- return;
288
- search.value = value;
289
- await loadItemsWithDebounce();
290
- };
291
- const loadItems = async (isSearch) => {
292
- loading.value = true;
293
- try {
294
- const { results, count: itemsCount } = await apiMethodWAC({
295
- page: page.value,
296
- search: search.value,
297
- ...selectedValues.value?.length && !search.value && { includedIds: selectedValues.value },
298
- ...params
299
- });
300
- count.value = itemsCount;
301
- if (isSearch) {
302
- const cashedMapItems = selectedValues.value.map((selectedValue) => [
303
- selectedValue,
304
- items.value.get(selectedValue)
305
- ]);
306
- items.value = new Map([...cashedMapItems]);
341
+ const selectedItemsCached = vue.ref([]);
342
+ vue.watch(
343
+ data,
344
+ (newValue) => {
345
+ if (!newValue)
346
+ return;
347
+ if (!has__default(newValue, dataItemsKey)) {
348
+ logger.warn(
349
+ `Unable to find key *"${dataItemsKey}"* (property "dataItemsKey") in data object from API.`,
350
+ paramsForLogger
351
+ );
352
+ return;
307
353
  }
308
- const resultsForMap = results.map(mapResultCallback);
309
- items.value = new Map([...items.value, ...resultsForMap]);
310
- page.value += 1;
311
- loading.value = false;
312
- } catch (error) {
313
- if (isAborted(error))
354
+ if (!has__default(newValue, dataCountKey)) {
355
+ logger.warn(
356
+ `Unable to find key *"${dataCountKey}"* (property "dataCountKey") in data object from API.`,
357
+ paramsForLogger
358
+ );
314
359
  return;
315
- loading.value = false;
360
+ }
361
+ if (!get__default(newValue, dataItemsKey) || get__default(newValue, dataCountKey) === void 0)
362
+ return;
363
+ count.value = get__default(newValue, dataCountKey, 0);
364
+ const newItems = get__default(newValue, dataItemsKey);
365
+ itemsByPages.value = {
366
+ ...reactiveData.page !== 1 && itemsByPages.value,
367
+ [reactiveData.page]: newItems
368
+ };
369
+ if (reactiveData.page === 1 && reactiveData.selectedValues?.length && !reactiveData.search) {
370
+ if (newItems.some((item) => !has__default(item, dataItemIdKey))) {
371
+ logger.warn(
372
+ `Unable to find key *"${dataItemIdKey}"* (property "dataItemIdKey") in items from API.`,
373
+ 'This key must be match with "optionValue" in UiMultiselect.',
374
+ paramsForLogger
375
+ );
376
+ }
377
+ selectedItemsCached.value = newItems.filter(
378
+ (item) => reactiveData.selectedValues.includes(get__default(item, dataItemIdKey))
379
+ );
380
+ }
381
+ onUpdated?.({
382
+ search: reactiveData.search,
383
+ page: reactiveData.page,
384
+ selectedValues: reactiveData.selectedValues,
385
+ params: reactiveData.params ? JSON.parse(reactiveData.params) : void 0
386
+ });
387
+ },
388
+ { immediate: true }
389
+ );
390
+ const items = vue.computed(() => {
391
+ if (!itemsByPages.value)
392
+ return selectedItemsCached.value;
393
+ if (!Object.keys(itemsByPages.value).length)
394
+ return selectedItemsCached.value;
395
+ const itemsByPagesAsArray = Object.values(itemsByPages.value).reduce(
396
+ (acc, item) => [...acc, ...item],
397
+ []
398
+ );
399
+ const itemsAsArray = [...selectedItemsCached.value, ...itemsByPagesAsArray];
400
+ const itemsAsMap = itemsAsArray.reduce((acc, item) => {
401
+ const key = get__default(item, dataItemIdKey, JSON.stringify(item));
402
+ return acc.set(key, item);
403
+ }, /* @__PURE__ */ new Map());
404
+ return [...itemsAsMap.values()];
405
+ });
406
+ const options = vue.computed(() => {
407
+ if (!items.value.length)
408
+ return [];
409
+ if (!mapOptionCallback)
410
+ return this.items.value;
411
+ return items.value.map(mapOptionCallback);
412
+ });
413
+ const hasNextPage = vue.computed(() => count.value > items.value.length);
414
+ const loadPage = (newPage = 1) => {
415
+ reactiveData.page = newPage;
416
+ if (newPage === 1) {
417
+ reactiveData.selectedValues = core.toValue(selectedValues);
316
418
  }
317
419
  };
318
- const loadItemsWithDebounce = core.useDebounceFn(async () => {
319
- page.value = 1;
320
- await loadItems(true);
321
- }, 300);
420
+ const updateSearchWithDebounce = core.useDebounceFn((value) => {
421
+ reactiveData.search = value;
422
+ reactiveData.page = 1;
423
+ reactiveData.selectedValues = core.toValue(selectedValues);
424
+ }, delay);
425
+ const updateSearch = (value) => {
426
+ updateSearchWithDebounce(value);
427
+ };
428
+ if (vue.isRef(selectedValues)) {
429
+ vue.watch(selectedValues, async (newSelectedValues) => {
430
+ if (!newSelectedValues.length) {
431
+ selectedItemsCached.value = [];
432
+ } else {
433
+ if (items.value.some((item) => !has__default(item, dataItemIdKey))) {
434
+ logger.warn(
435
+ `Unable to find key *"${dataItemIdKey}"* (property "dataItemIdKey") in items from API.`,
436
+ 'This key must be match with "optionValue" in UiMultiselect.',
437
+ paramsForLogger
438
+ );
439
+ }
440
+ selectedItemsCached.value = items.value.filter(
441
+ (item) => newSelectedValues.includes(get__default(item, dataItemIdKey))
442
+ );
443
+ }
444
+ await vue.nextTick();
445
+ if (reactiveData.page === 1) {
446
+ reactiveData.selectedValues = newSelectedValues;
447
+ }
448
+ });
449
+ }
450
+ if (vue.isRef(params)) {
451
+ vue.watch(params, (newParams) => {
452
+ reactiveData.page = 1;
453
+ reactiveData.params = JSON.stringify(newParams);
454
+ reactiveData.selectedValues = core.toValue(selectedValues);
455
+ });
456
+ }
322
457
  vue.onBeforeUnmount(() => {
323
458
  abort?.();
324
459
  });
325
460
  return {
326
- search,
461
+ items,
327
462
  options,
328
- loading,
463
+ search: vue.computed(() => reactiveData.search),
329
464
  hasNextPage,
330
- items,
331
- loadItems,
332
- handleSearch
465
+ isFetching,
466
+ isLoading,
467
+ loadPage,
468
+ updateSearch
333
469
  };
334
470
  }
335
471
 
336
472
  function useAsyncSelect({
337
473
  apiMethod,
338
- mapResultCallback,
339
- includedIds = void 0,
340
- params = void 0
474
+ mapOptionCallback = void 0,
475
+ selectedValue = void 0,
476
+ params = void 0,
477
+ queryKey,
478
+ dataItemsKey = "results",
479
+ dataCountKey = "count",
480
+ delay = 300,
481
+ onUpdated = void 0
341
482
  }) {
342
- const items = vue.ref(/* @__PURE__ */ new Map());
343
- const loading = vue.ref(false);
344
- const search = vue.ref("");
483
+ const logger = useLogger("UTILS", {
484
+ tag: "useAsyncSelect",
485
+ color: "#b54708",
486
+ debug: true
487
+ });
488
+ const paramsForLogger = { queryKey, dataItemsKey, dataCountKey };
489
+ const reactiveData = vue.reactive({
490
+ search: "",
491
+ page: 1,
492
+ selectedValue: core.toValue(selectedValue),
493
+ params: JSON.stringify(core.toValue(params))
494
+ });
495
+ const { call, abort } = useAbortController(apiMethod);
496
+ const loadWAC = () => call({
497
+ page: reactiveData.page,
498
+ search: reactiveData.search,
499
+ ...reactiveData.selectedValue && { includedIds: [reactiveData.selectedValue] },
500
+ ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
501
+ });
502
+ const { data, isFetching, isLoading } = vueQuery.useQuery({
503
+ queryKey: [queryKey, reactiveData],
504
+ queryFn: loadWAC
505
+ });
506
+ const itemsByPages = vue.ref(null);
345
507
  const count = vue.ref(0);
346
- const page = vue.ref(1);
347
- const options = vue.computed(() => [...items.value.values()]);
348
- const hasNextPage = vue.computed(() => count.value > items.value.size);
349
- const { call: apiMethodWAC, abort, isAborted } = useAbortController(apiMethod);
350
- const handleSearch = async (value) => {
351
- if (search.value === value)
352
- return;
353
- search.value = value;
354
- await loadItemsWithDebounce();
355
- };
356
- const loadItems = async (isSearch) => {
357
- loading.value = true;
358
- try {
359
- const { results, count: itemsCount } = await apiMethodWAC({
360
- page: page.value,
361
- search: search.value,
362
- ...includedIds?.length && includedIds,
363
- ...params
364
- });
365
- count.value = itemsCount;
366
- if (isSearch)
367
- items.value = /* @__PURE__ */ new Map();
368
- const resultsForMap = results.map(mapResultCallback);
369
- items.value = new Map([...items.value, ...resultsForMap]);
370
- page.value += 1;
371
- loading.value = false;
372
- } catch (error) {
373
- if (isAborted(error))
508
+ vue.watch(
509
+ data,
510
+ (newValue) => {
511
+ if (!newValue)
374
512
  return;
375
- loading.value = false;
376
- }
513
+ if (!has__default(newValue, dataItemsKey)) {
514
+ logger.warn(
515
+ `Unable to find key *"${dataItemsKey}"* (property "dataItemsKey") in data object from API.`,
516
+ paramsForLogger
517
+ );
518
+ return;
519
+ }
520
+ if (!has__default(newValue, dataCountKey)) {
521
+ logger.warn(
522
+ `Unable to find key *"${dataCountKey}"* (property "dataCountKey") in data object from API.`,
523
+ paramsForLogger
524
+ );
525
+ return;
526
+ }
527
+ if (!get__default(newValue, dataItemsKey) || get__default(newValue, dataCountKey) === void 0)
528
+ return;
529
+ count.value = get__default(newValue, dataCountKey, 0);
530
+ const newItems = get__default(newValue, dataItemsKey);
531
+ itemsByPages.value = {
532
+ ...reactiveData.page !== 1 && itemsByPages.value,
533
+ [reactiveData.page]: newItems
534
+ };
535
+ onUpdated?.({
536
+ search: reactiveData.search,
537
+ page: reactiveData.page,
538
+ selectedValue: reactiveData.selectedValue,
539
+ params: reactiveData.params ? JSON.parse(reactiveData.params) : void 0
540
+ });
541
+ },
542
+ { immediate: true }
543
+ );
544
+ const items = vue.computed(() => {
545
+ if (!itemsByPages.value)
546
+ return [];
547
+ if (!Object.keys(itemsByPages.value).length)
548
+ return [];
549
+ return Object.values(itemsByPages.value).reduce(
550
+ (acc, item) => [...acc, ...item],
551
+ []
552
+ );
553
+ });
554
+ const options = vue.computed(() => {
555
+ if (!items.value.length)
556
+ return [];
557
+ if (!mapOptionCallback)
558
+ return this.items.value;
559
+ return items.value.map(mapOptionCallback);
560
+ });
561
+ const hasNextPage = vue.computed(() => count.value > items.value.length);
562
+ const loadPage = (newPage = 1) => {
563
+ reactiveData.page = newPage;
564
+ };
565
+ const updateSearchWithDebounce = core.useDebounceFn((value) => {
566
+ reactiveData.search = value;
567
+ reactiveData.page = 1;
568
+ }, delay);
569
+ const updateSearch = (value) => {
570
+ updateSearchWithDebounce(value);
377
571
  };
378
- const loadItemsWithDebounce = core.useDebounceFn(async () => {
379
- page.value = 1;
380
- await loadItems(true);
381
- }, 300);
572
+ if (vue.isRef(selectedValue)) {
573
+ vue.watch(selectedValue, (newSelectedValue) => {
574
+ reactiveData.page = 1;
575
+ reactiveData.selectedValue = newSelectedValue;
576
+ });
577
+ }
578
+ if (vue.isRef(params)) {
579
+ vue.watch(params, (newParams) => {
580
+ reactiveData.page = 1;
581
+ reactiveData.params = JSON.stringify(newParams);
582
+ });
583
+ }
382
584
  vue.onBeforeUnmount(() => {
383
585
  abort?.();
384
586
  });
385
587
  return {
386
- search,
588
+ items,
387
589
  options,
388
- loading,
590
+ search: vue.computed(() => reactiveData.search),
389
591
  hasNextPage,
390
- items,
391
- loadItems,
392
- handleSearch
592
+ isFetching,
593
+ isLoading,
594
+ loadPage,
595
+ updateSearch
393
596
  };
394
597
  }
395
598
 
@@ -487,32 +690,23 @@ function useDetectBrowser(versions, userAgent) {
487
690
  });
488
691
  }
489
692
 
490
- function isEnabled(options) {
491
- if (options?.debug !== void 0)
492
- return options.debug;
493
- const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
494
- if (isBrowser) {
495
- const debug = localStorage.getItem("debug");
496
- if (debug === "true")
497
- return true;
498
- if (debug === "false")
499
- return false;
500
- }
501
- const isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
502
- if (isNode) {
503
- const debug = process.env.NODE_DEBUG;
504
- if (debug === "true")
505
- return true;
506
- if (debug === "false")
507
- return false;
508
- }
509
- return false;
510
- }
511
- function useLogger(scope, options) {
512
- const prefix = options?.tag ? `[${scope.toUpperCase()}.${options.tag}]:` : `[${scope.toUpperCase()}]:`;
513
- const logger = logdown__default(prefix, { prefixColor: options?.color });
514
- logger.state.isEnabled = isEnabled(options);
515
- return logger;
693
+ const isLocked = vue.ref(false);
694
+ function useGlobalScroll() {
695
+ const lock = () => {
696
+ isLocked.value = true;
697
+ document.body.style.paddingRight = `${window.innerWidth - document.documentElement.clientWidth}px`;
698
+ document.body.style.overflow = "hidden";
699
+ };
700
+ const unlock = () => {
701
+ isLocked.value = false;
702
+ document.body.style.overflow = "auto";
703
+ document.body.style.paddingRight = "0px";
704
+ };
705
+ return {
706
+ isLocked,
707
+ lock,
708
+ unlock
709
+ };
516
710
  }
517
711
 
518
712
  function validatePhone(rule, value) {
@@ -597,6 +791,7 @@ exports.useAsyncSelect = useAsyncSelect;
597
791
  exports.useClassName = useClassName;
598
792
  exports.useDayjs = useDayjs;
599
793
  exports.useDetectBrowser = useDetectBrowser;
794
+ exports.useGlobalScroll = useGlobalScroll;
600
795
  exports.useLogger = useLogger;
601
796
  exports.validateNumber = validateNumber;
602
797
  exports.validatePhone = validatePhone;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as vue from 'vue';
2
- import { ComputedRef, WritableComputedRef } from 'vue';
2
+ import { MaybeRef } from '@vueuse/core';
3
3
  import dayjs from 'dayjs';
4
4
  import { Browser } from 'detect-browser';
5
5
  import logdown from 'logdown';
@@ -106,34 +106,59 @@ declare function useAbortController<T extends (...args: any[]) => any>(callback:
106
106
  isAborted(error: ResponseError): boolean;
107
107
  };
108
108
 
109
- declare function useAsyncMultiselect<T extends (...args: any[]) => any, K extends (params: Awaited<ReturnType<T>>['results'][0]) => any>({ apiMethod, mapResultCallback, selectedValues, params, }: {
109
+ interface ReactiveData$1 {
110
+ search: string;
111
+ page: number;
112
+ selectedValues?: any[];
113
+ params?: any;
114
+ }
115
+ declare function useAsyncMultiselect<T extends (...args: any[]) => any, K extends (params: any) => any>({ apiMethod, mapOptionCallback, selectedValues, params, queryKey, dataItemsKey, dataItemIdKey, dataCountKey, delay, onUpdated, }: {
110
116
  apiMethod: T;
111
- mapResultCallback: K;
112
- selectedValues: ComputedRef<Parameters<T>[0]['includedIds']> | WritableComputedRef<Parameters<T>[0]['includedIds']>;
113
- params?: Parameters<T>[0];
117
+ mapOptionCallback?: K;
118
+ selectedValues?: MaybeRef<Parameters<T>[0]['includedIds']>;
119
+ params?: MaybeRef<Partial<Parameters<T>[0]>>;
120
+ queryKey: string;
121
+ dataItemsKey?: string;
122
+ dataItemIdKey?: string;
123
+ dataCountKey?: string;
124
+ delay?: number;
125
+ onUpdated?: (data: ReactiveData$1) => void;
114
126
  }): {
115
- search: vue.Ref<string>;
116
- options: ComputedRef<ReturnType<K>[1][]>;
117
- loading: vue.Ref<boolean>;
118
- hasNextPage: ComputedRef<boolean>;
119
- items: vue.Ref<Map<ReturnType<K>[0], ReturnType<K>[1]>>;
120
- loadItems: (isSearch?: boolean) => Promise<void>;
121
- handleSearch: (value: string) => Promise<void>;
127
+ items: vue.ComputedRef<any[]>;
128
+ options: vue.ComputedRef<ReturnType<K>[]>;
129
+ search: vue.ComputedRef<string>;
130
+ hasNextPage: vue.ComputedRef<boolean>;
131
+ isFetching: vue.Ref<boolean>;
132
+ isLoading: vue.Ref<false> | vue.Ref<true>;
133
+ loadPage: (newPage?: number) => void;
134
+ updateSearch: (value: string) => void;
122
135
  };
123
136
 
124
- declare function useAsyncSelect<T extends (...args: any[]) => any, K extends (params: Awaited<ReturnType<T>>['results'][0]) => any>({ apiMethod, mapResultCallback, includedIds, params, }: {
137
+ interface ReactiveData {
138
+ search: string;
139
+ page: number;
140
+ selectedValue?: any[];
141
+ params?: any;
142
+ }
143
+ declare function useAsyncSelect<T extends (...args: any[]) => any, K extends (params: any) => any>({ apiMethod, mapOptionCallback, selectedValue, params, queryKey, dataItemsKey, dataCountKey, delay, onUpdated, }: {
125
144
  apiMethod: T;
126
- mapResultCallback: K;
127
- includedIds?: Parameters<T>[0]['includedIds'];
128
- params?: Parameters<T>[0];
145
+ mapOptionCallback?: K;
146
+ selectedValue?: MaybeRef<Parameters<T>[0]['includedIds']>;
147
+ params?: MaybeRef<Partial<Parameters<T>[0]>>;
148
+ queryKey: string;
149
+ dataItemsKey?: string;
150
+ dataCountKey?: string;
151
+ delay?: number;
152
+ onUpdated?: (data: ReactiveData) => void;
129
153
  }): {
130
- search: vue.Ref<string>;
131
- options: vue.ComputedRef<ReturnType<K>[1][]>;
132
- loading: vue.Ref<boolean>;
154
+ items: vue.ComputedRef<any[]>;
155
+ options: vue.ComputedRef<ReturnType<K>[]>;
156
+ search: vue.ComputedRef<string>;
133
157
  hasNextPage: vue.ComputedRef<boolean>;
134
- items: vue.Ref<Map<ReturnType<K>[0], ReturnType<K>[1]>>;
135
- loadItems: (isSearch?: boolean) => Promise<void>;
136
- handleSearch: (value: string) => Promise<void>;
158
+ isFetching: vue.Ref<boolean>;
159
+ isLoading: vue.Ref<false> | vue.Ref<true>;
160
+ loadPage: (newPage?: number) => void;
161
+ updateSearch: (value: string) => void;
137
162
  };
138
163
 
139
164
  declare function useClassName(block: string): {
@@ -169,6 +194,12 @@ type VersionsList = {
169
194
  };
170
195
  declare function useDetectBrowser(versions: VersionsList, userAgent?: any): BrowserInfo;
171
196
 
197
+ declare function useGlobalScroll(): {
198
+ isLocked: vue.Ref<boolean>;
199
+ lock: () => void;
200
+ unlock: () => void;
201
+ };
202
+
172
203
  /**
173
204
  * @see https://github.com/caiogondim/logdown.js#readme
174
205
  */
@@ -196,4 +227,4 @@ declare function isTypeUrl(message?: string): RuleItem;
196
227
  declare function isTypeNumber(value?: number, message?: string): RuleItem;
197
228
  declare function isStrictLength(value?: number, message?: string): RuleItem;
198
229
 
199
- export { BrowserInfo, Dictionary, ResponseError, UiComponentsResolver, VersionsList, camelizeKeys, createClassName, formatMoney, genLoadingTableRows, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, isMax, isMin, isRequired, isStrictLength, isTypeEmail, isTypeNumber, isTypeUrl, parsePhone, snakelizeKeys, unformatNumber, useAbortController, useAsyncMultiselect, useAsyncSelect, useClassName, useDayjs, useDetectBrowser, useLogger, validateNumber, validatePhone };
230
+ export { BrowserInfo, Dictionary, ResponseError, UiComponentsResolver, VersionsList, camelizeKeys, createClassName, formatMoney, genLoadingTableRows, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, isMax, isMin, isRequired, isStrictLength, isTypeEmail, isTypeNumber, isTypeUrl, parsePhone, snakelizeKeys, unformatNumber, useAbortController, useAsyncMultiselect, useAsyncSelect, useClassName, useDayjs, useDetectBrowser, useGlobalScroll, useLogger, validateNumber, validatePhone };
package/dist/index.mjs CHANGED
@@ -2,8 +2,12 @@ import camelCase from 'lodash/camelCase.js';
2
2
  import { CURRENCY_DEFAULT } from '@karta.io/common-data';
3
3
  import { parsePhoneNumberFromString } from 'libphonenumber-js';
4
4
  import snakeCase from 'lodash/snakeCase.js';
5
- import { ref, computed, onBeforeUnmount } from 'vue';
6
- import { useDebounceFn } from '@vueuse/core';
5
+ import { reactive, ref, watch, computed, isRef, nextTick, onBeforeUnmount } from 'vue';
6
+ import { useQuery } from '@tanstack/vue-query';
7
+ import { toValue, useDebounceFn } from '@vueuse/core';
8
+ import get from 'lodash/get.js';
9
+ import has from 'lodash/has.js';
10
+ import logdown from 'logdown';
7
11
  import dayjs from 'dayjs';
8
12
  import utc from 'dayjs/plugin/utc.js';
9
13
  import tz from 'dayjs/plugin/timezone.js';
@@ -11,7 +15,6 @@ import updateLocale from 'dayjs/plugin/updateLocale.js';
11
15
  import isToday from 'dayjs/plugin/isToday.js';
12
16
  import customParseFormat from 'dayjs/plugin/customParseFormat.js';
13
17
  import { detect } from 'detect-browser';
14
- import logdown from 'logdown';
15
18
 
16
19
  function camelizeKeys(object) {
17
20
  if (Array.isArray(object))
@@ -254,128 +257,326 @@ function useAbortController(callback) {
254
257
  };
255
258
  }
256
259
 
260
+ function isEnabled(options) {
261
+ if (options?.debug !== void 0)
262
+ return options.debug;
263
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
264
+ if (isBrowser) {
265
+ const debug = localStorage.getItem("debug");
266
+ if (debug === "true")
267
+ return true;
268
+ if (debug === "false")
269
+ return false;
270
+ }
271
+ const isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
272
+ if (isNode) {
273
+ const debug = process.env.NODE_DEBUG;
274
+ if (debug === "true")
275
+ return true;
276
+ if (debug === "false")
277
+ return false;
278
+ }
279
+ return false;
280
+ }
281
+ function useLogger(scope, options) {
282
+ const prefix = options?.tag ? `[${scope.toUpperCase()}.${options.tag}]:` : `[${scope.toUpperCase()}]:`;
283
+ const logger = logdown(prefix, { prefixColor: options?.color });
284
+ logger.state.isEnabled = isEnabled(options);
285
+ return logger;
286
+ }
287
+
257
288
  function useAsyncMultiselect({
258
289
  apiMethod,
259
- mapResultCallback,
260
- selectedValues,
261
- params = void 0
290
+ mapOptionCallback = void 0,
291
+ selectedValues = void 0,
292
+ params = void 0,
293
+ queryKey,
294
+ dataItemsKey = "results",
295
+ dataItemIdKey = "id",
296
+ dataCountKey = "count",
297
+ delay = 300,
298
+ onUpdated = void 0
262
299
  }) {
263
- const items = ref(/* @__PURE__ */ new Map());
264
- const loading = ref(false);
265
- const search = ref("");
300
+ const logger = useLogger("UTILS", {
301
+ tag: "useAsyncMultiselect",
302
+ color: "#b54708",
303
+ debug: true
304
+ });
305
+ const paramsForLogger = { queryKey, dataItemsKey, dataItemIdKey, dataCountKey };
306
+ const reactiveData = reactive({
307
+ search: "",
308
+ page: 1,
309
+ selectedValues: toValue(selectedValues),
310
+ params: JSON.stringify(toValue(params))
311
+ });
312
+ 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
+ });
319
+ const { data, isFetching, isLoading } = useQuery({
320
+ queryKey: [queryKey, reactiveData],
321
+ queryFn: loadWAC
322
+ });
323
+ const itemsByPages = ref(null);
266
324
  const count = ref(0);
267
- const page = ref(1);
268
- const options = computed(() => [...items.value.values()]);
269
- const hasNextPage = computed(() => count.value > items.value.size);
270
- const { call: apiMethodWAC, abort, isAborted } = useAbortController(apiMethod);
271
- const handleSearch = async (value) => {
272
- if (search.value === value)
273
- return;
274
- search.value = value;
275
- await loadItemsWithDebounce();
276
- };
277
- const loadItems = async (isSearch) => {
278
- loading.value = true;
279
- try {
280
- const { results, count: itemsCount } = await apiMethodWAC({
281
- page: page.value,
282
- search: search.value,
283
- ...selectedValues.value?.length && !search.value && { includedIds: selectedValues.value },
284
- ...params
285
- });
286
- count.value = itemsCount;
287
- if (isSearch) {
288
- const cashedMapItems = selectedValues.value.map((selectedValue) => [
289
- selectedValue,
290
- items.value.get(selectedValue)
291
- ]);
292
- items.value = new Map([...cashedMapItems]);
325
+ const selectedItemsCached = ref([]);
326
+ watch(
327
+ data,
328
+ (newValue) => {
329
+ if (!newValue)
330
+ return;
331
+ if (!has(newValue, dataItemsKey)) {
332
+ logger.warn(
333
+ `Unable to find key *"${dataItemsKey}"* (property "dataItemsKey") in data object from API.`,
334
+ paramsForLogger
335
+ );
336
+ return;
337
+ }
338
+ if (!has(newValue, dataCountKey)) {
339
+ logger.warn(
340
+ `Unable to find key *"${dataCountKey}"* (property "dataCountKey") in data object from API.`,
341
+ paramsForLogger
342
+ );
343
+ return;
293
344
  }
294
- const resultsForMap = results.map(mapResultCallback);
295
- items.value = new Map([...items.value, ...resultsForMap]);
296
- page.value += 1;
297
- loading.value = false;
298
- } catch (error) {
299
- if (isAborted(error))
345
+ if (!get(newValue, dataItemsKey) || get(newValue, dataCountKey) === void 0)
300
346
  return;
301
- loading.value = false;
347
+ count.value = get(newValue, dataCountKey, 0);
348
+ const newItems = get(newValue, dataItemsKey);
349
+ itemsByPages.value = {
350
+ ...reactiveData.page !== 1 && itemsByPages.value,
351
+ [reactiveData.page]: newItems
352
+ };
353
+ if (reactiveData.page === 1 && reactiveData.selectedValues?.length && !reactiveData.search) {
354
+ if (newItems.some((item) => !has(item, dataItemIdKey))) {
355
+ logger.warn(
356
+ `Unable to find key *"${dataItemIdKey}"* (property "dataItemIdKey") in items from API.`,
357
+ 'This key must be match with "optionValue" in UiMultiselect.',
358
+ paramsForLogger
359
+ );
360
+ }
361
+ selectedItemsCached.value = newItems.filter(
362
+ (item) => reactiveData.selectedValues.includes(get(item, dataItemIdKey))
363
+ );
364
+ }
365
+ onUpdated?.({
366
+ search: reactiveData.search,
367
+ page: reactiveData.page,
368
+ selectedValues: reactiveData.selectedValues,
369
+ params: reactiveData.params ? JSON.parse(reactiveData.params) : void 0
370
+ });
371
+ },
372
+ { immediate: true }
373
+ );
374
+ const items = computed(() => {
375
+ if (!itemsByPages.value)
376
+ return selectedItemsCached.value;
377
+ if (!Object.keys(itemsByPages.value).length)
378
+ return selectedItemsCached.value;
379
+ const itemsByPagesAsArray = Object.values(itemsByPages.value).reduce(
380
+ (acc, item) => [...acc, ...item],
381
+ []
382
+ );
383
+ const itemsAsArray = [...selectedItemsCached.value, ...itemsByPagesAsArray];
384
+ const itemsAsMap = itemsAsArray.reduce((acc, item) => {
385
+ const key = get(item, dataItemIdKey, JSON.stringify(item));
386
+ return acc.set(key, item);
387
+ }, /* @__PURE__ */ new Map());
388
+ return [...itemsAsMap.values()];
389
+ });
390
+ const options = computed(() => {
391
+ if (!items.value.length)
392
+ return [];
393
+ if (!mapOptionCallback)
394
+ return this.items.value;
395
+ return items.value.map(mapOptionCallback);
396
+ });
397
+ const hasNextPage = computed(() => count.value > items.value.length);
398
+ const loadPage = (newPage = 1) => {
399
+ reactiveData.page = newPage;
400
+ if (newPage === 1) {
401
+ reactiveData.selectedValues = toValue(selectedValues);
302
402
  }
303
403
  };
304
- const loadItemsWithDebounce = useDebounceFn(async () => {
305
- page.value = 1;
306
- await loadItems(true);
307
- }, 300);
404
+ const updateSearchWithDebounce = useDebounceFn((value) => {
405
+ reactiveData.search = value;
406
+ reactiveData.page = 1;
407
+ reactiveData.selectedValues = toValue(selectedValues);
408
+ }, delay);
409
+ const updateSearch = (value) => {
410
+ updateSearchWithDebounce(value);
411
+ };
412
+ if (isRef(selectedValues)) {
413
+ watch(selectedValues, async (newSelectedValues) => {
414
+ if (!newSelectedValues.length) {
415
+ selectedItemsCached.value = [];
416
+ } else {
417
+ if (items.value.some((item) => !has(item, dataItemIdKey))) {
418
+ logger.warn(
419
+ `Unable to find key *"${dataItemIdKey}"* (property "dataItemIdKey") in items from API.`,
420
+ 'This key must be match with "optionValue" in UiMultiselect.',
421
+ paramsForLogger
422
+ );
423
+ }
424
+ selectedItemsCached.value = items.value.filter(
425
+ (item) => newSelectedValues.includes(get(item, dataItemIdKey))
426
+ );
427
+ }
428
+ await nextTick();
429
+ if (reactiveData.page === 1) {
430
+ reactiveData.selectedValues = newSelectedValues;
431
+ }
432
+ });
433
+ }
434
+ if (isRef(params)) {
435
+ watch(params, (newParams) => {
436
+ reactiveData.page = 1;
437
+ reactiveData.params = JSON.stringify(newParams);
438
+ reactiveData.selectedValues = toValue(selectedValues);
439
+ });
440
+ }
308
441
  onBeforeUnmount(() => {
309
442
  abort?.();
310
443
  });
311
444
  return {
312
- search,
445
+ items,
313
446
  options,
314
- loading,
447
+ search: computed(() => reactiveData.search),
315
448
  hasNextPage,
316
- items,
317
- loadItems,
318
- handleSearch
449
+ isFetching,
450
+ isLoading,
451
+ loadPage,
452
+ updateSearch
319
453
  };
320
454
  }
321
455
 
322
456
  function useAsyncSelect({
323
457
  apiMethod,
324
- mapResultCallback,
325
- includedIds = void 0,
326
- params = void 0
458
+ mapOptionCallback = void 0,
459
+ selectedValue = void 0,
460
+ params = void 0,
461
+ queryKey,
462
+ dataItemsKey = "results",
463
+ dataCountKey = "count",
464
+ delay = 300,
465
+ onUpdated = void 0
327
466
  }) {
328
- const items = ref(/* @__PURE__ */ new Map());
329
- const loading = ref(false);
330
- const search = ref("");
467
+ const logger = useLogger("UTILS", {
468
+ tag: "useAsyncSelect",
469
+ color: "#b54708",
470
+ debug: true
471
+ });
472
+ const paramsForLogger = { queryKey, dataItemsKey, dataCountKey };
473
+ const reactiveData = reactive({
474
+ search: "",
475
+ page: 1,
476
+ selectedValue: toValue(selectedValue),
477
+ params: JSON.stringify(toValue(params))
478
+ });
479
+ const { call, abort } = useAbortController(apiMethod);
480
+ const loadWAC = () => call({
481
+ page: reactiveData.page,
482
+ search: reactiveData.search,
483
+ ...reactiveData.selectedValue && { includedIds: [reactiveData.selectedValue] },
484
+ ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
485
+ });
486
+ const { data, isFetching, isLoading } = useQuery({
487
+ queryKey: [queryKey, reactiveData],
488
+ queryFn: loadWAC
489
+ });
490
+ const itemsByPages = ref(null);
331
491
  const count = ref(0);
332
- const page = ref(1);
333
- const options = computed(() => [...items.value.values()]);
334
- const hasNextPage = computed(() => count.value > items.value.size);
335
- const { call: apiMethodWAC, abort, isAborted } = useAbortController(apiMethod);
336
- const handleSearch = async (value) => {
337
- if (search.value === value)
338
- return;
339
- search.value = value;
340
- await loadItemsWithDebounce();
341
- };
342
- const loadItems = async (isSearch) => {
343
- loading.value = true;
344
- try {
345
- const { results, count: itemsCount } = await apiMethodWAC({
346
- page: page.value,
347
- search: search.value,
348
- ...includedIds?.length && includedIds,
349
- ...params
350
- });
351
- count.value = itemsCount;
352
- if (isSearch)
353
- items.value = /* @__PURE__ */ new Map();
354
- const resultsForMap = results.map(mapResultCallback);
355
- items.value = new Map([...items.value, ...resultsForMap]);
356
- page.value += 1;
357
- loading.value = false;
358
- } catch (error) {
359
- if (isAborted(error))
492
+ watch(
493
+ data,
494
+ (newValue) => {
495
+ if (!newValue)
360
496
  return;
361
- loading.value = false;
362
- }
497
+ if (!has(newValue, dataItemsKey)) {
498
+ logger.warn(
499
+ `Unable to find key *"${dataItemsKey}"* (property "dataItemsKey") in data object from API.`,
500
+ paramsForLogger
501
+ );
502
+ return;
503
+ }
504
+ if (!has(newValue, dataCountKey)) {
505
+ logger.warn(
506
+ `Unable to find key *"${dataCountKey}"* (property "dataCountKey") in data object from API.`,
507
+ paramsForLogger
508
+ );
509
+ return;
510
+ }
511
+ if (!get(newValue, dataItemsKey) || get(newValue, dataCountKey) === void 0)
512
+ return;
513
+ count.value = get(newValue, dataCountKey, 0);
514
+ const newItems = get(newValue, dataItemsKey);
515
+ itemsByPages.value = {
516
+ ...reactiveData.page !== 1 && itemsByPages.value,
517
+ [reactiveData.page]: newItems
518
+ };
519
+ onUpdated?.({
520
+ search: reactiveData.search,
521
+ page: reactiveData.page,
522
+ selectedValue: reactiveData.selectedValue,
523
+ params: reactiveData.params ? JSON.parse(reactiveData.params) : void 0
524
+ });
525
+ },
526
+ { immediate: true }
527
+ );
528
+ const items = computed(() => {
529
+ if (!itemsByPages.value)
530
+ return [];
531
+ if (!Object.keys(itemsByPages.value).length)
532
+ return [];
533
+ return Object.values(itemsByPages.value).reduce(
534
+ (acc, item) => [...acc, ...item],
535
+ []
536
+ );
537
+ });
538
+ const options = computed(() => {
539
+ if (!items.value.length)
540
+ return [];
541
+ if (!mapOptionCallback)
542
+ return this.items.value;
543
+ return items.value.map(mapOptionCallback);
544
+ });
545
+ const hasNextPage = computed(() => count.value > items.value.length);
546
+ const loadPage = (newPage = 1) => {
547
+ reactiveData.page = newPage;
363
548
  };
364
- const loadItemsWithDebounce = useDebounceFn(async () => {
365
- page.value = 1;
366
- await loadItems(true);
367
- }, 300);
549
+ const updateSearchWithDebounce = useDebounceFn((value) => {
550
+ reactiveData.search = value;
551
+ reactiveData.page = 1;
552
+ }, delay);
553
+ const updateSearch = (value) => {
554
+ updateSearchWithDebounce(value);
555
+ };
556
+ if (isRef(selectedValue)) {
557
+ watch(selectedValue, (newSelectedValue) => {
558
+ reactiveData.page = 1;
559
+ reactiveData.selectedValue = newSelectedValue;
560
+ });
561
+ }
562
+ if (isRef(params)) {
563
+ watch(params, (newParams) => {
564
+ reactiveData.page = 1;
565
+ reactiveData.params = JSON.stringify(newParams);
566
+ });
567
+ }
368
568
  onBeforeUnmount(() => {
369
569
  abort?.();
370
570
  });
371
571
  return {
372
- search,
572
+ items,
373
573
  options,
374
- loading,
574
+ search: computed(() => reactiveData.search),
375
575
  hasNextPage,
376
- items,
377
- loadItems,
378
- handleSearch
576
+ isFetching,
577
+ isLoading,
578
+ loadPage,
579
+ updateSearch
379
580
  };
380
581
  }
381
582
 
@@ -473,32 +674,23 @@ function useDetectBrowser(versions, userAgent) {
473
674
  });
474
675
  }
475
676
 
476
- function isEnabled(options) {
477
- if (options?.debug !== void 0)
478
- return options.debug;
479
- const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
480
- if (isBrowser) {
481
- const debug = localStorage.getItem("debug");
482
- if (debug === "true")
483
- return true;
484
- if (debug === "false")
485
- return false;
486
- }
487
- const isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
488
- if (isNode) {
489
- const debug = process.env.NODE_DEBUG;
490
- if (debug === "true")
491
- return true;
492
- if (debug === "false")
493
- return false;
494
- }
495
- return false;
496
- }
497
- function useLogger(scope, options) {
498
- const prefix = options?.tag ? `[${scope.toUpperCase()}.${options.tag}]:` : `[${scope.toUpperCase()}]:`;
499
- const logger = logdown(prefix, { prefixColor: options?.color });
500
- logger.state.isEnabled = isEnabled(options);
501
- return logger;
677
+ const isLocked = ref(false);
678
+ function useGlobalScroll() {
679
+ const lock = () => {
680
+ isLocked.value = true;
681
+ document.body.style.paddingRight = `${window.innerWidth - document.documentElement.clientWidth}px`;
682
+ document.body.style.overflow = "hidden";
683
+ };
684
+ const unlock = () => {
685
+ isLocked.value = false;
686
+ document.body.style.overflow = "auto";
687
+ document.body.style.paddingRight = "0px";
688
+ };
689
+ return {
690
+ isLocked,
691
+ lock,
692
+ unlock
693
+ };
502
694
  }
503
695
 
504
696
  function validatePhone(rule, value) {
@@ -552,4 +744,4 @@ function isStrictLength(value = 3, message) {
552
744
  };
553
745
  }
554
746
 
555
- export { UiComponentsResolver, camelizeKeys, createClassName, formatMoney, genLoadingTableRows, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, isMax, isMin, isRequired, isStrictLength, isTypeEmail, isTypeNumber, isTypeUrl, parsePhone, snakelizeKeys, unformatNumber, useAbortController, useAsyncMultiselect, useAsyncSelect, useClassName, useDayjs, useDetectBrowser, useLogger, validateNumber, validatePhone };
747
+ export { UiComponentsResolver, camelizeKeys, createClassName, formatMoney, genLoadingTableRows, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, isMax, isMin, isRequired, isStrictLength, isTypeEmail, isTypeNumber, isTypeUrl, parsePhone, snakelizeKeys, unformatNumber, useAbortController, useAsyncMultiselect, useAsyncSelect, useClassName, useDayjs, useDetectBrowser, useGlobalScroll, useLogger, validateNumber, validatePhone };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@karta.io/utils",
3
- "version": "0.34.1",
3
+ "version": "0.35.1",
4
4
  "description": "karta.io utils for admin and application",
5
5
  "author": "Vitaly Blokhin <karambafe@gmail.com>",
6
6
  "homepage": "",
@@ -21,11 +21,17 @@
21
21
  "dist"
22
22
  ],
23
23
  "peerDependencies": {
24
+ "@tanstack/vue-query": "4.29.20",
24
25
  "vue": "3.3.x"
25
26
  },
27
+ "peerDependenciesMeta": {
28
+ "@tanstack/vue-query": {
29
+ "optional": true
30
+ }
31
+ },
26
32
  "dependencies": {
27
- "@karta.io/common-data": "^0.34.1",
28
- "@vueuse/core": "9.13.0",
33
+ "@karta.io/common-data": "^0.35.1",
34
+ "@vueuse/core": "10.2.1",
29
35
  "async-validator": "4.2.5",
30
36
  "dayjs": "1.11.8",
31
37
  "detect-browser": "5.3.0",