@karta.io/utils 1.0.0-beta.50 → 1.0.0-beta.51

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.
Files changed (43) hide show
  1. package/dist/helpers/appComponentsResolver.d.ts +5 -0
  2. package/dist/helpers/camelizeKeys.d.ts +2 -0
  3. package/dist/helpers/convertEnumToOptions.d.ts +8 -0
  4. package/dist/helpers/enrichError.d.ts +8 -0
  5. package/dist/helpers/formatError.d.ts +7 -0
  6. package/dist/helpers/formatMoney.d.ts +6 -0
  7. package/dist/helpers/genHash.d.ts +1 -0
  8. package/dist/helpers/genRandomNumber.d.ts +1 -0
  9. package/dist/helpers/genUUID.d.ts +1 -0
  10. package/dist/helpers/getCardNumber.d.ts +7 -0
  11. package/dist/helpers/getCountryFromPhone.d.ts +1 -0
  12. package/dist/helpers/isElementIgnored.d.ts +4 -0
  13. package/dist/helpers/isEmptyObject.d.ts +1 -0
  14. package/dist/helpers/isHtml.d.ts +1 -0
  15. package/dist/helpers/mapDataObjectForFilters.d.ts +10 -0
  16. package/dist/helpers/pagination.d.ts +18 -0
  17. package/dist/helpers/parsePhone.d.ts +1 -0
  18. package/dist/helpers/snakelizeKeys.d.ts +3 -0
  19. package/dist/helpers/uiComponentsResolver.d.ts +5 -0
  20. package/dist/helpers/unformatNumber.d.ts +19 -0
  21. package/dist/helpers/validateNumber.d.ts +1 -0
  22. package/dist/hooks/useAbortController.d.ts +6 -0
  23. package/dist/hooks/useAsyncItems.d.ts +19 -0
  24. package/dist/hooks/useAsyncMultiselect.d.ts +31 -0
  25. package/dist/hooks/useAsyncSelect.d.ts +30 -0
  26. package/dist/hooks/useBreakpoint.d.ts +11 -0
  27. package/dist/hooks/useClassName.d.ts +9 -0
  28. package/dist/hooks/useDayjs.d.ts +10 -0
  29. package/dist/hooks/useDetectBrowser.d.ts +13 -0
  30. package/dist/hooks/useDialog.d.ts +48 -0
  31. package/dist/hooks/useFilters.d.ts +18 -0
  32. package/dist/hooks/useGlobalScroll.d.ts +6 -0
  33. package/dist/hooks/useLogger.d.ts +8 -0
  34. package/dist/hooks/usePanel.d.ts +27 -0
  35. package/dist/index.cjs +1536 -1495
  36. package/dist/index.d.ts +37 -394
  37. package/dist/index.mjs +1493 -1470
  38. package/dist/types.d.ts +11 -0
  39. package/dist/validator/formRules.d.ts +14 -0
  40. package/dist/validator/validatePhone.d.ts +1 -0
  41. package/package.json +22 -23
  42. package/dist/index.d.cts +0 -394
  43. package/dist/index.d.mts +0 -394
package/dist/index.mjs CHANGED
@@ -1,1570 +1,1593 @@
1
- import camelCase from 'lodash/camelCase.js';
2
- import flatMap from 'lodash/flatMap.js';
3
- import { CURRENCY_DEFAULT, BREAKPOINTS } from '@karta.io/common-data';
4
- import { parsePhoneNumberFromString } from 'libphonenumber-js';
5
- import snakeCase from 'lodash/snakeCase.js';
6
- import { toValue, computed, ref, watch, reactive, isRef, nextTick, onBeforeUnmount, onMounted, getCurrentInstance, render, createVNode } from 'vue';
7
- import { useQuery, useQueryClient } from '@tanstack/vue-query';
8
- import { useDebounceFn, useBreakpoints } from '@vueuse/core';
9
- import get from 'lodash/get.js';
10
- import has from 'lodash/has.js';
11
- import union from 'lodash/union.js';
12
- import logdown from 'logdown';
13
- import dayjs from 'dayjs';
14
- import utc from 'dayjs/plugin/utc.js';
15
- import tz from 'dayjs/plugin/timezone.js';
16
- import updateLocale from 'dayjs/plugin/updateLocale.js';
17
- import isToday from 'dayjs/plugin/isToday.js';
18
- import customParseFormat from 'dayjs/plugin/customParseFormat.js';
19
- import { detect } from 'detect-browser';
20
- import { useRoute, useRouter } from 'vue-router';
21
- import qs from 'qs';
22
-
1
+ import camelCase from "lodash/camelCase.js";
2
+ import flatMap from "lodash/flatMap.js";
3
+ import { BREAKPOINTS, CURRENCY_DEFAULT } from "@karta.io/common-data";
4
+ import { parsePhoneNumberFromString } from "libphonenumber-js";
5
+ import snakeCase from "lodash/snakeCase.js";
6
+ import { computed, createVNode, getCurrentInstance, isRef, nextTick, onBeforeUnmount, onMounted, reactive, ref, render, toValue, watch } from "vue";
7
+ import { useQuery, useQueryClient } from "@tanstack/vue-query";
8
+ import { useBreakpoints, useDebounceFn } from "@vueuse/core";
9
+ import get from "lodash/get.js";
10
+ import has from "lodash/has.js";
11
+ import union from "lodash/union.js";
12
+ import logdown from "logdown";
13
+ import dayjs from "dayjs";
14
+ import utc from "dayjs/plugin/utc.js";
15
+ import tz from "dayjs/plugin/timezone.js";
16
+ import updateLocale from "dayjs/plugin/updateLocale.js";
17
+ import isToday from "dayjs/plugin/isToday.js";
18
+ import customParseFormat from "dayjs/plugin/customParseFormat.js";
19
+ import { detect } from "detect-browser";
20
+ import { useRoute, useRouter } from "vue-router";
21
+ import qs from "qs";
22
+ //#region src/helpers/appComponentsResolver.ts
23
23
  function AppComponentsResolver(options = {}) {
24
- const { prefix = "" } = options;
25
- return (name) => {
26
- const componentName = prefix && name.startsWith(prefix) ? name.substring(prefix.length) : name;
27
- const isAppComponent = componentName.startsWith("App");
28
- if (isAppComponent) {
29
- return { name: componentName, from: "@karta.io/app-components" };
30
- }
31
- };
24
+ const { prefix = "" } = options;
25
+ return (name) => {
26
+ const componentName = prefix && name.startsWith(prefix) ? name.substring(prefix.length) : name;
27
+ if (componentName.startsWith("App")) return {
28
+ name: componentName,
29
+ from: "@karta.io/app-components"
30
+ };
31
+ };
32
32
  }
33
-
33
+ //#endregion
34
+ //#region src/helpers/camelizeKeys.ts
34
35
  function camelizeKeys(object) {
35
- if (Array.isArray(object)) {
36
- return object.map((v) => camelizeKeys(v));
37
- }
38
- if (object !== null && object.constructor === Object) {
39
- return Object.keys(object).reduce(
40
- (result, key) => ({
41
- ...result,
42
- [camelCase(key)]: camelizeKeys(object[key])
43
- }),
44
- {}
45
- );
46
- }
47
- return object;
36
+ if (Array.isArray(object)) return object.map((v) => camelizeKeys(v));
37
+ if (object !== null && object.constructor === Object) return Object.keys(object).reduce((result, key) => ({
38
+ ...result,
39
+ [camelCase(key)]: camelizeKeys(object[key])
40
+ }), {});
41
+ return object;
48
42
  }
49
-
50
- const OPTIONS_DEFAULT = {
51
- labelType: "value"
52
- };
43
+ //#endregion
44
+ //#region src/helpers/convertEnumToOptions.ts
45
+ var OPTIONS_DEFAULT = { labelType: "value" };
53
46
  function convertEnumToOptions(obj, options) {
54
- const newOptions = {
55
- ...OPTIONS_DEFAULT,
56
- ...options
57
- };
58
- return Object.entries(obj).map(([key, value]) => ({
59
- value,
60
- label: newOptions.labelType === "key" ? key : value
61
- }));
62
- }
63
-
64
- class EnrichError extends Error {
65
- constructor(data) {
66
- super(data.message);
67
- Object.assign(this, data);
68
- }
47
+ const newOptions = {
48
+ ...OPTIONS_DEFAULT,
49
+ ...options
50
+ };
51
+ return Object.entries(obj).map(([key, value]) => ({
52
+ value,
53
+ label: newOptions.labelType === "key" ? key : value
54
+ }));
69
55
  }
70
-
56
+ //#endregion
57
+ //#region src/helpers/enrichError.ts
58
+ var EnrichError = class extends Error {
59
+ constructor(data) {
60
+ super(data.message);
61
+ Object.assign(this, data);
62
+ }
63
+ };
64
+ //#endregion
65
+ //#region src/helpers/isHtml.ts
71
66
  function isHtml(data) {
72
- try {
73
- if (typeof DOMParser !== "undefined") {
74
- const parser = new DOMParser();
75
- const doc = parser.parseFromString(data, "text/html");
76
- return Array.from(doc.body.childNodes).some(
77
- (node) => node.nodeType === Node.ELEMENT_NODE
78
- );
79
- }
80
- const htmlPattern = /<\/?[a-z][\s\S]*>/i;
81
- return htmlPattern.test(data);
82
- } catch (_) {
83
- return false;
84
- }
67
+ try {
68
+ if (typeof DOMParser !== "undefined") {
69
+ const doc = new DOMParser().parseFromString(data, "text/html");
70
+ return Array.from(doc.body.childNodes).some((node) => node.nodeType === Node.ELEMENT_NODE);
71
+ }
72
+ return /<\/?[a-z][\s\S]*>/i.test(data);
73
+ } catch (_) {
74
+ return false;
75
+ }
85
76
  }
86
-
77
+ //#endregion
78
+ //#region src/helpers/formatError.ts
87
79
  function getStatusMessage(status) {
88
- let message = "";
89
- switch (status) {
90
- case 200:
91
- message = "All done. Request successfully executed";
92
- break;
93
- case 201:
94
- message = "Data successfully created";
95
- break;
96
- case 400:
97
- message = "Bad request";
98
- break;
99
- case 401:
100
- message = "Need auth";
101
- break;
102
- case 404:
103
- message = "Not found";
104
- break;
105
- case 500:
106
- message = "Something wrong. Internal server error";
107
- break;
108
- case 501:
109
- message = "501: Not implemented";
110
- break;
111
- case 502:
112
- message = "502: Bad gateway";
113
- break;
114
- case 503:
115
- message = "Service unavailable. Try again later";
116
- break;
117
- default:
118
- message = "Something wrong. Client default error message";
119
- break;
120
- }
121
- return message;
80
+ let message = "";
81
+ switch (status) {
82
+ case 200:
83
+ message = "All done. Request successfully executed";
84
+ break;
85
+ case 201:
86
+ message = "Data successfully created";
87
+ break;
88
+ case 400:
89
+ message = "Bad request";
90
+ break;
91
+ case 401:
92
+ message = "Need auth";
93
+ break;
94
+ case 404:
95
+ message = "Not found";
96
+ break;
97
+ case 500:
98
+ message = "Something wrong. Internal server error";
99
+ break;
100
+ case 501:
101
+ message = "501: Not implemented";
102
+ break;
103
+ case 502:
104
+ message = "502: Bad gateway";
105
+ break;
106
+ case 503:
107
+ message = "Service unavailable. Try again later";
108
+ break;
109
+ default: message = "Something wrong. Client default error message";
110
+ }
111
+ return message;
122
112
  }
123
113
  function formatErrorDataMessage(data) {
124
- if (!data) return "";
125
- return Object.values(data).reduce((accum, current) => {
126
- if (current && typeof current === "string")
127
- return accum ? `${accum} | ${current}` : current;
128
- if (Array.isArray(current) && current.length) {
129
- const value = `${flatMap(current).join(" | ")}`;
130
- return accum ? `${accum} | ${value}` : value;
131
- }
132
- return accum;
133
- }, "");
114
+ if (!data) return "";
115
+ return Object.values(data).reduce((accum, current) => {
116
+ if (current && typeof current === "string") return accum ? `${accum} | ${current}` : current;
117
+ if (Array.isArray(current) && current.length) {
118
+ const value = `${flatMap(current).join(" | ")}`;
119
+ return accum ? `${accum} | ${value}` : value;
120
+ }
121
+ return accum;
122
+ }, "");
134
123
  }
135
124
  function formatErrorForNotify(error) {
136
- if (!error) return;
137
- if (error.status >= 400 && error.status < 500) {
138
- let message = "";
139
- if (!error.data || typeof error.data === "string" && isHtml(error.data)) {
140
- message = error.statusMessage || error.message || getStatusMessage(error.status);
141
- } else if (typeof error.data === "string" && !isHtml(error.data)) {
142
- message = error.data;
143
- } else {
144
- message = formatErrorDataMessage(error.data);
145
- }
146
- return {
147
- title: "Request error",
148
- message
149
- };
150
- }
151
- if (error.status >= 500) {
152
- return {
153
- title: "Internal server error",
154
- message: error.statusMessage || error.message || getStatusMessage(error.status)
155
- };
156
- }
157
- if (error instanceof Error) {
158
- return {
159
- title: "Internal client error",
160
- message: error.message
161
- };
162
- }
125
+ if (!error) return;
126
+ if (error.status >= 400 && error.status < 500) {
127
+ let message = "";
128
+ if (!error.data || typeof error.data === "string" && isHtml(error.data)) message = error.statusMessage || error.message || getStatusMessage(error.status);
129
+ else if (typeof error.data === "string" && !isHtml(error.data)) message = error.data;
130
+ else message = formatErrorDataMessage(error.data);
131
+ return {
132
+ title: "Request error",
133
+ message
134
+ };
135
+ }
136
+ if (error.status >= 500) return {
137
+ title: "Internal server error",
138
+ message: error.statusMessage || error.message || getStatusMessage(error.status)
139
+ };
140
+ if (error instanceof Error) return {
141
+ title: "Internal client error",
142
+ message: error.message
143
+ };
163
144
  }
164
-
145
+ //#endregion
146
+ //#region src/helpers/formatMoney.ts
165
147
  function formatMoney(value, currency = CURRENCY_DEFAULT, options = {}) {
166
- const { locale = "en-US", defaultValue = 0, ...otherOptions } = options;
167
- try {
168
- let convertedValue = Number(value);
169
- if (value === null || Number.isNaN(convertedValue)) {
170
- if (defaultValue === "") return defaultValue;
171
- convertedValue = Number(defaultValue);
172
- }
173
- const formatter = new Intl.NumberFormat(locale, {
174
- style: "currency",
175
- currency,
176
- minimumFractionDigits: 2,
177
- maximumFractionDigits: 2,
178
- ...otherOptions
179
- });
180
- return formatter.format(convertedValue);
181
- } catch (_error) {
182
- return defaultValue;
183
- }
148
+ const { locale = "en-US", defaultValue = 0, ...otherOptions } = options;
149
+ try {
150
+ let convertedValue = Number(value);
151
+ if (value === null || Number.isNaN(convertedValue)) {
152
+ if (defaultValue === "") return defaultValue;
153
+ convertedValue = Number(defaultValue);
154
+ }
155
+ return new Intl.NumberFormat(locale, {
156
+ style: "currency",
157
+ currency,
158
+ minimumFractionDigits: 2,
159
+ maximumFractionDigits: 2,
160
+ ...otherOptions
161
+ }).format(convertedValue);
162
+ } catch (_error) {
163
+ return defaultValue;
164
+ }
184
165
  }
