@karta.io/utils 0.23.6 → 0.25.0

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/README.md CHANGED
@@ -4,24 +4,32 @@
4
4
 
5
5
  ## Хелперы:
6
6
 
7
- - formatMoney
8
- - createClassName
9
7
  - camelizeKeys
8
+ - createClassName
9
+ - formatMoney
10
10
  - genLoadingTableRows
11
11
  - genRandomNumber
12
+ - genUUID
12
13
  - getCardNumber
13
14
  - getCountryFromPhone
14
- - getPaginationParams
15
15
  - isElementIgnored
16
16
  - isEmptyObject
17
17
  - pagination
18
18
  - parsePhone
19
+ - snakelizeKeys
19
20
  - unformatNumber
20
21
  - validateNumber
22
+ - viewExample
21
23
 
22
24
  ## Хуки:
23
25
 
26
+ - [useAbortController](src/hooks/USE_ABORT_CONTROLLER.md)
27
+ - [useAsyncMultiselect](src/hooks/USE_ASYNC_MULTISELECT.md)
28
+ - [useAsyncSelect](src/hooks/USE_ASYNC_SELECT.md)
24
29
  - useClassName
30
+ - useDayjs
31
+ - [useDetectBrowser](src/hooks/USE_DETECT_BROWSER.md)
32
+ - [useLogger](src/hooks/USE_LOGGER.md)
25
33
 
26
34
  ## Кастомные правила для валидатора
27
35
 
package/dist/index.cjs CHANGED
@@ -1,16 +1,38 @@
1
1
  'use strict';
2
2
 
3
- const libphonenumberJs = require('libphonenumber-js');
4
3
  const lodashEs = require('lodash-es');
4
+ const libphonenumberJs = require('libphonenumber-js');
5
+ const vue = require('vue');
6
+ const core = require('@vueuse/core');
5
7
  const dayjs = require('dayjs');
6
8
  const utc = require('dayjs/plugin/utc.js');
7
9
  const tz = require('dayjs/plugin/timezone.js');
8
10
  const updateLocale = require('dayjs/plugin/updateLocale.js');
9
11
  const isToday = require('dayjs/plugin/isToday.js');
10
12
  const detectBrowser = require('detect-browser');
13
+ const logdown = require('logdown');
11
14
 
