@o3r/transloco 15.3.0-prerelease.9 → 15.4.0-prerelease.0

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.
@@ -1,1188 +1,998 @@
1
- import { immutablePrimitive, deepFill, otterComponentInfoPropertyName, sendOtterMessage, filterMessageContent } from '@o3r/core';
2
- import * as i0 from '@angular/core';
3
- import { InjectionToken, inject, Injectable, Injector, Optional, NgModule, makeEnvironmentProviders, signal, ChangeDetectorRef, Pipe, RendererFactory2, LOCALE_ID, isDevMode, ElementRef, Renderer2, TemplateRef, DestroyRef, SimpleChange, Input, Directive, ApplicationRef } from '@angular/core';
4
- import { TRANSLOCO_LOADER, TranslocoService, provideTransloco, TranslocoDirective, TranslocoPipe, TRANSLOCO_SCOPE, TRANSLOCO_LANG, TRANSLOCO_TRANSPILER } from '@jsverse/transloco';
5
- import { from, of, combineLatest, startWith, switchMap as switchMap$1, map as map$1, distinctUntilChanged, firstValueFrom, shareReplay, Subject, lastValueFrom, fromEvent } from 'rxjs';
6
- import { DynamicContentService } from '@o3r/dynamic-content';
7
- import { LoggerService } from '@o3r/logger';
8
- import { switchMap, catchError, map } from 'rxjs/operators';
9
- import { CurrencyPipe, DatePipe, DecimalPipe } from '@angular/common';
10
- import { toObservable, takeUntilDestroyed } from '@angular/core/rxjs-interop';
11
- import * as i1 from '@ngrx/store';
12
- import { createAction, props, on, createReducer, StoreModule, provideState, createFeatureSelector, createSelector, Store, select } from '@ngrx/store';
13
- import { Directionality } from '@angular/cdk/bidi';
14
-
15
- /**
16
- * Decorator to pass localization url
17
- * @param url
18
- */
19
- // eslint-disable-next-line @typescript-eslint/naming-convention -- decorator should start with a capital letter
1
+ import { deepFill, filterMessageContent, immutablePrimitive, otterComponentInfoPropertyName, sendOtterMessage } from "@o3r/core";
2
+ import * as i0 from "@angular/core";
3
+ import { ApplicationRef, ChangeDetectorRef, DestroyRef, Directive, ElementRef, Injectable, InjectionToken, Injector, Input, LOCALE_ID, NgModule, Optional, Pipe, Renderer2, RendererFactory2, SimpleChange, TemplateRef, inject, isDevMode, makeEnvironmentProviders, signal } from "@angular/core";
4
+ import { TRANSLOCO_LANG, TRANSLOCO_LOADER, TRANSLOCO_SCOPE, TRANSLOCO_TRANSPILER, TranslocoDirective, TranslocoPipe, TranslocoService, provideTransloco } from "@jsverse/transloco";
5
+ import { Subject, combineLatest, distinctUntilChanged, firstValueFrom, from, fromEvent, lastValueFrom, map, of, shareReplay, startWith, switchMap } from "rxjs";
6
+ import { DynamicContentService } from "@o3r/dynamic-content";
7
+ import { LoggerService } from "@o3r/logger";
8
+ import { catchError, map as map$1, switchMap as switchMap$1 } from "rxjs/operators";
9
+ import { CurrencyPipe, DatePipe, DecimalPipe } from "@angular/common";
10
+ import { takeUntilDestroyed, toObservable } from "@angular/core/rxjs-interop";
11
+ import * as i1 from "@ngrx/store";
12
+ import { Store, StoreModule, createAction, createFeatureSelector, createReducer, createSelector, on, props, provideState, select } from "@ngrx/store";
13
+ import { Directionality } from "@angular/cdk/bidi";
20
14
  function Localization(url) {
21
- return (target, key) => {
22
- const privateField = url || `_${key}`;
23
- const privateValue = target[key];
24
- if (delete target[key]) {
25
- Object.defineProperty(target, key, {
26
- get: function () {
27
- return this[privateField];
28
- },
29
- set: function (value) {
30
- const currentField = this[privateField] || privateValue;
31
- this[privateField] = typeof currentField === 'undefined' ? immutablePrimitive(value) : deepFill(currentField, value);
32
- if (this[otterComponentInfoPropertyName]) {
33
- this[otterComponentInfoPropertyName].translations = this[privateField];
34
- }
35
- },
36
- enumerable: true,
37
- configurable: true
38
- });
39
- }
40
- };
15
+ return (target, key) => {
16
+ const privateField = url || `_${key}`;
17
+ const privateValue = target[key];
18
+ if (delete target[key]) Object.defineProperty(target, key, {
19
+ get: function() {
20
+ return this[privateField];
21
+ },
22
+ set: function(value) {
23
+ const currentField = this[privateField] || privateValue;
24
+ this[privateField] = typeof currentField === "undefined" ? immutablePrimitive(value) : deepFill(currentField, value);
25
+ if (this[otterComponentInfoPropertyName]) this[otterComponentInfoPropertyName].translations = this[privateField];
26
+ },
27
+ enumerable: true,
28
+ configurable: true
29
+ });
30
+ };
41
31
  }
42
-
43
- /**
44
- * Default configuration for LocalizationModule
45
- */
46
32
  const DEFAULT_LOCALIZATION_CONFIGURATION = {
47
- supportedLocales: [],
48
- endPointUrl: '',
49
- useDynamicContent: false,
50
- rtlLanguages: ['ar', 'he'],
51
- fallbackLanguage: 'en',
52
- bundlesOutputPath: '',
53
- debugMode: false,
54
- enableTranslationDeactivation: false,
55
- mergeWithLocalTranslations: false
33
+ supportedLocales: [],
34
+ endPointUrl: "",
35
+ useDynamicContent: false,
36
+ rtlLanguages: ["ar", "he"],
37
+ fallbackLanguage: "en",
38
+ bundlesOutputPath: "",
39
+ debugMode: false,
40
+ enableTranslationDeactivation: false,
41
+ mergeWithLocalTranslations: false
56
42
  };
57
-
58
- /**
59
- * Formats a debug key string combining the translation key and its value.
60
- * Used across the localization service, pipe, and directive when debugMode is enabled.
61
- * @param key The translation key
62
- * @param value The translated value
63
- */
64
43
  function getDebugKey(key, value) {
65
- return `${key} - ${value}`;
44
+ return `${key} - ${value}`;
66
45
  }
67
-
68
- /** Localization Configuration Token */
69
- const LOCALIZATION_CONFIGURATION_TOKEN = new InjectionToken('Localization Configuration injection token');
70
-
71
- const JSON_EXT = '.json';
72
- /**
73
- * This class is responsible for loading translation bundles from remote or local endpoints depending on the LocalizationConfiguration.
74
- * Fallback mechanism ensures that if a bundle in some language cannot be fetched remotely
75
- * we try to fetch the same language bundle locally (bundles stored inside the application)
76
- * and finally load the fallback language bundle (if all previous fetches failed)
77
- */
78
- class TranslationsLoader {
79
- constructor() {
80
- this.localizationConfiguration = inject(LOCALIZATION_CONFIGURATION_TOKEN);
81
- this.logger = inject(LoggerService, { optional: true });
82
- this.dynamicContentService = inject(DynamicContentService, { optional: true });
83
- }
84
- /**
85
- * Download a language bundle file
86
- * @param url Url to the bundle file
87
- */
88
- downloadLanguageBundle$(url) {
89
- const queryParams = this.localizationConfiguration.queryParams;
90
- const parsedUrl = new URL(url, window.location.origin);
91
- if (queryParams) {
92
- Object.entries(queryParams).forEach(([key, value]) => parsedUrl.searchParams.append(key, value));
93
- }
94
- return from(fetch(parsedUrl.href, this.localizationConfiguration.fetchOptions)).pipe(switchMap((response) => response.json()));
95
- }
96
- /**
97
- * @inheritdoc
98
- */
99
- getTranslation(lang) {
100
- const fallback = this.localizationConfiguration.fallbackLanguage;
101
- let localizationPath$ = of(this.localizationConfiguration.endPointUrl);
102
- if (this.localizationConfiguration.useDynamicContent) {
103
- if (!this.dynamicContentService) {
104
- throw new Error('Dynamic Content is not available. Please verify you have provided the DynamicContent in your application');
105
- }
106
- localizationPath$ = this.dynamicContentService.getContentPathStream(this.localizationConfiguration.endPointUrl);
107
- }
108
- return localizationPath$.pipe(switchMap((localizationPath) => {
109
- if (localizationPath) {
110
- const localizationBundle$ = this.downloadLanguageBundle$(localizationPath + lang + JSON_EXT);
111
- if (this.localizationConfiguration.mergeWithLocalTranslations) {
112
- return combineLatest([
113
- localizationBundle$.pipe(catchError(() => {
114
- this.logger?.warn(`Failed to load the localization resource from ${localizationPath + lang + JSON_EXT} during merge, falling back to local translations only`);
115
- return of({});
116
- })),
117
- this.getTranslationFromLocal(lang, fallback).pipe(map((translations) => {
118
- Object.entries(translations).forEach(([key, value]) => translations[key] = `[local] ${value}`);
119
- return translations;
120
- }))
121
- ]).pipe(map(([dynamicTranslations, localTranslations]) => ({ ...localTranslations, ...dynamicTranslations })));
122
- }
123
- /*
124
- * if endPointUrl is specified by the configuration then:
125
- * 1. try to load lang from endPointUrl
126
- * 2. if 1 fails then try to load from the app (local file)
127
- */
128
- return localizationBundle$.pipe(catchError(() => {
129
- this.logger?.warn(`Failed to load the localization resource from ${localizationPath + lang + JSON_EXT}, trying from the application resources`);
130
- return this.getTranslationFromLocal(lang, fallback);
131
- }));
132
- }
133
- /*
134
- * else if endPointUrl NOT specified by then configuration then:
135
- * 1. try to load from the app (local file)
136
- */
137
- this.logger?.warn('No localization endpoint specified, localization fetch from application resources');
138
- return this.getTranslationFromLocal(lang, fallback);
139
- }));
140
- }
141
- /**
142
- *
143
- *Fetches localization bundles from published folder (internal to application)
144
- *
145
- *1. try to load lang from local
146
- *2. if 1 fails try to load fallback lang but only if it's different from lang in 1
147
- * @param lang - language of the bundle
148
- * @param fallbackLanguage - fallback language in case bundle in language not found
149
- */
150
- getTranslationFromLocal(lang, fallbackLanguage) {
151
- const pathPrefix = this.localizationConfiguration.bundlesOutputPath;
152
- return this.downloadLanguageBundle$(pathPrefix + lang + JSON_EXT).pipe(catchError(() => {
153
- if (lang === fallbackLanguage) {
154
- this.logger?.error(`Failed to load ${lang} from ${pathPrefix + lang + JSON_EXT}.`);
155
- return of({});
156
- }
157
- else {
158
- this.logger?.warn(`Failed to load ${lang} from ${pathPrefix + lang + JSON_EXT}. Application will fallback to ${fallbackLanguage}`);
159
- return this.getTranslationFromLocal(fallbackLanguage, fallbackLanguage);
160
- }
161
- }));
162
- }
163
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: TranslationsLoader, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
164
- /** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: TranslationsLoader }); }
165
- }
166
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: TranslationsLoader, decorators: [{
167
- type: Injectable
168
- }] });
169
-
170
- /**
171
- * Creates a loader of translations bundles based on the configuration
172
- * (endPointUrl and language determine which bundle we load and where do we fetch it from)
173
- * @param localizationConfiguration
174
- * @param logger service to handle the log of warning and errors
175
- * @param dynamicContentService (optional)
176
- */
46
+ const LOCALIZATION_CONFIGURATION_TOKEN = new InjectionToken("Localization Configuration injection token");
47
+ const JSON_EXT = ".json";
48
+ var TranslationsLoader = class TranslationsLoader {
49
+ constructor() {
50
+ this.localizationConfiguration = inject(LOCALIZATION_CONFIGURATION_TOKEN);
51
+ this.logger = inject(LoggerService, { optional: true });
52
+ this.dynamicContentService = inject(DynamicContentService, { optional: true });
53
+ }
54
+ downloadLanguageBundle$(url) {
55
+ const queryParams = this.localizationConfiguration.queryParams;
56
+ const parsedUrl = new URL(url, window.location.origin);
57
+ if (queryParams) Object.entries(queryParams).forEach(([key, value]) => parsedUrl.searchParams.append(key, value));
58
+ return from(fetch(parsedUrl.href, this.localizationConfiguration.fetchOptions)).pipe(switchMap$1((response) => response.json()));
59
+ }
60
+ getTranslation(lang) {
61
+ const fallback = this.localizationConfiguration.fallbackLanguage;
62
+ let localizationPath$ = of(this.localizationConfiguration.endPointUrl);
63
+ if (this.localizationConfiguration.useDynamicContent) {
64
+ if (!this.dynamicContentService) throw new Error("Dynamic Content is not available. Please verify you have provided the DynamicContent in your application");
65
+ localizationPath$ = this.dynamicContentService.getContentPathStream(this.localizationConfiguration.endPointUrl);
66
+ }
67
+ return localizationPath$.pipe(switchMap$1((localizationPath) => {
68
+ if (localizationPath) {
69
+ const localizationBundle$ = this.downloadLanguageBundle$(localizationPath + lang + JSON_EXT);
70
+ if (this.localizationConfiguration.mergeWithLocalTranslations) return combineLatest([localizationBundle$.pipe(catchError(() => {
71
+ this.logger?.warn(`Failed to load the localization resource from ${localizationPath + lang + JSON_EXT} during merge, falling back to local translations only`);
72
+ return of({});
73
+ })), this.getTranslationFromLocal(lang, fallback).pipe(map$1((translations) => {
74
+ Object.entries(translations).forEach(([key, value]) => translations[key] = `[local] ${value}`);
75
+ return translations;
76
+ }))]).pipe(map$1(([dynamicTranslations, localTranslations]) => ({
77
+ ...localTranslations,
78
+ ...dynamicTranslations
79
+ })));
80
+ return localizationBundle$.pipe(catchError(() => {
81
+ this.logger?.warn(`Failed to load the localization resource from ${localizationPath + lang + JSON_EXT}, trying from the application resources`);
82
+ return this.getTranslationFromLocal(lang, fallback);
83
+ }));
84
+ }
85
+ this.logger?.warn("No localization endpoint specified, localization fetch from application resources");
86
+ return this.getTranslationFromLocal(lang, fallback);
87
+ }));
88
+ }
89
+ getTranslationFromLocal(lang, fallbackLanguage) {
90
+ const pathPrefix = this.localizationConfiguration.bundlesOutputPath;
91
+ return this.downloadLanguageBundle$(pathPrefix + lang + JSON_EXT).pipe(catchError(() => {
92
+ if (lang === fallbackLanguage) {
93
+ this.logger?.error(`Failed to load ${lang} from ${pathPrefix + lang + JSON_EXT}.`);
94
+ return of({});
95
+ } else {
96
+ this.logger?.warn(`Failed to load ${lang} from ${pathPrefix + lang + JSON_EXT}. Application will fallback to ${fallbackLanguage}`);
97
+ return this.getTranslationFromLocal(fallbackLanguage, fallbackLanguage);
98
+ }
99
+ }));
100
+ }
101
+ static {
102
+ this.ɵfac = i0.ɵɵngDeclareFactory({
103
+ minVersion: "12.0.0",
104
+ version: "22.2.3",
105
+ ngImport: i0,
106
+ type: TranslationsLoader,
107
+ deps: [],
108
+ target: i0.ɵɵFactoryTarget.Injectable
109
+ });
110
+ }
111
+ static {
112
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
113
+ minVersion: "12.0.0",
114
+ version: "22.2.3",
115
+ ngImport: i0,
116
+ type: TranslationsLoader
117
+ });
118
+ }
119
+ };
120
+ i0.ɵɵngDeclareClassMetadata({
121
+ minVersion: "12.0.0",
122
+ version: "22.2.3",
123
+ ngImport: i0,
124
+ type: TranslationsLoader,
125
+ decorators: [{ type: Injectable }]
126
+ });
177
127
  function createTranslateLoader(localizationConfiguration, logger, dynamicContentService) {
178
- const injector = Injector.create({
179
- providers: [
180
- { provide: LOCALIZATION_CONFIGURATION_TOKEN, useValue: localizationConfiguration },
181
- { provide: LoggerService, useValue: logger },
182
- { provide: DynamicContentService, useValue: dynamicContentService },
183
- {
184
- provide: TranslationsLoader,
185
- deps: [[LoggerService, new Optional()], [DynamicContentService, new Optional()], LOCALIZATION_CONFIGURATION_TOKEN]
186
- }
187
- ]
188
- });
189
- return injector.get(TranslationsLoader);
128
+ return Injector.create({ providers: [
129
+ {
130
+ provide: LOCALIZATION_CONFIGURATION_TOKEN,
131
+ useValue: localizationConfiguration
132
+ },
133
+ {
134
+ provide: LoggerService,
135
+ useValue: logger
136
+ },
137
+ {
138
+ provide: DynamicContentService,
139
+ useValue: dynamicContentService
140
+ },
141
+ {
142
+ provide: TranslationsLoader,
143
+ deps: [
144
+ [LoggerService, new Optional()],
145
+ [DynamicContentService, new Optional()],
146
+ LOCALIZATION_CONFIGURATION_TOKEN
147
+ ]
148
+ }
149
+ ] }).get(TranslationsLoader);
190
150
  }