185
-
166
+ //#endregion
167
+ //#region src/helpers/genHash.ts
186
168
  function genHash(hashLength) {
187
- const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
188
- let result = "";
189
- for (let i = 0; i < hashLength; i++) {
190
- result += chars.charAt(Math.floor(Math.random() * chars.length));
191
- }
192
- return result;
169
+ const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
170
+ let result = "";
171
+ for (let i = 0; i < hashLength; i++) result += chars.charAt(Math.floor(Math.random() * 62));
172
+ return result;
193
173
  }
194
-
174
+ //#endregion
175
+ //#region src/helpers/genRandomNumber.ts
195
176
  function genRandomNumber(min, max) {
196
- return Math.floor(Math.random() * (max - min + 1)) + min;
177
+ return Math.floor(Math.random() * (max - min + 1)) + min;
197
178
  }
198
-
179
+ //#endregion
180
+ //#region src/helpers/genUUID.ts
199
181
  function genUUID() {
200
- let d = (/* @__PURE__ */ new Date()).getTime();
201
- let d2 = performance && performance.now && performance.now() * 1e3 || 0;
202
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
203
- let r = Math.random() * 16;
204
- if (d > 0) {
205
- r = (d + r) % 16 | 0;
206
- d = Math.floor(d / 16);
207
- } else {
208
- r = (d2 + r) % 16 | 0;
209
- d2 = Math.floor(d2 / 16);
210
- }
211
- return (c === "x" ? r : r & 7 | 8).toString(16);
212
- });
182
+ /**
183
+ * @see https://stackoverflow.com/a/8809472
184
+ */
185
+ let d = (/* @__PURE__ */ new Date()).getTime();
186
+ let d2 = performance && performance.now && performance.now() * 1e3 || 0;
187
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
188
+ let r = Math.random() * 16;
189
+ if (d > 0) {
190
+ r = (d + r) % 16 | 0;
191
+ d = Math.floor(d / 16);
192
+ } else {
193
+ r = (d2 + r) % 16 | 0;
194
+ d2 = Math.floor(d2 / 16);
195
+ }
196
+ return (c === "x" ? r : r & 7 | 8).toString(16);
197
+ });
213
198
  }
214
-
199
+ //#endregion
200
+ //#region src/helpers/getCardNumber.ts
215
201
  function getCardNumber(number, options) {
216
- const { hasOnlyLast4 = false, isHidden = false, dot = "\u2022" } = options || {};
217
- let result;
218
- if (isHidden) {
219
- result = "\u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022";
220
- } else {
221
- result = number.replace(
222
- /(\d{4})?(\d{4})?(\d{4})?(\d{4})?/,
223
- hasOnlyLast4 ? "\u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 $4" : "$1 $2 $3 $4"
224
- );
225
- }
226
- return dot === "\u2022" ? result : result.replaceAll("\u2022", dot);
202
+ const { hasOnlyLast4 = false, isHidden = false, dot = "•" } = options || {};
203
+ let result;
204
+ if (isHidden) result = "•••• •••• •••• ••••";
205
+ else result = number.replace(/(\d{4})?(\d{4})?(\d{4})?(\d{4})?/, hasOnlyLast4 ? "•••• •••• •••• $4" : "$1 $2 $3 $4");
206
+ return dot === "•" ? result : result.replaceAll("•", dot);
227
207
  }
228
-
208
+ //#endregion
209
+ //#region src/helpers/getCountryFromPhone.ts
229
210
  function getCountryFromPhone(phone) {
230
- if (!phone) return "";
231
- const replacedPhone = phone.replace(/[a-zA-Z]/g, "");
232
- const phoneNumber = parsePhoneNumberFromString(replacedPhone);
233
- return phoneNumber?.country ?? "";
211
+ if (!phone) return "";
212
+ const replacedPhone = phone.replace(/[a-zA-Z]/g, "");
213
+ return parsePhoneNumberFromString(replacedPhone)?.country ?? "";
234
214
  }
