@esfaenza/localizations 11.2.9 → 11.2.11

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