191
- /**
192
- * TranslocoLoader provider, using framework's TranslationsLoader class
193
- */
194
151
  const translateLoaderProvider = {
195
- provide: TRANSLOCO_LOADER,
196
- useFactory: createTranslateLoader,
197
- deps: [LOCALIZATION_CONFIGURATION_TOKEN, [new Optional(), LoggerService], [new Optional(), DynamicContentService]]
152
+ provide: TRANSLOCO_LOADER,
153
+ useFactory: createTranslateLoader,
154
+ deps: [
155
+ LOCALIZATION_CONFIGURATION_TOKEN,
156
+ [new Optional(), LoggerService],
157
+ [new Optional(), DynamicContentService]
158
+ ]
198
159
  };
199
-
200
- /** Actions */
201
- const ACTION_SET = '[LocalizationOverride] set';
202
- /**
203
- * Clear all overrides and fill the store with the payload
204
- */
205
- const setLocalizationOverride = createAction(ACTION_SET, props());
206
-
207
- /**
208
- * LocalizationOverride Store initial value
209
- */
160
+ const setLocalizationOverride = createAction("[LocalizationOverride] set", props());
210
161
  const localizationOverrideInitialState = { localizationOverrides: {} };
211
- /**
212
- * List of basic actions for LocalizationOverride Store
213
- */
214
- const localizationOverrideReducerFeatures = [
215
- on(setLocalizationOverride, (_state, payload) => ({ ...payload.state }))
216
- ];
217
- /**
218
- * LocalizationOverride Store reducer
219
- */
162
+ const localizationOverrideReducerFeatures = [on(setLocalizationOverride, (_state, payload) => ({ ...payload.state }))];
220
163
  const localizationOverrideReducer = createReducer(localizationOverrideInitialState, ...localizationOverrideReducerFeatures);
221
-
222
- /**
223
- * Name of the LocalizationOverride Store
224
- */
225
- const LOCALIZATION_OVERRIDE_STORE_NAME = 'localizationOverride';
226
-
227
- /** Token of the LocalizationOverride reducer */
228
- const LOCALIZATION_OVERRIDE_REDUCER_TOKEN = new InjectionToken('Feature LocalizationOverride Reducer');
229
- /** Provide default reducer for LocalizationOverride store */
164
+ const LOCALIZATION_OVERRIDE_STORE_NAME = "localizationOverride";
165
+ const LOCALIZATION_OVERRIDE_REDUCER_TOKEN = new InjectionToken("Feature LocalizationOverride Reducer");
230
166
  function getDefaultLocalizationOverrideReducer() {
231
- return localizationOverrideReducer;
232
- }
233
- /**
234
- * NgModule for localization override store.
235
- * @deprecated Will be removed in v16. Use {@link provideLocalizationOverrideStore} instead.
236
- */
237
- class LocalizationOverrideStoreModule {
238
- static forRoot(reducerFactory) {
239
- return {
240
- ngModule: LocalizationOverrideStoreModule,
241
- providers: [
242
- { provide: LOCALIZATION_OVERRIDE_REDUCER_TOKEN, useFactory: reducerFactory }
243
- ]
244
- };
245
- }
246
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationOverrideStoreModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
247
- /** @nocollapse */ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "22.2.0", ngImport: i0, type: LocalizationOverrideStoreModule, imports: [i1.StoreFeatureModule] }); }
248
- /** @nocollapse */ static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationOverrideStoreModule, providers: [
249
- { provide: LOCALIZATION_OVERRIDE_REDUCER_TOKEN, useFactory: getDefaultLocalizationOverrideReducer }
250
- ], imports: [StoreModule.forFeature(LOCALIZATION_OVERRIDE_STORE_NAME, LOCALIZATION_OVERRIDE_REDUCER_TOKEN)] }); }
167
+ return localizationOverrideReducer;
251
168
  }
252
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationOverrideStoreModule, decorators: [{
253
- type: NgModule,
254
- args: [{
255
- imports: [
256
- StoreModule.forFeature(LOCALIZATION_OVERRIDE_STORE_NAME, LOCALIZATION_OVERRIDE_REDUCER_TOKEN)
257
- ],
258
- providers: [
259
- { provide: LOCALIZATION_OVERRIDE_REDUCER_TOKEN, useFactory: getDefaultLocalizationOverrideReducer }
260
- ]
261
- }]
262
- }] });
263
- /**
264
- * Provide LocalizationOverride feature store.
265
- * @param reducerFactory Optional factory to override the default reducer.
266
- */
169
+ var LocalizationOverrideStoreModule = class LocalizationOverrideStoreModule {
170
+ static forRoot(reducerFactory) {
171
+ return {
172
+ ngModule: LocalizationOverrideStoreModule,
173
+ providers: [{
174
+ provide: LOCALIZATION_OVERRIDE_REDUCER_TOKEN,
175
+ useFactory: reducerFactory
176
+ }]
177
+ };
178
+ }
179
+ static {
180
+ this.ɵfac = i0.ɵɵngDeclareFactory({
181
+ minVersion: "12.0.0",
182
+ version: "22.2.3",
183
+ ngImport: i0,
184
+ type: LocalizationOverrideStoreModule,
185
+ deps: [],
186
+ target: i0.ɵɵFactoryTarget.NgModule
187
+ });
188
+ }
189
+ static {
190
+ this.ɵmod = i0.ɵɵngDeclareNgModule({
191
+ minVersion: "14.0.0",
192
+ version: "22.2.3",
193
+ ngImport: i0,
194
+ type: LocalizationOverrideStoreModule,
195
+ imports: [i1.StoreFeatureModule]
196
+ });
197
+ }
198
+ static {
199
+ this.ɵinj = i0.ɵɵngDeclareInjector({
200
+ minVersion: "12.0.0",
201
+ version: "22.2.3",
202
+ ngImport: i0,
203
+ type: LocalizationOverrideStoreModule,
204
+ providers: [{
205
+ provide: LOCALIZATION_OVERRIDE_REDUCER_TOKEN,
206
+ useFactory: getDefaultLocalizationOverrideReducer
207
+ }],
208
+ imports: [StoreModule.forFeature(LOCALIZATION_OVERRIDE_STORE_NAME, LOCALIZATION_OVERRIDE_REDUCER_TOKEN)]
209
+ });
210
+ }
211
+ };
212
+ i0.ɵɵngDeclareClassMetadata({
213
+ minVersion: "12.0.0",
214
+ version: "22.2.3",
215
+ ngImport: i0,
216
+ type: LocalizationOverrideStoreModule,
217
+ decorators: [{
218
+ type: NgModule,
219
+ args: [{
220
+ imports: [StoreModule.forFeature(LOCALIZATION_OVERRIDE_STORE_NAME, LOCALIZATION_OVERRIDE_REDUCER_TOKEN)],
221
+ providers: [{
222
+ provide: LOCALIZATION_OVERRIDE_REDUCER_TOKEN,
223
+ useFactory: getDefaultLocalizationOverrideReducer
224
+ }]
225
+ }]
226
+ }]
227
+ });
267
228
  function provideLocalizationOverrideStore(reducerFactory) {
268
- return makeEnvironmentProviders([
269
- provideState(LOCALIZATION_OVERRIDE_STORE_NAME, reducerFactory ? reducerFactory() : localizationOverrideReducer)
270
- ]);
229
+ return makeEnvironmentProviders([provideState(LOCALIZATION_OVERRIDE_STORE_NAME, reducerFactory ? reducerFactory() : localizationOverrideReducer)]);
271
230
  }
