@esfaenza/localizations 15.2.1 → 15.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/esm2020/lib/core/localization.base.mjs +80 -160
  2. package/esm2020/lib/core/localization.persistor.mjs +103 -0
  3. package/esm2020/lib/locale-persistor/LocalStorageCachePersistor.mjs +25 -0
  4. package/esm2020/lib/locale-persistor/LocalePersistor.mjs +8 -0
  5. package/esm2020/lib/localizations.module.mjs +12 -4
  6. package/esm2020/lib/localizations.service.mjs +52 -38
  7. package/esm2020/lib/models/BaseLocalizationTokens.mjs +14 -0
  8. package/esm2020/lib/models/ItemLocalization.mjs +18 -0
  9. package/esm2020/lib/models/LocaleDefinitions.mjs +32 -0
  10. package/esm2020/lib/models/LocaleObject.mjs +18 -0
  11. package/esm2020/lib/models/LocalizationMissingPolicy.mjs +11 -0
  12. package/esm2020/lib/models/LocalizationModuleConfig.mjs +6 -0
  13. package/esm2020/lib/models/SpecializedLocalization.mjs +16 -0
  14. package/esm2020/lib/tokens.mjs +4 -4
  15. package/esm2020/public-api.mjs +5 -2
  16. package/fesm2015/esfaenza-localizations.mjs +269 -182
  17. package/fesm2015/esfaenza-localizations.mjs.map +1 -1
  18. package/fesm2020/esfaenza-localizations.mjs +262 -178
  19. package/fesm2020/esfaenza-localizations.mjs.map +1 -1
  20. package/lib/core/localization.base.d.ts +12 -59
  21. package/lib/core/localization.persistor.d.ts +57 -0
  22. package/lib/locale-persistor/LocalStorageCachePersistor.d.ts +11 -0
  23. package/lib/locale-persistor/LocalePersistor.d.ts +18 -0
  24. package/lib/localizations.module.d.ts +1 -1
  25. package/lib/localizations.service.d.ts +11 -17
  26. package/lib/models/BaseLocalizationTokens.d.ts +12 -0
  27. package/lib/models/LocalizationMissingPolicy.d.ts +9 -0
  28. package/lib/models/LocalizationModuleConfig.d.ts +17 -0
  29. package/lib/tokens.d.ts +4 -3
  30. package/package.json +1 -1
  31. package/public-api.d.ts +4 -1
  32. package/esm2020/lib/models/classes/ItemLocalization.mjs +0 -18
  33. package/esm2020/lib/models/classes/LocaleDefinitions.mjs +0 -32
  34. package/esm2020/lib/models/classes/LocaleObject.mjs +0 -18
  35. package/esm2020/lib/models/classes/LocalizationModuleConfig.mjs +0 -6
  36. package/esm2020/lib/models/classes/SpecializedLocalization.mjs +0 -16
  37. package/esm2020/lib/models/index.mjs +0 -6
  38. package/lib/models/classes/LocalizationModuleConfig.d.ts +0 -9
  39. package/lib/models/index.d.ts +0 -5
  40. /package/lib/models/{classes/ItemLocalization.d.ts → ItemLocalization.d.ts} +0 -0
  41. /package/lib/models/{classes/LocaleDefinitions.d.ts → LocaleDefinitions.d.ts} +0 -0
  42. /package/lib/models/{classes/LocaleObject.d.ts → LocaleObject.d.ts} +0 -0
  43. /package/lib/models/{classes/SpecializedLocalization.d.ts → SpecializedLocalization.d.ts} +0 -0
@@ -1,12 +1,10 @@
1
+ import { __awaiter } from 'tslib';
1
2
  import * as i0 from '@angular/core';
2
3
  import { InjectionToken, Injectable, Inject, Pipe, Optional, NgModule } from '@angular/core';
4
+ import { take, first } from 'rxjs/operators';
5
+ import { ReplaySubject, of } from 'rxjs';
3
6
  import * as i1 from '@esfaenza/extensions';
4
7
 
5
- /**
6
- * Locale da utilizzare per le traduzioni
7
- */
8
- const LOC_LOCALE = new InjectionToken('LOC_LOCALE');
9
-
10
8
  /**
11
9
  * Contenitore delle localizzazioni collegate ad un testo "base", una per ogni linguaggio supportato
12
10
  */
@@ -74,12 +72,6 @@ LocaleDefinitions.AvailableLocales = [
74
72
  new LocaleObject('en-US', 'English', ['en', 'en-US'])
75
73
  ];
76
74
 
77
- /**
78
- * Classe di configurazione per il modulo di localizzazione
79
- */
80
- class LocalizationModuleConfig {
81
- }
82
-
83
75
  /**
84
76
  * Classe che rappresenta la localizzazione di un test base per una certa lingua
85
77
  */
@@ -96,77 +88,13 @@ class SpecializedLocalization {
96
88
  }
97
89
  }
98
90
 
