@hakistack/i18n 0.1.0 → 0.2.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.
- package/README.md +181 -30
- package/cli/bin.cjs +894 -423
- package/fesm2022/hakistack-i18n-engine.mjs +140 -85
- package/fesm2022/hakistack-i18n-engine.mjs.map +1 -1
- package/fesm2022/hakistack-i18n.mjs +302 -92
- package/fesm2022/hakistack-i18n.mjs.map +1 -1
- package/package.json +14 -7
- package/schematics/ng-add/index.cjs +9 -34
- package/schematics/ng-add/index.cjs.map +1 -1
- package/schematics/ng-add/schema.json +1 -1
- package/types/hakistack-i18n-engine.d.ts +94 -30
- package/types/hakistack-i18n.d.ts +227 -53
|
@@ -1,20 +1,26 @@
|
|
|
1
1
|
import { buildLanguageTree, buildScopedTree, buildKeysTree } from '@hakistack/i18n/engine';
|
|
2
|
-
export { SOURCE_LANG, TRANSLATION_BRAND, buildEagerTree, buildKeysTree, buildLanguageTree, buildScopedTree, defineTranslations, extractLanguage, getTranslation, isTranslationValue, normalizeScope, scopeToFilesystemPath, setAtScope, t } from '@hakistack/i18n/engine';
|
|
2
|
+
export { SOURCE_LANG, TRANSLATION_BRAND, buildEagerTree, buildKeysTree, buildLanguageTree, buildScopedTree, defineTranslations, extractLanguage, findKeyConflicts, getTranslation, isTranslationValue, mergeKeys, normalizeScope, scopeToFilesystemPath, setAtScope, t } from '@hakistack/i18n/engine';
|
|
3
3
|
import * as i0 from '@angular/core';
|
|
4
|
-
import { Injectable, InjectionToken, inject, DOCUMENT, signal, isDevMode, provideAppInitializer, makeEnvironmentProviders, TemplateRef, ViewContainerRef,
|
|
5
|
-
import { TranslocoService, provideTransloco, provideTranslocoInterceptor, provideTranslocoMissingHandler } from '@jsverse/transloco';
|
|
6
|
-
export { translateObjectSignal
|
|
4
|
+
import { Injectable, InjectionToken, inject, PendingTasks, DOCUMENT, REQUEST, signal, computed, isDevMode, provideAppInitializer, makeEnvironmentProviders, TemplateRef, ViewContainerRef, Directive } from '@angular/core';
|
|
5
|
+
import { TranslocoService, provideTransloco, provideTranslocoInterceptor, provideTranslocoMissingHandler, translateSignal as translateSignal$1 } from '@jsverse/transloco';
|
|
6
|
+
export { translateObjectSignal } from '@jsverse/transloco';
|
|
7
7
|
import { HttpClient } from '@angular/common/http';
|
|
8
|
-
import { firstValueFrom, of } from 'rxjs';
|
|
9
|
-
import {
|
|
8
|
+
import { from, firstValueFrom, of, switchMap, map, catchError } from 'rxjs';
|
|
9
|
+
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
|
-
* Strips
|
|
12
|
+
* Strips translator-comment siblings before translations enter Transloco's store.
|
|
13
13
|
*
|
|
14
14
|
* Translator-context comments (added via `t('en', { es: '…' }, { comment })`)
|
|
15
|
-
* are
|
|
16
|
-
*
|
|
17
|
-
*
|
|
15
|
+
* are written into the generated JSON as a `<key>.comment` sibling of their
|
|
16
|
+
* key. The registry loader never emits them; this interceptor removes them
|
|
17
|
+
* when the JSON is served over HTTP.
|
|
18
|
+
*
|
|
19
|
+
* Transloco hands this hook the **flattened** translation, so a real key whose
|
|
20
|
+
* last segment is `comment` (`post.comment`) also ends in `.comment`. The two
|
|
21
|
+
* are told apart structurally: a comment sibling `x.comment` only exists next
|
|
22
|
+
* to a translation `x`, while a real `post.comment` means `post` is a group and
|
|
23
|
+
* therefore never a flat key itself.
|
|
18
24
|
*/
|
|
19
25
|
class TranslocoCommentInterceptor {
|
|
20
26
|
preSaveTranslation(translation) {
|
|
@@ -29,14 +35,15 @@ class TranslocoCommentInterceptor {
|
|
|
29
35
|
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoCommentInterceptor, decorators: [{
|
|
30
36
|
type: Injectable
|
|
31
37
|
}] });
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
38
|
+
const COMMENT_SUFFIX = '.comment';
|
|
39
|
+
/** Exported for tests. Expects a flattened translation (what Transloco passes). */
|
|
40
|
+
function stripCommentKeys(flat) {
|
|
35
41
|
const out = {};
|
|
36
|
-
for (const [key, value] of Object.entries(
|
|
37
|
-
|
|
42
|
+
for (const [key, value] of Object.entries(flat)) {
|
|
43
|
+
const commentOf = key.endsWith(COMMENT_SUFFIX) ? key.slice(0, -COMMENT_SUFFIX.length) : null;
|
|
44
|
+
if (commentOf !== null && typeof flat[commentOf] === 'string')
|
|
38
45
|
continue;
|
|
39
|
-
out[key] =
|
|
46
|
+
out[key] = value;
|
|
40
47
|
}
|
|
41
48
|
return out;
|
|
42
49
|
}
|
|
@@ -88,12 +95,118 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImpo
|
|
|
88
95
|
}] });
|
|
89
96
|
|
|
90
97
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
98
|
+
* Translation loader backed by the generated `TRANSLATIONS` loaders: each
|
|
99
|
+
* language (and each scoped scope) is a separate chunk, dynamically imported
|
|
100
|
+
* the first time it is needed.
|
|
101
|
+
*
|
|
102
|
+
* The import runs as an Angular pending task, so server rendering waits for it
|
|
103
|
+
* and serializes translated HTML (no flash or hydration mismatch).
|
|
104
|
+
*/
|
|
105
|
+
class TranslocoLazyLoader {
|
|
106
|
+
config = inject(I18N_RUNTIME_CONFIG);
|
|
107
|
+
pendingTasks = inject(PendingTasks);
|
|
108
|
+
getTranslation(input) {
|
|
109
|
+
// Transloco requests scopes as `<scope>/<lang>` (e.g. `'admin/users/es'`); plain `'es'` is the root.
|
|
110
|
+
const slash = input.lastIndexOf('/');
|
|
111
|
+
const lang = slash === -1 ? input : input.slice(slash + 1);
|
|
112
|
+
const translations = this.config.translations;
|
|
113
|
+
const table = slash === -1 ? translations?.root : translations?.scopes?.[input.slice(0, slash)];
|
|
114
|
+
const load = table?.[lang];
|
|
115
|
+
if (!load) {
|
|
116
|
+
// Rejecting lets Transloco fall back (fallback language / missing handler).
|
|
117
|
+
return from(Promise.reject(new Error(`@hakistack/i18n: no translations generated for '${input}'.`)));
|
|
118
|
+
}
|
|
119
|
+
const done = this.pendingTasks.add();
|
|
120
|
+
return from(load()
|
|
121
|
+
.then((mod) => mod.default)
|
|
122
|
+
.finally(done));
|
|
123
|
+
}
|
|
124
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoLazyLoader, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
125
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoLazyLoader });
|
|
126
|
+
}
|
|
127
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoLazyLoader, decorators: [{
|
|
128
|
+
type: Injectable
|
|
129
|
+
}] });
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Locale helpers built on the standard `Intl` APIs (no locale data shipped).
|
|
133
|
+
*
|
|
134
|
+
* A *language* is what the translations are written in (`es`); a *locale* is
|
|
135
|
+
* the BCP 47 tag that drives formatting and `<html lang>` (`es-PR`). They
|
|
136
|
+
* default to the same tag but are configured separately per language option.
|
|
137
|
+
*/
|
|
138
|
+
/** Scripts written right-to-left (ISO 15924). */
|
|
139
|
+
const RTL_SCRIPTS = new Set(['Arab', 'Hebr', 'Thaa', 'Syrc', 'Nkoo', 'Adlm', 'Rohg', 'Mand', 'Samr', 'Mend']);
|
|
140
|
+
/**
|
|
141
|
+
* Text direction of a BCP 47 tag: `'rtl'` for Arabic, Hebrew, Persian, Urdu,
|
|
142
|
+
* Sorani (`ckb`), `pa-Arab`… and `'ltr'` otherwise. Uses `Intl.Locale` text
|
|
143
|
+
* info when the runtime has it, else the likely script (`maximize()`).
|
|
144
|
+
*/
|
|
145
|
+
function textDirection(tag) {
|
|
146
|
+
try {
|
|
147
|
+
const locale = new Intl.Locale(tag);
|
|
148
|
+
const direction = locale.getTextInfo?.().direction ?? locale.textInfo?.direction;
|
|
149
|
+
if (direction === 'rtl' || direction === 'ltr')
|
|
150
|
+
return direction;
|
|
151
|
+
const script = locale.maximize().script;
|
|
152
|
+
return script && RTL_SCRIPTS.has(script) ? 'rtl' : 'ltr';
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return 'ltr'; // not a valid tag
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** Language tags of an `Accept-Language` header, most preferred first (`q=0` dropped). */
|
|
159
|
+
function parseAcceptLanguage(header) {
|
|
160
|
+
if (!header)
|
|
161
|
+
return [];
|
|
162
|
+
return header
|
|
163
|
+
.split(',')
|
|
164
|
+
.map((part, index) => {
|
|
165
|
+
const [tag, ...attrs] = part.trim().split(';');
|
|
166
|
+
const q = attrs.map((a) => a.trim()).find((a) => a.startsWith('q='));
|
|
167
|
+
return { tag: tag.trim(), q: q ? Number(q.slice(2)) : 1, index };
|
|
168
|
+
})
|
|
169
|
+
.filter((entry) => entry.tag && entry.tag !== '*' && entry.q > 0)
|
|
170
|
+
.sort((a, b) => b.q - a.q || a.index - b.index)
|
|
171
|
+
.map((entry) => entry.tag);
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Best available language for a preference list: an exact tag match first
|
|
175
|
+
* (case-insensitive), then the same base language (`fr-CA` → `fr`, `es` → `es-MX`).
|
|
176
|
+
*/
|
|
177
|
+
function negotiateLanguage(preferred, available) {
|
|
178
|
+
const base = (tag) => tag.toLowerCase().split('-')[0];
|
|
179
|
+
for (const tag of preferred) {
|
|
180
|
+
const exact = available.find((a) => a.toLowerCase() === tag.toLowerCase());
|
|
181
|
+
if (exact)
|
|
182
|
+
return exact;
|
|
183
|
+
const sameBase = available.find((a) => base(a) === base(tag));
|
|
184
|
+
if (sameBase)
|
|
185
|
+
return sameBase;
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Name of the localStorage entry and of the cookie that remember the chosen language. */
|
|
191
|
+
const STORAGE_KEY = 'hakistack_i18n_lang';
|
|
192
|
+
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
|
|
193
|
+
/**
|
|
194
|
+
* App-level active-language service on top of `TranslocoService`:
|
|
93
195
|
*
|
|
94
|
-
*
|
|
95
|
-
* (
|
|
96
|
-
*
|
|
196
|
+
* - `language()` — the translation language; `locale()` — its BCP 47
|
|
197
|
+
* formatting locale (`es` + `locale: 'es-PR'`); `dir()` — `'ltr' | 'rtl'`.
|
|
198
|
+
* All follow Transloco's active language however it changes.
|
|
199
|
+
* - `<html lang>` (the locale) and `<html dir>` are kept in sync, on the
|
|
200
|
+
* server too.
|
|
201
|
+
* - {@link setLanguage} loads, activates and remembers a language
|
|
202
|
+
* (`localStorage`, or a cookie that SSR can read — `persistLanguage`).
|
|
203
|
+
* - On bootstrap ({@link initializeLanguage}, wired by `provideI18n` when
|
|
204
|
+
* `persistLanguage` or `detectLanguage` is set): the remembered language,
|
|
205
|
+
* else the best match for `Accept-Language` / `navigator.languages`
|
|
206
|
+
* (`detectLanguage`), else `defaultLang`.
|
|
207
|
+
*
|
|
208
|
+
* One instance per application (per request during SSR): no state is shared
|
|
209
|
+
* between users.
|
|
97
210
|
*
|
|
98
211
|
* ```ts
|
|
99
212
|
* private readonly i18nLang = inject(LanguageService);
|
|
@@ -101,24 +214,55 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImpo
|
|
|
101
214
|
* ```
|
|
102
215
|
*/
|
|
103
216
|
class LanguageService {
|
|
104
|
-
STORAGE_KEY = 'hakistack_i18n_lang';
|
|
105
217
|
transloco = inject(TranslocoService);
|
|
106
218
|
document = inject(DOCUMENT);
|
|
219
|
+
request = inject(REQUEST, { optional: true });
|
|
220
|
+
config = inject(I18N_RUNTIME_CONFIG, { optional: true });
|
|
107
221
|
defaultLanguage = this.transloco.getDefaultLang();
|
|
222
|
+
persistence = this.config?.persistence ?? 'local-storage';
|
|
108
223
|
/** Available languages from Transloco config. */
|
|
109
224
|
availableLanguages = this.transloco.getAvailableLangs();
|
|
110
|
-
/** Current active language (
|
|
111
|
-
language = signal(this.
|
|
225
|
+
/** Current active translation language (kept in sync with Transloco). */
|
|
226
|
+
language = signal(this.transloco.getActiveLang(), ...(ngDevMode ? [{ debugName: "language" }] : /* istanbul ignore next */ []));
|
|
227
|
+
/** Formatting locale of the active language (its `locale` option, else its id) — for `Intl.*` and locale pipes. */
|
|
228
|
+
locale = computed(() => this.option(this.language())?.locale ?? this.language(), ...(ngDevMode ? [{ debugName: "locale" }] : /* istanbul ignore next */ []));
|
|
229
|
+
/** Text direction of the active language (its `dir` option, else derived from the locale). */
|
|
230
|
+
dir = computed(() => this.option(this.language())?.dir ?? textDirection(this.locale()), ...(ngDevMode ? [{ debugName: "dir" }] : /* istanbul ignore next */ []));
|
|
231
|
+
constructor() {
|
|
232
|
+
this.transloco.langChanges$.pipe(takeUntilDestroyed()).subscribe((lang) => {
|
|
233
|
+
this.language.set(lang);
|
|
234
|
+
const html = this.document.documentElement;
|
|
235
|
+
html.setAttribute('lang', this.locale());
|
|
236
|
+
html.setAttribute('dir', this.dir());
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Bootstrap: the remembered language, else (with `detectLanguage`) the user's
|
|
241
|
+
* preference, else the default. Nothing is written: only an explicit
|
|
242
|
+
* {@link setLanguage} choice is remembered, so detection keeps following the
|
|
243
|
+
* user's preferences until they pick a language.
|
|
244
|
+
*/
|
|
112
245
|
async initializeLanguage() {
|
|
113
|
-
|
|
246
|
+
const remembered = this.rememberedLanguage();
|
|
247
|
+
const detected = remembered ?? (this.config?.detectLanguage ? this.preferredLanguage() : null);
|
|
248
|
+
await this.setLanguage(detected ?? this.defaultLanguage, { remember: false });
|
|
114
249
|
}
|
|
115
|
-
|
|
250
|
+
/**
|
|
251
|
+
* Load and activate `lang`, then remember it. Languages that are not in the
|
|
252
|
+
* configured `languages` list are ignored (with a dev-mode warning) so they
|
|
253
|
+
* can never become the active or stored language.
|
|
254
|
+
*/
|
|
255
|
+
async setLanguage(lang, options = {}) {
|
|
256
|
+
if (!this.isAvailable(lang)) {
|
|
257
|
+
if (isDevMode())
|
|
258
|
+
console.warn(`[@hakistack/i18n] setLanguage('${lang}') ignored — not one of the configured languages.`);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
116
261
|
try {
|
|
117
262
|
await firstValueFrom(this.transloco.load(lang));
|
|
118
263
|
this.transloco.setActiveLang(lang);
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
this.document.documentElement.setAttribute('lang', lang);
|
|
264
|
+
if (options.remember ?? true)
|
|
265
|
+
this.remember(lang);
|
|
122
266
|
}
|
|
123
267
|
catch (error) {
|
|
124
268
|
console.warn(`Failed to load language '${lang}', falling back to default`, error);
|
|
@@ -129,48 +273,78 @@ class LanguageService {
|
|
|
129
273
|
}
|
|
130
274
|
/** Is `lang` one of the configured available languages? */
|
|
131
275
|
isAvailable(lang) {
|
|
132
|
-
return this.
|
|
276
|
+
return this.languageIds().includes(lang);
|
|
277
|
+
}
|
|
278
|
+
languageIds() {
|
|
279
|
+
return this.availableLanguages.map((l) => (typeof l === 'string' ? l : l.id));
|
|
280
|
+
}
|
|
281
|
+
option(lang) {
|
|
282
|
+
return this.config?.languages.find((l) => l.id === lang);
|
|
133
283
|
}
|
|
134
284
|
/**
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
* (stale/garbage localStorage must never become the active `<html lang>`).
|
|
285
|
+
* The remembered language when it is still available — never a stale or
|
|
286
|
+
* garbage value. `null` when nothing (usable) is stored.
|
|
138
287
|
*/
|
|
139
|
-
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
288
|
+
rememberedLanguage() {
|
|
289
|
+
const stored = this.persistence === 'cookie' ? this.readCookie() : this.readLocalStorage();
|
|
290
|
+
return stored && this.isAvailable(stored) ? stored : null;
|
|
291
|
+
}
|
|
292
|
+
/** Best configured language for the request's `Accept-Language` (SSR) or `navigator.languages` (browser). */
|
|
293
|
+
preferredLanguage() {
|
|
294
|
+
const preferred = this.request
|
|
295
|
+
? parseAcceptLanguage(this.request.headers.get('accept-language'))
|
|
296
|
+
: typeof navigator !== 'undefined'
|
|
297
|
+
? [...(navigator.languages ?? [navigator.language])].filter(Boolean)
|
|
298
|
+
: [];
|
|
299
|
+
return negotiateLanguage(preferred, this.languageIds());
|
|
300
|
+
}
|
|
301
|
+
remember(lang) {
|
|
302
|
+
if (this.persistence === 'cookie')
|
|
303
|
+
this.writeCookie(lang);
|
|
304
|
+
else
|
|
305
|
+
this.writeLocalStorage(lang);
|
|
306
|
+
}
|
|
307
|
+
/** The request's `Cookie` header during SSR, `document.cookie` in the browser. */
|
|
308
|
+
readCookie() {
|
|
309
|
+
const header = this.request ? this.request.headers.get('cookie') : this.document.cookie;
|
|
310
|
+
for (const part of (header ?? '').split(';')) {
|
|
311
|
+
const [name, ...value] = part.trim().split('=');
|
|
312
|
+
if (name === STORAGE_KEY)
|
|
313
|
+
return decodeURIComponent(value.join('='));
|
|
314
|
+
}
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
writeCookie(lang) {
|
|
318
|
+
if (this.request)
|
|
319
|
+
return; // server: the browser keeps the cookie it sent
|
|
320
|
+
const secure = this.document.location?.protocol === 'https:' ? '; Secure' : '';
|
|
321
|
+
this.document.cookie = `${STORAGE_KEY}=${encodeURIComponent(lang)}; Path=/; Max-Age=${COOKIE_MAX_AGE}; SameSite=Lax${secure}`;
|
|
322
|
+
}
|
|
323
|
+
readLocalStorage() {
|
|
143
324
|
try {
|
|
144
|
-
|
|
145
|
-
return stored && this.isAvailable(stored) ? stored : this.defaultLanguage;
|
|
325
|
+
return typeof localStorage === 'undefined' ? null : localStorage.getItem(STORAGE_KEY);
|
|
146
326
|
}
|
|
147
327
|
catch (error) {
|
|
148
328
|
console.warn('Failed to read language from localStorage:', error);
|
|
149
|
-
return
|
|
329
|
+
return null;
|
|
150
330
|
}
|
|
151
331
|
}
|
|
152
|
-
|
|
153
|
-
const storage = this.storage();
|
|
154
|
-
if (!storage)
|
|
155
|
-
return;
|
|
332
|
+
writeLocalStorage(lang) {
|
|
156
333
|
try {
|
|
157
|
-
|
|
334
|
+
if (typeof localStorage !== 'undefined')
|
|
335
|
+
localStorage.setItem(STORAGE_KEY, lang);
|
|
158
336
|
}
|
|
159
337
|
catch (error) {
|
|
160
338
|
console.warn('Failed to save language to localStorage:', error);
|
|
161
339
|
}
|
|
162
340
|
}
|
|
163
|
-
/** `localStorage` when it exists (browser); `null` on the server. */
|
|
164
|
-
storage() {
|
|
165
|
-
return typeof localStorage === 'undefined' ? null : localStorage;
|
|
166
|
-
}
|
|
167
341
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: LanguageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
168
342
|
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: LanguageService, providedIn: 'root' });
|
|
169
343
|
}
|
|
170
344
|
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: LanguageService, decorators: [{
|
|
171
345
|
type: Injectable,
|
|
172
346
|
args: [{ providedIn: 'root' }]
|
|
173
|
-
}] });
|
|
347
|
+
}], ctorParameters: () => [] });
|
|
174
348
|
|
|
175
349
|
/**
|
|
176
350
|
* Missing-key handler that surfaces failures in dev mode.
|
|
@@ -180,12 +354,21 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImpo
|
|
|
180
354
|
* `[scope.key]` in dev so missing-key bugs jump out immediately. In production,
|
|
181
355
|
* behavior is always `''`.
|
|
182
356
|
*
|
|
357
|
+
* Providing a handler replaces Transloco's default one, which is where the
|
|
358
|
+
* `missingHandler.logMissingKey` console warning lives — so this handler warns
|
|
359
|
+
* too (once per key, outside prod mode).
|
|
360
|
+
*
|
|
183
361
|
* The build-time validator remains the source of truth for *static* keys; this
|
|
184
362
|
* handler catches dynamic / `selectTranslate(varKey)` / typo cases.
|
|
185
363
|
*/
|
|
186
364
|
class TranslocoVisibleMissingHandler {
|
|
187
365
|
config = inject(I18N_RUNTIME_CONFIG);
|
|
188
|
-
|
|
366
|
+
warned = new Set();
|
|
367
|
+
handle(key, data) {
|
|
368
|
+
if (data.missingHandler?.logMissingKey && !data.prodMode && !this.warned.has(key)) {
|
|
369
|
+
this.warned.add(key);
|
|
370
|
+
console.warn(`[@hakistack/i18n] Missing translation for '${key}' (${data.activeLang})`);
|
|
371
|
+
}
|
|
189
372
|
if (isDevMode() && this.config.missingKeyInDev === 'show') {
|
|
190
373
|
return `[${key}]`;
|
|
191
374
|
}
|
|
@@ -198,6 +381,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImpo
|
|
|
198
381
|
type: Injectable
|
|
199
382
|
}] });
|
|
200
383
|
|
|
384
|
+
/** Translator comments are for the JSON files only; the runtime store never needs them. */
|
|
385
|
+
const NO_COMMENTS = { comments: false };
|
|
201
386
|
/**
|
|
202
387
|
* Translation loader backed by the in-memory module registry.
|
|
203
388
|
*
|
|
@@ -221,7 +406,7 @@ class TranslocoRegistryLoader {
|
|
|
221
406
|
if (slashIdx === -1) {
|
|
222
407
|
// No scope provider in play — return the full tree (eager + every scoped
|
|
223
408
|
// module merged at its scope path).
|
|
224
|
-
return of(buildLanguageTree(this.config.registry, input, this.config.fallbackLang));
|
|
409
|
+
return of(buildLanguageTree(this.config.registry, input, this.config.fallbackLang, NO_COMMENTS));
|
|
225
410
|
}
|
|
226
411
|
// Scoped request — return ONLY that scope's data, unwrapped (Transloco
|
|
227
412
|
// namespaces it back under the scope key in its internal store). The scope
|
|
@@ -229,7 +414,7 @@ class TranslocoRegistryLoader {
|
|
|
229
414
|
// normalizes it against the registry's dotted scopes.
|
|
230
415
|
const scope = input.substring(0, slashIdx);
|
|
231
416
|
const lang = input.substring(slashIdx + 1);
|
|
232
|
-
const tree = buildScopedTree(this.config.registry, lang, this.config.fallbackLang, scope);
|
|
417
|
+
const tree = buildScopedTree(this.config.registry, lang, this.config.fallbackLang, scope, NO_COMMENTS);
|
|
233
418
|
return of((tree ?? {}));
|
|
234
419
|
}
|
|
235
420
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslocoRegistryLoader, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
@@ -245,7 +430,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImpo
|
|
|
245
430
|
* Collapses what used to be a hand-written `provideTransloco(...)` config plus
|
|
246
431
|
* a list of custom hooks (`provideTranslocoInterceptor`,
|
|
247
432
|
* `provideTranslocoMissingHandler`) into a single provider. Wires:
|
|
248
|
-
* - Transloco with the registry
|
|
433
|
+
* - Transloco with the registry, lazy (per-language chunks) or HTTP loader.
|
|
249
434
|
* - The comment-stripping interceptor + the visible missing-key handler.
|
|
250
435
|
* - `I18N_KEYS` (the runtime `TK` tree) for the translate directive.
|
|
251
436
|
* - `I18N_RUNTIME_CONFIG` (resolved defaults) for the loader/handler.
|
|
@@ -269,20 +454,40 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImpo
|
|
|
269
454
|
* }),
|
|
270
455
|
* ],
|
|
271
456
|
* };
|
|
457
|
+
*
|
|
458
|
+
* @example Lazy: one chunk per language, no translation in the initial bundle
|
|
459
|
+
* import { TK } from './i18n/definitions/keys.generated';
|
|
460
|
+
* import { TRANSLATIONS } from './i18n/definitions/translations.generated';
|
|
461
|
+
*
|
|
462
|
+
* provideI18n({ keys: TK, translations: TRANSLATIONS, languages: [...] })
|
|
272
463
|
*/
|
|
273
464
|
function provideI18n(config) {
|
|
274
465
|
const defaultLang = config.defaultLang ?? config.languages[0]?.id;
|
|
275
466
|
if (!defaultLang) {
|
|
276
467
|
throw new Error('provideI18n: `languages` must contain at least one entry (or set `defaultLang`).');
|
|
277
468
|
}
|
|
469
|
+
if (!config.keys && !config.registry) {
|
|
470
|
+
throw new Error('provideI18n: pass `keys` (the generated TK) or `registry` (ALL_TRANSLATIONS).');
|
|
471
|
+
}
|
|
472
|
+
const loader = config.loader ?? (config.translations ? 'lazy' : 'registry');
|
|
473
|
+
if (loader === 'registry' && !config.registry) {
|
|
474
|
+
throw new Error("provideI18n: the 'registry' loader needs `registry` (ALL_TRANSLATIONS). For lazy loading pass `translations` (TRANSLATIONS).");
|
|
475
|
+
}
|
|
476
|
+
if (loader === 'lazy' && !config.translations) {
|
|
477
|
+
throw new Error("provideI18n: the 'lazy' loader needs `translations` (the generated TRANSLATIONS).");
|
|
478
|
+
}
|
|
278
479
|
const resolved = {
|
|
279
|
-
registry: config.registry,
|
|
480
|
+
registry: config.registry ?? [],
|
|
481
|
+
translations: config.translations ?? null,
|
|
482
|
+
languages: config.languages,
|
|
483
|
+
persistence: config.persistLanguage === 'cookie' ? 'cookie' : 'local-storage',
|
|
484
|
+
detectLanguage: !!config.detectLanguage,
|
|
280
485
|
defaultLang,
|
|
281
486
|
fallbackLang: config.fallbackLang ?? 'en',
|
|
282
487
|
missingKeyInDev: config.missingKeyInDev ?? 'show',
|
|
283
488
|
assetsPath: (config.assetsPath ?? '/assets/i18n').replace(/\/$/, ''),
|
|
284
489
|
};
|
|
285
|
-
const loaderClass =
|
|
490
|
+
const loaderClass = { registry: TranslocoRegistryLoader, lazy: TranslocoLazyLoader, http: TranslocoHttpLoader }[loader];
|
|
286
491
|
const providers = [
|
|
287
492
|
provideTransloco({
|
|
288
493
|
config: {
|
|
@@ -292,7 +497,9 @@ function provideI18n(config) {
|
|
|
292
497
|
reRenderOnLangChange: true,
|
|
293
498
|
prodMode: !isDevMode(),
|
|
294
499
|
missingHandler: {
|
|
295
|
-
|
|
500
|
+
// Every generated tree (registry, lazy modules, JSON) already resolves each key to the
|
|
501
|
+
// fallback language, so Transloco must not load the fallback language as well.
|
|
502
|
+
useFallbackTranslation: false,
|
|
296
503
|
logMissingKey: isDevMode(),
|
|
297
504
|
},
|
|
298
505
|
},
|
|
@@ -301,9 +508,9 @@ function provideI18n(config) {
|
|
|
301
508
|
provideTranslocoInterceptor(TranslocoCommentInterceptor),
|
|
302
509
|
provideTranslocoMissingHandler(TranslocoVisibleMissingHandler),
|
|
303
510
|
{ provide: I18N_RUNTIME_CONFIG, useValue: resolved },
|
|
304
|
-
{ provide: I18N_KEYS, useValue: buildKeysTree(config.registry) },
|
|
511
|
+
{ provide: I18N_KEYS, useValue: config.keys ?? buildKeysTree(config.registry ?? []) },
|
|
305
512
|
];
|
|
306
|
-
if (config.persistLanguage) {
|
|
513
|
+
if (config.persistLanguage || config.detectLanguage) {
|
|
307
514
|
providers.push(provideAppInitializer(() => {
|
|
308
515
|
const languageService = inject(LanguageService);
|
|
309
516
|
return languageService.initializeLanguage();
|
|
@@ -343,10 +550,15 @@ function provideI18n(config) {
|
|
|
343
550
|
* }
|
|
344
551
|
* ```
|
|
345
552
|
*
|
|
346
|
-
* **
|
|
553
|
+
* **Loading:** the directive loads the active language itself (like
|
|
554
|
+
* Transloco's own `*transloco`), creates its view once that load settles, and
|
|
555
|
+
* re-renders after every language switch has loaded — no app initializer or
|
|
556
|
+
* other translation consumer is required.
|
|
557
|
+
*
|
|
558
|
+
* **Optimizations:**
|
|
347
559
|
* - JS Proxy for lazy property access (no upfront tree building).
|
|
348
560
|
* - Proxy objects cached via WeakMap; translate fns cached per key via Map.
|
|
349
|
-
* -
|
|
561
|
+
* - One `markForCheck` per language change; no work in between.
|
|
350
562
|
*/
|
|
351
563
|
class TranslateDirectiveBase {
|
|
352
564
|
transloco = inject(TranslocoService);
|
|
@@ -354,14 +566,9 @@ class TranslateDirectiveBase {
|
|
|
354
566
|
templateRef = inject((TemplateRef));
|
|
355
567
|
viewContainer = inject(ViewContainerRef);
|
|
356
568
|
viewRef = null;
|
|
357
|
-
/** Tracks the current language (auto-updates on language change). */
|
|
358
|
-
currentLang = toSignal(this.transloco.langChanges$, {
|
|
359
|
-
initialValue: this.transloco.getActiveLang(),
|
|
360
|
-
});
|
|
361
569
|
proxyCache = new WeakMap();
|
|
362
570
|
translateFnCache = new Map();
|
|
363
571
|
isDev = typeof ngDevMode !== 'undefined' && !!ngDevMode;
|
|
364
|
-
warnedKeys = this.isDev ? new Set() : null;
|
|
365
572
|
/**
|
|
366
573
|
* Optional prefix prepended to every key (for scoped translations).
|
|
367
574
|
*
|
|
@@ -377,8 +584,11 @@ class TranslateDirectiveBase {
|
|
|
377
584
|
return prefix ? `${prefix}.${key}` : key;
|
|
378
585
|
}
|
|
379
586
|
constructor() {
|
|
380
|
-
this.
|
|
381
|
-
|
|
587
|
+
this.transloco.langChanges$
|
|
588
|
+
.pipe(
|
|
589
|
+
// A failed load still renders: Transloco's fallback / missing handler take over.
|
|
590
|
+
switchMap((lang) => this.transloco.load(lang).pipe(map(() => lang), catchError(() => of(lang)))), takeUntilDestroyed())
|
|
591
|
+
.subscribe((lang) => this.render(lang));
|
|
382
592
|
}
|
|
383
593
|
createLazyTranslationProxy(keysObject) {
|
|
384
594
|
const createProxy = (obj) => {
|
|
@@ -393,14 +603,8 @@ class TranslateDirectiveBase {
|
|
|
393
603
|
const cachedFn = this.translateFnCache.get(fullKey);
|
|
394
604
|
if (cachedFn)
|
|
395
605
|
return cachedFn;
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
if (this.isDev && result === fullKey && !this.warnedKeys.has(fullKey)) {
|
|
399
|
-
console.warn(`[TranslateDirective] Missing translation: "${fullKey}"`);
|
|
400
|
-
this.warnedKeys.add(fullKey);
|
|
401
|
-
}
|
|
402
|
-
return result;
|
|
403
|
-
});
|
|
606
|
+
// Missing keys are reported by the missing handler (dev warning + `[key]`).
|
|
607
|
+
const translateFn = ((params) => this.transloco.translate(fullKey, params));
|
|
404
608
|
if (this.isDev) {
|
|
405
609
|
Object.defineProperty(translateFn, 'key', { value, writable: false, enumerable: false });
|
|
406
610
|
}
|
|
@@ -421,26 +625,19 @@ class TranslateDirectiveBase {
|
|
|
421
625
|
};
|
|
422
626
|
return createProxy(keysObject);
|
|
423
627
|
}
|
|
424
|
-
|
|
425
|
-
|
|
628
|
+
render(lang) {
|
|
629
|
+
if (this.viewRef) {
|
|
630
|
+
this.viewRef.context.lang = lang;
|
|
631
|
+
this.viewRef.markForCheck();
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
426
634
|
const context = {
|
|
427
|
-
$implicit:
|
|
428
|
-
lang
|
|
635
|
+
$implicit: this.createLazyTranslationProxy(this.keys),
|
|
636
|
+
lang,
|
|
429
637
|
translate: (key, params) => this.transloco.translate(this.withPrefix(key), params),
|
|
430
638
|
};
|
|
431
639
|
this.viewRef = this.viewContainer.createEmbeddedView(this.templateRef, context);
|
|
432
640
|
}
|
|
433
|
-
setupLangChangeEffect() {
|
|
434
|
-
effect(() => {
|
|
435
|
-
const newLang = this.currentLang();
|
|
436
|
-
untracked(() => {
|
|
437
|
-
if (this.viewRef) {
|
|
438
|
-
this.viewRef.context.lang = newLang;
|
|
439
|
-
this.viewRef.markForCheck();
|
|
440
|
-
}
|
|
441
|
-
});
|
|
442
|
-
});
|
|
443
|
-
}
|
|
444
641
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.10", ngImport: i0, type: TranslateDirectiveBase, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
445
642
|
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.10", type: TranslateDirectiveBase, isStandalone: true, ngImport: i0 });
|
|
446
643
|
}
|
|
@@ -448,6 +645,19 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImpo
|
|
|
448
645
|
type: Directive
|
|
449
646
|
}], ctorParameters: () => [] });
|
|
450
647
|
|
|
648
|
+
/**
|
|
649
|
+
* Transloco's `translateSignal`, with interpolation params checked against the
|
|
650
|
+
* key: for `TK.home.welcome` generated from `t('Welcome, {{username}}!')`,
|
|
651
|
+
* `translateSignal(TK.home.welcome)` is a compile error and
|
|
652
|
+
* `translateSignal(TK.home.welcome, { username })` is required. Plain keys,
|
|
653
|
+
* key arrays and key signals keep Transloco's signature. Runtime behavior is
|
|
654
|
+
* Transloco's (same arguments, same reactivity).
|
|
655
|
+
*/
|
|
656
|
+
function translateSignal(key, ...args) {
|
|
657
|
+
const [params, lang, injector] = args;
|
|
658
|
+
return translateSignal$1(key, params, lang, injector);
|
|
659
|
+
}
|
|
660
|
+
|
|
451
661
|
/*
|
|
452
662
|
* @hakistack/i18n
|
|
453
663
|
*
|
|
@@ -471,5 +681,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.10", ngImpo
|
|
|
471
681
|
* Generated bundle index. Do not edit.
|
|
472
682
|
*/
|
|
473
683
|
|
|
474
|
-
export { I18N_KEYS, I18N_RUNTIME_CONFIG, LanguageService, TranslateDirectiveBase, TranslocoCommentInterceptor, TranslocoHttpLoader, TranslocoRegistryLoader, TranslocoVisibleMissingHandler, provideI18n };
|
|
684
|
+
export { I18N_KEYS, I18N_RUNTIME_CONFIG, LanguageService, TranslateDirectiveBase, TranslocoCommentInterceptor, TranslocoHttpLoader, TranslocoLazyLoader, TranslocoRegistryLoader, TranslocoVisibleMissingHandler, negotiateLanguage, parseAcceptLanguage, provideI18n, textDirection, translateSignal };
|
|
475
685
|
//# sourceMappingURL=hakistack-i18n.mjs.map
|