@serhii.olishevskyi/docs 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3171 +1,51 @@
1
- // src/UI/components/inputs/TextfieldComponent.tsx
2
- import { useState as useState5 } from "react";
3
1
  import {
4
- TextField as TextField2,
5
- InputAdornment,
6
- IconButton as IconButton2,
7
- Box as Box3,
8
- Tooltip as Tooltip3
9
- } from "@mui/material";
10
- import LockIcon from "@mui/icons-material/Lock";
11
- import ContentCopyIcon from "@mui/icons-material/ContentCopy";
12
- import CheckIcon from "@mui/icons-material/Check";
13
- import ClearIcon from "@mui/icons-material/Clear";
14
- import TranslateIcon3 from "@mui/icons-material/Translate";
15
-
16
- // src/UI/components/inputs/TranslatableTooltip.tsx
17
- import { Tooltip } from "@mui/material";
18
-
19
- // src/context/TranslationEditProvider.tsx
20
- import { createContext as createContext3, useContext as useContext3, useState as useState2, useEffect as useEffect2, useCallback as useCallback2 } from "react";
21
-
22
- // node_modules/i18next/dist/esm/i18next.js
23
- var isString = (obj) => typeof obj === "string";
24
- var defer = () => {
25
- let res;
26
- let rej;
27
- const promise = new Promise((resolve, reject) => {
28
- res = resolve;
29
- rej = reject;
30
- });
31
- promise.resolve = res;
32
- promise.reject = rej;
33
- return promise;
34
- };
35
- var makeString = (object) => {
36
- if (object == null) return "";
37
- return String(object);
38
- };
39
- var copy = (a, s, t2) => {
40
- a.forEach((m) => {
41
- if (s[m]) t2[m] = s[m];
42
- });
43
- };
44
- var lastOfPathSeparatorRegExp = /###/g;
45
- var cleanKey = (key) => key && key.includes("###") ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
46
- var canNotTraverseDeeper = (object) => !object || isString(object);
47
- var getLastOfPath = (object, path, Empty) => {
48
- const stack = !isString(path) ? path : path.split(".");
49
- let stackIndex = 0;
50
- while (stackIndex < stack.length - 1) {
51
- if (canNotTraverseDeeper(object)) return {};
52
- const key = cleanKey(stack[stackIndex]);
53
- if (!object[key] && Empty) object[key] = new Empty();
54
- if (Object.prototype.hasOwnProperty.call(object, key)) {
55
- object = object[key];
56
- } else {
57
- object = {};
58
- }
59
- ++stackIndex;
60
- }
61
- if (canNotTraverseDeeper(object)) return {};
62
- return {
63
- obj: object,
64
- k: cleanKey(stack[stackIndex])
65
- };
66
- };
67
- var setPath = (object, path, newValue) => {
68
- const {
69
- obj,
70
- k
71
- } = getLastOfPath(object, path, Object);
72
- if (obj !== void 0 || path.length === 1) {
73
- obj[k] = newValue;
74
- return;
75
- }
76
- let e = path[path.length - 1];
77
- let p = path.slice(0, path.length - 1);
78
- let last = getLastOfPath(object, p, Object);
79
- while (last.obj === void 0 && p.length) {
80
- e = `${p[p.length - 1]}.${e}`;
81
- p = p.slice(0, p.length - 1);
82
- last = getLastOfPath(object, p, Object);
83
- if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") {
84
- last.obj = void 0;
85
- }
86
- }
87
- last.obj[`${last.k}.${e}`] = newValue;
88
- };
89
- var pushPath = (object, path, newValue, concat) => {
90
- const {
91
- obj,
92
- k
93
- } = getLastOfPath(object, path, Object);
94
- obj[k] = obj[k] || [];
95
- obj[k].push(newValue);
96
- };
97
- var getPath = (object, path) => {
98
- const {
99
- obj,
100
- k
101
- } = getLastOfPath(object, path);
102
- if (!obj) return void 0;
103
- if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0;
104
- return obj[k];
105
- };
106
- var getPathWithDefaults = (data, defaultData, key) => {
107
- const value = getPath(data, key);
108
- if (value !== void 0) {
109
- return value;
110
- }
111
- return getPath(defaultData, key);
112
- };
113
- var deepExtend = (target, source, overwrite) => {
114
- for (const prop in source) {
115
- if (prop !== "__proto__" && prop !== "constructor") {
116
- if (Object.prototype.hasOwnProperty.call(target, prop)) {
117
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
118
- if (overwrite) target[prop] = source[prop];
119
- } else {
120
- deepExtend(target[prop], source[prop], overwrite);
121
- }
122
- } else {
123
- target[prop] = source[prop];
124
- }
125
- }
126
- }
127
- return target;
128
- };
129
- var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
130
- var _entityMap = {
131
- "&": "&amp;",
132
- "<": "&lt;",
133
- ">": "&gt;",
134
- '"': "&quot;",
135
- "'": "&#39;",
136
- "/": "&#x2F;"
137
- };
138
- var escape = (data) => {
139
- if (isString(data)) {
140
- return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
141
- }
142
- return data;
143
- };
144
- var RegExpCache = class {
145
- constructor(capacity) {
146
- this.capacity = capacity;
147
- this.regExpMap = /* @__PURE__ */ new Map();
148
- this.regExpQueue = [];
149
- }
150
- getRegExp(pattern) {
151
- const regExpFromCache = this.regExpMap.get(pattern);
152
- if (regExpFromCache !== void 0) {
153
- return regExpFromCache;
154
- }
155
- const regExpNew = new RegExp(pattern);
156
- if (this.regExpQueue.length === this.capacity) {
157
- this.regExpMap.delete(this.regExpQueue.shift());
158
- }
159
- this.regExpMap.set(pattern, regExpNew);
160
- this.regExpQueue.push(pattern);
161
- return regExpNew;
162
- }
163
- };
164
- var chars = [" ", ",", "?", "!", ";"];
165
- var looksLikeObjectPathRegExpCache = new RegExpCache(20);
166
- var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
167
- nsSeparator = nsSeparator || "";
168
- keySeparator = keySeparator || "";
169
- const possibleChars = chars.filter((c) => !nsSeparator.includes(c) && !keySeparator.includes(c));
170
- if (possibleChars.length === 0) return true;
171
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
172
- let matched = !r.test(key);
173
- if (!matched) {
174
- const ki = key.indexOf(keySeparator);
175
- if (ki > 0 && !r.test(key.substring(0, ki))) {
176
- matched = true;
177
- }
178
- }
179
- return matched;
180
- };
181
- var deepFind = (obj, path, keySeparator = ".") => {
182
- if (!obj) return void 0;
183
- if (obj[path]) {
184
- if (!Object.prototype.hasOwnProperty.call(obj, path)) return void 0;
185
- return obj[path];
186
- }
187
- const tokens = path.split(keySeparator);
188
- let current = obj;
189
- for (let i = 0; i < tokens.length; ) {
190
- if (!current || typeof current !== "object") {
191
- return void 0;
192
- }
193
- let next;
194
- let nextPath = "";
195
- for (let j = i; j < tokens.length; ++j) {
196
- if (j !== i) {
197
- nextPath += keySeparator;
198
- }
199
- nextPath += tokens[j];
200
- next = current[nextPath];
201
- if (next !== void 0) {
202
- if (["string", "number", "boolean"].includes(typeof next) && j < tokens.length - 1) {
203
- continue;
204
- }
205
- i += j - i + 1;
206
- break;
207
- }
208
- }
209
- current = next;
210
- }
211
- return current;
212
- };
213
- var getCleanedCode = (code) => code?.replace(/_/g, "-");
214
- var consoleLogger = {
215
- type: "logger",
216
- log(args) {
217
- this.output("log", args);
218
- },
219
- warn(args) {
220
- this.output("warn", args);
221
- },
222
- error(args) {
223
- this.output("error", args);
224
- },
225
- output(type, args) {
226
- console?.[type]?.apply?.(console, args);
227
- }
228
- };
229
- var Logger = class _Logger {
230
- constructor(concreteLogger, options = {}) {
231
- this.init(concreteLogger, options);
232
- }
233
- init(concreteLogger, options = {}) {
234
- this.prefix = options.prefix || "i18next:";
235
- this.logger = concreteLogger || consoleLogger;
236
- this.options = options;
237
- this.debug = options.debug;
238
- }
239
- log(...args) {
240
- return this.forward(args, "log", "", true);
241
- }
242
- warn(...args) {
243
- return this.forward(args, "warn", "", true);
244
- }
245
- error(...args) {
246
- return this.forward(args, "error", "");
247
- }
248
- deprecate(...args) {
249
- return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
250
- }
251
- forward(args, lvl, prefix, debugOnly) {
252
- if (debugOnly && !this.debug) return null;
253
- args = args.map((a) => isString(a) ? a.replace(/[\r\n\x00-\x1F\x7F]/g, " ") : a);
254
- if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
255
- return this.logger[lvl](args);
256
- }
257
- create(moduleName) {
258
- return new _Logger(this.logger, {
259
- ...{
260
- prefix: `${this.prefix}:${moduleName}:`
261
- },
262
- ...this.options
263
- });
264
- }
265
- clone(options) {
266
- options = options || this.options;
267
- options.prefix = options.prefix || this.prefix;
268
- return new _Logger(this.logger, options);
269
- }
270
- };
271
- var baseLogger = new Logger();
272
- var EventEmitter = class {
273
- constructor() {
274
- this.observers = {};
275
- }
276
- on(events, listener) {
277
- events.split(" ").forEach((event) => {
278
- if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
279
- const numListeners = this.observers[event].get(listener) || 0;
280
- this.observers[event].set(listener, numListeners + 1);
281
- });
282
- return this;
283
- }
284
- off(event, listener) {
285
- if (!this.observers[event]) return;
286
- if (!listener) {
287
- delete this.observers[event];
288
- return;
289
- }
290
- this.observers[event].delete(listener);
291
- }
292
- once(event, listener) {
293
- const wrapper = (...args) => {
294
- listener(...args);
295
- this.off(event, wrapper);
296
- };
297
- this.on(event, wrapper);
298
- return this;
299
- }
300
- emit(event, ...args) {
301
- if (this.observers[event]) {
302
- const cloned = Array.from(this.observers[event].entries());
303
- cloned.forEach(([observer, numTimesAdded]) => {
304
- for (let i = 0; i < numTimesAdded; i++) {
305
- observer(...args);
306
- }
307
- });
308
- }
309
- if (this.observers["*"]) {
310
- const cloned = Array.from(this.observers["*"].entries());
311
- cloned.forEach(([observer, numTimesAdded]) => {
312
- for (let i = 0; i < numTimesAdded; i++) {
313
- observer(event, ...args);
314
- }
315
- });
316
- }
317
- }
318
- };
319
- var ResourceStore = class extends EventEmitter {
320
- constructor(data, options = {
321
- ns: ["translation"],
322
- defaultNS: "translation"
323
- }) {
324
- super();
325
- this.data = data || {};
326
- this.options = options;
327
- if (this.options.keySeparator === void 0) {
328
- this.options.keySeparator = ".";
329
- }
330
- if (this.options.ignoreJSONStructure === void 0) {
331
- this.options.ignoreJSONStructure = true;
332
- }
333
- }
334
- addNamespaces(ns) {
335
- if (!this.options.ns.includes(ns)) {
336
- this.options.ns.push(ns);
337
- }
338
- }
339
- removeNamespaces(ns) {
340
- const index = this.options.ns.indexOf(ns);
341
- if (index > -1) {
342
- this.options.ns.splice(index, 1);
343
- }
344
- }
345
- getResource(lng, ns, key, options = {}) {
346
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
347
- const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
348
- let path;
349
- if (lng.includes(".")) {
350
- path = lng.split(".");
351
- } else {
352
- path = [lng, ns];
353
- if (key) {
354
- if (Array.isArray(key)) {
355
- path.push(...key);
356
- } else if (isString(key) && keySeparator) {
357
- path.push(...key.split(keySeparator));
358
- } else {
359
- path.push(key);
360
- }
361
- }
362
- }
363
- const result = getPath(this.data, path);
364
- if (!result && !ns && !key && lng.includes(".")) {
365
- lng = path[0];
366
- ns = path[1];
367
- key = path.slice(2).join(".");
368
- }
369
- if (result || !ignoreJSONStructure || !isString(key)) return result;
370
- return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
371
- }
372
- addResource(lng, ns, key, value, options = {
373
- silent: false
374
- }) {
375
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
376
- let path = [lng, ns];
377
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
378
- if (lng.includes(".")) {
379
- path = lng.split(".");
380
- value = ns;
381
- ns = path[1];
382
- }
383
- this.addNamespaces(ns);
384
- setPath(this.data, path, value);
385
- if (!options.silent) this.emit("added", lng, ns, key, value);
386
- }
387
- addResources(lng, ns, resources, options = {
388
- silent: false
389
- }) {
390
- for (const m in resources) {
391
- if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
392
- silent: true
393
- });
394
- }
395
- if (!options.silent) this.emit("added", lng, ns, resources);
396
- }
397
- addResourceBundle(lng, ns, resources, deep, overwrite, options = {
398
- silent: false,
399
- skipCopy: false
400
- }) {
401
- let path = [lng, ns];
402
- if (lng.includes(".")) {
403
- path = lng.split(".");
404
- deep = resources;
405
- resources = ns;
406
- ns = path[1];
407
- }
408
- this.addNamespaces(ns);
409
- let pack = getPath(this.data, path) || {};
410
- if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
411
- if (deep) {
412
- deepExtend(pack, resources, overwrite);
413
- } else {
414
- pack = {
415
- ...pack,
416
- ...resources
417
- };
418
- }
419
- setPath(this.data, path, pack);
420
- if (!options.silent) this.emit("added", lng, ns, resources);
421
- }
422
- removeResourceBundle(lng, ns) {
423
- if (this.hasResourceBundle(lng, ns)) {
424
- delete this.data[lng][ns];
425
- }
426
- this.removeNamespaces(ns);
427
- this.emit("removed", lng, ns);
428
- }
429
- hasResourceBundle(lng, ns) {
430
- return this.getResource(lng, ns) !== void 0;
431
- }
432
- getResourceBundle(lng, ns) {
433
- if (!ns) ns = this.options.defaultNS;
434
- return this.getResource(lng, ns);
435
- }
436
- getDataByLanguage(lng) {
437
- return this.data[lng];
438
- }
439
- hasLanguageSomeTranslations(lng) {
440
- const data = this.getDataByLanguage(lng);
441
- const n = data && Object.keys(data) || [];
442
- return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
443
- }
444
- toJSON() {
445
- return this.data;
446
- }
447
- };
448
- var postProcessor = {
449
- processors: {},
450
- addPostProcessor(module) {
451
- this.processors[module.name] = module;
452
- },
453
- handle(processors, value, key, options, translator) {
454
- processors.forEach((processor) => {
455
- value = this.processors[processor]?.process(value, key, options, translator) ?? value;
456
- });
457
- return value;
458
- }
459
- };
460
- var PATH_KEY = /* @__PURE__ */ Symbol("i18next/PATH_KEY");
461
- function createProxy() {
462
- const state = [];
463
- const handler = /* @__PURE__ */ Object.create(null);
464
- let proxy;
465
- handler.get = (target, key) => {
466
- proxy?.revoke?.();
467
- if (key === PATH_KEY) return state;
468
- state.push(key);
469
- proxy = Proxy.revocable(target, handler);
470
- return proxy.proxy;
471
- };
472
- return Proxy.revocable(/* @__PURE__ */ Object.create(null), handler).proxy;
473
- }
474
- function keysFromSelector(selector, opts) {
475
- const {
476
- [PATH_KEY]: path
477
- } = selector(createProxy());
478
- const keySeparator = opts?.keySeparator ?? ".";
479
- const nsSeparator = opts?.nsSeparator ?? ":";
480
- const strict = opts?.enableSelector === "strict";
481
- if (path.length > 1 && nsSeparator) {
482
- const ns = opts?.ns;
483
- const nsList = strict ? Array.isArray(ns) ? ns : ns ? [ns] : null : Array.isArray(ns) ? ns : null;
484
- if (nsList) {
485
- const candidates = strict ? nsList : nsList.length > 1 ? nsList.slice(1) : [];
486
- if (candidates.includes(path[0])) {
487
- return `${path[0]}${nsSeparator}${path.slice(1).join(keySeparator)}`;
488
- }
489
- }
490
- }
491
- return path.join(keySeparator);
492
- }
493
- var shouldHandleAsObject = (res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number";
494
- var Translator = class _Translator extends EventEmitter {
495
- constructor(services, options = {}) {
496
- super();
497
- copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
498
- this.options = options;
499
- if (this.options.keySeparator === void 0) {
500
- this.options.keySeparator = ".";
501
- }
502
- this.logger = baseLogger.create("translator");
503
- this.checkedLoadedFor = {};
504
- }
505
- changeLanguage(lng) {
506
- if (lng) this.language = lng;
507
- }
508
- exists(key, o = {
509
- interpolation: {}
510
- }) {
511
- const opt = {
512
- ...o
513
- };
514
- if (key == null) return false;
515
- const resolved = this.resolve(key, opt);
516
- if (resolved?.res === void 0) return false;
517
- const isObject = shouldHandleAsObject(resolved.res);
518
- if (opt.returnObjects === false && isObject) {
519
- return false;
520
- }
521
- return true;
522
- }
523
- extractFromKey(key, opt) {
524
- let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
525
- if (nsSeparator === void 0) nsSeparator = ":";
526
- const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
527
- let namespaces = opt.ns || this.options.defaultNS || [];
528
- const wouldCheckForNsInKey = nsSeparator && key.includes(nsSeparator);
529
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
530
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
531
- const m = key.match(this.interpolator.nestingRegexp);
532
- if (m && m.length > 0) {
533
- return {
534
- key,
535
- namespaces: isString(namespaces) ? [namespaces] : namespaces
536
- };
537
- }
538
- const parts = key.split(nsSeparator);
539
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.includes(parts[0])) namespaces = parts.shift();
540
- key = parts.join(keySeparator);
541
- }
542
- return {
543
- key,
544
- namespaces: isString(namespaces) ? [namespaces] : namespaces
545
- };
546
- }
547
- translate(keys, o, lastKey) {
548
- let opt = typeof o === "object" ? {
549
- ...o
550
- } : o;
551
- if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) {
552
- opt = this.options.overloadTranslationOptionHandler(arguments);
553
- }
554
- if (typeof opt === "object") opt = {
555
- ...opt
556
- };
557
- if (!opt) opt = {};
558
- if (keys == null) return "";
559
- if (typeof keys === "function") keys = keysFromSelector(keys, {
560
- ...this.options,
561
- ...opt
562
- });
563
- if (!Array.isArray(keys)) keys = [String(keys)];
564
- keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, {
565
- ...this.options,
566
- ...opt
567
- }) : String(k));
568
- const returnDetails = opt.returnDetails !== void 0 ? opt.returnDetails : this.options.returnDetails;
569
- const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
570
- const {
571
- key,
572
- namespaces
573
- } = this.extractFromKey(keys[keys.length - 1], opt);
574
- const namespace = namespaces[namespaces.length - 1];
575
- let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
576
- if (nsSeparator === void 0) nsSeparator = ":";
577
- const lng = opt.lng || this.language;
578
- const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
579
- if (lng?.toLowerCase() === "cimode") {
580
- if (appendNamespaceToCIMode) {
581
- if (returnDetails) {
582
- return {
583
- res: `${namespace}${nsSeparator}${key}`,
584
- usedKey: key,
585
- exactUsedKey: key,
586
- usedLng: lng,
587
- usedNS: namespace,
588
- usedParams: this.getUsedParamsDetails(opt)
589
- };
590
- }
591
- return `${namespace}${nsSeparator}${key}`;
592
- }
593
- if (returnDetails) {
594
- return {
595
- res: key,
596
- usedKey: key,
597
- exactUsedKey: key,
598
- usedLng: lng,
599
- usedNS: namespace,
600
- usedParams: this.getUsedParamsDetails(opt)
601
- };
602
- }
603
- return key;
604
- }
605
- const resolved = this.resolve(keys, opt);
606
- let res = resolved?.res;
607
- const resUsedKey = resolved?.usedKey || key;
608
- const resExactUsedKey = resolved?.exactUsedKey || key;
609
- const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
610
- const joinArrays = opt.joinArrays !== void 0 ? opt.joinArrays : this.options.joinArrays;
611
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
612
- const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
613
- const hasDefaultValue = _Translator.hasDefaultValue(opt);
614
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : "";
615
- const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
616
- ordinal: false
617
- }) : "";
618
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
619
- const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
620
- let resForObjHndl = res;
621
- if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
622
- resForObjHndl = defaultValue;
623
- }
624
- const handleAsObject = shouldHandleAsObject(resForObjHndl);
625
- const resType = Object.prototype.toString.apply(resForObjHndl);
626
- if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && !noObject.includes(resType) && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
627
- if (!opt.returnObjects && !this.options.returnObjects) {
628
- if (!this.options.returnedObjectHandler) {
629
- this.logger.warn("accessing an object - but returnObjects options is not enabled!");
630
- }
631
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
632
- ...opt,
633
- ns: namespaces
634
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
635
- if (returnDetails) {
636
- resolved.res = r;
637
- resolved.usedParams = this.getUsedParamsDetails(opt);
638
- return resolved;
639
- }
640
- return r;
641
- }
642
- if (keySeparator) {
643
- const resTypeIsArray = Array.isArray(resForObjHndl);
644
- const copy2 = resTypeIsArray ? [] : {};
645
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
646
- for (const m in resForObjHndl) {
647
- if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
648
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
649
- if (hasDefaultValue && !res) {
650
- copy2[m] = this.translate(deepKey, {
651
- ...opt,
652
- defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : void 0,
653
- ...{
654
- joinArrays: false,
655
- ns: namespaces
656
- }
657
- });
658
- } else {
659
- copy2[m] = this.translate(deepKey, {
660
- ...opt,
661
- ...{
662
- joinArrays: false,
663
- ns: namespaces
664
- }
665
- });
666
- }
667
- if (copy2[m] === deepKey) copy2[m] = resForObjHndl[m];
668
- }
669
- }
670
- res = copy2;
671
- }
672
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
673
- res = res.join(joinArrays);
674
- if (res) res = this.extendTranslation(res, keys, opt, lastKey);
675
- } else {
676
- let usedDefault = false;
677
- let usedKey = false;
678
- if (!this.isValidLookup(res) && hasDefaultValue) {
679
- usedDefault = true;
680
- res = defaultValue;
681
- }
682
- if (!this.isValidLookup(res)) {
683
- usedKey = true;
684
- res = key;
685
- }
686
- const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
687
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
688
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
689
- if (usedKey || usedDefault || updateMissing) {
690
- this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, needsPluralHandling && !updateMissing ? `${key}${this.pluralResolver.getSuffix(lng, opt.count, opt)}` : key, updateMissing ? defaultValue : res);
691
- if (keySeparator) {
692
- const fk = this.resolve(key, {
693
- ...opt,
694
- keySeparator: false
695
- });
696
- if (fk && fk.res) this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.");
697
- }
698
- let lngs = [];
699
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
700
- if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
701
- for (let i = 0; i < fallbackLngs.length; i++) {
702
- lngs.push(fallbackLngs[i]);
703
- }
704
- } else if (this.options.saveMissingTo === "all") {
705
- lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
706
- } else {
707
- lngs.push(opt.lng || this.language);
708
- }
709
- const send = (l, k, specificDefaultValue) => {
710
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
711
- if (this.options.missingKeyHandler) {
712
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
713
- } else if (this.backendConnector?.saveMissing) {
714
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
715
- }
716
- this.emit("missingKey", l, namespace, k, res);
717
- };
718
- if (this.options.saveMissing) {
719
- if (this.options.saveMissingPlurals && needsPluralHandling) {
720
- lngs.forEach((language) => {
721
- const suffixes = this.pluralResolver.getSuffixes(language, opt);
722
- if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && !suffixes.includes(`${this.options.pluralSeparator}zero`)) {
723
- suffixes.push(`${this.options.pluralSeparator}zero`);
724
- }
725
- suffixes.forEach((suffix) => {
726
- send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
727
- });
728
- });
729
- } else {
730
- send(lngs, key, defaultValue);
731
- }
732
- }
733
- }
734
- res = this.extendTranslation(res, keys, opt, resolved, lastKey);
735
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
736
- res = `${namespace}${nsSeparator}${key}`;
737
- }
738
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
739
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : void 0, opt);
740
- }
741
- }
742
- if (returnDetails) {
743
- resolved.res = res;
744
- resolved.usedParams = this.getUsedParamsDetails(opt);
745
- return resolved;
746
- }
747
- return res;
748
- }
749
- extendTranslation(res, key, opt, resolved, lastKey) {
750
- if (this.i18nFormat?.parse) {
751
- res = this.i18nFormat.parse(res, {
752
- ...this.options.interpolation.defaultVariables,
753
- ...opt
754
- }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
755
- resolved
756
- });
757
- } else if (!opt.skipInterpolation) {
758
- if (opt.interpolation) this.interpolator.init({
759
- ...opt,
760
- ...{
761
- interpolation: {
762
- ...this.options.interpolation,
763
- ...opt.interpolation
764
- }
765
- }
766
- });
767
- const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== void 0 ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
768
- let nestBef;
769
- if (skipOnVariables) {
770
- const nb = res.match(this.interpolator.nestingRegexp);
771
- nestBef = nb && nb.length;
772
- }
773
- let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
774
- if (this.options.interpolation.defaultVariables) data = {
775
- ...this.options.interpolation.defaultVariables,
776
- ...data
777
- };
778
- res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
779
- if (skipOnVariables) {
780
- const na = res.match(this.interpolator.nestingRegexp);
781
- const nestAft = na && na.length;
782
- if (nestBef < nestAft) opt.nest = false;
783
- }
784
- if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
785
- if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
786
- if (lastKey?.[0] === args[0] && !opt.context) {
787
- this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
788
- return null;
789
- }
790
- return this.translate(...args, key);
791
- }, opt);
792
- if (opt.interpolation) this.interpolator.reset();
793
- }
794
- const postProcess = opt.postProcess || this.options.postProcess;
795
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
796
- if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
797
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
798
- i18nResolved: {
799
- ...resolved,
800
- usedParams: this.getUsedParamsDetails(opt)
801
- },
802
- ...opt
803
- } : opt, this);
804
- }
805
- return res;
806
- }
807
- resolve(keys, opt = {}) {
808
- let found;
809
- let usedKey;
810
- let exactUsedKey;
811
- let usedLng;
812
- let usedNS;
813
- if (isString(keys)) keys = [keys];
814
- if (Array.isArray(keys)) keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, {
815
- ...this.options,
816
- ...opt
817
- }) : k);
818
- keys.forEach((k) => {
819
- if (this.isValidLookup(found)) return;
820
- const extracted = this.extractFromKey(k, opt);
821
- const key = extracted.key;
822
- usedKey = key;
823
- let namespaces = extracted.namespaces;
824
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
825
- const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
826
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
827
- const needsContextHandling = opt.context !== void 0 && (isString(opt.context) || typeof opt.context === "number") && opt.context !== "";
828
- const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
829
- namespaces.forEach((ns) => {
830
- if (this.isValidLookup(found)) return;
831
- usedNS = ns;
832
- if (!this.checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
833
- this.checkedLoadedFor[`${codes[0]}-${ns}`] = true;
834
- this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
835
- }
836
- codes.forEach((code) => {
837
- if (this.isValidLookup(found)) return;
838
- usedLng = code;
839
- const finalKeys = [key];
840
- if (this.i18nFormat?.addLookupKeys) {
841
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
842
- } else {
843
- let pluralSuffix;
844
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
845
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
846
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
847
- if (needsPluralHandling) {
848
- if (opt.ordinal && pluralSuffix.startsWith(ordinalPrefix)) {
849
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
850
- }
851
- finalKeys.push(key + pluralSuffix);
852
- if (needsZeroSuffixLookup) {
853
- finalKeys.push(key + zeroSuffix);
854
- }
855
- }
856
- if (needsContextHandling) {
857
- const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`;
858
- finalKeys.push(contextKey);
859
- if (needsPluralHandling) {
860
- if (opt.ordinal && pluralSuffix.startsWith(ordinalPrefix)) {
861
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
862
- }
863
- finalKeys.push(contextKey + pluralSuffix);
864
- if (needsZeroSuffixLookup) {
865
- finalKeys.push(contextKey + zeroSuffix);
866
- }
867
- }
868
- }
869
- }
870
- let possibleKey;
871
- while (possibleKey = finalKeys.pop()) {
872
- if (!this.isValidLookup(found)) {
873
- exactUsedKey = possibleKey;
874
- found = this.getResource(code, ns, possibleKey, opt);
875
- }
876
- }
877
- });
878
- });
879
- });
880
- return {
881
- res: found,
882
- usedKey,
883
- exactUsedKey,
884
- usedLng,
885
- usedNS
886
- };
887
- }
888
- isValidLookup(res) {
889
- return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
890
- }
891
- getResource(code, ns, key, options = {}) {
892
- if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
893
- return this.resourceStore.getResource(code, ns, key, options);
894
- }
895
- getUsedParamsDetails(options = {}) {
896
- const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
897
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
898
- let data = useOptionsReplaceForData ? options.replace : options;
899
- if (useOptionsReplaceForData && typeof options.count !== "undefined") {
900
- data = {
901
- ...data,
902
- count: options.count
903
- };
904
- }
905
- if (this.options.interpolation.defaultVariables) {
906
- data = {
907
- ...this.options.interpolation.defaultVariables,
908
- ...data
909
- };
910
- }
911
- if (!useOptionsReplaceForData) {
912
- data = {
913
- ...data
914
- };
915
- for (const key of optionsKeys) {
916
- delete data[key];
917
- }
918
- }
919
- return data;
920
- }
921
- static hasDefaultValue(options) {
922
- const prefix = "defaultValue";
923
- for (const option in options) {
924
- if (Object.prototype.hasOwnProperty.call(options, option) && option.startsWith(prefix) && void 0 !== options[option]) {
925
- return true;
926
- }
927
- }
928
- return false;
929
- }
930
- };
931
- var LanguageUtil = class {
932
- constructor(options) {
933
- this.options = options;
934
- this.supportedLngs = this.options.supportedLngs || false;
935
- this.logger = baseLogger.create("languageUtils");
936
- this.resolveHierarchyCache = {};
937
- }
938
- clearCache() {
939
- this.resolveHierarchyCache = {};
940
- }
941
- getScriptPartFromCode(code) {
942
- code = getCleanedCode(code);
943
- if (!code || !code.includes("-")) return null;
944
- const p = code.split("-");
945
- if (p.length === 2) return null;
946
- p.pop();
947
- if (p[p.length - 1].toLowerCase() === "x") return null;
948
- return this.formatLanguageCode(p.join("-"));
949
- }
950
- getLanguagePartFromCode(code) {
951
- code = getCleanedCode(code);
952
- if (!code || !code.includes("-")) return code;
953
- const p = code.split("-");
954
- return this.formatLanguageCode(p[0]);
955
- }
956
- formatLanguageCode(code) {
957
- if (isString(code) && code.includes("-")) {
958
- let formattedCode;
959
- try {
960
- formattedCode = Intl.getCanonicalLocales(code)[0];
961
- } catch (e) {
962
- }
963
- if (formattedCode && this.options.lowerCaseLng) {
964
- formattedCode = formattedCode.toLowerCase();
965
- }
966
- if (formattedCode) return formattedCode;
967
- if (this.options.lowerCaseLng) {
968
- return code.toLowerCase();
969
- }
970
- return code;
971
- }
972
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
973
- }
974
- isSupportedCode(code) {
975
- if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
976
- code = this.getLanguagePartFromCode(code);
977
- }
978
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.includes(code);
979
- }
980
- getBestMatchFromCodes(codes) {
981
- if (!codes) return null;
982
- let found;
983
- codes.forEach((code) => {
984
- if (found) return;
985
- const cleanedLng = this.formatLanguageCode(code);
986
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
987
- });
988
- if (!found && this.options.supportedLngs) {
989
- codes.forEach((code) => {
990
- if (found) return;
991
- const lngScOnly = this.getScriptPartFromCode(code);
992
- if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
993
- const lngOnly = this.getLanguagePartFromCode(code);
994
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
995
- found = this.options.supportedLngs.find((supportedLng) => {
996
- if (supportedLng === lngOnly) return true;
997
- if (!supportedLng.includes("-") && !lngOnly.includes("-")) return false;
998
- if (supportedLng.includes("-") && !lngOnly.includes("-") && supportedLng.slice(0, supportedLng.indexOf("-")) === lngOnly) return true;
999
- if (supportedLng.startsWith(lngOnly) && lngOnly.length > 1) return true;
1000
- return false;
1001
- });
1002
- });
1003
- }
1004
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1005
- return found;
1006
- }
1007
- getFallbackCodes(fallbacks, code) {
1008
- if (!fallbacks) return [];
1009
- if (typeof fallbacks === "function") fallbacks = fallbacks(code);
1010
- if (isString(fallbacks)) fallbacks = [fallbacks];
1011
- if (Array.isArray(fallbacks)) return fallbacks;
1012
- if (!code) return fallbacks.default || [];
1013
- let found = fallbacks[code];
1014
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1015
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
1016
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1017
- if (!found) found = fallbacks.default;
1018
- return found || [];
1019
- }
1020
- toResolveHierarchy(code, fallbackCode) {
1021
- const fallbackLng = this.options.fallbackLng;
1022
- const fallbackLngKey = Array.isArray(fallbackLng) ? fallbackLng.join("|") : fallbackLng;
1023
- if (fallbackLngKey !== this._cachedFallbackLng) {
1024
- this.resolveHierarchyCache = {};
1025
- this._cachedFallbackLng = fallbackLngKey;
1026
- }
1027
- const hasCacheableFallback = fallbackCode === void 0 || fallbackCode === false || isString(fallbackCode);
1028
- const usesUncacheableOptionsFallback = fallbackCode === void 0 && typeof this.options.fallbackLng === "function";
1029
- const cacheable = isString(code) && hasCacheableFallback && !usesUncacheableOptionsFallback;
1030
- let cacheKey = null;
1031
- if (cacheable) {
1032
- let fallbackCacheKey;
1033
- if (fallbackCode === void 0) fallbackCacheKey = "undefined";
1034
- else if (fallbackCode === false) fallbackCacheKey = "boolean:false";
1035
- else fallbackCacheKey = `string:${fallbackCode}`;
1036
- cacheKey = `${code.length}:${code}|${fallbackCacheKey}`;
1037
- }
1038
- if (cacheKey !== null) {
1039
- const cached = this.resolveHierarchyCache[cacheKey];
1040
- if (cached !== void 0) return cached.slice();
1041
- }
1042
- const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
1043
- const codes = [];
1044
- const addCode = (c) => {
1045
- if (!c) return;
1046
- if (this.isSupportedCode(c)) {
1047
- codes.push(c);
1048
- } else {
1049
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
1050
- }
1051
- };
1052
- if (isString(code) && (code.includes("-") || code.includes("_"))) {
1053
- if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
1054
- if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
1055
- if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
1056
- } else if (isString(code)) {
1057
- addCode(this.formatLanguageCode(code));
1058
- }
1059
- fallbackCodes.forEach((fc) => {
1060
- if (!codes.includes(fc)) addCode(this.formatLanguageCode(fc));
1061
- });
1062
- if (cacheKey !== null) {
1063
- this.resolveHierarchyCache[cacheKey] = codes;
1064
- return codes.slice();
1065
- }
1066
- return codes;
1067
- }
1068
- };
1069
- var suffixesOrder = {
1070
- zero: 0,
1071
- one: 1,
1072
- two: 2,
1073
- few: 3,
1074
- many: 4,
1075
- other: 5
1076
- };
1077
- var dummyRule = {
1078
- select: (count) => count === 1 ? "one" : "other",
1079
- resolvedOptions: () => ({
1080
- pluralCategories: ["one", "other"]
1081
- })
1082
- };
1083
- var PluralResolver = class {
1084
- constructor(languageUtils, options = {}) {
1085
- this.languageUtils = languageUtils;
1086
- this.options = options;
1087
- this.logger = baseLogger.create("pluralResolver");
1088
- this.pluralRulesCache = {};
1089
- }
1090
- clearCache() {
1091
- this.pluralRulesCache = {};
1092
- }
1093
- getRule(code, options = {}) {
1094
- const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
1095
- const type = options.ordinal ? "ordinal" : "cardinal";
1096
- const cacheKey = JSON.stringify({
1097
- cleanedCode,
1098
- type
1099
- });
1100
- if (cacheKey in this.pluralRulesCache) {
1101
- return this.pluralRulesCache[cacheKey];
1102
- }
1103
- let rule;
1104
- try {
1105
- rule = new Intl.PluralRules(cleanedCode, {
1106
- type
1107
- });
1108
- } catch (err) {
1109
- if (typeof Intl === "undefined") {
1110
- this.logger.error("No Intl support, please use an Intl polyfill!");
1111
- return dummyRule;
1112
- }
1113
- if (!code.match(/-|_/)) return dummyRule;
1114
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1115
- rule = this.getRule(lngPart, options);
1116
- }
1117
- this.pluralRulesCache[cacheKey] = rule;
1118
- return rule;
1119
- }
1120
- needsPlural(code, options = {}) {
1121
- let rule = this.getRule(code, options);
1122
- if (!rule) rule = this.getRule("dev", options);
1123
- return rule?.resolvedOptions().pluralCategories.length > 1;
1124
- }
1125
- getPluralFormsOfKey(code, key, options = {}) {
1126
- return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
1127
- }
1128
- getSuffixes(code, options = {}) {
1129
- let rule = this.getRule(code, options);
1130
- if (!rule) rule = this.getRule("dev", options);
1131
- if (!rule) return [];
1132
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
1133
- }
1134
- getSuffix(code, count, options = {}) {
1135
- const rule = this.getRule(code, options);
1136
- if (rule) {
1137
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
1138
- }
1139
- this.logger.warn(`no plural rule found for: ${code}`);
1140
- return this.getSuffix("dev", count, options);
1141
- }
1142
- };
1143
- var deepFindWithDefaults = (data, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => {
1144
- let path = getPathWithDefaults(data, defaultData, key);
1145
- if (!path && ignoreJSONStructure && isString(key)) {
1146
- path = deepFind(data, key, keySeparator);
1147
- if (path === void 0) path = deepFind(defaultData, key, keySeparator);
1148
- }
1149
- return path;
1150
- };
1151
- var regexSafe = (val) => val.replace(/\$/g, "$$$$");
1152
- var Interpolator = class {
1153
- constructor(options = {}) {
1154
- this.logger = baseLogger.create("interpolator");
1155
- this.options = options;
1156
- this.format = options?.interpolation?.format || ((value) => value);
1157
- this.init(options);
1158
- }
1159
- init(options = {}) {
1160
- if (!options.interpolation) options.interpolation = {
1161
- escapeValue: true
1162
- };
1163
- const {
1164
- escape: escape$1,
1165
- escapeValue,
1166
- useRawValueToEscape,
1167
- prefix,
1168
- prefixEscaped,
1169
- suffix,
1170
- suffixEscaped,
1171
- formatSeparator,
1172
- unescapeSuffix,
1173
- unescapePrefix,
1174
- nestingPrefix,
1175
- nestingPrefixEscaped,
1176
- nestingSuffix,
1177
- nestingSuffixEscaped,
1178
- nestingOptionsSeparator,
1179
- maxReplaces,
1180
- alwaysFormat
1181
- } = options.interpolation;
1182
- this.escape = escape$1 !== void 0 ? escape$1 : escape;
1183
- this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
1184
- this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
1185
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
1186
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
1187
- this.formatSeparator = formatSeparator || ",";
1188
- this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix ? regexEscape(unescapePrefix) : "-";
1189
- this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix ? regexEscape(unescapeSuffix) : "";
1190
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
1191
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
1192
- this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
1193
- this.maxReplaces = maxReplaces || 1e3;
1194
- this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
1195
- this.resetRegExp();
1196
- }
1197
- reset() {
1198
- if (this.options) this.init(this.options);
1199
- }
1200
- resetRegExp() {
1201
- const getOrResetRegExp = (existingRegExp, pattern) => {
1202
- if (existingRegExp?.source === pattern) {
1203
- existingRegExp.lastIndex = 0;
1204
- return existingRegExp;
1205
- }
1206
- return new RegExp(pattern, "g");
1207
- };
1208
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1209
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1210
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1211
- }
1212
- interpolate(str, data, lng, options) {
1213
- let match;
1214
- let value;
1215
- let replaces;
1216
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1217
- const handleFormat = (key) => {
1218
- if (!key.includes(this.formatSeparator)) {
1219
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1220
- return this.alwaysFormat ? this.format(path, void 0, lng, {
1221
- ...options,
1222
- ...data,
1223
- interpolationkey: key
1224
- }) : path;
1225
- }
1226
- const p = key.split(this.formatSeparator);
1227
- const k = p.shift().trim();
1228
- const f = p.join(this.formatSeparator).trim();
1229
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1230
- ...options,
1231
- ...data,
1232
- interpolationkey: k
1233
- });
1234
- };
1235
- this.resetRegExp();
1236
- if (!this.escapeValue && typeof str === "string" && /\$t\([^)]*\{[^}]*\{\{/.test(str)) {
1237
- this.logger.warn("nesting options string contains interpolated variables with escapeValue: false \u2014 if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");
1238
- }
1239
- const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1240
- const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1241
- const todos = [{
1242
- regex: this.regexpUnescape,
1243
- safeValue: (val) => val
1244
- }, {
1245
- regex: this.regexp,
1246
- safeValue: (val) => this.escapeValue ? this.escape(val) : val
1247
- }];
1248
- todos.forEach((todo) => {
1249
- replaces = 0;
1250
- while (match = todo.regex.exec(str)) {
1251
- const matchedVar = match[1].trim();
1252
- value = handleFormat(matchedVar);
1253
- if (value === void 0) {
1254
- if (typeof missingInterpolationHandler === "function") {
1255
- const temp = missingInterpolationHandler(str, match, options);
1256
- value = isString(temp) ? temp : "";
1257
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1258
- value = "";
1259
- } else if (skipOnVariables) {
1260
- value = match[0];
1261
- continue;
1262
- } else {
1263
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1264
- value = "";
1265
- }
1266
- } else if (!isString(value) && !this.useRawValueToEscape) {
1267
- value = makeString(value);
1268
- }
1269
- const safeValue = todo.safeValue(value);
1270
- str = str.replace(match[0], regexSafe(safeValue));
1271
- if (skipOnVariables) {
1272
- todo.regex.lastIndex += safeValue.length;
1273
- todo.regex.lastIndex -= match[0].length;
1274
- } else {
1275
- todo.regex.lastIndex = 0;
1276
- }
1277
- replaces++;
1278
- if (replaces >= this.maxReplaces) {
1279
- break;
1280
- }
1281
- }
1282
- });
1283
- return str;
1284
- }
1285
- nest(str, fc, options = {}) {
1286
- let match;
1287
- let value;
1288
- let clonedOptions;
1289
- const handleHasOptions = (key, inheritedOptions) => {
1290
- const sep = this.nestingOptionsSeparator;
1291
- if (!key.includes(sep)) return key;
1292
- const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`));
1293
- let optionsString = `{${c[1]}`;
1294
- key = c[0];
1295
- optionsString = this.interpolate(optionsString, clonedOptions);
1296
- const matchedSingleQuotes = optionsString.match(/'/g);
1297
- const matchedDoubleQuotes = optionsString.match(/"/g);
1298
- if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) {
1299
- optionsString = optionsString.replace(/'/g, '"');
1300
- }
1301
- try {
1302
- clonedOptions = JSON.parse(optionsString);
1303
- if (inheritedOptions) clonedOptions = {
1304
- ...inheritedOptions,
1305
- ...clonedOptions
1306
- };
1307
- } catch (e) {
1308
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1309
- return `${key}${sep}${optionsString}`;
1310
- }
1311
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.includes(this.prefix)) delete clonedOptions.defaultValue;
1312
- return key;
1313
- };
1314
- while (match = this.nestingRegexp.exec(str)) {
1315
- let formatters = [];
1316
- clonedOptions = {
1317
- ...options
1318
- };
1319
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1320
- clonedOptions.applyPostProcessor = false;
1321
- delete clonedOptions.defaultValue;
1322
- const keyEndIndex = /{.*}/s.test(match[1]) ? match[1].lastIndexOf("}") + 1 : match[1].indexOf(this.formatSeparator);
1323
- if (keyEndIndex !== -1) {
1324
- formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean);
1325
- match[1] = match[1].slice(0, keyEndIndex);
1326
- }
1327
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1328
- if (value && match[0] === str && !isString(value)) return value;
1329
- if (!isString(value)) value = makeString(value);
1330
- if (!value) {
1331
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1332
- value = "";
1333
- }
1334
- if (formatters.length) {
1335
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1336
- ...options,
1337
- interpolationkey: match[1].trim()
1338
- }), value.trim());
1339
- }
1340
- str = str.replace(match[0], regexSafe(makeString(value)));
1341
- this.regexp.lastIndex = 0;
1342
- }
1343
- return str;
1344
- }
1345
- };
1346
- var parseFormatStr = (formatStr) => {
1347
- let formatName = formatStr.toLowerCase().trim();
1348
- const formatOptions = {};
1349
- if (formatStr.includes("(")) {
1350
- const p = formatStr.split("(");
1351
- formatName = p[0].toLowerCase().trim();
1352
- const optStr = p[1].slice(0, -1);
1353
- if (formatName === "currency" && !optStr.includes(":")) {
1354
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1355
- } else if (formatName === "relativetime" && !optStr.includes(":")) {
1356
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1357
- } else {
1358
- const opts = optStr.split(";");
1359
- opts.forEach((opt) => {
1360
- if (opt) {
1361
- const [key, ...rest] = opt.split(":");
1362
- const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
1363
- const trimmedKey = key.trim();
1364
- if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1365
- if (val === "false") formatOptions[trimmedKey] = false;
1366
- if (val === "true") formatOptions[trimmedKey] = true;
1367
- if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1368
- }
1369
- });
1370
- }
1371
- }
1372
- return {
1373
- formatName,
1374
- formatOptions
1375
- };
1376
- };
1377
- var createCachedFormatter = (fn) => {
1378
- const cache = {};
1379
- return (v, l, o) => {
1380
- let optForCache = o;
1381
- if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
1382
- optForCache = {
1383
- ...optForCache,
1384
- [o.interpolationkey]: void 0
1385
- };
1386
- }
1387
- const key = l + JSON.stringify(optForCache);
1388
- let frm = cache[key];
1389
- if (!frm) {
1390
- frm = fn(getCleanedCode(l), o);
1391
- cache[key] = frm;
1392
- }
1393
- return frm(v);
1394
- };
1395
- };
1396
- var createNonCachedFormatter = (fn) => (v, l, o) => fn(getCleanedCode(l), o)(v);
1397
- var Formatter = class {
1398
- constructor(options = {}) {
1399
- this.logger = baseLogger.create("formatter");
1400
- this.options = options;
1401
- this.init(options);
1402
- }
1403
- init(services, options = {
1404
- interpolation: {}
1405
- }) {
1406
- this.formatSeparator = options.interpolation.formatSeparator || ",";
1407
- const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1408
- this.formats = {
1409
- number: cf((lng, opt) => {
1410
- const formatter = new Intl.NumberFormat(lng, {
1411
- ...opt
1412
- });
1413
- return (val) => formatter.format(val);
1414
- }),
1415
- currency: cf((lng, opt) => {
1416
- const formatter = new Intl.NumberFormat(lng, {
1417
- ...opt,
1418
- style: "currency"
1419
- });
1420
- return (val) => formatter.format(val);
1421
- }),
1422
- datetime: cf((lng, opt) => {
1423
- const formatter = new Intl.DateTimeFormat(lng, {
1424
- ...opt
1425
- });
1426
- return (val) => formatter.format(val);
1427
- }),
1428
- relativetime: cf((lng, opt) => {
1429
- const formatter = new Intl.RelativeTimeFormat(lng, {
1430
- ...opt
1431
- });
1432
- return (val) => formatter.format(val, opt.range || "day");
1433
- }),
1434
- list: cf((lng, opt) => {
1435
- const formatter = new Intl.ListFormat(lng, {
1436
- ...opt
1437
- });
1438
- return (val) => formatter.format(val);
1439
- })
1440
- };
1441
- }
1442
- add(name, fc) {
1443
- this.formats[name.toLowerCase().trim()] = fc;
1444
- }
1445
- addCached(name, fc) {
1446
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1447
- }
1448
- format(value, format, lng, options = {}) {
1449
- if (!format) return value;
1450
- if (value == null) return value;
1451
- const rawFormats = format.split(this.formatSeparator);
1452
- const formats = [];
1453
- for (let i = 0; i < rawFormats.length; i++) {
1454
- let f = rawFormats[i];
1455
- while (f.indexOf("(") > -1 && !f.includes(")") && i + 1 < rawFormats.length) {
1456
- f = `${f}${this.formatSeparator}${rawFormats[++i]}`;
1457
- }
1458
- formats.push(f);
1459
- }
1460
- const result = formats.reduce((mem, f) => {
1461
- const {
1462
- formatName,
1463
- formatOptions
1464
- } = parseFormatStr(f);
1465
- if (this.formats[formatName]) {
1466
- let formatted = mem;
1467
- try {
1468
- const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1469
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1470
- formatted = this.formats[formatName](mem, l, {
1471
- ...formatOptions,
1472
- ...options,
1473
- ...valOptions
1474
- });
1475
- } catch (error) {
1476
- this.logger.warn(error);
1477
- }
1478
- return formatted;
1479
- } else {
1480
- this.logger.warn(`there was no format function for ${formatName}`);
1481
- }
1482
- return mem;
1483
- }, value);
1484
- return result;
1485
- }
1486
- };
1487
- var removePending = (q, name) => {
1488
- if (q.pending[name] !== void 0) {
1489
- delete q.pending[name];
1490
- q.pendingCount--;
1491
- }
1492
- };
1493
- var Connector = class extends EventEmitter {
1494
- constructor(backend, store, services, options = {}) {
1495
- super();
1496
- this.backend = backend;
1497
- this.store = store;
1498
- this.services = services;
1499
- this.languageUtils = services.languageUtils;
1500
- this.options = options;
1501
- this.logger = baseLogger.create("backendConnector");
1502
- this.waitingReads = [];
1503
- this.maxParallelReads = options.maxParallelReads || 10;
1504
- this.readingCalls = 0;
1505
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1506
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1507
- this.state = {};
1508
- this.queue = [];
1509
- this.backend?.init?.(services, options.backend, options);
1510
- }
1511
- queueLoad(languages, namespaces, options, callback) {
1512
- const toLoad = {};
1513
- const pending = {};
1514
- const toLoadLanguages = {};
1515
- const toLoadNamespaces = {};
1516
- languages.forEach((lng) => {
1517
- let hasAllNamespaces = true;
1518
- namespaces.forEach((ns) => {
1519
- const name = `${lng}|${ns}`;
1520
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1521
- this.state[name] = 2;
1522
- } else if (this.state[name] < 0) ;
1523
- else if (this.state[name] === 1) {
1524
- if (pending[name] === void 0) pending[name] = true;
1525
- } else {
1526
- this.state[name] = 1;
1527
- hasAllNamespaces = false;
1528
- if (pending[name] === void 0) pending[name] = true;
1529
- if (toLoad[name] === void 0) toLoad[name] = true;
1530
- if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true;
1531
- }
1532
- });
1533
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1534
- });
1535
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1536
- this.queue.push({
1537
- pending,
1538
- pendingCount: Object.keys(pending).length,
1539
- loaded: {},
1540
- errors: [],
1541
- callback
1542
- });
1543
- }
1544
- return {
1545
- toLoad: Object.keys(toLoad),
1546
- pending: Object.keys(pending),
1547
- toLoadLanguages: Object.keys(toLoadLanguages),
1548
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1549
- };
1550
- }
1551
- loaded(name, err, data) {
1552
- const s = name.split("|");
1553
- const lng = s[0];
1554
- const ns = s[1];
1555
- if (err) this.emit("failedLoading", lng, ns, err);
1556
- if (!err && data) {
1557
- this.store.addResourceBundle(lng, ns, data, void 0, void 0, {
1558
- skipCopy: true
1559
- });
1560
- }
1561
- this.state[name] = err ? -1 : 2;
1562
- if (err && data) this.state[name] = 0;
1563
- const loaded = {};
1564
- this.queue.forEach((q) => {
1565
- pushPath(q.loaded, [lng], ns);
1566
- removePending(q, name);
1567
- if (err) q.errors.push(err);
1568
- if (q.pendingCount === 0 && !q.done) {
1569
- Object.keys(q.loaded).forEach((l) => {
1570
- if (!loaded[l]) loaded[l] = {};
1571
- const loadedKeys = q.loaded[l];
1572
- if (loadedKeys.length) {
1573
- loadedKeys.forEach((n) => {
1574
- if (loaded[l][n] === void 0) loaded[l][n] = true;
1575
- });
1576
- }
1577
- });
1578
- q.done = true;
1579
- if (q.errors.length) {
1580
- q.callback(q.errors);
1581
- } else {
1582
- q.callback();
1583
- }
1584
- }
1585
- });
1586
- this.emit("loaded", loaded);
1587
- this.queue = this.queue.filter((q) => !q.done);
1588
- }
1589
- read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1590
- if (!lng.length) return callback(null, {});
1591
- if (this.readingCalls >= this.maxParallelReads) {
1592
- this.waitingReads.push({
1593
- lng,
1594
- ns,
1595
- fcName,
1596
- tried,
1597
- wait,
1598
- callback
1599
- });
1600
- return;
1601
- }
1602
- this.readingCalls++;
1603
- const resolver = (err, data) => {
1604
- this.readingCalls--;
1605
- if (this.waitingReads.length > 0) {
1606
- const next = this.waitingReads.shift();
1607
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1608
- }
1609
- if (err && data && tried < this.maxRetries) {
1610
- setTimeout(() => {
1611
- this.read(lng, ns, fcName, tried + 1, wait * 2, callback);
1612
- }, wait);
1613
- return;
1614
- }
1615
- callback(err, data);
1616
- };
1617
- const fc = this.backend[fcName].bind(this.backend);
1618
- if (fc.length === 2) {
1619
- try {
1620
- const r = fc(lng, ns);
1621
- if (r && typeof r.then === "function") {
1622
- r.then((data) => resolver(null, data)).catch(resolver);
1623
- } else {
1624
- resolver(null, r);
1625
- }
1626
- } catch (err) {
1627
- resolver(err);
1628
- }
1629
- return;
1630
- }
1631
- return fc(lng, ns, resolver);
1632
- }
1633
- prepareLoading(languages, namespaces, options = {}, callback) {
1634
- if (!this.backend) {
1635
- this.logger.warn("No backend was added via i18next.use. Will not load resources.");
1636
- return callback && callback();
1637
- }
1638
- if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1639
- if (isString(namespaces)) namespaces = [namespaces];
1640
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
1641
- if (!toLoad.toLoad.length) {
1642
- if (!toLoad.pending.length) callback();
1643
- return null;
1644
- }
1645
- toLoad.toLoad.forEach((name) => {
1646
- this.loadOne(name);
1647
- });
1648
- }
1649
- load(languages, namespaces, callback) {
1650
- this.prepareLoading(languages, namespaces, {}, callback);
1651
- }
1652
- reload(languages, namespaces, callback) {
1653
- this.prepareLoading(languages, namespaces, {
1654
- reload: true
1655
- }, callback);
1656
- }
1657
- loadOne(name, prefix = "") {
1658
- const s = name.split("|");
1659
- const lng = s[0];
1660
- const ns = s[1];
1661
- this.read(lng, ns, "read", void 0, void 0, (err, data) => {
1662
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1663
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1664
- this.loaded(name, err, data);
1665
- });
1666
- }
1667
- saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {
1668
- }) {
1669
- if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1670
- this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
1671
- return;
1672
- }
1673
- if (key === void 0 || key === null || key === "") return;
1674
- if (this.backend?.create) {
1675
- const opts = {
1676
- ...options,
1677
- isUpdate
1678
- };
1679
- const fc = this.backend.create.bind(this.backend);
1680
- if (fc.length < 6) {
1681
- try {
1682
- let r;
1683
- if (fc.length === 5) {
1684
- r = fc(languages, namespace, key, fallbackValue, opts);
1685
- } else {
1686
- r = fc(languages, namespace, key, fallbackValue);
1687
- }
1688
- if (r && typeof r.then === "function") {
1689
- r.then((data) => clb(null, data)).catch(clb);
1690
- } else {
1691
- clb(null, r);
1692
- }
1693
- } catch (err) {
1694
- clb(err);
1695
- }
1696
- } else {
1697
- fc(languages, namespace, key, fallbackValue, clb, opts);
1698
- }
1699
- }
1700
- if (!languages || !languages[0]) return;
1701
- this.store.addResource(languages[0], namespace, key, fallbackValue);
1702
- }
1703
- };
1704
- var get = () => ({
1705
- debug: false,
1706
- initAsync: true,
1707
- ns: ["translation"],
1708
- defaultNS: ["translation"],
1709
- fallbackLng: ["dev"],
1710
- fallbackNS: false,
1711
- supportedLngs: false,
1712
- nonExplicitSupportedLngs: false,
1713
- load: "all",
1714
- preload: false,
1715
- keySeparator: ".",
1716
- nsSeparator: ":",
1717
- pluralSeparator: "_",
1718
- contextSeparator: "_",
1719
- enableSelector: false,
1720
- partialBundledLanguages: false,
1721
- saveMissing: false,
1722
- updateMissing: false,
1723
- saveMissingTo: "fallback",
1724
- saveMissingPlurals: true,
1725
- missingKeyHandler: false,
1726
- missingInterpolationHandler: false,
1727
- postProcess: false,
1728
- postProcessPassResolved: false,
1729
- returnNull: false,
1730
- returnEmptyString: true,
1731
- returnObjects: false,
1732
- joinArrays: false,
1733
- returnedObjectHandler: false,
1734
- parseMissingKeyHandler: false,
1735
- appendNamespaceToMissingKey: false,
1736
- appendNamespaceToCIMode: false,
1737
- overloadTranslationOptionHandler: (args) => {
1738
- let ret = {};
1739
- if (typeof args[1] === "object") ret = args[1];
1740
- if (isString(args[1])) ret.defaultValue = args[1];
1741
- if (isString(args[2])) ret.tDescription = args[2];
1742
- if (typeof args[2] === "object" || typeof args[3] === "object") {
1743
- const options = args[3] || args[2];
1744
- Object.keys(options).forEach((key) => {
1745
- ret[key] = options[key];
1746
- });
1747
- }
1748
- return ret;
1749
- },
1750
- interpolation: {
1751
- escapeValue: true,
1752
- prefix: "{{",
1753
- suffix: "}}",
1754
- formatSeparator: ",",
1755
- unescapePrefix: "-",
1756
- nestingPrefix: "$t(",
1757
- nestingSuffix: ")",
1758
- nestingOptionsSeparator: ",",
1759
- maxReplaces: 1e3,
1760
- skipOnVariables: true
1761
- },
1762
- cacheInBuiltFormats: true
1763
- });
1764
- var transformOptions = (options) => {
1765
- if (isString(options.ns)) options.ns = [options.ns];
1766
- if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1767
- if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1768
- if (options.supportedLngs && !options.supportedLngs.includes("cimode")) {
1769
- options.supportedLngs = options.supportedLngs.concat(["cimode"]);
1770
- }
1771
- return options;
1772
- };
1773
- var noop = () => {
1774
- };
1775
- var bindMemberFunctions = (inst) => {
1776
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1777
- mems.forEach((mem) => {
1778
- if (typeof inst[mem] === "function") {
1779
- inst[mem] = inst[mem].bind(inst);
1780
- }
1781
- });
1782
- };
1783
- var I18n = class _I18n extends EventEmitter {
1784
- constructor(options = {}, callback) {
1785
- super();
1786
- this.options = transformOptions(options);
1787
- this.services = {};
1788
- this.logger = baseLogger;
1789
- this.modules = {
1790
- external: []
1791
- };
1792
- bindMemberFunctions(this);
1793
- if (callback && !this.isInitialized && !options.isClone) {
1794
- if (!this.options.initAsync) {
1795
- this.init(options, callback);
1796
- return this;
1797
- }
1798
- setTimeout(() => {
1799
- this.init(options, callback);
1800
- }, 0);
1801
- }
1802
- }
1803
- init(options = {}, callback) {
1804
- this.isInitializing = true;
1805
- if (typeof options === "function") {
1806
- callback = options;
1807
- options = {};
1808
- }
1809
- if (options.defaultNS == null && options.ns) {
1810
- if (isString(options.ns)) {
1811
- options.defaultNS = options.ns;
1812
- } else if (!options.ns.includes("translation")) {
1813
- options.defaultNS = options.ns[0];
1814
- }
1815
- }
1816
- const defOpts = get();
1817
- this.options = {
1818
- ...defOpts,
1819
- ...this.options,
1820
- ...transformOptions(options)
1821
- };
1822
- this.options.interpolation = {
1823
- ...defOpts.interpolation,
1824
- ...this.options.interpolation
1825
- };
1826
- if (options.keySeparator !== void 0) {
1827
- this.options.userDefinedKeySeparator = options.keySeparator;
1828
- }
1829
- if (options.nsSeparator !== void 0) {
1830
- this.options.userDefinedNsSeparator = options.nsSeparator;
1831
- }
1832
- if (typeof this.options.overloadTranslationOptionHandler !== "function") {
1833
- this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;
1834
- }
1835
- const createClassOnDemand = (ClassOrObject) => {
1836
- if (!ClassOrObject) return null;
1837
- if (typeof ClassOrObject === "function") return new ClassOrObject();
1838
- return ClassOrObject;
1839
- };
1840
- if (!this.options.isClone) {
1841
- if (this.modules.logger) {
1842
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1843
- } else {
1844
- baseLogger.init(null, this.options);
1845
- }
1846
- let formatter;
1847
- if (this.modules.formatter) {
1848
- formatter = this.modules.formatter;
1849
- } else {
1850
- formatter = Formatter;
1851
- }
1852
- const lu = new LanguageUtil(this.options);
1853
- this.store = new ResourceStore(this.options.resources, this.options);
1854
- const s = this.services;
1855
- s.logger = baseLogger;
1856
- s.resourceStore = this.store;
1857
- s.languageUtils = lu;
1858
- s.pluralResolver = new PluralResolver(lu, {
1859
- prepend: this.options.pluralSeparator
1860
- });
1861
- if (formatter) {
1862
- s.formatter = createClassOnDemand(formatter);
1863
- if (s.formatter.init) s.formatter.init(s, this.options);
1864
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1865
- }
1866
- s.interpolator = new Interpolator(this.options);
1867
- s.utils = {
1868
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1869
- };
1870
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1871
- s.backendConnector.on("*", (event, ...args) => {
1872
- this.emit(event, ...args);
1873
- });
1874
- if (this.modules.languageDetector) {
1875
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1876
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1877
- }
1878
- if (this.modules.i18nFormat) {
1879
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1880
- if (s.i18nFormat.init) s.i18nFormat.init(this);
1881
- }
1882
- this.translator = new Translator(this.services, this.options);
1883
- this.translator.on("*", (event, ...args) => {
1884
- this.emit(event, ...args);
1885
- });
1886
- this.modules.external.forEach((m) => {
1887
- if (m.init) m.init(this);
1888
- });
1889
- }
1890
- this.format = this.options.interpolation.format;
1891
- if (!callback) callback = noop;
1892
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1893
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1894
- if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0];
1895
- }
1896
- if (!this.services.languageDetector && !this.options.lng) {
1897
- this.logger.warn("init: no languageDetector is used and no lng is defined");
1898
- }
1899
- const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
1900
- storeApi.forEach((fcName) => {
1901
- this[fcName] = (...args) => this.store[fcName](...args);
1902
- });
1903
- const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
1904
- storeApiChained.forEach((fcName) => {
1905
- this[fcName] = (...args) => {
1906
- this.store[fcName](...args);
1907
- return this;
1908
- };
1909
- });
1910
- const deferred = defer();
1911
- const load = () => {
1912
- const finish = (err, t2) => {
1913
- this.isInitializing = false;
1914
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!");
1915
- this.isInitialized = true;
1916
- if (!this.options.isClone) this.logger.log("initialized", this.options);
1917
- this.emit("initialized", this.options);
1918
- deferred.resolve(t2);
1919
- callback(err, t2);
1920
- };
1921
- if ((this.languages || this.isLanguageChangingTo) && !this.isInitialized) return finish(null, this.t.bind(this));
1922
- this.changeLanguage(this.options.lng, finish);
1923
- };
1924
- if (this.options.resources || !this.options.initAsync) {
1925
- load();
1926
- } else {
1927
- setTimeout(load, 0);
1928
- }
1929
- return deferred;
1930
- }
1931
- loadResources(language, callback = noop) {
1932
- let usedCallback = callback;
1933
- const usedLng = isString(language) ? language : this.language;
1934
- if (typeof language === "function") usedCallback = language;
1935
- if (!this.options.resources || this.options.partialBundledLanguages) {
1936
- if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1937
- const toLoad = [];
1938
- const append = (lng) => {
1939
- if (!lng) return;
1940
- if (lng === "cimode") return;
1941
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1942
- lngs.forEach((l) => {
1943
- if (l === "cimode") return;
1944
- if (!toLoad.includes(l)) toLoad.push(l);
1945
- });
1946
- };
1947
- if (!usedLng) {
1948
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1949
- fallbacks.forEach((l) => append(l));
1950
- } else {
1951
- append(usedLng);
1952
- }
1953
- this.options.preload?.forEach?.((l) => append(l));
1954
- this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
1955
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1956
- usedCallback(e);
1957
- });
1958
- } else {
1959
- usedCallback(null);
1960
- }
1961
- }
1962
- reloadResources(lngs, ns, callback) {
1963
- const deferred = defer();
1964
- if (typeof lngs === "function") {
1965
- callback = lngs;
1966
- lngs = void 0;
1967
- }
1968
- if (typeof ns === "function") {
1969
- callback = ns;
1970
- ns = void 0;
1971
- }
1972
- if (!lngs) lngs = this.languages;
1973
- if (!ns) ns = this.options.ns;
1974
- if (!callback) callback = noop;
1975
- this.services.backendConnector.reload(lngs, ns, (err) => {
1976
- deferred.resolve();
1977
- callback(err);
1978
- });
1979
- return deferred;
1980
- }
1981
- use(module) {
1982
- if (!module) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
1983
- if (!module.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
1984
- if (module.type === "backend") {
1985
- this.modules.backend = module;
1986
- }
1987
- if (module.type === "logger" || module.log && module.warn && module.error) {
1988
- this.modules.logger = module;
1989
- }
1990
- if (module.type === "languageDetector") {
1991
- this.modules.languageDetector = module;
1992
- }
1993
- if (module.type === "i18nFormat") {
1994
- this.modules.i18nFormat = module;
1995
- }
1996
- if (module.type === "postProcessor") {
1997
- postProcessor.addPostProcessor(module);
1998
- }
1999
- if (module.type === "formatter") {
2000
- this.modules.formatter = module;
2001
- }
2002
- if (module.type === "3rdParty") {
2003
- this.modules.external.push(module);
2004
- }
2005
- return this;
2006
- }
2007
- setResolvedLanguage(l) {
2008
- if (!l || !this.languages) return;
2009
- if (["cimode", "dev"].includes(l)) return;
2010
- for (let li = 0; li < this.languages.length; li++) {
2011
- const lngInLngs = this.languages[li];
2012
- if (["cimode", "dev"].includes(lngInLngs)) continue;
2013
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2014
- this.resolvedLanguage = lngInLngs;
2015
- break;
2016
- }
2017
- }
2018
- if (!this.resolvedLanguage && !this.languages.includes(l) && this.store.hasLanguageSomeTranslations(l)) {
2019
- this.resolvedLanguage = l;
2020
- this.languages.unshift(l);
2021
- }
2022
- }
2023
- changeLanguage(lng, callback) {
2024
- this.isLanguageChangingTo = lng;
2025
- const deferred = defer();
2026
- this.emit("languageChanging", lng);
2027
- const setLngProps = (l) => {
2028
- this.language = l;
2029
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
2030
- this.resolvedLanguage = void 0;
2031
- this.setResolvedLanguage(l);
2032
- };
2033
- const done = (err, l) => {
2034
- if (l) {
2035
- if (this.isLanguageChangingTo === lng) {
2036
- setLngProps(l);
2037
- this.translator.changeLanguage(l);
2038
- this.isLanguageChangingTo = void 0;
2039
- this.emit("languageChanged", l);
2040
- this.logger.log("languageChanged", l);
2041
- }
2042
- } else {
2043
- this.isLanguageChangingTo = void 0;
2044
- }
2045
- deferred.resolve((...args) => this.t(...args));
2046
- if (callback) callback(err, (...args) => this.t(...args));
2047
- };
2048
- const setLng = (lngs) => {
2049
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
2050
- const fl = isString(lngs) ? lngs : lngs && lngs[0];
2051
- const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
2052
- if (l) {
2053
- if (!this.language) {
2054
- setLngProps(l);
2055
- }
2056
- if (!this.translator.language) this.translator.changeLanguage(l);
2057
- this.services.languageDetector?.cacheUserLanguage?.(l);
2058
- }
2059
- this.loadResources(l, (err) => {
2060
- done(err, l);
2061
- });
2062
- };
2063
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2064
- setLng(this.services.languageDetector.detect());
2065
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2066
- if (this.services.languageDetector.detect.length === 0) {
2067
- this.services.languageDetector.detect().then(setLng);
2068
- } else {
2069
- this.services.languageDetector.detect(setLng);
2070
- }
2071
- } else {
2072
- setLng(lng);
2073
- }
2074
- return deferred;
2075
- }
2076
- getFixedT(lng, ns, keyPrefix, fixedOpts) {
2077
- const scopeNs = fixedOpts?.scopeNs;
2078
- const fixedT = (key, opts, ...rest) => {
2079
- let o;
2080
- if (typeof opts !== "object") {
2081
- o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2082
- } else {
2083
- o = {
2084
- ...opts
2085
- };
2086
- }
2087
- o.lng = o.lng || fixedT.lng;
2088
- o.lngs = o.lngs || fixedT.lngs;
2089
- const explicitCallNs = o.ns !== void 0 && o.ns !== null;
2090
- o.ns = o.ns || fixedT.ns;
2091
- if (o.keyPrefix !== "") o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2092
- const selectorOpts = {
2093
- ...this.options,
2094
- ...o
2095
- };
2096
- if (Array.isArray(scopeNs) && !explicitCallNs) selectorOpts.ns = scopeNs;
2097
- if (typeof o.keyPrefix === "function") o.keyPrefix = keysFromSelector(o.keyPrefix, selectorOpts);
2098
- const keySeparator = this.options.keySeparator || ".";
2099
- let resultKey;
2100
- if (o.keyPrefix && Array.isArray(key)) {
2101
- resultKey = key.map((k) => {
2102
- if (typeof k === "function") k = keysFromSelector(k, selectorOpts);
2103
- return `${o.keyPrefix}${keySeparator}${k}`;
2104
- });
2105
- } else {
2106
- if (typeof key === "function") key = keysFromSelector(key, selectorOpts);
2107
- resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2108
- }
2109
- return this.t(resultKey, o);
2110
- };
2111
- if (isString(lng)) {
2112
- fixedT.lng = lng;
2113
- } else {
2114
- fixedT.lngs = lng;
2115
- }
2116
- fixedT.ns = ns;
2117
- fixedT.keyPrefix = keyPrefix;
2118
- return fixedT;
2119
- }
2120
- t(...args) {
2121
- return this.translator?.translate(...args);
2122
- }
2123
- exists(...args) {
2124
- return this.translator?.exists(...args);
2125
- }
2126
- setDefaultNamespace(ns) {
2127
- this.options.defaultNS = ns;
2128
- }
2129
- hasLoadedNamespace(ns, options = {}) {
2130
- if (!this.isInitialized) {
2131
- this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
2132
- return false;
2133
- }
2134
- if (!this.languages || !this.languages.length) {
2135
- this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
2136
- return false;
2137
- }
2138
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
2139
- const fallbackLng = this.options ? this.options.fallbackLng : false;
2140
- const lastLng = this.languages[this.languages.length - 1];
2141
- if (lng.toLowerCase() === "cimode") return true;
2142
- const loadNotPending = (l, n) => {
2143
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
2144
- return loadState === -1 || loadState === 0 || loadState === 2;
2145
- };
2146
- if (options.precheck) {
2147
- const preResult = options.precheck(this, loadNotPending);
2148
- if (preResult !== void 0) return preResult;
2149
- }
2150
- if (this.hasResourceBundle(lng, ns)) return true;
2151
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2152
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2153
- return false;
2154
- }
2155
- loadNamespaces(ns, callback) {
2156
- const deferred = defer();
2157
- if (!this.options.ns) {
2158
- if (callback) callback();
2159
- return Promise.resolve();
2160
- }
2161
- if (isString(ns)) ns = [ns];
2162
- ns.forEach((n) => {
2163
- if (!this.options.ns.includes(n)) this.options.ns.push(n);
2164
- });
2165
- this.loadResources((err) => {
2166
- deferred.resolve();
2167
- if (callback) callback(err);
2168
- });
2169
- return deferred;
2170
- }
2171
- loadLanguages(lngs, callback) {
2172
- const deferred = defer();
2173
- if (isString(lngs)) lngs = [lngs];
2174
- const preloaded = this.options.preload || [];
2175
- const newLngs = lngs.filter((lng) => !preloaded.includes(lng) && this.services.languageUtils.isSupportedCode(lng));
2176
- if (!newLngs.length) {
2177
- if (callback) callback();
2178
- return Promise.resolve();
2179
- }
2180
- this.options.preload = preloaded.concat(newLngs);
2181
- this.loadResources((err) => {
2182
- deferred.resolve();
2183
- if (callback) callback(err);
2184
- });
2185
- return deferred;
2186
- }
2187
- dir(lng) {
2188
- if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2189
- if (!lng) return "rtl";
2190
- try {
2191
- const l = new Intl.Locale(lng);
2192
- if (l && l.getTextInfo) {
2193
- const ti = l.getTextInfo();
2194
- if (ti && ti.direction) return ti.direction;
2195
- }
2196
- } catch (e) {
2197
- }
2198
- const rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"];
2199
- const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2200
- if (lng.toLowerCase().indexOf("-latn") > 1) return "ltr";
2201
- return rtlLngs.includes(languageUtils.getLanguagePartFromCode(lng)) || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
2202
- }
2203
- static createInstance(options = {}, callback) {
2204
- const instance2 = new _I18n(options, callback);
2205
- instance2.createInstance = _I18n.createInstance;
2206
- return instance2;
2207
- }
2208
- cloneInstance(options = {}, callback = noop) {
2209
- const forkResourceStore = options.forkResourceStore;
2210
- if (forkResourceStore) delete options.forkResourceStore;
2211
- const mergedOptions = {
2212
- ...this.options,
2213
- ...options,
2214
- ...{
2215
- isClone: true
2216
- }
2217
- };
2218
- const clone = new _I18n(mergedOptions);
2219
- if (options.debug !== void 0 || options.prefix !== void 0) {
2220
- clone.logger = clone.logger.clone(options);
2221
- }
2222
- const membersToCopy = ["store", "services", "language"];
2223
- membersToCopy.forEach((m) => {
2224
- clone[m] = this[m];
2225
- });
2226
- clone.services = {
2227
- ...this.services
2228
- };
2229
- clone.services.utils = {
2230
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2231
- };
2232
- if (forkResourceStore) {
2233
- const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2234
- prev[l] = {
2235
- ...this.store.data[l]
2236
- };
2237
- prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2238
- acc[n] = {
2239
- ...prev[l][n]
2240
- };
2241
- return acc;
2242
- }, prev[l]);
2243
- return prev;
2244
- }, {});
2245
- clone.store = new ResourceStore(clonedData, mergedOptions);
2246
- clone.services.resourceStore = clone.store;
2247
- }
2248
- if (options.interpolation) {
2249
- const defOpts = get();
2250
- const mergedInterpolation = {
2251
- ...defOpts.interpolation,
2252
- ...this.options.interpolation,
2253
- ...options.interpolation
2254
- };
2255
- const mergedForInterpolator = {
2256
- ...mergedOptions,
2257
- interpolation: mergedInterpolation
2258
- };
2259
- clone.services.interpolator = new Interpolator(mergedForInterpolator);
2260
- }
2261
- clone.translator = new Translator(clone.services, mergedOptions);
2262
- clone.translator.on("*", (event, ...args) => {
2263
- clone.emit(event, ...args);
2264
- });
2265
- clone.init(mergedOptions, callback);
2266
- clone.translator.options = mergedOptions;
2267
- clone.translator.backendConnector.services.utils = {
2268
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2269
- };
2270
- return clone;
2271
- }
2272
- toJSON() {
2273
- return {
2274
- options: this.options,
2275
- store: this.store,
2276
- language: this.language,
2277
- languages: this.languages,
2278
- resolvedLanguage: this.resolvedLanguage
2279
- };
2280
- }
2281
- };
2282
- var instance = I18n.createInstance();
2283
- var createInstance = instance.createInstance;
2284
- var dir = instance.dir;
2285
- var init = instance.init;
2286
- var loadResources = instance.loadResources;
2287
- var reloadResources = instance.reloadResources;
2288
- var use = instance.use;
2289
- var changeLanguage = instance.changeLanguage;
2290
- var getFixedT = instance.getFixedT;
2291
- var t = instance.t;
2292
- var exists = instance.exists;
2293
- var setDefaultNamespace = instance.setDefaultNamespace;
2294
- var hasLoadedNamespace = instance.hasLoadedNamespace;
2295
- var loadNamespaces = instance.loadNamespaces;
2296
- var loadLanguages = instance.loadLanguages;
2297
-
2298
- // src/i18n/config.ts
2299
- import { initReactI18next } from "react-i18next";
2300
-
2301
- // src/i18n/customCacheBackend.ts
2302
- var _SupabaseCacheBackend = class _SupabaseCacheBackend {
2303
- // 1. Принимаем SupabaseClient в конструктор
2304
- constructor(supabase) {
2305
- this.type = "backend";
2306
- this.supabase = supabase;
2307
- }
2308
- init(services, backendOptions, i18nextOptions) {
2309
- if (backendOptions?.supabase) {
2310
- this.supabase = backendOptions.supabase;
2311
- }
2312
- }
2313
- /**
2314
- * Загрузка всего манифеста версий из Supabase в память
2315
- */
2316
- async loadManifest() {
2317
- if (_SupabaseCacheBackend.isManifestLoaded || !this.supabase) return;
2318
- try {
2319
- const { data, error } = await this.supabase.from("translation_versions").select("namespace, lang_code, version");
2320
- if (error) {
2321
- if (error.code === "PGRST303" || error.message?.includes("future")) {
2322
- console.warn("[i18n] Time drift detected (JWT in future). Falling back to cached translations.");
2323
- }
2324
- throw error;
2325
- }
2326
- if (data) {
2327
- const manifestMap = {};
2328
- data.forEach((row) => {
2329
- manifestMap[`${row.lang_code}:${row.namespace}`] = row.version;
2330
- });
2331
- _SupabaseCacheBackend.manifest = manifestMap;
2332
- _SupabaseCacheBackend.isManifestLoaded = true;
2333
- }
2334
- } catch (err) {
2335
- console.warn("[i18n] Could not load translation versions manifest, using local cache:", err);
2336
- }
2337
- }
2338
- /**
2339
- * Основной метод чтения локализации
2340
- */
2341
- async read(language, namespace, callback) {
2342
- const cacheKey = `i18n_${language}_${namespace}`;
2343
- const versionKey = `i18n_ver_${language}_${namespace}`;
2344
- const manifestKey = `${language}:${namespace}`;
2345
- try {
2346
- await this.loadManifest();
2347
- const cachedData = localStorage.getItem(cacheKey);
2348
- const localVersion = parseInt(localStorage.getItem(versionKey) || "0", 10);
2349
- const serverVersion = _SupabaseCacheBackend.manifest[manifestKey];
2350
- if (cachedData && serverVersion !== void 0 && localVersion === serverVersion) {
2351
- callback(null, JSON.parse(cachedData));
2352
- return;
2353
- }
2354
- if (cachedData && !_SupabaseCacheBackend.isManifestLoaded) {
2355
- callback(null, JSON.parse(cachedData));
2356
- return;
2357
- }
2358
- if (!this.supabase) {
2359
- throw new Error("[SupabaseCacheBackend]: Supabase client is not initialized.");
2360
- }
2361
- const { data, error } = await this.supabase.from("translations").select("key, value").eq("lang_code", language).eq("namespace", namespace);
2362
- if (error) throw error;
2363
- const freshData = {};
2364
- if (data) {
2365
- data.forEach((row) => {
2366
- this.setNestedKey(freshData, row.key, row.value);
2367
- });
2368
- }
2369
- localStorage.setItem(cacheKey, JSON.stringify(freshData));
2370
- if (serverVersion !== void 0) {
2371
- localStorage.setItem(versionKey, serverVersion.toString());
2372
- }
2373
- callback(null, freshData);
2374
- } catch (err) {
2375
- console.warn(`[i18n] Fallback to cache for ${language}/${namespace} due to error:`, err);
2376
- const cachedData = localStorage.getItem(cacheKey);
2377
- if (cachedData) {
2378
- callback(null, JSON.parse(cachedData));
2379
- } else {
2380
- callback(err, false);
2381
- }
2382
- }
2383
- }
2384
- setNestedKey(obj, path, value) {
2385
- const keys = path.split(".");
2386
- let current = obj;
2387
- for (let i = 0; i < keys.length - 1; i++) {
2388
- const key = keys[i];
2389
- if (!current[key] || typeof current[key] !== "object") {
2390
- current[key] = {};
2391
- }
2392
- current = current[key];
2393
- }
2394
- current[keys[keys.length - 1]] = value;
2395
- }
2396
- create(languages, namespace, key, fallbackValue) {
2397
- }
2398
- };
2399
- _SupabaseCacheBackend.type = "backend";
2400
- // Локальный манифест версий
2401
- _SupabaseCacheBackend.manifest = {};
2402
- _SupabaseCacheBackend.isManifestLoaded = false;
2403
- var SupabaseCacheBackend = _SupabaseCacheBackend;
2404
-
2405
- // src/i18n/config.ts
2406
- var config_default = instance;
2407
-
2408
- // src/context/AuthProvider.tsx
2409
- import { createContext as createContext2, useContext as useContext2, useEffect, useState, useCallback, useRef } from "react";
2410
-
2411
- // src/context/SupabaseProvider.tsx
2412
- import { createContext, useContext, useMemo } from "react";
2413
- import { createClient } from "@supabase/supabase-js";
2414
- import { jsx } from "react/jsx-runtime";
2415
- var SupabaseContext = createContext(null);
2416
- var SupabaseProvider = ({
2417
- children,
2418
- client,
2419
- config
2420
- }) => {
2421
- const supabaseInstance = useMemo(() => {
2422
- if (client) return client;
2423
- if (config?.url && config?.anonKey) {
2424
- return createClient(config.url, config.anonKey);
2425
- }
2426
- throw new Error(
2427
- '[SupabaseProvider]: \u0412\u0430\u043C \u043D\u0443\u0436\u043D\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u0442\u044C \u043B\u0438\u0431\u043E prop "client", \u043B\u0438\u0431\u043E "config" ({ url, anonKey }).'
2428
- );
2429
- }, [client, config]);
2430
- return /* @__PURE__ */ jsx(SupabaseContext.Provider, { value: { supabase: supabaseInstance }, children });
2431
- };
2432
- var useSupabase = () => {
2433
- const context = useContext(SupabaseContext);
2434
- if (!context) {
2435
- throw new Error("useSupabase \u0434\u043E\u043B\u0436\u0435\u043D \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F \u0432\u043D\u0443\u0442\u0440\u0438 <SupabaseProvider>");
2436
- }
2437
- return context.supabase;
2438
- };
2439
-
2440
- // src/context/AuthProvider.tsx
2441
- import { jsx as jsx2 } from "react/jsx-runtime";
2442
- var AuthContext = createContext2(void 0);
2443
- var useAuth = () => {
2444
- const context = useContext2(AuthContext);
2445
- if (!context) {
2446
- throw new Error("useAuth should be used within the AuthProvider");
2447
- }
2448
- return context;
2449
- };
2450
-
2451
- // src/context/TranslationEditProvider.tsx
2452
- import { jsx as jsx3 } from "react/jsx-runtime";
2453
- var TranslationEditContext = createContext3(void 0);
2454
- var TranslationEditProvider = ({ children }) => {
2455
- const supabase = useSupabase();
2456
- const { user } = useAuth();
2457
- const [isTranslationMode, setIsTranslationMode] = useState2(false);
2458
- const [canEdit, setCanEdit] = useState2(false);
2459
- const [isLoadingPermissions, setIsLoadingPermissions] = useState2(true);
2460
- const checkPermission = useCallback2(async () => {
2461
- if (!user) {
2462
- setCanEdit(false);
2463
- setIsTranslationMode(false);
2464
- setIsLoadingPermissions(false);
2465
- return;
2466
- }
2467
- try {
2468
- setIsLoadingPermissions(true);
2469
- const { data, error } = await supabase.from("translation_responsible_users").select("id").eq("user_id", user.id).maybeSingle();
2470
- if (error) {
2471
- console.error("Error checking translation responsibilities:", error);
2472
- setCanEdit(false);
2473
- setIsTranslationMode(false);
2474
- } else {
2475
- const hasAccess = Boolean(data);
2476
- setCanEdit(hasAccess);
2477
- if (!hasAccess) {
2478
- setIsTranslationMode(false);
2479
- }
2480
- }
2481
- } catch (err) {
2482
- console.error("Permission check failed:", err);
2483
- setCanEdit(false);
2484
- } finally {
2485
- setIsLoadingPermissions(false);
2486
- }
2487
- }, [user]);
2488
- useEffect2(() => {
2489
- checkPermission();
2490
- }, [checkPermission]);
2491
- const updateTranslation = async (key, namespace, newValue) => {
2492
- if (!canEdit) return;
2493
- const currentLang = config_default.language;
2494
- const { error } = await supabase.from("translations").upsert({
2495
- key,
2496
- namespace,
2497
- lang_code: currentLang,
2498
- value: newValue
2499
- }, { onConflict: "key,namespace,lang_code" });
2500
- if (error) return alert("\u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u0432 \u0411\u0414");
2501
- localStorage.removeItem(`i18n_ver_${currentLang}_${namespace}`);
2502
- config_default.addResource(currentLang, namespace, key, newValue);
2503
- config_default.changeLanguage(currentLang);
2504
- };
2505
- const handleSetTranslationMode = (val) => {
2506
- if (canEdit) {
2507
- setIsTranslationMode(val);
2508
- }
2509
- };
2510
- return /* @__PURE__ */ jsx3(
2511
- TranslationEditContext.Provider,
2512
- {
2513
- value: {
2514
- isTranslationMode,
2515
- setIsTranslationMode: handleSetTranslationMode,
2516
- canEdit,
2517
- isLoadingPermissions,
2518
- updateTranslation
2519
- },
2520
- children
2521
- }
2522
- );
2523
- };
2524
- var useTranslationEdit = () => {
2525
- const context = useContext3(TranslationEditContext);
2526
- if (!context) throw new Error("useTranslationEdit must be used within TranslationEditProvider");
2527
- return context;
2528
- };
2529
-
2530
- // src/UI/components/inputs/TranslatableTooltip.tsx
2531
- import { jsx as jsx4 } from "react/jsx-runtime";
2532
- var TranslatableTooltip = ({
2533
- title,
2534
- disableSpan,
2535
- children,
2536
- ...props
2537
- }) => {
2538
- const { isTranslationMode } = useTranslationEdit();
2539
- return /* @__PURE__ */ jsx4(
2540
- Tooltip,
2541
- {
2542
- title,
2543
- slotProps: {
2544
- popper: {
2545
- sx: isTranslationMode ? {
2546
- pointerEvents: "auto",
2547
- // Разрешаем клики внутри тултипа
2548
- "& .MuiTooltip-tooltip": {
2549
- pointerEvents: "auto"
2550
- }
2551
- } : void 0
2552
- }
2553
- },
2554
- leaveDelay: isTranslationMode ? 1e3 : 100,
2555
- ...props,
2556
- children: disableSpan ? children : /* @__PURE__ */ jsx4("span", { children })
2557
- }
2558
- );
2559
- };
2560
-
2561
- // src/UI/components/inputs/TextfieldComponent.tsx
2562
- import { useTranslation as useTranslation2 } from "react-i18next";
2563
-
2564
- // src/services/translation.service.ts
2565
- var translationService = {
2566
- // 1. Принимаем client первым аргументом
2567
- incrementVersion: async (client, namespace, langCodes) => {
2568
- try {
2569
- const { data } = await client.from("translation_versions").select("version, lang_code").eq("namespace", namespace);
2570
- const currentVersion = data && data.length > 0 ? Math.max(...data.map((d) => d.version || 0)) : 0;
2571
- const nextVersion = currentVersion + 1;
2572
- const languagesToUpdate = langCodes && langCodes.length > 0 ? langCodes : ["uk"];
2573
- const updates = languagesToUpdate.map((lang_code) => ({
2574
- namespace,
2575
- lang_code,
2576
- version: nextVersion,
2577
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
2578
- }));
2579
- const { error } = await client.from("translation_versions").upsert(updates, { onConflict: "namespace,lang_code" });
2580
- if (error) console.error("Error updating translation version:", error);
2581
- return nextVersion;
2582
- } catch (err) {
2583
- console.error("Failed to increment version in Supabase:", err);
2584
- return null;
2585
- }
2586
- },
2587
- translateSmart: async (client, aiGenerateFn, params) => {
2588
- const languagesToTranslate = params.targetLangs || (params.targetLang ? [params.targetLang] : []);
2589
- try {
2590
- const { data, error } = await client.functions.invoke("translate-smart", { body: params });
2591
- if (!error && data) return data;
2592
- } catch {
2593
- console.warn("Edge Function translate-smart \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C AIProvider...");
2594
- }
2595
- if (aiGenerateFn) {
2596
- const prompt = `Translate the source text into language codes: ${JSON.stringify(languagesToTranslate)}.
2597
- Source Text: "${params.text}"
2598
- ${params.contextHint ? `Context Hint: "${params.contextHint}"` : ""}`;
2599
- const translations = await aiGenerateFn({
2600
- prompt,
2601
- systemInstruction: 'Respond STRICTLY with a valid JSON mapping lang code to text. Example: {"en": "Hello"}',
2602
- jsonMode: true
2603
- });
2604
- if (translations) {
2605
- if (params.targetLang) {
2606
- return { translatedText: translations[params.targetLang] || params.text };
2607
- }
2608
- return { translations };
2609
- }
2610
- }
2611
- if (params.targetLang) {
2612
- const fallbackUrl = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${params.targetLang}&dt=t&q=${encodeURIComponent(params.text)}`;
2613
- const res = await fetch(fallbackUrl);
2614
- if (res.ok) {
2615
- const data = await res.json();
2616
- return { translatedText: data[0].map((x) => x[0]).join("") };
2617
- }
2618
- }
2619
- throw new Error("All translation strategies failed.");
2620
- }
2621
- };
2622
-
2623
- // src/i18n/TranslateText.tsx
2624
- import { useState as useState4, useRef as useRef2, useEffect as useEffect4 } from "react";
2625
- import { useTranslation } from "react-i18next";
2626
- import { Box as Box2, Popper, Paper as Paper2, MenuList, MenuItem, ListItemIcon, ListItemText } from "@mui/material";
2627
- import TranslateIcon2 from "@mui/icons-material/Translate";
2628
- import LaunchIcon from "@mui/icons-material/Launch";
2629
-
2630
- // src/i18n/TranslationDialog.tsx
2631
- import { useEffect as useEffect3, useState as useState3 } from "react";
2632
- import {
2633
- Dialog,
2634
- DialogTitle,
2635
- DialogContent,
2636
- DialogActions,
2637
- Button,
2638
- TextField,
2639
- Box,
2640
- Typography,
2641
- CircularProgress,
2642
- IconButton,
2643
- Tooltip as Tooltip2,
2644
- Paper,
2645
- Alert
2646
- } from "@mui/material";
2647
- import AutoFixHighIcon from "@mui/icons-material/AutoFixHigh";
2648
- import TranslateIcon from "@mui/icons-material/Translate";
2649
- import LightbulbIcon from "@mui/icons-material/Lightbulb";
2650
-
2651
- // src/context/AIProvider.tsx
2652
- import { createContext as createContext4, useContext as useContext4, useMemo as useMemo2 } from "react";
2653
- import { GoogleGenAI } from "@google/genai";
2654
- import { jsx as jsx5 } from "react/jsx-runtime";
2655
- var AIContext = createContext4(null);
2656
- var AIProvider = ({
2657
- children,
2658
- config,
2659
- apiKey: directApiKey
2660
- }) => {
2661
- const apiKey = directApiKey || config?.apiKey;
2662
- const provider = config?.provider || "gemini";
2663
- const modelName = config?.modelName || (provider === "gemini" ? "gemini-2.5-flash" : "gpt-4o-mini");
2664
- const contextValue = useMemo2(() => {
2665
- return {
2666
- apiKey,
2667
- provider,
2668
- modelName,
2669
- generate: async ({
2670
- prompt,
2671
- systemInstruction,
2672
- jsonMode = false,
2673
- temperature
2674
- }) => {
2675
- if (!apiKey) {
2676
- console.warn("[AIProvider]: API Key \u043D\u0435 \u0437\u0430\u0434\u0430\u043D.");
2677
- return null;
2678
- }
2679
- if (provider === "gemini") {
2680
- try {
2681
- const ai = new GoogleGenAI({ apiKey });
2682
- const response = await ai.models.generateContent({
2683
- model: modelName,
2684
- contents: prompt,
2685
- config: {
2686
- systemInstruction,
2687
- temperature,
2688
- responseMimeType: jsonMode ? "application/json" : "text/plain"
2689
- }
2690
- });
2691
- const rawText = response.text?.trim() || "";
2692
- if (jsonMode) {
2693
- const cleanedText = rawText.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "").trim();
2694
- return JSON.parse(cleanedText);
2695
- }
2696
- return rawText;
2697
- } catch (err) {
2698
- console.error("[AIProvider Gemini Error]:", err);
2699
- return null;
2700
- }
2701
- }
2702
- if (provider === "openai") {
2703
- try {
2704
- const messages = [];
2705
- if (systemInstruction) {
2706
- messages.push({ role: "system", content: systemInstruction });
2707
- }
2708
- messages.push({ role: "user", content: prompt });
2709
- const res = await fetch("https://api.openai.com/v1/chat/completions", {
2710
- method: "POST",
2711
- headers: {
2712
- "Content-Type": "application/json",
2713
- Authorization: `Bearer ${apiKey}`
2714
- },
2715
- body: JSON.stringify({
2716
- model: modelName,
2717
- messages,
2718
- temperature,
2719
- ...jsonMode ? { response_format: { type: "json_object" } } : {}
2720
- })
2721
- });
2722
- const data = await res.json();
2723
- const content = data.choices?.[0]?.message?.content?.trim() || "";
2724
- if (jsonMode) {
2725
- return JSON.parse(content);
2726
- }
2727
- return content;
2728
- } catch (err) {
2729
- console.error("[AIProvider OpenAI Error]:", err);
2730
- return null;
2731
- }
2732
- }
2733
- return null;
2734
- }
2735
- };
2736
- }, [apiKey, provider, modelName]);
2737
- return /* @__PURE__ */ jsx5(AIContext.Provider, { value: contextValue, children });
2738
- };
2739
- var useAI = () => {
2740
- const context = useContext4(AIContext);
2741
- if (!context) {
2742
- throw new Error("useAI \u0434\u043E\u043B\u0436\u0435\u043D \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F \u0432\u043D\u0443\u0442\u0440\u0438 <AIProvider>");
2743
- }
2744
- return context;
2745
- };
2746
-
2747
- // src/i18n/TranslationDialog.tsx
2748
- import { jsx as jsx6, jsxs } from "react/jsx-runtime";
2749
- var TranslationDialog = ({
2750
- open,
2751
- onClose,
2752
- translationKey,
2753
- namespace,
2754
- onSave
2755
- }) => {
2756
- const supabase = useSupabase();
2757
- const { generate } = useAI();
2758
- const [languages, setLanguages] = useState3([]);
2759
- const [values, setValues] = useState3({});
2760
- const [contextHint, setContextHint] = useState3("");
2761
- const [loading, setLoading] = useState3(false);
2762
- const [saving, setSaving] = useState3(false);
2763
- const [translatingCode, setTranslatingCode] = useState3(null);
2764
- const [isTranslatingAll, setIsTranslatingAll] = useState3(false);
2765
- const [error, setError] = useState3(null);
2766
- useEffect3(() => {
2767
- if (!open) return;
2768
- const fetchData = async () => {
2769
- setLoading(true);
2770
- setError(null);
2771
- try {
2772
- const { data: langs, error: langErr } = await supabase.from("languages").select("code, name, svg_flag").eq("enabled", true);
2773
- if (langErr) throw langErr;
2774
- setLanguages(langs || []);
2775
- const { data: trans, error: transErr } = await supabase.from("translations").select("lang_code, value, context_hint").eq("namespace", namespace).eq("key", translationKey);
2776
- if (transErr) throw transErr;
2777
- const initialValues = {};
2778
- let existingHint = "";
2779
- langs?.forEach((l) => {
2780
- const found = trans?.find((t2) => t2.lang_code === l.code);
2781
- initialValues[l.code] = found ? found.value : "";
2782
- if (found?.context_hint) {
2783
- existingHint = found.context_hint;
2784
- }
2785
- });
2786
- setValues(initialValues);
2787
- setContextHint(existingHint);
2788
- } catch (err) {
2789
- console.error("Failed to load translations:", err);
2790
- setError(err?.message || "Failed to load initial translation data.");
2791
- } finally {
2792
- setLoading(false);
2793
- }
2794
- };
2795
- fetchData();
2796
- }, [open, translationKey, namespace]);
2797
- const handleAutoTranslate = async (e, targetLang) => {
2798
- e.preventDefault();
2799
- e.stopPropagation();
2800
- setError(null);
2801
- setTranslatingCode(targetLang);
2802
- try {
2803
- const res = await translationService.translateSmart(supabase, generate, {
2804
- text: translationKey,
2805
- targetLang,
2806
- contextHint
2807
- });
2808
- if (res?.translatedText) {
2809
- setValues((prev) => ({ ...prev, [targetLang]: res.translatedText }));
2810
- }
2811
- } catch (err) {
2812
- console.log(err);
2813
- setError(`Failed to translate into ${targetLang}. ${err?.message || ""}`);
2814
- } finally {
2815
- setTranslatingCode(null);
2816
- }
2817
- };
2818
- const handleTranslateAll = async (e) => {
2819
- e.preventDefault();
2820
- e.stopPropagation();
2821
- if (!translationKey || languages.length === 0) return;
2822
- setIsTranslatingAll(true);
2823
- setError(null);
2824
- try {
2825
- const targetLangs = languages.map((l) => l.code);
2826
- const res = await translationService.translateSmart(supabase, generate, {
2827
- text: translationKey,
2828
- targetLangs,
2829
- contextHint
2830
- });
2831
- if (res?.translations) {
2832
- setValues((prev) => ({ ...prev, ...res.translations }));
2833
- }
2834
- } catch (err) {
2835
- console.error("Batch translation error:", err);
2836
- setError(err?.message || "Failed to translate all languages.");
2837
- } finally {
2838
- setIsTranslatingAll(false);
2839
- }
2840
- };
2841
- const handleSaveAll = async (e) => {
2842
- e.preventDefault();
2843
- e.stopPropagation();
2844
- setSaving(true);
2845
- setError(null);
2846
- try {
2847
- await onSave(values, contextHint);
2848
- onClose();
2849
- } catch (err) {
2850
- console.error("Failed to save translations:", err);
2851
- setError(err?.message || "Failed to save translations. Please try again.");
2852
- } finally {
2853
- setSaving(false);
2854
- }
2855
- };
2856
- const handleClose = (_, reason) => {
2857
- if (reason === "backdropClick" && isBusy) return;
2858
- setError(null);
2859
- onClose();
2860
- };
2861
- const isBusy = loading || saving || isTranslatingAll || translatingCode !== null;
2862
- return /* @__PURE__ */ jsxs(
2863
- Dialog,
2864
- {
2865
- open,
2866
- onClose: handleClose,
2867
- fullWidth: true,
2868
- maxWidth: "sm",
2869
- onClick: (e) => e.stopPropagation(),
2870
- onMouseDown: (e) => e.stopPropagation(),
2871
- children: [
2872
- /* @__PURE__ */ jsxs(DialogTitle, { sx: { pb: 1, display: "flex", justifyContent: "space-between", alignItems: "flex-start" }, children: [
2873
- /* @__PURE__ */ jsxs(Box, { children: [
2874
- "Context Translation",
2875
- /* @__PURE__ */ jsxs(Typography, { component: "div", variant: "subtitle2", color: "text.secondary", sx: { wordBreak: "break-all", mt: 0.5 }, children: [
2876
- "Original: ",
2877
- /* @__PURE__ */ jsxs("strong", { children: [
2878
- '"',
2879
- translationKey,
2880
- '"'
2881
- ] })
2882
- ] })
2883
- ] }),
2884
- !loading && /* @__PURE__ */ jsx6(
2885
- Button,
2886
- {
2887
- type: "button",
2888
- size: "small",
2889
- variant: "outlined",
2890
- color: "secondary",
2891
- startIcon: isTranslatingAll ? /* @__PURE__ */ jsx6(CircularProgress, { size: 16, color: "inherit" }) : /* @__PURE__ */ jsx6(TranslateIcon, { fontSize: "small" }),
2892
- onClick: handleTranslateAll,
2893
- disabled: isBusy,
2894
- sx: { flexShrink: 0, ml: 2, whiteSpace: "nowrap" },
2895
- children: isTranslatingAll ? "Translating..." : "Translate All"
2896
- }
2897
- )
2898
- ] }),
2899
- /* @__PURE__ */ jsxs(DialogContent, { dividers: true, sx: { pt: 2 }, children: [
2900
- error && /* @__PURE__ */ jsx6(Alert, { severity: "error", onClose: () => setError(null), sx: { mb: 2 }, children: error }),
2901
- loading ? /* @__PURE__ */ jsx6(Box, { sx: { display: "flex", justifyContent: "center", py: 4 }, children: /* @__PURE__ */ jsx6(CircularProgress, {}) }) : /* @__PURE__ */ jsxs(Box, { sx: { display: "flex", flexDirection: "column", gap: 2.5 }, children: [
2902
- /* @__PURE__ */ jsxs(Paper, { variant: "outlined", sx: { p: 2, bgcolor: "action.hover", borderRadius: 2 }, children: [
2903
- /* @__PURE__ */ jsxs(Box, { sx: { display: "flex", alignItems: "center", gap: 1, mb: 1 }, children: [
2904
- /* @__PURE__ */ jsx6(LightbulbIcon, { color: "warning", fontSize: "small" }),
2905
- /* @__PURE__ */ jsx6(Typography, { variant: "subtitle2", sx: { fontWeight: 600 }, children: "Context Hint / Clarification" })
2906
- ] }),
2907
- /* @__PURE__ */ jsx6(
2908
- TextField,
2909
- {
2910
- fullWidth: true,
2911
- multiline: true,
2912
- rows: 2,
2913
- size: "small",
2914
- value: contextHint,
2915
- onChange: (e) => setContextHint(e.target.value),
2916
- placeholder: "e.g. Website navigation menu link to the home page",
2917
- helperText: "This hint explains the exact meaning to AI translation models.",
2918
- disabled: isBusy
2919
- }
2920
- )
2921
- ] }),
2922
- languages.map((lang) => /* @__PURE__ */ jsxs(Box, { sx: { display: "flex", alignItems: "center", gap: 2 }, children: [
2923
- /* @__PURE__ */ jsx6(
2924
- Box,
2925
- {
2926
- sx: {
2927
- width: 32,
2928
- height: 22,
2929
- flexShrink: 0,
2930
- borderRadius: "4px",
2931
- overflow: "hidden",
2932
- boxShadow: 1,
2933
- "& svg": { width: "100%", height: "100%", display: "block" }
2934
- },
2935
- dangerouslySetInnerHTML: { __html: lang.svg_flag }
2936
- }
2937
- ),
2938
- /* @__PURE__ */ jsx6(
2939
- TextField,
2940
- {
2941
- fullWidth: true,
2942
- label: lang.name,
2943
- size: "small",
2944
- value: values[lang.code] || "",
2945
- onChange: (e) => setValues((prev) => ({ ...prev, [lang.code]: e.target.value })),
2946
- placeholder: "Enter manual translation...",
2947
- disabled: isBusy
2948
- }
2949
- ),
2950
- /* @__PURE__ */ jsx6(Tooltip2, { title: "Translate with context hint", children: /* @__PURE__ */ jsx6("span", { children: /* @__PURE__ */ jsx6(
2951
- IconButton,
2952
- {
2953
- type: "button",
2954
- color: "primary",
2955
- disabled: isBusy,
2956
- onClick: (e) => handleAutoTranslate(e, lang.code),
2957
- children: translatingCode === lang.code ? /* @__PURE__ */ jsx6(CircularProgress, { size: 20, color: "inherit" }) : /* @__PURE__ */ jsx6(AutoFixHighIcon, { fontSize: "small" })
2958
- }
2959
- ) }) })
2960
- ] }, lang.code))
2961
- ] })
2962
- ] }),
2963
- /* @__PURE__ */ jsxs(DialogActions, { sx: { px: 3, py: 2 }, children: [
2964
- /* @__PURE__ */ jsx6(Button, { onClick: onClose, disabled: isBusy, color: "inherit", type: "button", children: "Cancel" }),
2965
- /* @__PURE__ */ jsx6(
2966
- Button,
2967
- {
2968
- onClick: handleSaveAll,
2969
- variant: "contained",
2970
- disabled: isBusy,
2971
- type: "button",
2972
- children: saving ? "Saving..." : "Save All"
2973
- }
2974
- )
2975
- ] })
2976
- ]
2977
- }
2978
- );
2979
- };
2980
-
2981
- // src/context/TranslateProvider.tsx
2982
- import { createContext as createContext5, useContext as useContext5 } from "react";
2983
- import { jsx as jsx7 } from "react/jsx-runtime";
2984
- var TranslationNamespaceContext = createContext5({
2985
- namespace: "common"
2986
- // значение по умолчанию
2987
- });
2988
- var TranslateProvider = ({ namespace, children }) => {
2989
- return /* @__PURE__ */ jsx7(TranslationNamespaceContext.Provider, { value: { namespace }, children });
2990
- };
2991
- var useTranslationNamespace = (overrideNamespace) => {
2992
- const context = useContext5(TranslationNamespaceContext);
2993
- return overrideNamespace || context.namespace;
2994
- };
2995
-
2996
- // src/i18n/TranslateText.tsx
2997
- import { Fragment, jsx as jsx8, jsxs as jsxs2 } from "react/jsx-runtime";
2998
- var TranslateText = ({
2999
- children,
3000
- values
3001
- }) => {
3002
- const namespace = useTranslationNamespace();
3003
- const { t: t2, i18n } = useTranslation(namespace);
3004
- const { isTranslationMode, canEdit } = useTranslationEdit();
3005
- const supabase = useSupabase();
3006
- const [anchorEl, setAnchorEl] = useState4(null);
3007
- const [isDialogOpen, setIsDialogOpen] = useState4(false);
3008
- const timeoutRef = useRef2(null);
3009
- const translatedValue = t2(children, values);
3010
- useEffect4(() => {
3011
- return () => {
3012
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
3013
- };
3014
- }, []);
3015
- if (!canEdit || !isTranslationMode) {
3016
- return /* @__PURE__ */ jsx8(Fragment, { children: translatedValue });
3017
- }
3018
- const handleSaveTranslations = async (newValues, contextHint) => {
3019
- const upsertData = Object.entries(newValues).map(([langCode, text]) => ({
3020
- lang_code: langCode,
3021
- namespace,
3022
- key: children,
3023
- value: text,
3024
- context_hint: contextHint
3025
- }));
3026
- const { error } = await supabase.from("translations").upsert(upsertData, { onConflict: "lang_code,namespace,key" });
3027
- if (error) {
3028
- alert("\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u0438 \u0432 \u0431\u0430\u0437\u0443 \u0434\u0430\u043D\u043D\u044B\u0445");
3029
- throw error;
3030
- }
3031
- await translationService.incrementVersion(supabase, namespace, Object.keys(newValues));
3032
- Object.entries(newValues).forEach(([langCode, text]) => {
3033
- i18n.addResource(langCode, namespace, children, text);
3034
- });
3035
- };
3036
- const handleMouseEnter = (event) => {
3037
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
3038
- setAnchorEl(event.currentTarget);
3039
- };
3040
- const handleMouseLeave = () => {
3041
- timeoutRef.current = setTimeout(() => {
3042
- setAnchorEl(null);
3043
- }, 200);
3044
- };
3045
- const handleOpenDialog = (e) => {
3046
- e.preventDefault();
3047
- e.stopPropagation();
3048
- setAnchorEl(null);
3049
- if (document.activeElement instanceof HTMLElement) {
3050
- document.activeElement.blur();
3051
- }
3052
- setIsDialogOpen(true);
3053
- };
3054
- const handleLaunchAction = (_) => {
3055
- setAnchorEl(null);
3056
- };
3057
- const open = Boolean(anchorEl);
3058
- return /* @__PURE__ */ jsxs2(Fragment, { children: [
3059
- /* @__PURE__ */ jsx8(
3060
- Box2,
3061
- {
3062
- component: "span",
3063
- onMouseEnter: handleMouseEnter,
3064
- onMouseLeave: handleMouseLeave,
3065
- onClick: (e) => {
3066
- e.preventDefault();
3067
- e.stopPropagation();
3068
- },
3069
- sx: {
3070
- display: "inline-block",
3071
- position: "relative",
3072
- borderRadius: "4px",
3073
- padding: "0 3px",
3074
- margin: "0 1px",
3075
- border: "1px dashed #f59e0b",
3076
- backgroundColor: "rgba(254, 243, 199, 0.35)",
3077
- cursor: "pointer",
3078
- transition: "all 0.2s ease-in-out",
3079
- userSelect: "none",
3080
- "&:hover": {
3081
- backgroundColor: "#fef08a",
3082
- borderColor: "#d97706",
3083
- boxShadow: "0 0 0 2px rgba(245, 158, 11, 0.35)",
3084
- transform: "scale(1.02)"
3085
- }
3086
- },
3087
- children: translatedValue
3088
- }
3089
- ),
3090
- /* @__PURE__ */ jsx8(
3091
- Popper,
3092
- {
3093
- open,
3094
- anchorEl,
3095
- placement: "bottom-start",
3096
- style: { zIndex: 1300 },
3097
- children: /* @__PURE__ */ jsx8(
3098
- Paper2,
3099
- {
3100
- elevation: 4,
3101
- onMouseEnter: () => {
3102
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
3103
- },
3104
- onMouseLeave: handleMouseLeave,
3105
- sx: {
3106
- mt: 0.5,
3107
- borderRadius: 2,
3108
- minWidth: 140,
3109
- boxShadow: "0px 10px 15px -3px rgba(0,0,0,0.1)"
3110
- },
3111
- children: /* @__PURE__ */ jsxs2(MenuList, { dense: true, sx: { py: 0.5 }, children: [
3112
- /* @__PURE__ */ jsxs2(MenuItem, { onClick: handleOpenDialog, sx: { py: 0.8, px: 1.5 }, children: [
3113
- /* @__PURE__ */ jsx8(ListItemIcon, { sx: { minWidth: "28px !important" }, children: /* @__PURE__ */ jsx8(TranslateIcon2, { fontSize: "small", sx: { color: "#d97706" } }) }),
3114
- /* @__PURE__ */ jsx8(
3115
- ListItemText,
3116
- {
3117
- primary: "Localization",
3118
- slotProps: {
3119
- primary: {
3120
- sx: {
3121
- fontSize: "0.825rem",
3122
- fontWeight: 600,
3123
- color: "text.primary"
3124
- }
3125
- }
3126
- }
3127
- }
3128
- )
3129
- ] }),
3130
- /* @__PURE__ */ jsxs2(MenuItem, { onClick: handleLaunchAction, sx: { py: 0.8, px: 1.5 }, children: [
3131
- /* @__PURE__ */ jsx8(ListItemIcon, { sx: { minWidth: "28px !important" }, children: /* @__PURE__ */ jsx8(LaunchIcon, { fontSize: "small", color: "secondary" }) }),
3132
- /* @__PURE__ */ jsx8(
3133
- ListItemText,
3134
- {
3135
- primary: "Launch action",
3136
- slotProps: {
3137
- primary: {
3138
- sx: {
3139
- fontSize: "0.825rem",
3140
- fontWeight: 600,
3141
- color: "text.primary"
3142
- }
3143
- }
3144
- }
3145
- }
3146
- )
3147
- ] })
3148
- ] })
3149
- }
3150
- )
3151
- }
3152
- ),
3153
- /* @__PURE__ */ jsx8("span", { style: { display: "inline" }, onClick: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsx8(
3154
- TranslationDialog,
3155
- {
3156
- open: isDialogOpen,
3157
- onClose: () => setIsDialogOpen(false),
3158
- translationKey: children,
3159
- namespace,
3160
- onSave: handleSaveTranslations
3161
- }
3162
- ) })
3163
- ] });
3164
- };
2
+ AIProvider,
3
+ BreadcrumbProvider,
4
+ ConfirmationProvider,
5
+ CopyClipboardButtonComponent,
6
+ LocalizationProvider,
7
+ Providers,
8
+ SupabaseProvider,
9
+ ThemeProvider,
10
+ ToastProvider,
11
+ TranslatableTooltipComponent,
12
+ TranslateProvider,
13
+ TranslateText,
14
+ TranslationDialog,
15
+ TranslationEditProvider,
16
+ UserRoleChipComponent,
17
+ UserStatusChipComponent,
18
+ translationService,
19
+ useAI,
20
+ useAppTheme,
21
+ useBreadcrumb,
22
+ useConfirmation,
23
+ useLocalization,
24
+ useSupabase,
25
+ useToast,
26
+ useTranslationEdit,
27
+ useTranslationNamespace
28
+ } from "./chunk-CT3G3YSD.mjs";
3165
29
 
3166
- // src/UI/components/inputs/TextfieldComponent.tsx
3167
- import { Fragment as Fragment2, jsx as jsx9, jsxs as jsxs3 } from "react/jsx-runtime";
3168
- var TextfieldComponent = ({
30
+ // src/UI/components/inputs/TextFieldComponent.tsx
31
+ import { useState } from "react";
32
+ import {
33
+ TextField,
34
+ InputAdornment,
35
+ IconButton,
36
+ Box,
37
+ Tooltip
38
+ } from "@mui/material";
39
+ import LockIcon from "@mui/icons-material/Lock";
40
+ import ContentCopyIcon from "@mui/icons-material/ContentCopy";
41
+ import CheckIcon from "@mui/icons-material/Check";
42
+ import ClearIcon from "@mui/icons-material/Clear";
43
+ import TranslateIcon from "@mui/icons-material/Translate";
44
+ import { useTranslation } from "react-i18next";
45
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
46
+ var TextFieldComponent = ({
47
+ overrideNamespace,
48
+ label,
3169
49
  value = "",
3170
50
  onChange,
3171
51
  disabled = false,
@@ -3181,15 +61,15 @@ var TextfieldComponent = ({
3181
61
  }) => {
3182
62
  const supabase = useSupabase();
3183
63
  const namespace = useTranslationNamespace();
3184
- const { t: t2, i18n } = useTranslation2(namespace);
64
+ const { t, i18n } = useTranslation(namespace);
3185
65
  const { isTranslationMode } = useTranslationEdit();
3186
- const [copied, setCopied] = useState5(false);
3187
- const [isDialogOpen, setIsDialogOpen] = useState5(false);
66
+ const [copied, setCopied] = useState(false);
67
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
3188
68
  const isReadOnly = Boolean(slotProps?.htmlInput?.readOnly);
3189
69
  const isLocked = disabled || isReadOnly;
3190
70
  const stringValue = String(value ?? "");
3191
71
  const hasValue = stringValue.length > 0;
3192
- const translatedPlaceholder = placeholderKey ? t2(placeholderKey) : void 0;
72
+ const translatedPlaceholder = placeholderKey ? t(placeholderKey) : void 0;
3193
73
  const handleClear = (e) => {
3194
74
  e.stopPropagation();
3195
75
  if (onChange) {
@@ -3231,10 +111,11 @@ var TextfieldComponent = ({
3231
111
  i18n.addResource(langCode, namespace, placeholderKey, text);
3232
112
  });
3233
113
  };
3234
- return /* @__PURE__ */ jsxs3(Fragment2, { children: [
3235
- /* @__PURE__ */ jsx9(
3236
- TextField2,
114
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
115
+ /* @__PURE__ */ jsx(
116
+ TextField,
3237
117
  {
118
+ label: typeof label === "string" ? /* @__PURE__ */ jsx(TranslateText, { overrideNamespace, children: label }) : label,
3238
119
  value,
3239
120
  onChange,
3240
121
  disabled,
@@ -3256,27 +137,27 @@ var TextfieldComponent = ({
3256
137
  input: {
3257
138
  ...slotProps?.input || {},
3258
139
  readOnly: isReadOnly,
3259
- endAdornment: /* @__PURE__ */ jsxs3(InputAdornment, { position: "end", sx: { gap: 0.5 }, children: [
3260
- hasValue && !isLocked && !disableClearButton && /* @__PURE__ */ jsx9(TranslatableTooltip, { title: /* @__PURE__ */ jsx9(TranslateText, { children: clearTooltip }), children: /* @__PURE__ */ jsx9(
3261
- IconButton2,
140
+ endAdornment: /* @__PURE__ */ jsxs(InputAdornment, { position: "end", sx: { gap: 0.5 }, children: [
141
+ hasValue && !isLocked && !disableClearButton && /* @__PURE__ */ jsx(TranslatableTooltipComponent, { title: /* @__PURE__ */ jsx(TranslateText, { overrideNamespace, children: clearTooltip }), children: /* @__PURE__ */ jsx(
142
+ IconButton,
3262
143
  {
3263
144
  size: "small",
3264
145
  onClick: handleClear,
3265
146
  edge: "end",
3266
147
  "aria-label": "clear input",
3267
- children: /* @__PURE__ */ jsx9(ClearIcon, { fontSize: "small" })
148
+ children: /* @__PURE__ */ jsx(ClearIcon, { fontSize: "small" })
3268
149
  }
3269
150
  ) }),
3270
- hasValue && /* @__PURE__ */ jsx9(TranslatableTooltip, { title: /* @__PURE__ */ jsx9(TranslateText, { children: copied ? copiedTooltip : copyTooltip }), children: /* @__PURE__ */ jsx9(
3271
- IconButton2,
151
+ hasValue && /* @__PURE__ */ jsx(TranslatableTooltipComponent, { title: /* @__PURE__ */ jsx(TranslateText, { overrideNamespace, children: copied ? copiedTooltip : copyTooltip }), children: /* @__PURE__ */ jsx(
152
+ IconButton,
3272
153
  {
3273
154
  size: "small",
3274
155
  onClick: handleCopy,
3275
156
  edge: "end",
3276
157
  "aria-label": "copy content",
3277
158
  color: copied ? "success" : "default",
3278
- children: /* @__PURE__ */ jsxs3(
3279
- Box3,
159
+ children: /* @__PURE__ */ jsxs(
160
+ Box,
3280
161
  {
3281
162
  sx: {
3282
163
  display: "flex",
@@ -3287,7 +168,7 @@ var TextfieldComponent = ({
3287
168
  height: 20
3288
169
  },
3289
170
  children: [
3290
- /* @__PURE__ */ jsx9(
171
+ /* @__PURE__ */ jsx(
3291
172
  ContentCopyIcon,
3292
173
  {
3293
174
  fontSize: "small",
@@ -3299,7 +180,7 @@ var TextfieldComponent = ({
3299
180
  }
3300
181
  }
3301
182
  ),
3302
- /* @__PURE__ */ jsx9(
183
+ /* @__PURE__ */ jsx(
3303
184
  CheckIcon,
3304
185
  {
3305
186
  fontSize: "small",
@@ -3317,8 +198,8 @@ var TextfieldComponent = ({
3317
198
  )
3318
199
  }
3319
200
  ) }),
3320
- isLocked && showLock && /* @__PURE__ */ jsx9(TranslatableTooltip, { title: /* @__PURE__ */ jsx9(TranslateText, { children: lockTooltip }), children: /* @__PURE__ */ jsx9(
3321
- IconButton2,
201
+ isLocked && showLock && /* @__PURE__ */ jsx(TranslatableTooltipComponent, { title: /* @__PURE__ */ jsx(TranslateText, { overrideNamespace, children: lockTooltip }), children: /* @__PURE__ */ jsx(
202
+ IconButton,
3322
203
  {
3323
204
  size: "small",
3324
205
  disabled: true,
@@ -3329,12 +210,12 @@ var TextfieldComponent = ({
3329
210
  color: "text.secondary"
3330
211
  }
3331
212
  },
3332
- children: /* @__PURE__ */ jsx9(LockIcon, { fontSize: "small" })
213
+ children: /* @__PURE__ */ jsx(LockIcon, { fontSize: "small" })
3333
214
  }
3334
215
  ) }),
3335
216
  slotProps?.input?.endAdornment,
3336
- isTranslationMode && placeholderKey && /* @__PURE__ */ jsx9(Tooltip3, { title: `Translate placeholder: "${placeholderKey}"`, children: /* @__PURE__ */ jsx9(
3337
- IconButton2,
217
+ isTranslationMode && placeholderKey && /* @__PURE__ */ jsx(Tooltip, { title: `Translate placeholder: "${placeholderKey}"`, children: /* @__PURE__ */ jsx(
218
+ IconButton,
3338
219
  {
3339
220
  size: "small",
3340
221
  onClick: (e) => {
@@ -3351,7 +232,7 @@ var TextfieldComponent = ({
3351
232
  backgroundColor: "#fef08a"
3352
233
  }
3353
234
  },
3354
- children: /* @__PURE__ */ jsx9(TranslateIcon3, { fontSize: "small" })
235
+ children: /* @__PURE__ */ jsx(TranslateIcon, { fontSize: "small" })
3355
236
  }
3356
237
  ) })
3357
238
  ] })
@@ -3359,7 +240,7 @@ var TextfieldComponent = ({
3359
240
  }
3360
241
  }
3361
242
  ),
3362
- placeholderKey && /* @__PURE__ */ jsx9(
243
+ placeholderKey && /* @__PURE__ */ jsx(
3363
244
  TranslationDialog,
3364
245
  {
3365
246
  namespace,
@@ -3373,12 +254,13 @@ var TextfieldComponent = ({
3373
254
  };
3374
255
 
3375
256
  // src/UI/components/inputs/NumberInputComponent.tsx
3376
- import { useState as useState6, useEffect as useEffect5, useCallback as useCallback3, useMemo as useMemo3 } from "react";
3377
- import { IconButton as IconButton3, InputAdornment as InputAdornment2, Box as Box4 } from "@mui/material";
257
+ import { useState as useState2, useEffect, useCallback, useMemo } from "react";
258
+ import { IconButton as IconButton2, InputAdornment as InputAdornment2, Box as Box2 } from "@mui/material";
3378
259
  import AddIcon from "@mui/icons-material/Add";
3379
260
  import RemoveIcon from "@mui/icons-material/Remove";
3380
- import { Fragment as Fragment3, jsx as jsx10, jsxs as jsxs4 } from "react/jsx-runtime";
261
+ import { Fragment as Fragment2, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
3381
262
  var NumberInputComponent = ({
263
+ overrideNamespace,
3382
264
  value,
3383
265
  onChange,
3384
266
  allowNegative = true,
@@ -3395,17 +277,17 @@ var NumberInputComponent = ({
3395
277
  onBlur,
3396
278
  ...props
3397
279
  }) => {
3398
- const [inputValue, setInputValue] = useState6(
280
+ const [inputValue, setInputValue] = useState2(
3399
281
  value !== null && value !== void 0 ? String(value) : ""
3400
282
  );
3401
- useEffect5(() => {
283
+ useEffect(() => {
3402
284
  const stringVal = value !== null && value !== void 0 ? String(value) : "";
3403
285
  if (Number(stringVal) !== Number(inputValue) || stringVal === "" && inputValue !== "." && inputValue !== "-") {
3404
286
  setInputValue(stringVal);
3405
287
  }
3406
288
  }, [value]);
3407
289
  const effectiveMin = !allowNegative ? Math.max(0, minValue ?? 0) : minValue;
3408
- const formatDisplayValue = useCallback3(
290
+ const formatDisplayValue = useCallback(
3409
291
  (raw) => {
3410
292
  if (!useGrouping || !raw) return raw;
3411
293
  const isNegative2 = raw.startsWith("-");
@@ -3416,7 +298,7 @@ var NumberInputComponent = ({
3416
298
  },
3417
299
  [useGrouping]
3418
300
  );
3419
- const formatAndClampValue = useCallback3(
301
+ const formatAndClampValue = useCallback(
3420
302
  (num) => {
3421
303
  let clamped = num;
3422
304
  if (effectiveMin !== void 0 && clamped < effectiveMin) {
@@ -3434,7 +316,7 @@ var NumberInputComponent = ({
3434
316
  },
3435
317
  [effectiveMin, maxValue, allowFractional, decimalPlaces]
3436
318
  );
3437
- const handleChange = useCallback3(
319
+ const handleChange = useCallback(
3438
320
  (e) => {
3439
321
  let raw = e.target.value.replace(/\s/g, "").replace(",", ".");
3440
322
  if (!allowNegative) {
@@ -3477,7 +359,7 @@ var NumberInputComponent = ({
3477
359
  },
3478
360
  [allowNegative, allowFractional, decimalPlaces, maxValue, onChange]
3479
361
  );
3480
- const handleBlur = useCallback3(
362
+ const handleBlur = useCallback(
3481
363
  (e) => {
3482
364
  onBlur?.(e);
3483
365
  if (inputValue === "" || inputValue === "-" || inputValue === ".") {
@@ -3494,7 +376,7 @@ var NumberInputComponent = ({
3494
376
  },
3495
377
  [inputValue, formatAndClampValue, onChange, onBlur]
3496
378
  );
3497
- const handleStep = useCallback3(
379
+ const handleStep = useCallback(
3498
380
  (delta) => {
3499
381
  if (disabled) return;
3500
382
  const currentNum = typeof value === "number" ? value : Number(inputValue) || 0;
@@ -3506,15 +388,16 @@ var NumberInputComponent = ({
3506
388
  [disabled, value, inputValue, formatAndClampValue, onChange]
3507
389
  );
3508
390
  const currentNumeric = typeof value === "number" ? value : Number(inputValue);
3509
- const isNegative = useMemo3(() => {
391
+ const isNegative = useMemo(() => {
3510
392
  return !isNaN(currentNumeric) && currentNumeric < 0;
3511
393
  }, [currentNumeric]);
3512
394
  const isDecrementDisabled = disabled || effectiveMin !== void 0 && !isNaN(currentNumeric) && currentNumeric <= effectiveMin;
3513
395
  const isIncrementDisabled = disabled || maxValue !== void 0 && !isNaN(currentNumeric) && currentNumeric >= maxValue;
3514
- return /* @__PURE__ */ jsx10(
3515
- TextfieldComponent,
396
+ return /* @__PURE__ */ jsx2(
397
+ TextFieldComponent,
3516
398
  {
3517
399
  ...props,
400
+ overrideNamespace,
3518
401
  type: "text",
3519
402
  disabled,
3520
403
  value: formatDisplayValue(inputValue),
@@ -3543,29 +426,29 @@ var NumberInputComponent = ({
3543
426
  }
3544
427
  }
3545
428
  },
3546
- endAdornment: /* @__PURE__ */ jsxs4(Fragment3, { children: [
429
+ endAdornment: /* @__PURE__ */ jsxs2(Fragment2, { children: [
3547
430
  slotProps?.input?.endAdornment,
3548
- showStepper && !disabled && /* @__PURE__ */ jsx10(InputAdornment2, { position: "end", sx: { ml: 0.5 }, children: /* @__PURE__ */ jsxs4(Box4, { sx: { display: "flex", alignItems: "center", gap: "2px" }, children: [
3549
- /* @__PURE__ */ jsx10(
3550
- IconButton3,
431
+ showStepper && !disabled && /* @__PURE__ */ jsx2(InputAdornment2, { position: "end", sx: { ml: 0.5 }, children: /* @__PURE__ */ jsxs2(Box2, { sx: { display: "flex", alignItems: "center", gap: "2px" }, children: [
432
+ /* @__PURE__ */ jsx2(
433
+ IconButton2,
3551
434
  {
3552
435
  size: "small",
3553
436
  onClick: () => handleStep(-step),
3554
437
  disabled: isDecrementDisabled,
3555
438
  sx: { p: "2px" },
3556
439
  "aria-label": "decrement",
3557
- children: /* @__PURE__ */ jsx10(RemoveIcon, { fontSize: "small" })
440
+ children: /* @__PURE__ */ jsx2(RemoveIcon, { fontSize: "small" })
3558
441
  }
3559
442
  ),
3560
- /* @__PURE__ */ jsx10(
3561
- IconButton3,
443
+ /* @__PURE__ */ jsx2(
444
+ IconButton2,
3562
445
  {
3563
446
  size: "small",
3564
447
  onClick: () => handleStep(step),
3565
448
  disabled: isIncrementDisabled,
3566
449
  sx: { p: "2px" },
3567
450
  "aria-label": "increment",
3568
- children: /* @__PURE__ */ jsx10(AddIcon, { fontSize: "small" })
451
+ children: /* @__PURE__ */ jsx2(AddIcon, { fontSize: "small" })
3569
452
  }
3570
453
  )
3571
454
  ] }) })
@@ -3576,541 +459,418 @@ var NumberInputComponent = ({
3576
459
  );
3577
460
  };
3578
461
 
3579
- // src/UI/index.ts
3580
- var CardForm = {
3581
- Inputs: {
3582
- TextField: TextfieldComponent,
3583
- NumberField: NumberInputComponent
3584
- }
3585
- /*Layout: {
3586
- Row: FormRow,
3587
- },*/
3588
- };
3589
-
3590
- // src/context/LocalizationProvider.tsx
3591
- import { createContext as createContext6, useContext as useContext6, useMemo as useMemo4, useEffect as useEffect6, useState as useState7 } from "react";
3592
- import { useTranslation as useTranslation3 } from "react-i18next";
3593
- import moment from "moment/min/moment-with-locales";
3594
- import { jsx as jsx11 } from "react/jsx-runtime";
3595
- var DEFAULT_DATETIME_FORMATS = {
3596
- uk: "DD.MM.YYYY, HH:mm",
3597
- de: "DD.MM.YYYY, HH:mm",
3598
- en: "MM/DD/YYYY, hh:mm A",
3599
- es: "DD/MM/YYYY, HH:mm",
3600
- fr: "DD/MM/YYYY, HH:mm",
3601
- it: "DD/MM/YYYY, HH:mm"
3602
- };
3603
- var DEFAULT_DATE_FORMATS = {
3604
- uk: "DD.MM.YYYY",
3605
- de: "DD.MM.YYYY",
3606
- en: "MM/DD/YYYY",
3607
- es: "DD/MM/YYYY",
3608
- fr: "DD/MM/YYYY",
3609
- it: "DD/MM/YYYY"
3610
- };
3611
- var DEFAULT_TIME_FORMATS = {
3612
- uk: "HH:mm:ss",
3613
- de: "HH:mm:ss",
3614
- en: "hh:mm:ss A",
3615
- es: "HH:mm:ss",
3616
- fr: "HH:mm:ss",
3617
- it: "HH:mm:ss"
3618
- };
3619
- var LocalizationContext = createContext6(void 0);
3620
- var LocalizationProvider = ({ children }) => {
3621
- const supabase = useSupabase();
3622
- const { i18n } = useTranslation3();
3623
- const [languages, setLanguages] = useState7([]);
3624
- const [isLoadingLangs, setIsLoadingLangs] = useState7(true);
3625
- const [languagesError, setLanguagesError] = useState7(null);
3626
- useEffect6(() => {
3627
- let isMounted = true;
3628
- const fetchLanguages = async () => {
3629
- try {
3630
- setIsLoadingLangs(true);
3631
- setLanguagesError(null);
3632
- const { data: langs, error: langErr } = await supabase.from("languages").select("code, name, svg_flag, enabled, created_at").eq("enabled", true).order("code", { ascending: true });
3633
- if (langErr) {
3634
- throw langErr;
3635
- }
3636
- if (isMounted && langs) {
3637
- setLanguages(langs);
3638
- }
3639
- } catch (err) {
3640
- console.error("Failed to load languages from Supabase:", err);
3641
- if (isMounted) {
3642
- setLanguagesError(err.message || "Error loading languages");
3643
- }
3644
- } finally {
3645
- if (isMounted) {
3646
- setIsLoadingLangs(false);
3647
- }
3648
- }
3649
- };
3650
- fetchLanguages();
3651
- return () => {
3652
- isMounted = false;
3653
- };
3654
- }, [supabase]);
3655
- const rawLang = i18n.language || "uk";
3656
- const currentLang = rawLang.split("-")[0].toLowerCase();
3657
- const getDateFormat = () => {
3658
- return DEFAULT_DATE_FORMATS[currentLang] || "DD.MM.YYYY";
462
+ // src/UI/components/inputs/UrlComponent.tsx
463
+ import { useState as useState3 } from "react";
464
+ import {
465
+ TextField as TextField2,
466
+ InputAdornment as InputAdornment3,
467
+ IconButton as IconButton3,
468
+ Tooltip as Tooltip2,
469
+ Popover,
470
+ Box as Box3,
471
+ Typography,
472
+ Button
473
+ } from "@mui/material";
474
+ import LinkIcon from "@mui/icons-material/Link";
475
+ import LaunchIcon from "@mui/icons-material/Launch";
476
+ import ContentCopyIcon2 from "@mui/icons-material/ContentCopy";
477
+ import CheckIcon2 from "@mui/icons-material/Check";
478
+ import EditNoteIcon from "@mui/icons-material/EditNote";
479
+ import LockIcon2 from "@mui/icons-material/Lock";
480
+ import { Fragment as Fragment3, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
481
+ function UrlComponent({
482
+ overrideNamespace,
483
+ label,
484
+ value,
485
+ onChange,
486
+ disabled = false,
487
+ readOnly = false,
488
+ required = false,
489
+ error = false,
490
+ helperText = "",
491
+ description = "",
492
+ fullWidth = true,
493
+ openInNewTab = true,
494
+ showLock = true,
495
+ lockTooltip = "Field is not editable",
496
+ sx
497
+ }) {
498
+ const [copied, setCopied] = useState3(false);
499
+ const [anchorEl, setAnchorEl] = useState3(null);
500
+ const isViewMode = disabled || readOnly;
501
+ const currentUrl = typeof value === "object" && value !== null ? value.url || "" : value || "";
502
+ const currentTitle = typeof value === "object" && value !== null ? value.title || "" : "";
503
+ const getFormattedUrl = (val) => {
504
+ if (!val) return "";
505
+ const trimmed = val.trim();
506
+ if (trimmed.match(/^[a-zA-Z]+:\/\//)) {
507
+ return trimmed;
508
+ }
509
+ return `https://${trimmed}`;
3659
510
  };
3660
- const getTimeFormat = () => {
3661
- return DEFAULT_TIME_FORMATS[currentLang] || "HH:mm:ss";
511
+ const finalUrl = getFormattedUrl(currentUrl);
512
+ const targetAttribute = openInNewTab ? "_blank" : "_self";
513
+ const displayLabelText = currentTitle.trim() || currentUrl;
514
+ const handleUrlChange = (newUrl) => {
515
+ onChange?.({ url: newUrl, title: currentTitle });
3662
516
  };
3663
- const getDateTimeFormat = () => {
3664
- return DEFAULT_DATETIME_FORMATS[currentLang] || "DD.MM.YYYY, HH:mm";
517
+ const handleTitleChange = (newTitle) => {
518
+ onChange?.({ url: currentUrl, title: newTitle });
3665
519
  };
3666
- const formatDateTime = (date, customPattern) => {
3667
- if (!date) return "\u2014";
3668
- const pattern = customPattern || DEFAULT_DATETIME_FORMATS[currentLang] || "DD.MM.YYYY, HH:mm";
3669
- return moment(date).locale(currentLang).format(pattern);
520
+ const handleCopy = (e) => {
521
+ e.stopPropagation();
522
+ if (!finalUrl) return;
523
+ navigator.clipboard.writeText(finalUrl);
524
+ setCopied(true);
525
+ setTimeout(() => setCopied(false), 2e3);
3670
526
  };
3671
- const formatDate = (date, customPattern) => {
3672
- if (!date) return "\u2014";
3673
- const pattern = customPattern || DEFAULT_DATE_FORMATS[currentLang] || "DD.MM.YYYY";
3674
- return moment(date).locale(currentLang).format(pattern);
527
+ const handleOpenLink = (e) => {
528
+ e.stopPropagation();
529
+ if (finalUrl) {
530
+ window.open(finalUrl, targetAttribute, openInNewTab ? "noopener,noreferrer" : void 0);
531
+ }
3675
532
  };
3676
- const formatTime = (date, customPattern) => {
3677
- if (!date) return "\u2014";
3678
- const pattern = customPattern || DEFAULT_TIME_FORMATS[currentLang] || "HH:mm:ss";
3679
- return moment(date).locale(currentLang).format(pattern);
533
+ const handleInputClick = (e) => {
534
+ if (isViewMode && finalUrl) {
535
+ handleOpenLink(e);
536
+ }
3680
537
  };
3681
- const formatRelativeTime = (date, withoutSuffix = false) => {
3682
- if (!date) return "\u2014";
3683
- return moment(date).locale(currentLang).fromNow(withoutSuffix);
538
+ const handleOpenTitleMenu = (e) => {
539
+ e.stopPropagation();
540
+ setAnchorEl(e.currentTarget);
3684
541
  };
3685
- const changeLanguage2 = async (lang) => {
3686
- await i18n.changeLanguage(lang);
542
+ const handleCloseTitleMenu = () => {
543
+ setAnchorEl(null);
3687
544
  };
3688
- const value = useMemo4(
3689
- () => ({
3690
- currentLang,
3691
- languages,
3692
- isLoadingLangs,
3693
- languagesError,
3694
- changeLanguage: changeLanguage2,
3695
- getDateFormat,
3696
- getTimeFormat,
3697
- getDateTimeFormat,
3698
- formatDateTime,
3699
- formatDate,
3700
- formatTime,
3701
- formatRelativeTime
3702
- }),
3703
- [currentLang, languages, isLoadingLangs, languagesError]
3704
- );
3705
- return /* @__PURE__ */ jsx11(LocalizationContext.Provider, { value, children });
3706
- };
3707
- var useLocalization = () => {
3708
- const context = useContext6(LocalizationContext);
3709
- if (!context) {
3710
- throw new Error("useLocalization must be used within a LocalizationProvider");
3711
- }
3712
- return context;
3713
- };
3714
-
3715
- // src/context/ThemeProvider.tsx
3716
- import { createContext as createContext7, useContext as useContext7, useMemo as useMemo5, useState as useState8, useEffect as useEffect7 } from "react";
3717
- import { createTheme, ThemeProvider as MuiThemeProvider, CssBaseline, useMediaQuery } from "@mui/material";
3718
- import { jsx as jsx12, jsxs as jsxs5 } from "react/jsx-runtime";
3719
- var DEFAULT_LIGHT_COLORS = {
3720
- primary: "#1976d2",
3721
- secondary: "#9c27b0",
3722
- backgroundDefault: "#f5f5f5",
3723
- backgroundPaper: "#ffffff",
3724
- textPrimary: "#0f172a",
3725
- textSecondary: "#475569",
3726
- success: "#2e7d32",
3727
- error: "#d32f2f",
3728
- warning: "#ed6c02",
3729
- info: "#0288d1"
3730
- };
3731
- var DEFAULT_DARK_COLORS = {
3732
- primary: "#90caf9",
3733
- secondary: "#ce93d8",
3734
- backgroundDefault: "#0f172a",
3735
- backgroundPaper: "#1e293b",
3736
- textPrimary: "#f8fafc",
3737
- textSecondary: "#94a3b8",
3738
- success: "#66bb6a",
3739
- error: "#f44336",
3740
- warning: "#ffa726",
3741
- info: "#29b6f6"
3742
- };
3743
- var INITIAL_THEME_CONFIG = {
3744
- name: "Base MUI Theme",
3745
- mode: "light",
3746
- borderRadius: 12,
3747
- colors: {
3748
- light: DEFAULT_LIGHT_COLORS,
3749
- dark: DEFAULT_DARK_COLORS
3750
- },
3751
- typography: {
3752
- fontFamily: '"Inter", "Roboto", "Helvetica", "Arial", sans-serif',
3753
- fontSize: 14,
3754
- fontWeightLight: 300,
3755
- fontWeightRegular: 400,
3756
- fontWeightMedium: 600,
3757
- fontWeightBold: 700
3758
- }
3759
- };
3760
- var buildMuiTheme = (config) => {
3761
- const currentMode = config.mode;
3762
- const currentColors = config.colors?.[currentMode] || (currentMode === "light" ? DEFAULT_LIGHT_COLORS : DEFAULT_DARK_COLORS);
3763
- return createTheme({
3764
- palette: {
3765
- mode: currentMode,
3766
- primary: {
3767
- main: currentColors.primary,
3768
- light: currentMode === "light" ? "#63a4ff" : "#a1d2fa",
3769
- dark: currentMode === "light" ? "#004ba0" : "#42a5f5"
3770
- },
3771
- secondary: {
3772
- main: currentColors.secondary
3773
- },
3774
- background: {
3775
- default: currentColors.backgroundDefault,
3776
- paper: currentColors.backgroundPaper
3777
- },
3778
- text: {
3779
- primary: currentColors.textPrimary,
3780
- secondary: currentColors.textSecondary || (currentMode === "light" ? "#475569" : "#94a3b8")
3781
- },
3782
- success: { main: currentColors.success },
3783
- error: { main: currentColors.error },
3784
- warning: { main: currentColors.warning },
3785
- info: { main: currentColors.info }
3786
- },
3787
- shape: {
3788
- borderRadius: config.borderRadius
3789
- },
3790
- typography: {
3791
- fontFamily: config.typography?.fontFamily || INITIAL_THEME_CONFIG.typography.fontFamily,
3792
- fontSize: config.typography?.fontSize || INITIAL_THEME_CONFIG.typography.fontSize,
3793
- fontWeightLight: config.typography?.fontWeightLight || INITIAL_THEME_CONFIG.typography.fontWeightLight,
3794
- fontWeightRegular: config.typography?.fontWeightRegular || INITIAL_THEME_CONFIG.typography.fontWeightRegular,
3795
- fontWeightMedium: config.typography?.fontWeightMedium || INITIAL_THEME_CONFIG.typography.fontWeightMedium,
3796
- fontWeightBold: config.typography?.fontWeightBold || INITIAL_THEME_CONFIG.typography.fontWeightBold,
3797
- h5: { fontWeight: 700, fontSize: "1.25rem" },
3798
- subtitle1: { fontWeight: 600, fontSize: "0.95rem" },
3799
- body2: { fontSize: "0.85rem" }
3800
- },
3801
- components: {
3802
- MuiAutocomplete: {
3803
- defaultProps: {
3804
- noOptionsText: "\u041D\u0456\u0447\u043E\u0433\u043E \u043D\u0435 \u0437\u043D\u0430\u0439\u0434\u0435\u043D\u043E"
3805
- }
3806
- },
3807
- MuiListItem: {
3808
- styleOverrides: {
3809
- root: {
3810
- transition: "all 0.2s ease-in-out",
3811
- "&:hover": {
3812
- backgroundColor: currentMode === "light" ? "#f1f5f9" : "#334155"
3813
- }
545
+ const isTitlePopoverOpen = Boolean(anchorEl);
546
+ const displayHelperText = error ? helperText : description || helperText;
547
+ return /* @__PURE__ */ jsxs3(Fragment3, { children: [
548
+ /* @__PURE__ */ jsx3(
549
+ TextField2,
550
+ {
551
+ label: /* @__PURE__ */ jsx3(TranslateText, { overrideNamespace, children: label }),
552
+ type: isViewMode ? "text" : "url",
553
+ value: isViewMode ? displayLabelText : currentUrl,
554
+ onChange: (e) => handleUrlChange(e.target.value),
555
+ required,
556
+ error,
557
+ disabled,
558
+ margin: "dense",
559
+ helperText: displayHelperText,
560
+ fullWidth,
561
+ placeholder: "example.com",
562
+ sx: {
563
+ "& .MuiInputLabel-asterisk": {
564
+ color: "red",
565
+ fontSize: "1.5rem"
566
+ },
567
+ "& .MuiInputBase-input": {
568
+ color: isViewMode && finalUrl ? "primary.main" : void 0,
569
+ textDecoration: isViewMode && finalUrl ? "underline" : "none",
570
+ cursor: isViewMode && finalUrl ? "pointer" : void 0,
571
+ fontWeight: isViewMode && finalUrl ? 500 : void 0
572
+ },
573
+ ...sx
574
+ },
575
+ slotProps: {
576
+ htmlInput: {
577
+ readOnly,
578
+ onClick: handleInputClick
579
+ },
580
+ input: {
581
+ startAdornment: /* @__PURE__ */ jsx3(InputAdornment3, { position: "start", children: /* @__PURE__ */ jsx3(LinkIcon, { fontSize: "small", color: isViewMode && finalUrl ? "primary" : "action" }) }),
582
+ endAdornment: /* @__PURE__ */ jsxs3(InputAdornment3, { position: "end", sx: { gap: 0.5 }, children: [
583
+ !isViewMode && /* @__PURE__ */ jsx3(Tooltip2, { title: currentTitle ? `Title: "${currentTitle}"` : /* @__PURE__ */ jsx3(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Set link title" }), children: /* @__PURE__ */ jsx3(
584
+ IconButton3,
585
+ {
586
+ size: "small",
587
+ onClick: handleOpenTitleMenu,
588
+ color: currentTitle ? "primary" : "default",
589
+ children: /* @__PURE__ */ jsx3(EditNoteIcon, { fontSize: "small" })
590
+ }
591
+ ) }),
592
+ finalUrl && /* @__PURE__ */ jsx3(Tooltip2, { title: copied ? /* @__PURE__ */ jsx3(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Copied!" }) : /* @__PURE__ */ jsx3(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Copy link" }), children: /* @__PURE__ */ jsx3(IconButton3, { size: "small", onClick: handleCopy, color: copied ? "success" : "default", children: copied ? /* @__PURE__ */ jsx3(CheckIcon2, { fontSize: "small" }) : /* @__PURE__ */ jsx3(ContentCopyIcon2, { fontSize: "small" }) }) }),
593
+ isViewMode && showLock && /* @__PURE__ */ jsx3(Tooltip2, { title: /* @__PURE__ */ jsx3(TranslateText, { overrideNamespace, children: lockTooltip }), children: /* @__PURE__ */ jsx3(
594
+ IconButton3,
595
+ {
596
+ size: "small",
597
+ disabled: true,
598
+ edge: "end",
599
+ "aria-label": "locked input",
600
+ sx: {
601
+ "&.Mui-disabled": {
602
+ color: "text.secondary"
603
+ }
604
+ },
605
+ children: /* @__PURE__ */ jsx3(LockIcon2, { fontSize: "small" })
606
+ }
607
+ ) }),
608
+ finalUrl && /* @__PURE__ */ jsx3(Tooltip2, { title: /* @__PURE__ */ jsx3(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Open link" }), children: /* @__PURE__ */ jsx3(IconButton3, { size: "small", onClick: handleOpenLink, children: /* @__PURE__ */ jsx3(LaunchIcon, { fontSize: "small", color: isViewMode ? "primary" : "action" }) }) })
609
+ ] })
3814
610
  }
3815
611
  }
3816
- },
3817
- MuiListItemButton: {
3818
- styleOverrides: {
3819
- root: {
3820
- transition: "all 0.2s ease-in-out",
3821
- "&:hover": {
3822
- backgroundColor: currentMode === "light" ? "#f1f5f9" : "#334155"
612
+ }
613
+ ),
614
+ /* @__PURE__ */ jsxs3(
615
+ Popover,
616
+ {
617
+ open: isTitlePopoverOpen,
618
+ anchorEl,
619
+ onClose: handleCloseTitleMenu,
620
+ anchorOrigin: {
621
+ vertical: "bottom",
622
+ horizontal: "right"
623
+ },
624
+ transformOrigin: {
625
+ vertical: "top",
626
+ horizontal: "right"
627
+ },
628
+ slotProps: {
629
+ paper: { sx: { p: 2, width: 280 } }
630
+ },
631
+ children: [
632
+ /* @__PURE__ */ jsx3(Typography, { variant: "subtitle2", sx: { mb: 1, fontWeight: "bold" }, children: /* @__PURE__ */ jsx3(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Link Title (Anchor)" }) }),
633
+ /* @__PURE__ */ jsxs3(Typography, { variant: "caption", color: "text.secondary", sx: { mb: 1.5, display: "block" }, children: [
634
+ /* @__PURE__ */ jsx3(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Specify the text to display instead of the URL address" }),
635
+ ":"
636
+ ] }),
637
+ /* @__PURE__ */ jsx3(
638
+ TextField2,
639
+ {
640
+ size: "small",
641
+ fullWidth: true,
642
+ placeholder: "e.g. Instruction",
643
+ value: currentTitle,
644
+ onChange: (e) => handleTitleChange(e.target.value),
645
+ autoFocus: true,
646
+ onKeyDown: (e) => {
647
+ if (e.key === "Enter") {
648
+ e.preventDefault();
649
+ handleCloseTitleMenu();
650
+ }
651
+ }
3823
652
  }
3824
- }
3825
- }
3826
- },
3827
- MuiButton: {
3828
- styleOverrides: {
3829
- root: {
3830
- textTransform: "none",
3831
- fontWeight: 600,
3832
- borderRadius: `${config.borderRadius}px`,
3833
- padding: "10px 24px",
3834
- transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
3835
- }
3836
- }
3837
- },
3838
- MuiPaper: {
3839
- styleOverrides: {
3840
- rounded: {
3841
- borderRadius: `${config.borderRadius * 1.25}px`
3842
- }
3843
- }
653
+ ),
654
+ /* @__PURE__ */ jsx3(Box3, { sx: { display: "flex", justifyContent: "flex-end", mt: 1.5 }, children: /* @__PURE__ */ jsx3(Button, { size: "small", variant: "contained", onClick: handleCloseTitleMenu, children: /* @__PURE__ */ jsx3(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Done" }) }) })
655
+ ]
3844
656
  }
657
+ )
658
+ ] });
659
+ }
660
+
661
+ // src/UI/components/inputs/EmailInputComponent.tsx
662
+ import { useState as useState4 } from "react";
663
+ import { jsx as jsx4 } from "react/jsx-runtime";
664
+ var EMAIL_REGEX = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
665
+ var EmailInputComponent = ({
666
+ value = "",
667
+ onChange,
668
+ onBlur,
669
+ error: externalError,
670
+ helperText: externalHelperText,
671
+ invalidEmailError = "Invalid email address",
672
+ disableValidation = false,
673
+ onValidationChange,
674
+ ...props
675
+ }) => {
676
+ const [internalError, setInternalError] = useState4(null);
677
+ const validateEmail = (val) => {
678
+ if (disableValidation) return true;
679
+ const stringVal = String(val ?? "").trim();
680
+ if (!stringVal) {
681
+ setInternalError(null);
682
+ onValidationChange?.(true);
683
+ return true;
684
+ }
685
+ const isValid = EMAIL_REGEX.test(stringVal);
686
+ const errorMessage = isValid ? null : invalidEmailError;
687
+ setInternalError(errorMessage);
688
+ onValidationChange?.(isValid);
689
+ return isValid;
690
+ };
691
+ const handleChange = (e) => {
692
+ const newValue = e.target.value;
693
+ if (internalError) {
694
+ validateEmail(newValue);
695
+ }
696
+ if (onChange) {
697
+ onChange(e);
698
+ }
699
+ };
700
+ const handleBlur = (e) => {
701
+ validateEmail(e.target.value);
702
+ if (onBlur) {
703
+ onBlur(e);
3845
704
  }
3846
- });
705
+ };
706
+ const hasError = Boolean(externalError || internalError);
707
+ const displayHelperText = externalHelperText || internalError || void 0;
708
+ return /* @__PURE__ */ jsx4(
709
+ TextFieldComponent,
710
+ {
711
+ type: "email",
712
+ value,
713
+ onChange: handleChange,
714
+ onBlur: handleBlur,
715
+ error: hasError,
716
+ helperText: displayHelperText,
717
+ ...props
718
+ }
719
+ );
3847
720
  };
3848
- var ThemeContext = createContext7(void 0);
3849
- var THEME_STORAGE_KEY = "docsua_custom_theme_config";
3850
- var THEME_MODE_STORAGE_KEY = "docsua_custom_theme_mode";
3851
- var ThemeProvider = ({ children }) => {
721
+
722
+ // src/UI/components/data.display/UserAvatarComponent.tsx
723
+ import { useState as useState5, useEffect as useEffect2, lazy, Suspense } from "react";
724
+ import { Avatar, Tooltip as Tooltip3, Typography as Typography2 } from "@mui/material";
725
+ import { Fragment as Fragment4, jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
726
+ var LazyUserPopover = lazy(() => import("./UserPopoverComponent-BNJWFSLT.mjs"));
727
+ var getInitials = (name) => {
728
+ if (!name) return "?";
729
+ const parts = name.trim().split(" ");
730
+ if (parts.length >= 2) {
731
+ return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
732
+ }
733
+ return name[0].toUpperCase();
734
+ };
735
+ var UserAvatarComponent = ({
736
+ userId = "",
737
+ avatarUrl = "",
738
+ displayName = "",
739
+ employeePost = "",
740
+ size = 40,
741
+ disableBorder = false,
742
+ disableShadow = false,
743
+ disablePopover = false,
744
+ disableTooltip = false,
745
+ sx = {}
746
+ }) => {
3852
747
  const supabase = useSupabase();
3853
- const { user, isAuthenticated, loading: isAuthLoading } = useAuth();
3854
- const userId = user?.id;
3855
- const [themeConfig, setThemeConfig] = useState8(() => {
3856
- const saved = localStorage.getItem(THEME_STORAGE_KEY);
3857
- if (saved) {
3858
- try {
3859
- return JSON.parse(saved);
3860
- } catch (e) {
748
+ const [anchorEl, setAnchorEl] = useState5(null);
749
+ const [hasInteracted, setHasInteracted] = useState5(false);
750
+ const [resolvedAvatarUrl, setResolvedAvatarUrl] = useState5(null);
751
+ const canShowPopover = !disablePopover && Boolean(userId);
752
+ useEffect2(() => {
753
+ let isMounted = true;
754
+ const resolveAvatar = async () => {
755
+ if (!avatarUrl) {
756
+ if (isMounted) setResolvedAvatarUrl(null);
757
+ return;
3861
758
  }
3862
- }
3863
- return INITIAL_THEME_CONFIG;
3864
- });
3865
- useEffect7(() => {
3866
- if (isAuthLoading) return;
3867
- if (isAuthenticated && userId) {
3868
- const fetchActiveTheme = async () => {
759
+ if (!avatarUrl.startsWith("http") && !avatarUrl.startsWith("data:")) {
3869
760
  try {
3870
- const { data, error } = await supabase.from("user_themes").select("*").eq("user_id", userId).eq("is_active", true).maybeSingle();
3871
- if (error) {
3872
- console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0435 \u0442\u0435\u043C\u044B \u0438\u0437 Supabase:", error.message);
3873
- return;
3874
- }
3875
- if (data) {
3876
- const activeTheme = data;
3877
- const savedMode = localStorage.getItem(THEME_MODE_STORAGE_KEY);
3878
- setThemeConfig({
3879
- id: activeTheme.id,
3880
- name: activeTheme.name || INITIAL_THEME_CONFIG.name,
3881
- mode: savedMode || activeTheme.config?.mode || "light",
3882
- borderRadius: activeTheme.config?.borderRadius ?? INITIAL_THEME_CONFIG.borderRadius,
3883
- colors: activeTheme.config?.colors || INITIAL_THEME_CONFIG.colors,
3884
- typography: activeTheme.config?.typography || INITIAL_THEME_CONFIG.typography,
3885
- updatedAt: activeTheme.updated_at || void 0
3886
- });
761
+ const { data } = await supabase.storage.from("user-media").createSignedUrl(avatarUrl, 3600);
762
+ if (isMounted) {
763
+ setResolvedAvatarUrl(data?.signedUrl || null);
3887
764
  }
3888
765
  } catch (err) {
3889
- console.error("\u041D\u0435\u043F\u0440\u0435\u0434\u0432\u0438\u0434\u0435\u043D\u043D\u0430\u044F \u043E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0437\u0430\u043F\u0440\u043E\u0441\u0435 \u0442\u0435\u043C\u044B:", err);
766
+ console.error("Error resolving signed url for avatar:", err);
767
+ if (isMounted) setResolvedAvatarUrl(null);
3890
768
  }
3891
- };
3892
- fetchActiveTheme();
3893
- } else {
3894
- setThemeConfig(INITIAL_THEME_CONFIG);
3895
- localStorage.removeItem(THEME_STORAGE_KEY);
3896
- localStorage.removeItem(THEME_MODE_STORAGE_KEY);
3897
- }
3898
- }, [isAuthenticated, isAuthLoading, userId]);
3899
- useEffect7(() => {
3900
- if (isAuthenticated) {
3901
- localStorage.setItem(THEME_STORAGE_KEY, JSON.stringify(themeConfig));
3902
- localStorage.setItem(THEME_MODE_STORAGE_KEY, themeConfig.mode);
769
+ } else {
770
+ if (isMounted) setResolvedAvatarUrl(avatarUrl);
771
+ }
772
+ };
773
+ resolveAvatar();
774
+ return () => {
775
+ isMounted = false;
776
+ };
777
+ }, [avatarUrl]);
778
+ const handleClick = (event) => {
779
+ event.stopPropagation();
780
+ event.preventDefault();
781
+ if (canShowPopover) {
782
+ setAnchorEl(event.currentTarget);
783
+ if (!hasInteracted) {
784
+ setHasInteracted(true);
785
+ }
3903
786
  }
3904
- }, [themeConfig, isAuthenticated]);
3905
- const mode = themeConfig.mode;
3906
- const setMode = (newMode) => {
3907
- setThemeConfig((prev) => ({ ...prev, mode: newMode }));
3908
- };
3909
- const toggleTheme = () => {
3910
- setMode(mode === "light" ? "dark" : "light");
3911
787
  };
3912
- const theme = useMemo5(() => buildMuiTheme(themeConfig), [themeConfig]);
3913
- const displayState = {
3914
- isMobile: useMediaQuery(theme.breakpoints.down("sm")),
3915
- isTablet: useMediaQuery(theme.breakpoints.between("sm", "md")),
3916
- isDesktop: useMediaQuery(theme.breakpoints.between("md", "lg")),
3917
- isWideDesktop: useMediaQuery(theme.breakpoints.between("lg", "xl")),
3918
- isSuperWideDesktop: useMediaQuery(theme.breakpoints.up("xl"))
3919
- };
3920
- return /* @__PURE__ */ jsx12(ThemeContext.Provider, { value: { mode, toggleTheme, setMode, theme, themeConfig, setThemeConfig, displayState }, children: /* @__PURE__ */ jsxs5(MuiThemeProvider, { theme, children: [
3921
- /* @__PURE__ */ jsx12(CssBaseline, {}),
3922
- children
3923
- ] }) });
3924
- };
3925
- var useAppTheme = () => {
3926
- const context = useContext7(ThemeContext);
3927
- if (!context) {
3928
- throw new Error("useAppTheme should be used within the ThemeProvider");
3929
- }
3930
- return context;
3931
- };
3932
-
3933
- // src/context/BreadcrumbProvider.tsx
3934
- import { createContext as createContext8, useContext as useContext8, useState as useState9 } from "react";
3935
- import { jsx as jsx13 } from "react/jsx-runtime";
3936
- var BreadcrumbContext = createContext8({
3937
- breadcrumbTitles: {},
3938
- setBreadcrumbTitle: () => {
3939
- }
3940
- });
3941
- var BreadcrumbProvider = ({ children }) => {
3942
- const [breadcrumbTitles, setBreadcrumbTitles] = useState9({});
3943
- const setBreadcrumbTitle = (path, title) => {
3944
- setBreadcrumbTitles((prev) => {
3945
- if (prev[path] === title) return prev;
3946
- return { ...prev, [path]: title };
3947
- });
788
+ const handleClose = (event) => {
789
+ if (event) {
790
+ event.stopPropagation();
791
+ event.preventDefault();
792
+ }
793
+ setAnchorEl(null);
3948
794
  };
3949
- return /* @__PURE__ */ jsx13(BreadcrumbContext.Provider, { value: { breadcrumbTitles, setBreadcrumbTitle }, children });
3950
- };
3951
- var useBreadcrumb = () => useContext8(BreadcrumbContext);
3952
-
3953
- // src/context/ToastProvider.tsx
3954
- import { createContext as createContext9, useContext as useContext9, useState as useState10, useCallback as useCallback4, useMemo as useMemo6 } from "react";
3955
- import { Snackbar, Alert as Alert2 } from "@mui/material";
3956
- import { jsx as jsx14, jsxs as jsxs6 } from "react/jsx-runtime";
3957
- var ToastContext = createContext9(void 0);
3958
- var ToastProvider = ({ children }) => {
3959
- const [toast, setToast] = useState10(null);
3960
- const showToast = useCallback4((text, type = "info") => {
3961
- setToast({ text, type });
3962
- }, []);
3963
- const hideToast = useCallback4(() => {
3964
- setToast(null);
3965
- }, []);
3966
- const contextValue = useMemo6(() => ({
3967
- showToast,
3968
- hideToast
3969
- }), [showToast, hideToast]);
3970
- return /* @__PURE__ */ jsxs6(ToastContext.Provider, { value: contextValue, children: [
3971
- children,
3972
- /* @__PURE__ */ jsx14(
3973
- Snackbar,
795
+ const isPopoverOpen = Boolean(anchorEl);
796
+ const initials = getInitials(displayName || "");
797
+ const getTooltip = /* @__PURE__ */ jsxs4(Fragment4, { children: [
798
+ /* @__PURE__ */ jsx5(Typography2, { component: "div", variant: "caption", children: displayName }),
799
+ displayName && employeePost && /* @__PURE__ */ jsx5(Typography2, { component: "div", variant: "caption", children: employeePost })
800
+ ] });
801
+ return /* @__PURE__ */ jsxs4(Fragment4, { children: [
802
+ /* @__PURE__ */ jsx5(Tooltip3, { title: disableTooltip || isPopoverOpen ? "" : getTooltip, children: /* @__PURE__ */ jsx5(
803
+ Avatar,
3974
804
  {
3975
- open: Boolean(toast),
3976
- autoHideDuration: 3500,
3977
- onClose: hideToast,
3978
- anchorOrigin: { vertical: "bottom", horizontal: "center" },
3979
- children: /* @__PURE__ */ jsx14(
3980
- Alert2,
3981
- {
3982
- severity: toast?.type || "info",
3983
- variant: "filled",
3984
- onClose: hideToast,
3985
- children: toast?.text
3986
- }
3987
- )
805
+ src: resolvedAvatarUrl || void 0,
806
+ alt: displayName || "User Avatar",
807
+ onClick: handleClick,
808
+ sx: {
809
+ width: size,
810
+ height: size,
811
+ fontSize: size * 0.4,
812
+ fontWeight: 600,
813
+ bgcolor: "primary.main",
814
+ color: "primary.contrastText",
815
+ cursor: canShowPopover ? "pointer" : void 0,
816
+ transition: "transform 0.2s ease, box-shadow 0.2s ease",
817
+ border: disableBorder ? "none" : "2px solid",
818
+ borderColor: "background.paper",
819
+ boxShadow: disableShadow ? "none" : 2,
820
+ "&:hover": {
821
+ transform: canShowPopover ? "scale(1.05)" : "none"
822
+ },
823
+ ...sx
824
+ },
825
+ children: !resolvedAvatarUrl && initials
3988
826
  }
3989
- )
3990
- ] });
3991
- };
3992
- var useToast = () => {
3993
- const context = useContext9(ToastContext);
3994
- if (!context) {
3995
- throw new Error("useToast must be used within a ToastProvider");
3996
- }
3997
- return context;
3998
- };
3999
-
4000
- // src/context/ConfirmationProvider.tsx
4001
- import { createContext as createContext10, useContext as useContext10, useState as useState11, useCallback as useCallback5 } from "react";
4002
- import {
4003
- Button as Button2,
4004
- Dialog as Dialog2,
4005
- DialogActions as DialogActions2,
4006
- DialogContent as DialogContent2,
4007
- DialogContentText,
4008
- DialogTitle as DialogTitle2,
4009
- Box as Box5
4010
- } from "@mui/material";
4011
- import {
4012
- Error as ErrorIcon,
4013
- WarningAmberOutlined as WarningIcon,
4014
- InfoOutlined as InfoIcon,
4015
- CheckCircleOutlined as SuccessIcon
4016
- } from "@mui/icons-material";
4017
- import { jsx as jsx15, jsxs as jsxs7 } from "react/jsx-runtime";
4018
- var ConfirmContext = createContext10(null);
4019
- var SEVERITY_ICONS = {
4020
- error: /* @__PURE__ */ jsx15(ErrorIcon, { color: "error", sx: { fontSize: 40 } }),
4021
- warning: /* @__PURE__ */ jsx15(WarningIcon, { color: "warning", sx: { fontSize: 40 } }),
4022
- info: /* @__PURE__ */ jsx15(InfoIcon, { color: "info", sx: { fontSize: 40 } }),
4023
- success: /* @__PURE__ */ jsx15(SuccessIcon, { color: "success", sx: { fontSize: 40 } })
4024
- };
4025
- var ConfirmationProvider = ({ children }) => {
4026
- const [open, setOpen] = useState11(false);
4027
- const [options, setOptions] = useState11(null);
4028
- const [resolver, setResolver] = useState11(null);
4029
- const confirm = useCallback5((opts) => {
4030
- setOptions(opts);
4031
- setOpen(true);
4032
- return new Promise((resolve) => {
4033
- setResolver(() => resolve);
4034
- });
4035
- }, []);
4036
- const handleClose = (result) => {
4037
- setOpen(false);
4038
- if (resolver) {
4039
- resolver(result);
4040
- }
4041
- };
4042
- const severityType = options?.type || "info";
4043
- return /* @__PURE__ */ jsxs7(ConfirmContext.Provider, { value: { confirm }, children: [
4044
- children,
4045
- /* @__PURE__ */ jsxs7(
4046
- Dialog2,
827
+ ) }),
828
+ canShowPopover && hasInteracted && /* @__PURE__ */ jsx5(Suspense, { fallback: null, children: /* @__PURE__ */ jsx5(
829
+ LazyUserPopover,
4047
830
  {
4048
- open,
4049
- onClose: () => handleClose("cancel"),
4050
- maxWidth: "xs",
4051
- fullWidth: true,
4052
- disableEnforceFocus: true,
4053
- disableRestoreFocus: true,
4054
- children: [
4055
- /* @__PURE__ */ jsxs7(DialogTitle2, { sx: { display: "flex", alignItems: "center", gap: 1.5, pb: 1 }, children: [
4056
- SEVERITY_ICONS[severityType],
4057
- /* @__PURE__ */ jsx15(Box5, { component: "span", sx: { fontWeight: 600 }, children: options?.title || /* @__PURE__ */ jsx15(TranslateText, { children: "Confirmation" }) })
4058
- ] }),
4059
- /* @__PURE__ */ jsx15(DialogContent2, { sx: { py: 2 }, dividers: true, children: /* @__PURE__ */ jsx15(DialogContentText, { color: "text.secondary", children: options?.message }) }),
4060
- /* @__PURE__ */ jsxs7(DialogActions2, { sx: { pt: 2, px: 2, justifyContent: "flex-end", gap: 1 }, children: [
4061
- (options?.showCancelButton ?? true) && /* @__PURE__ */ jsx15(
4062
- Button2,
4063
- {
4064
- onClick: () => handleClose("cancel"),
4065
- color: "inherit",
4066
- variant: "text",
4067
- children: options?.cancelText || /* @__PURE__ */ jsx15(TranslateText, { children: "Cancel" })
4068
- }
4069
- ),
4070
- options?.showNoButton && /* @__PURE__ */ jsx15(
4071
- Button2,
4072
- {
4073
- onClick: () => handleClose("no"),
4074
- color: "inherit",
4075
- variant: "outlined",
4076
- children: options?.noText || /* @__PURE__ */ jsx15(TranslateText, { children: "No" })
4077
- }
4078
- ),
4079
- /* @__PURE__ */ jsx15(
4080
- Button2,
4081
- {
4082
- onClick: () => handleClose("yes"),
4083
- color: options?.confirmColor || (severityType === "error" ? "error" : "primary"),
4084
- variant: "contained",
4085
- autoFocus: true,
4086
- children: options?.confirmText || /* @__PURE__ */ jsx15(TranslateText, { children: "Yes" })
4087
- }
4088
- )
4089
- ] })
4090
- ]
831
+ userId,
832
+ anchorEl,
833
+ open: isPopoverOpen,
834
+ onClose: handleClose
4091
835
  }
4092
- )
836
+ ) })
4093
837
  ] });
4094
838
  };
4095
- var useConfirmation = () => {
4096
- const context = useContext10(ConfirmContext);
4097
- if (!context) {
4098
- throw new Error("useConfirm must be used within a ConfirmProvider");
839
+
840
+ // src/UI/index.ts
841
+ var UI = {
842
+ Inputs: {
843
+ TextField: TextFieldComponent,
844
+ NumberField: NumberInputComponent,
845
+ EmailField: EmailInputComponent,
846
+ Url: UrlComponent
847
+ },
848
+ Buttons: {
849
+ CopyClipboardButton: CopyClipboardButtonComponent
850
+ },
851
+ DataDisplay: {
852
+ TranslatableTooltip: TranslatableTooltipComponent,
853
+ UserAvatar: UserAvatarComponent,
854
+ UserRoleChip: UserRoleChipComponent,
855
+ UserStatusChip: UserStatusChipComponent
4099
856
  }
4100
- return context.confirm;
857
+ /*Layout: {
858
+ Row: FormRow,
859
+ },*/
4101
860
  };
4102
861
  export {
4103
862
  AIProvider,
4104
863
  BreadcrumbProvider,
4105
- CardForm,
4106
864
  ConfirmationProvider,
4107
865
  LocalizationProvider,
866
+ Providers,
4108
867
  SupabaseProvider,
4109
868
  ThemeProvider,
4110
869
  ToastProvider,
4111
870
  TranslateProvider,
4112
871
  TranslateText,
4113
872
  TranslationEditProvider,
873
+ UI,
4114
874
  useAI,
4115
875
  useAppTheme,
4116
876
  useBreadcrumb,