272
-
273
- /** Select LocalizationOverride State */
274
231
  const selectLocalizationOverrideState = createFeatureSelector(LOCALIZATION_OVERRIDE_STORE_NAME);
275
- /** Select all localization override map */
276
232
  const selectLocalizationOverride = createSelector(selectLocalizationOverrideState, (state) => state?.localizationOverrides || {});
277
-
278
- /**
279
- * Deserializer for the LocalizationOverride store storage
280
- * @param rawObject
281
- */
282
233
  const localizationOverrideStorageDeserializer = (rawObject) => {
283
- if (!rawObject) {
284
- return localizationOverrideInitialState;
285
- }
286
- return rawObject;
234
+ if (!rawObject) return localizationOverrideInitialState;
235
+ return rawObject;
287
236
  };
288
- /** Serializer/Deserializer configuration for the LocalizationOverride store sync */
289
- const localizationOverrideStorageSync = {
290
- deserialize: localizationOverrideStorageDeserializer
237
+ const localizationOverrideStorageSync = { deserialize: localizationOverrideStorageDeserializer };
238
+ var LocalizationService = class LocalizationService {
239
+ constructor() {
240
+ this.translateService = inject(TranslocoService);
241
+ this.logger = inject(LoggerService, { optional: true });
242
+ this.configuration = inject(LOCALIZATION_CONFIGURATION_TOKEN);
243
+ this.store = inject(Store, { optional: true });
244
+ this.localeSplitIdentifier = "-";
245
+ this._showKeys = signal(false, ...ngDevMode ? [{ debugName: "_showKeys" }] : /* istanbul ignore next */ []);
246
+ this.showKeys$ = toObservable(this._showKeys);
247
+ this.showKeys = this._showKeys.asReadonly();
248
+ this.configure().catch((err) => {
249
+ this.logger?.error(`Failed to configure LocalizationService: ${err}`);
250
+ });
251
+ if (this.store) this.keyMapping$ = this.store.pipe(select(selectLocalizationOverride));
252
+ else this.logger?.debug("Store not available: localization key overrides via rules engine will not be active.");
253
+ }
254
+ checkFallbackLocalesMap(language) {
255
+ if (language && !this.configuration.supportedLocales.includes(language)) {
256
+ const closestSupportedLanguageCode = this.getFirstClosestSupportedLanguageCode(language);
257
+ const fallbackForLanguage = this.getFallbackMapLangCode(language);
258
+ const fallbackStrategyDebug = fallbackForLanguage && " associated fallback language " || closestSupportedLanguageCode && " closest supported language " || this.configuration.fallbackLanguage && " configured default language ";
259
+ const fallbackLang = fallbackForLanguage || closestSupportedLanguageCode || this.configuration.fallbackLanguage || language;
260
+ if (language !== fallbackLang) this.logger?.debug(`Non supported languages ${language} will fallback to ${fallbackStrategyDebug} ${fallbackLang}`);
261
+ return fallbackLang;
262
+ } else if (!language) this.logger?.debug("Language is not defined");
263
+ return language;
264
+ }
265
+ getFallbackMapLangCode(language) {
266
+ const fallbackLocalesMap = this.configuration.fallbackLocalesMap;
267
+ const [locale] = language.split(this.localeSplitIdentifier);
268
+ return fallbackLocalesMap && (fallbackLocalesMap[language] || fallbackLocalesMap[locale]);
269
+ }
270
+ getFirstClosestSupportedLanguageCode(language) {
271
+ const [locale] = language.split(this.localeSplitIdentifier);
272
+ const firstClosestRegx = new RegExp(`^${locale}${this.localeSplitIdentifier}?`, "i");
273
+ return this.configuration.supportedLocales.find((supportedLang) => firstClosestRegx.test(supportedLang));
274
+ }
275
+ getTranslationStream(translationKey, interpolateParams) {
276
+ const translation$ = this.translateService.events$.pipe(startWith(void 0), switchMap(() => this.translateService.selectTranslate(translationKey, interpolateParams)), map((value) => this.configuration.debugMode ? getDebugKey(translationKey, value) : value), distinctUntilChanged());
277
+ if (!this.configuration.enableTranslationDeactivation) return translation$;
278
+ return combineLatest([translation$, this.showKeys$]).pipe(map(([value, showKeys]) => showKeys ? translationKey : value));
279
+ }
280
+ async configure() {
281
+ const language = this.checkFallbackLocalesMap(this.configuration.language || this.configuration.fallbackLanguage);
282
+ this.translateService.setAvailableLangs(this.configuration.supportedLocales);
283
+ this.translateService.setDefaultLang(language);
284
+ await firstValueFrom(this.useLanguage(language));
285
+ }
286
+ isTranslationDeactivationEnabled() {
287
+ return this.configuration.enableTranslationDeactivation;
288
+ }
289
+ getLanguages() {
290
+ return this.translateService.getAvailableLangs().map((l) => typeof l === "string" ? l : l.id);
291
+ }
292
+ useLanguage(language) {
293
+ language = this.checkFallbackLocalesMap(language);
294
+ this.translateService.setActiveLang(language);
295
+ return this.translateService.load(language);
296
+ }
297
+ getCurrentLanguage() {
298
+ return this.translateService.getActiveLang();
299
+ }
300
+ getTranslateService() {
301
+ return this.translateService;
302
+ }
303
+ toggleShowKeys(value) {
304
+ if (!this.configuration.enableTranslationDeactivation) throw new Error("Translation deactivation is not enabled. Please set the LocalizationConfiguration property \"enableTranslationDeactivation\" accordingly.");
305
+ const newValue = value === void 0 ? !this.showKeys() : value;
306
+ this._showKeys.set(newValue);
307
+ }
308
+ getKey(requestedKey) {
309
+ return this.keyMapping$ ? this.keyMapping$.pipe(map((keyMapping) => keyMapping[requestedKey] || requestedKey), distinctUntilChanged()) : of(requestedKey);
310
+ }
311
+ translate(key, interpolateParams) {
312
+ return this.getKey(key).pipe(switchMap((translationKey) => this.getTranslationStream(translationKey, interpolateParams)), shareReplay({
313
+ refCount: true,
314
+ bufferSize: 1
315
+ }));
316
+ }
317
+ static {
318
+ this.ɵfac = i0.ɵɵngDeclareFactory({
319
+ minVersion: "12.0.0",
320
+ version: "22.2.3",
321
+ ngImport: i0,
322
+ type: LocalizationService,
323
+ deps: [],
324
+ target: i0.ɵɵFactoryTarget.Injectable
325
+ });
326
+ }
327
+ static {
328
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
329
+ minVersion: "12.0.0",
330
+ version: "22.2.3",
331
+ ngImport: i0,
332
+ type: LocalizationService
333
+ });
334
+ }
291
335
  };
