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