99
- /**
100
- * Classe singleton che contiene le traduzioni di base (per evitare di ripeterle in oggi classe di traduzione) e le funzioni base per
101
- * inserire e leggere traduzioni in/da una cache
102
- */
103
- class BaseLocalization {
104
- /**
105
- * Costruttore. Da qui utilizzando il metodo statico **BaseLocalization.set** si va a popolare la cache delle traduzioni **BaseTranslations**
106
- */
107
- constructor() {
108
- /**
109
- * Cache di tutte le localizzazioni di base
110
- */
111
- this.BaseTranslations = {};
112
- // Odio sprecare caratteri... soprattutto quando rischio che non vengano minificati
113
- let bt = this.BaseTranslations;
114
- let bl = BaseLocalization;
115
- bl.set(bt, "en->it", "Remove", ["Elimina"]);
116
- bl.set(bt, "en->it", "Paging", ["Paginazione"]);
117
- bl.set(bt, "en->it", "Yes", ["Si"]);
118
- bl.set(bt, "en->it", "No", ["No"]);
119
- bl.set(bt, "en->it", "YES", ["SI'"]);
120
- bl.set(bt, "en->it", "NO", ["NO"]);
121
- bl.set(bt, "en->it", "Found objects", ["Risultati trovati"]);
122
- bl.set(bt, "en->it", "Loading data...", ["Carico i dati..."]);
123
- bl.set(bt, "en->it", "Error during save operations", ["Errori durante il salvataggio"]);
124
- bl.set(bt, "en->it", "Error", ["Errore"]);
125
- bl.set(bt, "en->it", "Warning", ["Avviso"]);
126
- bl.set(bt, "en->it", "Information", ["Informazione"]);
127
- bl.set(bt, "en->it", "Save", ["Salva"]);
128
- bl.set(bt, "en->it", "Back", ["Indietro"]);
129
- bl.set(bt, "en->it", "From", ["Da"]);
130
- bl.set(bt, "en->it", "To", ["A"]);
131
- bl.set(bt, "en->it", "View Chart", ["Vedi Grafico"]);
132
- bl.set(bt, "en->it", "View Table", ["Vedi Tabella"]);
133
- bl.set(bt, "en->it", "Notes", ["Note"]);
134
- bl.set(bt, "en->it", "Edit Notes", ["Modifica Note"]);
135
- bl.set(bt, "en->it", "Cancel", ["Annulla"]);
136
- bl.set(bt, "en->it", "Confirm", ["Conferma"]);
137
- bl.set(bt, "en->it", "View", ["Visualizza"]);
138
- bl.set(bt, "en->it", "Close", ["Chiudi"]);
139
- bl.set(bt, "en->it", "Select", ["Seleziona"]);
140
- bl.set(bt, "en->it", "Meter Reading registered successfully", ["Lettura registrata correttamente"]);
141
- bl.set(bt, "en->it", "Validation errors during save operations", ["Errori di validazione durante il salvataggio"]);
142
- bl.set(bt, "en->it", "Can't register reading", ["Impossibile registrare la lettura"]);
143
- bl.set(bt, "en->it", "Electricity", ["Elettricita"]);
144
- bl.set(bt, "en->it", "Gas", ["Gas"]);
145
- bl.set(bt, "en->it", "Water", ["Acqua"]);
146
- bl.set(bt, "en->it", "Delete", ["Elimina"]);
147
- bl.set(bt, "en->it", "This operation cannot be reverted", ["Questa operazione non puo' essere annullata"]);
148
- bl.set(bt, "en->it", "Hide", ["Nascondi"]);
149
- // Helper validazione
150
- bl.set(bt, "en->it", "Required field", ["Campo richiesto"]);
151
- bl.set(bt, "en->it", "Wrong field format", ["Formato campo errato"]);
152
- bl.set(bt, "en->it", "Wrong field format or field missing", ["Formato campo errato o campo mancante"]);
153
- bl.set(bt, "en->it", "You don't have the required permissions to view this page. The navigation has been blocked", ["Non si hanno privilegi a sufficienza per accedere a questa pagina. La navigazione e' stata bloccata"]);
154
- // Informazioni sulle date
155
- bl.setToken(bt, "en->it", "getDateMonthPosition", "0", ["1"]);
156
- bl.setToken(bt, "en->it", "getDisplayDateMonthPosition", "1", ["1"]);
157
- bl.setToken(bt, "en->it", "getLocale", "en-US", ["it-IT"]);
158
- bl.setToken(bt, "en->it", "getSmallDateFormat", "MM/DD/YYYY", ["DD/MM/YYYY"]);
159
- bl.setToken(bt, "en->it", "getDefaultDateFormat", "MM/DD/YYYY", ["MM/DD/YYYY"]);
160
- bl.setToken(bt, "en->it", "getSmallDateDisplayFormat", "DD/MM/YYYY", ["DD/MM/YYYY"]);
161
- bl.setToken(bt, "en->it", "getFullDateFormat", "MM/DD/YYYY HH:mm:ss", ["DD/MM/YYYY HH:mm:ss"]);
162
- bl.setToken(bt, "en->it", "getFullDateDisplayFormat", "DD/MM/YYYY HH:mm:ss", ["DD/MM/YYYY HH:mm:ss"]);
163
- bl.setToken(bt, "en->it", "getFullDateFormatNoSeconds", "MM/DD/YYYY HH:mm", ["DD/MM/YYYY HH:mm"]);
164
- bl.setToken(bt, "en->it", "getFullDateDisplayFormatNoSeconds", "DD/MM/YYYY HH:mm", ["DD/MM/YYYY HH:mm"]);
91
+ class LocalizationPersistor {
92
+ constructor(LocCache = null) {
93
+ this.LocCache = LocCache;
165
94
  }
166
95
  /**
167
96
  * Imposta la localizzazione di un token all'interno della cache scelta
168
97
  *
169
- * @param {{ [id: string]: ItemLocalization }} locCache Cache all'interno della quale inserire l'informazione del token con le localizzazioni
170
98
  * @param {string} direction Direzione della traduzione, rappresenta la lingua base in cui aspettarsi il testo e le varie lingue in cui viene tradotta.
171
99
  * Ad esempio, "en->it" indica che il parametro **left** è valido per le localizzazioni in inglese, mentre nell'elemento 0 del parametro **right**
172
100
  * è presente l'unica traduzione in italiano, per definire più traduzioni sul lato destro della freccia bisogna concatenarle con la virgola, ad esempio "en->it,jp,ecc"
@@ -174,56 +102,54 @@ class BaseLocalization {
174
102
  * @param {string} left Valore del token per la lingua specificata nel lato immediatamente sinistro alla freccia del parametro **direction**
175
103
  * @param {string} right Array con i valori facenti riferimento all'N-esima lingua del lato destro del parametro **direction**
176
104
  */
177
- static setToken(locCache, direction, token, left, right) {
105
+ setToken(direction, token, left, right) {
178
106
  let parsingRegex = /([a-zA-Z]+)[\s]*->[\s]*([a-zA-Z,\s]+)+/g;
179
107
  var parsingRes = parsingRegex.exec(direction);
180
108
  let from = parsingRes[1];
181
109
  let to = parsingRes[2].replace(/\s/g, '').split(',');
182
110
  let localeFrom = LocaleDefinitions.getByAlias(from);
183
- BaseLocalization._set(locCache, token, localeFrom.id, left, true);
111
+ this._set(token, localeFrom.id, left, true);
184
112
  to.forEach((t, index) => {
185
113
  let localeTo = LocaleDefinitions.getByAlias(t);
186
- BaseLocalization._set(locCache, token, localeTo.id, right[index], true);
114
+ this._set(token, localeTo.id, right[index], true);
187
115
  });
188
116
  }
189
117
  /**
190
118
  * Imposta la localizzazione di una frase all'interno della cache scelta
191
119
  *
192
- * @param {{ [id: string]: ItemLocalization }} locCache Cache all'interno della quale inserire l'informazione della frase con le localizzazioni
193
120
  * @param {string} direction Direzione della traduzione, rappresenta la lingua base in cui aspettarsi il testo e le varie lingue in cui viene tradotta.
194
121
  * Ad esempio, "en->it" indica che il parametro **left** è valido per le localizzazioni in inglese, mentre nell'elemento 0 del parametro **right**
195
122
  * è presente l'unica traduzione in italiano, per definire più traduzioni sul lato destro della freccia bisogna concatenarle con la virgola, ad esempio "en->it,jp,ecc"
196
123
  * @param {string} left Valore della frase per la lingua specificata nel lato immediatamente sinistro alla freccia del parametro **direction**
197
124
  * @param {string} right Array con i valori facenti riferimento all'N-esima lingua del lato destro del parametro **direction**
198
125
  */
199
- static set(locCache, direction, left, right) {
126
+ set(direction, left, right) {
200
127
  let parsingRegex = /([a-zA-Z]+)[\s]*->[\s]*([a-zA-Z,\s]+)+/g;
201
128
  var parsingRes = parsingRegex.exec(direction);
202
129
  let from = parsingRes[1];
203
130
  let to = parsingRes[2].replace(/\s/g, '').split(',');
204
131
  let localeFrom = LocaleDefinitions.getByAlias(from);
205
- BaseLocalization._set(locCache, left, localeFrom.id, left);
132
+ this._set(left, localeFrom.id, left);
206
133
  to.forEach((t, index) => {
207
134
  let localeTo = LocaleDefinitions.getByAlias(t);
208
- BaseLocalization._set(locCache, left, localeTo.id, right[index]);
135
+ this._set(left, localeTo.id, right[index]);
209
136
  });
210
137
  }
211
138
  /**
212
139
  * Imposta all'interno della cache specificata un'unica traduzione partendo da un testo di base
213
140
  *
214
- * @param {{ [id: string]: ItemLocalization }} locCache Cache all'interno della quale inserire l'informazione del testo con le localizzazioni
215
141
  * @param {string} text Testo da tradurre
216
142
  * @param {string} culture Lingua per cui inserire la traduzione
217
143
  * @param {string} translation Traduzione del **text** nella lingua specificata da **culture**
218
144
  * @param {boolean} token Indica se il **text** è un token o è una frase normale
219
145
  */
220
- static _set(locCache, text, culture, translation, token) {
221
- let item = BaseLocalization.findByText(locCache, text, token);
146
+ _set(text, culture, translation, token) {
147
+ let item = this.get(text, token);
222
148
  if (!item) {
223
- locCache[text] = new ItemLocalization(token, text, [new SpecializedLocalization(culture, translation)]);
149
+ this.LocCache[text] = new ItemLocalization(token, text, [new SpecializedLocalization(culture, translation)]);
224
150
  return;
225
151
  }
226
- var trs = BaseLocalization.translationByCulture(item, culture);
152
+ var trs = this.translationByCulture(item, culture);
227
153
  if (trs) {
228
154
  console.warn("Localization already loaded for sentence '" + text + "' and culture " + culture);
229
155
  return;
@@ -233,18 +159,15 @@ class BaseLocalization {
233
159
  /**
234
160
  * Partendo da una cache di localizzazione, dato un testo che può essere o meno un token, cerca quell'elemento all'interno della cache
235
161
  *
236
- * @param {{ [id: string]: ItemLocalization }} locCache Cache all'interno del quale cercare il **text**
237
- * @param {string} text Testo da cercare nella **locCache**
162
+ * @param {string} text Testo da cercare nella **LocCache**
238
163
  * @param {boolean} allowtokens Indica se l'elemento cercato può essere un token o se dev'essere per forza una frase (per evitare rari
239
164
  * casi di collisione in cui magari un token è uguale a una frase tradotta)
240
165
  *
241
166
  * @returns {ItemLocalization} Informazioni di localizzazione per il **text** cercato
242
167
  */
243
- static findByText(locCache, text, allowtokens) {
244
- let possibleItem = locCache[text];
245
- if (!possibleItem)
246
- return null;
247
- var item = allowtokens || !possibleItem.token ? possibleItem : null;
168
+ get(text, allowtokens) {
169
+ let possibleItem = this.LocCache[text];
170
+ var item = possibleItem && (allowtokens || !possibleItem.token) ? possibleItem : null;
248
171
  return item;
249
172
  }
250
173
  /**
@@ -255,7 +178,7 @@ class BaseLocalization {
255
178
  *
256
179
  * @returns {SpecializedLocalization} Informazioni di localizzazione specifiche della lingua richiesta
257
180
  */
258
- static translationByCulture(item, culture) {
181
+ translationByCulture(item, culture) {
259
182
  for (let i = 0; i < item.translations.length; i++) {
260
183
  let trl = item.translations[i];
261
184
  if (trl.culture == culture)
@@ -263,12 +186,178 @@ class BaseLocalization {
263
186
  }
264
187
  return null;
265
188
  }
189
+ }
190
+
191
+ var BaseLocalizationTokens;
192
+ (function (BaseLocalizationTokens) {
193
+ BaseLocalizationTokens["getDateMonthPosition"] = "getDateMonthPosition";
194
+ BaseLocalizationTokens["getDisplayDateMonthPosition"] = "getDisplayDateMonthPosition";
195
+ BaseLocalizationTokens["getLocale"] = "getLocale";
196
+ BaseLocalizationTokens["getSmallDateFormat"] = "getSmallDateFormat";
197
+ BaseLocalizationTokens["getDefaultDateFormat"] = "getDefaultDateFormat";
198
+ BaseLocalizationTokens["getSmallDateDisplayFormat"] = "getSmallDateDisplayFormat";
199
+ BaseLocalizationTokens["getFullDateFormat"] = "getFullDateFormat";
200
+ BaseLocalizationTokens["getFullDateDisplayFormat"] = "getFullDateDisplayFormat";
201
+ BaseLocalizationTokens["getFullDateFormatNoSeconds"] = "getFullDateFormatNoSeconds";
202
+ BaseLocalizationTokens["getFullDateDisplayFormatNoSeconds"] = "getFullDateDisplayFormatNoSeconds";
203
+ })(BaseLocalizationTokens || (BaseLocalizationTokens = {}));
204
+
205
+ /** Locale da utilizzare per le traduzioni */
206
+ const LOC_LOCALE = new InjectionToken('LOC_LOCALE');
207
+ /** Policy da utilizzare per traduzioni mancanti */
208
+ const LOC_MISSING_POLICY = new InjectionToken('LOC_MISSING_POLICY');
209
+
210
+ /** Classe astratta che rappresenta lo stato di persistenza fra la libreria e uno storage */
211
+ class LocalePersistor {
212
+ constructor() {
213
+ /** Chiave su cui salvare il locale */
214
+ this.LOCALE = "LOCALE";
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Classe singleton che contiene le traduzioni di base (per evitare di ripeterle in oggi classe di traduzione) e le funzioni base per
220
+ * inserire e leggere traduzioni in/da una cache
221
+ */
222
+ class BaseLocalization {
223
+ /**
224
+ * Costruttore. Da qui utilizzando il metodo statico **BaseLocalization.set** si va a popolare la cache delle traduzioni **BaseTranslations**
225
+ */
226
+ constructor(LocalePersistor, defaultLocale) {
227
+ this.LocalePersistor = LocalePersistor;
228
+ /**
229
+ * Cache di tutte le localizzazioni di base
230
+ */
231
+ this.LocCache = {};
232
+ /**
233
+ * Locale di riferimento per tutte le traduzioni
234
+ */
235
+ this.Locale = new ReplaySubject(1);
236
+ // Recupero il locale alla partenza del BaseLocalization in modo, spero di dare tempo all'applicazione di tirarlo su
237
+ this.LocalePersistor.recover().pipe(take(1)).subscribe((l) => __awaiter(this, void 0, void 0, function* () {
238
+ if (!l) {
239
+ l = defaultLocale;
240
+ this.LocalePersistor.persist(defaultLocale);
241
+ }
242
+ this.Locale.next(l);
243
+ }));
244
+ this.Persistor = new LocalizationPersistor(this.LocCache);
245
+ this.Persistor.set("en->it", "Remove", ["Elimina"]);
246
+ this.Persistor.set("en->it", "Paging", ["Paginazione"]);
247
+ this.Persistor.set("en->it", "Yes", ["Si"]);
248
+ this.Persistor.set("en->it", "No", ["No"]);
249
+ this.Persistor.set("en->it", "YES", ["SI'"]);
250
+ this.Persistor.set("en->it", "NO", ["NO"]);
251
+ this.Persistor.set("en->it", "Found objects", ["Risultati trovati"]);
252
+ this.Persistor.set("en->it", "Loading data...", ["Carico i dati..."]);
253
+ this.Persistor.set("en->it", "Error during save operations", ["Errori durante il salvataggio"]);
254
+ this.Persistor.set("en->it", "Error", ["Errore"]);
255
+ this.Persistor.set("en->it", "Warning", ["Avviso"]);
256
+ this.Persistor.set("en->it", "Information", ["Informazione"]);
257
+ this.Persistor.set("en->it", "Save", ["Salva"]);
258
+ this.Persistor.set("en->it", "Back", ["Indietro"]);
259
+ this.Persistor.set("en->it", "From", ["Da"]);
260
+ this.Persistor.set("en->it", "To", ["A"]);
261
+ this.Persistor.set("en->it", "View Chart", ["Vedi Grafico"]);
262
+ this.Persistor.set("en->it", "View Table", ["Vedi Tabella"]);
263
+ this.Persistor.set("en->it", "Notes", ["Note"]);
264
+ this.Persistor.set("en->it", "Edit Notes", ["Modifica Note"]);
265
+ this.Persistor.set("en->it", "Cancel", ["Annulla"]);
266
+ this.Persistor.set("en->it", "Confirm", ["Conferma"]);
267
+ this.Persistor.set("en->it", "View", ["Visualizza"]);
268
+ this.Persistor.set("en->it", "Close", ["Chiudi"]);
269
+ this.Persistor.set("en->it", "Select", ["Seleziona"]);
270
+ this.Persistor.set("en->it", "Meter Reading registered successfully", ["Lettura registrata correttamente"]);
271
+ this.Persistor.set("en->it", "Validation errors during save operations", ["Errori di validazione durante il salvataggio"]);
272
+ this.Persistor.set("en->it", "Can't register reading", ["Impossibile registrare la lettura"]);
273
+ this.Persistor.set("en->it", "Electricity", ["Elettricita"]);
274
+ this.Persistor.set("en->it", "Gas", ["Gas"]);
275
+ this.Persistor.set("en->it", "Water", ["Acqua"]);
276
+ this.Persistor.set("en->it", "Delete", ["Elimina"]);
277
+ this.Persistor.set("en->it", "This operation cannot be reverted", ["Questa operazione non puo' essere annullata"]);
278
+ this.Persistor.set("en->it", "Hide", ["Nascondi"]);
279
+ // Helper validazione
280
+ this.Persistor.set("en->it", "Required field", ["Campo richiesto"]);
281
+ this.Persistor.set("en->it", "Wrong field format", ["Formato campo errato"]);
282
+ this.Persistor.set("en->it", "Wrong field format or field missing", ["Formato campo errato o campo mancante"]);
283
+ this.Persistor.set("en->it", "You don't have the required permissions to view this page. The navigation has been blocked", ["Non si hanno privilegi a sufficienza per accedere a questa pagina. La navigazione e' stata bloccata"]);
284
+ // Informazioni sulle date
285
+ this.Persistor.setToken("en->it", BaseLocalizationTokens.getDateMonthPosition, "0", ["1"]);
286
+ this.Persistor.setToken("en->it", BaseLocalizationTokens.getDisplayDateMonthPosition, "1", ["1"]);
287
+ this.Persistor.setToken("en->it", BaseLocalizationTokens.getLocale, "en-US", ["it-IT"]);
288
+ this.Persistor.setToken("en->it", BaseLocalizationTokens.getSmallDateFormat, "MM/DD/YYYY", ["DD/MM/YYYY"]);
289
+ this.Persistor.setToken("en->it", BaseLocalizationTokens.getDefaultDateFormat, "MM/DD/YYYY", ["MM/DD/YYYY"]);
290
+ this.Persistor.setToken("en->it", BaseLocalizationTokens.getSmallDateDisplayFormat, "DD/MM/YYYY", ["DD/MM/YYYY"]);
291
+ this.Persistor.setToken("en->it", BaseLocalizationTokens.getFullDateFormat, "MM/DD/YYYY HH:mm:ss", ["DD/MM/YYYY HH:mm:ss"]);
292
+ this.Persistor.setToken("en->it", BaseLocalizationTokens.getFullDateDisplayFormat, "DD/MM/YYYY HH:mm:ss", ["DD/MM/YYYY HH:mm:ss"]);
293
+ this.Persistor.setToken("en->it", BaseLocalizationTokens.getFullDateFormatNoSeconds, "MM/DD/YYYY HH:mm", ["DD/MM/YYYY HH:mm"]);
294
+ this.Persistor.setToken("en->it", BaseLocalizationTokens.getFullDateDisplayFormatNoSeconds, "DD/MM/YYYY HH:mm", ["DD/MM/YYYY HH:mm"]);
295
+ }
266
296
  }
267
- BaseLocalization.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: BaseLocalization, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
268
- BaseLocalization.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: BaseLocalization });
297
+ BaseLocalization.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: BaseLocalization, deps: [{ token: LocalePersistor }, { token: LOC_LOCALE }], target: i0.ɵɵFactoryTarget.Injectable });
298
+ BaseLocalization.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: BaseLocalization, providedIn: 'root' });
269
299
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: BaseLocalization, decorators: [{
270
- type: Injectable
271
- }], ctorParameters: function () { return []; } });
300
+ type: Injectable,
301
+ args: [{ providedIn: 'root' }]
302
+ }], ctorParameters: function () {
303
+ return [{ type: LocalePersistor }, { type: undefined, decorators: [{
304
+ type: Inject,
305
+ args: [LOC_LOCALE]
306
+ }] }];
307
+ } });
308
+
309
+ // Angular
310
+ /**
311
+ * Pipe che permette di formattare una data in base al formato specificato. Utilizza il **DateService** di **@esfaenza/extensions** per ricondurre l'input a una data valida
312
+ */
313
+ class LocDatePipe {
314
+ /**
315
+ * @ignore
316
+ */
317
+ constructor(dts) {
318
+ this.dts = dts;
319
+ }
320
+ /**
321
+ * Trasformazione della data in input in base al formato richiesto
322
+ *
323
+ * @param {any} value Valore da ricondurre ad una data e formattare
324
+ * @param {string} format Formato in output della data da visualizzare
325
+ *
326
+ * @returns {string} Data formattata in base al formato
327
+ */
328
+ transform(value, format = "DD/MM/YYYY") {
329
+ if (value == null || value === "")
330
+ return null;
331
+ if (!this.dts) {
332
+ console.error("Tentativo di usare loc_date senza DateService. È possibile importare DateService installando e configurando il pacchetto @esfaenza/extensions");
333
+ return null;
334
+ }
335
+ var detatchedValue = JSON.parse(JSON.stringify(value));
336
+ var dt = this.dts.getDateConvertion(detatchedValue);
337
+ return dt.format(format);
338
+ }
339
+ }
340
+ LocDatePipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocDatePipe, deps: [{ token: i1.DateService, optional: true }], target: i0.ɵɵFactoryTarget.Pipe });
341
+ LocDatePipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "15.2.9", ngImport: i0, type: LocDatePipe, name: "loc_date" });
342
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocDatePipe, decorators: [{
343
+ type: Pipe,
344
+ args: [{ name: "loc_date", pure: true }]
345
+ }], ctorParameters: function () {
346
+ return [{ type: i1.DateService, decorators: [{
347
+ type: Optional
348
+ }] }];
349
+ } });
350
+
351
+ /**
352
+ * Enum che rappresenta le policy di comportamento qualore il sistema di localizzazione non trovi la localizzazione cercata,
353
+ * usare **ThrowException** solo se ci si sente infallibili o si vuole debuggare in maniera approfondita l'applicazione
354
+ */
355
+ var LocalizationMissingPolicy;
356
+ (function (LocalizationMissingPolicy) {
357
+ LocalizationMissingPolicy[LocalizationMissingPolicy["PrintEmpty"] = 0] = "PrintEmpty";
358
+ LocalizationMissingPolicy[LocalizationMissingPolicy["PrintSource"] = 1] = "PrintSource";
359
+ LocalizationMissingPolicy[LocalizationMissingPolicy["ThrowException"] = 2] = "ThrowException";
360
+ })(LocalizationMissingPolicy || (LocalizationMissingPolicy = {}));
272
361
 