292
-
293
- /**
294
- * Service which is wrapping the configuration logic of TranslocoService from JSVerse Transloco.
295
- * Any application willing to use localization just needs to inject LocalizationService
296
- * in the root component and call its configure() method.
297
- */
298
- class LocalizationService {
299
- constructor() {
300
- this.translateService = inject(TranslocoService);
301
- this.logger = inject(LoggerService, { optional: true });
302
- this.configuration = inject(LOCALIZATION_CONFIGURATION_TOKEN);
303
- this.store = inject(Store, { optional: true });
304
- this.localeSplitIdentifier = '-';
305
- /**
306
- * Internal signal that we use to track changes between keys only and translation mode
307
- */
308
- this._showKeys = signal(false, /* @ts-ignore */
309
- ...(ngDevMode ? [{ debugName: "_showKeys" }] : /* istanbul ignore next */ []));
310
- /**
311
- * _showKeys exposed as an Observable
312
- */
313
- this.showKeys$ = toObservable(this._showKeys);
314
- /**
315
- * Return the current value of debug show/hide translation keys.
316
- */
317
- this.showKeys = this._showKeys.asReadonly();
318
- this.configure().catch((err) => {
319
- this.logger?.error(`Failed to configure LocalizationService: ${err}`);
320
- });
321
- if (this.store) {
322
- this.keyMapping$ = this.store.pipe(select(selectLocalizationOverride));
323
- }
324
- else {
325
- this.logger?.debug('Store not available: localization key overrides via rules engine will not be active.');
326
- }
327
- }
328
- /**
329
- * This will handle the fallback language hierarchy to find out fallback language.
330
- * supportedLocales language has highest priority, next priority goes to fallbackLocalesMap and default would be
331
- * fallbackLanguage.
332
- * @param language Selected language.
333
- * @returns selected language if supported, fallback language otherwise.
334
- */
335
- checkFallbackLocalesMap(language) {
336
- if (language && !this.configuration.supportedLocales.includes(language)) {
337
- const closestSupportedLanguageCode = this.getFirstClosestSupportedLanguageCode(language);
338
- const fallbackForLanguage = this.getFallbackMapLangCode(language);
339
- const fallbackStrategyDebug = (fallbackForLanguage && ' associated fallback language ')
340
- || (closestSupportedLanguageCode && ' closest supported language ')
341
- || (this.configuration.fallbackLanguage && ' configured default language ');
342
- const fallbackLang = fallbackForLanguage || closestSupportedLanguageCode || this.configuration.fallbackLanguage || language;
343
- if (language !== fallbackLang) {
344
- this.logger?.debug(`Non supported languages ${language} will fallback to ${fallbackStrategyDebug} ${fallbackLang}`);
345
- }
346
- return fallbackLang;
347
- }
348
- else if (!language) {
349
- this.logger?.debug('Language is not defined');
350
- }
351
- return language;
352
- }
353
- /**
354
- * This function checks if fallback language can be provided from fallbackLocalesMap.
355
- * supportedLocales: ['en-GB', 'en-US', 'fr-FR'], fallbackLocalesMap: {'en-CA': 'en-US', 'de': 'fr-FR'}
356
- * translate to en-CA -> fallback to en-US, translate to de-DE -> fallback to fr-FR
357
- * translate to en-NZ -> fallback to en-GB
358
- * @param language Selected language.
359
- * @returns Fallback language if available, undefined otherwise.
360
- */
361
- getFallbackMapLangCode(language) {
362
- const fallbackLocalesMap = this.configuration.fallbackLocalesMap;
363
- const [locale] = language.split(this.localeSplitIdentifier);
364
- return fallbackLocalesMap && (fallbackLocalesMap[language] || fallbackLocalesMap[locale]);
365
- }
366
- /**
367
- * This function checks if closest supported language available incase of selected language is not
368
- * supported language.
369
- * supportedLocales: ['en-GB', 'en-US', 'fr-FR']
370
- * translate to en-CA -> fallback to en-GB
371
- * @param language Selected language.
372
- * @returns Closest supported language if available, undefined otherwise.
373
- */
374
- getFirstClosestSupportedLanguageCode(language) {
375
- const [locale] = language.split(this.localeSplitIdentifier);
376
- const firstClosestRegx = new RegExp(`^${locale}${this.localeSplitIdentifier}?`, 'i');
377
- return this.configuration.supportedLocales.find((supportedLang) => firstClosestRegx.test(supportedLang));
378
- }
379
- /**
380
- * Returns a stream of translated values of a key which updates whenever the language changes.
381
- * @param translationKey Key to translate
382
- * @param interpolateParams Object to use in translation binding
383
- * @returns A stream of the translated key
384
- */
385
- getTranslationStream(translationKey, interpolateParams) {
386
- const translation$ = this.translateService.events$.pipe(startWith(undefined), switchMap$1(() => this.translateService.selectTranslate(translationKey, interpolateParams)), map$1((value) => this.configuration.debugMode ? getDebugKey(translationKey, value) : value), distinctUntilChanged());
387
- if (!this.configuration.enableTranslationDeactivation) {
388
- return translation$;
389
- }
390
- return combineLatest([
391
- translation$,
392
- this.showKeys$
393
- ]).pipe(map$1(([value, showKeys]) => showKeys ? translationKey : value));
394
- }
395
- /**
396
- * Configures TranslocoService and registers locales. This method is called from the application level.
397
- */
398
- async configure() {
399
- const language = this.checkFallbackLocalesMap(this.configuration.language || this.configuration.fallbackLanguage);
400
- this.translateService.setAvailableLangs(this.configuration.supportedLocales);
401
- this.translateService.setDefaultLang(language);
402
- await firstValueFrom(this.useLanguage(language));
403
- }
404
- /**
405
- * Is the translation deactivation enabled
406
- */
407
- isTranslationDeactivationEnabled() {
408
- return this.configuration.enableTranslationDeactivation;
409
- }
410
- /**
411
- * Wrapper to call the TranslocoService method getAvailableLangs().
412
- */
413
- getLanguages() {
414
- return this.translateService.getAvailableLangs().map((l) => (typeof l === 'string' ? l : l.id));
415
- }
416
- /**
417
- * Wrapper to call the TranslocoService method setActiveLang(language).
418
- * @param language
419
- */
420
- useLanguage(language) {
421
- language = this.checkFallbackLocalesMap(language);
422
- this.translateService.setActiveLang(language);
423
- return this.translateService.load(language);
424
- }
425
- /**
426
- * Wrapper to get the TranslocoService getActiveLang.
427
- */
428
- getCurrentLanguage() {
429
- return this.translateService.getActiveLang();
430
- }
431
- /**
432
- * Get the instance of the TranslocoService used by LocalizationService.
433
- */
434
- getTranslateService() {
435
- return this.translateService;
436
- }
437
- /**
438
- * Toggle the ShowKeys mode between active and inactive.
439
- * @param value if specified, set the ShowKeys mode to value. If not specified, toggle the ShowKeys mode.
440
- */
441
- toggleShowKeys(value) {
442
- if (!this.configuration.enableTranslationDeactivation) {
443
- throw new Error('Translation deactivation is not enabled. Please set the LocalizationConfiguration property "enableTranslationDeactivation" accordingly.');
444
- }
445
- const newValue = value === undefined ? !this.showKeys() : value;
446
- this._showKeys.set(newValue);
447
- }
448
- /**
449
- * Get an observable of translation key after global mapping
450
- * @param requestedKey Original translation key
451
- */
452
- getKey(requestedKey) {
453
- return this.keyMapping$
454
- ? this.keyMapping$.pipe(map$1((keyMapping) => keyMapping[requestedKey] || requestedKey), distinctUntilChanged())
455
- : of(requestedKey);
456
- }
457
- /**
458
- * Returns a stream of translated values of a key which updates whenever the language changes.
459
- * @param key Key to translate
460
- * @param interpolateParams Object to use in translation binding
461
- * @returns A stream of the translated key
462
- */
463
- translate(key, interpolateParams) {
464
- return this.getKey(key).pipe(switchMap$1((translationKey) => this.getTranslationStream(translationKey, interpolateParams)), shareReplay({ refCount: true, bufferSize: 1 }));
465
- }
466
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
467
- /** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationService }); }
468
- }
469
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationService, decorators: [{
470
- type: Injectable
471
- }], ctorParameters: () => [] });
472
-
473
- /**
474
- * Native angular CurrencyPipe taking the current lang into consideration
475
- */
476
- class LocalizedCurrencyPipe extends CurrencyPipe {
477
- constructor() {
478
- super(inject(LocalizationService).getCurrentLanguage());
479
- this.localizationService = inject(LocalizationService);
480
- this.changeDetectorRef = inject(ChangeDetectorRef);
481
- this.localizationService.getTranslateService().langChanges$
482
- .pipe(takeUntilDestroyed())
483
- .subscribe(() => this.changeDetectorRef.markForCheck());
484
- }
485
- transform(value, currencyCode, display, digitsInfo, locale) {
486
- return this.localizationService.showKeys() ? '' : super.transform(value, currencyCode, display, digitsInfo, locale || this.localizationService.getCurrentLanguage());
487
- }
488
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizedCurrencyPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
489
- /** @nocollapse */ static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "22.2.0", ngImport: i0, type: LocalizedCurrencyPipe, isStandalone: true, name: "currency", pure: false }); }
490
- }
491
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizedCurrencyPipe, decorators: [{
492
- type: Pipe,
493
- args: [{
494
- name: 'currency',
495
- pure: false,
496
- standalone: true
497
- }]
498
- }], ctorParameters: () => [] });
499
-
500
- /**
501
- * Native angular DatePipe taking the current lang into consideration
502
- */
503
- class LocalizedDatePipe extends DatePipe {
504
- constructor() {
505
- super(inject(LocalizationService).getCurrentLanguage());
506
- this.localizationService = inject(LocalizationService);
507
- this.changeDetectorRef = inject(ChangeDetectorRef);
508
- this.localizationService.getTranslateService().langChanges$
509
- .pipe(takeUntilDestroyed())
510
- .subscribe(() => this.changeDetectorRef.markForCheck());
511
- }
512
- transform(value, format = 'mediumDate', timezone, locale) {
513
- return this.localizationService.showKeys() ? format : super.transform(value, format, timezone, locale || this.localizationService.getCurrentLanguage());
514
- }
515
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizedDatePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
516
- /** @nocollapse */ static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "22.2.0", ngImport: i0, type: LocalizedDatePipe, isStandalone: true, name: "date", pure: false }); }
517
- }
518
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizedDatePipe, decorators: [{
519
- type: Pipe,
520
- args: [{
521
- name: 'date',
522
- pure: false,
523
- standalone: true
524
- }]
525
- }], ctorParameters: () => [] });
526
-
527
- /**
528
- * Native angular DecimalPipe taking the current lang into consideration
529
- */
530
- class LocalizedDecimalPipe extends DecimalPipe {
531
- constructor() {
532
- super(inject(LocalizationService).getCurrentLanguage());
533
- this.localizationService = inject(LocalizationService);
534
- this.changeDetectorRef = inject(ChangeDetectorRef);
535
- this.localizationService.getTranslateService().langChanges$
536
- .pipe(takeUntilDestroyed())
537
- .subscribe(() => this.changeDetectorRef.markForCheck());
538
- }
539
- transform(value, digitsInfo, locale) {
540
- return this.localizationService.showKeys() ? '' : super.transform(value, digitsInfo, locale || this.localizationService.getCurrentLanguage());
541
- }
542
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizedDecimalPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
543
- /** @nocollapse */ static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "22.2.0", ngImport: i0, type: LocalizedDecimalPipe, isStandalone: true, name: "number", pure: false }); }
544
- }
545
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizedDecimalPipe, decorators: [{
546
- type: Pipe,
547
- args: [{
548
- name: 'number',
549
- pure: false,
550
- standalone: true
551
- }]
552
- }], ctorParameters: () => [] });
553
-
554
- /**
555
- * Service for handling the text direction based on the LocalizationConfiguration
556
- */
557
- class TextDirectionService {
558
- constructor() {
559
- this.translateService = inject(TranslocoService);
560
- this.configuration = inject(LOCALIZATION_CONFIGURATION_TOKEN);
561
- this.rendererFactory = inject(RendererFactory2);
562
- this.directionality = inject(Directionality);
563
- this.renderer = this.rendererFactory.createRenderer(null, null);
564
- }
565
- /**
566
- * Updates the dir attribute on body HTML tag.
567
- * @returns a subscription that updates the dir attribute
568
- */
569
- onLangChangeSubscription() {
570
- if (this.subscription && !this.subscription.closed) {
571
- return this.subscription;
572
- }
573
- this.subscription = this.translateService.langChanges$.subscribe((lang) => {
574
- const direction = this.configuration.rtlLanguages.includes(lang.split('-')[0]) ? 'rtl' : 'ltr';
575
- this.renderer.setAttribute(document.body, 'dir', direction);
576
- this.directionality.change.emit(direction);
577
- });
578
- return this.subscription;
579
- }
580
- ngOnDestroy() {
581
- this.subscription?.unsubscribe();
582
- }
583
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: TextDirectionService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
584
- /** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: TextDirectionService }); }
585
- }
586
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: TextDirectionService, decorators: [{
587
- type: Injectable
588
- }], ctorParameters: () => [] });
589
-
590
- /**
591
- * creates LocalizationConfiguration, which is used if the application
592
- * @param configuration Localization configuration
593
- */
336
+ i0.ɵɵngDeclareClassMetadata({
337
+ minVersion: "12.0.0",
338
+ version: "22.2.3",
339
+ ngImport: i0,
340
+ type: LocalizationService,
341
+ decorators: [{ type: Injectable }],
342
+ ctorParameters: () => []
343
+ });
344
+ var LocalizedCurrencyPipe = class LocalizedCurrencyPipe extends CurrencyPipe {
345
+ constructor() {
346
+ super(inject(LocalizationService).getCurrentLanguage());
347
+ this.localizationService = inject(LocalizationService);
348
+ this.changeDetectorRef = inject(ChangeDetectorRef);
349
+ this.localizationService.getTranslateService().langChanges$.pipe(takeUntilDestroyed()).subscribe(() => this.changeDetectorRef.markForCheck());
350
+ }
351
+ transform(value, currencyCode, display, digitsInfo, locale) {
352
+ return this.localizationService.showKeys() ? "" : super.transform(value, currencyCode, display, digitsInfo, locale || this.localizationService.getCurrentLanguage());
353
+ }
354
+ static {
355
+ this.ɵfac = i0.ɵɵngDeclareFactory({
356
+ minVersion: "12.0.0",
357
+ version: "22.2.3",
358
+ ngImport: i0,
359
+ type: LocalizedCurrencyPipe,
360
+ deps: [],
361
+ target: i0.ɵɵFactoryTarget.Pipe
362
+ });
363
+ }
364
+ static {
365
+ this.ɵpipe = i0.ɵɵngDeclarePipe({
366
+ minVersion: "14.0.0",
367
+ version: "22.2.3",
368
+ ngImport: i0,
369
+ type: LocalizedCurrencyPipe,
370
+ isStandalone: true,
371
+ name: "currency",
372
+ pure: false
373
+ });
374
+ }
375
+ };
376
+ i0.ɵɵngDeclareClassMetadata({
377
+ minVersion: "12.0.0",
378
+ version: "22.2.3",
379
+ ngImport: i0,
380
+ type: LocalizedCurrencyPipe,
381
+ decorators: [{
382
+ type: Pipe,
383
+ args: [{
384
+ name: "currency",
385
+ pure: false,
386
+ standalone: true
387
+ }]
388
+ }],
389
+ ctorParameters: () => []
390
+ });
391
+ var LocalizedDatePipe = class LocalizedDatePipe extends DatePipe {
392
+ constructor() {
393
+ super(inject(LocalizationService).getCurrentLanguage());
394
+ this.localizationService = inject(LocalizationService);
395
+ this.changeDetectorRef = inject(ChangeDetectorRef);
396
+ this.localizationService.getTranslateService().langChanges$.pipe(takeUntilDestroyed()).subscribe(() => this.changeDetectorRef.markForCheck());
397
+ }
398
+ transform(value, format = "mediumDate", timezone, locale) {
399
+ return this.localizationService.showKeys() ? format : super.transform(value, format, timezone, locale || this.localizationService.getCurrentLanguage());
400
+ }
401
+ static {
402
+ this.ɵfac = i0.ɵɵngDeclareFactory({
403
+ minVersion: "12.0.0",
404
+ version: "22.2.3",
405
+ ngImport: i0,
406
+ type: LocalizedDatePipe,
407
+ deps: [],
408
+ target: i0.ɵɵFactoryTarget.Pipe
409
+ });
410
+ }
411
+ static {
412
+ this.ɵpipe = i0.ɵɵngDeclarePipe({
413
+ minVersion: "14.0.0",
414
+ version: "22.2.3",
415
+ ngImport: i0,
416
+ type: LocalizedDatePipe,
417
+ isStandalone: true,
418
+ name: "date",
419
+ pure: false
420
+ });
421
+ }
422
+ };
423
+ i0.ɵɵngDeclareClassMetadata({
424
+ minVersion: "12.0.0",
425
+ version: "22.2.3",
426
+ ngImport: i0,
427
+ type: LocalizedDatePipe,
428
+ decorators: [{
429
+ type: Pipe,
430
+ args: [{
431
+ name: "date",
432
+ pure: false,
433
+ standalone: true
434
+ }]
435
+ }],
436
+ ctorParameters: () => []
437
+ });
438
+ var LocalizedDecimalPipe = class LocalizedDecimalPipe extends DecimalPipe {
439
+ constructor() {
440
+ super(inject(LocalizationService).getCurrentLanguage());
441
+ this.localizationService = inject(LocalizationService);
442
+ this.changeDetectorRef = inject(ChangeDetectorRef);
443
+ this.localizationService.getTranslateService().langChanges$.pipe(takeUntilDestroyed()).subscribe(() => this.changeDetectorRef.markForCheck());
444
+ }
445
+ transform(value, digitsInfo, locale) {
446
+ return this.localizationService.showKeys() ? "" : super.transform(value, digitsInfo, locale || this.localizationService.getCurrentLanguage());
447
+ }
448
+ static {
449
+ this.ɵfac = i0.ɵɵngDeclareFactory({
450
+ minVersion: "12.0.0",
451
+ version: "22.2.3",
452
+ ngImport: i0,
453
+ type: LocalizedDecimalPipe,
454
+ deps: [],
455
+ target: i0.ɵɵFactoryTarget.Pipe
456
+ });
457
+ }
458
+ static {
459
+ this.ɵpipe = i0.ɵɵngDeclarePipe({
460
+ minVersion: "14.0.0",
461
+ version: "22.2.3",
462
+ ngImport: i0,
463
+ type: LocalizedDecimalPipe,
464
+ isStandalone: true,
465
+ name: "number",
466
+ pure: false
467
+ });
468
+ }
469
+ };
470
+ i0.ɵɵngDeclareClassMetadata({
471
+ minVersion: "12.0.0",
472
+ version: "22.2.3",
473
+ ngImport: i0,
474
+ type: LocalizedDecimalPipe,
475
+ decorators: [{
476
+ type: Pipe,
477
+ args: [{
478
+ name: "number",
479
+ pure: false,
480
+ standalone: true
481
+ }]
482
+ }],
483
+ ctorParameters: () => []
484
+ });
485
+ var TextDirectionService = class TextDirectionService {
486
+ constructor() {
487
+ this.translateService = inject(TranslocoService);
488
+ this.configuration = inject(LOCALIZATION_CONFIGURATION_TOKEN);
489
+ this.rendererFactory = inject(RendererFactory2);
490
+ this.directionality = inject(Directionality);
491
+ this.renderer = this.rendererFactory.createRenderer(null, null);
492
+ }
493
+ onLangChangeSubscription() {
494
+ if (this.subscription && !this.subscription.closed) return this.subscription;
495
+ this.subscription = this.translateService.langChanges$.subscribe((lang) => {
496
+ const direction = this.configuration.rtlLanguages.includes(lang.split("-")[0]) ? "rtl" : "ltr";
497
+ this.renderer.setAttribute(document.body, "dir", direction);
498
+ this.directionality.change.emit(direction);
499
+ });
500
+ return this.subscription;
501
+ }
502
+ ngOnDestroy() {
503
+ this.subscription?.unsubscribe();
504
+ }
505
+ static {
506
+ this.ɵfac = i0.ɵɵngDeclareFactory({
507
+ minVersion: "12.0.0",
508
+ version: "22.2.3",
509
+ ngImport: i0,
510
+ type: TextDirectionService,
511
+ deps: [],
512
+ target: i0.ɵɵFactoryTarget.Injectable
513
+ });
514
+ }
515
+ static {
516
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
517
+ minVersion: "12.0.0",
518
+ version: "22.2.3",
519
+ ngImport: i0,
520
+ type: TextDirectionService
521
+ });
522
+ }
523
+ };
524
+ i0.ɵɵngDeclareClassMetadata({
525
+ minVersion: "12.0.0",
526
+ version: "22.2.3",
527
+ ngImport: i0,
528
+ type: TextDirectionService,
529
+ decorators: [{ type: Injectable }],
530
+ ctorParameters: () => []
531
+ });
594
532
  function createLocalizationConfiguration(configuration) {
595
- return {
596
- ...DEFAULT_LOCALIZATION_CONFIGURATION,
597
- ...configuration
598
- };
533
+ return {
534
+ ...DEFAULT_LOCALIZATION_CONFIGURATION,
535
+ ...configuration
536
+ };
599
537
  }
