@pie-qti/i18n 1.0.0-beta.4 → 1.0.0-beta.5
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 +54 -7
- package/dist/core/I18n.d.ts +13 -1
- package/dist/core/I18n.js +13 -28
- package/dist/core/I18n.js.map +1 -1
- package/dist/core/I18nProvider.d.ts +6 -2
- package/dist/core/I18nProvider.js.map +1 -1
- package/dist/core/accessible-text.d.ts +19 -2
- package/dist/core/accessible-text.js +32 -7
- package/dist/core/accessible-text.js.map +1 -1
- package/dist/locales/ar.d.ts +483 -148
- package/dist/locales/ar.js +492 -156
- package/dist/locales/ar.js.map +1 -1
- package/dist/locales/en.d.ts +407 -148
- package/dist/locales/en.js +420 -156
- package/dist/locales/en.js.map +1 -1
- package/dist/locales/es.d.ts +426 -148
- package/dist/locales/es.js +435 -156
- package/dist/locales/es.js.map +1 -1
- package/dist/locales/fr.d.ts +426 -148
- package/dist/locales/fr.js +435 -156
- package/dist/locales/fr.js.map +1 -1
- package/dist/locales/nl.d.ts +407 -148
- package/dist/locales/nl.js +416 -156
- package/dist/locales/nl.js.map +1 -1
- package/dist/locales/ro.d.ts +426 -148
- package/dist/locales/ro.js +435 -156
- package/dist/locales/ro.js.map +1 -1
- package/dist/locales/th.d.ts +407 -148
- package/dist/locales/th.js +416 -156
- package/dist/locales/th.js.map +1 -1
- package/dist/locales/zh-Hans.d.ts +407 -148
- package/dist/locales/zh-Hans.js +416 -156
- package/dist/locales/zh-Hans.js.map +1 -1
- package/dist/providers/SvelteI18nProvider.d.ts +10 -1
- package/dist/providers/SvelteI18nProvider.js.map +1 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -272,7 +272,7 @@ Custom translations have higher priority than framework translations, so you can
|
|
|
272
272
|
|
|
273
273
|
### Recommended Pattern (Svelte 5)
|
|
274
274
|
|
|
275
|
-
The recommended approach is simple: use `$derived` to create memoized translations
|
|
275
|
+
The recommended approach is simple: use `$derived` to create memoized translations, passing the English default as the second argument to `t()`.
|
|
276
276
|
|
|
277
277
|
```svelte
|
|
278
278
|
<script lang="ts">
|
|
@@ -286,8 +286,8 @@ let { i18n }: Props = $props();
|
|
|
286
286
|
|
|
287
287
|
// Memoized translations - evaluated once when component loads
|
|
288
288
|
const translations = $derived({
|
|
289
|
-
submit: i18n?.t('common.submit'
|
|
290
|
-
cancel: i18n?.t('common.cancel'
|
|
289
|
+
submit: i18n?.t('common.submit', 'Submit'),
|
|
290
|
+
cancel: i18n?.t('common.cancel', 'Cancel')
|
|
291
291
|
});
|
|
292
292
|
</script>
|
|
293
293
|
|
|
@@ -295,21 +295,38 @@ const translations = $derived({
|
|
|
295
295
|
<button class="btn btn-outline">{translations.cancel}</button>
|
|
296
296
|
```
|
|
297
297
|
|
|
298
|
+
The fallback contract: `t()` always returns a `string` — the translation, the
|
|
299
|
+
default passed as its second argument (interpolated like a translation), or, for
|
|
300
|
+
a key no catalog carries and no default was given, the key itself. It never
|
|
301
|
+
returns nullish, so `??` after `t()` is dead code. The only nullish value in the
|
|
302
|
+
pattern is `i18n` itself when a component was mounted without a provider, which
|
|
303
|
+
is what the optional chain covers:
|
|
304
|
+
|
|
305
|
+
```svelte
|
|
306
|
+
<!-- i18n undefined → renders 'Submit'; key missing from a catalog → same. -->
|
|
307
|
+
<button>{i18n?.t('common.submit', 'Submit') ?? 'Submit'}</button>
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
A key no catalog carries warns at runtime in every environment and is caught in
|
|
311
|
+
CI by `check:i18n`'s consumer key scan, so the "renders the key itself" case is
|
|
312
|
+
a build failure, not a UI bug that ships.
|
|
313
|
+
|
|
298
314
|
### Inline Pattern (For Simple Cases)
|
|
299
315
|
|
|
300
316
|
For one-off translations, you can call `t()` directly:
|
|
301
317
|
|
|
302
318
|
```svelte
|
|
303
|
-
<button>{i18n?.t('common.submit') ?? 'Submit'}</button>
|
|
319
|
+
<button>{i18n?.t('common.submit', 'Submit') ?? 'Submit'}</button>
|
|
304
320
|
```
|
|
305
321
|
|
|
306
322
|
### Helper Pattern (For Cleaner Code)
|
|
307
323
|
|
|
308
|
-
Create a translation helper for repeated use
|
|
324
|
+
Create a translation helper for repeated use. The trailing `??` fires only when
|
|
325
|
+
no provider was passed — never when a key is missing:
|
|
309
326
|
|
|
310
327
|
```svelte
|
|
311
328
|
<script lang="ts">
|
|
312
|
-
const t = $derived((key: string, fallback: string) => i18n?.t(key) ?? fallback);
|
|
329
|
+
const t = $derived((key: string, fallback: string) => i18n?.t(key, fallback) ?? fallback);
|
|
313
330
|
</script>
|
|
314
331
|
|
|
315
332
|
<button>{t('common.submit', 'Submit')}</button>
|
|
@@ -327,7 +344,7 @@ interface Props {
|
|
|
327
344
|
|
|
328
345
|
let { i18n = $bindable() }: Props = $props();
|
|
329
346
|
|
|
330
|
-
const t = $derived((key: string, fallback: string) => i18n?.t(key) ?? fallback);
|
|
347
|
+
const t = $derived((key: string, fallback: string) => i18n?.t(key, fallback) ?? fallback);
|
|
331
348
|
```
|
|
332
349
|
|
|
333
350
|
**Note:** No manual subscriptions needed. Components re-render when the host passes a new provider or view; hosts that change the locale in place opt into reload.
|
|
@@ -393,6 +410,7 @@ The checker:
|
|
|
393
410
|
- ✅ **Automatically detects** all locale files (no configuration)
|
|
394
411
|
- ✅ **Reports missing keys** in other locales
|
|
395
412
|
- ✅ **Detects obsolete keys** that should be removed
|
|
413
|
+
- ✅ **Compares placeholder names** — a locale must use the same `{name}` interpolation variables as en (plural leaves may omit them, for locales that spell small counts out as words)
|
|
396
414
|
- ✅ **Runs in CI/CD** to block PRs with incomplete translations
|
|
397
415
|
|
|
398
416
|
**Integrated into build:**
|
|
@@ -404,6 +422,35 @@ bun run build # Automatically checks translations first
|
|
|
404
422
|
See [`scripts/check-translations.ts`](./scripts/check-translations.ts) for the checker's behavior
|
|
405
423
|
and options.
|
|
406
424
|
|
|
425
|
+
### Consumer Key Scan
|
|
426
|
+
|
|
427
|
+
The hardcoded-string scanner and compile-time types cannot see every call shape,
|
|
428
|
+
and a key referenced by a component but carried by no catalog silently renders
|
|
429
|
+
its hardcoded English default in every other locale. `bun run check-consumer-keys`
|
|
430
|
+
walks consumer source (`packages/<pkg>/src`, `apps/<app>/src`) and asserts every
|
|
431
|
+
literal key passed to `t()`, `translate()`, `translatePlural()`,
|
|
432
|
+
`interfaceText()` or `.plural()`, or named in a `labelKey`, exists in the
|
|
433
|
+
framework en catalog or in a registered host custom-messages catalog. Dynamic
|
|
434
|
+
keys (template literals, variables) are covered at runtime by the providers'
|
|
435
|
+
missing-key warning, which fires in every environment.
|
|
436
|
+
|
|
437
|
+
A host app that keeps its own strings registers their catalog module — the same
|
|
438
|
+
module it passes to `createDefaultI18nProvider(locale, customMessages)` — in
|
|
439
|
+
`HOST_CUSTOM_CATALOGS` at the top of [`scripts/check-consumer-keys.ts`](./scripts/check-consumer-keys.ts);
|
|
440
|
+
the scan unions the keys of every registered catalog into the set it accepts.
|
|
441
|
+
A catalog that is not registered there fails the scan as unknown keys, and
|
|
442
|
+
catalogs living outside this repository are out of the scan's scope entirely
|
|
443
|
+
(its roots are `packages/*/src` and `apps/*/src`), so their keys cannot be
|
|
444
|
+
checked here.
|
|
445
|
+
|
|
446
|
+
```bash
|
|
447
|
+
# Scan every package and app (part of `check:i18n`; exits 1 on an unknown key)
|
|
448
|
+
bun run check-consumer-keys
|
|
449
|
+
|
|
450
|
+
# Scan a custom path
|
|
451
|
+
bun run check-consumer-keys --path=../custom-components/src
|
|
452
|
+
```
|
|
453
|
+
|
|
407
454
|
### Hardcoded String Scanner
|
|
408
455
|
|
|
409
456
|
The scanner parses Svelte templates with the Svelte compiler and reports learner-visible strings that bypass the catalog: template text, and `aria-label`, `title` and `placeholder` values on DOM elements that are static text or a template literal. Script literals, component props and test directories are out of scope. A finding names the catalog key when en already carries the string.
|
package/dist/core/I18n.d.ts
CHANGED
|
@@ -55,10 +55,22 @@ export declare class DefaultI18nProvider implements I18nProvider {
|
|
|
55
55
|
getLocale(): string;
|
|
56
56
|
/**
|
|
57
57
|
* Translate message key with optional default and/or interpolation
|
|
58
|
+
*
|
|
59
|
+
* Overloads: the first overload enumerates the framework catalog keys
|
|
60
|
+
* (`MessageKey`), so editors complete keys and a typo stands out against the
|
|
61
|
+
* union. The second overload is the documented escape hatch for keys that
|
|
62
|
+
* live in a host's `customMessages` catalog rather than a framework catalog —
|
|
63
|
+
* the key namespace at runtime is framework keys plus custom keys, and a
|
|
64
|
+
* plain-string overload cannot reject a misspelled framework key that also
|
|
65
|
+
* matches it, so compile-time typo catching for literal keys is enforced by
|
|
66
|
+
* the `check-consumer-keys` scan in `check:i18n` instead, and at runtime by
|
|
67
|
+
* the unconditional missing-key warning below.
|
|
68
|
+
*
|
|
58
69
|
* @example t('upload.label') => "Upload a file"
|
|
59
70
|
* @example t('upload.label', 'Upload') => translated or "Upload" if missing
|
|
60
|
-
* @example t('upload.
|
|
71
|
+
* @example t('upload.fileSize', { size: 42 }) => "42 bytes"
|
|
61
72
|
*/
|
|
73
|
+
t(key: MessageKey, defaultOrValues?: Record<string, any> | string, values?: Record<string, any>): string;
|
|
62
74
|
t(key: string, defaultOrValues?: Record<string, any> | string, values?: Record<string, any>): string;
|
|
63
75
|
/**
|
|
64
76
|
* Pluralization support
|
package/dist/core/I18n.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* It uses standard dynamic imports for lazy locale loading and provides simple
|
|
6
6
|
* interpolation and pluralization support.
|
|
7
7
|
*/
|
|
8
|
+
import { interpolate } from './accessible-text.js';
|
|
8
9
|
import { languageDirection } from './direction.js';
|
|
9
10
|
import { normalizeLanguageTag } from './language-tags.js';
|
|
10
11
|
import { formattingLocale } from './numbering.js';
|
|
@@ -56,15 +57,6 @@ function intlLocale(tag) {
|
|
|
56
57
|
return FALLBACK_LOCALE;
|
|
57
58
|
}
|
|
58
59
|
}
|
|
59
|
-
/**
|
|
60
|
-
* Whether to log missing-translation warnings.
|
|
61
|
-
*
|
|
62
|
-
* `process` does not exist in a plain browser, so the read is guarded rather
|
|
63
|
-
* than bare: an unguarded `process.env.NODE_ENV` throws a ReferenceError on the
|
|
64
|
-
* missing-key path for any consumer that is not running the code through a
|
|
65
|
-
* bundler that substitutes it.
|
|
66
|
-
*/
|
|
67
|
-
const isDevelopment = typeof process !== 'undefined' && process.env?.NODE_ENV === 'development';
|
|
68
60
|
export class DefaultI18nProvider {
|
|
69
61
|
/** Shared across instances: constructing Intl.PluralRules is not cheap */
|
|
70
62
|
static pluralRules = new Map();
|
|
@@ -152,12 +144,6 @@ export class DefaultI18nProvider {
|
|
|
152
144
|
getLocale() {
|
|
153
145
|
return this.currentLocale;
|
|
154
146
|
}
|
|
155
|
-
/**
|
|
156
|
-
* Translate message key with optional default and/or interpolation
|
|
157
|
-
* @example t('upload.label') => "Upload a file"
|
|
158
|
-
* @example t('upload.label', 'Upload') => translated or "Upload" if missing
|
|
159
|
-
* @example t('upload.selected', { name: 'file.pdf' }) => "Selected: file.pdf"
|
|
160
|
-
*/
|
|
161
147
|
t(key, defaultOrValues, values) {
|
|
162
148
|
const message = this.getMessage(key);
|
|
163
149
|
const interpolationValues = typeof defaultOrValues === 'object' && defaultOrValues !== null
|
|
@@ -165,20 +151,19 @@ export class DefaultI18nProvider {
|
|
|
165
151
|
: values;
|
|
166
152
|
const defaultStr = typeof defaultOrValues === 'string' ? defaultOrValues : undefined;
|
|
167
153
|
if (!message) {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
154
|
+
// Unconditional, in every environment: a key no catalog carries silently
|
|
155
|
+
// degrades the UI to its English default or to the key itself, and a
|
|
156
|
+
// warning gated on NODE_ENV never fires in production builds — which is
|
|
157
|
+
// exactly where a regression ships. The runtime typo guard is paired
|
|
158
|
+
// with the `check-consumer-keys` scan at CI time.
|
|
159
|
+
console.warn(`[i18n] Missing translation: ${key} (locale: ${this.currentLocale})`);
|
|
172
160
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
return this.formatNumber(value);
|
|
180
|
-
return String(value ?? match);
|
|
181
|
-
});
|
|
161
|
+
// A default is message text, not a marker: it interpolates like a translation,
|
|
162
|
+
// so a key no catalog carries degrades to English instead of literal "{count}".
|
|
163
|
+
const text = message || defaultStr;
|
|
164
|
+
if (text === undefined)
|
|
165
|
+
return key;
|
|
166
|
+
return interpolate(text, interpolationValues, (value) => this.formatNumber(value));
|
|
182
167
|
}
|
|
183
168
|
/**
|
|
184
169
|
* Pluralization support
|
package/dist/core/I18n.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"I18n.js","sourceRoot":"","sources":["../../src/core/I18n.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EACN,kBAAkB,EAElB,oBAAoB,EACpB,sBAAsB,EACtB,UAAU,GACV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAElC;;;;;;;;;;;;;;GAcG;AACH,MAAM,aAAa,GAA6E;IAC/F,EAAE,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IAC1C,EAAE,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,kBAAkB,CAAC;IACpC,EAAE,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,kBAAkB,CAAC;IACpC,EAAE,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,kBAAkB,CAAC;IACpC,EAAE,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,kBAAkB,CAAC;IACpC,EAAE,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,kBAAk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C,GAAG,CAAC,CAAC;YAC3B,CAAC;QACF,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;;AAGF;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CACxC,SAAqB,OAAO,EAC5B,cAA+C;IAE/C,OAAO,IAAI,mBAAmB,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;AACxD,CAAC","sourcesContent":["/**\n * Default I18n provider implementation\n *\n * This is the framework's default implementation of the I18nProvider interface.\n * It uses standard dynamic imports for lazy locale loading and provides simple\n * interpolation and pluralization support.\n */\n\nimport type { I18nProvider, InterpolationValues, PluralOptions } from './I18nProvider.js';\nimport type { LocaleCode, MessageKey, LocaleMessages } from './types.js';\nimport { languageDirection } from './direction.js';\nimport { normalizeLanguageTag } from './language-tags.js';\nimport { formattingLocale } from './numbering.js';\nimport {\n\tFRAMEWORK_CATALOGS,\n\ttype FrameworkCatalogCode,\n\tlocaleLookupSequence,\n\tresolveFrameworkLocale,\n\tstepServes,\n} from './negotiation.js';\nimport en from '../locales/en.js';\n\n/**\n * Lazy loaders for the framework catalogs, keyed by language.\n *\n * An explicit static map rather than a bundler macro: `tsc` emits these\n * `import()` calls verbatim, so the published package evaluates anywhere ESM\n * does — webpack, esbuild, Rollup, Node, or a browser loading the files\n * directly. Every bundler still sees the specifiers statically, so each locale\n * remains its own chunk and a host that only renders English never fetches the\n * others. Adding a locale means adding a line here alongside the file and its\n * key in `FRAMEWORK_CATALOGS`.\n *\n * `en` is a plain static import because it is the fallback for every missing\n * key in every other locale, so it must be resolvable synchronously in the\n * constructor.\n */\nconst localeLoaders: Record<FrameworkCatalogCode, () => Promise<{ default: LocaleMessages }>> = {\n\ten: () => Promise.resolve({ default: en }),\n\tar: () => import('../locales/ar.js'),\n\tes: () => import('../locales/es.js'),\n\tfr: () => import('../locales/fr.js'),\n\tnl: () => import('../locales/nl.js'),\n\tro: () => import('../locales/ro.js'),\n\tth: () => import('../locales/th.js'),\n\t'zh-Hans': () => import('../locales/zh-Hans.js'),\n};\n\n/** Catalog keys by their normalized form, which is what a lookup step is. */\nconst catalogsByStep = new Map<string, FrameworkCatalogCode>(\n\tFRAMEWORK_CATALOGS.map((code) => [normalizeLanguageTag(code), code])\n);\n\n/**\n * The locale every lookup falls back to. Walked like any other tag, so custom\n * messages keyed `en-US` and the framework `en` catalog both serve it.\n */\nconst FALLBACK_LOCALE = 'en-US';\n\n/**\n * A tag `Intl` accepts for the active locale: POSIX separators and suffixes\n * are rewritten (`ar_SA` → `ar-SA`), and a tag `Intl` still rejects formats as\n * English rather than throwing.\n */\nfunction intlLocale(tag: string): string {\n\tconst candidate = tag.trim().replace(/_/g, '-').split(/[.@]/)[0];\n\ttry {\n\t\treturn Intl.getCanonicalLocales(candidate)[0] ?? FALLBACK_LOCALE;\n\t} catch {\n\t\treturn FALLBACK_LOCALE;\n\t}\n}\n\n/**\n * Whether to log missing-translation warnings.\n *\n * `process` does not exist in a plain browser, so the read is guarded rather\n * than bare: an unguarded `process.env.NODE_ENV` throws a ReferenceError on the\n * missing-key path for any consumer that is not running the code through a\n * bundler that substitutes it.\n */\nconst isDevelopment: boolean =\n\ttypeof process !== 'undefined' && process.env?.NODE_ENV === 'development';\n\nexport class DefaultI18nProvider implements I18nProvider {\n\t/** Shared across instances: constructing Intl.PluralRules is not cheap */\n\tprivate static pluralRules: Map<string, Intl.PluralRules> = new Map();\n\n\tprivate currentLocale: LocaleCode;\n\tprivate messages: Partial<Record<FrameworkCatalogCode, LocaleMessages>>;\n\tprivate customMessages: Record<string, LocaleMessages>; // Client-provided translations\n\tprivate loadedLocales: Set<FrameworkCatalogCode> = new Set();\n\tprivate pendingLoads: Map<FrameworkCatalogCode, Promise<void>> = new Map();\n\n\t/**\n\t * Settles once the catalog for this provider's locale is loaded. Set only on\n\t * a `withLocale()` view created before that catalog was resident; the view\n\t * starts the load itself. Never rejects: a failed load is logged and the view\n\t * keeps rendering through the English fallback.\n\t */\n\tready?: Promise<void>;\n\n\t/**\n\t * @param locale - Active locale; any BCP 47 or POSIX tag. The host owns this\n\t * value: the provider reads no storage and persists nothing.\n\t * @param customMessages - Host translations by locale tag, consulted before\n\t * the framework catalogs.\n\t */\n\tconstructor(locale: LocaleCode = 'en-US', customMessages?: Record<string, LocaleMessages>) {\n\t\tthis.currentLocale = locale;\n\t\tthis.messages = {};\n\t\tthis.customMessages = customMessages || {};\n\n\t\t// en is the fallback for every other locale, so it is always present\n\t\tthis.messages.en = en;\n\t\tthis.loadedLocales.add('en');\n\t}\n\n\t/**\n\t * Load the framework catalog that serves a locale tag.\n\t *\n\t * The tag is negotiated (`es-MX` loads `es`, `zh-CN` loads `zh-Hans`). A tag\n\t * no framework catalog serves resolves without loading anything: it renders\n\t * from custom messages and the English fallback. Rejects only when a catalog\n\t * module fails to load.\n\t */\n\tasync loadLocale(locale: LocaleCode): Promise<void> {\n\t\tconst code = resolveFrameworkLocale(locale);\n\t\tif (!code || this.loadedLocales.has(code)) return;\n\n\t\tlet pending = this.pendingLoads.get(code);\n\t\tif (!pending) {\n\t\t\tpending = localeLoaders[code]()\n\t\t\t\t.then((module) => {\n\t\t\t\t\tthis.messages[code] = module.default;\n\t\t\t\t\tthis.loadedLocales.add(code);\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.pendingLoads.delete(code);\n\t\t\t\t});\n\t\t\tthis.pendingLoads.set(code, pending);\n\t\t}\n\n\t\ttry {\n\t\t\tawait pending;\n\t\t} catch (error) {\n\t\t\tconsole.error(`[i18n] Failed to load locale '${locale}':`, error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Whether every catalog a locale needs is resident: true for a tag no\n\t * framework catalog serves, since there is nothing to load.\n\t */\n\tisLocaleLoaded(locale: LocaleCode): boolean {\n\t\tconst code = resolveFrameworkLocale(locale);\n\t\treturn !code || this.loadedLocales.has(code);\n\t}\n\n\t/**\n\t * Set current locale\n\t * For framework locales, loadLocale() should be called first.\n\t * For custom locales, translations should be provided via customMessages.\n\t */\n\tsetLocale(locale: string): void {\n\t\tconst hasCustom = Object.keys(this.customMessages).some((tag) => localeLookupSequence(locale).includes(normalizeLanguageTag(tag)));\n\t\tif (!this.isLocaleLoaded(locale) && !hasCustom) {\n\t\t\tconsole.warn(`[i18n] Locale '${locale}' not loaded and no custom messages provided. Using fallback locale.`);\n\t\t}\n\t\tthis.currentLocale = locale as LocaleCode;\n\t}\n\n\t/**\n\t * Get current locale\n\t */\n\tgetLocale(): string {\n\t\treturn this.currentLocale;\n\t}\n\n\t/**\n\t * Translate message key with optional default and/or interpolation\n\t * @example t('upload.label') => \"Upload a file\"\n\t * @example t('upload.label', 'Upload') => translated or \"Upload\" if missing\n\t * @example t('upload.selected', { name: 'file.pdf' }) => \"Selected: file.pdf\"\n\t */\n\tt(key: string, defaultOrValues?: Record<string, any> | string, values?: Record<string, any>): string {\n\t\tconst message = this.getMessage(key);\n\t\tconst interpolationValues = typeof defaultOrValues === 'object' && defaultOrValues !== null\n\t\t\t? defaultOrValues\n\t\t\t: values;\n\t\tconst defaultStr = typeof defaultOrValues === 'string' ? defaultOrValues : undefined;\n\n\t\tif (!message) {\n\t\t\tif (isDevelopment) {\n\t\t\t\tconsole.warn(`[i18n] Missing translation: ${key} (locale: ${this.currentLocale})`);\n\t\t\t}\n\t\t\treturn defaultStr ?? key;\n\t\t}\n\n\t\tif (!interpolationValues) return message;\n\n\t\t// Replace {key} with values[key]; numbers take the locale's digits\n\t\treturn message.replace(/\\{(\\w+)\\}/g, (match, k) => {\n\t\t\tconst value = interpolationValues[k];\n\t\t\tif (typeof value === 'number') return this.formatNumber(value);\n\t\t\treturn String(value ?? match);\n\t\t});\n\t}\n\n\t/**\n\t * Pluralization support\n\t *\n\t * The plural category comes from `Intl.PluralRules` for the active locale, so\n\t * locales with more than two forms resolve correctly: Arabic selects between\n\t * zero/one/two/few/many/other, Romanian between one/few/other. A locale whose\n\t * catalog does not carry the selected category falls back to `.other`.\n\t *\n\t * @example plural('plurals.files', { count: 1 }) => \"1 file selected\"\n\t * @example plural('plurals.files', { count: 5 }) => \"5 files selected\"\n\t */\n\tplural(key: string, options: PluralOptions): string {\n\t\tconst { count } = options;\n\t\tconst category = this.selectPluralCategory(count);\n\t\tconst categoryKey = `${key}.${category}`;\n\t\tconst pluralKey = this.getMessage(categoryKey) !== undefined ? categoryKey : `${key}.other`;\n\t\treturn this.t(pluralKey, options);\n\t}\n\n\t/**\n\t * Select the CLDR plural category for a count in the active locale\n\t *\n\t * Falls back to the English one/other split if the locale tag is not one\n\t * `Intl.PluralRules` accepts — a host may set an arbitrary custom locale code.\n\t */\n\tprivate selectPluralCategory(count: number): Intl.LDMLPluralRule {\n\t\tlet rules = DefaultI18nProvider.pluralRules.get(this.currentLocale);\n\n\t\tif (!rules) {\n\t\t\trules = new Intl.PluralRules(intlLocale(this.currentLocale));\n\t\t\tDefaultI18nProvider.pluralRules.set(this.currentLocale, rules);\n\t\t}\n\n\t\treturn rules.select(count);\n\t}\n\n\t/**\n\t * Writing direction of the current locale\n\t *\n\t * @example getDirection() => 'rtl' for ar-SA, 'ltr' for en-US\n\t */\n\tgetDirection(): 'ltr' | 'rtl' {\n\t\treturn languageDirection(this.currentLocale);\n\t}\n\n\t/**\n\t * A view of this provider fixed to another locale\n\t *\n\t * Catalogs, loaded-locale bookkeeping and custom messages are shared by\n\t * reference, so `loadLocale()` through either side is visible to both and no\n\t * catalog is parsed twice. This is what lets two players on one page render\n\t * different locales from one provider: the locale is per-view, the catalogs\n\t * are per-provider.\n\t *\n\t * When the catalog its locale negotiates to is not resident, the view loads\n\t * it and `ready` settles when that load does; until then it renders through\n\t * the English fallback. A view over a resident catalog has no `ready`.\n\t */\n\twithLocale(locale: LocaleCode): DefaultI18nProvider {\n\t\tif (locale === this.currentLocale && this.isLocaleLoaded(locale)) return this;\n\n\t\tconst view = new DefaultI18nProvider(locale, this.customMessages);\n\t\tview.messages = this.messages;\n\t\tview.loadedLocales = this.loadedLocales;\n\t\tview.pendingLoads = this.pendingLoads;\n\t\tif (!view.isLocaleLoaded(locale)) {\n\t\t\t// loadLocale() has already logged a failure; the view falls back to English.\n\t\t\tview.ready = view.loadLocale(locale).catch(() => {});\n\t\t}\n\t\treturn view;\n\t}\n\n\t/**\n\t * Format a number in the locale's pinned numbering system\n\t *\n\t * @example formatNumber(1234.5) => \"1,234.5\" for ar, \"١٬٢٣٤٫٥\" for ar-EG\n\t */\n\tformatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n\t\treturn new Intl.NumberFormat(formattingLocale(this.currentLocale), options).format(value);\n\t}\n\n\t/**\n\t * Format a date in the locale's pinned numbering system, on the Gregorian\n\t * calendar unless the locale carries `-u-ca-`\n\t */\n\tformatDate(date: Date, options?: Intl.DateTimeFormatOptions): string {\n\t\treturn new Intl.DateTimeFormat(formattingLocale(this.currentLocale), options).format(date);\n\t}\n\n\t/**\n\t * Get nested message by dot notation key\n\t *\n\t * Walks the active locale's negotiation sequence, then the English fallback's.\n\t * At each step custom messages come before the framework catalog, so for\n\t * `es-MX` the order is custom `es-MX`, custom `es`, framework `es`, custom\n\t * `en-US`, custom `en`, framework `en`.\n\t */\n\tprivate getMessage(key: string): string | undefined {\n\t\treturn this.lookupMessage(key, this.currentLocale) ?? this.lookupMessage(key, FALLBACK_LOCALE);\n\t}\n\n\tprivate lookupMessage(key: string, locale: string): string | undefined {\n\t\tconst customTags = Object.keys(this.customMessages);\n\n\t\tfor (const step of localeLookupSequence(locale)) {\n\t\t\tfor (const tag of customTags) {\n\t\t\t\tif (normalizeLanguageTag(tag) !== step || !stepServes(locale, step, tag)) continue;\n\t\t\t\tconst custom = this.getMessageFromObject(key, this.customMessages[tag]);\n\t\t\t\tif (custom !== undefined) return custom;\n\t\t\t}\n\n\t\t\tconst code = catalogsByStep.get(step);\n\t\t\tif (code && stepServes(locale, step, code)) {\n\t\t\t\tconst message = this.getMessageFromObject(key, this.messages[code]);\n\t\t\t\tif (message !== undefined) return message;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Get message from a specific messages object\n\t *\n\t * Resolves to a string or nothing. A key that lands on a namespace branch\n\t * (`t('common')`) or on a plural sub-object (`t('plurals.items')`) is a miss,\n\t * not a hit: returning the branch would put an object where the caller\n\t * expects a string, and interpolating one throws.\n\t */\n\tprivate getMessageFromObject(key: string, messages: any): string | undefined {\n\t\tif (!messages) return undefined;\n\n\t\tconst parts = key.split('.');\n\t\tlet current: any = messages;\n\n\t\tfor (const part of parts) {\n\t\t\tif (current === null || typeof current !== 'object') return undefined;\n\t\t\tcurrent = current[part];\n\t\t\tif (current === undefined) return undefined;\n\t\t}\n\n\t\treturn typeof current === 'string' ? current : undefined;\n\t}\n\n\n\t/**\n\t * Add or update custom messages for a locale\n\t * This allows clients to provide their own translations or override defaults\n\t */\n\taddCustomMessages(locale: string, messages: LocaleMessages): void {\n\t\tthis.customMessages[locale] = this.deepMerge(\n\t\t\tthis.customMessages[locale] || {},\n\t\t\tmessages\n\t\t);\n\t}\n\n\t/**\n\t * Deep merge two objects (for merging translation objects)\n\t */\n\tprivate deepMerge(target: any, source: any): any {\n\t\tconst result = { ...target };\n\t\tfor (const key in source) {\n\t\t\tif (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {\n\t\t\t\tresult[key] = this.deepMerge(result[key] || {}, source[key]);\n\t\t\t} else {\n\t\t\t\tresult[key] = source[key];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Factory function to create a default i18n provider instance\n * @param locale - Initial locale code (default: 'en-US')\n * @param customMessages - Optional custom translations to add or override framework defaults\n * @returns DefaultI18nProvider instance\n */\nexport function createDefaultI18nProvider(\n\tlocale: LocaleCode = 'en-US',\n\tcustomMessages?: Record<string, LocaleMessages>\n): I18nProvider {\n\treturn new DefaultI18nProvider(locale, customMessages);\n}\n\nexport type { LocaleCode, MessageKey, InterpolationValues, PluralOptions };\n"]}
|
|
1
|
+
{"version":3,"file":"I18n.js","sourceRoot":"","sources":["../../src/core/I18n.ts"],"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E,EACjC,QAAQ,CACR,CAAC;IACH,CAAC;IAED;;OAEG;IACK,SAAS,CAAC,MAAW,EAAE,MAAW;QACzC,MAAM,MAAM,GAAG,EAAE,GAAG,MAAM,EAAE,CAAC;QAC7B,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;YAC1B,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;gBACnF,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;YAC9D,CAAC;iBAAM,CAAC;gBACP,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;YAC3B,CAAC;QACF,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;;AAGF;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CACxC,SAAqB,OAAO,EAC5B,cAA+C;IAE/C,OAAO,IAAI,mBAAmB,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;AACxD,CAAC","sourcesContent":["/**\n * Default I18n provider implementation\n *\n * This is the framework's default implementation of the I18nProvider interface.\n * It uses standard dynamic imports for lazy locale loading and provides simple\n * interpolation and pluralization support.\n */\n\nimport type { I18nProvider, InterpolationValues, PluralOptions } from './I18nProvider.js';\nimport type { LocaleCode, MessageKey, LocaleMessages } from './types.js';\nimport { interpolate } from './accessible-text.js';\nimport { languageDirection } from './direction.js';\nimport { normalizeLanguageTag } from './language-tags.js';\nimport { formattingLocale } from './numbering.js';\nimport {\n\tFRAMEWORK_CATALOGS,\n\ttype FrameworkCatalogCode,\n\tlocaleLookupSequence,\n\tresolveFrameworkLocale,\n\tstepServes,\n} from './negotiation.js';\nimport en from '../locales/en.js';\n\n/**\n * Lazy loaders for the framework catalogs, keyed by language.\n *\n * An explicit static map rather than a bundler macro: `tsc` emits these\n * `import()` calls verbatim, so the published package evaluates anywhere ESM\n * does — webpack, esbuild, Rollup, Node, or a browser loading the files\n * directly. Every bundler still sees the specifiers statically, so each locale\n * remains its own chunk and a host that only renders English never fetches the\n * others. Adding a locale means adding a line here alongside the file and its\n * key in `FRAMEWORK_CATALOGS`.\n *\n * `en` is a plain static import because it is the fallback for every missing\n * key in every other locale, so it must be resolvable synchronously in the\n * constructor.\n */\nconst localeLoaders: Record<FrameworkCatalogCode, () => Promise<{ default: LocaleMessages }>> = {\n\ten: () => Promise.resolve({ default: en }),\n\tar: () => import('../locales/ar.js'),\n\tes: () => import('../locales/es.js'),\n\tfr: () => import('../locales/fr.js'),\n\tnl: () => import('../locales/nl.js'),\n\tro: () => import('../locales/ro.js'),\n\tth: () => import('../locales/th.js'),\n\t'zh-Hans': () => import('../locales/zh-Hans.js'),\n};\n\n/** Catalog keys by their normalized form, which is what a lookup step is. */\nconst catalogsByStep = new Map<string, FrameworkCatalogCode>(\n\tFRAMEWORK_CATALOGS.map((code) => [normalizeLanguageTag(code), code])\n);\n\n/**\n * The locale every lookup falls back to. Walked like any other tag, so custom\n * messages keyed `en-US` and the framework `en` catalog both serve it.\n */\nconst FALLBACK_LOCALE = 'en-US';\n\n/**\n * A tag `Intl` accepts for the active locale: POSIX separators and suffixes\n * are rewritten (`ar_SA` → `ar-SA`), and a tag `Intl` still rejects formats as\n * English rather than throwing.\n */\nfunction intlLocale(tag: string): string {\n\tconst candidate = tag.trim().replace(/_/g, '-').split(/[.@]/)[0];\n\ttry {\n\t\treturn Intl.getCanonicalLocales(candidate)[0] ?? FALLBACK_LOCALE;\n\t} catch {\n\t\treturn FALLBACK_LOCALE;\n\t}\n}\n\nexport class DefaultI18nProvider implements I18nProvider {\n\t/** Shared across instances: constructing Intl.PluralRules is not cheap */\n\tprivate static pluralRules: Map<string, Intl.PluralRules> = new Map();\n\n\tprivate currentLocale: LocaleCode;\n\tprivate messages: Partial<Record<FrameworkCatalogCode, LocaleMessages>>;\n\tprivate customMessages: Record<string, LocaleMessages>; // Client-provided translations\n\tprivate loadedLocales: Set<FrameworkCatalogCode> = new Set();\n\tprivate pendingLoads: Map<FrameworkCatalogCode, Promise<void>> = new Map();\n\n\t/**\n\t * Settles once the catalog for this provider's locale is loaded. Set only on\n\t * a `withLocale()` view created before that catalog was resident; the view\n\t * starts the load itself. Never rejects: a failed load is logged and the view\n\t * keeps rendering through the English fallback.\n\t */\n\tready?: Promise<void>;\n\n\t/**\n\t * @param locale - Active locale; any BCP 47 or POSIX tag. The host owns this\n\t * value: the provider reads no storage and persists nothing.\n\t * @param customMessages - Host translations by locale tag, consulted before\n\t * the framework catalogs.\n\t */\n\tconstructor(locale: LocaleCode = 'en-US', customMessages?: Record<string, LocaleMessages>) {\n\t\tthis.currentLocale = locale;\n\t\tthis.messages = {};\n\t\tthis.customMessages = customMessages || {};\n\n\t\t// en is the fallback for every other locale, so it is always present\n\t\tthis.messages.en = en;\n\t\tthis.loadedLocales.add('en');\n\t}\n\n\t/**\n\t * Load the framework catalog that serves a locale tag.\n\t *\n\t * The tag is negotiated (`es-MX` loads `es`, `zh-CN` loads `zh-Hans`). A tag\n\t * no framework catalog serves resolves without loading anything: it renders\n\t * from custom messages and the English fallback. Rejects only when a catalog\n\t * module fails to load.\n\t */\n\tasync loadLocale(locale: LocaleCode): Promise<void> {\n\t\tconst code = resolveFrameworkLocale(locale);\n\t\tif (!code || this.loadedLocales.has(code)) return;\n\n\t\tlet pending = this.pendingLoads.get(code);\n\t\tif (!pending) {\n\t\t\tpending = localeLoaders[code]()\n\t\t\t\t.then((module) => {\n\t\t\t\t\tthis.messages[code] = module.default;\n\t\t\t\t\tthis.loadedLocales.add(code);\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.pendingLoads.delete(code);\n\t\t\t\t});\n\t\t\tthis.pendingLoads.set(code, pending);\n\t\t}\n\n\t\ttry {\n\t\t\tawait pending;\n\t\t} catch (error) {\n\t\t\tconsole.error(`[i18n] Failed to load locale '${locale}':`, error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Whether every catalog a locale needs is resident: true for a tag no\n\t * framework catalog serves, since there is nothing to load.\n\t */\n\tisLocaleLoaded(locale: LocaleCode): boolean {\n\t\tconst code = resolveFrameworkLocale(locale);\n\t\treturn !code || this.loadedLocales.has(code);\n\t}\n\n\t/**\n\t * Set current locale\n\t * For framework locales, loadLocale() should be called first.\n\t * For custom locales, translations should be provided via customMessages.\n\t */\n\tsetLocale(locale: string): void {\n\t\tconst hasCustom = Object.keys(this.customMessages).some((tag) => localeLookupSequence(locale).includes(normalizeLanguageTag(tag)));\n\t\tif (!this.isLocaleLoaded(locale) && !hasCustom) {\n\t\t\tconsole.warn(`[i18n] Locale '${locale}' not loaded and no custom messages provided. Using fallback locale.`);\n\t\t}\n\t\tthis.currentLocale = locale as LocaleCode;\n\t}\n\n\t/**\n\t * Get current locale\n\t */\n\tgetLocale(): string {\n\t\treturn this.currentLocale;\n\t}\n\n\t/**\n\t * Translate message key with optional default and/or interpolation\n\t *\n\t * Overloads: the first overload enumerates the framework catalog keys\n\t * (`MessageKey`), so editors complete keys and a typo stands out against the\n\t * union. The second overload is the documented escape hatch for keys that\n\t * live in a host's `customMessages` catalog rather than a framework catalog —\n\t * the key namespace at runtime is framework keys plus custom keys, and a\n\t * plain-string overload cannot reject a misspelled framework key that also\n\t * matches it, so compile-time typo catching for literal keys is enforced by\n\t * the `check-consumer-keys` scan in `check:i18n` instead, and at runtime by\n\t * the unconditional missing-key warning below.\n\t *\n\t * @example t('upload.label') => \"Upload a file\"\n\t * @example t('upload.label', 'Upload') => translated or \"Upload\" if missing\n\t * @example t('upload.fileSize', { size: 42 }) => \"42 bytes\"\n\t */\n\tt(key: MessageKey, defaultOrValues?: Record<string, any> | string, values?: Record<string, any>): string;\n\tt(key: string, defaultOrValues?: Record<string, any> | string, values?: Record<string, any>): string;\n\tt(key: string, defaultOrValues?: Record<string, any> | string, values?: Record<string, any>): string {\n\t\tconst message = this.getMessage(key);\n\t\tconst interpolationValues = typeof defaultOrValues === 'object' && defaultOrValues !== null\n\t\t\t? defaultOrValues\n\t\t\t: values;\n\t\tconst defaultStr = typeof defaultOrValues === 'string' ? defaultOrValues : undefined;\n\n\t\tif (!message) {\n\t\t\t// Unconditional, in every environment: a key no catalog carries silently\n\t\t\t// degrades the UI to its English default or to the key itself, and a\n\t\t\t// warning gated on NODE_ENV never fires in production builds — which is\n\t\t\t// exactly where a regression ships. The runtime typo guard is paired\n\t\t\t// with the `check-consumer-keys` scan at CI time.\n\t\t\tconsole.warn(`[i18n] Missing translation: ${key} (locale: ${this.currentLocale})`);\n\t\t}\n\n\t\t// A default is message text, not a marker: it interpolates like a translation,\n\t\t// so a key no catalog carries degrades to English instead of literal \"{count}\".\n\t\tconst text = message || defaultStr;\n\t\tif (text === undefined) return key;\n\t\treturn interpolate(text, interpolationValues, (value) => this.formatNumber(value));\n\t}\n\n\t/**\n\t * Pluralization support\n\t *\n\t * The plural category comes from `Intl.PluralRules` for the active locale, so\n\t * locales with more than two forms resolve correctly: Arabic selects between\n\t * zero/one/two/few/many/other, Romanian between one/few/other. A locale whose\n\t * catalog does not carry the selected category falls back to `.other`.\n\t *\n\t * @example plural('plurals.files', { count: 1 }) => \"1 file selected\"\n\t * @example plural('plurals.files', { count: 5 }) => \"5 files selected\"\n\t */\n\tplural(key: string, options: PluralOptions): string {\n\t\tconst { count } = options;\n\t\tconst category = this.selectPluralCategory(count);\n\t\tconst categoryKey = `${key}.${category}`;\n\t\tconst pluralKey = this.getMessage(categoryKey) !== undefined ? categoryKey : `${key}.other`;\n\t\treturn this.t(pluralKey, options);\n\t}\n\n\t/**\n\t * Select the CLDR plural category for a count in the active locale\n\t *\n\t * Falls back to the English one/other split if the locale tag is not one\n\t * `Intl.PluralRules` accepts — a host may set an arbitrary custom locale code.\n\t */\n\tprivate selectPluralCategory(count: number): Intl.LDMLPluralRule {\n\t\tlet rules = DefaultI18nProvider.pluralRules.get(this.currentLocale);\n\n\t\tif (!rules) {\n\t\t\trules = new Intl.PluralRules(intlLocale(this.currentLocale));\n\t\t\tDefaultI18nProvider.pluralRules.set(this.currentLocale, rules);\n\t\t}\n\n\t\treturn rules.select(count);\n\t}\n\n\t/**\n\t * Writing direction of the current locale\n\t *\n\t * @example getDirection() => 'rtl' for ar-SA, 'ltr' for en-US\n\t */\n\tgetDirection(): 'ltr' | 'rtl' {\n\t\treturn languageDirection(this.currentLocale);\n\t}\n\n\t/**\n\t * A view of this provider fixed to another locale\n\t *\n\t * Catalogs, loaded-locale bookkeeping and custom messages are shared by\n\t * reference, so `loadLocale()` through either side is visible to both and no\n\t * catalog is parsed twice. This is what lets two players on one page render\n\t * different locales from one provider: the locale is per-view, the catalogs\n\t * are per-provider.\n\t *\n\t * When the catalog its locale negotiates to is not resident, the view loads\n\t * it and `ready` settles when that load does; until then it renders through\n\t * the English fallback. A view over a resident catalog has no `ready`.\n\t */\n\twithLocale(locale: LocaleCode): DefaultI18nProvider {\n\t\tif (locale === this.currentLocale && this.isLocaleLoaded(locale)) return this;\n\n\t\tconst view = new DefaultI18nProvider(locale, this.customMessages);\n\t\tview.messages = this.messages;\n\t\tview.loadedLocales = this.loadedLocales;\n\t\tview.pendingLoads = this.pendingLoads;\n\t\tif (!view.isLocaleLoaded(locale)) {\n\t\t\t// loadLocale() has already logged a failure; the view falls back to English.\n\t\t\tview.ready = view.loadLocale(locale).catch(() => {});\n\t\t}\n\t\treturn view;\n\t}\n\n\t/**\n\t * Format a number in the locale's pinned numbering system\n\t *\n\t * @example formatNumber(1234.5) => \"1,234.5\" for ar, \"١٬٢٣٤٫٥\" for ar-EG\n\t */\n\tformatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n\t\treturn new Intl.NumberFormat(formattingLocale(this.currentLocale), options).format(value);\n\t}\n\n\t/**\n\t * Format a date in the locale's pinned numbering system, on the Gregorian\n\t * calendar unless the locale carries `-u-ca-`\n\t */\n\tformatDate(date: Date, options?: Intl.DateTimeFormatOptions): string {\n\t\treturn new Intl.DateTimeFormat(formattingLocale(this.currentLocale), options).format(date);\n\t}\n\n\t/**\n\t * Get nested message by dot notation key\n\t *\n\t * Walks the active locale's negotiation sequence, then the English fallback's.\n\t * At each step custom messages come before the framework catalog, so for\n\t * `es-MX` the order is custom `es-MX`, custom `es`, framework `es`, custom\n\t * `en-US`, custom `en`, framework `en`.\n\t */\n\tprivate getMessage(key: string): string | undefined {\n\t\treturn this.lookupMessage(key, this.currentLocale) ?? this.lookupMessage(key, FALLBACK_LOCALE);\n\t}\n\n\tprivate lookupMessage(key: string, locale: string): string | undefined {\n\t\tconst customTags = Object.keys(this.customMessages);\n\n\t\tfor (const step of localeLookupSequence(locale)) {\n\t\t\tfor (const tag of customTags) {\n\t\t\t\tif (normalizeLanguageTag(tag) !== step || !stepServes(locale, step, tag)) continue;\n\t\t\t\tconst custom = this.getMessageFromObject(key, this.customMessages[tag]);\n\t\t\t\tif (custom !== undefined) return custom;\n\t\t\t}\n\n\t\t\tconst code = catalogsByStep.get(step);\n\t\t\tif (code && stepServes(locale, step, code)) {\n\t\t\t\tconst message = this.getMessageFromObject(key, this.messages[code]);\n\t\t\t\tif (message !== undefined) return message;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Get message from a specific messages object\n\t *\n\t * Resolves to a string or nothing. A key that lands on a namespace branch\n\t * (`t('common')`) or on a plural sub-object (`t('plurals.items')`) is a miss,\n\t * not a hit: returning the branch would put an object where the caller\n\t * expects a string, and interpolating one throws.\n\t */\n\tprivate getMessageFromObject(key: string, messages: any): string | undefined {\n\t\tif (!messages) return undefined;\n\n\t\tconst parts = key.split('.');\n\t\tlet current: any = messages;\n\n\t\tfor (const part of parts) {\n\t\t\tif (current === null || typeof current !== 'object') return undefined;\n\t\t\tcurrent = current[part];\n\t\t\tif (current === undefined) return undefined;\n\t\t}\n\n\t\treturn typeof current === 'string' ? current : undefined;\n\t}\n\n\n\t/**\n\t * Add or update custom messages for a locale\n\t * This allows clients to provide their own translations or override defaults\n\t */\n\taddCustomMessages(locale: string, messages: LocaleMessages): void {\n\t\tthis.customMessages[locale] = this.deepMerge(\n\t\t\tthis.customMessages[locale] || {},\n\t\t\tmessages\n\t\t);\n\t}\n\n\t/**\n\t * Deep merge two objects (for merging translation objects)\n\t */\n\tprivate deepMerge(target: any, source: any): any {\n\t\tconst result = { ...target };\n\t\tfor (const key in source) {\n\t\t\tif (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {\n\t\t\t\tresult[key] = this.deepMerge(result[key] || {}, source[key]);\n\t\t\t} else {\n\t\t\t\tresult[key] = source[key];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Factory function to create a default i18n provider instance\n * @param locale - Initial locale code (default: 'en-US')\n * @param customMessages - Optional custom translations to add or override framework defaults\n * @returns DefaultI18nProvider instance\n */\nexport function createDefaultI18nProvider(\n\tlocale: LocaleCode = 'en-US',\n\tcustomMessages?: Record<string, LocaleMessages>\n): I18nProvider {\n\treturn new DefaultI18nProvider(locale, customMessages);\n}\n\nexport type { LocaleCode, MessageKey, InterpolationValues, PluralOptions };\n"]}
|
|
@@ -17,10 +17,14 @@ export interface I18nProvider {
|
|
|
17
17
|
setLocale(locale: string): Promise<void> | void;
|
|
18
18
|
/**
|
|
19
19
|
* Translate a message key with optional default and/or interpolation
|
|
20
|
-
* @param key - Message key (e.g., 'common.submit', 'assessment.question')
|
|
20
|
+
* @param key - Message key (e.g., 'common.submit', 'assessment.question').
|
|
21
|
+
* The runtime key namespace is the framework catalogs' `MessageKey` union
|
|
22
|
+
* plus keys a host supplies through `customMessages`; implementations that
|
|
23
|
+
* wrap only the framework catalogs type the parameter as `MessageKey`.
|
|
21
24
|
* @param defaultOrValues - Optional default string or interpolation values
|
|
22
25
|
* @param values - Optional interpolation values (if second arg is default string)
|
|
23
|
-
* @returns Translated message, default, or key if not found
|
|
26
|
+
* @returns Translated message, default, or key if not found. Values fill a
|
|
27
|
+
* default exactly as they fill a translated message.
|
|
24
28
|
*/
|
|
25
29
|
t(key: string, defaultOrValues?: Record<string, any> | string, values?: Record<string, any>): string;
|
|
26
30
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"I18nProvider.js","sourceRoot":"","sources":["../../src/core/I18nProvider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG","sourcesContent":["/**\n * Framework-agnostic i18n provider interface\n *\n * This interface defines the contract for internationalization services.\n * Users can provide their own implementations (ICU MessageFormat, i18next, etc.)\n * or use the default implementation provided by the framework.\n */\n\nexport interface I18nProvider {\n\t/**\n\t * Get the current locale tag as the host set it (e.g., 'en-US', 'fr', 'ar_SA')\n\t */\n\tgetLocale(): string;\n\n\t/**\n\t * Set the current locale and optionally load locale messages\n\t * @param locale - BCP 47 locale code\n\t */\n\tsetLocale(locale: string): Promise<void> | void;\n\n\t/**\n\t * Translate a message key with optional default and/or interpolation\n\t * @param key - Message key (e.g., 'common.submit', 'assessment.question')\n\t * @param defaultOrValues - Optional default string or interpolation values\n\t * @param values - Optional interpolation values (if second arg is default string)\n\t * @returns Translated message, default, or key if not found\n\t */\n\tt(key: string, defaultOrValues?: Record<string, any> | string, values?: Record<string, any>): string;\n\n\t/**\n\t * Optional: Pluralization support\n\t * @param key - Base message key\n\t * @param options - Options including count and interpolation values\n\t * @returns Pluralized and translated message\n\t */\n\tplural?(key: string, options: { count: number; [key: string]: any }): string;\n\n\t/**\n\t * Optional: Writing direction of the current locale\n\t *\n\t * Components reflect this onto a `dir` attribute. `direction` is an inherited\n\t * CSS property, so a `dir` on the host element crosses into shadow content\n\t * without any per-component wiring.\n\t *\n\t * @returns 'rtl' for right-to-left locales, otherwise 'ltr'\n\t */\n\tgetDirection?(): 'ltr' | 'rtl';\n\n\t/**\n\t * Optional: A view of this provider fixed to another locale\n\t *\n\t * Lets two players on one page render different locales without either\n\t * mutating the other's active locale. A provider that cannot produce such a\n\t * view simply omits this, and callers fall back to the provider itself.\n\t *\n\t * @param locale - BCP 47 locale code for the view\n\t */\n\twithLocale?(locale: string): I18nProvider;\n\n\t/**\n\t * Optional: Settles once the catalog for this provider's locale is loaded\n\t *\n\t * Set on a `withLocale()` view whose catalog is not yet resident. A caller\n\t * renders immediately (English fills the gap) and renders again, once, when\n\t * this settles. It never rejects: a failed load leaves the English fallback.\n\t */\n\treadonly ready?: Promise<void>;\n\n\t/**\n\t * Optional: Format number according to locale\n\t * @param value - Number to format\n\t * @param options - Intl.NumberFormat options\n\t * @returns Formatted number string\n\t */\n\tformatNumber?(value: number, options?: Intl.NumberFormatOptions): string;\n\n\t/**\n\t * Optional: Format date according to locale\n\t * @param date - Date to format\n\t * @param options - Intl.DateTimeFormat options\n\t * @returns Formatted date string\n\t */\n\tformatDate?(date: Date, options?: Intl.DateTimeFormatOptions): string;\n}\n\n/**\n * Interpolation values for dynamic message content\n */\nexport interface InterpolationValues {\n\t[key: string]: string | number;\n}\n\n/**\n * Pluralization options\n */\nexport interface PluralOptions {\n\tcount: number;\n\t[key: string]: string | number;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"I18nProvider.js","sourceRoot":"","sources":["../../src/core/I18nProvider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG","sourcesContent":["/**\n * Framework-agnostic i18n provider interface\n *\n * This interface defines the contract for internationalization services.\n * Users can provide their own implementations (ICU MessageFormat, i18next, etc.)\n * or use the default implementation provided by the framework.\n */\n\nexport interface I18nProvider {\n\t/**\n\t * Get the current locale tag as the host set it (e.g., 'en-US', 'fr', 'ar_SA')\n\t */\n\tgetLocale(): string;\n\n\t/**\n\t * Set the current locale and optionally load locale messages\n\t * @param locale - BCP 47 locale code\n\t */\n\tsetLocale(locale: string): Promise<void> | void;\n\n\t/**\n\t * Translate a message key with optional default and/or interpolation\n\t * @param key - Message key (e.g., 'common.submit', 'assessment.question').\n\t * The runtime key namespace is the framework catalogs' `MessageKey` union\n\t * plus keys a host supplies through `customMessages`; implementations that\n\t * wrap only the framework catalogs type the parameter as `MessageKey`.\n\t * @param defaultOrValues - Optional default string or interpolation values\n\t * @param values - Optional interpolation values (if second arg is default string)\n\t * @returns Translated message, default, or key if not found. Values fill a\n\t * default exactly as they fill a translated message.\n\t */\n\tt(key: string, defaultOrValues?: Record<string, any> | string, values?: Record<string, any>): string;\n\n\t/**\n\t * Optional: Pluralization support\n\t * @param key - Base message key\n\t * @param options - Options including count and interpolation values\n\t * @returns Pluralized and translated message\n\t */\n\tplural?(key: string, options: { count: number; [key: string]: any }): string;\n\n\t/**\n\t * Optional: Writing direction of the current locale\n\t *\n\t * Components reflect this onto a `dir` attribute. `direction` is an inherited\n\t * CSS property, so a `dir` on the host element crosses into shadow content\n\t * without any per-component wiring.\n\t *\n\t * @returns 'rtl' for right-to-left locales, otherwise 'ltr'\n\t */\n\tgetDirection?(): 'ltr' | 'rtl';\n\n\t/**\n\t * Optional: A view of this provider fixed to another locale\n\t *\n\t * Lets two players on one page render different locales without either\n\t * mutating the other's active locale. A provider that cannot produce such a\n\t * view simply omits this, and callers fall back to the provider itself.\n\t *\n\t * @param locale - BCP 47 locale code for the view\n\t */\n\twithLocale?(locale: string): I18nProvider;\n\n\t/**\n\t * Optional: Settles once the catalog for this provider's locale is loaded\n\t *\n\t * Set on a `withLocale()` view whose catalog is not yet resident. A caller\n\t * renders immediately (English fills the gap) and renders again, once, when\n\t * this settles. It never rejects: a failed load leaves the English fallback.\n\t */\n\treadonly ready?: Promise<void>;\n\n\t/**\n\t * Optional: Format number according to locale\n\t * @param value - Number to format\n\t * @param options - Intl.NumberFormat options\n\t * @returns Formatted number string\n\t */\n\tformatNumber?(value: number, options?: Intl.NumberFormatOptions): string;\n\n\t/**\n\t * Optional: Format date according to locale\n\t * @param date - Date to format\n\t * @param options - Intl.DateTimeFormat options\n\t * @returns Formatted date string\n\t */\n\tformatDate?(date: Date, options?: Intl.DateTimeFormatOptions): string;\n}\n\n/**\n * Interpolation values for dynamic message content\n */\nexport interface InterpolationValues {\n\t[key: string]: string | number;\n}\n\n/**\n * Pluralization options\n */\nexport interface PluralOptions {\n\tcount: number;\n\t[key: string]: string | number;\n}\n"]}
|
|
@@ -10,14 +10,31 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import type { I18nProvider } from './I18nProvider.js';
|
|
12
12
|
type Values = Record<string, unknown>;
|
|
13
|
+
/**
|
|
14
|
+
* Fill `{name}` placeholders: the one interpolation every message goes through,
|
|
15
|
+
* translated or fallback. Numbers take `formatNumber`, which a provider points
|
|
16
|
+
* at its locale's digits. A value that was not supplied leaves its placeholder
|
|
17
|
+
* visible: a legible authoring bug beats a silent blank.
|
|
18
|
+
*/
|
|
19
|
+
export declare function interpolate(message: string, values?: Values, formatNumber?: (value: number) => string): string;
|
|
13
20
|
/**
|
|
14
21
|
* Translate `key`, or interpolate the English `fallback` when the component was
|
|
15
|
-
* mounted without a provider.
|
|
22
|
+
* mounted without a provider or no catalog carries the key.
|
|
23
|
+
*
|
|
24
|
+
* `I18nProvider` is a host extension point, so a default handed back verbatim
|
|
25
|
+
* is filled here: placeholders never reach a candidate, whichever provider runs.
|
|
26
|
+
*
|
|
27
|
+
* `key` stays `string` rather than `MessageKey`: components pass keys held in
|
|
28
|
+
* string-typed structures (label tables, wrapper helpers), and hosts pass keys
|
|
29
|
+
* from their own `customMessages` catalogs. Literal-key correctness is enforced
|
|
30
|
+
* by the `check-consumer-keys` scan in `check:i18n`, and at runtime by the
|
|
31
|
+
* provider's unconditional missing-key warning.
|
|
16
32
|
*/
|
|
17
33
|
export declare function translate(i18n: I18nProvider | undefined, key: string, fallback: string, values?: Values): string;
|
|
18
34
|
/**
|
|
19
35
|
* Pluralize the plural group `key` for `count`, or pick from the English
|
|
20
|
-
* `fallback` forms when the component was mounted without a provider
|
|
36
|
+
* `fallback` forms when the component was mounted without a provider or no
|
|
37
|
+
* catalog carries the group.
|
|
21
38
|
*/
|
|
22
39
|
export declare function translatePlural(i18n: I18nProvider | undefined, key: string, fallback: {
|
|
23
40
|
one: string;
|
|
@@ -8,25 +8,50 @@
|
|
|
8
8
|
* punctuation in its translation (`accessibility.sentence` turns a bare label
|
|
9
9
|
* into one).
|
|
10
10
|
*/
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Fill `{name}` placeholders: the one interpolation every message goes through,
|
|
13
|
+
* translated or fallback. Numbers take `formatNumber`, which a provider points
|
|
14
|
+
* at its locale's digits. A value that was not supplied leaves its placeholder
|
|
15
|
+
* visible: a legible authoring bug beats a silent blank.
|
|
16
|
+
*/
|
|
17
|
+
export function interpolate(message, values, formatNumber = String) {
|
|
12
18
|
if (!values)
|
|
13
19
|
return message;
|
|
14
|
-
return message.replace(/\{(\w+)\}/g, (match, key) =>
|
|
20
|
+
return message.replace(/\{(\w+)\}/g, (match, key) => {
|
|
21
|
+
const value = values[key];
|
|
22
|
+
return typeof value === 'number' ? formatNumber(value) : String(value ?? match);
|
|
23
|
+
});
|
|
15
24
|
}
|
|
16
25
|
/**
|
|
17
26
|
* Translate `key`, or interpolate the English `fallback` when the component was
|
|
18
|
-
* mounted without a provider.
|
|
27
|
+
* mounted without a provider or no catalog carries the key.
|
|
28
|
+
*
|
|
29
|
+
* `I18nProvider` is a host extension point, so a default handed back verbatim
|
|
30
|
+
* is filled here: placeholders never reach a candidate, whichever provider runs.
|
|
31
|
+
*
|
|
32
|
+
* `key` stays `string` rather than `MessageKey`: components pass keys held in
|
|
33
|
+
* string-typed structures (label tables, wrapper helpers), and hosts pass keys
|
|
34
|
+
* from their own `customMessages` catalogs. Literal-key correctness is enforced
|
|
35
|
+
* by the `check-consumer-keys` scan in `check:i18n`, and at runtime by the
|
|
36
|
+
* provider's unconditional missing-key warning.
|
|
19
37
|
*/
|
|
20
38
|
export function translate(i18n, key, fallback, values) {
|
|
21
|
-
|
|
39
|
+
if (!i18n)
|
|
40
|
+
return interpolate(fallback, values);
|
|
41
|
+
const message = i18n.t(key, fallback, values);
|
|
42
|
+
return message === fallback ? interpolate(fallback, values, i18n.formatNumber?.bind(i18n)) : message;
|
|
22
43
|
}
|
|
23
44
|
/**
|
|
24
45
|
* Pluralize the plural group `key` for `count`, or pick from the English
|
|
25
|
-
* `fallback` forms when the component was mounted without a provider
|
|
46
|
+
* `fallback` forms when the component was mounted without a provider or no
|
|
47
|
+
* catalog carries the group.
|
|
26
48
|
*/
|
|
27
49
|
export function translatePlural(i18n, key, fallback, count, values) {
|
|
28
|
-
|
|
29
|
-
|
|
50
|
+
const message = i18n?.plural?.(key, { ...values, count });
|
|
51
|
+
// A provider answers a miss with the key it looked up, never with a sentence.
|
|
52
|
+
const missed = message === undefined || message === key || message.startsWith(`${key}.`);
|
|
53
|
+
if (!missed)
|
|
54
|
+
return message;
|
|
30
55
|
const form = count === 1 ? 'one' : 'other';
|
|
31
56
|
return translate(i18n, `${key}.${form}`, fallback[form], { ...values, count });
|
|
32
57
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accessible-text.js","sourceRoot":"","sources":["../../src/core/accessible-text.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH,
|
|
1
|
+
{"version":3,"file":"accessible-text.js","sourceRoot":"","sources":["../../src/core/accessible-text.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAC1B,OAAe,EACf,MAAe,EACf,eAA0C,MAAM;IAEhD,IAAI,CAAC,MAAM;QAAE,OAAO,OAAO,CAAC;IAC5B,OAAO,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QACnD,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1B,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,IAAI,KAAK,CAA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AO,SAAS,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAsB,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjF,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,UAAU,CAAC,IAA8B,EAAE,KAAe;IACzE,IAAI,CAAC;QACJ,OAAO,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACjH,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzB,CAAC;AACF,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,KAAoB;IAClD,OAAO,KAAK,CAAC,WAAW,IAAI,KAAK,CAAC,OAAO,KAAK,GAAG,CAAC;AACnD,CAAC","sourcesContent":["/**\n * Helpers for the accessible names and live-region messages components compose.\n *\n * A message is never assembled from translated fragments: word order, list\n * joining and sentence punctuation differ by language. Each key is a whole\n * phrase or a whole sentence with named placeholders, and a label built from\n * several states joins complete sentences, each of which carries its own\n * punctuation in its translation (`accessibility.sentence` turns a bare label\n * into one).\n */\n\nimport type { I18nProvider } from './I18nProvider.js';\n\ntype Values = Record<string, unknown>;\n\n/**\n * Fill `{name}` placeholders: the one interpolation every message goes through,\n * translated or fallback. Numbers take `formatNumber`, which a provider points\n * at its locale's digits. A value that was not supplied leaves its placeholder\n * visible: a legible authoring bug beats a silent blank.\n */\nexport function interpolate(\n\tmessage: string,\n\tvalues?: Values,\n\tformatNumber: (value: number) => string = String,\n): string {\n\tif (!values) return message;\n\treturn message.replace(/\\{(\\w+)\\}/g, (match, key) => {\n\t\tconst value = values[key];\n\t\treturn typeof value === 'number' ? formatNumber(value) : String(value ?? match);\n\t});\n}\n\n/**\n * Translate `key`, or interpolate the English `fallback` when the component was\n * mounted without a provider or no catalog carries the key.\n *\n * `I18nProvider` is a host extension point, so a default handed back verbatim\n * is filled here: placeholders never reach a candidate, whichever provider runs.\n *\n * `key` stays `string` rather than `MessageKey`: components pass keys held in\n * string-typed structures (label tables, wrapper helpers), and hosts pass keys\n * from their own `customMessages` catalogs. Literal-key correctness is enforced\n * by the `check-consumer-keys` scan in `check:i18n`, and at runtime by the\n * provider's unconditional missing-key warning.\n */\nexport function translate(i18n: I18nProvider | undefined, key: string, fallback: string, values?: Values): string {\n\tif (!i18n) return interpolate(fallback, values);\n\tconst message = i18n.t(key, fallback, values);\n\treturn message === fallback ? interpolate(fallback, values, i18n.formatNumber?.bind(i18n)) : message;\n}\n\n/**\n * Pluralize the plural group `key` for `count`, or pick from the English\n * `fallback` forms when the component was mounted without a provider or no\n * catalog carries the group.\n */\nexport function translatePlural(\n\ti18n: I18nProvider | undefined,\n\tkey: string,\n\tfallback: { one: string; other: string },\n\tcount: number,\n\tvalues?: Record<string, string | number>,\n): string {\n\tconst message = i18n?.plural?.(key, { ...values, count });\n\t// A provider answers a miss with the key it looked up, never with a sentence.\n\tconst missed = message === undefined || message === key || message.startsWith(`${key}.`);\n\tif (!missed) return message;\n\tconst form = count === 1 ? 'one' : 'other';\n\treturn translate(i18n, `${key}.${form}`, fallback[form], { ...values, count });\n}\n\n/** Join complete sentences, skipping the conditions that did not apply. */\nexport function joinSentences(...sentences: Array<string | false | null | undefined>): string {\n\treturn sentences.filter((sentence): sentence is string => !!sentence).join(' ');\n}\n\n/** A conjunction list in the provider's locale: \"A, B and C\", \"A، B وC\". */\nexport function formatList(i18n: I18nProvider | undefined, items: string[]): string {\n\ttry {\n\t\treturn new Intl.ListFormat(i18n?.getLocale().replace(/_/g, '-') || 'en', { type: 'conjunction' }).format(items);\n\t} catch {\n\t\treturn items.join(', ');\n\t}\n}\n\n/**\n * True while an input method editor is composing, when Escape and Enter belong\n * to the IME (cancel or commit the candidate) and a handler must not act on\n * them. `keyCode` 229 covers engines that end composition before the event.\n */\nexport function isImeComposing(event: KeyboardEvent): boolean {\n\treturn event.isComposing || event.keyCode === 229;\n}\n"]}
|