@arc-js/intl 0.0.5 → 0.0.7
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/README.md +130 -109
- package/config.d.ts +14 -6
- package/config.js +1 -6
- package/config.min.js +1 -1
- package/core/TranslationService.js +57 -59
- package/core/TranslationService.min.js +1 -1
- package/hooks/useTranslation.jsx +30 -8
- package/hooks/useTranslation.tsx +34 -7
- package/package.json +1 -5
- package/providers/IntlProvider.jsx +69 -21
- package/providers/IntlProvider.tsx +87 -25
- package/utils/loaders.d.ts +15 -1
- package/utils/loaders.js +41 -918
- package/utils/loaders.min.js +1 -1
- package/utils.d.ts +1 -2
- package/utils.js +0 -900
- package/utils.min.js +1 -1
- package/vite.config.ts +0 -14
|
@@ -910,10 +910,8 @@ function requireCooks () {
|
|
|
910
910
|
|
|
911
911
|
requireCooks();
|
|
912
912
|
|
|
913
|
-
var _a;
|
|
914
913
|
const DEFAULT_LOCALE = 'en';
|
|
915
914
|
const SUPPORTED_LOCALES = ['en', 'fr'];
|
|
916
|
-
const SRC_DIR = ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.VITE_APP_SRC_DIR) || '/src';
|
|
917
915
|
|
|
918
916
|
const mergeDeep = (target, source) => {
|
|
919
917
|
if (typeof target !== 'object' || typeof source !== 'object')
|
|
@@ -932,20 +930,15 @@ const mergeDeep = (target, source) => {
|
|
|
932
930
|
return output;
|
|
933
931
|
};
|
|
934
932
|
|
|
935
|
-
|
|
936
|
-
const moduleTranslations = import.meta.glob('@/modules/*/locales/*.json', { eager: false });
|
|
933
|
+
let translationsConfig = null;
|
|
937
934
|
const loadBaseTranslations = (locale) => __awaiter(void 0, void 0, void 0, function* () {
|
|
938
935
|
try {
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
return module.default || module;
|
|
943
|
-
}
|
|
944
|
-
else {
|
|
945
|
-
const module = yield import(
|
|
946
|
-
path);
|
|
947
|
-
return module.default;
|
|
936
|
+
if (!(translationsConfig === null || translationsConfig === void 0 ? void 0 : translationsConfig.base[locale])) {
|
|
937
|
+
console.warn(`No base translations found for locale: ${locale}`);
|
|
938
|
+
return {};
|
|
948
939
|
}
|
|
940
|
+
const loader = translationsConfig.base[locale];
|
|
941
|
+
return yield loader();
|
|
949
942
|
}
|
|
950
943
|
catch (error) {
|
|
951
944
|
console.error(`Failed to load base ${locale} translations`, error);
|
|
@@ -954,27 +947,29 @@ const loadBaseTranslations = (locale) => __awaiter(void 0, void 0, void 0, funct
|
|
|
954
947
|
});
|
|
955
948
|
const loadModulesTranslations = (locale) => __awaiter(void 0, void 0, void 0, function* () {
|
|
956
949
|
const results = [];
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
try {
|
|
961
|
-
const moduleName = match[1];
|
|
962
|
-
const module = yield loader();
|
|
963
|
-
results.push({
|
|
964
|
-
moduleName: moduleName,
|
|
965
|
-
translations: module.default || module
|
|
966
|
-
});
|
|
967
|
-
}
|
|
968
|
-
catch (error) {
|
|
969
|
-
console.error(`Failed to load translations from ${path}`, error);
|
|
970
|
-
}
|
|
971
|
-
}
|
|
950
|
+
{
|
|
951
|
+
console.warn(`No modules configuration found for locale "${locale}"`);
|
|
952
|
+
return results;
|
|
972
953
|
}
|
|
973
|
-
return results;
|
|
974
954
|
});
|
|
975
955
|
const loadModuleTranslations = (moduleName, locale) => __awaiter(void 0, void 0, void 0, function* () {
|
|
976
|
-
|
|
977
|
-
|
|
956
|
+
var _a, _b;
|
|
957
|
+
if (!((_b = (_a = void 0 ) === null || _a === void 0 ? void 0 : _a[moduleName]) === null || _b === void 0 ? void 0 : _b[locale])) {
|
|
958
|
+
console.warn(`No translations config found for module "${moduleName}" and locale "${locale}"`);
|
|
959
|
+
return undefined;
|
|
960
|
+
}
|
|
961
|
+
try {
|
|
962
|
+
const loader = translationsConfig.modules[moduleName][locale];
|
|
963
|
+
const translations = yield loader();
|
|
964
|
+
return {
|
|
965
|
+
moduleName,
|
|
966
|
+
translations
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
catch (error) {
|
|
970
|
+
console.error(`Failed to load translations for module "${moduleName}" and locale "${locale}"`, error);
|
|
971
|
+
return undefined;
|
|
972
|
+
}
|
|
978
973
|
});
|
|
979
974
|
|
|
980
975
|
class TranslationService {
|
|
@@ -1013,58 +1008,61 @@ class TranslationService {
|
|
|
1013
1008
|
}
|
|
1014
1009
|
loadLocale(locale) {
|
|
1015
1010
|
return __awaiter(this, void 0, void 0, function* () {
|
|
1016
|
-
if (!this.supportedLocales.includes(locale))
|
|
1011
|
+
if (!this.supportedLocales.includes(locale)) {
|
|
1017
1012
|
return;
|
|
1018
|
-
|
|
1019
|
-
const
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
console.log(`[@arc-js -> intl -> core -> TranslationService.ts] TranslationService | loadLocale - moduleTranslations:: `, moduleTranslations);
|
|
1023
|
-
this.resources[locale] = moduleTranslations.reduce((acc, { moduleName, translations }) => {
|
|
1013
|
+
}
|
|
1014
|
+
const base = yield loadBaseTranslations(locale);
|
|
1015
|
+
const allModules = yield loadModulesTranslations(locale);
|
|
1016
|
+
this.resources[locale] = allModules.reduce((acc, { moduleName, translations }) => {
|
|
1024
1017
|
return mergeDeep(acc, { [moduleName]: translations });
|
|
1025
|
-
}, { core:
|
|
1026
|
-
console.log(`[@arc-js -> intl -> core -> TranslationService.ts] TranslationService | loadLocale - this.resources:: `, this.resources);
|
|
1018
|
+
}, { core: base });
|
|
1027
1019
|
});
|
|
1028
1020
|
}
|
|
1029
1021
|
loadModule(moduleName) {
|
|
1030
1022
|
return __awaiter(this, void 0, void 0, function* () {
|
|
1031
|
-
|
|
1032
|
-
if (this.loadedModules.has(moduleName))
|
|
1023
|
+
if (this.loadedModules.has(moduleName)) {
|
|
1033
1024
|
return;
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1025
|
+
}
|
|
1026
|
+
for (const locale of this.supportedLocales) {
|
|
1027
|
+
const moduleData = yield loadModuleTranslations(moduleName, locale);
|
|
1028
|
+
if (moduleData === null || moduleData === void 0 ? void 0 : moduleData.translations) {
|
|
1029
|
+
if (!this.resources[locale]) {
|
|
1030
|
+
this.resources[locale] = { core: {} };
|
|
1031
|
+
}
|
|
1032
|
+
this.resources[locale][moduleName] = moduleData.translations;
|
|
1033
|
+
}
|
|
1034
|
+
else {
|
|
1035
|
+
console.warn(`No translations found for module ${moduleName} in locale ${locale}`);
|
|
1041
1036
|
}
|
|
1042
|
-
|
|
1043
|
-
});
|
|
1037
|
+
}
|
|
1044
1038
|
this.loadedModules.add(moduleName);
|
|
1045
1039
|
});
|
|
1046
1040
|
}
|
|
1047
1041
|
t(key, params = {}, options = {}) {
|
|
1048
|
-
const { moduleName, defaultValue = key, count, context } = options;
|
|
1049
|
-
|
|
1050
|
-
const translation = this.findTranslation(key, moduleName || 'core', context, count) || defaultValue;
|
|
1042
|
+
const { moduleName = 'core', defaultValue = key, count, context } = options;
|
|
1043
|
+
const translation = this.findTranslation(key, moduleName, context, count) || defaultValue;
|
|
1051
1044
|
return this.interpolate(translation, params);
|
|
1052
1045
|
}
|
|
1053
1046
|
findTranslation(key, moduleName, context, count) {
|
|
1054
1047
|
const resources = this.resources[this.currentLocale];
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1048
|
+
if (!resources) {
|
|
1049
|
+
console.error(`No resources found for locale: ${this.currentLocale}`);
|
|
1050
|
+
return undefined;
|
|
1051
|
+
}
|
|
1052
|
+
if (!resources[moduleName]) {
|
|
1053
|
+
console.error(`Module "${moduleName}" not found in resources for locale ${this.currentLocale}`);
|
|
1054
|
+
console.error(`Available modules:`, Object.keys(resources));
|
|
1059
1055
|
return undefined;
|
|
1056
|
+
}
|
|
1060
1057
|
let translationKey = key;
|
|
1061
1058
|
if (context)
|
|
1062
1059
|
translationKey = `${key}_${context}`;
|
|
1063
1060
|
if (count !== undefined)
|
|
1064
1061
|
translationKey = this.pluralizeKey(translationKey, count);
|
|
1065
|
-
|
|
1062
|
+
const result = key.split('.').reduce((acc, part) => {
|
|
1066
1063
|
return acc && acc[part] !== undefined ? acc[part] : undefined;
|
|
1067
1064
|
}, resources[moduleName]);
|
|
1065
|
+
return result;
|
|
1068
1066
|
}
|
|
1069
1067
|
pluralizeKey(key, count) {
|
|
1070
1068
|
const rules = new Intl.PluralRules(this.currentLocale);
|
|
@@ -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,_a,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 l=r[t+1],u=n[l];if(u){var c=s.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!==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"],SRC_DIR=(null==(_a=null==process?void 0:process.env)?void 0:_a.VITE_APP_SRC_DIR)||"/src",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},baseTranslations=import.meta.glob("@/locales/*.json",{eager:!1}),moduleTranslations=import.meta.glob("@/modules/*/locales/*.json",{eager:!1}),loadBaseTranslations=a=>__awaiter(void 0,void 0,void 0,function*(){try{var e,t=`@/locales/${a}.json`;return baseTranslations[t]?(e=yield baseTranslations[t]()).default||e:(yield import(t)).default}catch(e){return{}}}),loadModulesTranslations=n=>__awaiter(void 0,void 0,void 0,function*(){var e,t,a=[];for([e,t]of Object.entries(moduleTranslations)){var i=e.match(new RegExp(SRC_DIR+"/modules/([^/]+)/locales/[^/]+\\.json$"));if(i&&e.includes(`/${n}.json`))try{var r=i[1],s=yield t();a.push({moduleName:r,translations:s.default||s})}catch(e){}}return a}),loadModuleTranslations=(t,e)=>__awaiter(void 0,void 0,void 0,function*(){return(yield loadModulesTranslations(e)).find(e=>e.moduleName===t)});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(a){return __awaiter(this,void 0,void 0,function*(){var e,t;this.supportedLocales.includes(a)&&(e=yield loadBaseTranslations(a),t=yield loadModulesTranslations(a),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*(){this.loadedModules.has(a)||((yield Promise.all(this.supportedLocales.map(t=>__awaiter(this,void 0,void 0,function*(){var e=yield loadModuleTranslations(a,t);return{locale:t,translations:e||[]}})))).forEach(({locale:e,translations:t})=>{this.resources[e]||(this.resources[e]={core:{}}),this.resources[e][a]=t}),this.loadedModules.add(a))})}t(e,t={},a={}){var{moduleName:a,defaultValue:i=e,count:r,context:s}=a,e=this.findTranslation(e,a||"core",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,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"],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},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{}}}),loadModulesTranslations=e=>__awaiter(void 0,void 0,void 0,function*(){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(a){return __awaiter(this,void 0,void 0,function*(){var e,t;this.supportedLocales.includes(a)&&(e=yield loadBaseTranslations(a),t=yield loadModulesTranslations(a),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)){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};
|
|
2
2
|
//# sourceMappingURL=TranslationService.min.js.map
|
package/hooks/useTranslation.jsx
CHANGED
|
@@ -1,18 +1,40 @@
|
|
|
1
|
-
|
|
2
|
-
import React from "react"
|
|
3
|
-
import { useEffect } from 'react';
|
|
1
|
+
import { useEffect, useState, useCallback } from 'react';
|
|
4
2
|
import { useArcIntl } from '../providers/IntlProvider';
|
|
5
3
|
export const useTranslation = moduleName => {
|
|
4
|
+
import React from "react";
|
|
5
|
+
|
|
6
6
|
const arcIntl = useArcIntl();
|
|
7
|
+
const [isModuleLoading, setIsModuleLoading] = useState(false);
|
|
8
|
+
const [moduleLoaded, setModuleLoaded] = useState(!moduleName);
|
|
9
|
+
const t = useCallback((key, params, options) => {
|
|
10
|
+
if (moduleName && !moduleLoaded && !options?.moduleName) {
|
|
11
|
+
console.warn(`Module ${moduleName} not loaded yet, using default value`);
|
|
12
|
+
return options?.defaultValue || key;
|
|
13
|
+
}
|
|
14
|
+
const finalOptions = {
|
|
15
|
+
...options,
|
|
16
|
+
moduleName: options?.moduleName || moduleName || 'core'
|
|
17
|
+
};
|
|
18
|
+
return arcIntl.t(key, params || {}, finalOptions);
|
|
19
|
+
}, [arcIntl, moduleName, moduleLoaded]);
|
|
7
20
|
useEffect(() => {
|
|
8
|
-
if (moduleName) {
|
|
9
|
-
|
|
21
|
+
if (moduleName && !moduleLoaded) {
|
|
22
|
+
setIsModuleLoading(true);
|
|
23
|
+
arcIntl.loadModuleTranslations(moduleName).then(() => {
|
|
24
|
+
setModuleLoaded(true);
|
|
25
|
+
}).catch(error => {
|
|
26
|
+
console.error(`Failed to load module ${moduleName}:`, error);
|
|
27
|
+
}).finally(() => {
|
|
28
|
+
setIsModuleLoading(false);
|
|
29
|
+
});
|
|
10
30
|
}
|
|
11
|
-
}, [moduleName]);
|
|
31
|
+
}, [moduleName, moduleLoaded, arcIntl]);
|
|
12
32
|
return {
|
|
13
|
-
t
|
|
33
|
+
t,
|
|
14
34
|
changeLocale: arcIntl.changeLocale,
|
|
15
35
|
currentLocale: arcIntl.currentLocale,
|
|
16
|
-
isLoading: arcIntl.isLoading
|
|
36
|
+
isLoading: arcIntl.isLoading || isModuleLoading,
|
|
37
|
+
isModuleLoaded: moduleLoaded,
|
|
38
|
+
loadModule: arcIntl.loadModuleTranslations
|
|
17
39
|
};
|
|
18
40
|
};
|
package/hooks/useTranslation.tsx
CHANGED
|
@@ -1,20 +1,47 @@
|
|
|
1
|
-
|
|
2
|
-
import { useEffect } from 'react';
|
|
1
|
+
import { useEffect, useState, useCallback } from 'react';
|
|
3
2
|
import { useArcIntl } from '../providers/IntlProvider';
|
|
4
3
|
|
|
5
4
|
export const useTranslation = (moduleName?: string) => {
|
|
6
5
|
const arcIntl = useArcIntl();
|
|
6
|
+
const [isModuleLoading, setIsModuleLoading] = useState(false);
|
|
7
|
+
const [moduleLoaded, setModuleLoaded] = useState(!moduleName);
|
|
8
|
+
|
|
9
|
+
const t = useCallback((key: string, params?: Record<string, any>, options?: any) => {
|
|
10
|
+
if (moduleName && !moduleLoaded && !options?.moduleName) {
|
|
11
|
+
console.warn(`Module ${moduleName} not loaded yet, using default value`);
|
|
12
|
+
return options?.defaultValue || key;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const finalOptions = {
|
|
16
|
+
...options,
|
|
17
|
+
moduleName: options?.moduleName || moduleName || 'core'
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
return arcIntl.t(key, params || {}, finalOptions);
|
|
21
|
+
}, [arcIntl, moduleName, moduleLoaded]);
|
|
7
22
|
|
|
8
23
|
useEffect(() => {
|
|
9
|
-
if (moduleName) {
|
|
10
|
-
|
|
24
|
+
if (moduleName && !moduleLoaded) {
|
|
25
|
+
setIsModuleLoading(true);
|
|
26
|
+
arcIntl.loadModuleTranslations(moduleName)
|
|
27
|
+
.then(() => {
|
|
28
|
+
setModuleLoaded(true);
|
|
29
|
+
})
|
|
30
|
+
.catch(error => {
|
|
31
|
+
console.error(`Failed to load module ${moduleName}:`, error);
|
|
32
|
+
})
|
|
33
|
+
.finally(() => {
|
|
34
|
+
setIsModuleLoading(false);
|
|
35
|
+
});
|
|
11
36
|
}
|
|
12
|
-
}, [moduleName]);
|
|
37
|
+
}, [moduleName, moduleLoaded, arcIntl]);
|
|
13
38
|
|
|
14
39
|
return {
|
|
15
|
-
t
|
|
40
|
+
t,
|
|
16
41
|
changeLocale: arcIntl.changeLocale,
|
|
17
42
|
currentLocale: arcIntl.currentLocale,
|
|
18
|
-
isLoading: arcIntl.isLoading,
|
|
43
|
+
isLoading: arcIntl.isLoading || isModuleLoading,
|
|
44
|
+
isModuleLoaded: moduleLoaded,
|
|
45
|
+
loadModule: arcIntl.loadModuleTranslations,
|
|
19
46
|
};
|
|
20
47
|
};
|
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.7",
|
|
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": [],
|
|
@@ -14,13 +14,9 @@
|
|
|
14
14
|
"login": "npm login"
|
|
15
15
|
},
|
|
16
16
|
"devDependencies": {
|
|
17
|
-
"@vitejs/plugin-react": "^4.3.4",
|
|
18
|
-
"vite": "^6.4.1"
|
|
19
17
|
},
|
|
20
18
|
"dependencies": {
|
|
21
19
|
"react": "^19.2.3",
|
|
22
|
-
"vite-plugin-html": "^3.2.2",
|
|
23
|
-
"vite-tsconfig-paths": "^5.1.4",
|
|
24
20
|
"@arc-js/cooks": "^0.0.3"
|
|
25
21
|
}
|
|
26
22
|
}
|
|
@@ -1,35 +1,77 @@
|
|
|
1
|
-
|
|
2
|
-
import React from "react"
|
|
3
|
-
import { createContext, useContext, useState, useEffect } from 'react';
|
|
1
|
+
import { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
|
4
2
|
import { TranslationService } from '../core/TranslationService';
|
|
5
3
|
import { getSavedLocale, saveLocale, SUPPORTED_LOCALES } from '../config';
|
|
4
|
+
import { setTranslationsConfig } from '../utils/loaders';
|
|
5
|
+
import React from "react";
|
|
6
|
+
|
|
6
7
|
const ArcIntlContext = createContext(null);
|
|
7
|
-
const useArcIntlValue = (supportedLocales = SUPPORTED_LOCALES) => {
|
|
8
|
+
const useArcIntlValue = (translationsConfig, supportedLocales = SUPPORTED_LOCALES) => {
|
|
8
9
|
const [service] = useState(() => new TranslationService(supportedLocales));
|
|
9
|
-
const [currentLocale, setCurrentLocale] = useState(getSavedLocale());
|
|
10
|
+
const [currentLocale, setCurrentLocale] = useState(getSavedLocale(supportedLocales));
|
|
10
11
|
const [isLoading, setIsLoading] = useState(true);
|
|
12
|
+
const [loadedModules, setLoadedModules] = useState(new Set());
|
|
13
|
+
useEffect(() => {
|
|
14
|
+
setTranslationsConfig(translationsConfig);
|
|
15
|
+
}, [translationsConfig]);
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
const loadAllModules = async () => {
|
|
18
|
+
if (translationsConfig.modules) {
|
|
19
|
+
const moduleNames = Object.keys(translationsConfig.modules);
|
|
20
|
+
for (const moduleName of moduleNames) {
|
|
21
|
+
try {
|
|
22
|
+
await service.loadModule(moduleName);
|
|
23
|
+
setLoadedModules(prev => new Set(prev).add(moduleName));
|
|
24
|
+
} catch (error) {
|
|
25
|
+
console.error(`Failed to load module ${moduleName}:`, error);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
loadAllModules();
|
|
31
|
+
}, [translationsConfig.modules, service]);
|
|
11
32
|
useEffect(() => {
|
|
12
33
|
const initialize = async () => {
|
|
13
|
-
|
|
14
|
-
|
|
34
|
+
setIsLoading(true);
|
|
35
|
+
try {
|
|
36
|
+
await service.initialize(currentLocale);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
console.error('Failed to initialize translations:', error);
|
|
39
|
+
} finally {
|
|
40
|
+
setIsLoading(false);
|
|
41
|
+
}
|
|
15
42
|
};
|
|
16
43
|
initialize();
|
|
17
|
-
}, []);
|
|
18
|
-
const changeLocale = async locale => {
|
|
44
|
+
}, [currentLocale, service]);
|
|
45
|
+
const changeLocale = useCallback(async locale => {
|
|
46
|
+
if (!supportedLocales.includes(locale)) {
|
|
47
|
+
console.warn(`Locale ${locale} is not supported`);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (locale === currentLocale) return;
|
|
19
51
|
setIsLoading(true);
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
52
|
+
try {
|
|
53
|
+
setCurrentLocale(locale);
|
|
54
|
+
saveLocale(locale);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
console.error('Failed to change locale:', error);
|
|
57
|
+
setIsLoading(false);
|
|
58
|
+
}
|
|
59
|
+
}, [currentLocale, supportedLocales]);
|
|
60
|
+
const loadModuleTranslations = useCallback(async moduleName => {
|
|
27
61
|
setIsLoading(true);
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
62
|
+
try {
|
|
63
|
+
await service.loadModule(moduleName);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
console.error(`Failed to load module ${moduleName}:`, error);
|
|
66
|
+
} finally {
|
|
67
|
+
setIsLoading(false);
|
|
68
|
+
}
|
|
69
|
+
}, [service]);
|
|
70
|
+
const t = useCallback((key, params, options) => {
|
|
71
|
+
return service.t(key, params || {}, options || {});
|
|
72
|
+
}, [service]);
|
|
31
73
|
return {
|
|
32
|
-
t
|
|
74
|
+
t,
|
|
33
75
|
changeLocale,
|
|
34
76
|
currentLocale,
|
|
35
77
|
isLoading,
|
|
@@ -37,10 +79,11 @@ const useArcIntlValue = (supportedLocales = SUPPORTED_LOCALES) => {
|
|
|
37
79
|
};
|
|
38
80
|
};
|
|
39
81
|
export const ArcIntlProvider = ({
|
|
82
|
+
translations,
|
|
40
83
|
supportedLocales,
|
|
41
84
|
children
|
|
42
85
|
}) => {
|
|
43
|
-
const value = useArcIntlValue(typeof supportedLocales === 'object' && !!Array.isArray(supportedLocales) && supportedLocales.length > 0 ? supportedLocales : SUPPORTED_LOCALES);
|
|
86
|
+
const value = useArcIntlValue(translations, typeof supportedLocales === 'object' && !!Array.isArray(supportedLocales) && supportedLocales.length > 0 ? supportedLocales : SUPPORTED_LOCALES);
|
|
44
87
|
return React.createElement(ArcIntlContext.Provider, {
|
|
45
88
|
value: value
|
|
46
89
|
}, children);
|
|
@@ -49,4 +92,9 @@ export const useArcIntl = () => {
|
|
|
49
92
|
const context = useContext(ArcIntlContext);
|
|
50
93
|
if (!context) throw new Error('useArcIntl must be used within an ArcIntlProvider');
|
|
51
94
|
return context;
|
|
95
|
+
};
|
|
96
|
+
export default {
|
|
97
|
+
useArcIntlValue,
|
|
98
|
+
ArcIntlProvider,
|
|
99
|
+
useArcIntl
|
|
52
100
|
};
|