600
- /**
601
- * Factory to inject the LOCALE_ID token with the current language into Angular context
602
- * @param localizationService Localization service
603
- */
604
538
  function localeIdNgBridge(localizationService) {
605
- return localizationService.getCurrentLanguage();
539
+ return localizationService.getCurrentLanguage();
606
540
  }
607
- /** Custom Localization Configuration Token to override default localization configuration */
608
- const CUSTOM_LOCALIZATION_CONFIGURATION_TOKEN = new InjectionToken('Partial Localization configuration');
609
- /**
610
- * Provide localization services and configuration for the application.
611
- * This is the recommended way to set up localization in standalone applications.
612
- * @param configuration Optional partial localization configuration to override defaults. Can be a configuration object or a factory function.
613
- * @example Override of default and supported languages override at application bootstrap
614
- * ```typescript
615
- * bootstrapApplication(App, {
616
- * providers: [
617
- * provideLocalization({ language: 'en-US', supportedLocales: ['en-US', 'fr-FR'] })
618
- * ]
619
- * });
620
- * ```
621
- */
541
+ const CUSTOM_LOCALIZATION_CONFIGURATION_TOKEN = new InjectionToken("Partial Localization configuration");
622
542
  function provideLocalization(configuration) {
623
- const config = typeof configuration === 'function' ? configuration() : (configuration || {});
624
- const mergedConfig = { ...DEFAULT_LOCALIZATION_CONFIGURATION, ...config };
625
- const providers = [
626
- provideTransloco({
627
- config: {
628
- availableLangs: mergedConfig.supportedLocales || [],
629
- defaultLang: mergedConfig.language || mergedConfig.fallbackLanguage,
630
- reRenderOnLangChange: true,
631
- prodMode: !isDevMode(),
632
- fallbackLang: mergedConfig.fallbackLanguage,
633
- missingHandler: {
634
- useFallbackTranslation: true
635
- }
636
- }
637
- }),
638
- translateLoaderProvider,
639
- LocalizationService,
640
- TextDirectionService,
641
- { provide: LOCALIZATION_CONFIGURATION_TOKEN, useFactory: createLocalizationConfiguration, deps: [[new Optional(), CUSTOM_LOCALIZATION_CONFIGURATION_TOKEN]] },
642
- { provide: LOCALE_ID, useFactory: localeIdNgBridge, deps: [LocalizationService] },
643
- { provide: DatePipe, useClass: LocalizedDatePipe },
644
- { provide: DecimalPipe, useClass: LocalizedDecimalPipe },
645
- { provide: CurrencyPipe, useClass: LocalizedCurrencyPipe }
646
- ];
647
- if (configuration) {
648
- providers.push({
649
- provide: CUSTOM_LOCALIZATION_CONFIGURATION_TOKEN,
650
- ...(typeof configuration === 'function' ? { useFactory: configuration } : { useValue: configuration })
651
- });
652
- }
653
- return makeEnvironmentProviders(providers);
654
- }
655
-
656
- /**
657
- * TranslocoDirective class adding debug functionality.
658
- *
659
- * Extends the TranslocoDirective from Transloco to add:
660
- * - Key mapping via LocalizationService (override store)
661
- * - Show keys mode (display raw keys instead of translations)
662
- * - Debug mode (display key alongside translation)
663
- *
664
- * For the structural strategy (`*transloco`), the debug/showKeys behavior is handled
665
- * by overriding `getTranslateFn`.
666
- *
667
- * For the attribute strategy (`[transloco]="key"`), the parent's private `attributeStrategy()`
668
- * sets `innerText` directly. Since we cannot override this private method, we apply
669
- * debug/showKeys transformations by overwriting `innerText` immediately after calling
670
- * `super.ngOnInit()` and `super.ngOnChanges()`, in the same call stack.
671
- */
672
- class LocalizationTranslateDirective extends TranslocoDirective {
673
- /** @inheritdoc */
674
- set transloco(key) {
675
- if (key) {
676
- this.translocoSubject.next(key);
677
- }
678
- }
679
- constructor() {
680
- super();
681
- this.localizationService = inject(LocalizationService);
682
- this.localizationConfig = inject(LOCALIZATION_CONFIGURATION_TOKEN);
683
- this.changeDetectorRef = inject(ChangeDetectorRef);
684
- this.hostElement = inject(ElementRef);
685
- this.hostRenderer = inject(Renderer2);
686
- this.isAttributeStrategy = inject(TemplateRef, { optional: true }) === null;
687
- this.o3rDestroyRef = inject(DestroyRef);
688
- /**
689
- * Should we display keys instead of translations
690
- */
691
- this.showKeys = false;
692
- /**
693
- * Subject to emit translation key changes
694
- */
695
- this.translocoSubject = new Subject();
696
- if (this.localizationConfig.enableTranslationDeactivation) {
697
- this.localizationService.showKeys$.pipe(takeUntilDestroyed(this.o3rDestroyRef)).subscribe((showKeys) => {
698
- this.showKeys = showKeys;
699
- this.changeDetectorRef.markForCheck();
700
- });
701
- }
702
- // Set up reactive key mapping subscription
703
- this.translocoSubject.pipe(switchMap$1((key) => this.localizationService.getKey(key)), takeUntilDestroyed(this.o3rDestroyRef)).subscribe((newKey) => {
704
- const previousKey = this.key;
705
- this.key = newKey;
706
- this.changeDetectorRef.markForCheck();
707
- super.ngOnChanges({ transloco: new SimpleChange(previousKey, newKey, !previousKey) });
708
- });
709
- }
710
- /**
711
- * For the attribute strategy, overwrites `innerText` with the debug/showKeys value
712
- * immediately after the parent has set it.
713
- */
714
- applyAttributeDebug() {
715
- if (!this.isAttributeStrategy || !this.key) {
716
- return;
717
- }
718
- if (this.showKeys) {
719
- this.hostRenderer.setProperty(this.hostElement.nativeElement, 'innerText', this.key);
720
- }
721
- else if (this.localizationConfig.debugMode) {
722
- this.hostRenderer.setProperty(this.hostElement.nativeElement, 'innerText', getDebugKey(this.key, this.hostElement.nativeElement.innerText));
723
- }
724
- }
725
- /**
726
- * Override getTranslateFn to plug debug/showKeys for the structural strategy.
727
- * @param lang Current language
728
- * @param prefix Scope prefix
729
- */
730
- getTranslateFn(lang, prefix) {
731
- const parentTranslateFn = super.getTranslateFn(lang, prefix);
732
- return (key, params) => {
733
- if (this.showKeys) {
734
- return key;
735
- }
736
- const value = parentTranslateFn(key, params);
737
- if (this.localizationConfig.debugMode) {
738
- return getDebugKey(key, value);
739
- }
740
- return value;
741
- };
742
- }
743
- /** @inheritdoc */
744
- ngOnInit() {
745
- super.ngOnInit();
746
- this.applyAttributeDebug();
747
- }
748
- /** @inheritdoc */
749
- ngOnChanges(changes) {
750
- super.ngOnChanges(changes);
751
- this.applyAttributeDebug();
752
- }
753
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationTranslateDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
754
- /** @nocollapse */ static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "22.2.0", type: LocalizationTranslateDirective, isStandalone: true, selector: "[transloco]", inputs: { transloco: "transloco" }, usesInheritance: true, usesOnChanges: true, ngImport: i0 }); }
543
+ const config = typeof configuration === "function" ? configuration() : configuration || {};
544
+ const mergedConfig = {
545
+ ...DEFAULT_LOCALIZATION_CONFIGURATION,
546
+ ...config
547
+ };
548
+ const providers = [
549
+ provideTransloco({ config: {
550
+ availableLangs: mergedConfig.supportedLocales || [],
551
+ defaultLang: mergedConfig.language || mergedConfig.fallbackLanguage,
552
+ reRenderOnLangChange: true,
553
+ prodMode: !isDevMode(),
554
+ fallbackLang: mergedConfig.fallbackLanguage,
555
+ missingHandler: { useFallbackTranslation: true }
556
+ } }),
557
+ translateLoaderProvider,
558
+ LocalizationService,
559
+ TextDirectionService,
560
+ {
561
+ provide: LOCALIZATION_CONFIGURATION_TOKEN,
562
+ useFactory: createLocalizationConfiguration,
563
+ deps: [[new Optional(), CUSTOM_LOCALIZATION_CONFIGURATION_TOKEN]]
564
+ },
565
+ {
566
+ provide: LOCALE_ID,
567
+ useFactory: localeIdNgBridge,
568
+ deps: [LocalizationService]
569
+ },
570
+ {
571
+ provide: DatePipe,
572
+ useClass: LocalizedDatePipe
573
+ },
574
+ {
575
+ provide: DecimalPipe,
576
+ useClass: LocalizedDecimalPipe
577
+ },
578
+ {
579
+ provide: CurrencyPipe,
580
+ useClass: LocalizedCurrencyPipe
581
+ }
582
+ ];
583
+ if (configuration) providers.push({
584
+ provide: CUSTOM_LOCALIZATION_CONFIGURATION_TOKEN,
585
+ ...typeof configuration === "function" ? { useFactory: configuration } : { useValue: configuration }
586
+ });
587
+ return makeEnvironmentProviders(providers);
755
588
  }
