@arc-js/intl 0.0.93 → 0.0.94
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/core/TranslationService.d.ts +15 -1
- package/core/TranslationService.js +115 -61
- package/core/TranslationService.min.js +1 -1
- package/hooks/useTranslation.jsx +6 -4
- package/hooks/useTranslation.tsx +7 -5
- package/package.json +1 -1
- package/providers/IntlProvider.jsx +46 -25
- package/providers/IntlProvider.tsx +49 -26
- package/utils/loaders.d.ts +4 -5
- package/utils/loaders.js +23 -33
- package/utils/loaders.min.js +1 -1
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
declare const SUPPORTED_LOCALES: string[];
|
|
2
2
|
type Locale = typeof SUPPORTED_LOCALES[number];
|
|
3
|
+
interface TranslationMap {
|
|
4
|
+
[locale: string]: () => Promise<Record<string, any>>;
|
|
5
|
+
}
|
|
6
|
+
interface ModuleTranslations {
|
|
7
|
+
[moduleName: string]: TranslationMap;
|
|
8
|
+
}
|
|
9
|
+
interface TranslationsConfig {
|
|
10
|
+
base: {
|
|
11
|
+
[locale: string]: () => Promise<Record<string, any>>;
|
|
12
|
+
};
|
|
13
|
+
modules?: ModuleTranslations;
|
|
14
|
+
}
|
|
3
15
|
|
|
4
16
|
interface TranslationOptions {
|
|
5
17
|
moduleName?: string;
|
|
@@ -13,7 +25,9 @@ declare class TranslationService {
|
|
|
13
25
|
private currentLocale;
|
|
14
26
|
private loadedModules;
|
|
15
27
|
private supportedLocales;
|
|
16
|
-
|
|
28
|
+
private translationsConfig;
|
|
29
|
+
constructor(supportedLocales?: string[], translationsConfig?: TranslationsConfig);
|
|
30
|
+
setTranslationsConfig(config: TranslationsConfig): void;
|
|
17
31
|
initialize(locale: Locale): Promise<void>;
|
|
18
32
|
loadLocale(locale: Locale): Promise<void>;
|
|
19
33
|
loadModule(moduleName: string): Promise<void>;
|
|
@@ -913,59 +913,96 @@ requireCooks();
|
|
|
913
913
|
const DEFAULT_LOCALE = 'en';
|
|
914
914
|
const SUPPORTED_LOCALES = ['en', 'fr'];
|
|
915
915
|
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
916
|
+
const mergeDeep = (target, source) => {
|
|
917
|
+
if (typeof target !== 'object' || typeof source !== 'object')
|
|
918
|
+
return source;
|
|
919
|
+
const output = Object.assign({}, target);
|
|
920
|
+
for (const key in source) {
|
|
921
|
+
if (source.hasOwnProperty(key)) {
|
|
922
|
+
if (target.hasOwnProperty(key)) {
|
|
923
|
+
output[key] = mergeDeep(target[key], source[key]);
|
|
924
|
+
}
|
|
925
|
+
else {
|
|
926
|
+
output[key] = source[key];
|
|
927
|
+
}
|
|
926
928
|
}
|
|
929
|
+
}
|
|
930
|
+
return output;
|
|
931
|
+
};
|
|
932
|
+
|
|
933
|
+
const loadBaseTranslations = (locale, translationsConfig) => __awaiter(void 0, void 0, void 0, function* () {
|
|
934
|
+
console.log('📥 LOADING base translations for:', locale);
|
|
935
|
+
console.log('📊 Config available:', translationsConfig ? 'YES' : 'NO');
|
|
936
|
+
if (!(translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.base[locale])) {
|
|
937
|
+
console.warn(`❌ No base translations found for locale: ${locale}`);
|
|
938
|
+
console.warn('Available locales:', (translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.base) ? Object.keys(translationsConfig.base) : 'none');
|
|
939
|
+
return {};
|
|
940
|
+
}
|
|
941
|
+
try {
|
|
927
942
|
const loader = translationsConfig.base[locale];
|
|
928
943
|
const result = yield loader();
|
|
929
|
-
console.log(
|
|
944
|
+
console.log(`✅ Base translations loaded for ${locale}:`, Object.keys(result));
|
|
930
945
|
return result;
|
|
931
946
|
}
|
|
932
947
|
catch (error) {
|
|
933
|
-
console.error(
|
|
948
|
+
console.error(`❌ Failed to load base ${locale} translations`, error);
|
|
934
949
|
return {};
|
|
935
950
|
}
|
|
936
951
|
});
|
|
937
|
-
const
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
952
|
+
const loadModulesTranslations = (locale, translationsConfig) => __awaiter(void 0, void 0, void 0, function* () {
|
|
953
|
+
const results = [];
|
|
954
|
+
if (!(translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.modules)) {
|
|
955
|
+
console.warn(`⚠️ No modules configuration found for locale "${locale}"`);
|
|
956
|
+
return results;
|
|
957
|
+
}
|
|
958
|
+
for (const [moduleName, moduleTranslations] of Object.entries(translationsConfig.modules)) {
|
|
959
|
+
if (moduleTranslations[locale]) {
|
|
960
|
+
try {
|
|
961
|
+
const loader = moduleTranslations[locale];
|
|
962
|
+
const translations = yield loader();
|
|
963
|
+
results.push({
|
|
964
|
+
moduleName,
|
|
965
|
+
translations
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
catch (error) {
|
|
969
|
+
console.error(`❌ Failed to load translations for module "${moduleName}" and locale "${locale}"`, error);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
else {
|
|
973
|
+
console.warn(`⚠️ No translations for module "${moduleName}" in locale "${locale}"`);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return results;
|
|
977
|
+
});
|
|
978
|
+
const loadModuleTranslations = (moduleName, locale, translationsConfig) => __awaiter(void 0, void 0, void 0, function* () {
|
|
979
|
+
var _a, _b, _c;
|
|
980
|
+
console.log('📥 LOADING module translations:', { moduleName, locale });
|
|
981
|
+
if (!((_b = (_a = translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.modules) === null || _a === void 0 ? void 0 : _a[moduleName]) === null || _b === void 0 ? void 0 : _b[locale])) {
|
|
982
|
+
console.warn(`❌ No translations config found for module "${moduleName}" and locale "${locale}"`);
|
|
983
|
+
console.warn('Available modules:', (translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.modules) ? Object.keys(translationsConfig.modules) : 'none');
|
|
984
|
+
if ((_c = translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.modules) === null || _c === void 0 ? void 0 : _c[moduleName]) {
|
|
947
985
|
console.warn(`Available locales for ${moduleName}:`, Object.keys(translationsConfig.modules[moduleName]));
|
|
948
986
|
}
|
|
949
987
|
return undefined;
|
|
950
988
|
}
|
|
951
989
|
try {
|
|
952
990
|
const loader = translationsConfig.modules[moduleName][locale];
|
|
953
|
-
console.log('Loader found, loading...');
|
|
954
991
|
const translations = yield loader();
|
|
955
|
-
console.log(
|
|
992
|
+
console.log(`✅ Module ${moduleName} translations loaded for ${locale}:`, Object.keys(translations));
|
|
956
993
|
return {
|
|
957
994
|
moduleName,
|
|
958
995
|
translations
|
|
959
996
|
};
|
|
960
997
|
}
|
|
961
998
|
catch (error) {
|
|
962
|
-
console.error(
|
|
999
|
+
console.error(`❌ Failed to load translations for module "${moduleName}" and locale "${locale}"`, error);
|
|
963
1000
|
return undefined;
|
|
964
1001
|
}
|
|
965
1002
|
});
|
|
966
1003
|
|
|
967
1004
|
class TranslationService {
|
|
968
|
-
constructor(supportedLocales = SUPPORTED_LOCALES) {
|
|
1005
|
+
constructor(supportedLocales = SUPPORTED_LOCALES, translationsConfig) {
|
|
969
1006
|
Object.defineProperty(this, "resources", {
|
|
970
1007
|
enumerable: true,
|
|
971
1008
|
configurable: true,
|
|
@@ -990,70 +1027,86 @@ class TranslationService {
|
|
|
990
1027
|
writable: true,
|
|
991
1028
|
value: SUPPORTED_LOCALES
|
|
992
1029
|
});
|
|
1030
|
+
Object.defineProperty(this, "translationsConfig", {
|
|
1031
|
+
enumerable: true,
|
|
1032
|
+
configurable: true,
|
|
1033
|
+
writable: true,
|
|
1034
|
+
value: null
|
|
1035
|
+
});
|
|
993
1036
|
this.supportedLocales = supportedLocales;
|
|
1037
|
+
if (translationsConfig) {
|
|
1038
|
+
this.translationsConfig = translationsConfig;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
setTranslationsConfig(config) {
|
|
1042
|
+
console.log('🔄 Setting translations config in TranslationService', {
|
|
1043
|
+
baseLocales: Object.keys(config.base),
|
|
1044
|
+
modules: Object.keys(config.modules || {})
|
|
1045
|
+
});
|
|
1046
|
+
this.translationsConfig = config;
|
|
994
1047
|
}
|
|
995
1048
|
initialize(locale) {
|
|
996
1049
|
return __awaiter(this, void 0, void 0, function* () {
|
|
1050
|
+
console.log('🚀 Initializing TranslationService with locale:', locale);
|
|
1051
|
+
if (!this.translationsConfig) {
|
|
1052
|
+
console.error('❌ No translations config set in TranslationService');
|
|
1053
|
+
throw new Error('Translations config not set');
|
|
1054
|
+
}
|
|
997
1055
|
this.currentLocale = locale;
|
|
998
1056
|
yield this.loadLocale(locale);
|
|
999
1057
|
});
|
|
1000
1058
|
}
|
|
1001
1059
|
loadLocale(locale) {
|
|
1002
1060
|
return __awaiter(this, void 0, void 0, function* () {
|
|
1003
|
-
console.log(
|
|
1061
|
+
console.log(`📥 LOADING LOCALE: ${locale}`);
|
|
1004
1062
|
if (!this.supportedLocales.includes(locale)) {
|
|
1005
|
-
console.warn(
|
|
1063
|
+
console.warn(`⚠️ Locale ${locale} is not supported`);
|
|
1006
1064
|
return;
|
|
1007
1065
|
}
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
this.resources[locale] = {
|
|
1012
|
-
core: base
|
|
1013
|
-
};
|
|
1014
|
-
console.log(`Initial resources for ${locale}:`, Object.keys(this.resources[locale]));
|
|
1015
|
-
console.log('Loading existing modules for this locale...');
|
|
1016
|
-
for (const moduleName of this.loadedModules) {
|
|
1017
|
-
console.log(`Loading module ${moduleName} for locale ${locale}...`);
|
|
1018
|
-
const moduleData = yield loadModuleTranslations(moduleName, locale);
|
|
1019
|
-
if (moduleData === null || moduleData === void 0 ? void 0 : moduleData.translations) {
|
|
1020
|
-
this.resources[locale][moduleName] = moduleData.translations;
|
|
1021
|
-
console.log(`Module ${moduleName} added to ${locale} resources`);
|
|
1022
|
-
}
|
|
1023
|
-
else {
|
|
1024
|
-
console.warn(`No translations found for module ${moduleName} in locale ${locale}`);
|
|
1025
|
-
}
|
|
1066
|
+
if (!this.translationsConfig) {
|
|
1067
|
+
console.error('❌ No translations config available');
|
|
1068
|
+
return;
|
|
1026
1069
|
}
|
|
1027
|
-
|
|
1028
|
-
console.log('
|
|
1070
|
+
const base = yield loadBaseTranslations(locale, this.translationsConfig);
|
|
1071
|
+
console.log('✅ Base translations loaded for', locale, ':', Object.keys(base));
|
|
1072
|
+
const allModules = yield loadModulesTranslations(locale, this.translationsConfig);
|
|
1073
|
+
console.log('✅ Modules loaded:', allModules.map(m => m.moduleName));
|
|
1074
|
+
this.resources[locale] = allModules.reduce((acc, { moduleName, translations }) => {
|
|
1075
|
+
return mergeDeep(acc, { [moduleName]: translations });
|
|
1076
|
+
}, { core: base });
|
|
1077
|
+
console.log(`✅ LOCALE ${locale} LOADED - Resources:`, Object.keys(this.resources[locale]));
|
|
1029
1078
|
});
|
|
1030
1079
|
}
|
|
1031
1080
|
loadModule(moduleName) {
|
|
1032
1081
|
return __awaiter(this, void 0, void 0, function* () {
|
|
1033
|
-
console.log(
|
|
1034
|
-
console.log(
|
|
1082
|
+
console.log(`📦 LOADING MODULE: ${moduleName}`);
|
|
1083
|
+
console.log(`📊 Already loaded modules:`, Array.from(this.loadedModules));
|
|
1035
1084
|
if (this.loadedModules.has(moduleName)) {
|
|
1036
|
-
console.log(
|
|
1085
|
+
console.log(`✅ Module ${moduleName} already loaded`);
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
if (!this.translationsConfig) {
|
|
1089
|
+
console.error('❌ No translations config available');
|
|
1037
1090
|
return;
|
|
1038
1091
|
}
|
|
1039
1092
|
for (const locale of this.supportedLocales) {
|
|
1040
|
-
console.log(
|
|
1041
|
-
const moduleData = yield loadModuleTranslations(moduleName, locale);
|
|
1093
|
+
console.log(`📥 Loading module ${moduleName} for locale ${locale}...`);
|
|
1094
|
+
const moduleData = yield loadModuleTranslations(moduleName, locale, this.translationsConfig);
|
|
1042
1095
|
if (moduleData === null || moduleData === void 0 ? void 0 : moduleData.translations) {
|
|
1043
|
-
console.log(
|
|
1096
|
+
console.log(`✅ Found translations for ${moduleName} in ${locale}`);
|
|
1044
1097
|
if (!this.resources[locale]) {
|
|
1045
|
-
console.log(
|
|
1098
|
+
console.log(`📝 Creating resources for locale ${locale}`);
|
|
1046
1099
|
this.resources[locale] = { core: {} };
|
|
1047
1100
|
}
|
|
1048
1101
|
this.resources[locale][moduleName] = moduleData.translations;
|
|
1049
|
-
console.log(
|
|
1102
|
+
console.log(`📊 Resources for ${locale}:`, Object.keys(this.resources[locale]));
|
|
1050
1103
|
}
|
|
1051
1104
|
else {
|
|
1052
|
-
console.warn(
|
|
1105
|
+
console.warn(`⚠️ No translations found for module ${moduleName} in locale ${locale}`);
|
|
1053
1106
|
}
|
|
1054
1107
|
}
|
|
1055
1108
|
this.loadedModules.add(moduleName);
|
|
1056
|
-
console.log(
|
|
1109
|
+
console.log(`✅ MODULE ${moduleName} LOADED successfully`);
|
|
1057
1110
|
});
|
|
1058
1111
|
}
|
|
1059
1112
|
t(key, params = {}, options = {}) {
|
|
@@ -1064,12 +1117,13 @@ class TranslationService {
|
|
|
1064
1117
|
findTranslation(key, moduleName, context, count) {
|
|
1065
1118
|
const resources = this.resources[this.currentLocale];
|
|
1066
1119
|
if (!resources) {
|
|
1067
|
-
console.error(
|
|
1120
|
+
console.error(`❌ No resources found for locale: ${this.currentLocale}`);
|
|
1121
|
+
console.error('Available locales:', Object.keys(this.resources));
|
|
1068
1122
|
return undefined;
|
|
1069
1123
|
}
|
|
1070
1124
|
if (!resources[moduleName]) {
|
|
1071
|
-
console.error(
|
|
1072
|
-
console.error(
|
|
1125
|
+
console.error(`❌ Module "${moduleName}" not found in resources for locale ${this.currentLocale}`);
|
|
1126
|
+
console.error('Available modules:', Object.keys(resources));
|
|
1073
1127
|
return undefined;
|
|
1074
1128
|
}
|
|
1075
1129
|
let translationKey = key;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function __awaiter(e,t,n,o){return new(n=n||Promise)(function(a,t){function i(e){try{s(o.next(e))}catch(e){t(e)}}function r(e){try{s(o.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(i,r)}s((o=o.apply(e,[])).next())})}var hasRequiredTimez,hasRequiredCooks,cooks={},timez={};function requireTimez(){if(!hasRequiredTimez){hasRequiredTimez=1,Object.defineProperty(timez,"__esModule",{value:!0});class m{constructor(e,t=!1){!1===this.dateChecker(e)?this._date=void 0:e instanceof m&&e&&null!=e&&e._date?this._date=new Date(null==e?void 0:e._date):e instanceof Date?this._date=new Date(e):"string"==typeof e?this._date=m.parseString(e,t):"number"==typeof e?this._date=new Date(e):null==e||"number"==typeof e&&isNaN(e)?this._date=new Date:this._date=void 0}static now(){return new m}static parse(e,t){return"string"==typeof t&&0<t.length&&(e instanceof m&&e&&null!=e&&e._date||e instanceof Date||"string"==typeof e||"number"==typeof e||null==e||"number"==typeof e&&isNaN(e))&&m.parseWithFormat(e,t)||new m(e)}static unix(e){return new m(1e3*e)}static utc(){var e=new Date;return new m(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()))}year(){var e;return null==(e=this._date)?void 0:e.getFullYear()}month(){return this._date?this._date.getMonth()+1:void 0}date(){var e;return null==(e=this._date)?void 0:e.getDate()}hour(){var e;return null==(e=this._date)?void 0:e.getHours()}minute(){var e;return null==(e=this._date)?void 0:e.getMinutes()}second(){var e;return null==(e=this._date)?void 0:e.getSeconds()}millisecond(){var e;return null==(e=this._date)?void 0:e.getMilliseconds()}day(){var e;return null==(e=this._date)?void 0:e.getDay()}add(e,t){if(!this._date)return new m(void 0);var a=new Date(this._date);switch(t){case"years":a.setFullYear(a.getFullYear()+e);break;case"months":a.setMonth(a.getMonth()+e);break;case"days":a.setDate(a.getDate()+e);break;case"hours":a.setHours(a.getHours()+e);break;case"minutes":a.setMinutes(a.getMinutes()+e);break;case"seconds":a.setSeconds(a.getSeconds()+e);break;case"milliseconds":a.setMilliseconds(a.getMilliseconds()+e)}return new m(a)}subtract(e,t){return this.add(-e,t)}startOf(e){if(!this._date)return new m(void 0);var t=new Date(this._date);switch(e){case"year":t.setMonth(0,1),t.setHours(0,0,0,0);break;case"month":t.setDate(1),t.setHours(0,0,0,0);break;case"day":t.setHours(0,0,0,0);break;case"hour":t.setMinutes(0,0,0);break;case"minute":t.setSeconds(0,0);break;case"second":t.setMilliseconds(0)}return new m(t)}endOf(e){var t=this.startOf(e);switch(e){case"year":return t.add(1,"years").subtract(1,"milliseconds");case"month":return t.add(1,"months").subtract(1,"milliseconds");case"day":return t.add(1,"days").subtract(1,"milliseconds");case"hour":return t.add(1,"hours").subtract(1,"milliseconds");case"minute":return t.add(1,"minutes").subtract(1,"milliseconds");case"second":return t.add(1,"seconds").subtract(1,"milliseconds");default:return t}}isBefore(e,t="()"){t="]"===t[1],e=e instanceof m?e:new m(e);return!(!this._date||!e._date)&&(!t&&this._date<e._date||!!t&&this._date<=e._date)}isAfter(e,t="()"){t="["===t[0],e=e instanceof m?e:new m(e);return!(!this._date||!e._date)&&(!t&&this._date>e._date||!!t&&this._date>=e._date)}isSame(e,t){var a,e=e instanceof m?e:new m(e);return!t&&this._date&&e._date?this._date.getTime()===e._date.getTime():(a=t?this.startOf(t):void 0,e=t?e.startOf(t):void 0,!!(a&&null!=a&&a._date&&e&&null!=e&&e._date)&&a._date.getTime()===e._date.getTime())}isBetween(e,t,a="()"){var e=e instanceof m?e:new m(e),t=t instanceof m?t:new m(t),i="["===a[0],a="]"===a[1],i=i&&this.isSame(e)||this.isAfter(e),e=a&&this.isSame(t)||this.isBefore(t);return i&&e}format(e){if(!e)return this.toISOString();var t,a,i=m.PREDEFINED_FORMATS[e];if(i)return this.format(i);let r="",s=0;for(;s<e.length;)"["===e[s]?-1===(a=e.indexOf("]",s))?(r+=e[s],s++):(t=e.substring(s+1,a),r+=t,s=a+1):"%"===e[s]&&s+1<e.length?(t="%"+e[s+1],a=m.FORMAT_TOKENS[t],r+=a?a(this):t,s+=2):(r+=e[s],s++);return r}setTimezone(e){var t;return this._date?(t=this._date.getTimezoneOffset(),e=this.parseTimezoneOffset(e),e=new Date(this._date.getTime()+6e4*(e-t)),new m(e)):new m(void 0)}utc(){return this._date?new m(new Date(Date.UTC(this._date.getUTCFullYear(),this._date.getUTCMonth(),this._date.getUTCDate(),this._date.getUTCHours(),this._date.getUTCMinutes(),this._date.getUTCSeconds(),this._date.getUTCMilliseconds()))):new m(void 0)}local(){return this._date?new m(new Date(this._date.getFullYear(),this._date.getMonth(),this._date.getDate(),this._date.getHours(),this._date.getMinutes(),this._date.getSeconds(),this._date.getMilliseconds())):new m(void 0)}toString(){var e;return null==(e=this._date)?void 0:e.toString()}toISOString(){var e;return null==(e=this._date)?void 0:e.toISOString()}toDate(){return this._date?new Date(this._date):void 0}valueOf(){var e;return null==(e=this._date)?void 0:e.getTime()}unix(){return this._date?Math.floor(this._date.getTime()/1e3):void 0}utcOffset(){return this._date?-this._date.getTimezoneOffset():void 0}isCorrect(){return!!this._date&&!isNaN(this._date.getTime())}timezone(){if(this._date)try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone||void 0}catch(e){return this.timezoneFromOffset()}}timezoneAbbr(){if(this._date)try{var e=new Intl.DateTimeFormat("en",{timeZoneName:"short"}).formatToParts(this._date).find(e=>"timeZoneName"===e.type);return(null==e?void 0:e.value)||void 0}catch(e){return this.timezoneAbbrFromOffset()}}timezoneName(){if(this._date)try{var e=new Intl.DateTimeFormat("en",{timeZoneName:"long"}).formatToParts(this._date).find(e=>"timeZoneName"===e.type);return(null==e?void 0:e.value)||void 0}catch(e){return this.timezoneNameFromOffset()}}timezoneOffsetString(){var e=this.utcOffset();if(void 0!==e)return(0<=e?"+":"-")+Math.floor(Math.abs(e)/60).toString().padStart(2,"0")+":"+(Math.abs(e)%60).toString().padStart(2,"0")}dateChecker(e){return e instanceof m&&!!e&&!(null==e||!e._date)||e instanceof Date||"string"==typeof e||"number"==typeof e||null==e||"number"==typeof e&&isNaN(e)}timezoneFromOffset(){var e=this.utcOffset();if(void 0!==e)return{0:"Etc/UTC",60:"Europe/Paris",120:"Europe/Athens",180:"Europe/Moscow",240:"Asia/Dubai",270:"Asia/Tehran",300:"Asia/Karachi",330:"Asia/Kolkata",345:"Asia/Rangoon",360:"Asia/Dhaka",390:"Asia/Yangon",420:"Asia/Bangkok",480:"Asia/Shanghai",525:"Asia/Kathmandu",540:"Asia/Tokyo",570:"Australia/Adelaide",600:"Australia/Sydney",630:"Australia/Lord_Howe",660:"Pacific/Noumea",675:"Australia/Eucla",720:"Pacific/Auckland",780:"Pacific/Chatham","-60":"Atlantic/Azores","-120":"America/Noronha","-180":"America/Argentina/Buenos_Aires","-210":"America/St_Johns","-240":"America/Halifax","-270":"America/Caracas","-300":"America/New_York","-360":"America/Chicago","-420":"America/Denver","-480":"America/Los_Angeles","-540":"America/Anchorage","-600":"Pacific/Honolulu","-660":"Pacific/Pago_Pago","-720":"Pacific/Kiritimati"}[e]||"Etc/GMT"+(0<=e?"-":"+")+Math.abs(e)/60}timezoneAbbrFromOffset(){var e=this.utcOffset();if(void 0!==e)return{0:"GMT",60:"CET","-300":"EST","-360":"CST","-420":"MST","-480":"PST"}[e]||"GMT"+(0<=e?"+":"")+e/60}timezoneNameFromOffset(){var e=this.utcOffset();if(void 0!==e)return{0:"Greenwich Mean Time",60:"Central European Time","-300":"Eastern Standard Time","-360":"Central Standard Time","-420":"Mountain Standard Time","-480":"Pacific Standard Time"}[e]||"GMT"+(0<=e?"+":"")+e/60}isDST(){if(this._date)try{var e=new Date(this._date.getFullYear(),0,1),t=new Date(this._date.getFullYear(),6,1),a=Math.max(e.getTimezoneOffset(),t.getTimezoneOffset());return this._date.getTimezoneOffset()<a}catch(e){}}static parseString(e,t=!1){var a=new Date(e);if(!isNaN(a.getTime()))return a;var i,r=[/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/,/^(\d{4})-(\d{2})-(\d{2})$/,/^(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2})$/,/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/];for(i of r){var s=e.match(i);if(s){s=s.slice(1).map(Number);if(i===r[0])return new Date(Date.UTC(s[0],s[1]-1,s[2],s[3],s[4],s[5],s[6]));if(i===r[1])return new Date(s[0],s[1]-1,s[2]);if(i===r[2])return new Date(s[0],s[1]-1,s[2],s[3],s[4],s[5]);if(i===r[3])return new Date(s[0],s[1]-1,s[2],s[3],s[4],s[5])}}a=new Date(e);if(!isNaN(a.getTime()))return a;if(t)throw new Error("Unable to parse date string: "+e)}static parseWithFormat(e,r){if(e&&r){var s=String(e).trim();if(s){var n={Y:{regex:/\d{4}/,extract:e=>parseInt(e,10)},y:{regex:/\d{2}/,extract:e=>{e=parseInt(e,10);return 70<=e?1900+e:2e3+e}},m:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},d:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},H:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},M:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},S:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},f:{regex:/\d{1,3}/,extract:e=>parseInt(e,10)}},o={year:(new Date).getFullYear(),month:1,day:1,hour:0,minute:0,second:0,millisecond:0};let e=0,t=0,a=!1,i="";for(;t<r.length&&e<s.length;){var d=r[t];if("["===d)a=!0,i="",t++;else if("]"===d&&a){if(s.substring(e,e+i.length)!==i)return;e+=i.length,a=!1,i="",t++}else if(a)i+=d,t++;else if("%"===d&&t+1<r.length){var u=r[t+1],l=n[u];if(l){var c=s.substring(e).match(l.regex);if(!c||0!==c.index)return;var c=c[0],h=l.extract(c);switch(u){case"Y":case"y":o.year=h;break;case"m":o.month=h;break;case"d":o.day=h;break;case"H":o.hour=h;break;case"M":o.minute=h;break;case"S":o.second=h;break;case"f":o.millisecond=h}e+=c.length}else e++;t+=2}else{if(d!==s[e])return;e++,t++}}if(!(o.month<1||12<o.month||o.day<1||31<o.day||o.hour<0||23<o.hour||o.minute<0||59<o.minute||o.second<0||59<o.second||o.millisecond<0||999<o.millisecond))try{var f=new Date(o.year,o.month-1,o.day,o.hour,o.minute,o.second,o.millisecond);if(!isNaN(f.getTime()))return new m(f)}catch(e){}}}}static getTokenLength(e){return{Y:4,y:2,m:2,d:2,H:2,M:2,S:2,f:3,z:5}[e]||1}parseTimezoneOffset(e){var t={UTC:0,EST:-300,EDT:-240,CST:-360,CDT:-300,PST:-480,PDT:-420};return void 0!==t[e.toUpperCase()]?t[e.toUpperCase()]:(t=e.match(/^([+-])(\d{1,2}):?(\d{2})?$/))?("+"===t[1]?1:-1)*(60*parseInt(t[2],10)+(t[3]?parseInt(t[3],10):0)):this._date?-this._date.getTimezoneOffset():0}static get FORMATS(){return Object.assign({},m.PREDEFINED_FORMATS)}static exposeToGlobal(){"undefined"!=typeof window&&(window.Timez=m)}}m.FORMAT_TOKENS={"%Y":e=>null==(e=e.year())?void 0:e.toString().padStart(4,"0"),"%y":e=>null==(e=e.year())?void 0:e.toString().slice(-2).padStart(2,"0"),"%m":e=>null==(e=e.month())?void 0:e.toString().padStart(2,"0"),"%d":e=>null==(e=e.date())?void 0:e.toString().padStart(2,"0"),"%H":e=>null==(e=e.hour())?void 0:e.toString().padStart(2,"0"),"%M":e=>null==(e=e.minute())?void 0:e.toString().padStart(2,"0"),"%S":e=>null==(e=e.second())?void 0:e.toString().padStart(2,"0"),"%f":e=>null==(e=e.millisecond())?void 0:e.toString().padStart(3,"0"),"%z":e=>{e=e.utcOffset();if(e)return(0<=e?"+":"-")+Math.floor(Math.abs(e)/60).toString().padStart(2,"0")+(Math.abs(e)%60).toString().padStart(2,"0")},"%s":e=>{e=e.valueOf();return e?Math.floor(e/1e3).toString():void 0}},m.PREDEFINED_FORMATS={ISO:"%Y-%m-%dT%H:%M:%S.%fZ",ISO_DATE:"%Y-%m-%d",ISO_TIME:"%H:%M:%S.%fZ",COMPACT:"%Y%m%d%H%M%S",SLASH_DATETIME:"%Y/%m/%d %H:%M:%S.%fZ",SLASH_DATETIME_SEC:"%Y/%m/%d %H:%M:%S",SLASH_DATETIME_MIN:"%Y/%m/%d %H:%M",EUROPEAN:"%d/%m/%Y %H:%M:%S GMT%z",SLASH_DATE:"%Y/%m/%d",TIME_MICRO:"%H:%M:%S.%fZ",TIME_SEC:"%H:%M:%S",CUSTOM_GREETING:"[Bonjour celestin, ][la date actuelle est:: le] %d/%m/%Y [à] %H:%M:%S.%f[Z]"},"undefined"!=typeof window&&(window.Timez=m),timez.Timez=m,timez.default=m}return timez}function requireCooks(){if(!hasRequiredCooks){hasRequiredCooks=1,Object.defineProperty(cooks,"__esModule",{value:!0});var r=requireTimez(),e=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];[...e,...e.map(e=>e.toUpperCase())];class t{static set(e,t,a={}){if(this.isBrowser())try{var i=this.serialize(t),r=encodeURIComponent(i),s=this.buildCookieString(e,r,a);document.cookie=s}catch(e){}}static get(e){if(!this.isBrowser())return null;try{var t,a=this.getAllCookies()[e];return a?(t=decodeURIComponent(a),this.deserialize(t)):null}catch(e){return null}}static remove(e,t="/",a){this.isBrowser()&&(t={expires:new Date(0),path:t,domain:a},this.set(e,"",t))}static has(e){return null!==this.get(e)}static keys(){var e;return this.isBrowser()?(e=this.getAllCookies(),Object.keys(e)):[]}static clear(){var e;this.isBrowser()&&(e=this.getAllCookies(),Object.keys(e).forEach(e=>{this.remove(e)}))}static serialize(e){return e instanceof Date?JSON.stringify({__type:"Date",__value:e.toISOString()}):JSON.stringify(e)}static deserialize(e){e=JSON.parse(e);return e&&"object"==typeof e&&"Date"===e.__type?new Date(e.__value):e}static buildCookieString(e,t,a){a=Object.assign(Object.assign({},this.DEFAULT_OPTIONS),a);let i=e+"="+t;if(void 0!==a.expires){let e;e="number"==typeof a.expires?(new r.Timez).add(a.expires,"seconds").toDate()||new Date:a.expires,i+="; expires="+e.toUTCString()}return a.path&&(i+="; path="+a.path),a.domain&&(i+="; domain="+a.domain),a.secure&&(i+="; secure"),a.sameSite&&(i+="; samesite="+a.sameSite),i}static getAllCookies(){return document.cookie.split(";").reduce((e,t)=>{var[t,a]=t.split("=").map(e=>e.trim());return t&&(e[t]=a||""),e},{})}static isBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document}static exposeToGlobal(){"undefined"!=typeof window&&(window.Cooks=t)}}t.DEFAULT_OPTIONS={path:"/",secure:!0,sameSite:"lax"},"undefined"!=typeof window&&(window.Cooks=t),cooks.Cooks=t,cooks.default=t}return cooks}requireCooks();let DEFAULT_LOCALE="en",SUPPORTED_LOCALES=["en","fr"],translationsConfig=null,loadBaseTranslations=e=>__awaiter(void 0,void 0,void 0,function*(){try{return null!=translationsConfig&&translationsConfig.base[e]?yield(0,translationsConfig.base[e])():{}}catch(e){return{}}}),loadModuleTranslations=(e,t)=>__awaiter(void 0,void 0,void 0,function*(){});class TranslationService{constructor(e=SUPPORTED_LOCALES){Object.defineProperty(this,"resources",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"currentLocale",{enumerable:!0,configurable:!0,writable:!0,value:DEFAULT_LOCALE}),Object.defineProperty(this,"loadedModules",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"supportedLocales",{enumerable:!0,configurable:!0,writable:!0,value:SUPPORTED_LOCALES}),this.supportedLocales=e}initialize(e){return __awaiter(this,void 0,void 0,function*(){this.currentLocale=e,yield this.loadLocale(e)})}loadLocale(i){return __awaiter(this,void 0,void 0,function*(){if(this.supportedLocales.includes(i)){var e,t=yield loadBaseTranslations(i);this.resources[i]={core:t};for(e of this.loadedModules){var a=yield loadModuleTranslations(e,i);null!=a&&a.translations&&(this.resources[i][e]=a.translations)}}})}loadModule(a){return __awaiter(this,void 0,void 0,function*(){if(!this.loadedModules.has(a)){for(var e of this.supportedLocales){var t=yield loadModuleTranslations(a,e);null!=t&&t.translations&&(this.resources[e]||(this.resources[e]={core:{}}),this.resources[e][a]=t.translations)}this.loadedModules.add(a)}})}t(e,t={},a={}){var{moduleName:a="core",defaultValue:i=e,count:r,context:s}=a,e=this.findTranslation(e,a,s,r)||i;return this.interpolate(e,t)}findTranslation(t,a,i,r){var s=this.resources[this.currentLocale];if(s&&s[a]){let e=i?t+"_"+i:t;return void 0!==r&&(e=this.pluralizeKey(e,r)),t.split(".").reduce((e,t)=>e&&void 0!==e[t]?e[t]:void 0,s[a])}}pluralizeKey(e,t){return e+"_"+new Intl.PluralRules(this.currentLocale).select(t)}interpolate(e,t){return Object.entries(t).reduce((e,[t,a])=>e.replace(new RegExp(`\\{${t}\\}`,"g"),String(a)),e)}setLocale(e){this.supportedLocales.includes(e)&&(this.currentLocale=e)}getCurrentLocale(){return this.currentLocale}}export{TranslationService};
|
|
1
|
+
function __awaiter(e,t,s,o){return new(s=s||Promise)(function(a,t){function i(e){try{n(o.next(e))}catch(e){t(e)}}function r(e){try{n(o.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?a(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,r)}n((o=o.apply(e,[])).next())})}var hasRequiredTimez,hasRequiredCooks,cooks={},timez={};function requireTimez(){if(!hasRequiredTimez){hasRequiredTimez=1,Object.defineProperty(timez,"__esModule",{value:!0});class m{constructor(e,t=!1){!1===this.dateChecker(e)?this._date=void 0:e instanceof m&&e&&null!=e&&e._date?this._date=new Date(null==e?void 0:e._date):e instanceof Date?this._date=new Date(e):"string"==typeof e?this._date=m.parseString(e,t):"number"==typeof e?this._date=new Date(e):null==e||"number"==typeof e&&isNaN(e)?this._date=new Date:this._date=void 0}static now(){return new m}static parse(e,t){return"string"==typeof t&&0<t.length&&(e instanceof m&&e&&null!=e&&e._date||e instanceof Date||"string"==typeof e||"number"==typeof e||null==e||"number"==typeof e&&isNaN(e))&&m.parseWithFormat(e,t)||new m(e)}static unix(e){return new m(1e3*e)}static utc(){var e=new Date;return new m(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()))}year(){var e;return null==(e=this._date)?void 0:e.getFullYear()}month(){return this._date?this._date.getMonth()+1:void 0}date(){var e;return null==(e=this._date)?void 0:e.getDate()}hour(){var e;return null==(e=this._date)?void 0:e.getHours()}minute(){var e;return null==(e=this._date)?void 0:e.getMinutes()}second(){var e;return null==(e=this._date)?void 0:e.getSeconds()}millisecond(){var e;return null==(e=this._date)?void 0:e.getMilliseconds()}day(){var e;return null==(e=this._date)?void 0:e.getDay()}add(e,t){if(!this._date)return new m(void 0);var a=new Date(this._date);switch(t){case"years":a.setFullYear(a.getFullYear()+e);break;case"months":a.setMonth(a.getMonth()+e);break;case"days":a.setDate(a.getDate()+e);break;case"hours":a.setHours(a.getHours()+e);break;case"minutes":a.setMinutes(a.getMinutes()+e);break;case"seconds":a.setSeconds(a.getSeconds()+e);break;case"milliseconds":a.setMilliseconds(a.getMilliseconds()+e)}return new m(a)}subtract(e,t){return this.add(-e,t)}startOf(e){if(!this._date)return new m(void 0);var t=new Date(this._date);switch(e){case"year":t.setMonth(0,1),t.setHours(0,0,0,0);break;case"month":t.setDate(1),t.setHours(0,0,0,0);break;case"day":t.setHours(0,0,0,0);break;case"hour":t.setMinutes(0,0,0);break;case"minute":t.setSeconds(0,0);break;case"second":t.setMilliseconds(0)}return new m(t)}endOf(e){var t=this.startOf(e);switch(e){case"year":return t.add(1,"years").subtract(1,"milliseconds");case"month":return t.add(1,"months").subtract(1,"milliseconds");case"day":return t.add(1,"days").subtract(1,"milliseconds");case"hour":return t.add(1,"hours").subtract(1,"milliseconds");case"minute":return t.add(1,"minutes").subtract(1,"milliseconds");case"second":return t.add(1,"seconds").subtract(1,"milliseconds");default:return t}}isBefore(e,t="()"){t="]"===t[1],e=e instanceof m?e:new m(e);return!(!this._date||!e._date)&&(!t&&this._date<e._date||!!t&&this._date<=e._date)}isAfter(e,t="()"){t="["===t[0],e=e instanceof m?e:new m(e);return!(!this._date||!e._date)&&(!t&&this._date>e._date||!!t&&this._date>=e._date)}isSame(e,t){var a,e=e instanceof m?e:new m(e);return!t&&this._date&&e._date?this._date.getTime()===e._date.getTime():(a=t?this.startOf(t):void 0,e=t?e.startOf(t):void 0,!!(a&&null!=a&&a._date&&e&&null!=e&&e._date)&&a._date.getTime()===e._date.getTime())}isBetween(e,t,a="()"){var e=e instanceof m?e:new m(e),t=t instanceof m?t:new m(t),i="["===a[0],a="]"===a[1],i=i&&this.isSame(e)||this.isAfter(e),e=a&&this.isSame(t)||this.isBefore(t);return i&&e}format(e){if(!e)return this.toISOString();var t,a,i=m.PREDEFINED_FORMATS[e];if(i)return this.format(i);let r="",n=0;for(;n<e.length;)"["===e[n]?-1===(a=e.indexOf("]",n))?(r+=e[n],n++):(t=e.substring(n+1,a),r+=t,n=a+1):"%"===e[n]&&n+1<e.length?(t="%"+e[n+1],a=m.FORMAT_TOKENS[t],r+=a?a(this):t,n+=2):(r+=e[n],n++);return r}setTimezone(e){var t;return this._date?(t=this._date.getTimezoneOffset(),e=this.parseTimezoneOffset(e),e=new Date(this._date.getTime()+6e4*(e-t)),new m(e)):new m(void 0)}utc(){return this._date?new m(new Date(Date.UTC(this._date.getUTCFullYear(),this._date.getUTCMonth(),this._date.getUTCDate(),this._date.getUTCHours(),this._date.getUTCMinutes(),this._date.getUTCSeconds(),this._date.getUTCMilliseconds()))):new m(void 0)}local(){return this._date?new m(new Date(this._date.getFullYear(),this._date.getMonth(),this._date.getDate(),this._date.getHours(),this._date.getMinutes(),this._date.getSeconds(),this._date.getMilliseconds())):new m(void 0)}toString(){var e;return null==(e=this._date)?void 0:e.toString()}toISOString(){var e;return null==(e=this._date)?void 0:e.toISOString()}toDate(){return this._date?new Date(this._date):void 0}valueOf(){var e;return null==(e=this._date)?void 0:e.getTime()}unix(){return this._date?Math.floor(this._date.getTime()/1e3):void 0}utcOffset(){return this._date?-this._date.getTimezoneOffset():void 0}isCorrect(){return!!this._date&&!isNaN(this._date.getTime())}timezone(){if(this._date)try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone||void 0}catch(e){return this.timezoneFromOffset()}}timezoneAbbr(){if(this._date)try{var e=new Intl.DateTimeFormat("en",{timeZoneName:"short"}).formatToParts(this._date).find(e=>"timeZoneName"===e.type);return(null==e?void 0:e.value)||void 0}catch(e){return this.timezoneAbbrFromOffset()}}timezoneName(){if(this._date)try{var e=new Intl.DateTimeFormat("en",{timeZoneName:"long"}).formatToParts(this._date).find(e=>"timeZoneName"===e.type);return(null==e?void 0:e.value)||void 0}catch(e){return this.timezoneNameFromOffset()}}timezoneOffsetString(){var e=this.utcOffset();if(void 0!==e)return(0<=e?"+":"-")+Math.floor(Math.abs(e)/60).toString().padStart(2,"0")+":"+(Math.abs(e)%60).toString().padStart(2,"0")}dateChecker(e){return e instanceof m&&!!e&&!(null==e||!e._date)||e instanceof Date||"string"==typeof e||"number"==typeof e||null==e||"number"==typeof e&&isNaN(e)}timezoneFromOffset(){var e=this.utcOffset();if(void 0!==e)return{0:"Etc/UTC",60:"Europe/Paris",120:"Europe/Athens",180:"Europe/Moscow",240:"Asia/Dubai",270:"Asia/Tehran",300:"Asia/Karachi",330:"Asia/Kolkata",345:"Asia/Rangoon",360:"Asia/Dhaka",390:"Asia/Yangon",420:"Asia/Bangkok",480:"Asia/Shanghai",525:"Asia/Kathmandu",540:"Asia/Tokyo",570:"Australia/Adelaide",600:"Australia/Sydney",630:"Australia/Lord_Howe",660:"Pacific/Noumea",675:"Australia/Eucla",720:"Pacific/Auckland",780:"Pacific/Chatham","-60":"Atlantic/Azores","-120":"America/Noronha","-180":"America/Argentina/Buenos_Aires","-210":"America/St_Johns","-240":"America/Halifax","-270":"America/Caracas","-300":"America/New_York","-360":"America/Chicago","-420":"America/Denver","-480":"America/Los_Angeles","-540":"America/Anchorage","-600":"Pacific/Honolulu","-660":"Pacific/Pago_Pago","-720":"Pacific/Kiritimati"}[e]||"Etc/GMT"+(0<=e?"-":"+")+Math.abs(e)/60}timezoneAbbrFromOffset(){var e=this.utcOffset();if(void 0!==e)return{0:"GMT",60:"CET","-300":"EST","-360":"CST","-420":"MST","-480":"PST"}[e]||"GMT"+(0<=e?"+":"")+e/60}timezoneNameFromOffset(){var e=this.utcOffset();if(void 0!==e)return{0:"Greenwich Mean Time",60:"Central European Time","-300":"Eastern Standard Time","-360":"Central Standard Time","-420":"Mountain Standard Time","-480":"Pacific Standard Time"}[e]||"GMT"+(0<=e?"+":"")+e/60}isDST(){if(this._date)try{var e=new Date(this._date.getFullYear(),0,1),t=new Date(this._date.getFullYear(),6,1),a=Math.max(e.getTimezoneOffset(),t.getTimezoneOffset());return this._date.getTimezoneOffset()<a}catch(e){}}static parseString(e,t=!1){var a=new Date(e);if(!isNaN(a.getTime()))return a;var i,r=[/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/,/^(\d{4})-(\d{2})-(\d{2})$/,/^(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2})$/,/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/];for(i of r){var n=e.match(i);if(n){n=n.slice(1).map(Number);if(i===r[0])return new Date(Date.UTC(n[0],n[1]-1,n[2],n[3],n[4],n[5],n[6]));if(i===r[1])return new Date(n[0],n[1]-1,n[2]);if(i===r[2])return new Date(n[0],n[1]-1,n[2],n[3],n[4],n[5]);if(i===r[3])return new Date(n[0],n[1]-1,n[2],n[3],n[4],n[5])}}a=new Date(e);if(!isNaN(a.getTime()))return a;if(t)throw new Error("Unable to parse date string: "+e)}static parseWithFormat(e,r){if(e&&r){var n=String(e).trim();if(n){var s={Y:{regex:/\d{4}/,extract:e=>parseInt(e,10)},y:{regex:/\d{2}/,extract:e=>{e=parseInt(e,10);return 70<=e?1900+e:2e3+e}},m:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},d:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},H:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},M:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},S:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},f:{regex:/\d{1,3}/,extract:e=>parseInt(e,10)}},o={year:(new Date).getFullYear(),month:1,day:1,hour:0,minute:0,second:0,millisecond:0};let e=0,t=0,a=!1,i="";for(;t<r.length&&e<n.length;){var d=r[t];if("["===d)a=!0,i="",t++;else if("]"===d&&a){if(n.substring(e,e+i.length)!==i)return;e+=i.length,a=!1,i="",t++}else if(a)i+=d,t++;else if("%"===d&&t+1<r.length){var l=r[t+1],u=s[l];if(u){var c=n.substring(e).match(u.regex);if(!c||0!==c.index)return;var c=c[0],h=u.extract(c);switch(l){case"Y":case"y":o.year=h;break;case"m":o.month=h;break;case"d":o.day=h;break;case"H":o.hour=h;break;case"M":o.minute=h;break;case"S":o.second=h;break;case"f":o.millisecond=h}e+=c.length}else e++;t+=2}else{if(d!==n[e])return;e++,t++}}if(!(o.month<1||12<o.month||o.day<1||31<o.day||o.hour<0||23<o.hour||o.minute<0||59<o.minute||o.second<0||59<o.second||o.millisecond<0||999<o.millisecond))try{var f=new Date(o.year,o.month-1,o.day,o.hour,o.minute,o.second,o.millisecond);if(!isNaN(f.getTime()))return new m(f)}catch(e){}}}}static getTokenLength(e){return{Y:4,y:2,m:2,d:2,H:2,M:2,S:2,f:3,z:5}[e]||1}parseTimezoneOffset(e){var t={UTC:0,EST:-300,EDT:-240,CST:-360,CDT:-300,PST:-480,PDT:-420};return void 0!==t[e.toUpperCase()]?t[e.toUpperCase()]:(t=e.match(/^([+-])(\d{1,2}):?(\d{2})?$/))?("+"===t[1]?1:-1)*(60*parseInt(t[2],10)+(t[3]?parseInt(t[3],10):0)):this._date?-this._date.getTimezoneOffset():0}static get FORMATS(){return Object.assign({},m.PREDEFINED_FORMATS)}static exposeToGlobal(){"undefined"!=typeof window&&(window.Timez=m)}}m.FORMAT_TOKENS={"%Y":e=>null==(e=e.year())?void 0:e.toString().padStart(4,"0"),"%y":e=>null==(e=e.year())?void 0:e.toString().slice(-2).padStart(2,"0"),"%m":e=>null==(e=e.month())?void 0:e.toString().padStart(2,"0"),"%d":e=>null==(e=e.date())?void 0:e.toString().padStart(2,"0"),"%H":e=>null==(e=e.hour())?void 0:e.toString().padStart(2,"0"),"%M":e=>null==(e=e.minute())?void 0:e.toString().padStart(2,"0"),"%S":e=>null==(e=e.second())?void 0:e.toString().padStart(2,"0"),"%f":e=>null==(e=e.millisecond())?void 0:e.toString().padStart(3,"0"),"%z":e=>{e=e.utcOffset();if(e)return(0<=e?"+":"-")+Math.floor(Math.abs(e)/60).toString().padStart(2,"0")+(Math.abs(e)%60).toString().padStart(2,"0")},"%s":e=>{e=e.valueOf();return e?Math.floor(e/1e3).toString():void 0}},m.PREDEFINED_FORMATS={ISO:"%Y-%m-%dT%H:%M:%S.%fZ",ISO_DATE:"%Y-%m-%d",ISO_TIME:"%H:%M:%S.%fZ",COMPACT:"%Y%m%d%H%M%S",SLASH_DATETIME:"%Y/%m/%d %H:%M:%S.%fZ",SLASH_DATETIME_SEC:"%Y/%m/%d %H:%M:%S",SLASH_DATETIME_MIN:"%Y/%m/%d %H:%M",EUROPEAN:"%d/%m/%Y %H:%M:%S GMT%z",SLASH_DATE:"%Y/%m/%d",TIME_MICRO:"%H:%M:%S.%fZ",TIME_SEC:"%H:%M:%S",CUSTOM_GREETING:"[Bonjour celestin, ][la date actuelle est:: le] %d/%m/%Y [à] %H:%M:%S.%f[Z]"},"undefined"!=typeof window&&(window.Timez=m),timez.Timez=m,timez.default=m}return timez}function requireCooks(){if(!hasRequiredCooks){hasRequiredCooks=1,Object.defineProperty(cooks,"__esModule",{value:!0});var r=requireTimez(),e=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];[...e,...e.map(e=>e.toUpperCase())];class t{static set(e,t,a={}){if(this.isBrowser())try{var i=this.serialize(t),r=encodeURIComponent(i),n=this.buildCookieString(e,r,a);document.cookie=n}catch(e){}}static get(e){if(!this.isBrowser())return null;try{var t,a=this.getAllCookies()[e];return a?(t=decodeURIComponent(a),this.deserialize(t)):null}catch(e){return null}}static remove(e,t="/",a){this.isBrowser()&&(t={expires:new Date(0),path:t,domain:a},this.set(e,"",t))}static has(e){return null!==this.get(e)}static keys(){var e;return this.isBrowser()?(e=this.getAllCookies(),Object.keys(e)):[]}static clear(){var e;this.isBrowser()&&(e=this.getAllCookies(),Object.keys(e).forEach(e=>{this.remove(e)}))}static serialize(e){return e instanceof Date?JSON.stringify({__type:"Date",__value:e.toISOString()}):JSON.stringify(e)}static deserialize(e){e=JSON.parse(e);return e&&"object"==typeof e&&"Date"===e.__type?new Date(e.__value):e}static buildCookieString(e,t,a){a=Object.assign(Object.assign({},this.DEFAULT_OPTIONS),a);let i=e+"="+t;if(void 0!==a.expires){let e;e="number"==typeof a.expires?(new r.Timez).add(a.expires,"seconds").toDate()||new Date:a.expires,i+="; expires="+e.toUTCString()}return a.path&&(i+="; path="+a.path),a.domain&&(i+="; domain="+a.domain),a.secure&&(i+="; secure"),a.sameSite&&(i+="; samesite="+a.sameSite),i}static getAllCookies(){return document.cookie.split(";").reduce((e,t)=>{var[t,a]=t.split("=").map(e=>e.trim());return t&&(e[t]=a||""),e},{})}static isBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document}static exposeToGlobal(){"undefined"!=typeof window&&(window.Cooks=t)}}t.DEFAULT_OPTIONS={path:"/",secure:!0,sameSite:"lax"},"undefined"!=typeof window&&(window.Cooks=t),cooks.Cooks=t,cooks.default=t}return cooks}requireCooks();let DEFAULT_LOCALE="en",SUPPORTED_LOCALES=["en","fr"],mergeDeep=(e,t)=>{if("object"!=typeof e||"object"!=typeof t)return t;var a,i=Object.assign({},e);for(a in t)t.hasOwnProperty(a)&&(e.hasOwnProperty(a)?i[a]=mergeDeep(e[a],t[a]):i[a]=t[a]);return i},loadBaseTranslations=(t,a)=>__awaiter(void 0,void 0,void 0,function*(){if(null==a||!a.base[t])return{};try{var e=yield(0,a.base[t])();return e}catch(e){return{}}}),loadModulesTranslations=(r,n)=>__awaiter(void 0,void 0,void 0,function*(){var e=[];if(null!=n&&n.modules)for(var[t,a]of Object.entries(n.modules))if(a[r])try{var i=yield(0,a[r])();e.push({moduleName:t,translations:i})}catch(e){}return e}),loadModuleTranslations=(a,i,r)=>__awaiter(void 0,void 0,void 0,function*(){var e;if(null!=(e=null==(e=null==r?void 0:r.modules)?void 0:e[a])&&e[i])try{var t=yield(0,r.modules[a][i])();return{moduleName:a,translations:t}}catch(e){}else null!=(e=null==r?void 0:r.modules)&&e[a]});class TranslationService{constructor(e=SUPPORTED_LOCALES,t){Object.defineProperty(this,"resources",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"currentLocale",{enumerable:!0,configurable:!0,writable:!0,value:DEFAULT_LOCALE}),Object.defineProperty(this,"loadedModules",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"supportedLocales",{enumerable:!0,configurable:!0,writable:!0,value:SUPPORTED_LOCALES}),Object.defineProperty(this,"translationsConfig",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.supportedLocales=e,t&&(this.translationsConfig=t)}setTranslationsConfig(e){this.translationsConfig=e}initialize(e){return __awaiter(this,void 0,void 0,function*(){if(!this.translationsConfig)throw new Error("Translations config not set");this.currentLocale=e,yield this.loadLocale(e)})}loadLocale(a){return __awaiter(this,void 0,void 0,function*(){var e,t;this.supportedLocales.includes(a)&&this.translationsConfig&&(e=yield loadBaseTranslations(a,this.translationsConfig),t=yield loadModulesTranslations(a,this.translationsConfig),this.resources[a]=t.reduce((e,{moduleName:t,translations:a})=>mergeDeep(e,{[t]:a}),{core:e}))})}loadModule(a){return __awaiter(this,void 0,void 0,function*(){if(!this.loadedModules.has(a)&&this.translationsConfig){for(var e of this.supportedLocales){var t=yield loadModuleTranslations(a,e,this.translationsConfig);null!=t&&t.translations&&(this.resources[e]||(this.resources[e]={core:{}}),this.resources[e][a]=t.translations)}this.loadedModules.add(a)}})}t(e,t={},a={}){var{moduleName:a="core",defaultValue:i=e,count:r,context:n}=a,e=this.findTranslation(e,a,n,r)||i;return this.interpolate(e,t)}findTranslation(t,a,i,r){var n=this.resources[this.currentLocale];if(n&&n[a]){let e=i?t+"_"+i:t;return void 0!==r&&(e=this.pluralizeKey(e,r)),t.split(".").reduce((e,t)=>e&&void 0!==e[t]?e[t]:void 0,n[a])}}pluralizeKey(e,t){return e+"_"+new Intl.PluralRules(this.currentLocale).select(t)}interpolate(e,t){return Object.entries(t).reduce((e,[t,a])=>e.replace(new RegExp(`\\{${t}\\}`,"g"),String(a)),e)}setLocale(e){this.supportedLocales.includes(e)&&(this.currentLocale=e)}getCurrentLocale(){return this.currentLocale}}export{TranslationService};
|
|
2
2
|
//# sourceMappingURL=TranslationService.min.js.map
|
package/hooks/useTranslation.jsx
CHANGED
|
@@ -6,8 +6,8 @@ export function useTranslation(moduleName) {
|
|
|
6
6
|
const [isModuleLoading, setIsModuleLoading] = useState(false);
|
|
7
7
|
const [moduleLoaded, setModuleLoaded] = useState(!moduleName);
|
|
8
8
|
const t = useCallback((key, params, options) => {
|
|
9
|
-
if (moduleName && !moduleLoaded) {
|
|
10
|
-
console.warn(
|
|
9
|
+
if (moduleName && !moduleLoaded && !options?.moduleName) {
|
|
10
|
+
console.warn(`⚠️ Module ${moduleName} not loaded yet, using default value`);
|
|
11
11
|
return options?.defaultValue || key;
|
|
12
12
|
}
|
|
13
13
|
const finalOptions = {
|
|
@@ -20,9 +20,10 @@ export function useTranslation(moduleName) {
|
|
|
20
20
|
if (moduleName && !moduleLoaded && !arcIntl.isLoading) {
|
|
21
21
|
setIsModuleLoading(true);
|
|
22
22
|
arcIntl.loadModuleTranslations(moduleName).then(() => {
|
|
23
|
+
console.log(`✅ Module ${moduleName} loaded via useTranslation hook`);
|
|
23
24
|
setModuleLoaded(true);
|
|
24
25
|
}).catch(error => {
|
|
25
|
-
console.error(
|
|
26
|
+
console.error(`❌ Failed to load module ${moduleName}:`, error);
|
|
26
27
|
}).finally(() => {
|
|
27
28
|
setIsModuleLoading(false);
|
|
28
29
|
});
|
|
@@ -34,6 +35,7 @@ export function useTranslation(moduleName) {
|
|
|
34
35
|
currentLocale: arcIntl.currentLocale,
|
|
35
36
|
isLoading: arcIntl.isLoading || isModuleLoading,
|
|
36
37
|
isModuleLoaded: moduleLoaded,
|
|
37
|
-
loadModule: arcIntl.loadModuleTranslations
|
|
38
|
+
loadModule: arcIntl.loadModuleTranslations,
|
|
39
|
+
isInitialized: arcIntl.isInitialized
|
|
38
40
|
};
|
|
39
41
|
}
|
package/hooks/useTranslation.tsx
CHANGED
|
@@ -7,16 +7,16 @@ export function useTranslation(moduleName?: string) {
|
|
|
7
7
|
const [moduleLoaded, setModuleLoaded] = useState(!moduleName);
|
|
8
8
|
|
|
9
9
|
const t = useCallback((key: string, params?: Record<string, any>, options?: any) => {
|
|
10
|
-
if (moduleName && !moduleLoaded) {
|
|
11
|
-
console.warn(
|
|
10
|
+
if (moduleName && !moduleLoaded && !options?.moduleName) {
|
|
11
|
+
console.warn(`⚠️ Module ${moduleName} not loaded yet, using default value`);
|
|
12
12
|
return options?.defaultValue || key;
|
|
13
13
|
}
|
|
14
|
-
|
|
14
|
+
|
|
15
15
|
const finalOptions = {
|
|
16
16
|
...options,
|
|
17
17
|
moduleName: options?.moduleName || moduleName || 'core'
|
|
18
18
|
};
|
|
19
|
-
|
|
19
|
+
|
|
20
20
|
return arcIntl.t(key, params || {}, finalOptions);
|
|
21
21
|
}, [arcIntl, moduleName, moduleLoaded]);
|
|
22
22
|
|
|
@@ -25,10 +25,11 @@ export function useTranslation(moduleName?: string) {
|
|
|
25
25
|
setIsModuleLoading(true);
|
|
26
26
|
arcIntl.loadModuleTranslations(moduleName)
|
|
27
27
|
.then(() => {
|
|
28
|
+
console.log(`✅ Module ${moduleName} loaded via useTranslation hook`);
|
|
28
29
|
setModuleLoaded(true);
|
|
29
30
|
})
|
|
30
31
|
.catch(error => {
|
|
31
|
-
console.error(
|
|
32
|
+
console.error(`❌ Failed to load module ${moduleName}:`, error);
|
|
32
33
|
})
|
|
33
34
|
.finally(() => {
|
|
34
35
|
setIsModuleLoading(false);
|
|
@@ -43,5 +44,6 @@ export function useTranslation(moduleName?: string) {
|
|
|
43
44
|
isLoading: arcIntl.isLoading || isModuleLoading,
|
|
44
45
|
isModuleLoaded: moduleLoaded,
|
|
45
46
|
loadModule: arcIntl.loadModuleTranslations,
|
|
47
|
+
isInitialized: arcIntl.isInitialized,
|
|
46
48
|
};
|
|
47
49
|
};
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.0.
|
|
6
|
+
"version": "0.0.94",
|
|
7
7
|
"description": "INTL est un système de gestion d'internationalisation (i18n) modulaire et performant pour les applications React avec TypeScript/JavaScript. Il fournit une gestion avancée des traductions, un chargement dynamique des modules, et une intégration transparente avec l'écosystème Arc.",
|
|
8
8
|
"main": "index.js",
|
|
9
9
|
"keywords": [],
|
|
@@ -2,80 +2,92 @@ import React from "react";
|
|
|
2
2
|
import { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
|
3
3
|
import { TranslationService } from '../core/TranslationService';
|
|
4
4
|
import { getSavedLocale, saveLocale, SUPPORTED_LOCALES } from '../config';
|
|
5
|
-
import { setTranslationsConfig } from '../utils/loaders';
|
|
6
5
|
const ArcIntlContext = createContext(null);
|
|
7
6
|
const useArcIntlValue = (translationsConfig, supportedLocales = SUPPORTED_LOCALES) => {
|
|
8
|
-
const [service] = useState(() => new TranslationService(supportedLocales));
|
|
7
|
+
const [service] = useState(() => new TranslationService(supportedLocales, translationsConfig));
|
|
9
8
|
const [currentLocale, setCurrentLocale] = useState(getSavedLocale(supportedLocales));
|
|
10
9
|
const [isLoading, setIsLoading] = useState(true);
|
|
11
|
-
const [
|
|
12
|
-
const [initialized, setInitialized] = useState(false);
|
|
13
|
-
useEffect(() => {
|
|
14
|
-
setTranslationsConfig(translationsConfig);
|
|
15
|
-
}, [translationsConfig])
|
|
10
|
+
const [initialized, setInitialized] = useState(false)
|
|
16
11
|
|
|
17
12
|
useEffect(() => {
|
|
18
13
|
const initialize = async () => {
|
|
14
|
+
console.log('🚀 INITIALIZING TranslationService...');
|
|
19
15
|
setIsLoading(true);
|
|
20
16
|
try {
|
|
21
|
-
|
|
22
|
-
|
|
17
|
+
if (!initialized) {
|
|
18
|
+
console.log('📝 First time initialization');
|
|
19
|
+
await service.initialize(currentLocale);
|
|
20
|
+
setInitialized(true);
|
|
21
|
+
} else {
|
|
22
|
+
console.log('🔄 Re-initializing with locale:', currentLocale);
|
|
23
|
+
await service.initialize(currentLocale);
|
|
24
|
+
}
|
|
23
25
|
} catch (error) {
|
|
24
|
-
console.error('Failed to initialize translations:', error);
|
|
26
|
+
console.error('❌ Failed to initialize translations:', error);
|
|
25
27
|
} finally {
|
|
26
28
|
setIsLoading(false);
|
|
27
29
|
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const timer = setTimeout(() => {
|
|
33
|
+
initialize();
|
|
34
|
+
}, 0);
|
|
35
|
+
return () => clearTimeout(timer);
|
|
36
|
+
}, [currentLocale, service, initialized])
|
|
31
37
|
|
|
32
38
|
useEffect(() => {
|
|
33
|
-
if (!initialized || !translationsConfig.modules) return;
|
|
39
|
+
if (!initialized || isLoading || !translationsConfig.modules) return;
|
|
34
40
|
const loadAllModules = async () => {
|
|
41
|
+
console.log('📦 Loading all modules from config...');
|
|
35
42
|
const moduleNames = Object.keys(translationsConfig.modules || {});
|
|
36
43
|
for (const moduleName of moduleNames) {
|
|
37
44
|
try {
|
|
45
|
+
console.log(`📥 Loading module: ${moduleName}`);
|
|
38
46
|
await service.loadModule(moduleName);
|
|
39
|
-
|
|
47
|
+
console.log(`✅ Module ${moduleName} loaded`);
|
|
40
48
|
} catch (error) {
|
|
41
|
-
console.error(
|
|
49
|
+
console.error(`❌ Failed to load module ${moduleName}:`, error);
|
|
42
50
|
}
|
|
43
51
|
}
|
|
44
52
|
};
|
|
45
53
|
loadAllModules();
|
|
46
|
-
}, [initialized, translationsConfig.modules, service]);
|
|
54
|
+
}, [initialized, translationsConfig.modules, service, isLoading]);
|
|
47
55
|
const changeLocale = useCallback(async locale => {
|
|
48
56
|
if (!supportedLocales.includes(locale)) {
|
|
49
|
-
console.warn(
|
|
57
|
+
console.warn(`⚠️ Locale ${locale} is not supported`);
|
|
50
58
|
return;
|
|
51
59
|
}
|
|
52
60
|
if (locale === currentLocale) return;
|
|
53
61
|
setIsLoading(true);
|
|
54
62
|
try {
|
|
63
|
+
console.log(`🔄 Changing locale from ${currentLocale} to ${locale}`);
|
|
55
64
|
await service.initialize(locale);
|
|
56
65
|
setCurrentLocale(locale);
|
|
57
66
|
saveLocale(locale);
|
|
67
|
+
console.log(`✅ Locale changed to ${locale}`);
|
|
58
68
|
} catch (error) {
|
|
59
|
-
console.error('Failed to change locale:', error);
|
|
69
|
+
console.error('❌ Failed to change locale:', error);
|
|
60
70
|
} finally {
|
|
61
71
|
setIsLoading(false);
|
|
62
72
|
}
|
|
63
73
|
}, [currentLocale, supportedLocales, service]);
|
|
64
74
|
const loadModuleTranslations = useCallback(async moduleName => {
|
|
65
|
-
if (loadedModules.has(moduleName)) return;
|
|
66
75
|
setIsLoading(true);
|
|
67
76
|
try {
|
|
77
|
+
console.log(`📥 Manually loading module: ${moduleName}`);
|
|
68
78
|
await service.loadModule(moduleName);
|
|
69
|
-
|
|
79
|
+
console.log(`✅ Module ${moduleName} loaded manually`);
|
|
70
80
|
} catch (error) {
|
|
71
|
-
console.error(
|
|
81
|
+
console.error(`❌ Failed to load module ${moduleName}:`, error);
|
|
72
82
|
throw error;
|
|
73
83
|
} finally {
|
|
74
84
|
setIsLoading(false);
|
|
75
85
|
}
|
|
76
|
-
}, [service
|
|
86
|
+
}, [service]);
|
|
77
87
|
const t = useCallback((key, params, options) => {
|
|
78
|
-
|
|
88
|
+
const result = service.t(key, params || {}, options || {});
|
|
89
|
+
console.log(`🌐 Translation: key="${key}", result="${result}", locale=${service.getCurrentLocale()}`);
|
|
90
|
+
return result;
|
|
79
91
|
}, [service]);
|
|
80
92
|
return {
|
|
81
93
|
t,
|
|
@@ -83,7 +95,7 @@ const useArcIntlValue = (translationsConfig, supportedLocales = SUPPORTED_LOCALE
|
|
|
83
95
|
currentLocale,
|
|
84
96
|
isLoading,
|
|
85
97
|
loadModuleTranslations,
|
|
86
|
-
|
|
98
|
+
isInitialized: initialized
|
|
87
99
|
};
|
|
88
100
|
};
|
|
89
101
|
export const ArcIntlProvider = ({
|
|
@@ -91,6 +103,10 @@ export const ArcIntlProvider = ({
|
|
|
91
103
|
supportedLocales,
|
|
92
104
|
children
|
|
93
105
|
}) => {
|
|
106
|
+
console.log('🎬 ArcIntlProvider rendering with translations:', {
|
|
107
|
+
baseLocales: Object.keys(translations.base),
|
|
108
|
+
modules: Object.keys(translations.modules || {})
|
|
109
|
+
});
|
|
94
110
|
const value = useArcIntlValue(translations, typeof supportedLocales === 'object' && !!Array.isArray(supportedLocales) && supportedLocales.length > 0 ? supportedLocales : SUPPORTED_LOCALES);
|
|
95
111
|
return React.createElement(ArcIntlContext.Provider, {
|
|
96
112
|
value: value
|
|
@@ -100,4 +116,9 @@ export const useArcIntl = () => {
|
|
|
100
116
|
const context = useContext(ArcIntlContext);
|
|
101
117
|
if (!context) throw new Error('useArcIntl must be used within an ArcIntlProvider');
|
|
102
118
|
return context;
|
|
119
|
+
};
|
|
120
|
+
export default {
|
|
121
|
+
useArcIntlValue,
|
|
122
|
+
ArcIntlProvider,
|
|
123
|
+
useArcIntl
|
|
103
124
|
};
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { createContext, useContext, useState, useEffect, useMemo, useCallback } from 'react';
|
|
2
2
|
import { TranslationService } from '../core/TranslationService';
|
|
3
3
|
import { getSavedLocale, saveLocale, SUPPORTED_LOCALES, type TranslationsConfig } from '../config';
|
|
4
|
-
import { setTranslationsConfig } from '../utils/loaders';
|
|
5
4
|
import type { Locale } from '../config';
|
|
6
5
|
|
|
7
6
|
const ArcIntlContext = createContext<ReturnType<typeof useArcIntlValue> | null>(null);
|
|
@@ -10,55 +9,65 @@ const useArcIntlValue = (
|
|
|
10
9
|
translationsConfig: TranslationsConfig,
|
|
11
10
|
supportedLocales: string[] = SUPPORTED_LOCALES
|
|
12
11
|
) => {
|
|
13
|
-
const [service] = useState(() => new TranslationService(supportedLocales));
|
|
12
|
+
const [service] = useState(() => new TranslationService(supportedLocales, translationsConfig));
|
|
14
13
|
const [currentLocale, setCurrentLocale] = useState<Locale>(getSavedLocale(supportedLocales));
|
|
15
14
|
const [isLoading, setIsLoading] = useState(true);
|
|
16
|
-
const [loadedModules, setLoadedModules] = useState<Set<string>>(new Set());
|
|
17
15
|
const [initialized, setInitialized] = useState(false);
|
|
18
16
|
|
|
19
|
-
useEffect(() => {
|
|
20
|
-
setTranslationsConfig(translationsConfig);
|
|
21
|
-
}, [translationsConfig]);
|
|
22
|
-
|
|
23
17
|
|
|
24
18
|
useEffect(() => {
|
|
25
19
|
const initialize = async () => {
|
|
20
|
+
console.log('🚀 INITIALIZING TranslationService...');
|
|
26
21
|
setIsLoading(true);
|
|
27
22
|
try {
|
|
28
|
-
|
|
29
|
-
|
|
23
|
+
if (!initialized) {
|
|
24
|
+
console.log('📝 First time initialization');
|
|
25
|
+
await service.initialize(currentLocale);
|
|
26
|
+
setInitialized(true);
|
|
27
|
+
} else {
|
|
28
|
+
console.log('🔄 Re-initializing with locale:', currentLocale);
|
|
29
|
+
await service.initialize(currentLocale);
|
|
30
|
+
}
|
|
30
31
|
} catch (error) {
|
|
31
|
-
console.error('Failed to initialize translations:', error);
|
|
32
|
+
console.error('❌ Failed to initialize translations:', error);
|
|
32
33
|
} finally {
|
|
33
34
|
setIsLoading(false);
|
|
34
35
|
}
|
|
35
36
|
};
|
|
36
|
-
|
|
37
|
-
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
const timer = setTimeout(() => {
|
|
40
|
+
initialize();
|
|
41
|
+
}, 0);
|
|
42
|
+
|
|
43
|
+
return () => clearTimeout(timer);
|
|
44
|
+
}, [currentLocale, service, initialized]);
|
|
38
45
|
|
|
39
46
|
|
|
40
47
|
useEffect(() => {
|
|
41
|
-
if (!initialized || !translationsConfig.modules) return;
|
|
48
|
+
if (!initialized || isLoading || !translationsConfig.modules) return;
|
|
42
49
|
|
|
43
50
|
const loadAllModules = async () => {
|
|
51
|
+
console.log('📦 Loading all modules from config...');
|
|
44
52
|
const moduleNames = Object.keys(translationsConfig.modules || {});
|
|
45
53
|
|
|
46
54
|
for (const moduleName of moduleNames) {
|
|
47
55
|
try {
|
|
56
|
+
console.log(`📥 Loading module: ${moduleName}`);
|
|
48
57
|
await service.loadModule(moduleName);
|
|
49
|
-
|
|
58
|
+
console.log(`✅ Module ${moduleName} loaded`);
|
|
50
59
|
} catch (error) {
|
|
51
|
-
console.error(
|
|
60
|
+
console.error(`❌ Failed to load module ${moduleName}:`, error);
|
|
52
61
|
}
|
|
53
62
|
}
|
|
54
63
|
};
|
|
55
64
|
|
|
56
65
|
loadAllModules();
|
|
57
|
-
}, [initialized, translationsConfig.modules, service]);
|
|
66
|
+
}, [initialized, translationsConfig.modules, service, isLoading]);
|
|
58
67
|
|
|
59
68
|
const changeLocale = useCallback(async (locale: Locale) => {
|
|
60
69
|
if (!supportedLocales.includes(locale)) {
|
|
61
|
-
console.warn(
|
|
70
|
+
console.warn(`⚠️ Locale ${locale} is not supported`);
|
|
62
71
|
return;
|
|
63
72
|
}
|
|
64
73
|
|
|
@@ -66,33 +75,36 @@ const useArcIntlValue = (
|
|
|
66
75
|
|
|
67
76
|
setIsLoading(true);
|
|
68
77
|
try {
|
|
78
|
+
console.log(`🔄 Changing locale from ${currentLocale} to ${locale}`);
|
|
69
79
|
await service.initialize(locale);
|
|
70
80
|
setCurrentLocale(locale);
|
|
71
81
|
saveLocale(locale);
|
|
82
|
+
console.log(`✅ Locale changed to ${locale}`);
|
|
72
83
|
} catch (error) {
|
|
73
|
-
console.error('Failed to change locale:', error);
|
|
84
|
+
console.error('❌ Failed to change locale:', error);
|
|
74
85
|
} finally {
|
|
75
86
|
setIsLoading(false);
|
|
76
87
|
}
|
|
77
88
|
}, [currentLocale, supportedLocales, service]);
|
|
78
89
|
|
|
79
90
|
const loadModuleTranslations = useCallback(async (moduleName: string) => {
|
|
80
|
-
if (loadedModules.has(moduleName)) return;
|
|
81
|
-
|
|
82
91
|
setIsLoading(true);
|
|
83
92
|
try {
|
|
93
|
+
console.log(`📥 Manually loading module: ${moduleName}`);
|
|
84
94
|
await service.loadModule(moduleName);
|
|
85
|
-
|
|
95
|
+
console.log(`✅ Module ${moduleName} loaded manually`);
|
|
86
96
|
} catch (error) {
|
|
87
|
-
console.error(
|
|
97
|
+
console.error(`❌ Failed to load module ${moduleName}:`, error);
|
|
88
98
|
throw error;
|
|
89
99
|
} finally {
|
|
90
100
|
setIsLoading(false);
|
|
91
101
|
}
|
|
92
|
-
}, [service
|
|
102
|
+
}, [service]);
|
|
93
103
|
|
|
94
104
|
const t = useCallback((key: string, params?: Record<string, any>, options?: any) => {
|
|
95
|
-
|
|
105
|
+
const result = service.t(key, params || {}, options || {});
|
|
106
|
+
console.log(`🌐 Translation: key="${key}", result="${result}", locale=${service.getCurrentLocale()}`);
|
|
107
|
+
return result;
|
|
96
108
|
}, [service]);
|
|
97
109
|
|
|
98
110
|
return {
|
|
@@ -101,7 +113,7 @@ const useArcIntlValue = (
|
|
|
101
113
|
currentLocale,
|
|
102
114
|
isLoading,
|
|
103
115
|
loadModuleTranslations,
|
|
104
|
-
|
|
116
|
+
isInitialized: initialized,
|
|
105
117
|
};
|
|
106
118
|
};
|
|
107
119
|
|
|
@@ -114,6 +126,11 @@ export const ArcIntlProvider: React.FC<{
|
|
|
114
126
|
supportedLocales,
|
|
115
127
|
children,
|
|
116
128
|
}) => {
|
|
129
|
+
console.log('🎬 ArcIntlProvider rendering with translations:', {
|
|
130
|
+
baseLocales: Object.keys(translations.base),
|
|
131
|
+
modules: Object.keys(translations.modules || {})
|
|
132
|
+
});
|
|
133
|
+
|
|
117
134
|
const value = useArcIntlValue(
|
|
118
135
|
translations,
|
|
119
136
|
(typeof supportedLocales === 'object' &&
|
|
@@ -130,4 +147,10 @@ export const useArcIntl = () => {
|
|
|
130
147
|
const context = useContext(ArcIntlContext);
|
|
131
148
|
if (!context) throw new Error('useArcIntl must be used within an ArcIntlProvider');
|
|
132
149
|
return context;
|
|
133
|
-
};
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
export default {
|
|
153
|
+
useArcIntlValue,
|
|
154
|
+
ArcIntlProvider,
|
|
155
|
+
useArcIntl,
|
|
156
|
+
}
|
package/utils/loaders.d.ts
CHANGED
|
@@ -11,15 +11,14 @@ interface TranslationsConfig {
|
|
|
11
11
|
modules?: ModuleTranslations;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
declare const
|
|
15
|
-
declare const
|
|
16
|
-
declare const loadModulesTranslations: (locale: string) => Promise<Array<{
|
|
14
|
+
declare const loadBaseTranslations: (locale: string, translationsConfig: TranslationsConfig) => Promise<Record<string, any>>;
|
|
15
|
+
declare const loadModulesTranslations: (locale: string, translationsConfig: TranslationsConfig) => Promise<Array<{
|
|
17
16
|
moduleName: string;
|
|
18
17
|
translations: Record<string, any>;
|
|
19
18
|
}>>;
|
|
20
|
-
declare const loadModuleTranslations: (moduleName: string, locale: string) => Promise<{
|
|
19
|
+
declare const loadModuleTranslations: (moduleName: string, locale: string, translationsConfig: TranslationsConfig) => Promise<{
|
|
21
20
|
moduleName: string;
|
|
22
21
|
translations: Record<string, any>;
|
|
23
22
|
} | undefined>;
|
|
24
23
|
|
|
25
|
-
export { loadBaseTranslations, loadModuleTranslations, loadModulesTranslations
|
|
24
|
+
export { loadBaseTranslations, loadModuleTranslations, loadModulesTranslations };
|
package/utils/loaders.js
CHANGED
|
@@ -17,35 +17,29 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
|
|
|
17
17
|
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
18
18
|
};
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
console.log('
|
|
23
|
-
translationsConfig
|
|
24
|
-
};
|
|
25
|
-
|
|
20
|
+
const loadBaseTranslations = (locale, translationsConfig) => __awaiter(void 0, void 0, void 0, function* () {
|
|
21
|
+
console.log('📥 LOADING base translations for:', locale);
|
|
22
|
+
console.log('📊 Config available:', translationsConfig ? 'YES' : 'NO');
|
|
23
|
+
if (!(translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.base[locale])) {
|
|
24
|
+
console.warn(`❌ No base translations found for locale: ${locale}`);
|
|
25
|
+
console.warn('Available locales:', (translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.base) ? Object.keys(translationsConfig.base) : 'none');
|
|
26
|
+
return {};
|
|
27
|
+
}
|
|
26
28
|
try {
|
|
27
|
-
console.log('Loading base translations for locale:', locale);
|
|
28
|
-
console.log('Config available:', !!translationsConfig);
|
|
29
|
-
console.log('Base translations available:', (translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.base) ? Object.keys(translationsConfig.base) : 'none');
|
|
30
|
-
if (!(translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.base[locale])) {
|
|
31
|
-
console.warn(`No base translations found for locale: ${locale}`);
|
|
32
|
-
console.warn('Available locales:', (translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.base) ? Object.keys(translationsConfig.base) : 'none');
|
|
33
|
-
return {};
|
|
34
|
-
}
|
|
35
29
|
const loader = translationsConfig.base[locale];
|
|
36
30
|
const result = yield loader();
|
|
37
|
-
console.log(
|
|
31
|
+
console.log(`✅ Base translations loaded for ${locale}:`, Object.keys(result));
|
|
38
32
|
return result;
|
|
39
33
|
}
|
|
40
34
|
catch (error) {
|
|
41
|
-
console.error(
|
|
35
|
+
console.error(`❌ Failed to load base ${locale} translations`, error);
|
|
42
36
|
return {};
|
|
43
37
|
}
|
|
44
38
|
});
|
|
45
|
-
const loadModulesTranslations = (locale) => __awaiter(void 0, void 0, void 0, function* () {
|
|
39
|
+
const loadModulesTranslations = (locale, translationsConfig) => __awaiter(void 0, void 0, void 0, function* () {
|
|
46
40
|
const results = [];
|
|
47
41
|
if (!(translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.modules)) {
|
|
48
|
-
console.warn(
|
|
42
|
+
console.warn(`⚠️ No modules configuration found for locale "${locale}"`);
|
|
49
43
|
return results;
|
|
50
44
|
}
|
|
51
45
|
for (const [moduleName, moduleTranslations] of Object.entries(translationsConfig.modules)) {
|
|
@@ -59,43 +53,39 @@ const loadModulesTranslations = (locale) => __awaiter(void 0, void 0, void 0, fu
|
|
|
59
53
|
});
|
|
60
54
|
}
|
|
61
55
|
catch (error) {
|
|
62
|
-
console.error(
|
|
56
|
+
console.error(`❌ Failed to load translations for module "${moduleName}" and locale "${locale}"`, error);
|
|
63
57
|
}
|
|
64
58
|
}
|
|
65
59
|
else {
|
|
66
|
-
console.warn(
|
|
60
|
+
console.warn(`⚠️ No translations for module "${moduleName}" in locale "${locale}"`);
|
|
67
61
|
}
|
|
68
62
|
}
|
|
69
63
|
return results;
|
|
70
64
|
});
|
|
71
|
-
const loadModuleTranslations = (moduleName, locale) => __awaiter(void 0, void 0, void 0, function* () {
|
|
72
|
-
var _a, _b, _c
|
|
73
|
-
console.log('
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
console.log('Locale exists in module:', ((_c = (_b = translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.modules) === null || _b === void 0 ? void 0 : _b[moduleName]) === null || _c === void 0 ? void 0 : _c[locale]) ? 'yes' : 'no');
|
|
77
|
-
if (!((_e = (_d = translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.modules) === null || _d === void 0 ? void 0 : _d[moduleName]) === null || _e === void 0 ? void 0 : _e[locale])) {
|
|
78
|
-
console.warn(`No translations config found for module "${moduleName}" and locale "${locale}"`);
|
|
65
|
+
const loadModuleTranslations = (moduleName, locale, translationsConfig) => __awaiter(void 0, void 0, void 0, function* () {
|
|
66
|
+
var _a, _b, _c;
|
|
67
|
+
console.log('📥 LOADING module translations:', { moduleName, locale });
|
|
68
|
+
if (!((_b = (_a = translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.modules) === null || _a === void 0 ? void 0 : _a[moduleName]) === null || _b === void 0 ? void 0 : _b[locale])) {
|
|
69
|
+
console.warn(`❌ No translations config found for module "${moduleName}" and locale "${locale}"`);
|
|
79
70
|
console.warn('Available modules:', (translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.modules) ? Object.keys(translationsConfig.modules) : 'none');
|
|
80
|
-
if ((
|
|
71
|
+
if ((_c = translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.modules) === null || _c === void 0 ? void 0 : _c[moduleName]) {
|
|
81
72
|
console.warn(`Available locales for ${moduleName}:`, Object.keys(translationsConfig.modules[moduleName]));
|
|
82
73
|
}
|
|
83
74
|
return undefined;
|
|
84
75
|
}
|
|
85
76
|
try {
|
|
86
77
|
const loader = translationsConfig.modules[moduleName][locale];
|
|
87
|
-
console.log('Loader found, loading...');
|
|
88
78
|
const translations = yield loader();
|
|
89
|
-
console.log(
|
|
79
|
+
console.log(`✅ Module ${moduleName} translations loaded for ${locale}:`, Object.keys(translations));
|
|
90
80
|
return {
|
|
91
81
|
moduleName,
|
|
92
82
|
translations
|
|
93
83
|
};
|
|
94
84
|
}
|
|
95
85
|
catch (error) {
|
|
96
|
-
console.error(
|
|
86
|
+
console.error(`❌ Failed to load translations for module "${moduleName}" and locale "${locale}"`, error);
|
|
97
87
|
return undefined;
|
|
98
88
|
}
|
|
99
89
|
});
|
|
100
90
|
|
|
101
|
-
export { loadBaseTranslations, loadModuleTranslations, loadModulesTranslations
|
|
91
|
+
export { loadBaseTranslations, loadModuleTranslations, loadModulesTranslations };
|
package/utils/loaders.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function __awaiter(n,o,
|
|
1
|
+
function __awaiter(n,o,i,r){return new(i=i||Promise)(function(a,o){function t(n){try{l(r.next(n))}catch(n){o(n)}}function e(n){try{l(r.throw(n))}catch(n){o(n)}}function l(n){var o;n.done?a(n.value):((o=n.value)instanceof i?o:new i(function(n){n(o)})).then(t,e)}l((r=r.apply(n,[])).next())})}let loadBaseTranslations=(o,a)=>__awaiter(void 0,void 0,void 0,function*(){if(null==a||!a.base[o])return{};try{var n=yield(0,a.base[o])();return n}catch(n){return{}}}),loadModulesTranslations=(e,l)=>__awaiter(void 0,void 0,void 0,function*(){var n=[];if(null!=l&&l.modules)for(var[o,a]of Object.entries(l.modules))if(a[e])try{var t=yield(0,a[e])();n.push({moduleName:o,translations:t})}catch(n){}return n}),loadModuleTranslations=(a,t,e)=>__awaiter(void 0,void 0,void 0,function*(){var n;if(null!=(n=null==(n=null==e?void 0:e.modules)?void 0:n[a])&&n[t])try{var o=yield(0,e.modules[a][t])();return{moduleName:a,translations:o}}catch(n){}else null!=(n=null==e?void 0:e.modules)&&n[a]});export{loadBaseTranslations,loadModuleTranslations,loadModulesTranslations};
|
|
2
2
|
//# sourceMappingURL=loaders.min.js.map
|