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