756
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationTranslateDirective, decorators: [{
757
- type: Directive,
758
- args: [{
759
- selector: '[transloco]',
760
- standalone: true
761
- }]
762
- }], ctorParameters: () => [], propDecorators: { transloco: [{
763
- type: Input
764
- }] } });
765
-
766
- /**
767
- * TranslocoPipe class adding debug functionality
768
- */
769
- class O3rLocalizationTranslatePipe extends TranslocoPipe {
770
- constructor() {
771
- super(inject(TranslocoService), inject(TRANSLOCO_SCOPE, { optional: true }) ?? undefined, inject(TRANSLOCO_LANG, { optional: true }) ?? undefined, inject(ChangeDetectorRef));
772
- /** Localization service instance */
773
- this.localizationService = inject(LocalizationService);
774
- /** Change detector service instance */
775
- this.changeDetector = inject(ChangeDetectorRef);
776
- /** Localization config token */
777
- this.localizationConfig = inject(LOCALIZATION_CONFIGURATION_TOKEN);
778
- /** Destroy reference */
779
- this.destroyRef = inject(DestroyRef);
780
- /**
781
- * Should we display keys instead of translations
782
- */
783
- this.showKeys = false;
784
- /**
785
- * Subject to emit translation key changes
786
- */
787
- this.querySubject = new Subject();
788
- if (this.localizationConfig.enableTranslationDeactivation) {
789
- this.localizationService.showKeys$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((showKeys) => {
790
- this.showKeys = showKeys;
791
- this.changeDetector.markForCheck();
792
- });
793
- }
794
- // Set up reactive key mapping subscription
795
- this.querySubject.pipe(switchMap$1((query) => this.localizationService.getKey(query)), takeUntilDestroyed(this.destroyRef)).subscribe((key) => {
796
- this.lastResolvedKey = key;
797
- this.changeDetector.markForCheck();
798
- });
799
- }
800
- /**
801
- * Calls original transform method and eventually outputs the key if debugMode (in LocalizationConfiguration) is enabled
802
- * @inheritdoc
803
- */
804
- transform(query, ...args) {
805
- if (!query || this.localizationService.showKeys()) {
806
- return query;
807
- }
808
- // Emit query to subject for reactive key mapping
809
- this.querySubject.next(query);
810
- const value = super.transform(this.lastResolvedKey, ...args);
811
- if (this.localizationConfig.debugMode) {
812
- return getDebugKey(this.lastResolvedKey, value);
813
- }
814
- return value;
815
- }
816
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: O3rLocalizationTranslatePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
817
- /** @nocollapse */ static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "22.2.0", ngImport: i0, type: O3rLocalizationTranslatePipe, isStandalone: true, name: "o3rTranslate", pure: false }); }
818
- }
819
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: O3rLocalizationTranslatePipe, decorators: [{
820
- type: Pipe,
821
- args: [{
822
- name: 'o3rTranslate',
823
- pure: false,
824
- standalone: true
825
- }]
826
- }], ctorParameters: () => [] });
827
-
828
- /**
829
- * Service that provides core localization devtools functionality
830
- */
831
- class OtterLocalizationDevtools {
832
- constructor() {
833
- this.localizationService = inject(LocalizationService);
834
- this.translateTranspiler = inject(TRANSLOCO_TRANSPILER);
835
- this.appRef = inject(ApplicationRef);
836
- this.languageChangeSubscriptions = new Set();
837
- }
838
- /**
839
- * Is the translation deactivation enabled
840
- */
841
- isTranslationDeactivationEnabled() {
842
- return this.localizationService.isTranslationDeactivationEnabled();
843
- }
844
- /**
845
- * Show localization keys
846
- * @param value value enforced by the DevTools extension
847
- */
848
- showLocalizationKeys(value) {
849
- this.localizationService.toggleShowKeys(value);
850
- this.appRef.tick();
851
- }
852
- /**
853
- * Returns the current language
854
- */
855
- getCurrentLanguage() {
856
- return this.localizationService.getCurrentLanguage();
857
- }
858
- /**
859
- * Set up a listener on language change
860
- * @param fn called when the language is changed in the app
861
- * @returns Object with unsubscribe() method to prevent memory leaks
862
- */
863
- onLanguageChange(fn) {
864
- const subscription = this.localizationService
865
- .getTranslateService()
866
- .langChanges$
867
- .subscribe((lang) => {
868
- fn(lang);
869
- });
870
- this.languageChangeSubscriptions.add(subscription);
871
- // Return custom object with unsubscribe method
872
- return {
873
- unsubscribe: () => {
874
- subscription.unsubscribe();
875
- this.languageChangeSubscriptions.delete(subscription);
876
- }
877
- };
878
- }
879
- /**
880
- * Clear all language change listeners
881
- */
882
- clearLanguageChangeListeners() {
883
- this.languageChangeSubscriptions.forEach((sub) => sub.unsubscribe());
884
- this.languageChangeSubscriptions.clear();
885
- }
886
- /**
887
- * Cleanup subscriptions when service is destroyed
888
- */
889
- ngOnDestroy() {
890
- this.clearLanguageChangeListeners();
891
- }
892
- /**
893
- * Switch the current language to the specified value
894
- * @param language new language to switch to
895
- */
896
- async switchLanguage(language) {
897
- if (!language) {
898
- return;
899
- }
900
- await lastValueFrom(this.localizationService.useLanguage(language));
901
- this.appRef.tick();
902
- }
903
- /**
904
- * Updates the specified localization key/values for the current language.
905
- *
906
- * Recommendation: To be used with a small number of keys to update to avoid performance issues.
907
- * @param keyValues key/values to update
908
- * @param language if not provided, the current language value
909
- */
910
- updateLocalizationKeys(keyValues, language) {
911
- const lang = language || this.getCurrentLanguage();
912
- const translateService = this.localizationService.getTranslateService();
913
- Object.entries(keyValues).forEach(([key, value]) => {
914
- translateService.setTranslationKey(key, value, { lang });
915
- });
916
- this.appRef.tick();
917
- }
918
- /**
919
- * Reload a language from the language file
920
- * @param language language to reload
921
- */
922
- async reloadLocalizationKeys(language) {
923
- const lang = language || this.getCurrentLanguage();
924
- if (this.translateTranspiler.setLocale) {
925
- this.translateTranspiler.setLocale(null);
926
- }
927
- const translateService = this.localizationService.getTranslateService();
928
- const translations = await lastValueFrom(translateService.load(lang));
929
- translateService.setTranslation(translations, lang, { merge: false });
930
- this.appRef.tick();
931
- }
932
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: OtterLocalizationDevtools, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
933
- /** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: OtterLocalizationDevtools }); }
934
- }
935
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: OtterLocalizationDevtools, decorators: [{
936
- type: Injectable
937
- }] });
938
-
939
- /**
940
- * Default configuration options for the Otter Localization Devtools
941
- */
589
+ var LocalizationTranslateDirective = class LocalizationTranslateDirective extends TranslocoDirective {
590
+ set transloco(key) {
591
+ if (key) this.translocoSubject.next(key);
592
+ }
593
+ constructor() {
594
+ super();
595
+ this.localizationService = inject(LocalizationService);
596
+ this.localizationConfig = inject(LOCALIZATION_CONFIGURATION_TOKEN);
597
+ this.changeDetectorRef = inject(ChangeDetectorRef);
598
+ this.hostElement = inject(ElementRef);
599
+ this.hostRenderer = inject(Renderer2);
600
+ this.isAttributeStrategy = inject(TemplateRef, { optional: true }) === null;
601
+ this.o3rDestroyRef = inject(DestroyRef);
602
+ this.showKeys = false;
603
+ this.translocoSubject = new Subject();
604
+ if (this.localizationConfig.enableTranslationDeactivation) this.localizationService.showKeys$.pipe(takeUntilDestroyed(this.o3rDestroyRef)).subscribe((showKeys) => {
605
+ this.showKeys = showKeys;
606
+ this.changeDetectorRef.markForCheck();
607
+ });
608
+ this.translocoSubject.pipe(switchMap((key) => this.localizationService.getKey(key)), takeUntilDestroyed(this.o3rDestroyRef)).subscribe((newKey) => {
609
+ const previousKey = this.key;
610
+ this.key = newKey;
611
+ this.changeDetectorRef.markForCheck();
612
+ super.ngOnChanges({ transloco: new SimpleChange(previousKey, newKey, !previousKey) });
613
+ });
614
+ }
615
+ applyAttributeDebug() {
616
+ if (!this.isAttributeStrategy || !this.key) return;
617
+ if (this.showKeys) this.hostRenderer.setProperty(this.hostElement.nativeElement, "innerText", this.key);
618
+ else if (this.localizationConfig.debugMode) this.hostRenderer.setProperty(this.hostElement.nativeElement, "innerText", getDebugKey(this.key, this.hostElement.nativeElement.innerText));
619
+ }
620
+ getTranslateFn(lang, prefix) {
621
+ const parentTranslateFn = super.getTranslateFn(lang, prefix);
622
+ return (key, params) => {
623
+ if (this.showKeys) return key;
624
+ const value = parentTranslateFn(key, params);
625
+ if (this.localizationConfig.debugMode) return getDebugKey(key, value);
626
+ return value;
627
+ };
628
+ }
629
+ ngOnInit() {
630
+ super.ngOnInit();
631
+ this.applyAttributeDebug();
632
+ }
633
+ ngOnChanges(changes) {
634
+ super.ngOnChanges(changes);
635
+ this.applyAttributeDebug();
636
+ }
637
+ static {
638
+ this.ɵfac = i0.ɵɵngDeclareFactory({
639
+ minVersion: "12.0.0",
640
+ version: "22.2.3",
641
+ ngImport: i0,
642
+ type: LocalizationTranslateDirective,
643
+ deps: [],
644
+ target: i0.ɵɵFactoryTarget.Directive
645
+ });
646
+ }
647
+ static {
648
+ this.ɵdir = i0.ɵɵngDeclareDirective({
649
+ minVersion: "14.0.0",
650
+ version: "22.2.3",
651
+ type: LocalizationTranslateDirective,
652
+ isStandalone: true,
653
+ selector: "[transloco]",
654
+ inputs: { transloco: "transloco" },
655
+ usesInheritance: true,
656
+ usesOnChanges: true,
657
+ ngImport: i0
658
+ });
659
+ }
660
+ };
661
+ i0.ɵɵngDeclareClassMetadata({
662
+ minVersion: "12.0.0",
663
+ version: "22.2.3",
664
+ ngImport: i0,
665
+ type: LocalizationTranslateDirective,
666
+ decorators: [{
667
+ type: Directive,
668
+ args: [{
669
+ selector: "[transloco]",
670
+ standalone: true
671
+ }]
672
+ }],
673
+ ctorParameters: () => [],
674
+ propDecorators: { transloco: [{ type: Input }] }
675
+ });
676
+ var O3rLocalizationTranslatePipe = class O3rLocalizationTranslatePipe extends TranslocoPipe {
677
+ constructor() {
678
+ super(inject(TranslocoService), inject(TRANSLOCO_SCOPE, { optional: true }) ?? void 0, inject(TRANSLOCO_LANG, { optional: true }) ?? void 0, inject(ChangeDetectorRef));
679
+ this.localizationService = inject(LocalizationService);
680
+ this.changeDetector = inject(ChangeDetectorRef);
681
+ this.localizationConfig = inject(LOCALIZATION_CONFIGURATION_TOKEN);
682
+ this.destroyRef = inject(DestroyRef);
683
+ this.showKeys = false;
684
+ this.querySubject = new Subject();
685
+ if (this.localizationConfig.enableTranslationDeactivation) this.localizationService.showKeys$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((showKeys) => {
686
+ this.showKeys = showKeys;
687
+ this.changeDetector.markForCheck();
688
+ });
689
+ this.querySubject.pipe(switchMap((query) => this.localizationService.getKey(query)), takeUntilDestroyed(this.destroyRef)).subscribe((key) => {
690
+ this.lastResolvedKey = key;
691
+ this.changeDetector.markForCheck();
692
+ });
693
+ }
694
+ transform(query, ...args) {
695
+ if (!query || this.localizationService.showKeys()) return query;
696
+ this.querySubject.next(query);
697
+ const value = super.transform(this.lastResolvedKey, ...args);
698
+ if (this.localizationConfig.debugMode) return getDebugKey(this.lastResolvedKey, value);
699
+ return value;
700
+ }
701
+ static {
702
+ this.ɵfac = i0.ɵɵngDeclareFactory({
703
+ minVersion: "12.0.0",
704
+ version: "22.2.3",
705
+ ngImport: i0,
706
+ type: O3rLocalizationTranslatePipe,
707
+ deps: [],
708
+ target: i0.ɵɵFactoryTarget.Pipe
709
+ });
710
+ }
711
+ static {
712
+ this.ɵpipe = i0.ɵɵngDeclarePipe({
713
+ minVersion: "14.0.0",
714
+ version: "22.2.3",
715
+ ngImport: i0,
716
+ type: O3rLocalizationTranslatePipe,
717
+ isStandalone: true,
718
+ name: "o3rTranslate",
719
+ pure: false
720
+ });
721
+ }
722
+ };
723
+ i0.ɵɵngDeclareClassMetadata({
724
+ minVersion: "12.0.0",
725
+ version: "22.2.3",
726
+ ngImport: i0,
727
+ type: O3rLocalizationTranslatePipe,
728
+ decorators: [{
729
+ type: Pipe,
730
+ args: [{
731
+ name: "o3rTranslate",
732
+ pure: false,
733
+ standalone: true
734
+ }]
735
+ }],
736
+ ctorParameters: () => []
737
+ });
738
+ var OtterLocalizationDevtools = class OtterLocalizationDevtools {
739
+ constructor() {
740
+ this.localizationService = inject(LocalizationService);
741
+ this.translateTranspiler = inject(TRANSLOCO_TRANSPILER);
742
+ this.appRef = inject(ApplicationRef);
743
+ this.languageChangeSubscriptions = /* @__PURE__ */ new Set();
744
+ }
745
+ isTranslationDeactivationEnabled() {
746
+ return this.localizationService.isTranslationDeactivationEnabled();
747
+ }
748
+ showLocalizationKeys(value) {
749
+ this.localizationService.toggleShowKeys(value);
750
+ this.appRef.tick();
751
+ }
752
+ getCurrentLanguage() {
753
+ return this.localizationService.getCurrentLanguage();
754
+ }
755
+ onLanguageChange(fn) {
756
+ const subscription = this.localizationService.getTranslateService().langChanges$.subscribe((lang) => {
757
+ fn(lang);
758
+ });
759
+ this.languageChangeSubscriptions.add(subscription);
760
+ return { unsubscribe: () => {
761
+ subscription.unsubscribe();
762
+ this.languageChangeSubscriptions.delete(subscription);
763
+ } };
764
+ }
765
+ clearLanguageChangeListeners() {
766
+ this.languageChangeSubscriptions.forEach((sub) => sub.unsubscribe());
767
+ this.languageChangeSubscriptions.clear();
768
+ }
769
+ ngOnDestroy() {
770
+ this.clearLanguageChangeListeners();
771
+ }
772
+ async switchLanguage(language) {
773
+ if (!language) return;
774
+ await lastValueFrom(this.localizationService.useLanguage(language));
775
+ this.appRef.tick();
776
+ }
777
+ updateLocalizationKeys(keyValues, language) {
778
+ const lang = language || this.getCurrentLanguage();
779
+ const translateService = this.localizationService.getTranslateService();
780
+ Object.entries(keyValues).forEach(([key, value]) => {
781
+ translateService.setTranslationKey(key, value, { lang });
782
+ });
783
+ this.appRef.tick();
784
+ }
785
+ async reloadLocalizationKeys(language) {
786
+ const lang = language || this.getCurrentLanguage();
787
+ if (this.translateTranspiler.setLocale) this.translateTranspiler.setLocale(null);
788
+ const translateService = this.localizationService.getTranslateService();
789
+ const translations = await lastValueFrom(translateService.load(lang));
790
+ translateService.setTranslation(translations, lang, { merge: false });
791
+ this.appRef.tick();
792
+ }
793
+ static {
794
+ this.ɵfac = i0.ɵɵngDeclareFactory({
795
+ minVersion: "12.0.0",
796
+ version: "22.2.3",
797
+ ngImport: i0,
798
+ type: OtterLocalizationDevtools,
799
+ deps: [],
800
+ target: i0.ɵɵFactoryTarget.Injectable
801
+ });
802
+ }
803
+ static {
804
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
805
+ minVersion: "12.0.0",
806
+ version: "22.2.3",
807
+ ngImport: i0,
808
+ type: OtterLocalizationDevtools
809
+ });
810
+ }
811
+ };
812
+ i0.ɵɵngDeclareClassMetadata({
813
+ minVersion: "12.0.0",
814
+ version: "22.2.3",
815
+ ngImport: i0,
816
+ type: OtterLocalizationDevtools,
817
+ decorators: [{ type: Injectable }]
818
+ });
942
819
  const OTTER_LOCALIZATION_DEVTOOLS_DEFAULT_OPTIONS = {
943
- isActivatedOnBootstrap: false,
944
- isActivatedOnBootstrapWhenCMSContext: true,
945
- metadataFilePath: './metadata/localisation.metadata.json'
820
+ isActivatedOnBootstrap: false,
821
+ isActivatedOnBootstrapWhenCMSContext: true,
822
+ metadataFilePath: "./metadata/localisation.metadata.json"
946
823
  };