273
362
  /**
274
363
  * Classe di localizzazione estendibile che permette di specificare le proprie localizzazioni e comunque rendere disponibili le localizzazioni globali
@@ -277,17 +366,23 @@ class LocalizationService {
277
366
  /**
278
367
  * Costruttore
279
368
  *
280
- * @param {string} baseLoc Locale da utilizzare nel momento che questo servizio richiede le traduzioni
369
+ * @param {string} Locale Locale da utilizzare nel momento che questo servizio richiede le traduzioni
281
370
  * @param {baseLocalization} baseLocalization Classe base di localizzazione già fornita a livello di root dalla libreria stessa.
282
371
  * È sufficiente iniettarla nell'eventuale costruttore che estende questa classe e passarla as-is
283
372
  */
284
- constructor(baseLoc, baseLocalization) {
285
- this.baseLoc = baseLoc;
286
- this.baseLocalization = baseLocalization;
373
+ constructor(injector) {
374
+ this.injector = injector;
287
375
  /**
288
376
  * Cache di tutte le localizzazioni disonibili all'interno di questa classe
289
377
  */
290
378
  this.TranslationCache = {};
379
+ this.LocalePersistor = this.injector.get(LocalePersistor);
380
+ this.baseLocalization = this.injector.get(BaseLocalization);
381
+ this.onMissing = this.injector.get(LOC_MISSING_POLICY);
382
+ this.Persistor = new LocalizationPersistor(this.TranslationCache);
383
+ this.baseLocalization.Locale.subscribe(lr => {
384
+ this.Locale = lr;
385
+ });
291
386
  }
292
387
  /**
293
388
  * Imposta la localizzazione di un token all'interno della **TranslationCache**
@@ -300,7 +395,7 @@ class LocalizationService {
300
395
  * @param {string} right Array con i valori facenti riferimento all'N-esima lingua del lato destro del parametro **direction**
301
396
  */
302
397
  setToken(direction, token, left, right) {
303
- BaseLocalization.setToken(this.TranslationCache, direction, token, left, right);
398
+ this.Persistor.setToken(direction, token, left, right);
304
399
  }
305
400
  /**
306
401
  * Imposta la localizzazione di una frase all'interno della **TranslationCache**
@@ -312,7 +407,13 @@ class LocalizationService {
312
407
  * @param {string} right Array con i valori facenti riferimento all'N-esima lingua del lato destro del parametro **direction**
313
408
  */
314
409
  set(direction, left, right) {
315
- BaseLocalization.set(this.TranslationCache, direction, left, right);
410
+ // Controlla di non reinserire la stessa localizzazione presente nel BaseLocalization
411
+ // i controlli per il non reinserimento della stessa localizzazione all'interno della stessa istanza è fatto lato Persistor
412
+ if (this.baseLocalization.Persistor.get(left, false)) {
413
+ console.warn(`La localizzazione per ${left} è già presente fra le localizzazioni base, ignoro l'operazione`);
414
+ return;
415
+ }
416
+ this.Persistor.set(direction, left, right);
316
417
  }
317
418
  /**
318
419
  * Localizza un token
@@ -333,93 +434,51 @@ class LocalizationService {
333
434
  * @returns {string} Frase localizzata
334
435
  */
335
436
  loc(text, allowtokens) {
437
+ if (!this.Locale)
438
+ throw "Il sistema di localizzazione non ha ancora caricato il Locale, assicurarsi di caricare l'APP solo al retrieve del locale'";
336
439
  if (!text || text == "undefined")
337
440
  return "";
338
- // Questo può succedere solo se qualcuno crea questa service a manazza. In quel caso prendo la classe di default e basta
339
- if (this.baseLocalization == null)
340
- this.baseLocalization = new BaseLocalization();
341
441
  // Prendo la localizzazione o dalla cache attuale o dalla cache del servizio base
342
- var item = BaseLocalization.findByText(this.TranslationCache, text, allowtokens) || BaseLocalization.findByText(this.baseLocalization.BaseTranslations, text, allowtokens);
442
+ var item = this.Persistor.get(text, allowtokens) || this.baseLocalization.Persistor.get(text, allowtokens);
343
443
  if (!item) {
344
- console.error("Couldn't find localization for '" + text + "'");
345
- return "";
444
+ let message = `Impossibile trovare la localizzazione per '${text}'`;
445
+ switch (this.onMissing) {
446
+ case LocalizationMissingPolicy.PrintEmpty:
447
+ console.error(message);
448
+ return "";
449
+ case LocalizationMissingPolicy.PrintSource:
450
+ console.warn(message);
451
+ return text;
452
+ case LocalizationMissingPolicy.ThrowException:
453
+ throw message;
454
+ }
346
455
  }
347
- var loc = BaseLocalization.translationByCulture(item, this.baseLoc);
456
+ var loc = this.Persistor.translationByCulture(item, this.Locale);
348
457
  if (!loc) {
349
- console.error("Couldn't find localization for '" + text + "', culture " + this.baseLoc);
458
+ console.error("Impossibile trovare la localizzazione per '" + text + "', culture " + this.Locale);
350
459
  return "";
351
460
  }
352
461
  return loc.translation;
353
462
  }
354
- /**
355
- * Localizzazione per Severity classiche (E per errore, W per warning e I per info)
356
- *
357
- * @param {string} text Severity da tradurre
358
- *
359
- * @returns {string} Severity tradotta
360
- */
361
- locSeverity(text) {
362
- if (text == "E")
363
- return this.loc("Error");
364
- if (text == "W")
365
- return this.loc("Warning");
366
- if (text == "I")
367
- return this.loc("Information");
368
- return "";
463
+ changeLocale(newLocale) {
464
+ return __awaiter(this, void 0, void 0, function* () {
465
+ let locale = yield this.LocalePersistor.recover().toPromise();
466
+ if (newLocale == locale) {
467
+ console.info("Il locale richiesto è lo stesso del locale attuale. Ignoro l'operazione");
468
+ return;
469
+ }
470
+ else {
471
+ yield this.LocalePersistor.persist(newLocale).toPromise();
472
+ location.reload();
473
+ }
474
+ });
369
475
  }
370
476
  }
371
- LocalizationService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocalizationService, deps: [{ token: LOC_LOCALE }, { token: BaseLocalization }], target: i0.ɵɵFactoryTarget.Injectable });
477
+ LocalizationService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocalizationService, deps: [{ token: i0.Injector }], target: i0.ɵɵFactoryTarget.Injectable });
372
478
  LocalizationService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocalizationService });
373
479
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocalizationService, decorators: [{
374
480
  type: Injectable
375
- }], ctorParameters: function () {
376
- return [{ type: undefined, decorators: [{
377
- type: Inject,
378
- args: [LOC_LOCALE]
379
- }] }, { type: BaseLocalization }];
380
- } });
381
-
382
- // Angular
383
- /**
384
- * Pipe che permette di formattare una data in base al formato specificato. Utilizza il **DateService** di **@esfaenza/extensions** per ricondurre l'input a una data valida
385
- */
386
- class LocDatePipe {
387
- /**
388
- * @ignore
389
- */
390
- constructor(dts) {
391
- this.dts = dts;
392
- }
393
- /**
394
- * Trasformazione della data in input in base al formato richiesto
395
- *
396
- * @param {any} value Valore da ricondurre ad una data e formattare
397
- * @param {string} format Formato in output della data da visualizzare
398
- *
399
- * @returns {string} Data formattata in base al formato
400
- */
401
- transform(value, format = "DD/MM/YYYY") {
402
- if (value == null || value === "")
403
- return null;
404
- if (!this.dts) {
405
- console.error("Tentativo di usare loc_date senza DateService. È possibile importare DateService installando e configurando il pacchetto @esfaenza/extensions");
406
- return null;
407
- }
408
- var detatchedValue = JSON.parse(JSON.stringify(value));
409
- var dt = this.dts.getDateConvertion(detatchedValue);
410
- return dt.format(format);
411
- }
412
- }
413
- LocDatePipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocDatePipe, deps: [{ token: i1.DateService, optional: true }], target: i0.ɵɵFactoryTarget.Pipe });
414
- LocDatePipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "15.2.9", ngImport: i0, type: LocDatePipe, name: "loc_date" });
415
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocDatePipe, decorators: [{
416
- type: Pipe,
417
- args: [{ name: "loc_date", pure: true }]
418
- }], ctorParameters: function () {
419
- return [{ type: i1.DateService, decorators: [{
420
- type: Optional
421
- }] }];
422
- } });
481
+ }], ctorParameters: function () { return [{ type: i0.Injector }]; } });
423
482
 