235
-
236
- function isElementIgnored({
237
- ignoredClasses,
238
- event
239
- } = {}) {
240
- if (ignoredClasses && event) {
241
- return Array.from(event.composedPath()).filter((item) => item.nodeType && item.nodeType !== 9).reduce((acc, item) => {
242
- const elementClasses = item.getAttribute("class");
243
- const array = elementClasses ? elementClasses.split(" ") : [];
244
- return acc.concat(array);
245
- }, []).some((item) => ignoredClasses.includes(item));
246
- }
247
- return false;
215
+ //#endregion
216
+ //#region src/helpers/isElementIgnored.ts
217
+ function isElementIgnored({ ignoredClasses, event } = {}) {
218
+ if (ignoredClasses && event) return Array.from(event.composedPath()).filter((item) => item.nodeType && item.nodeType !== 9).reduce((acc, item) => {
219
+ const elementClasses = item.getAttribute("class");
220
+ const array = elementClasses ? elementClasses.split(" ") : [];
221
+ return acc.concat(array);
222
+ }, []).some((item) => ignoredClasses.includes(item));
223
+ return false;
248
224
  }
249
-
225
+ //#endregion
226
+ //#region src/helpers/isEmptyObject.ts
250
227
  function isEmptyObject(object) {
251
- return !object || !Object.keys(object).length;
228
+ return !object || !Object.keys(object).length;
252
229
  }
253
-
254
- const optionsDefault = {
255
- labelKey: "title",
256
- valueKey: "",
257
- excludedItems: []
230
+ //#endregion
231
+ //#region src/helpers/mapDataObjectForFilters.ts
232
+ var optionsDefault = {
233
+ labelKey: "title",
234
+ valueKey: "",
235
+ excludedItems: []
258
236
  };
259
237
  function mapDataObjectForFilters(data, options) {
260
- const newOptions = {
261
- ...optionsDefault,
262
- ...options
263
- };
264
- const { labelKey, valueKey, excludedItems } = newOptions;
265
- return Object.entries(data).filter(([key]) => !excludedItems.includes(key)).map(([key, value]) => ({
266
- label: value?.[labelKey] || "Unknown label",
267
- value: value?.[valueKey] || key
268
- }));
238
+ const { labelKey, valueKey, excludedItems } = {
239
+ ...optionsDefault,
240
+ ...options
241
+ };
242
+ return Object.entries(data).filter(([key]) => !excludedItems.includes(key)).map(([key, value]) => ({
243
+ label: value?.[labelKey] || "Unknown label",
244
+ value: value?.[valueKey] || key
245
+ }));
269
246
  }
270
-
247
+ //#endregion
248
+ //#region src/helpers/validateNumber.ts
271
249
  function validateNumber(value, defaultValue) {
272
- if (value === "") return defaultValue;
273
- return Number.isNaN(Number(value)) ? defaultValue : Number(value);
250
+ if (value === "") return defaultValue;
251
+ return Number.isNaN(Number(value)) ? defaultValue : Number(value);
274
252
  }
275
-
276
- const PAGE_DEFAULT = 1;
277
- const LIMIT_DEFAULT = 25;
278
- function getPaginationParams({
279
- page,
280
- limit
281
- }) {
282
- const validatedPage = validateNumber(page, PAGE_DEFAULT);
283
- const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
284
- return {
285
- limit: validatedLimit,
286
- offset: validatedPage * validatedLimit - validatedLimit
287
- };
253
+ //#endregion
254
+ //#region src/helpers/pagination.ts
255
+ var PAGE_DEFAULT = 1;
256
+ var LIMIT_DEFAULT = 25;
257
+ function getPaginationParams({ page, limit }) {
258
+ const validatedPage = validateNumber(page, PAGE_DEFAULT);
259
+ const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
260
+ return {
261
+ limit: validatedLimit,
262
+ offset: validatedPage * validatedLimit - validatedLimit
263
+ };
288
264
  }
289
- function getPaginationLimit({
290
- limit
291
- }) {
292
- return validateNumber(limit, LIMIT_DEFAULT);
265
+ function getPaginationLimit({ limit }) {
266
+ return validateNumber(limit, LIMIT_DEFAULT);
293
267
  }
294
- function getPaginationOffset({
295
- page,
296
- limit
297
- }) {
298
- const validatedPage = validateNumber(page, PAGE_DEFAULT);
299
- const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
300
- return validatedPage * validatedLimit - validatedLimit;
268
+ function getPaginationOffset({ page, limit }) {
269
+ const validatedPage = validateNumber(page, PAGE_DEFAULT);
270
+ const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
271
+ return validatedPage * validatedLimit - validatedLimit;
301
272
  }
302
- function getPaginationPages({
303
- count,
304
- limit
305
- }) {
306
- return Math.ceil(count / validateNumber(limit, LIMIT_DEFAULT));
273
+ function getPaginationPages({ count, limit }) {
274
+ return Math.ceil(count / validateNumber(limit, LIMIT_DEFAULT));
307
275
  }
308
-
276
+ //#endregion
277
+ //#region src/helpers/parsePhone.ts
309
278
  function parsePhone(phone) {
310
- if (!phone || typeof phone !== "string") return "";
311
- const replacedPhone = phone.replace(/[a-zA-Z]/g, "");
312
- if (replacedPhone.length === 1 && replacedPhone !== "+") {
313
- return `+${replacedPhone}`;
314
- }
315
- const phoneNumber = parsePhoneNumberFromString(replacedPhone);
316
- return phoneNumber ? phoneNumber.formatInternational() : replacedPhone;
279
+ if (!phone || typeof phone !== "string") return "";
280
+ const replacedPhone = phone.replace(/[a-zA-Z]/g, "");
281
+ if (replacedPhone.length === 1 && replacedPhone !== "+") return `+${replacedPhone}`;
282
+ const phoneNumber = parsePhoneNumberFromString(replacedPhone);
283
+ return phoneNumber ? phoneNumber.formatInternational() : replacedPhone;
317
284
  }
318
-
285
+ //#endregion
286
+ //#region src/helpers/snakelizeKeys.ts
319
287
  function snakelizeKeys(prop) {
320
- if (Array.isArray(prop)) {
321
- return prop.map((item) => snakelizeKeys(item));
322
- }
323
- if (prop !== null && prop !== void 0 && prop.constructor === Object) {
324
- return Object.keys(prop).reduce(
325
- (accum, current) => ({
326
- ...accum,
327
- [snakeCase(current)]: snakelizeKeys(prop[current])
328
- }),
329
- {}
330
- );
331
- }
332
- return prop;
288
+ if (Array.isArray(prop)) return prop.map((item) => snakelizeKeys(item));
289
+ if (prop !== null && prop !== void 0 && prop.constructor === Object) return Object.keys(prop).reduce((accum, current) => ({
290
+ ...accum,
291
+ [snakeCase(current)]: snakelizeKeys(prop[current])
292
+ }), {});
293
+ return prop;
333
294
  }
334
-
335
- const LOCALE_RU = "ru-RU";
336
- const LOCALE_EN = "en-US";
295
+ //#endregion
296
+ //#region src/helpers/unformatNumber.ts
297
+ var LOCALE_RU = "ru-RU";
298
+ var LOCALE_EN = "en-US";
299
+ /**
300
+ * Принимает на вход число в виде строки или числа,
301
+ * возвращает корректное значение типа Number (убирает лишние пробелы и запятые)
302
+ * @example
303
+ * // returns 1000
304
+ * unformatNumber('1 000');
305
+ * @example
306
+ * // returns 1000
307
+ * unformatNumber('1,000')
308
+ * @example
309
+ * // returns 1000.123
310
+ * unformatNummber('1 000,123')
311
+ * @example
312
+ * // returns 1000.123
313
+ * unformatNummber('1,000.123')
314
+ * @param value
315
+ * @return number
316
+ */
337
317
  function unformatNumber(value) {
338
- if (!value || typeof value !== "string") return value;
339
- const string = value.trim();
340
- let locale;
341
- const spaceIndex = string.lastIndexOf(" ");
342
- const commaIndex = string.lastIndexOf(",");
343
- const dotIndex = string.lastIndexOf(".");
344
- const hasSpace = spaceIndex !== -1;
345
- const hasComma = commaIndex !== -1;
346
- const hasDot = dotIndex !== -1;
347
- const commasCount = (string.match(/,/g) || []).length;
348
- if (!Number.isNaN(Number(string))) return Number(string);
349
- if (hasSpace && hasComma && commaIndex > spaceIndex) locale = LOCALE_RU;
350
- if (hasSpace && !hasComma && !hasDot) locale = LOCALE_RU;
351
- if (hasComma && hasDot && dotIndex > commaIndex) locale = LOCALE_EN;
352
- if (hasComma && !hasSpace && !hasDot && commasCount > 1) locale = LOCALE_EN;
353
- if (commasCount === 1 && !hasSpace && !hasDot) {
354
- locale = string.length - 1 - commaIndex === 3 ? LOCALE_EN : LOCALE_RU;
355
- }
356
- if (locale === LOCALE_RU) {
357
- return Number(string.replaceAll(" ", "").replace(",", "."));
358
- }
359
- if (locale === LOCALE_EN) return Number(string.replaceAll(",", ""));
360
- return value;
318
+ if (!value || typeof value !== "string") return value;
319
+ const string = value.trim();
320
+ let locale;
321
+ const spaceIndex = string.lastIndexOf(" ");
322
+ const commaIndex = string.lastIndexOf(",");
323
+ const dotIndex = string.lastIndexOf(".");
324
+ const hasSpace = spaceIndex !== -1;
325
+ const hasComma = commaIndex !== -1;
326
+ const hasDot = dotIndex !== -1;
327
+ const commasCount = (string.match(/,/g) || []).length;
328
+ if (!Number.isNaN(Number(string))) return Number(string);
329
+ if (hasSpace && hasComma && commaIndex > spaceIndex) locale = LOCALE_RU;
330
+ if (hasSpace && !hasComma && !hasDot) locale = LOCALE_RU;
331
+ if (hasComma && hasDot && dotIndex > commaIndex) locale = LOCALE_EN;
332
+ if (hasComma && !hasSpace && !hasDot && commasCount > 1) locale = LOCALE_EN;
333
+ if (commasCount === 1 && !hasSpace && !hasDot) locale = string.length - 1 - commaIndex === 3 ? LOCALE_EN : LOCALE_RU;
334
+ if (locale === LOCALE_RU) return Number(string.replaceAll(" ", "").replace(",", "."));
335
+ if (locale === LOCALE_EN) return Number(string.replaceAll(",", ""));
336
+ return value;
361
337
  }
362
-
338
+ //#endregion
339
+ //#region src/helpers/uiComponentsResolver.ts
363
340
  function UiComponentsResolver(options = {}) {
364
- const { prefix = "" } = options;
365
- return (name) => {
366
- const componentName = prefix && name.startsWith(prefix) ? name.substring(prefix.length) : name;
367
- const isUiComponent = componentName.startsWith("Ui");
368
- if (isUiComponent) {
369
- return { name: componentName, from: "@karta.io/ui-components" };
370
- }
371
- };
341
+ const { prefix = "" } = options;
342
+ return (name) => {
343
+ const componentName = prefix && name.startsWith(prefix) ? name.substring(prefix.length) : name;
344
+ if (componentName.startsWith("Ui")) return {
345
+ name: componentName,
346
+ from: "@karta.io/ui-components"
347
+ };
348
+ };
372
349
  }
373
-
350
+ //#endregion
351
+ //#region src/hooks/useAbortController.ts
374
352
  function useAbortController(callback) {
375
- let controller = null;
376
- return {
377
- async call(...args) {
378
- if (controller) controller.abort();
379
- controller = new AbortController();
380
- let response;
381
- if (args.length > 0) {
382
- response = await callback(...args, {
383
- signal: controller.signal
384
- });
385
- } else {
386
- response = await callback({
387
- signal: controller.signal
388
- });
389
- }
390
- controller = null;
391
- return response;
392
- },
393
- abort() {
394
- if (!controller) return;
395
- controller.abort();
396
- controller = null;
397
- },
398
- isAborted(error) {
399
- return error.status === 418;
400
- }
401
- };
353
+ let controller = null;
354
+ return {
355
+ async call(...args) {
356
+ if (controller) controller.abort();
357
+ controller = new AbortController();
358
+ let response;
359
+ if (args.length > 0) response = await callback(...args, { signal: controller.signal });
360
+ else response = await callback({ signal: controller.signal });
361
+ controller = null;
362
+ return response;
363
+ },
364
+ abort() {
365
+ if (!controller) return;
366
+ controller.abort();
367
+ controller = null;
368
+ },
369
+ isAborted(error) {
370
+ return error.status === 418;
371
+ }
372
+ };
402
373
  }
403
-
404
- function useAsyncItems({
405
- apiMethod,
406
- queryKey,
407
- params,
408
- config = void 0
409
- }) {
410
- const getQueryKey = () => [queryKey, params];
411
- const { call, abort } = useAbortController(apiMethod);
412
- const { isLoading, isFetching, isError, data, error } = useQuery({
413
- queryKey: getQueryKey(),
414
- queryFn: () => call(toValue(params), config)
415
- });
416
- const items = computed(
417
- () => data.value?.results || []
418
- );
419
- const count = ref(0);
420
- watch(
421
- data,
422
- (newValue) => {
423
- if (newValue === void 0 || newValue.count === void 0) return;
424
- count.value = newValue.count;
425
- },
426
- { immediate: true }
427
- );
428
- const queryClient = useQueryClient();
429
- const refetch = () => {
430
- queryClient.invalidateQueries({ queryKey: getQueryKey() });
431
- };
432
- const reload = () => {
433
- queryClient.resetQueries({ queryKey: getQueryKey() });
434
- };
435
- return {
436
- isLoading,
437
- isFetching,
438
- isError,
439
- data,
440
- error,
441
- items,
442
- count,
443
- refetch,
444
- reload,
445
- abort
446
- };
374
+ //#endregion
375
+ //#region src/hooks/useAsyncItems.ts
376
+ function useAsyncItems({ apiMethod, queryKey, params, config = void 0 }) {
377
+ const getQueryKey = () => [queryKey, params];
378
+ const { call, abort } = useAbortController(apiMethod);
379
+ const { isLoading, isFetching, isError, data, error } = useQuery({
380
+ queryKey: getQueryKey(),
381
+ queryFn: () => call(toValue(params), config)
382
+ });
383
+ const items = computed(() => data.value?.results || []);
384
+ const count = ref(0);
385
+ watch(data, (newValue) => {
386
+ if (newValue === void 0 || newValue.count === void 0) return;
387
+ count.value = newValue.count;
388
+ }, { immediate: true });
389
+ const queryClient = useQueryClient();
390
+ const refetch = () => {
391
+ queryClient.invalidateQueries({ queryKey: getQueryKey() });
392
+ };
393
+ const reload = () => {
394
+ queryClient.resetQueries({ queryKey: getQueryKey() });
395
+ };
396
+ return {
397
+ isLoading,
398
+ isFetching,
399
+ isError,
400
+ data,
401
+ error,
402
+ items,
403
+ count,
404
+ refetch,
405
+ reload,
406
+ abort
407
+ };
447
408
  }
448
-
409
+ //#endregion
410
+ //#region src/hooks/useLogger.ts
411
+ /**
412
+ * @see https://github.com/caiogondim/logdown.js#readme
413
+ */
449
414
  function isEnabled(options) {
450
- if (options?.debug !== void 0) return options.debug;
451
- const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
452
- if (isBrowser) {
453
- const debug = localStorage.getItem("debug");
454
- if (debug === "true") return true;
455
- if (debug === "false") return false;
456
- }
457
- const isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
458
- if (isNode) {
459
- const debug = process.env.NODE_DEBUG;
460
- if (debug === "true") return true;
461
- if (debug === "false") return false;
462
- }
463
- return false;
415
+ if (options?.debug !== void 0) return options.debug;
416
+ if (typeof window !== "undefined" && typeof window.document !== "undefined") {
417
+ const debug = localStorage.getItem("debug");
418
+ if (debug === "true") return true;
419
+ if (debug === "false") return false;
420
+ }
421
+ if (typeof process !== "undefined" && process.versions != null && process.versions.node != null) {
422
+ const debug = process.env.NODE_DEBUG;
423
+ if (debug === "true") return true;
424
+ if (debug === "false") return false;
425
+ }
426
+ return false;
464
427
  }
465
428
  function useLogger(scope, options) {
466
- const prefix = options?.tag ? `[${scope.toUpperCase()}.${options.tag}]:` : `[${scope.toUpperCase()}]:`;
467
- const logger = logdown(prefix, { prefixColor: options?.color });
468
- logger.state.isEnabled = isEnabled(options);
469
- return logger;
429
+ const prefix = options?.tag ? `[${scope.toUpperCase()}.${options.tag}]:` : `[${scope.toUpperCase()}]:`;
430
+ const logger = logdown(prefix, { prefixColor: options?.color });
431
+ logger.state.isEnabled = isEnabled(options);
432
+ return logger;
470
433
  }
471
-
472
- function useAsyncMultiselect({
473
- apiMethod,
474
- mapOptionCallback = void 0,
475
- selectedValues = void 0,
476
- params = void 0,
477
- queryKey,
478
- dataItemsKey = "results",
479
- dataItemIdKey = "id",
480
- dataCountKey = "count",
481
- delay = 300,
482
- onUpdated = void 0
483
- }) {
484
- const logger = useLogger("UTILS", {
485
- tag: "useAsyncMultiselect",
486
- color: "#b54708",
487
- debug: true
488
- });
489
- const paramsForLogger = {
490
- queryKey,
491
- dataItemsKey,
492
- dataItemIdKey,
493
- dataCountKey
494
- };
495
- const reactiveData = reactive({
496
- search: "",
497
- page: 1,
498
- selectedValues: toValue(selectedValues),
499
- params: JSON.stringify(toValue(params))
500
- });
501
- const search = ref("");
502
- const { call, abort } = useAbortController(apiMethod);
503
- const loadWAC = () => {
504
- const includedIdsBySelectedValues = reactiveData.selectedValues ?? [];
505
- const includedIdsByParams = (Boolean(reactiveData.params) && JSON.parse(reactiveData.params || {})?.includedIds) ?? [];
506
- const includedIds = union(includedIdsBySelectedValues, includedIdsByParams);
507
- return call({
508
- page: reactiveData.page,
509
- search: reactiveData.search,
510
- ...reactiveData.params && { ...JSON.parse(reactiveData.params) },
511
- ...includedIds.length && { includedIds }
512
- });
513
- };
514
- const { data, isFetching, isLoading } = useQuery({
515
- queryKey: [queryKey, reactiveData],
516
- queryFn: loadWAC
517
- });
518
- const itemsByPages = ref(null);
519
- const count = ref(0);
520
- const selectedItemsCached = ref([]);
521
- watch(
522
- data,
523
- (newValue) => {
524
- if (!newValue) return;
525
- if (!has(newValue, dataItemsKey)) {
526
- logger.warn(
527
- `Unable to find key *"${dataItemsKey}"* (property "dataItemsKey") in data object from API.`,
528
- paramsForLogger
529
- );
530
- return;
531
- }
532
- if (!has(newValue, dataCountKey)) {
533
- logger.warn(
534
- `Unable to find key *"${dataCountKey}"* (property "dataCountKey") in data object from API.`,
535
- paramsForLogger
536
- );
537
- return;
538
- }
539
- if (!get(newValue, dataItemsKey) || get(newValue, dataCountKey) === void 0) {
540
- return;
541
- }
542
- count.value = get(newValue, dataCountKey, 0);
543
- const newItems = get(newValue, dataItemsKey);
544
- itemsByPages.value = {
545
- ...reactiveData.page !== 1 && itemsByPages.value,
546
- [reactiveData.page]: newItems
547
- };
548
- if (reactiveData.page === 1 && reactiveData.selectedValues?.length && !reactiveData.search) {
549
- if (newItems.some((item) => !has(item, dataItemIdKey))) {
550
- logger.warn(
551
- `Unable to find key *"${dataItemIdKey}"* (property "dataItemIdKey") in items from API.`,
552
- 'This key must be match with "optionValue" in UiMultiselect.',
553
- paramsForLogger
554
- );
555
- }
556
- selectedItemsCached.value = newItems.filter(
557
- (item) => reactiveData.selectedValues.includes(get(item, dataItemIdKey))
558
- );
559
- }
560
- onUpdated?.({
561
- search: reactiveData.search,
562
- page: reactiveData.page,
563
- selectedValues: reactiveData.selectedValues,
564
- params: reactiveData.params ? JSON.parse(reactiveData.params) : void 0
565
- });
566
- },
567
- { immediate: true }
568
- );
569
- const items = computed(() => {
570
- if (!itemsByPages.value) return selectedItemsCached.value;
571
- if (!Object.keys(itemsByPages.value).length) {
572
- return selectedItemsCached.value;
573
- }
574
- const itemsByPagesAsArray = Object.values(itemsByPages.value).reduce(
575
- (acc, item) => [...acc, ...item],
576
- []
577
- );
578
- const itemsAsArray = [...selectedItemsCached.value, ...itemsByPagesAsArray];
579
- const itemsAsMap = itemsAsArray.reduce((acc, item) => {
580
- const key = get(item, dataItemIdKey, JSON.stringify(item));
581
- return acc.set(key, item);
582
- }, /* @__PURE__ */ new Map());
583
- return [...itemsAsMap.values()];
584
- });
585
- const options = computed(() => {
586
- if (!items.value.length) return [];
587
- if (!mapOptionCallback) return items.value;
588
- return items.value.map(mapOptionCallback);
589
- });
590
- const hasNextPage = computed(() => count.value > items.value.length);
591
- const loadPage = (newPage = 1) => {
592
- reactiveData.page = newPage;
593
- if (newPage === 1) {
594
- reactiveData.selectedValues = toValue(selectedValues);
595
- }
596
- };
597
- const updateSearchWithDebounce = useDebounceFn((value) => {
598
- reactiveData.search = value;
599
- reactiveData.page = 1;
600
- reactiveData.selectedValues = toValue(selectedValues);
601
- }, delay);
602
- const updateSearch = (value) => {
603
- search.value = value;
604
- updateSearchWithDebounce(value);
605
- };
606
- const queryClient = useQueryClient();
607
- const refetch = () => {
608
- if (reactiveData.page !== 1) {
609
- queryClient.invalidateQueries({
610
- queryKey: [queryKey],
611
- refetchType: "none"
612
- });
613
- loadPage(1);
614
- } else {
615
- queryClient.invalidateQueries({
616
- queryKey: [queryKey]
617
- });
618
- }
619
- };
620
- const reload = () => {
621
- if (reactiveData.page !== 1) {
622
- queryClient.removeQueries({ queryKey: [queryKey] });
623
- loadPage(1);
624
- } else {
625
- queryClient.resetQueries({ queryKey: [queryKey] });
626
- }
627
- };
628
- if (isRef(selectedValues)) {
629
- watch(selectedValues, async (newSelectedValues) => {
630
- if (!newSelectedValues.length) {
631
- selectedItemsCached.value = [];
632
- } else {
633
- if (items.value.some((item) => !has(item, dataItemIdKey))) {
634
- logger.warn(
635
- `Unable to find key *"${dataItemIdKey}"* (property "dataItemIdKey") in items from API.`,
636
- 'This key must be match with "optionValue" in UiMultiselect.',
637
- paramsForLogger
638
- );
639
- }
640
- selectedItemsCached.value = items.value.filter(
641
- (item) => newSelectedValues.includes(get(item, dataItemIdKey))
642
- );
643
- }
644
- await nextTick();
645
- if (reactiveData.page === 1) {
646
- reactiveData.selectedValues = newSelectedValues;
647
- }
648
- });
649
- }
650
- if (isRef(params)) {
651
- watch(params, (newParams) => {
652
- reactiveData.page = 1;
653
- reactiveData.params = JSON.stringify(newParams);
654
- reactiveData.selectedValues = toValue(selectedValues);
655
- });
656
- }
657
- onBeforeUnmount(() => {
658
- abort?.();
659
- });
660
- return {
661
- items,
662
- options,
663
- search,
664
- hasNextPage,
665
- isFetching,
666
- isLoading,
667
- loadPage,
668
- updateSearch,
669
- refetch,
670
- reload
671
- };
434
+ //#endregion
435
+ //#region src/hooks/useAsyncMultiselect.ts
436
+ function useAsyncMultiselect({ apiMethod, mapOptionCallback = void 0, selectedValues = void 0, params = void 0, queryKey, dataItemsKey = "results", dataItemIdKey = "id", dataCountKey = "count", delay = 300, onUpdated = void 0 }) {
437
+ const logger = useLogger("UTILS", {
438
+ tag: "useAsyncMultiselect",
439
+ color: "#b54708",
440
+ debug: true
441
+ });
442
+ const paramsForLogger = {
443
+ queryKey,
444
+ dataItemsKey,
445
+ dataItemIdKey,
446
+ dataCountKey
447
+ };
448
+ /**
449
+ * Это объект прокидывается как доп данные для queryKey.
450
+ * Если сделать отдельные ref на search, page и тд, то возникают кейсы,
451
+ * когда нужно обновить одновременно несколько параметров (например selectedValues и page),
452
+ * чтобы не получить лишние запросы от vue-query.
453
+ */
454
+ const reactiveData = reactive({
455
+ search: "",
456
+ page: 1,
457
+ selectedValues: toValue(selectedValues),
458
+ params: JSON.stringify(toValue(params))
459
+ });
460
+ /**
461
+ * search в данном случае используется чисто как переменная для хранения актуального состояния
462
+ * А в асинхронную функцию уже передается reactiveData.search, который изменяется с задержкой
463
+ */
464
+ const search = ref("");
465
+ const { call, abort } = useAbortController(apiMethod);
466
+ const loadWAC = () => {
467
+ /**
468
+ * Добавил возможность добавлять в params includedIds
469
+ * для кейсов "выталкивания" наверх определенных пунктов
470
+ */
471
+ const includedIdsBySelectedValues = reactiveData.selectedValues ?? [];
472
+ const includedIdsByParams = (Boolean(reactiveData.params) && JSON.parse(reactiveData.params || {})?.includedIds) ?? [];
473
+ const includedIds = union(includedIdsBySelectedValues, includedIdsByParams);
474
+ return call({
475
+ page: reactiveData.page,
476
+ search: reactiveData.search,
477
+ ...reactiveData.params && { ...JSON.parse(reactiveData.params) },
478
+ ...includedIds.length && { includedIds }
479
+ });
480
+ };
481
+ const { data, isFetching, isLoading } = useQuery({
482
+ queryKey: [queryKey, reactiveData],
483
+ queryFn: loadWAC
484
+ });
485
+ const itemsByPages = ref(null);
486
+ const count = ref(0);
487
+ /**
488
+ * Сохраняем элементы, полученные из includedIds во внутреннюю память,
489
+ * чтобы корректно работать с кейсом, когда у нас активен поиск и есть selectedValues
490
+ */
491
+ const selectedItemsCached = ref([]);
492
+ watch(data, (newValue) => {
493
+ if (!newValue) return;
494
+ if (!has(newValue, dataItemsKey)) {
495
+ logger.warn(`Unable to find key *"${dataItemsKey}"* (property "dataItemsKey") in data object from API.`, paramsForLogger);
496
+ return;
497
+ }
498
+ if (!has(newValue, dataCountKey)) {
499
+ logger.warn(`Unable to find key *"${dataCountKey}"* (property "dataCountKey") in data object from API.`, paramsForLogger);
500
+ return;
501
+ }
502
+ if (!get(newValue, dataItemsKey) || get(newValue, dataCountKey) === void 0) return;
503
+ count.value = get(newValue, dataCountKey, 0);
504
+ const newItems = get(newValue, dataItemsKey);
505
+ /**
506
+ * Проверка на номер страницы очень важна:
507
+ *
508
+ * Если номер равен 1, то мы предполагаем,
509
+ * что изменилось одно из ключевых реактивных свойств (search, SelectedValue, params),
510
+ * а значит нам нужно полностью удалить все лишние данные для остальных страниц.
511
+ *
512
+ * Если номер больше 1, то мы лишь продолжаем формировать нашу "бесконечную" ленту - предыдущие данные остаются
513
+ */
514
+ itemsByPages.value = {
515
+ ...reactiveData.page !== 1 && itemsByPages.value,
516
+ [reactiveData.page]: newItems
517
+ };
518
+ if (reactiveData.page === 1 && reactiveData.selectedValues?.length && !reactiveData.search) {
519
+ if (newItems.some((item) => !has(item, dataItemIdKey))) logger.warn(`Unable to find key *"${dataItemIdKey}"* (property "dataItemIdKey") in items from API.`, "This key must be match with \"optionValue\" in UiMultiselect.", paramsForLogger);
520
+ selectedItemsCached.value = newItems.filter((item) => reactiveData.selectedValues.includes(get(item, dataItemIdKey)));
521
+ }
522
+ onUpdated?.({
523
+ search: reactiveData.search,
524
+ page: reactiveData.page,
525
+ selectedValues: reactiveData.selectedValues,
526
+ params: reactiveData.params ? JSON.parse(reactiveData.params) : void 0
527
+ });
528
+ }, { immediate: true });
529
+ const items = computed(() => {
530
+ if (!itemsByPages.value) return selectedItemsCached.value;
531
+ if (!Object.keys(itemsByPages.value).length) return selectedItemsCached.value;
532
+ const itemsByPagesAsArray = Object.values(itemsByPages.value).reduce((acc, item) => [...acc, ...item], []);
533
+ return [...[...selectedItemsCached.value, ...itemsByPagesAsArray].reduce((acc, item) => {
534
+ const key = get(item, dataItemIdKey, JSON.stringify(item));
535
+ return acc.set(key, item);
536
+ }, /* @__PURE__ */ new Map()).values()];
537
+ });
538
+ const options = computed(() => {
539
+ if (!items.value.length) return [];
540
+ if (!mapOptionCallback) return items.value;
541
+ return items.value.map(mapOptionCallback);
542
+ });
543
+ const hasNextPage = computed(() => count.value > items.value.length);
544
+ const loadPage = (newPage = 1) => {
545
+ reactiveData.page = newPage;
546
+ /**
547
+ * Изменение reactiveData генерирует новый запрос в API с за данными.
548
+ *
549
+ * Но нам нужно обрабатывать кейс с closeAfterSelect=true у UiMultiselect.
550
+ * В этом случае дропдаун не закрывается и, если добавляем новое значение
551
+ * на 3ей, 4ой и тд странице, то перезапрос данных обнулит пагинацию и начнет
552
+ * загружать все с 1ой страницы.
553
+ *
554
+ * Для обработки такого кейсы мы обновляем selectedValues в reactiveData только если:
555
+ * 1. Страница сброшена до 1ой
556
+ * 2. Изменилось значение поиска, а значит смотри пункт 1
557
+ * 3. Изменилось значение params, а значит смотри пункт 1
558
+ */
559
+ if (newPage === 1) reactiveData.selectedValues = toValue(selectedValues);
560
+ };
561
+ const updateSearchWithDebounce = useDebounceFn((value) => {
562
+ reactiveData.search = value;
563
+ reactiveData.page = 1;
564
+ reactiveData.selectedValues = toValue(selectedValues);
565
+ }, delay);
566
+ const updateSearch = (value) => {
567
+ search.value = value;
568
+ updateSearchWithDebounce(value);
569
+ };
570
+ const queryClient = useQueryClient();
571
+ const refetch = () => {
572
+ /**
573
+ * Такой кейс может быть полезен при обновлении value в UiMultiselect.
574
+ *
575
+ * Если страница не первая:
576
+ *
577
+ * Вначале помечаем все запросы по ключу устаревшими.
578
+ * refetchType: 'none' - предотвращает refetch по активному ключу.
579
+ * Это нужно для того, чтобы не запрашивать последнюю страницу.
580
+ *
581
+ * Переключаем страницу вручную - сразу происходит reFetch именно первой страницы.
582
+ *
583
+ * Если страница первая:
584
+ *
585
+ * Делаем обычный queryClient.invalidateQueries,
586
+ * функция сама сделает refetch.
587
+ *
588
+ * isLoading: false
589
+ * isFetching: true
590
+ */
591
+ if (reactiveData.page !== 1) {
592
+ queryClient.invalidateQueries({
593
+ queryKey: [queryKey],
594
+ refetchType: "none"
595
+ });
596
+ loadPage(1);
597
+ } else queryClient.invalidateQueries({ queryKey: [queryKey] });
598
+ };
599
+ const reload = () => {
600
+ /**
601
+ * Такой кейс может быть полезен при добавлении в UiMultiselect нового value.
602
+ *
603
+ * Если страница не первая:
604
+ *
605
+ * queryClient.resetQueries не имеет опции refetchType: 'none'
606
+ * и по умолчанию делает refetch последней активной страницы.
607
+ *
608
+ * Поэтому используем queryClient.removeQueries - он удаляет все запросы по ключу из кэша.
609
+ *
610
+ * Переключаем страницу вручную - сразу происходит fetch именно первой страницы.
611
+ *
612
+ * Если страница первая:
613
+ *
614
+ * Делаем обычный queryClient.resetQueries,
615
+ * функция сама сделает refetch.
616
+ *
617
+ * isLoading: true
618
+ * isFetching: true
619
+ */
620
+ if (reactiveData.page !== 1) {
621
+ queryClient.removeQueries({ queryKey: [queryKey] });
622
+ loadPage(1);
623
+ } else queryClient.resetQueries({ queryKey: [queryKey] });
624
+ };
625
+ if (isRef(selectedValues)) watch(selectedValues, async (newSelectedValues) => {
626
+ if (!newSelectedValues.length) selectedItemsCached.value = [];
627
+ else {
628
+ if (items.value.some((item) => !has(item, dataItemIdKey))) logger.warn(`Unable to find key *"${dataItemIdKey}"* (property "dataItemIdKey") in items from API.`, "This key must be match with \"optionValue\" in UiMultiselect.", paramsForLogger);
629
+ selectedItemsCached.value = items.value.filter((item) => newSelectedValues.includes(get(item, dataItemIdKey)));
630
+ }
631
+ await nextTick();
632
+ if (reactiveData.page === 1) reactiveData.selectedValues = newSelectedValues;
633
+ });
634
+ if (isRef(params)) watch(params, (newParams) => {
635
+ reactiveData.page = 1;
636
+ reactiveData.params = JSON.stringify(newParams);
637
+ reactiveData.selectedValues = toValue(selectedValues);
638
+ });
639
+ onBeforeUnmount(() => {
640
+ abort?.();
641
+ });
642
+ return {
643
+ items,
644
+ options,
645
+ search,
646
+ hasNextPage,
647
+ isFetching,
648
+ isLoading,
649
+ loadPage,
650
+ updateSearch,
651
+ refetch,
652
+ reload
653
+ };
672
654
  }
673
-
674
- function useAsyncSelect({
675
- apiMethod,
676
- mapOptionCallback = void 0,
677
- selectedValue = void 0,
678
- params = void 0,
679
- queryKey,
680
- dataItemsKey = "results",
681
- dataCountKey = "count",
682
- delay = 300,
683
- onUpdated = void 0
684
- }) {
685
- const logger = useLogger("UTILS", {
686
- tag: "useAsyncSelect",
687
- color: "#b54708",
688
- debug: true
689
- });
690
- const paramsForLogger = { queryKey, dataItemsKey, dataCountKey };
691
- const reactiveData = reactive({
692
- search: "",
693
- page: 1,
694
- selectedValue: toValue(selectedValue),
695
- params: JSON.stringify(toValue(params))
696
- });
697
- const search = ref("");
698
- const { call, abort } = useAbortController(apiMethod);
699
- const loadWAC = () => call({
700
- page: reactiveData.page,
701
- search: reactiveData.search,
702
- ...reactiveData.selectedValue && {
703
- includedIds: [reactiveData.selectedValue]
704
- },
705
- ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
706
- });
707
- const { data, isFetching, isLoading } = useQuery({
708
- queryKey: [queryKey, reactiveData],
709
- queryFn: loadWAC
710
- });
711
- const itemsByPages = ref(null);
712
- const count = ref(0);
713
- watch(
714
- data,
715
- (newValue) => {
716
- if (!newValue) return;
717
- if (!has(newValue, dataItemsKey)) {
718
- logger.warn(
719
- `Unable to find key *"${dataItemsKey}"* (property "dataItemsKey") in data object from API.`,
720
- paramsForLogger
721
- );
722
- return;
723
- }
724
- if (!has(newValue, dataCountKey)) {
725
- logger.warn(
726
- `Unable to find key *"${dataCountKey}"* (property "dataCountKey") in data object from API.`,
727
- paramsForLogger
728
- );
729
- return;
730
- }
731
- if (!get(newValue, dataItemsKey) || get(newValue, dataCountKey) === void 0) {
732
- return;
733
- }
734
- count.value = get(newValue, dataCountKey, 0);
735
- const newItems = get(newValue, dataItemsKey);
736
- itemsByPages.value = {
737
- ...reactiveData.page !== 1 && itemsByPages.value,
738
- [reactiveData.page]: newItems
739
- };
740
- onUpdated?.({
741
- search: reactiveData.search,
742
- page: reactiveData.page,
743
- selectedValue: reactiveData.selectedValue,
744
- params: reactiveData.params ? JSON.parse(reactiveData.params) : void 0
745
- });
746
- },
747
- { immediate: true }
748
- );
749
- const items = computed(() => {
750
- if (!itemsByPages.value) return [];
751
- if (!Object.keys(itemsByPages.value).length) return [];
752
- return Object.values(itemsByPages.value).reduce(
753
- (acc, item) => [...acc, ...item],
754
- []
755
- );
756
- });
757
- const options = computed(() => {
758
- if (!items.value.length) return [];
759
- if (!mapOptionCallback) return items.value;
760
- return items.value.map(mapOptionCallback);
761
- });
762
- const hasNextPage = computed(() => count.value > items.value.length);
763
- const loadPage = (newPage = 1) => {
764
- reactiveData.page = newPage;
765
- };
766
- const updateSearchWithDebounce = useDebounceFn((value) => {
767
- reactiveData.search = value;
768
- reactiveData.page = 1;
769
- }, delay);
770
- const updateSearch = (value) => {
771
- search.value = value;
772
- updateSearchWithDebounce(value);
773
- };
774
- const queryClient = useQueryClient();
775
- const refetch = () => {
776
- if (reactiveData.page !== 1) {
777
- queryClient.invalidateQueries({
778
- queryKey: [queryKey],
779
- refetchType: "none"
780
- });
781
- loadPage(1);
782
- } else {
783
- queryClient.invalidateQueries({
784
- queryKey: [queryKey]
785
- });
786
- }
787
- };
788
- const reload = () => {
789
- if (reactiveData.page !== 1) {
790
- queryClient.removeQueries({ queryKey: [queryKey] });
791
- loadPage(1);
792
- } else {
793
- queryClient.resetQueries({ queryKey: [queryKey] });
794
- }
795
- };
796
- if (isRef(selectedValue)) {
797
- watch(selectedValue, (newSelectedValue) => {
798
- reactiveData.page = 1;
799
- reactiveData.selectedValue = newSelectedValue;
800
- });
801
- }
802
- if (isRef(params)) {
803
- watch(params, (newParams) => {
804
- reactiveData.page = 1;
805
- reactiveData.params = JSON.stringify(newParams);
806
- });
807
- }
808
- onBeforeUnmount(() => {
809
- abort?.();
810
- });
811
- return {
812
- items,
813
- options,
814
- search,
815
- hasNextPage,
816
- isFetching,
817
- isLoading,
818
- loadPage,
819
- updateSearch,
820
- refetch,
821
- reload
822
- };
655
+ //#endregion
656
+ //#region src/hooks/useAsyncSelect.ts
657
+ function useAsyncSelect({ apiMethod, mapOptionCallback = void 0, selectedValue = void 0, params = void 0, queryKey, dataItemsKey = "results", dataCountKey = "count", delay = 300, onUpdated = void 0 }) {
658
+ const logger = useLogger("UTILS", {
659
+ tag: "useAsyncSelect",
660
+ color: "#b54708",
661
+ debug: true
662
+ });
663
+ const paramsForLogger = {
664
+ queryKey,
665
+ dataItemsKey,
666
+ dataCountKey
667
+ };
668
+ /**
669
+ * Это объект прокидывается как доп данные для queryKey.
670
+ * Если сделать отдельные ref на search, page и тд, то возникают кейсы,
671
+ * когда нужно обновить одновременно несколько параметров (например selectedValue и page),
672
+ * чтобы не получить лишние запросы от vue-query.
673
+ */
674
+ const reactiveData = reactive({
675
+ search: "",
676
+ page: 1,
677
+ selectedValue: toValue(selectedValue),
678
+ params: JSON.stringify(toValue(params))
679
+ });
680
+ /**
681
+ * search в данном случае используется чисто как переменная для хранения актуального состояния
682
+ * А в асинхронную функцию уже передается reactiveData.search, который изменяется с задержкой
683
+ */
684
+ const search = ref("");
685
+ const { call, abort } = useAbortController(apiMethod);
686
+ const loadWAC = () => call({
687
+ page: reactiveData.page,
688
+ search: reactiveData.search,
689
+ ...reactiveData.selectedValue && { includedIds: [reactiveData.selectedValue] },
690
+ ...reactiveData.params && { ...JSON.parse(reactiveData.params) }
691
+ });
692
+ const { data, isFetching, isLoading } = useQuery({
693
+ queryKey: [queryKey, reactiveData],
694
+ queryFn: loadWAC
695
+ });
696
+ const itemsByPages = ref(null);
697
+ const count = ref(0);
698
+ watch(data, (newValue) => {
699
+ if (!newValue) return;
700
+ if (!has(newValue, dataItemsKey)) {
701
+ logger.warn(`Unable to find key *"${dataItemsKey}"* (property "dataItemsKey") in data object from API.`, paramsForLogger);
702
+ return;
703
+ }
704
+ if (!has(newValue, dataCountKey)) {
705
+ logger.warn(`Unable to find key *"${dataCountKey}"* (property "dataCountKey") in data object from API.`, paramsForLogger);
706
+ return;
707
+ }
708
+ if (!get(newValue, dataItemsKey) || get(newValue, dataCountKey) === void 0) return;
709
+ count.value = get(newValue, dataCountKey, 0);
710
+ const newItems = get(newValue, dataItemsKey);
711
+ /**
712
+ * Проверка на номер страницы очень важна:
713
+ *
714
+ * Если номер равен 1, то мы предполагаем,
715
+ * что изменилось одно из ключевых реактивных свойств (search, SelectedValue, params),
716
+ * а значит нам нужно полностью удалить все лишние данные для остальных страниц.
717
+ *
718
+ * Если номер больше 1, то мы лишь продолжаем формировать нашу "бесконечную" ленту - предыдущие данные остаются
719
+ */
720
+ itemsByPages.value = {
721
+ ...reactiveData.page !== 1 && itemsByPages.value,
722
+ [reactiveData.page]: newItems
723
+ };
724
+ onUpdated?.({
725
+ search: reactiveData.search,
726
+ page: reactiveData.page,
727
+ selectedValue: reactiveData.selectedValue,
728
+ params: reactiveData.params ? JSON.parse(reactiveData.params) : void 0
729
+ });
730
+ }, { immediate: true });
731
+ const items = computed(() => {
732
+ if (!itemsByPages.value) return [];
733
+ if (!Object.keys(itemsByPages.value).length) return [];
734
+ return Object.values(itemsByPages.value).reduce((acc, item) => [...acc, ...item], []);
735
+ });
736
+ const options = computed(() => {
737
+ if (!items.value.length) return [];
738
+ if (!mapOptionCallback) return items.value;
739
+ return items.value.map(mapOptionCallback);
740
+ });
741
+ const hasNextPage = computed(() => count.value > items.value.length);
742
+ const loadPage = (newPage = 1) => {
743
+ reactiveData.page = newPage;
744
+ };
745
+ const updateSearchWithDebounce = useDebounceFn((value) => {
746
+ reactiveData.search = value;
747
+ reactiveData.page = 1;
748
+ }, delay);
749
+ const updateSearch = (value) => {
750
+ search.value = value;
751
+ updateSearchWithDebounce(value);
752
+ };
753
+ const queryClient = useQueryClient();
754
+ const refetch = () => {
755
+ /**
756
+ * Такой кейс может быть полезен при обновлении value в UiSelect.
757
+ *
758
+ * Если страница не первая:
759
+ *
760
+ * Вначале помечаем все запросы по ключу устаревшими.
761
+ * refetchType: 'none' - предотвращает refetch по активному ключу.
762
+ * Это нужно для того, чтобы не запрашивать последнюю страницу.
763
+ *
764
+ * Переключаем страницу вручную - сразу происходит reFetch именно первой страницы.
765
+ *
766
+ * Если страница первая:
767
+ *
768
+ * Делаем обычный queryClient.invalidateQueries,
769
+ * функция сама сделает refetch.
770
+ *
771
+ * isLoading: false
772
+ * isFetching: true
773
+ */
774
+ if (reactiveData.page !== 1) {
775
+ queryClient.invalidateQueries({
776
+ queryKey: [queryKey],
777
+ refetchType: "none"
778
+ });
779
+ loadPage(1);
780
+ } else queryClient.invalidateQueries({ queryKey: [queryKey] });
781
+ };
782
+ const reload = () => {
783
+ /**
784
+ * Такой кейс может быть полезен при добавлении в UiSelect нового value.
785
+ *
786
+ * Если страница не первая:
787
+ *
788
+ * queryClient.resetQueries не имеет опции refetchType: 'none'
789
+ * и по умолчанию делает refetch последней активной страницы.
790
+ *
791
+ * Поэтому используем queryClient.removeQueries - он удаляет все запросы по ключу из кэша.
792
+ *
793
+ * Переключаем страницу вручную - сразу происходит fetch именно первой страницы.
794
+ *
795
+ * Если страница первая:
796
+ *
797
+ * Делаем обычный queryClient.resetQueries,
798
+ * функция сама сделает refetch.
799
+ *
800
+ * isLoading: true
801
+ * isFetching: true
802
+ */
803
+ if (reactiveData.page !== 1) {
804
+ queryClient.removeQueries({ queryKey: [queryKey] });
805
+ loadPage(1);
806
+ } else queryClient.resetQueries({ queryKey: [queryKey] });
807
+ };
808
+ if (isRef(selectedValue)) watch(selectedValue, (newSelectedValue) => {
809
+ reactiveData.page = 1;
810
+ reactiveData.selectedValue = newSelectedValue;
811
+ });
812
+ if (isRef(params)) watch(params, (newParams) => {
813
+ reactiveData.page = 1;
814
+ reactiveData.params = JSON.stringify(newParams);
815
+ });
816
+ onBeforeUnmount(() => {
817
+ abort?.();
818
+ });
819
+ return {
820
+ items,
821
+ options,
822
+ search,
823
+ hasNextPage,
824
+ isFetching,
825
+ isLoading,
826
+ loadPage,
827
+ updateSearch,
828
+ refetch,
829
+ reload
830
+ };
823
831
  }
824
-
832
+ //#endregion
833
+ //#region src/hooks/useBreakpoint.ts
825
834
  function useBreakpoint() {
826
- const breakpoints = useBreakpoints(BREAKPOINTS);
827
- const isMobile = breakpoints.smaller("sm");
828
- const isDesktop = breakpoints.greaterOrEqual("md");
829
- const isGreaterXxs = breakpoints.greaterOrEqual("xxs");
830
- const isGreaterXs = breakpoints.greaterOrEqual("xs");
831
- const isGreaterSm = breakpoints.greaterOrEqual("sm");
832
- const isGreaterMd = breakpoints.greaterOrEqual("md");
833
- const isGreaterLg = breakpoints.greaterOrEqual("lg");
834
- const isGreaterXl = breakpoints.greaterOrEqual("xl");
835
- return {
836
- isMobile,
837
- isDesktop,
838
- isGreaterXxs,
839
- isGreaterXs,
840
- isGreaterSm,
841
- isGreaterMd,
842
- isGreaterLg,
843
- isGreaterXl
844
- };
835
+ const breakpoints = useBreakpoints(BREAKPOINTS);
836
+ return {
837
+ isMobile: breakpoints.smaller("sm"),
838
+ isDesktop: breakpoints.greaterOrEqual("md"),
839
+ isGreaterXxs: breakpoints.greaterOrEqual("xxs"),
840
+ isGreaterXs: breakpoints.greaterOrEqual("xs"),
841
+ isGreaterSm: breakpoints.greaterOrEqual("sm"),
842
+ isGreaterMd: breakpoints.greaterOrEqual("md"),
843
+ isGreaterLg: breakpoints.greaterOrEqual("lg"),
844
+ isGreaterXl: breakpoints.greaterOrEqual("xl")
845
+ };
845
846
  }
846
-
847
+ //#endregion
848
+ //#region src/hooks/useClassName.ts
847
849
  function _bem(block, blockSuffix, element, modifier, modifierValue) {
848
- let cls = block;
849
- if (blockSuffix) cls += `-${blockSuffix}`;
850
- if (element) cls += `__${element}`;
851
- if (modifier) cls += `_${modifier}`;
852
- if (modifierValue) cls += `_${modifierValue}`;
853
- return cls;
850
+ let cls = block;
851
+ if (blockSuffix) cls += `-${blockSuffix}`;
852
+ if (element) cls += `__${element}`;
853
+ if (modifier) cls += `_${modifier}`;
854
+ if (modifierValue) cls += `_${modifierValue}`;
855
+ return cls;
854
856
  }
855
857
  function useClassName(block) {
856
- const b = (blockSuffix = "") => _bem(block, blockSuffix, "", "", "");
857
- const e = (element) => element ? _bem(block, "", element, "", "") : "";
858
- const m = (modifier, condition = true) => modifier && condition ? _bem(block, "", "", modifier, "") : "";
859
- const em = (element, modifier, condition = true) => element && modifier && condition ? _bem(block, "", element, modifier, "") : "";
860
- const mv = (modifier, modifierValue, condition = true) => modifier && modifierValue && condition ? _bem(block, "", "", modifier, modifierValue) : "";
861
- const cssVar = (object) => {
862
- const styles = {};
863
- for (const key in object) styles[`--${block}-${key}`] = object[key];
864
- return styles;
865
- };
866
- const cssVarName = (name) => `--${block}-${name}`;
867
- return {
868
- b,
869
- e,
870
- m,
871
- em,
872
- mv,
873
- // CSS
874
- cssVar,
875
- cssVarName
876
- };
858
+ const b = (blockSuffix = "") => _bem(block, blockSuffix, "", "", "");
859
+ const e = (element) => element ? _bem(block, "", element, "", "") : "";
860
+ const m = (modifier, condition = true) => modifier && condition ? _bem(block, "", "", modifier, "") : "";
861
+ const em = (element, modifier, condition = true) => element && modifier && condition ? _bem(block, "", element, modifier, "") : "";
862
+ const mv = (modifier, modifierValue, condition = true) => modifier && modifierValue && condition ? _bem(block, "", "", modifier, modifierValue) : "";
863
+ const cssVar = (object) => {
864
+ const styles = {};
865
+ for (const key in object) styles[`--${block}-${key}`] = object[key];
866
+ return styles;
867
+ };
868
+ const cssVarName = (name) => `--${block}-${name}`;
869
+ return {
870
+ b,
871
+ e,
872
+ m,
873
+ em,
874
+ mv,
875
+ cssVar,
876
+ cssVarName
877
+ };
877
878
  }
878
-
879
+ //#endregion
880
+ //#region src/hooks/useDayjs.ts
879
881
  dayjs.extend(utc);
880
882
  dayjs.extend(tz);
881
883
  dayjs.extend(updateLocale);
882
884
  dayjs.extend(isToday);
883
885
  dayjs.extend(customParseFormat);
886
+ /**
887
+ * Обертка над dayjs, позволяющая задавать timezone
888
+ * @see https://day.js.org/en/
889
+ *
890
+ * Использовать параметр timezone нужно крайне аккуратно,
891
+ * может привести к утечкам памяти
892
+ * @todo Подумать как сделать оптимальнее
893
+ */
884
894
  function useDayjs(timezone) {
885
- dayjs.updateLocale("en", {
886
- weekStart: 1
887
- });
888
- if (!timezone) return dayjs;
889
- const dayjsExtended = (date, format, locale, strict) => dayjs(date, format, locale, strict).tz(timezone);
890
- return dayjsExtended;
895
+ dayjs.updateLocale("en", { weekStart: 1 });
896
+ if (!timezone) return dayjs;
897
+ const dayjsExtended = (date, format, locale, strict) => dayjs(date, format, locale, strict).tz(timezone);
898
+ return dayjsExtended;
891
899
  }
892
-
900
+ //#endregion
901
+ //#region src/hooks/useDetectBrowser.ts
893
902
  function parseVersion(version) {
894
- if (typeof version !== "string" && typeof version !== "number") {
895
- throw new TypeError(
896
- "Browser version must be type of string, number or negative boolean"
897
- );
898
- }
899
- const [major, minor = 0, patch = 0, build = 0] = typeof version === "string" ? version.split(".").map(Number) : [version];
900
- return {
901
- major,
902
- minor,
903
- patch,
904
- build
905
- };
903
+ if (typeof version !== "string" && typeof version !== "number") throw new TypeError("Browser version must be type of string, number or negative boolean");
904
+ const [major, minor = 0, patch = 0, build = 0] = typeof version === "string" ? version.split(".").map(Number) : [version];
905
+ return {
906
+ major,
907
+ minor,
908
+ patch,
909
+ build
910
+ };
906
911
  }
907
912
  function isVersionLower(minimum, target) {
908
- for (const k of ["major", "minor", "patch"]) {
909
- if (minimum[k] !== target[k]) return minimum[k] > target[k];
910
- }
911
- return minimum.build > target.build;
913
+ for (const k of [
914
+ "major",
915
+ "minor",
916
+ "patch"
917
+ ]) if (minimum[k] !== target[k]) return minimum[k] > target[k];
918
+ return minimum.build > target.build;
912
919
  }
913
920
  function useDetectBrowser(versions, userAgent) {
914
- const browserInfo = {};
915
- if (userAgent) {
916
- Object.assign(
917
- browserInfo,
918
- userAgent ? detect(userAgent) : {
919
- name: null,
920
- version: null,
921
- type: null,
922
- os: null
923
- }
924
- );
925
- } else {
926
- Object.assign(browserInfo, detect());
927
- }
928
- const rule = versions[browserInfo.name];
929
- return Object.freeze({
930
- isDeprecated: rule !== void 0 ? rule === false || isVersionLower(parseVersion(rule), parseVersion(browserInfo.version)) : false,
931
- ...browserInfo,
932
- options: Object.freeze(versions)
933
- });
921
+ const browserInfo = {};
922
+ if (userAgent) Object.assign(browserInfo, userAgent ? detect(userAgent) : {
923
+ name: null,
924
+ version: null,
925
+ type: null,
926
+ os: null
927
+ });
928
+ else Object.assign(browserInfo, detect());
929
+ const rule = versions[browserInfo.name];
930
+ return Object.freeze({
931
+ isDeprecated: rule !== void 0 ? rule === false || isVersionLower(parseVersion(rule), parseVersion(browserInfo.version)) : false,
932
+ ...browserInfo,
933
+ options: Object.freeze(versions)
934
+ });
934
935
  }
935
-
936
- const isLocked = ref(false);
936
+ //#endregion
937
+ //#region src/hooks/useGlobalScroll.ts
938
+ var isLocked = ref(false);
937
939
  function useGlobalScroll() {
938
- const lock = () => {
939
- isLocked.value = true;
940
- document.body.style.paddingRight = `${window.innerWidth - document.documentElement.clientWidth}px`;
941
- document.body.style.overflow = "hidden";
942
- };
943
- const unlock = () => {
944
- isLocked.value = false;
945
- document.body.style.overflow = "auto";
946
- document.body.style.paddingRight = "0px";
947
- };
948
- return {
949
- isLocked,
950
- lock,
951
- unlock
952
- };
940
+ const lock = () => {
941
+ isLocked.value = true;
942
+ document.body.style.paddingRight = `${window.innerWidth - document.documentElement.clientWidth}px`;
943
+ document.body.style.overflow = "hidden";
944
+ };
945
+ const unlock = () => {
946
+ isLocked.value = false;
947
+ document.body.style.overflow = "auto";
948
+ document.body.style.paddingRight = "0px";
949
+ };
950
+ return {
951
+ isLocked,
952
+ lock,
953
+ unlock
954
+ };
953
955
  }
954
-
955
- const CONFIRM_TEXT = "Are you sure you want to close? \nAll changes will be lost.";
956
- let dialogs = [];
957
- const HASH_PREFIX = "#ud_";
956
+ //#endregion
957
+ //#region src/hooks/useDialog.ts
958
+ var CONFIRM_TEXT = "Are you sure you want to close? \nAll changes will be lost.";
959
+ var dialogs = [];
960
+ var HASH_PREFIX = "#ud_";
958
961
  function useDialog(options) {
959
- const logger = useLogger("use-dialog");
960
- let hashPrefix = HASH_PREFIX;
961
- if (options?.hashPrefix) {
962
- if (options.hashPrefix.charAt(0) === "#") {
963
- hashPrefix = options?.hashPrefix;
964
- } else {
965
- logger.warn(
966
- `*hashPrefix* must start with "#". The default prefix "${HASH_PREFIX}" will be used`
967
- );
968
- }
969
- }
970
- let appContext;
971
- const {
972
- isLocked: isGlobalScrollLocked,
973
- lock: lockGlobalScroll,
974
- unlock: unlockGlobalScroll
975
- } = useGlobalScroll();
976
- const route = useRoute();
977
- const router = useRouter();
978
- const genHash = ({
979
- layer = 0,
980
- componentName,
981
- props
982
- }) => {
983
- const data = {
984
- name: componentName,
985
- layer,
986
- props
987
- };
988
- return `${hashPrefix}${window.btoa(JSON.stringify(data))}`;
989
- };
990
- const parseHash = (hash, componentName) => {
991
- if (!hash) return void 0;
992
- if (!hash.includes(hashPrefix)) return void 0;
993
- let dataFromHash;
994
- try {
995
- dataFromHash = JSON.parse(window.atob(hash.slice(hashPrefix.length)));
996
- } catch (_error) {
997
- logger.warn("*parseHash* cant parse hash");
998
- }
999
- if (typeof dataFromHash !== "object") return void 0;
1000
- if (!dataFromHash.name) {
1001
- logger.warn("*parseHash* cant find component name in hash");
1002
- return void 0;
1003
- }
1004
- if (dataFromHash.name !== componentName) return void 0;
1005
- return dataFromHash;
1006
- };
1007
- const clearHash = () => {
1008
- router.push({
1009
- name: route.name || void 0,
1010
- query: route.query,
1011
- hash: void 0
1012
- });
1013
- };
1014
- onMounted(() => {
1015
- appContext = getCurrentInstance()?.appContext;
1016
- });
1017
- const open = ({
1018
- layer = 0,
1019
- component,
1020
- props
1021
- }) => {
1022
- const uuid = genUUID();
1023
- const createComponent = () => {
1024
- const newProps = {
1025
- ...props,
1026
- layer
1027
- };
1028
- const el2 = document.createElement("div");
1029
- const vnode2 = createVNode(component, {
1030
- ...newProps,
1031
- modelValue: true,
1032
- uuid
1033
- });
1034
- vnode2.appContext = { ...appContext };
1035
- if (!vnode2?.props?.["onUpdate:modelValue"]) {
1036
- vnode2.props["onUpdate:modelValue"] = (value) => {
1037
- if (vnode2 && vnode2.component) {
1038
- vnode2.component.props.modelValue = value;
1039
- if (!value && route?.hash) {
1040
- const dataFromHash = parseHash(route.hash, component.name);
1041
- if (dataFromHash?.layer === layer) clearHash();
1042
- }
1043
- if (!value && (dialogs.length === 1 || layer === 0) && isGlobalScrollLocked.value) {
1044
- unlockGlobalScroll();
1045
- }
1046
- }
1047
- };
1048
- }
1049
- vnode2.close = () => {
1050
- if (!vnode2 || !vnode2.component) return;
1051
- vnode2.component.props.modelValue = false;
1052
- if (!route?.hash) return;
1053
- const dataFromHash = parseHash(route.hash, component.name);
1054
- if (dataFromHash?.layer === layer) clearHash();
1055
- };
1056
- vnode2.props.onDestroy = () => {
1057
- render(null, el2);
1058
- dialogs = dialogs.filter((dialog) => dialog.uuid !== uuid);
1059
- logger.info("Dialogs after destroy", dialogs);
1060
- };
1061
- const name = vnode2?.type?.name ?? "Unknown component";
1062
- const newDialog2 = {
1063
- uuid,
1064
- name,
1065
- vnode: vnode2,
1066
- layer
1067
- };
1068
- logger.log(`Open new dialog: "${name}"`);
1069
- if (!isGlobalScrollLocked.value) {
1070
- lockGlobalScroll();
1071
- }
1072
- return {
1073
- vnode: vnode2,
1074
- el: el2,
1075
- newDialog: newDialog2
1076
- };
1077
- };
1078
- if (!dialogs.length) {
1079
- const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
1080
- render(vnode2, el2);
1081
- dialogs = [newDialog2];
1082
- logger.info("Dialogs after open", dialogs);
1083
- return uuid;
1084
- }
1085
- if (layer === 0) {
1086
- closeAll();
1087
- const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
1088
- render(vnode2, el2);
1089
- dialogs = [newDialog2];
1090
- logger.info("Dialogs after open", dialogs);
1091
- return uuid;
1092
- }
1093
- if (!dialogs.some((dialog) => dialog.layer === layer)) {
1094
- const { vnode: vnode2, el: el2, newDialog: newDialog2 } = createComponent();
1095
- render(vnode2, el2);
1096
- dialogs = [...dialogs, newDialog2];
1097
- logger.info("Dialogs after open", dialogs);
1098
- return uuid;
1099
- }
1100
- const dialogOnCurrentLayer = dialogs.find((dialog) => dialog.layer === layer);
1101
- close(dialogOnCurrentLayer?.uuid || "");
1102
- const { vnode, el, newDialog } = createComponent();
1103
- render(vnode, el);
1104
- dialogs = [...dialogs, newDialog];
1105
- logger.info("Dialogs after open", dialogs);
1106
- return uuid;
1107
- };
1108
- const close = (uuid) => {
1109
- const dialog = dialogs.find((item) => item.uuid === uuid);
1110
- logger.log(`Close dialog: "${uuid}"`);
1111
- if ((dialogs.length === 1 || dialog.layer === 0) && isGlobalScrollLocked.value) {
1112
- unlockGlobalScroll();
1113
- }
1114
- dialog?.vnode.close();
1115
- };
1116
- const closeAll = () => {
1117
- dialogs.forEach((dialog) => {
1118
- dialog?.vnode.close();
1119
- });
1120
- if (isGlobalScrollLocked.value) {
1121
- unlockGlobalScroll();
1122
- }
1123
- };
1124
- const getInstance = (uuid) => {
1125
- return dialogs.find((item) => item.uuid === uuid)?.vnode;
1126
- };
1127
- const getLayer = (uuid) => {
1128
- if (!dialogs.length) return 0;
1129
- return dialogs.find((dialog) => dialog.uuid === uuid)?.layer || 0;
1130
- };
1131
- const isOnTop = (uuid) => {
1132
- if (!dialogs.length) return false;
1133
- const dialogsSorted = [...dialogs].sort((a, b) => b.layer - a.layer);
1134
- return dialogsSorted[0].uuid === uuid;
1135
- };
1136
- const showConfirm = (text = CONFIRM_TEXT) => {
1137
- return window.confirm(text);
1138
- };
1139
- const openByHash = ({
1140
- layer = 0,
1141
- component,
1142
- props
1143
- }) => {
1144
- router.push({
1145
- name: route.name || void 0,
1146
- query: route.query,
1147
- hash: genHash({ layer, props, componentName: component.name })
1148
- });
1149
- };
1150
- const watchHash = ({
1151
- component,
1152
- events
1153
- }) => {
1154
- logger.info(`start watching route.hash for dialog *${component.name}*`);
1155
- const stopWatch = watch(
1156
- () => route.hash,
1157
- async (newHash) => {
1158
- if (!newHash) {
1159
- if (!dialogs.length) return;
1160
- closeAll();
1161
- return;
1162
- }
1163
- const dataFromHash = parseHash(newHash, component.name);
1164
- if (!dataFromHash) return;
1165
- logger.info("*watchHash* data from hash", dataFromHash);
1166
- await nextTick();
1167
- open({
1168
- component,
1169
- layer: dataFromHash.layer || 0,
1170
- props: {
1171
- ...dataFromHash.props,
1172
- ...events
1173
- }
1174
- });
1175
- },
1176
- { immediate: true }
1177
- );
1178
- const stopWatchHash = () => {
1179
- logger.info(`stop watching route.hash for dialog *${component.name}*`);
1180
- stopWatch();
1181
- };
1182
- onBeforeUnmount(() => {
1183
- stopWatchHash();
1184
- });
1185
- return stopWatchHash;
1186
- };
1187
- return {
1188
- open,
1189
- getInstance,
1190
- getLayer,
1191
- close,
1192
- closeAll,
1193
- showConfirm,
1194
- isOnTop,
1195
- genHash,
1196
- parseHash,
1197
- clearHash,
1198
- openByHash,
1199
- watchHash
1200
- };
962
+ const logger = useLogger("use-dialog");
963
+ let hashPrefix = HASH_PREFIX;
964
+ if (options?.hashPrefix) if (options.hashPrefix.charAt(0) === "#") hashPrefix = options?.hashPrefix;
965
+ else logger.warn(`*hashPrefix* must start with "#". The default prefix "${HASH_PREFIX}" will be used`);
966
+ let appContext;
967
+ const { isLocked: isGlobalScrollLocked, lock: lockGlobalScroll, unlock: unlockGlobalScroll } = useGlobalScroll();
968
+ const route = useRoute();
969
+ const router = useRouter();
970
+ const genHash = ({ layer = 0, componentName, props }) => {
971
+ const data = {
972
+ name: componentName,
973
+ layer,
974
+ props
975
+ };
976
+ return `${hashPrefix}${window.btoa(JSON.stringify(data))}`;
977
+ };
978
+ const parseHash = (hash, componentName) => {
979
+ if (!hash) return void 0;
980
+ if (!hash.includes(hashPrefix)) return void 0;
981
+ let dataFromHash;
982
+ try {
983
+ dataFromHash = JSON.parse(window.atob(hash.slice(hashPrefix.length)));
984
+ } catch (_error) {
985
+ logger.warn("*parseHash* cant parse hash");
986
+ }
987
+ if (typeof dataFromHash !== "object") return void 0;
988
+ if (!dataFromHash.name) {
989
+ logger.warn("*parseHash* cant find component name in hash");
990
+ return;
991
+ }
992
+ if (dataFromHash.name !== componentName) return void 0;
993
+ return dataFromHash;
994
+ };
995
+ const clearHash = () => {
996
+ router.push({
997
+ name: route.name || void 0,
998
+ query: route.query,
999
+ hash: void 0
1000
+ });
1001
+ };
1002
+ onMounted(() => {
1003
+ appContext = getCurrentInstance()?.appContext;
1004
+ });
1005
+ const open = ({ layer = 0, component, props }) => {
1006
+ const uuid = genUUID();
1007
+ const createComponent = () => {
1008
+ const newProps = {
1009
+ ...props,
1010
+ layer
1011
+ };
1012
+ const el = document.createElement("div");
1013
+ const vnode = createVNode(component, {
1014
+ ...newProps,
1015
+ modelValue: true,
1016
+ uuid
1017
+ });
1018
+ vnode.appContext = { ...appContext };
1019
+ /**
1020
+ * Если у компонента не объявлен свой обработчик на onUpdate:modelValue,
1021
+ * то создаем его самостоятельно
1022
+ *
1023
+ * Например:
1024
+ * openDialog({
1025
+ * component: SomeDialog,
1026
+ * })
1027
+ *
1028
+ * Если же его явно объявили, то никаких костылей не нужно
1029
+ *
1030
+ * Пример кода когда диалог открывается и закрывается по хешу в роутере
1031
+ * openDialog({
1032
+ * component: SomeDialog,
1033
+ * props: {
1034
+ * 'onUpdate:modelValue': (value: boolean) => {
1035
+ if (value) return;
1036
+ router.push({ hash: undefined });
1037
+ },
1038
+ * },
1039
+ * })
1040
+ */
1041
+ if (!vnode?.props?.["onUpdate:modelValue"]) vnode.props["onUpdate:modelValue"] = (value) => {
1042
+ if (vnode && vnode.component) {
1043
+ vnode.component.props.modelValue = value;
1044
+ if (!value && route?.hash) {
1045
+ if (parseHash(route.hash, component.name)?.layer === layer) clearHash();
1046
+ }
1047
+ if (!value && (dialogs.length === 1 || layer === 0) && isGlobalScrollLocked.value) unlockGlobalScroll();
1048
+ }
1049
+ };
1050
+ vnode.close = () => {
1051
+ if (!vnode || !vnode.component) return;
1052
+ vnode.component.props.modelValue = false;
1053
+ if (!route?.hash) return;
1054
+ if (parseHash(route.hash, component.name)?.layer === layer) clearHash();
1055
+ };
1056
+ vnode.props.onDestroy = () => {
1057
+ render(null, el);
1058
+ dialogs = dialogs.filter((dialog) => dialog.uuid !== uuid);
1059
+ logger.info("Dialogs after destroy", dialogs);
1060
+ };
1061
+ const name = vnode?.type?.name ?? "Unknown component";
1062
+ const newDialog = {
1063
+ uuid,
1064
+ name,
1065
+ vnode,
1066
+ layer
1067
+ };
1068
+ logger.log(`Open new dialog: "${name}"`);
1069
+ if (!isGlobalScrollLocked.value) lockGlobalScroll();
1070
+ return {
1071
+ vnode,
1072
+ el,
1073
+ newDialog
1074
+ };
1075
+ };
1076
+ /**
1077
+ * Если нет диалогов, то просто открываем новый
1078
+ */
1079
+ if (!dialogs.length) {
1080
+ const { vnode, el, newDialog } = createComponent();
1081
+ render(vnode, el);
1082
+ dialogs = [newDialog];
1083
+ logger.info("Dialogs after open", dialogs);
1084
+ return uuid;
1085
+ }
1086
+ /**
1087
+ * Если открываем новый диалог с нулевым слоем,
1088
+ * то все другие диалоги надо закрыть
1089
+ */
1090
+ if (layer === 0) {
1091
+ closeAll();
1092
+ const { vnode, el, newDialog } = createComponent();
1093
+ render(vnode, el);
1094
+ dialogs = [newDialog];
1095
+ logger.info("Dialogs after open", dialogs);
1096
+ return uuid;
1097
+ }
1098
+ /**
1099
+ * Если мы пытаемся открыть диалог со слоем отличным от 0,
1100
+ * то нужно проверить наличие уже открытого диалога на этом слое.
1101
+ * Если диалога нет, то просто пушим в массив новый элемент
1102
+ * Если диалог есть, то через таймаут подменяем его
1103
+ */
1104
+ if (!dialogs.some((dialog) => dialog.layer === layer)) {
1105
+ const { vnode, el, newDialog } = createComponent();
1106
+ render(vnode, el);
1107
+ dialogs = [...dialogs, newDialog];
1108
+ logger.info("Dialogs after open", dialogs);
1109
+ return uuid;
1110
+ }
1111
+ const dialogOnCurrentLayer = dialogs.find((dialog) => dialog.layer === layer);
1112
+ close(dialogOnCurrentLayer?.uuid || "");
1113
+ const { vnode, el, newDialog } = createComponent();
1114
+ render(vnode, el);
1115
+ dialogs = [...dialogs, newDialog];
1116
+ logger.info("Dialogs after open", dialogs);
1117
+ return uuid;
1118
+ };
1119
+ const close = (uuid) => {
1120
+ const dialog = dialogs.find((item) => item.uuid === uuid);
1121
+ logger.log(`Close dialog: "${uuid}"`);
1122
+ if ((dialogs.length === 1 || dialog.layer === 0) && isGlobalScrollLocked.value) unlockGlobalScroll();
1123
+ dialog?.vnode.close();
1124
+ };
1125
+ const closeAll = () => {
1126
+ dialogs.forEach((dialog) => {
1127
+ dialog?.vnode.close();
1128
+ });
1129
+ if (isGlobalScrollLocked.value) unlockGlobalScroll();
1130
+ };
1131
+ const getInstance = (uuid) => {
1132
+ return dialogs.find((item) => item.uuid === uuid)?.vnode;
1133
+ };
1134
+ const getLayer = (uuid) => {
1135
+ if (!dialogs.length) return 0;
1136
+ return dialogs.find((dialog) => dialog.uuid === uuid)?.layer || 0;
1137
+ };
1138
+ const isOnTop = (uuid) => {
1139
+ if (!dialogs.length) return false;
1140
+ return [...dialogs].sort((a, b) => b.layer - a.layer)[0].uuid === uuid;
1141
+ };
1142
+ const showConfirm = (text = CONFIRM_TEXT) => {
1143
+ return window.confirm(text);
1144
+ };
1145
+ /**
1146
+ * Открытие диалога через hash
1147
+ *
1148
+ * Метод openByHash только дергает router и прокидывает в hash все необходимые данные.
1149
+ * Для полноценной работы на конкретной странице необходимо
1150
+ * для этого же компонента подключить watchHash
1151
+ */
1152
+ const openByHash = ({ layer = 0, component, props }) => {
1153
+ router.push({
1154
+ name: route.name || void 0,
1155
+ query: route.query,
1156
+ hash: genHash({
1157
+ layer,
1158
+ props,
1159
+ componentName: component.name
1160
+ })
1161
+ });
1162
+ };
1163
+ const watchHash = ({ component, events }) => {
1164
+ logger.info(`start watching route.hash for dialog *${component.name}*`);
1165
+ const stopWatch = watch(() => route.hash, async (newHash) => {
1166
+ if (!newHash) {
1167
+ if (!dialogs.length) return;
1168
+ closeAll();
1169
+ return;
1170
+ }
1171
+ const dataFromHash = parseHash(newHash, component.name);
1172
+ if (!dataFromHash) return;
1173
+ logger.info("*watchHash* data from hash", dataFromHash);
1174
+ await nextTick();
1175
+ open({
1176
+ component,
1177
+ layer: dataFromHash.layer || 0,
1178
+ props: {
1179
+ ...dataFromHash.props,
1180
+ ...events
1181
+ }
1182
+ });
1183
+ }, { immediate: true });
1184
+ const stopWatchHash = () => {
1185
+ logger.info(`stop watching route.hash for dialog *${component.name}*`);
1186
+ stopWatch();
1187
+ };
1188
+ onBeforeUnmount(() => {
1189
+ stopWatchHash();
1190
+ });
1191
+ return stopWatchHash;
1192
+ };
1193
+ return {
1194
+ open,
1195
+ getInstance,
1196
+ getLayer,
1197
+ close,
1198
+ closeAll,
1199
+ showConfirm,
1200
+ isOnTop,
1201
+ genHash,
1202
+ parseHash,
1203
+ clearHash,
1204
+ openByHash,
1205
+ watchHash
1206
+ };
1201
1207
  }
1202
-
1203
- const QS_STRINGIFY_PARAMS = {
1204
- arrayFormat: "comma",
1205
- encode: false,
1206
- skipNulls: true,
1207
- addQueryPrefix: true
1208
+ //#endregion
1209
+ //#region src/hooks/useFilters.ts
1210
+ var QS_STRINGIFY_PARAMS = {
1211
+ arrayFormat: "comma",
1212
+ encode: false,
1213
+ skipNulls: true,
1214
+ addQueryPrefix: true
1208
1215
  };
1209
- const isOpen = ref(false);
1216
+ var isOpen = ref(false);
1210
1217
  function useFilters({ config, initialFilters }) {
1211
- const router = useRouter();
1212
- const route = useRoute();
1213
- const parseRouteQuery = (query) => qs.parse(query ?? route.query);
1214
- const filtersFromQuery = computed(() => {
1215
- const parsedRouteQuery = parseRouteQuery();
1216
- if (!parsedRouteQuery.filters) return void 0;
1217
- return Object.entries(config).reduce(
1218
- (accum, [currentKey, currentValue]) => {
1219
- if (!parsedRouteQuery.filters[currentKey]) return accum;
1220
- if (currentValue.type === "ARRAY" /* Array */) {
1221
- const splitValues = parsedRouteQuery.filters[currentKey].split(",");
1222
- const checkedValue = currentValue?.possibleValues ? splitValues.filter(
1223
- (k) => currentValue?.possibleValues?.includes(k)
1224
- ) : splitValues;
1225
- if (!checkedValue?.length) return accum;
1226
- return {
1227
- ...accum,
1228
- [currentKey]: checkedValue
1229
- };
1230
- }
1231
- return {
1232
- ...accum,
1233
- [currentKey]: parsedRouteQuery.filters[currentKey]
1234
- };
1235
- },
1236
- {}
1237
- );
1238
- });
1239
- const filtersCount = computed(
1240
- () => filtersFromQuery.value ? Object.keys(filtersFromQuery.value).length : 0
1241
- );
1242
- const setQueryFromFilters = (filters) => {
1243
- const parsedRouteQuery = parseRouteQuery();
1244
- const filteredValue = Object.entries(filters).reduce(
1245
- (accum, [currentKey, currentValue]) => {
1246
- if (!currentValue?.length) return accum;
1247
- return { ...accum, [currentKey]: currentValue };
1248
- },
1249
- {}
1250
- );
1251
- const query = qs.stringify(
1252
- {
1253
- ...parsedRouteQuery,
1254
- filters: filteredValue,
1255
- page: void 0
1256
- },
1257
- QS_STRINGIFY_PARAMS
1258
- );
1259
- router.push(query.replaceAll("#", ""));
1260
- };
1261
- const getValidatedParams = (query) => {
1262
- const parsedRouteQuery = parseRouteQuery(query);
1263
- if (query?.filters) {
1264
- const filters = {
1265
- ...query.filters,
1266
- ...filtersFromQuery.value
1267
- };
1268
- return { ...parsedRouteQuery, filters };
1269
- }
1270
- return { ...parsedRouteQuery, filters: filtersFromQuery.value };
1271
- };
1272
- const open = () => {
1273
- isOpen.value = true;
1274
- };
1275
- const clear = () => setQueryFromFilters({});
1276
- const filtersModel = ref({
1277
- ...initialFilters,
1278
- ...filtersFromQuery.value
1279
- });
1280
- const updateOne = (key, value) => {
1281
- setQueryFromFilters({
1282
- ...filtersModel.value,
1283
- [key]: value ? String(value) : void 0
1284
- });
1285
- };
1286
- const updateMany = (filters) => {
1287
- const newFilters = Object.entries(filters).reduce(
1288
- (accum, [currentKey, currentValue]) => {
1289
- return {
1290
- ...accum,
1291
- [currentKey]: currentValue ? String(currentValue) : void 0
1292
- };
1293
- },
1294
- {}
1295
- );
1296
- setQueryFromFilters({
1297
- ...filtersModel.value,
1298
- ...newFilters
1299
- });
1300
- };
1301
- watch(filtersFromQuery, (newFilters) => {
1302
- if (!newFilters) {
1303
- filtersModel.value = { ...initialFilters };
1304
- return;
1305
- }
1306
- filtersModel.value = { ...initialFilters, ...newFilters };
1307
- });
1308
- return {
1309
- isOpen,
1310
- filtersModel,
1311
- filtersFromQuery,
1312
- filtersCount,
1313
- updateOne,
1314
- updateMany,
1315
- open,
1316
- clear,
1317
- setQueryFromFilters,
1318
- getValidatedParams
1319
- };
1218
+ const router = useRouter();
1219
+ const route = useRoute();
1220
+ const parseRouteQuery = (query) => qs.parse(query ?? route.query);
1221
+ const filtersFromQuery = computed(() => {
1222
+ const parsedRouteQuery = parseRouteQuery();
1223
+ if (!parsedRouteQuery.filters) return void 0;
1224
+ return Object.entries(config).reduce((accum, [currentKey, currentValue]) => {
1225
+ if (!parsedRouteQuery.filters[currentKey]) return accum;
1226
+ if (currentValue.type === "ARRAY") {
1227
+ const splitValues = parsedRouteQuery.filters[currentKey].split(",");
1228
+ const checkedValue = currentValue?.possibleValues ? splitValues.filter((k) => currentValue?.possibleValues?.includes(k)) : splitValues;
1229
+ if (!checkedValue?.length) return accum;
1230
+ return {
1231
+ ...accum,
1232
+ [currentKey]: checkedValue
1233
+ };
1234
+ }
1235
+ return {
1236
+ ...accum,
1237
+ [currentKey]: parsedRouteQuery.filters[currentKey]
1238
+ };
1239
+ }, {});
1240
+ });
1241
+ const filtersCount = computed(() => filtersFromQuery.value ? Object.keys(filtersFromQuery.value).length : 0);
1242
+ const setQueryFromFilters = (filters) => {
1243
+ const parsedRouteQuery = parseRouteQuery();
1244
+ const filteredValue = Object.entries(filters).reduce((accum, [currentKey, currentValue]) => {
1245
+ if (!currentValue?.length) return accum;
1246
+ return {
1247
+ ...accum,
1248
+ [currentKey]: currentValue
1249
+ };
1250
+ }, {});
1251
+ const query = qs.stringify({
1252
+ ...parsedRouteQuery,
1253
+ filters: filteredValue,
1254
+ page: void 0
1255
+ }, QS_STRINGIFY_PARAMS);
1256
+ /**
1257
+ * Очищаем символ # из строки, чтобы роутер не воспринимал часть за данных за этим символом как хеш
1258
+ */
1259
+ router.push(query.replaceAll("#", ""));
1260
+ };
1261
+ const getValidatedParams = (query) => {
1262
+ const parsedRouteQuery = parseRouteQuery(query);
1263
+ if (query?.filters) {
1264
+ const filters = {
1265
+ ...query.filters,
1266
+ ...filtersFromQuery.value
1267
+ };
1268
+ return {
1269
+ ...parsedRouteQuery,
1270
+ filters
1271
+ };
1272
+ }
1273
+ return {
1274
+ ...parsedRouteQuery,
1275
+ filters: filtersFromQuery.value
1276
+ };
1277
+ };
1278
+ const open = () => {
1279
+ isOpen.value = true;
1280
+ };
1281
+ const clear = () => setQueryFromFilters({});
1282
+ const filtersModel = ref({
1283
+ ...initialFilters,
1284
+ ...filtersFromQuery.value
1285
+ });
1286
+ const updateOne = (key, value) => {
1287
+ setQueryFromFilters({
1288
+ ...filtersModel.value,
1289
+ [key]: value ? String(value) : void 0
1290
+ });
1291
+ };
1292
+ const updateMany = (filters) => {
1293
+ const newFilters = Object.entries(filters).reduce((accum, [currentKey, currentValue]) => {
1294
+ return {
1295
+ ...accum,
1296
+ [currentKey]: currentValue ? String(currentValue) : void 0
1297
+ };
1298
+ }, {});
1299
+ setQueryFromFilters({
1300
+ ...filtersModel.value,
1301
+ ...newFilters
1302
+ });
1303
+ };
1304
+ watch(filtersFromQuery, (newFilters) => {
1305
+ if (!newFilters) {
1306
+ filtersModel.value = { ...initialFilters };
1307
+ return;
1308
+ }
1309
+ filtersModel.value = {
1310
+ ...initialFilters,
1311
+ ...newFilters
1312
+ };
1313
+ });
1314
+ return {
1315
+ isOpen,
1316
+ filtersModel,
1317
+ filtersFromQuery,
1318
+ filtersCount,
1319
+ updateOne,
1320
+ updateMany,
1321
+ open,
1322
+ clear,
1323
+ setQueryFromFilters,
1324
+ getValidatedParams
1325
+ };
1320
1326
  }
1321
-
1322
- let panels = [];
1327
+ //#endregion
1328
+ //#region src/hooks/usePanel.ts
1329
+ var panels = [];
1330
+ /**
1331
+ * @deprecated use useDialog
1332
+ */
1323
1333
  function usePanel() {
1324
- let appContext;
1325
- const logger = useLogger("use-panel");
1326
- const {
1327
- isLocked: isGlobalScrollLocked,
1328
- lock: lockGlobalScroll,
1329
- unlock: unlockGlobalScroll
1330
- } = useGlobalScroll();
1331
- const route = useRoute();
1332
- const router = useRouter();
1333
- onMounted(() => {
1334
- appContext = getCurrentInstance()?.appContext;
1335
- });
1336
- const open = ({
1337
- layer = 0,
1338
- component,
1339
- props
1340
- }) => {
1341
- const uuid = genUUID();
1342
- const createComponent = () => {
1343
- const newProps = {
1344
- ...props,
1345
- layer
1346
- };
1347
- const el2 = document.createElement("div");
1348
- const vnode2 = createVNode(component, {
1349
- ...newProps,
1350
- modelValue: true,
1351
- uuid
1352
- });
1353
- vnode2.appContext = { ...appContext };
1354
- if (!vnode2?.props?.["onUpdate:modelValue"]) {
1355
- vnode2.props["onUpdate:modelValue"] = (value) => {
1356
- if (vnode2 && vnode2.component) {
1357
- vnode2.component.props.modelValue = value;
1358
- if (!value && panels.length === 1 && isGlobalScrollLocked.value) {
1359
- unlockGlobalScroll();
1360
- }
1361
- }
1362
- };
1363
- }
1364
- vnode2.close = () => {
1365
- if (vnode2 && vnode2.component) {
1366
- vnode2.component.props.modelValue = false;
1367
- }
1368
- };
1369
- vnode2.props.onDestroy = () => {
1370
- render(null, el2);
1371
- panels = panels.filter((panel) => panel.uuid !== uuid);
1372
- logger.info("Panels after destroy", panels);
1373
- };
1374
- const name = vnode2?.type?.name ?? "Unknown component";
1375
- const newPanel2 = {
1376
- uuid,
1377
- name,
1378
- vnode: vnode2,
1379
- layer
1380
- };
1381
- logger.log(`Open new panel: "${name}"`);
1382
- if (!isGlobalScrollLocked.value) {
1383
- lockGlobalScroll();
1384
- }
1385
- return {
1386
- vnode: vnode2,
1387
- el: el2,
1388
- newPanel: newPanel2
1389
- };
1390
- };
1391
- if (!panels.length) {
1392
- const { vnode: vnode2, el: el2, newPanel: newPanel2 } = createComponent();
1393
- render(vnode2, el2);
1394
- panels = [newPanel2];
1395
- logger.info("Panels after open", panels);
1396
- return uuid;
1397
- }
1398
- if (layer === 0) {
1399
- closeAll();
1400
- const { vnode: vnode2, el: el2, newPanel: newPanel2 } = createComponent();
1401
- render(vnode2, el2);
1402
- panels = [newPanel2];
1403
- logger.info("Panels after open", panels);
1404
- return uuid;
1405
- }
1406
- if (!panels.some((panel) => panel.layer === layer)) {
1407
- const { vnode: vnode2, el: el2, newPanel: newPanel2 } = createComponent();
1408
- render(vnode2, el2);
1409
- panels = [...panels, newPanel2];
1410
- logger.info("Panels after open", panels);
1411
- return uuid;
1412
- }
1413
- const panelOnCurrentLayer = panels.find((panel) => panel.layer === layer);
1414
- close(panelOnCurrentLayer?.uuid || "");
1415
- const { vnode, el, newPanel } = createComponent();
1416
- render(vnode, el);
1417
- panels = [...panels, newPanel];
1418
- logger.info("Panels after open", panels);
1419
- return uuid;
1420
- };
1421
- const close = (uuid) => {
1422
- const panel = panels.find((item) => item.uuid === uuid);
1423
- logger.log(`Close panel: "${uuid}"`);
1424
- if (panels.length === 1 && isGlobalScrollLocked.value) {
1425
- unlockGlobalScroll();
1426
- }
1427
- panel?.vnode.close();
1428
- };
1429
- const closeAll = () => {
1430
- panels.forEach((panel) => {
1431
- panel?.vnode.close();
1432
- });
1433
- if (isGlobalScrollLocked.value) {
1434
- unlockGlobalScroll();
1435
- }
1436
- };
1437
- const getInstance = (uuid) => {
1438
- return panels.find((item) => item.uuid === uuid)?.vnode;
1439
- };
1440
- const openByHash = ({
1441
- layer = 0,
1442
- component,
1443
- props
1444
- }) => {
1445
- const data = {
1446
- name: component.name,
1447
- layer,
1448
- props
1449
- };
1450
- router.push({
1451
- name: route.name || void 0,
1452
- query: route.query,
1453
- hash: `#${window.btoa(JSON.stringify(data))}`
1454
- });
1455
- };
1456
- const watchHash = ({
1457
- component,
1458
- events
1459
- }) => {
1460
- logger.info(`start watching route.hash for panel *${component.name}*`);
1461
- const stopWatch = watch(
1462
- () => route.hash,
1463
- async (newHash) => {
1464
- if (!newHash) {
1465
- closeAll();
1466
- return;
1467
- }
1468
- let dataFromHash;
1469
- try {
1470
- dataFromHash = JSON.parse(window.atob(newHash.slice(1)));
1471
- } catch (_error) {
1472
- logger.error("*watchHash* cant parse hash");
1473
- }
1474
- if (typeof dataFromHash !== "object") return;
1475
- if (!dataFromHash.name) {
1476
- logger.error("*watchHash* cant find component name in hash");
1477
- return;
1478
- }
1479
- if (dataFromHash.name !== component.name) return;
1480
- logger.info("*watchHash* data from hash", dataFromHash);
1481
- await nextTick();
1482
- open({
1483
- component,
1484
- layer: dataFromHash.layer || 0,
1485
- props: {
1486
- "onUpdate:modelValue": (value) => {
1487
- if (value) return;
1488
- router.push({
1489
- name: route.name || void 0,
1490
- query: route.query,
1491
- hash: void 0
1492
- });
1493
- },
1494
- ...dataFromHash.props,
1495
- ...events
1496
- }
1497
- });
1498
- },
1499
- { immediate: true }
1500
- );
1501
- const stopWatchHash = () => {
1502
- logger.info(`stop watching route.hash for panel *${component.name}*`);
1503
- stopWatch();
1504
- };
1505
- onBeforeUnmount(() => {
1506
- stopWatchHash();
1507
- });
1508
- return stopWatchHash;
1509
- };
1510
- return {
1511
- open,
1512
- getInstance,
1513
- close,
1514
- closeAll,
1515
- openByHash,
1516
- watchHash
1517
- };
1334
+ let appContext;
1335
+ const logger = useLogger("use-panel");
1336
+ const { isLocked: isGlobalScrollLocked, lock: lockGlobalScroll, unlock: unlockGlobalScroll } = useGlobalScroll();
1337
+ const route = useRoute();
1338
+ const router = useRouter();
1339
+ onMounted(() => {
1340
+ appContext = getCurrentInstance()?.appContext;
1341
+ });
1342
+ const open = ({ layer = 0, component, props }) => {
1343
+ const uuid = genUUID();
1344
+ const createComponent = () => {
1345
+ const newProps = {
1346
+ ...props,
1347
+ layer
1348
+ };
1349
+ const el = document.createElement("div");
1350
+ const vnode = createVNode(component, {
1351
+ ...newProps,
1352
+ modelValue: true,
1353
+ uuid
1354
+ });
1355
+ vnode.appContext = { ...appContext };
1356
+ /**
1357
+ * Если у компонента не объявлен свой обработчик на onUpdate:modelValue,
1358
+ * то создаем его самостоятельно
1359
+ *
1360
+ * Например:
1361
+ * openPanel({
1362
+ * component: SomePanel,
1363
+ * })
1364
+ *
1365
+ * Если же его явно объявили, то никаких костылей не нужно
1366
+ *
1367
+ * Пример кода когда панель открывается и закрывается по хешу в роутере
1368
+ * openPanel({
1369
+ * component: SomePanel,
1370
+ * props: {
1371
+ * 'onUpdate:modelValue': (value: boolean) => {
1372
+ if (value) return;
1373
+ router.push({ hash: undefined });
1374
+ },
1375
+ * },
1376
+ * })
1377
+ */
1378
+ if (!vnode?.props?.["onUpdate:modelValue"]) vnode.props["onUpdate:modelValue"] = (value) => {
1379
+ if (vnode && vnode.component) {
1380
+ vnode.component.props.modelValue = value;
1381
+ if (!value && panels.length === 1 && isGlobalScrollLocked.value) unlockGlobalScroll();
1382
+ }
1383
+ };
1384
+ vnode.close = () => {
1385
+ if (vnode && vnode.component) vnode.component.props.modelValue = false;
1386
+ };
1387
+ vnode.props.onDestroy = () => {
1388
+ render(null, el);
1389
+ panels = panels.filter((panel) => panel.uuid !== uuid);
1390
+ logger.info("Panels after destroy", panels);
1391
+ };
1392
+ const name = vnode?.type?.name ?? "Unknown component";
1393
+ const newPanel = {
1394
+ uuid,
1395
+ name,
1396
+ vnode,
1397
+ layer
1398
+ };
1399
+ logger.log(`Open new panel: "${name}"`);
1400
+ if (!isGlobalScrollLocked.value) lockGlobalScroll();
1401
+ return {
1402
+ vnode,
1403
+ el,
1404
+ newPanel
1405
+ };
1406
+ };
1407
+ /**
1408
+ * Если нет панелей, то просто открываем новую
1409
+ */
1410
+ if (!panels.length) {
1411
+ const { vnode, el, newPanel } = createComponent();
1412
+ render(vnode, el);
1413
+ panels = [newPanel];
1414
+ logger.info("Panels after open", panels);
1415
+ return uuid;
1416
+ }
1417
+ /**
1418
+ * При открытии новой панели с нулевым слоем нужно закрыть
1419
+ * все предыдущие панели без учета их количества
1420
+ */
1421
+ if (layer === 0) {
1422
+ closeAll();
1423
+ const { vnode, el, newPanel } = createComponent();
1424
+ render(vnode, el);
1425
+ panels = [newPanel];
1426
+ logger.info("Panels after open", panels);
1427
+ return uuid;
1428
+ }
1429
+ /**
1430
+ * Если мы пытается открыть панель со слоем отличным от 0,
1431
+ * то нужно проверить наличие уже открытой панели на этом слое.
1432
+ * Если панели нет, то просто пушим в массив новый элемент
1433
+ * Если панель есть, то через таймаут подменяем ее
1434
+ */
1435
+ if (!panels.some((panel) => panel.layer === layer)) {
1436
+ const { vnode, el, newPanel } = createComponent();
1437
+ render(vnode, el);
1438
+ panels = [...panels, newPanel];
1439
+ logger.info("Panels after open", panels);
1440
+ return uuid;
1441
+ }
1442
+ const panelOnCurrentLayer = panels.find((panel) => panel.layer === layer);
1443
+ close(panelOnCurrentLayer?.uuid || "");
1444
+ const { vnode, el, newPanel } = createComponent();
1445
+ render(vnode, el);
1446
+ panels = [...panels, newPanel];
1447
+ logger.info("Panels after open", panels);
1448
+ return uuid;
1449
+ };
1450
+ const close = (uuid) => {
1451
+ const panel = panels.find((item) => item.uuid === uuid);
1452
+ logger.log(`Close panel: "${uuid}"`);
1453
+ if (panels.length === 1 && isGlobalScrollLocked.value) unlockGlobalScroll();
1454
+ panel?.vnode.close();
1455
+ };
1456
+ const closeAll = () => {
1457
+ panels.forEach((panel) => {
1458
+ panel?.vnode.close();
1459
+ });
1460
+ if (isGlobalScrollLocked.value) unlockGlobalScroll();
1461
+ };
1462
+ const getInstance = (uuid) => {
1463
+ return panels.find((item) => item.uuid === uuid)?.vnode;
1464
+ };
1465
+ /**
1466
+ * Открытие панелей через hash
1467
+ *
1468
+ * Метод openByHash только дергает router и прокидывает в hash все необходимые данные.
1469
+ * Для полноценной работы на конкретной странице необходимо
1470
+ * для этого же компонента подключить watchHash
1471
+ */
1472
+ const openByHash = ({ layer = 0, component, props }) => {
1473
+ const data = {
1474
+ name: component.name,
1475
+ layer,
1476
+ props
1477
+ };
1478
+ router.push({
1479
+ name: route.name || void 0,
1480
+ query: route.query,
1481
+ hash: `#${window.btoa(JSON.stringify(data))}`
1482
+ });
1483
+ };
1484
+ const watchHash = ({ component, events }) => {
1485
+ logger.info(`start watching route.hash for panel *${component.name}*`);
1486
+ const stopWatch = watch(() => route.hash, async (newHash) => {
1487
+ if (!newHash) {
1488
+ closeAll();
1489
+ return;
1490
+ }
1491
+ let dataFromHash;
1492
+ try {
1493
+ dataFromHash = JSON.parse(window.atob(newHash.slice(1)));
1494
+ } catch (_error) {
1495
+ logger.error("*watchHash* cant parse hash");
1496
+ }
1497
+ if (typeof dataFromHash !== "object") return;
1498
+ if (!dataFromHash.name) {
1499
+ logger.error("*watchHash* cant find component name in hash");
1500
+ return;
1501
+ }
1502
+ if (dataFromHash.name !== component.name) return;
1503
+ logger.info("*watchHash* data from hash", dataFromHash);
1504
+ await nextTick();
1505
+ open({
1506
+ component,
1507
+ layer: dataFromHash.layer || 0,
1508
+ props: {
1509
+ "onUpdate:modelValue": (value) => {
1510
+ if (value) return;
1511
+ router.push({
1512
+ name: route.name || void 0,
1513
+ query: route.query,
1514
+ hash: void 0
1515
+ });
1516
+ },
1517
+ ...dataFromHash.props,
1518
+ ...events
1519
+ }
1520
+ });
1521
+ }, { immediate: true });
1522
+ const stopWatchHash = () => {
1523
+ logger.info(`stop watching route.hash for panel *${component.name}*`);
1524
+ stopWatch();
1525
+ };
1526
+ onBeforeUnmount(() => {
1527
+ stopWatchHash();
1528
+ });
1529
+ return stopWatchHash;
1530
+ };
1531
+ return {
1532
+ open,
1533
+ getInstance,
1534
+ close,
1535
+ closeAll,
1536
+ openByHash,
1537
+ watchHash
1538
+ };
1518
1539
  }
1519
-
1540
+ //#endregion
1541
+ //#region src/validator/validatePhone.ts
1520
1542
  function validatePhone(rule, value) {
1521
- if (!value) return true;
1522
- const phoneNumber = parsePhoneNumberFromString(value);
1523
- return phoneNumber ? phoneNumber.isValid() : false;
1543
+ if (!value) return true;
1544
+ const phoneNumber = parsePhoneNumberFromString(value);
1545
+ return phoneNumber ? phoneNumber.isValid() : false;
1524
1546
  }
1525
-
1547
+ //#endregion
1548
+ //#region src/validator/formRules.ts
1526
1549
  function isRequired(value = true, message = "This field is required") {
1527
- return {
1528
- required: value,
1529
- message
1530
- };
1550
+ return {
1551
+ required: value,
1552
+ message
1553
+ };
1531
1554
  }
1532
1555
  function isMax(value = 255, message) {
1533
- return {
1534
- max: value,
1535
- message: message ?? `Length must be no more than ${value} characters`
1536
- };
1556
+ return {
1557
+ max: value,
1558
+ message: message ?? `Length must be no more than ${value} characters`
1559
+ };
1537
1560
  }
1538
1561
  function isMin(value = 3, message) {
1539
- return {
1540
- min: value,
1541
- message: message ?? `Length must be at least ${value} characters`
1542
- };
1562
+ return {
1563
+ min: value,
1564
+ message: message ?? `Length must be at least ${value} characters`
1565
+ };
1543
1566
  }
1544
1567
  function isTypeEmail(message = "Invalid format") {
1545
- return {
1546
- type: "email",
1547
- message
1548
- };
1568
+ return {
1569
+ type: "email",
1570
+ message
1571
+ };
1549
1572
  }
1550
1573
  function isTypeUrl(message = "The url is invalid") {
1551
- return {
1552
- type: "url",
1553
- message
1554
- };
1574
+ return {
1575
+ type: "url",
1576
+ message
1577
+ };
1555
1578
  }
1556
1579
  function isTypeNumber(value = 1, message) {
1557
- return {
1558
- type: "number",
1559
- min: value,
1560
- message: message ?? `Must be at least ${value}`
1561
- };
1580
+ return {
1581
+ type: "number",
1582
+ min: value,
1583
+ message: message ?? `Must be at least ${value}`
1584
+ };
1562
1585
  }
1563
1586
  function isStrictLength(value = 3, message) {
1564
- return {
1565
- len: value,
1566
- message: message ?? `Length must be exactly ${value} characters`
1567
- };
1587
+ return {
1588
+ len: value,
1589
+ message: message ?? `Length must be exactly ${value} characters`
1590
+ };
1568
1591
  }
1569
-
1592
+ //#endregion
1570
1593
  export { AppComponentsResolver, EnrichError, UiComponentsResolver, camelizeKeys, convertEnumToOptions, formatErrorDataMessage, formatErrorForNotify, formatMoney, genHash, genRandomNumber, genUUID, getCardNumber, getCountryFromPhone, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, getStatusMessage, isElementIgnored, isEmptyObject, isHtml, 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 };