947
- /**
948
- * Injection token for Otter Localization Devtools configuration options
949
- */
950
- const OTTER_LOCALIZATION_DEVTOOLS_OPTIONS = new InjectionToken('Otter Localization Devtools options');
951
-
952
- /* eslint-disable no-console -- This is the purpose of this service */
953
- /**
954
- * Service that exposes localization devtools functionality via the browser console
955
- */
956
- class LocalizationDevtoolsConsoleService {
957
- /** Name of the Window property to access to the devtools */
958
- static { this.windowModuleName = 'localization'; }
959
- constructor() {
960
- this.localizationDevtools = inject(OtterLocalizationDevtools);
961
- this.options = inject(OTTER_LOCALIZATION_DEVTOOLS_OPTIONS, { optional: true }) ?? OTTER_LOCALIZATION_DEVTOOLS_DEFAULT_OPTIONS;
962
- if (this.options.isActivatedOnBootstrap
963
- || (this.options.isActivatedOnBootstrapWhenCMSContext
964
- && document.body.dataset.cmscontext === 'true')) {
965
- this.activate();
966
- }
967
- }
968
- /** @inheritDoc */
969
- activate() {
970
- const windowWithDevtools = window;
971
- windowWithDevtools._OTTER_DEVTOOLS_ ||= {};
972
- windowWithDevtools._OTTER_DEVTOOLS_[LocalizationDevtoolsConsoleService.windowModuleName] = this;
973
- console.info(`Otter localization Devtools is now accessible via the _OTTER_DEVTOOLS_.${LocalizationDevtoolsConsoleService.windowModuleName} variable`);
974
- }
975
- /**
976
- * @inheritdoc
977
- */
978
- isTranslationDeactivationEnabled() {
979
- return this.localizationDevtools.isTranslationDeactivationEnabled();
980
- }
981
- /**
982
- * @inheritdoc
983
- */
984
- showLocalizationKeys(value) {
985
- this.localizationDevtools.showLocalizationKeys(value);
986
- }
987
- /**
988
- * @inheritdoc
989
- */
990
- getCurrentLanguage() {
991
- const currentLanguage = this.localizationDevtools.getCurrentLanguage();
992
- return currentLanguage;
993
- }
994
- /**
995
- * @inheritdoc
996
- */
997
- async switchLanguage(language) {
998
- const previous = this.localizationDevtools.getCurrentLanguage();
999
- await this.localizationDevtools.switchLanguage(language);
1000
- const current = this.localizationDevtools.getCurrentLanguage();
1001
- return {
1002
- requested: language,
1003
- previous,
1004
- current
1005
- };
1006
- }
1007
- /**
1008
- * @inheritdoc
1009
- */
1010
- onLanguageChange(fn) {
1011
- return this.localizationDevtools.onLanguageChange(fn);
1012
- }
1013
- /**
1014
- * @inheritdoc
1015
- */
1016
- clearLanguageChangeListeners() {
1017
- this.localizationDevtools.clearLanguageChangeListeners();
1018
- }
1019
- /**
1020
- * @inheritdoc
1021
- */
1022
- updateLocalizationKeys(keyValues, language) {
1023
- return this.localizationDevtools.updateLocalizationKeys(keyValues, language);
1024
- }
1025
- /**
1026
- * @inheritdoc
1027
- */
1028
- reloadLocalizationKeys(language) {
1029
- return this.localizationDevtools.reloadLocalizationKeys(language);
1030
- }
1031
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationDevtoolsConsoleService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1032
- /** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationDevtoolsConsoleService }); }
1033
- }
1034
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationDevtoolsConsoleService, decorators: [{
1035
- type: Injectable
1036
- }], ctorParameters: () => [] });
1037
-
1038
- /**
1039
- * Type guard to check if a message is a localization message
1040
- * @param message Message to check
1041
- * @returns True if the message is a localization message
1042
- */
824
+ const OTTER_LOCALIZATION_DEVTOOLS_OPTIONS = new InjectionToken("Otter Localization Devtools options");
825
+ var LocalizationDevtoolsConsoleService = class LocalizationDevtoolsConsoleService {
826
+ static {
827
+ this.windowModuleName = "localization";
828
+ }
829
+ constructor() {
830
+ this.localizationDevtools = inject(OtterLocalizationDevtools);
831
+ this.options = inject(OTTER_LOCALIZATION_DEVTOOLS_OPTIONS, { optional: true }) ?? OTTER_LOCALIZATION_DEVTOOLS_DEFAULT_OPTIONS;
832
+ if (this.options.isActivatedOnBootstrap || this.options.isActivatedOnBootstrapWhenCMSContext && document.body.dataset.cmscontext === "true") this.activate();
833
+ }
834
+ activate() {
835
+ const windowWithDevtools = window;
836
+ windowWithDevtools._OTTER_DEVTOOLS_ ||= {};
837
+ windowWithDevtools._OTTER_DEVTOOLS_[LocalizationDevtoolsConsoleService.windowModuleName] = this;
838
+ console.info(`Otter localization Devtools is now accessible via the _OTTER_DEVTOOLS_.${LocalizationDevtoolsConsoleService.windowModuleName} variable`);
839
+ }
840
+ isTranslationDeactivationEnabled() {
841
+ return this.localizationDevtools.isTranslationDeactivationEnabled();
842
+ }
843
+ showLocalizationKeys(value) {
844
+ this.localizationDevtools.showLocalizationKeys(value);
845
+ }
846
+ getCurrentLanguage() {
847
+ return this.localizationDevtools.getCurrentLanguage();
848
+ }
849
+ async switchLanguage(language) {
850
+ const previous = this.localizationDevtools.getCurrentLanguage();
851
+ await this.localizationDevtools.switchLanguage(language);
852
+ return {
853
+ requested: language,
854
+ previous,
855
+ current: this.localizationDevtools.getCurrentLanguage()
856
+ };
857
+ }
858
+ onLanguageChange(fn) {
859
+ return this.localizationDevtools.onLanguageChange(fn);
860
+ }
861
+ clearLanguageChangeListeners() {
862
+ this.localizationDevtools.clearLanguageChangeListeners();
863
+ }
864
+ updateLocalizationKeys(keyValues, language) {
865
+ return this.localizationDevtools.updateLocalizationKeys(keyValues, language);
866
+ }
867
+ reloadLocalizationKeys(language) {
868
+ return this.localizationDevtools.reloadLocalizationKeys(language);
869
+ }
870
+ static {
871
+ this.ɵfac = i0.ɵɵngDeclareFactory({
872
+ minVersion: "12.0.0",
873
+ version: "22.2.3",
874
+ ngImport: i0,
875
+ type: LocalizationDevtoolsConsoleService,
876
+ deps: [],
877
+ target: i0.ɵɵFactoryTarget.Injectable
878
+ });
879
+ }
880
+ static {
881
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
882
+ minVersion: "12.0.0",
883
+ version: "22.2.3",
884
+ ngImport: i0,
885
+ type: LocalizationDevtoolsConsoleService
886
+ });
887
+ }
888
+ };
889
+ i0.ɵɵngDeclareClassMetadata({
890
+ minVersion: "12.0.0",
891
+ version: "22.2.3",
892
+ ngImport: i0,
893
+ type: LocalizationDevtoolsConsoleService,
894
+ decorators: [{ type: Injectable }],
895
+ ctorParameters: () => []
896
+ });
1043
897
  const isLocalizationMessage = (message) => {
1044
- return message && (message.dataType === 'displayLocalizationKeys'
1045
- || message.dataType === 'languages'
1046
- || message.dataType === 'switchLanguage'
1047
- || message.dataType === 'localizations'
1048
- || message.dataType === 'updateLocalization'
1049
- || message.dataType === 'requestMessages'
1050
- || message.dataType === 'connect'
1051
- || message.dataType === 'reloadLocalizationKeys'
1052
- || message.dataType === 'isTranslationDeactivationEnabled'
1053
- || message.dataType === 'getTranslationValuesContentMessage');
898
+ return message && (message.dataType === "displayLocalizationKeys" || message.dataType === "languages" || message.dataType === "switchLanguage" || message.dataType === "localizations" || message.dataType === "updateLocalization" || message.dataType === "requestMessages" || message.dataType === "connect" || message.dataType === "reloadLocalizationKeys" || message.dataType === "isTranslationDeactivationEnabled" || message.dataType === "getTranslationValuesContentMessage");
1054
899
  };