12
- function viewExample(value) {
13
- return value;
15
+ function camelizeKeys(object) {
16
+ if (Array.isArray(object)) {
17
+ return object.map((v) => camelizeKeys(v));
18
+ }
19
+ if (object !== null && object.constructor === Object) {
20
+ return Object.keys(object).reduce(
21
+ (result, key) => ({
22
+ ...result,
23
+ [lodashEs.camelCase(key)]: camelizeKeys(object[key])
24
+ }),
25
+ {}
26
+ );
27
+ }
28
+ return object;
29
+ }
30
+
31
+ function createClassName(className) {
32
+ return function f(...classNames) {
33
+ const result = classNames.join("");
34
+ return (...args) => args.length ? f.apply(null, [result, ...args])() : result;
35
+ }(className);
14
36
  }
15
37
 
16
38
  function formatMoney(value, currency, options = { locale: "en-US", minimumFractionDigits: 2, maximumFractionDigits: 2 }) {
@@ -29,17 +51,33 @@ function formatMoney(value, currency, options = { locale: "en-US", minimumFracti
29
51
  return formatter.format(convertedValue);
30
52
  }
31
53
 
32
- function createClassName(className) {
33
- return function f(...classNames) {
34
- const result = classNames.join("");
35
- return (...args) => args.length ? f.apply(null, [result, ...args])() : result;
36
- }(className);
54
+ function genLoadingTableRows(columns, limit) {
55
+ const row = columns.reduce(
56
+ (acc, curr) => ({ ...acc, [curr.key]: void 0 }),
57
+ {}
58
+ );
59
+ return Array.from(Array(limit).keys()).map((item) => ({ id: item, ...row }));
37
60
  }
38
61
 
39
62
  function genRandomNumber(min, max) {
40
63
  return Math.floor(Math.random() * (max - min + 1)) + min;
41
64
  }
42
65
 
66
+ function genUUID() {
67
+ let d = new Date().getTime(), d2 = performance && performance.now && performance.now() * 1e3 || 0;
68
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
69
+ let r = Math.random() * 16;
70
+ if (d > 0) {
71
+ r = (d + r) % 16 | 0;
72
+ d = Math.floor(d / 16);
73
+ } else {
74
+ r = (d2 + r) % 16 | 0;
75
+ d2 = Math.floor(d2 / 16);
76
+ }
77
+ return (c == "x" ? r : r & 7 | 8).toString(16);
78
+ });
79
+ }
80
+
43
81
  function getCardNumber(number, options) {
44
82
  const { hasOnlyLast4 = false, isHidden = false, dot = "\u2022" } = options || {};
45
83
  let result;
@@ -62,49 +100,86 @@ function getCountryFromPhone(phone) {
62
100
  return phoneNumber?.country ?? "";
63
101
  }
64
102
 
65
- function genLoadingTableRows(columns, limit) {
66
- const row = columns.reduce(
67
- (acc, curr) => ({ ...acc, [curr.key]: void 0 }),
68
- {}
69
- );
70
- return Array.from(Array(limit).keys()).map((item) => ({ id: item, ...row }));
103
+ function isElementIgnored({
104
+ ignoredClasses,
105
+ event
106
+ } = {}) {
107
+ if (ignoredClasses && event) {
108
+ return Array.from(event.composedPath()).filter((item) => item.nodeType && item.nodeType !== 9).reduce((acc, item) => {
109
+ const elementClasses = item.getAttribute("class");
110
+ const array = elementClasses ? elementClasses.split(" ") : [];
111
+ return acc.concat(array);
112
+ }, []).some((item) => ignoredClasses.includes(item));
113
+ }
114
+ return false;
71
115
  }
72
116
 
73
- function genUUID() {
74
- let d = new Date().getTime(), d2 = performance && performance.now && performance.now() * 1e3 || 0;
75
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
76
- let r = Math.random() * 16;
77
- if (d > 0) {
78
- r = (d + r) % 16 | 0;
79
- d = Math.floor(d / 16);
80
- } else {
81
- r = (d2 + r) % 16 | 0;
82
- d2 = Math.floor(d2 / 16);
83
- }
84
- return (c == "x" ? r : r & 7 | 8).toString(16);
85
- });
117
+ function isEmptyObject(object) {
118
+ return !object || !Object.keys(object).length;
86
119
  }
87
120
 
88
- function camelizeKeys(object) {
89
- if (Array.isArray(object)) {
90
- return object.map((v) => camelizeKeys(v));
121
+ function validateNumber(value, defaultValue) {
122
+ if (value === "")
123
+ return defaultValue;
124
+ return Number.isNaN(Number(value)) ? defaultValue : Number(value);
125
+ }
126
+
127
+ const PAGE_DEFAULT = 1;
128
+ const LIMIT_DEFAULT = 25;
129
+ function getPaginationParams({
130
+ page,
131
+ limit
132
+ }) {
133
+ const validatedPage = validateNumber(page, PAGE_DEFAULT);
134
+ const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
135
+ return {
136
+ limit: validatedLimit,
137
+ offset: validatedPage * validatedLimit - validatedLimit
138
+ };
139
+ }
140
+ function getPaginationLimit({
141
+ limit
142
+ }) {
143
+ return validateNumber(limit, LIMIT_DEFAULT);
144
+ }
145
+ function getPaginationOffset({
146
+ page,
147
+ limit
148
+ }) {
149
+ const validatedPage = validateNumber(page, PAGE_DEFAULT);
150
+ const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
151
+ return validatedPage * validatedLimit - validatedLimit;
152
+ }
153
+ function getPaginationPages({
154
+ count,
155
+ limit
156
+ }) {
157
+ return Math.ceil(count / validateNumber(limit, LIMIT_DEFAULT));
158
+ }
159
+
160
+ function parsePhone(phone) {
161
+ const replacedPhone = phone.replace(/[a-zA-Z]/g, "");
162
+ if (replacedPhone.length === 1 && replacedPhone !== "+") {
163
+ return `+${replacedPhone}`;
91
164
  }
92
- if (object !== null && object.constructor === Object) {
93
- return Object.keys(object).reduce(
94
- (result, key) => ({
95
- ...result,
96
- [lodashEs.camelCase(key)]: camelizeKeys(object[key])
165
+ const phoneNumber = libphonenumberJs.parsePhoneNumberFromString(replacedPhone);
166
+ return phoneNumber ? phoneNumber.formatInternational() : replacedPhone;
167
+ }
168
+
169
+ function snakelizeKeys(prop) {
170
+ if (Array.isArray(prop)) {
171
+ return prop.map((item) => snakelizeKeys(item));
172
+ }
173
+ if (prop !== null && prop !== void 0 && prop.constructor === Object) {
174
+ return Object.keys(prop).reduce(
175
+ (accum, current) => ({
176
+ ...accum,
177
+ [lodashEs.snakeCase(current)]: snakelizeKeys(prop[current])
97
178
  }),
98
179
  {}
99
180
  );
100
181
  }
101
- return object;
102
- }
103
-
104
- function validateNumber(value, defaultValue) {
105
- if (value === "")
106
- return defaultValue;
107
- return Number.isNaN(Number(value)) ? defaultValue : Number(value);
182
+ return prop;
108
183
  }
109
184
 
110
185
  const LOCALE_RU = "ru-RU";
@@ -147,64 +222,173 @@ function unformatNumber(value) {
147
222
  return value;
148
223
  }
149
224
 
150
- const PAGE_DEFAULT = 1;
151
- const LIMIT_DEFAULT = 25;
152
- function getPaginationParams({
153
- page,
154
- limit
155
- }) {
156
- const validatedPage = validateNumber(page, PAGE_DEFAULT);
157
- const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
225
+ function useAbortController(callback) {
226
+ let controller = null;
158
227
  return {
159
- limit: validatedLimit,
160
- offset: validatedPage * validatedLimit - validatedLimit
228
+ async call(...args) {
229
+ if (controller) {
230
+ controller.abort();
231
+ }
232
+ controller = new AbortController();
233
+ let response;
234
+ if (args.length > 0) {
235
+ response = await callback(...args, {
236
+ signal: controller.signal
237
+ });
238
+ } else {
239
+ response = await callback({
240
+ signal: controller.signal
241
+ });
242
+ }
243
+ controller = null;
244
+ return response;
245
+ },
246
+ abort() {
247
+ if (!controller)
248
+ return;
249
+ controller.abort();
250
+ controller = null;
251
+ },
252
+ isAborted(error) {
253
+ return error.status === 418;
254
+ }
161
255
  };
162
256
  }
163
- function getPaginationLimit({
164
- limit
165
- }) {
166
- return validateNumber(limit, LIMIT_DEFAULT);
167
- }
168
- function getPaginationOffset({
169
- page,
170
- limit
171
- }) {
172
- const validatedPage = validateNumber(page, PAGE_DEFAULT);
173
- const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
174
- return validatedPage * validatedLimit - validatedLimit;
175
- }
176
- function getPaginationPages({
177
- count,
178
- limit
179
- }) {
180
- return Math.ceil(count / validateNumber(limit, LIMIT_DEFAULT));
181
- }
182
-
183
- function parsePhone(phone) {
184
- const replacedPhone = phone.replace(/[a-zA-Z]/g, "");
185
- if (replacedPhone.length === 1 && replacedPhone !== "+") {
186
- return `+${replacedPhone}`;
187
- }
188
- const phoneNumber = libphonenumberJs.parsePhoneNumberFromString(replacedPhone);
189
- return phoneNumber ? phoneNumber.formatInternational() : replacedPhone;
190
- }
191
257
 
192
- function isElementIgnored({
193
- ignoredClasses,
194
- event
195
- } = {}) {
196
- if (ignoredClasses && event) {
197
- return Array.from(event.composedPath()).filter((item) => item.nodeType && item.nodeType !== 9).reduce((acc, item) => {
198
- const elementClasses = item.getAttribute("class");
199
- const array = elementClasses ? elementClasses.split(" ") : [];
200
- return acc.concat(array);
201
- }, []).some((item) => ignoredClasses.includes(item));
202
- }
203
- return false;
258
+ function useAsyncMultiselect({
259
+ apiMethod,
260
+ mapResultCallback,
261
+ selectedValues,
262
+ params = void 0
263
+ }) {
264
+ const items = vue.ref(/* @__PURE__ */ new Map());
265
+ const loading = vue.ref(false);
266
+ const search = vue.ref("");
267
+ const count = vue.ref(0);
268
+ const page = vue.ref(1);
269
+ const options = vue.computed(() => [...items.value.values()]);
270
+ const hasNextPage = vue.computed(() => count.value > items.value.size);
271
+ const {
272
+ call: apiMethodWAC,
273
+ abort,
274
+ isAborted
275
+ } = useAbortController(apiMethod);
276
+ const handleSearch = async (value) => {
277
+ if (search.value === value)
278
+ return;
279
+ search.value = value;
280
+ await loadItemsWithDebounce();
281
+ };
282
+ const loadItems = async (isSearch) => {
283
+ loading.value = true;
284
+ try {
285
+ const { results, count: itemsCount } = await apiMethodWAC({
286
+ page: page.value,
287
+ search: search.value,
288
+ ...selectedValues.value?.length && !search.value && { includedIds: selectedValues.value },
289
+ ...params
290
+ });
291
+ count.value = itemsCount;
292
+ if (isSearch) {
293
+ const cashedMapItems = selectedValues.value.map(
294
+ (selectedValue) => [
295
+ selectedValue,
296
+ items.value.get(selectedValue)
297
+ ]
298
+ );
299
+ items.value = new Map([...cashedMapItems]);
300
+ }
301
+ const resultsForMap = results.map(mapResultCallback);
302
+ items.value = new Map([...items.value, ...resultsForMap]);
303
+ page.value += 1;
304
+ loading.value = false;
305
+ } catch (error) {
306
+ if (isAborted(error))
307
+ return;
308
+ loading.value = false;
309
+ }
310
+ };
311
+ const loadItemsWithDebounce = core.useDebounceFn(async () => {
312
+ page.value = 1;
313
+ await loadItems(true);
314
+ }, 300);
315
+ vue.onBeforeUnmount(() => {
316
+ abort?.();
317
+ });
318
+ return {
319
+ search,
320
+ options,
321
+ loading,
322
+ hasNextPage,
323
+ items,
324
+ loadItems,
325
+ handleSearch
326
+ };
204
327
  }
205
328
 
206
- function isEmptyObject(object) {
207
- return !object || !Object.keys(object).length;
329
+ function useAsyncSelect({
330
+ apiMethod,
331
+ mapResultCallback,
332
+ includedIds = void 0,
333
+ params = void 0
334
+ }) {
335
+ const items = vue.ref(/* @__PURE__ */ new Map());
336
+ const loading = vue.ref(false);
337
+ const search = vue.ref("");
338
+ const count = vue.ref(0);
339
+ const page = vue.ref(1);
340
+ const options = vue.computed(() => [...items.value.values()]);
341
+ const hasNextPage = vue.computed(() => count.value > items.value.size);
342
+ const {
343
+ call: apiMethodWAC,
344
+ abort,
345
+ isAborted
346
+ } = useAbortController(apiMethod);
347
+ const handleSearch = async (value) => {
348
+ if (search.value === value)
349
+ return;
350
+ search.value = value;
351
+ await loadItemsWithDebounce();
352
+ };
353
+ const loadItems = async (isSearch) => {
354
+ loading.value = true;
355
+ try {
356
+ const { results, count: itemsCount } = await apiMethodWAC({
357
+ page: page.value,
358
+ search: search.value,
359
+ ...includedIds?.length && includedIds,
360
+ ...params
361
+ });
362
+ count.value = itemsCount;
363
+ if (isSearch) {
364
+ items.value = /* @__PURE__ */ new Map();
365
+ }
366
+ const resultsForMap = results.map(mapResultCallback);
367
+ items.value = new Map([...items.value, ...resultsForMap]);
368
+ page.value += 1;
369
+ loading.value = false;
370
+ } catch (error) {
371
+ if (isAborted(error))
372
+ return;
373
+ loading.value = false;
374
+ }
375
+ };
376
+ const loadItemsWithDebounce = core.useDebounceFn(async () => {
377
+ page.value = 1;
378
+ await loadItems(true);
379
+ }, 300);
380
+ vue.onBeforeUnmount(() => {
381
+ abort?.();
382
+ });
383
+ return {
384
+ search,
385
+ options,
386
+ loading,
387
+ hasNextPage,
388
+ items,
389
+ loadItems,
390
+ handleSearch
391
+ };
208
392
  }
209
393
 
210
394
  const _bem = (block, blockSuffix, element, modifier, modifierValue) => {
@@ -243,6 +427,7 @@ const useClassName = (block) => {
243
427
  m,
244
428
  em,
245
429
  mv,
430
+ // CSS
246
431
  cssVar,
247
432
  cssVarName
248
433
  };
@@ -302,6 +487,34 @@ function useDetectBrowser(versions, userAgent) {
302
487
  });
303
488
  }
304
489
 
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(prefix, { prefixColor: options?.color });
514
+ logger.state.isEnabled = isEnabled(options);
515
+ return logger;
516
+ }
517
+
305
518
  function validatePhone(rule, value) {
306
519
  const phoneNumber = libphonenumberJs.parsePhoneNumberFromString(value);
307
520
  return phoneNumber ? phoneNumber.isValid() : false;
@@ -322,10 +535,14 @@ exports.getPaginationParams = getPaginationParams;
322
535
  exports.isElementIgnored = isElementIgnored;
323
536
  exports.isEmptyObject = isEmptyObject;
324
537
  exports.parsePhone = parsePhone;
538
+ exports.snakelizeKeys = snakelizeKeys;
325
539
  exports.unformatNumber = unformatNumber;
540
+ exports.useAbortController = useAbortController;
541
+ exports.useAsyncMultiselect = useAsyncMultiselect;
542
+ exports.useAsyncSelect = useAsyncSelect;
326
543
  exports.useClassName = useClassName;
327
544
  exports.useDayjs = useDayjs;
328
545
  exports.useDetectBrowser = useDetectBrowser;
546
+ exports.useLogger = useLogger;
329
547
  exports.validateNumber = validateNumber;
330
548
  exports.validatePhone = validatePhone;
331
- exports.viewExample = viewExample;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,22 @@
1
+ import * as vue from 'vue';
2
+ import { ComputedRef, WritableComputedRef } from 'vue';
1
3
  import dayjs from 'dayjs';
2
4
  import { Browser } from 'detect-browser';
5
+ import logdown from 'logdown';
3
6
 
4
- declare function viewExample(value: string): string;
7
+ interface Dictionary {
8
+ [keys: string | number]: any;
9
+ }
10
+ interface ResponseError {
11
+ status: number;
12
+ statusMessage: string;
13
+ message: string;
14
+ data: Record<string, string | string[]> | null;
15
+ }
16
+
17
+ declare function camelizeKeys(object: Dictionary): Dictionary;
18
+
19
+ declare function createClassName(className: string): (...classNames: string[]) => string;
5
20
 
6
21
  declare function formatMoney(value: string | number | null | undefined, currency?: string, options?: {
7
22
  locale: string;
@@ -9,33 +24,54 @@ declare function formatMoney(value: string | number | null | undefined, currency
9
24
  maximumFractionDigits: number;
10
25
  }): string;
11
26
 
12
- declare function createClassName(className: string): (...classNames: string[]) => string;
27
+ declare function genLoadingTableRows(columns: Dictionary[], limit: number): {
28
+ id: number | undefined;
29
+ key?: undefined;
30
+ }[];
13
31
 
14
32
  declare function genRandomNumber(min: number, max: number): number;
15
33
 
16
- interface Options {
34
+ declare function genUUID(): string;
35
+
36
+ interface Options$1 {
17
37
  hasOnlyLast4: boolean;
18
38
  isHidden: boolean;
19
39
  dot: string;
20
40
  }
21
- declare function getCardNumber(number: string, options?: Partial<Options>): string;
41
+ declare function getCardNumber(number: string, options?: Partial<Options$1>): string;
22
42
 
23
43
  declare function getCountryFromPhone(phone: string): string;
24
44
 
25
- interface Dictionary {
26
- [keys: string | number]: any;
27
- }
45
+ declare function isElementIgnored({ ignoredClasses, event, }?: {
46
+ ignoredClasses?: string[];
47
+ event?: Event;
48
+ }): boolean;
28
49
 
29
- declare function genLoadingTableRows(columns: Dictionary[], limit: number): {
30
- id: number | undefined;
31
- key?: undefined;
32
- }[];
50
+ declare function isEmptyObject(object: {}): boolean;
33
51
 
34
- declare function genUUID(): string;
52
+ declare function getPaginationParams({ page, limit, }: {
53
+ page: string | number;
54
+ limit: string | number;
55
+ }): {
56
+ limit: number;
57
+ offset: number;
58
+ };
59
+ declare function getPaginationLimit({ limit, }: {
60
+ limit: string | number;
61
+ }): number;
62
+ declare function getPaginationOffset({ page, limit, }: {
63
+ page: string | number;
64
+ limit: string | number;
65
+ }): number;
66
+ declare function getPaginationPages({ count, limit, }: {
67
+ count: number;
68
+ limit: string | number;
69
+ }): number;
35
70
 
36
- declare function camelizeKeys(object: Dictionary): Dictionary;
71
+ declare function parsePhone(phone: string): string;
37
72
 
38
- declare function validateNumber(value: string | number, defaultValue: number): number;
73
+ type SnakelizeKeysProp = Record<string | number, any>;
74
+ declare function snakelizeKeys(prop: SnakelizeKeysProp): SnakelizeKeysProp;
39
75
 
40
76
  /**
41
77
  * Принимает на вход число в виде строки или числа,
@@ -57,33 +93,43 @@ declare function validateNumber(value: string | number, defaultValue: number): n
57
93
  */
58
94
  declare function unformatNumber(value: string | number): string | number;
59
95
 
60
- declare function getPaginationParams({ page, limit, }: {
61
- page: string | number;
62
- limit: string | number;
63
- }): {
64
- limit: number;
65
- offset: number;
66
- };
67
- declare function getPaginationLimit({ limit, }: {
68
- limit: string | number;
69
- }): number;
70
- declare function getPaginationOffset({ page, limit, }: {
71
- page: string | number;
72
- limit: string | number;
73
- }): number;
74
- declare function getPaginationPages({ count, limit, }: {
75
- count: number;
76
- limit: string | number;
77
- }): number;
96
+ declare function validateNumber(value: string | number, defaultValue: number): number;
78
97
 
79
- declare function parsePhone(phone: string): string;
98
+ declare function useAbortController<T extends (...args: any[]) => any>(callback: T): {
99
+ call(...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;
100
+ abort(): void;
101
+ isAborted(error: ResponseError): boolean;
102
+ };
80
103
 
81
- declare function isElementIgnored({ ignoredClasses, event, }?: {
82
- ignoredClasses?: string[];
83
- event?: Event;
84
- }): boolean;
104
+ declare function useAsyncMultiselect<T extends (...args: any[]) => any, K extends (params: Awaited<ReturnType<T>>['results'][0]) => any>({ apiMethod, mapResultCallback, selectedValues, params, }: {
105
+ apiMethod: T;
106
+ mapResultCallback: K;
107
+ selectedValues: ComputedRef<Parameters<T>[0]['includedIds']> | WritableComputedRef<Parameters<T>[0]['includedIds']>;
108
+ params?: Parameters<T>[0];
109
+ }): {
110
+ search: vue.Ref<string>;
111
+ options: ComputedRef<ReturnType<K>[1][]>;
112
+ loading: vue.Ref<boolean>;
113
+ hasNextPage: ComputedRef<boolean>;
114
+ items: vue.Ref<Map<ReturnType<K>[0], ReturnType<K>[1]>>;
115
+ loadItems: (isSearch?: boolean) => Promise<void>;
116
+ handleSearch: (value: string) => Promise<void>;
117
+ };
85
118
 
86
- declare function isEmptyObject(object: {}): boolean;
119
+ declare function useAsyncSelect<T extends (...args: any[]) => any, K extends (params: Awaited<ReturnType<T>>['results'][0]) => any>({ apiMethod, mapResultCallback, includedIds, params, }: {
120
+ apiMethod: T;
121
+ mapResultCallback: K;
122
+ includedIds?: Parameters<T>[0]['includedIds'];
123
+ params?: Parameters<T>[0];
124
+ }): {
125
+ search: vue.Ref<string>;
126
+ options: vue.ComputedRef<ReturnType<K>[1][]>;
127
+ loading: vue.Ref<boolean>;
128
+ hasNextPage: vue.ComputedRef<boolean>;
129
+ items: vue.Ref<Map<ReturnType<K>[0], ReturnType<K>[1]>>;
130
+ loadItems: (isSearch?: boolean) => Promise<void>;
131
+ handleSearch: (value: string) => Promise<void>;
132
+ };
87
133
 
88
134
  declare const useClassName: (block: string) => {
89
135
  b: (blockSuffix?: string) => string;
@@ -118,6 +164,17 @@ type VersionsList = {
118
164
  };
119
165
  declare function useDetectBrowser(versions: VersionsList, userAgent?: any): BrowserInfo;
120
166
 
167
+ /**
168
+ * @see https://github.com/caiogondim/logdown.js#readme
169
+ */
170
+
171
+ interface Options {
172
+ tag?: string;
173
+ color?: string;
174
+ debug?: boolean;
175
+ }
176
+ declare function useLogger(scope: string, options?: Options): logdown.Logger;
177
+
121
178
  declare function validatePhone(rule: string, value: string): boolean;
122
179
 
123
- export { BrowserInfo, VersionsList, camelizeKeys, createClassName, formatMoney, genLoadingTableRows, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, parsePhone, unformatNumber, useClassName, useDayjs, useDetectBrowser, validateNumber, validatePhone, viewExample };
180
+ export { BrowserInfo, Dictionary, ResponseError, VersionsList, camelizeKeys, createClassName, formatMoney, genLoadingTableRows, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, parsePhone, snakelizeKeys, unformatNumber, useAbortController, useAsyncMultiselect, useAsyncSelect, useClassName, useDayjs, useDetectBrowser, useLogger, validateNumber, validatePhone };
package/dist/index.mjs CHANGED
@@ -1,14 +1,36 @@
1
+ import { camelCase, snakeCase } from 'lodash-es';
1
2
  import { parsePhoneNumberFromString } from 'libphonenumber-js';
2
- import { camelCase } from 'lodash-es';
3
+ import { ref, computed, onBeforeUnmount } from 'vue';
4
+ import { useDebounceFn } from '@vueuse/core';
3
5
  import dayjs from 'dayjs';
4
6
  import utc from 'dayjs/plugin/utc.js';
5
7
  import tz from 'dayjs/plugin/timezone.js';
6
8
  import updateLocale from 'dayjs/plugin/updateLocale.js';
7
9
  import isToday from 'dayjs/plugin/isToday.js';
8
10
  import { detect } from 'detect-browser';
11
+ import logdown from 'logdown';
9
12
 
10
- function viewExample(value) {
11
- return value;
13
+ function camelizeKeys(object) {
14
+ if (Array.isArray(object)) {
15
+ return object.map((v) => camelizeKeys(v));
16
+ }
17
+ if (object !== null && object.constructor === Object) {
18
+ return Object.keys(object).reduce(
19
+ (result, key) => ({
20
+ ...result,
21
+ [camelCase(key)]: camelizeKeys(object[key])
22
+ }),
23
+ {}
24
+ );
25
+ }
26
+ return object;
27
+ }
28
+
29
+ function createClassName(className) {
30
+ return function f(...classNames) {
31
+ const result = classNames.join("");
32
+ return (...args) => args.length ? f.apply(null, [result, ...args])() : result;
33
+ }(className);
12
34
  }
13
35
 
14
36
  function formatMoney(value, currency, options = { locale: "en-US", minimumFractionDigits: 2, maximumFractionDigits: 2 }) {
@@ -27,17 +49,33 @@ function formatMoney(value, currency, options = { locale: "en-US", minimumFracti
27
49
  return formatter.format(convertedValue);
28
50
  }
29
51
 
30
- function createClassName(className) {
31
- return function f(...classNames) {
32
- const result = classNames.join("");
33
- return (...args) => args.length ? f.apply(null, [result, ...args])() : result;
34
- }(className);
52
+ function genLoadingTableRows(columns, limit) {
53
+ const row = columns.reduce(
54
+ (acc, curr) => ({ ...acc, [curr.key]: void 0 }),
55
+ {}
56
+ );
57
+ return Array.from(Array(limit).keys()).map((item) => ({ id: item, ...row }));
35
58
  }
36
59
 
37
60
  function genRandomNumber(min, max) {
38
61
  return Math.floor(Math.random() * (max - min + 1)) + min;
39
62
  }
40
63
 
64
+ function genUUID() {
65
+ let d = new Date().getTime(), d2 = performance && performance.now && performance.now() * 1e3 || 0;
66
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
67
+ let r = Math.random() * 16;
68
+ if (d > 0) {
69
+ r = (d + r) % 16 | 0;
70
+ d = Math.floor(d / 16);
71
+ } else {
72
+ r = (d2 + r) % 16 | 0;
73
+ d2 = Math.floor(d2 / 16);
74
+ }
75
+ return (c == "x" ? r : r & 7 | 8).toString(16);
76
+ });
77
+ }
78
+
41
79
  function getCardNumber(number, options) {
42
80
  const { hasOnlyLast4 = false, isHidden = false, dot = "\u2022" } = options || {};
43
81
  let result;
@@ -60,49 +98,86 @@ function getCountryFromPhone(phone) {
60
98
  return phoneNumber?.country ?? "";
61
99
  }
62
100
 
63
- function genLoadingTableRows(columns, limit) {
64
- const row = columns.reduce(
65
- (acc, curr) => ({ ...acc, [curr.key]: void 0 }),
66
- {}
67
- );
68
- return Array.from(Array(limit).keys()).map((item) => ({ id: item, ...row }));
101
+ function isElementIgnored({
102
+ ignoredClasses,
103
+ event
104
+ } = {}) {
105
+ if (ignoredClasses && event) {
106
+ return Array.from(event.composedPath()).filter((item) => item.nodeType && item.nodeType !== 9).reduce((acc, item) => {
107
+ const elementClasses = item.getAttribute("class");
108
+ const array = elementClasses ? elementClasses.split(" ") : [];
109
+ return acc.concat(array);
110
+ }, []).some((item) => ignoredClasses.includes(item));
111
+ }
112
+ return false;
69
113
  }
70
114
 
71
- function genUUID() {
72
- let d = new Date().getTime(), d2 = performance && performance.now && performance.now() * 1e3 || 0;
73
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
74
- let r = Math.random() * 16;
75
- if (d > 0) {
76
- r = (d + r) % 16 | 0;
77
- d = Math.floor(d / 16);
78
- } else {
79
- r = (d2 + r) % 16 | 0;
80
- d2 = Math.floor(d2 / 16);
81
- }
82
- return (c == "x" ? r : r & 7 | 8).toString(16);
83
- });
115
+ function isEmptyObject(object) {
116
+ return !object || !Object.keys(object).length;
84
117
  }
85
118
 
86
- function camelizeKeys(object) {
87
- if (Array.isArray(object)) {
88
- return object.map((v) => camelizeKeys(v));
119
+ function validateNumber(value, defaultValue) {
120
+ if (value === "")
121
+ return defaultValue;
122
+ return Number.isNaN(Number(value)) ? defaultValue : Number(value);
123
+ }
124
+
125
+ const PAGE_DEFAULT = 1;
126
+ const LIMIT_DEFAULT = 25;
127
+ function getPaginationParams({
128
+ page,
129
+ limit
130
+ }) {
131
+ const validatedPage = validateNumber(page, PAGE_DEFAULT);
132
+ const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
133
+ return {
134
+ limit: validatedLimit,
135
+ offset: validatedPage * validatedLimit - validatedLimit
136
+ };
137
+ }
138
+ function getPaginationLimit({
139
+ limit
140
+ }) {
141
+ return validateNumber(limit, LIMIT_DEFAULT);
142
+ }
143
+ function getPaginationOffset({
144
+ page,
145
+ limit
146
+ }) {
147
+ const validatedPage = validateNumber(page, PAGE_DEFAULT);
148
+ const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
149
+ return validatedPage * validatedLimit - validatedLimit;
150
+ }
151
+ function getPaginationPages({
152
+ count,
153
+ limit
154
+ }) {
155
+ return Math.ceil(count / validateNumber(limit, LIMIT_DEFAULT));
156
+ }
157
+
158
+ function parsePhone(phone) {
159
+ const replacedPhone = phone.replace(/[a-zA-Z]/g, "");
160
+ if (replacedPhone.length === 1 && replacedPhone !== "+") {
161
+ return `+${replacedPhone}`;
89
162
  }
90
- if (object !== null && object.constructor === Object) {
91
- return Object.keys(object).reduce(
92
- (result, key) => ({
93
- ...result,
94
- [camelCase(key)]: camelizeKeys(object[key])
163
+ const phoneNumber = parsePhoneNumberFromString(replacedPhone);
164
+ return phoneNumber ? phoneNumber.formatInternational() : replacedPhone;
165
+ }
166
+
167
+ function snakelizeKeys(prop) {
168
+ if (Array.isArray(prop)) {
169
+ return prop.map((item) => snakelizeKeys(item));
170
+ }
171
+ if (prop !== null && prop !== void 0 && prop.constructor === Object) {
172
+ return Object.keys(prop).reduce(
173
+ (accum, current) => ({
174
+ ...accum,
175
+ [snakeCase(current)]: snakelizeKeys(prop[current])
95
176
  }),
96
177
  {}
97
178
  );
98
179
  }
99
- return object;
100
- }
101
-
102
- function validateNumber(value, defaultValue) {
103
- if (value === "")
104
- return defaultValue;
105
- return Number.isNaN(Number(value)) ? defaultValue : Number(value);
180
+ return prop;
106
181
  }
107
182
 
108
183
  const LOCALE_RU = "ru-RU";
@@ -145,64 +220,173 @@ function unformatNumber(value) {
145
220
  return value;
146
221
  }
147
222
 
148
- const PAGE_DEFAULT = 1;
149
- const LIMIT_DEFAULT = 25;
150
- function getPaginationParams({
151
- page,
152
- limit
153
- }) {
154
- const validatedPage = validateNumber(page, PAGE_DEFAULT);
155
- const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
223
+ function useAbortController(callback) {
224
+ let controller = null;
156
225
  return {
157
- limit: validatedLimit,
158
- offset: validatedPage * validatedLimit - validatedLimit
226
+ async call(...args) {
227
+ if (controller) {
228
+ controller.abort();
229
+ }
230
+ controller = new AbortController();
231
+ let response;
232
+ if (args.length > 0) {
233
+ response = await callback(...args, {
234
+ signal: controller.signal
235
+ });
236
+ } else {
237
+ response = await callback({
238
+ signal: controller.signal
239
+ });
240
+ }
241
+ controller = null;
242
+ return response;
243
+ },
244
+ abort() {
245
+ if (!controller)
246
+ return;
247
+ controller.abort();
248
+ controller = null;
249
+ },
250
+ isAborted(error) {
251
+ return error.status === 418;
252
+ }
159
253
  };
160
254
  }
161
- function getPaginationLimit({
162
- limit
163
- }) {
164
- return validateNumber(limit, LIMIT_DEFAULT);
165
- }
166
- function getPaginationOffset({
167
- page,
168
- limit
169
- }) {
170
- const validatedPage = validateNumber(page, PAGE_DEFAULT);
171
- const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
172
- return validatedPage * validatedLimit - validatedLimit;
173
- }
174
- function getPaginationPages({
175
- count,
176
- limit
177
- }) {
178
- return Math.ceil(count / validateNumber(limit, LIMIT_DEFAULT));
179
- }
180
-
181
- function parsePhone(phone) {
182
- const replacedPhone = phone.replace(/[a-zA-Z]/g, "");
183
- if (replacedPhone.length === 1 && replacedPhone !== "+") {
184
- return `+${replacedPhone}`;
185
- }
186
- const phoneNumber = parsePhoneNumberFromString(replacedPhone);
187
- return phoneNumber ? phoneNumber.formatInternational() : replacedPhone;
188
- }
189
255
 
190
- function isElementIgnored({
191
- ignoredClasses,
192
- event
193
- } = {}) {
194
- if (ignoredClasses && event) {
195
- return Array.from(event.composedPath()).filter((item) => item.nodeType && item.nodeType !== 9).reduce((acc, item) => {
196
- const elementClasses = item.getAttribute("class");
197
- const array = elementClasses ? elementClasses.split(" ") : [];
198
- return acc.concat(array);
199
- }, []).some((item) => ignoredClasses.includes(item));
200
- }
201
- return false;
256
+ function useAsyncMultiselect({
257
+ apiMethod,
258
+ mapResultCallback,
259
+ selectedValues,
260
+ params = void 0
261
+ }) {
262
+ const items = ref(/* @__PURE__ */ new Map());
263
+ const loading = ref(false);
264
+ const search = ref("");
265
+ const count = ref(0);
266
+ const page = ref(1);
267
+ const options = computed(() => [...items.value.values()]);
268
+ const hasNextPage = computed(() => count.value > items.value.size);
269
+ const {
270
+ call: apiMethodWAC,
271
+ abort,
272
+ isAborted
273
+ } = useAbortController(apiMethod);
274
+ const handleSearch = async (value) => {
275
+ if (search.value === value)
276
+ return;
277
+ search.value = value;
278
+ await loadItemsWithDebounce();
279
+ };
280
+ const loadItems = async (isSearch) => {
281
+ loading.value = true;
282
+ try {
283
+ const { results, count: itemsCount } = await apiMethodWAC({
284
+ page: page.value,
285
+ search: search.value,
286
+ ...selectedValues.value?.length && !search.value && { includedIds: selectedValues.value },
287
+ ...params
288
+ });
289
+ count.value = itemsCount;
290
+ if (isSearch) {
291
+ const cashedMapItems = selectedValues.value.map(
292
+ (selectedValue) => [
293
+ selectedValue,
294
+ items.value.get(selectedValue)
295
+ ]
296
+ );
297
+ items.value = new Map([...cashedMapItems]);
298
+ }
299
+ const resultsForMap = results.map(mapResultCallback);
300
+ items.value = new Map([...items.value, ...resultsForMap]);
301
+ page.value += 1;
302
+ loading.value = false;
303
+ } catch (error) {
304
+ if (isAborted(error))
305
+ return;
306
+ loading.value = false;
307
+ }
308
+ };
309
+ const loadItemsWithDebounce = useDebounceFn(async () => {
310
+ page.value = 1;
311
+ await loadItems(true);
312
+ }, 300);
313
+ onBeforeUnmount(() => {
314
+ abort?.();
315
+ });
316
+ return {
317
+ search,
318
+ options,
319
+ loading,
320
+ hasNextPage,
321
+ items,
322
+ loadItems,
323
+ handleSearch
324
+ };
202
325
  }
203
326
 
204
- function isEmptyObject(object) {
205
- return !object || !Object.keys(object).length;
327
+ function useAsyncSelect({
328
+ apiMethod,
329
+ mapResultCallback,
330
+ includedIds = void 0,
331
+ params = void 0
332
+ }) {
333
+ const items = ref(/* @__PURE__ */ new Map());
334
+ const loading = ref(false);
335
+ const search = ref("");
336
+ const count = ref(0);
337
+ const page = ref(1);
338
+ const options = computed(() => [...items.value.values()]);
339
+ const hasNextPage = computed(() => count.value > items.value.size);
340
+ const {
341
+ call: apiMethodWAC,
342
+ abort,
343
+ isAborted
344
+ } = useAbortController(apiMethod);
345
+ const handleSearch = async (value) => {
346
+ if (search.value === value)
347
+ return;
348
+ search.value = value;
349
+ await loadItemsWithDebounce();
350
+ };
351
+ const loadItems = async (isSearch) => {
352
+ loading.value = true;
353
+ try {
354
+ const { results, count: itemsCount } = await apiMethodWAC({
355
+ page: page.value,
356
+ search: search.value,
357
+ ...includedIds?.length && includedIds,
358
+ ...params
359
+ });
360
+ count.value = itemsCount;
361
+ if (isSearch) {
362
+ items.value = /* @__PURE__ */ new Map();
363
+ }
364
+ const resultsForMap = results.map(mapResultCallback);
365
+ items.value = new Map([...items.value, ...resultsForMap]);
366
+ page.value += 1;
367
+ loading.value = false;
368
+ } catch (error) {
369
+ if (isAborted(error))
370
+ return;
371
+ loading.value = false;
372
+ }
373
+ };
374
+ const loadItemsWithDebounce = useDebounceFn(async () => {
375
+ page.value = 1;
376
+ await loadItems(true);
377
+ }, 300);
378
+ onBeforeUnmount(() => {
379
+ abort?.();
380
+ });
381
+ return {
382
+ search,
383
+ options,
384
+ loading,
385
+ hasNextPage,
386
+ items,
387
+ loadItems,
388
+ handleSearch
389
+ };
206
390
  }
207
391
 
208
392
  const _bem = (block, blockSuffix, element, modifier, modifierValue) => {
@@ -241,6 +425,7 @@ const useClassName = (block) => {
241
425
  m,
242
426
  em,
243
427
  mv,
428
+ // CSS
244
429
  cssVar,
245
430
  cssVarName
246
431
  };
@@ -300,9 +485,37 @@ function useDetectBrowser(versions, userAgent) {
300
485
  });
301
486
  }
302
487
 
488
+ function isEnabled(options) {
489
+ if (options?.debug !== void 0)
490
+ return options.debug;
491
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
492
+ if (isBrowser) {
493
+ const debug = localStorage.getItem("debug");
494
+ if (debug === "true")
495
+ return true;
496
+ if (debug === "false")
497
+ return false;
498
+ }
499
+ const isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
500
+ if (isNode) {
501
+ const debug = process.env["NODE_DEBUG"];
502
+ if (debug === "true")
503
+ return true;
504
+ if (debug === "false")
505
+ return false;
506
+ }
507
+ return false;
508
+ }
509
+ function useLogger(scope, options) {
510
+ const prefix = options?.tag ? `[${scope.toUpperCase()}.${options.tag}]:` : `[${scope.toUpperCase()}]:`;
511
+ const logger = logdown(prefix, { prefixColor: options?.color });
512
+ logger.state.isEnabled = isEnabled(options);
513
+ return logger;
514
+ }
515
+
303
516
  function validatePhone(rule, value) {
304
517
  const phoneNumber = parsePhoneNumberFromString(value);
305
518
  return phoneNumber ? phoneNumber.isValid() : false;
306
519
  }
307
520
 
308
- export { camelizeKeys, createClassName, formatMoney, genLoadingTableRows, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, parsePhone, unformatNumber, useClassName, useDayjs, useDetectBrowser, validateNumber, validatePhone, viewExample };
521
+ export { camelizeKeys, createClassName, formatMoney, genLoadingTableRows, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, parsePhone, snakelizeKeys, unformatNumber, useAbortController, useAsyncMultiselect, useAsyncSelect, useClassName, useDayjs, useDetectBrowser, useLogger, validateNumber, validatePhone };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@karta.io/utils",
3
- "version": "0.23.6",
3
+ "version": "0.25.0",
4
4
  "description": "karta.io utils for admin and application",
5
5
  "author": "Vitaly Blokhin <karambafe@gmail.com>",
6
6
  "homepage": "",
@@ -19,12 +19,17 @@
19
19
  "files": [
20
20
  "dist"
21
21
  ],
22
+ "peerDependencies": {
23
+ "vue": "3.2.45"
24
+ },
22
25
  "dependencies": {
23
- "@karta.io/common-data": "^0.23.6",
26
+ "@karta.io/common-data": "^0.25.0",
27
+ "@vueuse/core": "9.10.0",
24
28
  "dayjs": "1.11.6",
25
29
  "detect-browser": "5.3.0",
26
30
  "libphonenumber-js": "1.9.44",
27
- "lodash-es": "4.17.21"
31
+ "lodash-es": "4.17.21",
32
+ "logdown": "3.3.1"
28
33
  },
29
34
  "devDependencies": {
30
35
  "@qvant/prettier-config": "0.1.0",
@@ -33,8 +38,9 @@
33
38
  "eslint-plugin-import": "2.26.0",
34
39
  "prettier": "2.8.0",
35
40
  "typescript": "4.9.4",
36
- "unbuild": "1.0.1",
37
- "vitest": "0.25.3"
41
+ "unbuild": "1.1.1",
42
+ "vitest": "0.25.3",
43
+ "vue": "^3.2.45"
38
44
  },
39
45
  "scripts": {
40
46
  "dev": "vitest",