424
483
  // Angular
425
484
  /**
@@ -457,6 +516,26 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImpor
457
516
  args: [{ name: "localize", pure: true }]
458
517
  }], ctorParameters: function () { return [{ type: LocalizationService }]; } });
459
518
 
519
+ // Angular
520
+ class LocalStorageLocalePersistor extends LocalePersistor {
521
+ /** @ignore Vedi classe base */
522
+ persist(locale) {
523
+ localStorage.setItem(this.LOCALE, locale);
524
+ return of(true).pipe(first());
525
+ }
526
+ /** @ignore Vedi classe base */
527
+ recover() {
528
+ var ret = localStorage.getItem(this.LOCALE);
529
+ return of(ret).pipe(first());
530
+ }
531
+ }
532
+ LocalStorageLocalePersistor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocalStorageLocalePersistor, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
533
+ LocalStorageLocalePersistor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocalStorageLocalePersistor });
534
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: LocalStorageLocalePersistor, decorators: [{
535
+ type: Injectable
536
+ }] });
537
+
538
+ // Angular
460
539
  class LocalizationModule {
461
540
  static forRoot(config) {
462
541
  return {
@@ -464,7 +543,9 @@ class LocalizationModule {
464
543
  providers: [
465
544
  LocalizationService,
466
545
  BaseLocalization,
467
- { provide: LOC_LOCALE, useValue: (config === null || config === void 0 ? void 0 : config.locale) || 'it-IT' }
546
+ { provide: LOC_LOCALE, useValue: (config === null || config === void 0 ? void 0 : config.defaultLocale) || 'it-IT' },
547
+ { provide: LOC_MISSING_POLICY, useValue: (config === null || config === void 0 ? void 0 : config.localizationMissingPolicy) || LocalizationMissingPolicy.PrintEmpty },
548
+ { provide: LocalePersistor, useClass: (config === null || config === void 0 ? void 0 : config.localePersistor) || LocalStorageLocalePersistor },
468
549
  ]
469
550
  };
470
551
  }
@@ -480,6 +561,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImpor
480
561
  }]
481
562
  }] });
482
563
 
564
+ /**
565
+ * Classe di configurazione per il modulo di localizzazione
566
+ */
567
+ class LocalizationModuleConfig {
568
+ }
569
+
483
570
  /*
484
571
  * Public API Surface of localizations
485
572
  */
@@ -488,5 +575,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImpor
488
575
  * Generated bundle index. Do not edit.
489
576
  */
490
577
 
491
- export { LOC_LOCALE, LocDatePipe, LocalizationModule, LocalizationModuleConfig, LocalizationService, LocalizePipe };
578
+ export { BaseLocalization, BaseLocalizationTokens, LOC_LOCALE, LOC_MISSING_POLICY, LocDatePipe, LocalizationMissingPolicy, LocalizationModule, LocalizationModuleConfig, LocalizationService, LocalizePipe };
492
579
  //# sourceMappingURL=esfaenza-localizations.mjs.map