1055
- /**
1056
- * Service that handles localization devtools messages communication
1057
- */
1058
- class LocalizationDevtoolsMessageService {
1059
- constructor() {
1060
- this.logger = inject(LoggerService);
1061
- this.localizationDevTools = inject(OtterLocalizationDevtools);
1062
- this.localizationService = inject(LocalizationService);
1063
- this.options = inject(OTTER_LOCALIZATION_DEVTOOLS_OPTIONS, { optional: true }) ?? OTTER_LOCALIZATION_DEVTOOLS_DEFAULT_OPTIONS;
1064
- this.sendMessage = (sendOtterMessage);
1065
- this.destroyRef = inject(DestroyRef);
1066
- this.options = {
1067
- ...OTTER_LOCALIZATION_DEVTOOLS_DEFAULT_OPTIONS,
1068
- ...this.options
1069
- };
1070
- if (this.options.isActivatedOnBootstrap) {
1071
- this.activate();
1072
- }
1073
- }
1074
- async sendLocalizationsMetadata() {
1075
- const metadata = await (await fetch(this.options.metadataFilePath)).json();
1076
- this.sendMessage('localizations', {
1077
- localizations: metadata
1078
- });
1079
- }
1080
- /**
1081
- * Function to trigger a re-send a requested messages to the Otter Chrome DevTools extension
1082
- * @param only restricted list of messages to re-send
1083
- */
1084
- handleReEmitRequest(only) {
1085
- if (!only || only.includes('localizations')) {
1086
- void this.sendLocalizationsMetadata();
1087
- }
1088
- if (!only || only.includes('switchLanguage')) {
1089
- this.sendMessage('switchLanguage', { language: this.localizationDevTools.getCurrentLanguage() });
1090
- }
1091
- if (!only || only.includes('languages')) {
1092
- this.sendMessage('languages', { languages: this.localizationService.getLanguages() });
1093
- }
1094
- if (!only || only.includes('getTranslationValuesContentMessage')) {
1095
- this.sendMessage('getTranslationValuesContentMessage', {
1096
- translations: this.localizationService.getTranslateService().getTranslation(this.localizationService.getCurrentLanguage())
1097
- });
1098
- }
1099
- if (!only || only.includes('isTranslationDeactivationEnabled')) {
1100
- this.sendMessage('isTranslationDeactivationEnabled', { enabled: this.localizationService.isTranslationDeactivationEnabled() });
1101
- }
1102
- }
1103
- /**
1104
- * Function to handle the incoming messages from Otter Chrome DevTools extension
1105
- * @param message Message coming from the Otter Chrome DevTools extension
1106
- */
1107
- handleEvents(message) {
1108
- this.logger.debug('Message handling by the localization service', message);
1109
- switch (message.dataType) {
1110
- case 'connect': {
1111
- this.connectPlugin();
1112
- break;
1113
- }
1114
- case 'displayLocalizationKeys': {
1115
- this.localizationDevTools.showLocalizationKeys(message.toggle);
1116
- break;
1117
- }
1118
- case 'requestMessages': {
1119
- void this.handleReEmitRequest(message.only);
1120
- break;
1121
- }
1122
- case 'switchLanguage': {
1123
- void this.localizationDevTools.switchLanguage(message.language);
1124
- break;
1125
- }
1126
- case 'updateLocalization': {
1127
- void this.localizationDevTools.updateLocalizationKeys({
1128
- [message.key]: message.value
1129
- }, message.lang);
1130
- break;
1131
- }
1132
- case 'reloadLocalizationKeys': {
1133
- void this.localizationDevTools.reloadLocalizationKeys(message.lang);
1134
- break;
1135
- }
1136
- default: {
1137
- this.logger.warn('Message ignored by the localization service', message);
1138
- }
1139
- }
1140
- }
1141
- /**
1142
- * Function to connect the plugin to the Otter Chrome DevTools extension
1143
- */
1144
- connectPlugin() {
1145
- this.logger.debug('Otter DevTools is plugged to localization service of the application');
1146
- }
1147
- /** @inheritDoc */
1148
- activate() {
1149
- fromEvent(window, 'message').pipe(takeUntilDestroyed(this.destroyRef), filterMessageContent(isLocalizationMessage)).subscribe((e) => this.handleEvents(e));
1150
- }
1151
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationDevtoolsMessageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1152
- /** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationDevtoolsMessageService }); }
1153
- }
1154
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LocalizationDevtoolsMessageService, decorators: [{
1155
- type: Injectable
1156
- }], ctorParameters: () => [] });
1157
-
1158
- /**
1159
- * Provide localization devtools functionality for the application.
1160
- * This is the recommended way to set up localization devtools in standalone applications.
1161
- * @param options Optional partial localization devtools configuration to override defaults. Can be a configuration object or a factory function.
1162
- * @example Load localization with automatic activation at bootstrap
1163
- * ```typescript
1164
- * bootstrapApplication(App, {
1165
- * providers: [
1166
- * provideLocalizationDevtools({ isActivatedOnBootstrap: true })
1167
- * ]
1168
- * });
1169
- * ```
1170
- */
900
+ var LocalizationDevtoolsMessageService = class LocalizationDevtoolsMessageService {
901
+ constructor() {
902
+ this.logger = inject(LoggerService);
903
+ this.localizationDevTools = inject(OtterLocalizationDevtools);
904
+ this.localizationService = inject(LocalizationService);
905
+ this.options = inject(OTTER_LOCALIZATION_DEVTOOLS_OPTIONS, { optional: true }) ?? OTTER_LOCALIZATION_DEVTOOLS_DEFAULT_OPTIONS;
906
+ this.sendMessage = sendOtterMessage;
907
+ this.destroyRef = inject(DestroyRef);
908
+ this.options = {
909
+ ...OTTER_LOCALIZATION_DEVTOOLS_DEFAULT_OPTIONS,
910
+ ...this.options
911
+ };
912
+ if (this.options.isActivatedOnBootstrap) this.activate();
913
+ }
914
+ async sendLocalizationsMetadata() {
915
+ const metadata = await (await fetch(this.options.metadataFilePath)).json();
916
+ this.sendMessage("localizations", { localizations: metadata });
917
+ }
918
+ handleReEmitRequest(only) {
919
+ if (!only || only.includes("localizations")) this.sendLocalizationsMetadata();
920
+ if (!only || only.includes("switchLanguage")) this.sendMessage("switchLanguage", { language: this.localizationDevTools.getCurrentLanguage() });
921
+ if (!only || only.includes("languages")) this.sendMessage("languages", { languages: this.localizationService.getLanguages() });
922
+ if (!only || only.includes("getTranslationValuesContentMessage")) this.sendMessage("getTranslationValuesContentMessage", { translations: this.localizationService.getTranslateService().getTranslation(this.localizationService.getCurrentLanguage()) });
923
+ if (!only || only.includes("isTranslationDeactivationEnabled")) this.sendMessage("isTranslationDeactivationEnabled", { enabled: this.localizationService.isTranslationDeactivationEnabled() });
924
+ }
925
+ handleEvents(message) {
926
+ this.logger.debug("Message handling by the localization service", message);
927
+ switch (message.dataType) {
928
+ case "connect":
929
+ this.connectPlugin();
930
+ break;
931
+ case "displayLocalizationKeys":
932
+ this.localizationDevTools.showLocalizationKeys(message.toggle);
933
+ break;
934
+ case "requestMessages":
935
+ this.handleReEmitRequest(message.only);
936
+ break;
937
+ case "switchLanguage":
938
+ this.localizationDevTools.switchLanguage(message.language);
939
+ break;
940
+ case "updateLocalization":
941
+ this.localizationDevTools.updateLocalizationKeys({ [message.key]: message.value }, message.lang);
942
+ break;
943
+ case "reloadLocalizationKeys":
944
+ this.localizationDevTools.reloadLocalizationKeys(message.lang);
945
+ break;
946
+ default: this.logger.warn("Message ignored by the localization service", message);
947
+ }
948
+ }
949
+ connectPlugin() {
950
+ this.logger.debug("Otter DevTools is plugged to localization service of the application");
951
+ }
952
+ activate() {
953
+ fromEvent(window, "message").pipe(takeUntilDestroyed(this.destroyRef), filterMessageContent(isLocalizationMessage)).subscribe((e) => this.handleEvents(e));
954
+ }
955
+ static {
956
+ this.ɵfac = i0.ɵɵngDeclareFactory({
957
+ minVersion: "12.0.0",
958
+ version: "22.2.3",
959
+ ngImport: i0,
960
+ type: LocalizationDevtoolsMessageService,
961
+ deps: [],
962
+ target: i0.ɵɵFactoryTarget.Injectable
963
+ });
964
+ }
965
+ static {
966
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
967
+ minVersion: "12.0.0",
968
+ version: "22.2.3",
969
+ ngImport: i0,
970
+ type: LocalizationDevtoolsMessageService
971
+ });
972
+ }
973
+ };
974
+ i0.ɵɵngDeclareClassMetadata({
975
+ minVersion: "12.0.0",
976
+ version: "22.2.3",
977
+ ngImport: i0,
978
+ type: LocalizationDevtoolsMessageService,
979
+ decorators: [{ type: Injectable }],
980
+ ctorParameters: () => []
981
+ });
1171
982
  function provideLocalizationDevtools(options) {
1172
- return makeEnvironmentProviders([
1173
- {
1174
- provide: OTTER_LOCALIZATION_DEVTOOLS_OPTIONS,
1175
- useValue: { ...OTTER_LOCALIZATION_DEVTOOLS_DEFAULT_OPTIONS, ...options }
1176
- },
1177
- LocalizationDevtoolsMessageService,
1178
- LocalizationDevtoolsConsoleService,
1179
- OtterLocalizationDevtools
1180
- ]);
983
+ return makeEnvironmentProviders([
984
+ {
985
+ provide: OTTER_LOCALIZATION_DEVTOOLS_OPTIONS,
986
+ useValue: {
987
+ ...OTTER_LOCALIZATION_DEVTOOLS_DEFAULT_OPTIONS,
988
+ ...options
989
+ }
990
+ },
991
+ LocalizationDevtoolsMessageService,
992
+ LocalizationDevtoolsConsoleService,
993
+ OtterLocalizationDevtools
994
+ ]);
1181
995
  }
1182
-
1183
- /**
1184
- * Generated bundle index. Do not edit.
1185
- */
1186
-
1187
996
  export { CUSTOM_LOCALIZATION_CONFIGURATION_TOKEN, DEFAULT_LOCALIZATION_CONFIGURATION, LOCALIZATION_CONFIGURATION_TOKEN, LOCALIZATION_OVERRIDE_REDUCER_TOKEN, LOCALIZATION_OVERRIDE_STORE_NAME, Localization, LocalizationDevtoolsConsoleService, LocalizationDevtoolsMessageService, LocalizationOverrideStoreModule, LocalizationService, LocalizationTranslateDirective, LocalizedCurrencyPipe, LocalizedDatePipe, LocalizedDecimalPipe, O3rLocalizationTranslatePipe, OTTER_LOCALIZATION_DEVTOOLS_DEFAULT_OPTIONS, OTTER_LOCALIZATION_DEVTOOLS_OPTIONS, OtterLocalizationDevtools, TextDirectionService, TranslationsLoader, createLocalizationConfiguration, createTranslateLoader, getDebugKey, getDefaultLocalizationOverrideReducer, localeIdNgBridge, localizationOverrideInitialState, localizationOverrideReducer, localizationOverrideReducerFeatures, localizationOverrideStorageDeserializer, localizationOverrideStorageSync, provideLocalization, provideLocalizationDevtools, provideLocalizationOverrideStore, selectLocalizationOverride, selectLocalizationOverrideState, setLocalizationOverride, translateLoaderProvider };
1188
- //# sourceMappingURL=o3r-transloco.mjs.map
997
+
998
+ //# sourceMappingURL=o3r-transloco.mjs.map