@pie-qti/i18n 1.0.0-beta.1 → 1.0.0-beta.2
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 +104 -55
- package/dist/core/I18n.d.ts +43 -13
- package/dist/core/I18n.js +135 -112
- package/dist/core/I18n.js.map +1 -1
- package/dist/core/I18nProvider.d.ts +9 -1
- package/dist/core/I18nProvider.js.map +1 -1
- package/dist/core/accessible-text.d.ts +36 -0
- package/dist/core/accessible-text.js +54 -0
- package/dist/core/accessible-text.js.map +1 -0
- package/dist/core/direction.d.ts +39 -0
- package/dist/core/direction.js +96 -0
- package/dist/core/direction.js.map +1 -0
- package/dist/core/language-tags.d.ts +47 -0
- package/dist/core/language-tags.js +91 -0
- package/dist/core/language-tags.js.map +1 -0
- package/dist/core/negotiation.d.ts +41 -0
- package/dist/core/negotiation.js +71 -0
- package/dist/core/negotiation.js.map +1 -0
- package/dist/core/numbering.d.ts +31 -0
- package/dist/core/numbering.js +88 -0
- package/dist/core/numbering.js.map +1 -0
- package/dist/core/pseudo.d.ts +33 -0
- package/dist/core/pseudo.js +44 -0
- package/dist/core/pseudo.js.map +1 -0
- package/dist/core/types.d.ts +13 -3
- package/dist/core/types.js.map +1 -1
- package/dist/index.d.ts +12 -2
- package/dist/index.js +13 -2
- package/dist/index.js.map +1 -1
- package/dist/locales/{ar-SA.d.ts → ar.d.ts} +65 -3
- package/dist/locales/{ar-SA.js → ar.js} +66 -4
- package/dist/locales/ar.js.map +1 -0
- package/dist/locales/{en-US.d.ts → en.d.ts} +61 -3
- package/dist/locales/{en-US.js → en.js} +62 -4
- package/dist/locales/en.js.map +1 -0
- package/dist/locales/{es-ES.d.ts → es.d.ts} +62 -3
- package/dist/locales/{es-ES.js → es.js} +63 -4
- package/dist/locales/es.js.map +1 -0
- package/dist/locales/{fr-FR.d.ts → fr.d.ts} +62 -3
- package/dist/locales/{fr-FR.js → fr.js} +63 -4
- package/dist/locales/fr.js.map +1 -0
- package/dist/locales/{nl-NL.d.ts → nl.d.ts} +61 -3
- package/dist/locales/{nl-NL.js → nl.js} +62 -4
- package/dist/locales/nl.js.map +1 -0
- package/dist/locales/{ro-RO.d.ts → ro.d.ts} +62 -3
- package/dist/locales/{ro-RO.js → ro.js} +63 -4
- package/dist/locales/ro.js.map +1 -0
- package/dist/locales/{th-TH.d.ts → th.d.ts} +61 -3
- package/dist/locales/{th-TH.js → th.js} +62 -4
- package/dist/locales/th.js.map +1 -0
- package/dist/locales/{zh-CN.d.ts → zh-Hans.d.ts} +61 -3
- package/dist/locales/{zh-CN.js → zh-Hans.js} +62 -4
- package/dist/locales/zh-Hans.js.map +1 -0
- package/dist/providers/SvelteI18nProvider.d.ts +31 -12
- package/dist/providers/SvelteI18nProvider.js +33 -38
- package/dist/providers/SvelteI18nProvider.js.map +1 -1
- package/package.json +4 -2
- package/dist/locales/ar-SA.js.map +0 -1
- package/dist/locales/en-US.js.map +0 -1
- package/dist/locales/es-ES.js.map +0 -1
- package/dist/locales/fr-FR.js.map +0 -1
- package/dist/locales/nl-NL.js.map +0 -1
- package/dist/locales/ro-RO.js.map +0 -1
- package/dist/locales/th-TH.js.map +0 -1
- package/dist/locales/zh-CN.js.map +0 -1
package/dist/core/I18n.js
CHANGED
|
@@ -5,31 +5,57 @@
|
|
|
5
5
|
* It uses standard dynamic imports for lazy locale loading and provides simple
|
|
6
6
|
* interpolation and pluralization support.
|
|
7
7
|
*/
|
|
8
|
-
import
|
|
8
|
+
import { languageDirection } from './direction.js';
|
|
9
|
+
import { normalizeLanguageTag } from './language-tags.js';
|
|
10
|
+
import { formattingLocale } from './numbering.js';
|
|
11
|
+
import { FRAMEWORK_CATALOGS, localeLookupSequence, resolveFrameworkLocale, stepServes, } from './negotiation.js';
|
|
12
|
+
import en from '../locales/en.js';
|
|
9
13
|
/**
|
|
10
|
-
* Lazy loaders for the framework
|
|
14
|
+
* Lazy loaders for the framework catalogs, keyed by language.
|
|
11
15
|
*
|
|
12
16
|
* An explicit static map rather than a bundler macro: `tsc` emits these
|
|
13
17
|
* `import()` calls verbatim, so the published package evaluates anywhere ESM
|
|
14
18
|
* does — webpack, esbuild, Rollup, Node, or a browser loading the files
|
|
15
19
|
* directly. Every bundler still sees the specifiers statically, so each locale
|
|
16
20
|
* remains its own chunk and a host that only renders English never fetches the
|
|
17
|
-
* others. Adding a locale means adding a line here alongside the file
|
|
21
|
+
* others. Adding a locale means adding a line here alongside the file and its
|
|
22
|
+
* key in `FRAMEWORK_CATALOGS`.
|
|
18
23
|
*
|
|
19
|
-
* en
|
|
24
|
+
* `en` is a plain static import because it is the fallback for every missing
|
|
20
25
|
* key in every other locale, so it must be resolvable synchronously in the
|
|
21
26
|
* constructor.
|
|
22
27
|
*/
|
|
23
28
|
const localeLoaders = {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
'zh-
|
|
29
|
+
en: () => Promise.resolve({ default: en }),
|
|
30
|
+
ar: () => import('../locales/ar.js'),
|
|
31
|
+
es: () => import('../locales/es.js'),
|
|
32
|
+
fr: () => import('../locales/fr.js'),
|
|
33
|
+
nl: () => import('../locales/nl.js'),
|
|
34
|
+
ro: () => import('../locales/ro.js'),
|
|
35
|
+
th: () => import('../locales/th.js'),
|
|
36
|
+
'zh-Hans': () => import('../locales/zh-Hans.js'),
|
|
32
37
|
};
|
|
38
|
+
/** Catalog keys by their normalized form, which is what a lookup step is. */
|
|
39
|
+
const catalogsByStep = new Map(FRAMEWORK_CATALOGS.map((code) => [normalizeLanguageTag(code), code]));
|
|
40
|
+
/**
|
|
41
|
+
* The locale every lookup falls back to. Walked like any other tag, so custom
|
|
42
|
+
* messages keyed `en-US` and the framework `en` catalog both serve it.
|
|
43
|
+
*/
|
|
44
|
+
const FALLBACK_LOCALE = 'en-US';
|
|
45
|
+
/**
|
|
46
|
+
* A tag `Intl` accepts for the active locale: POSIX separators and suffixes
|
|
47
|
+
* are rewritten (`ar_SA` → `ar-SA`), and a tag `Intl` still rejects formats as
|
|
48
|
+
* English rather than throwing.
|
|
49
|
+
*/
|
|
50
|
+
function intlLocale(tag) {
|
|
51
|
+
const candidate = tag.trim().replace(/_/g, '-').split(/[.@]/)[0];
|
|
52
|
+
try {
|
|
53
|
+
return Intl.getCanonicalLocales(candidate)[0] ?? FALLBACK_LOCALE;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return FALLBACK_LOCALE;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
33
59
|
/**
|
|
34
60
|
* Whether to log missing-translation warnings.
|
|
35
61
|
*
|
|
@@ -39,82 +65,83 @@ const localeLoaders = {
|
|
|
39
65
|
* bundler that substitutes it.
|
|
40
66
|
*/
|
|
41
67
|
const isDevelopment = typeof process !== 'undefined' && process.env?.NODE_ENV === 'development';
|
|
42
|
-
/**
|
|
43
|
-
* Right-to-left primary language subtags.
|
|
44
|
-
*
|
|
45
|
-
* Only consulted when `Intl.Locale.prototype.textInfo` is unavailable — it is the
|
|
46
|
-
* authoritative source but shipped late in Safari, and an assessment rendered
|
|
47
|
-
* left-to-right for an Arabic reader is not a graceful degradation.
|
|
48
|
-
*/
|
|
49
|
-
const RTL_LANGUAGES = new Set([
|
|
50
|
-
'ar', // Arabic
|
|
51
|
-
'ckb', // Central Kurdish
|
|
52
|
-
'dv', // Dhivehi
|
|
53
|
-
'fa', // Persian
|
|
54
|
-
'he',
|
|
55
|
-
'iw', // Hebrew (current and legacy subtags)
|
|
56
|
-
'ks', // Kashmiri
|
|
57
|
-
'ku', // Kurdish
|
|
58
|
-
'nqo', // N'Ko
|
|
59
|
-
'ps', // Pashto
|
|
60
|
-
'sd', // Sindhi
|
|
61
|
-
'syr', // Syriac
|
|
62
|
-
'ug', // Uyghur
|
|
63
|
-
'ur', // Urdu
|
|
64
|
-
'yi', // Yiddish
|
|
65
|
-
]);
|
|
66
68
|
export class DefaultI18nProvider {
|
|
67
69
|
/** Shared across instances: constructing Intl.PluralRules is not cheap */
|
|
68
70
|
static pluralRules = new Map();
|
|
69
71
|
currentLocale;
|
|
70
72
|
messages;
|
|
71
73
|
customMessages; // Client-provided translations
|
|
72
|
-
fallbackLocale = 'en-US';
|
|
73
74
|
loadedLocales = new Set();
|
|
75
|
+
pendingLoads = new Map();
|
|
76
|
+
/**
|
|
77
|
+
* Settles once the catalog for this provider's locale is loaded. Set only on
|
|
78
|
+
* a `withLocale()` view created before that catalog was resident; the view
|
|
79
|
+
* starts the load itself. Never rejects: a failed load is logged and the view
|
|
80
|
+
* keeps rendering through the English fallback.
|
|
81
|
+
*/
|
|
82
|
+
ready;
|
|
83
|
+
/**
|
|
84
|
+
* @param locale - Active locale; any BCP 47 or POSIX tag. The host owns this
|
|
85
|
+
* value: the provider reads no storage and persists nothing.
|
|
86
|
+
* @param customMessages - Host translations by locale tag, consulted before
|
|
87
|
+
* the framework catalogs.
|
|
88
|
+
*/
|
|
74
89
|
constructor(locale = 'en-US', customMessages) {
|
|
75
|
-
|
|
76
|
-
// This allows locale changes to persist across page reloads
|
|
77
|
-
const storedLocale = typeof localStorage !== 'undefined'
|
|
78
|
-
? localStorage.getItem('pie-qti-locale')
|
|
79
|
-
: null;
|
|
80
|
-
this.currentLocale = storedLocale || locale;
|
|
90
|
+
this.currentLocale = locale;
|
|
81
91
|
this.messages = {};
|
|
82
92
|
this.customMessages = customMessages || {};
|
|
83
|
-
// en
|
|
84
|
-
this.messages
|
|
85
|
-
this.loadedLocales.add('en
|
|
93
|
+
// en is the fallback for every other locale, so it is always present
|
|
94
|
+
this.messages.en = en;
|
|
95
|
+
this.loadedLocales.add('en');
|
|
86
96
|
}
|
|
87
97
|
/**
|
|
88
|
-
* Load
|
|
89
|
-
*
|
|
98
|
+
* Load the framework catalog that serves a locale tag.
|
|
99
|
+
*
|
|
100
|
+
* The tag is negotiated (`es-MX` loads `es`, `zh-CN` loads `zh-Hans`). A tag
|
|
101
|
+
* no framework catalog serves resolves without loading anything: it renders
|
|
102
|
+
* from custom messages and the English fallback. Rejects only when a catalog
|
|
103
|
+
* module fails to load.
|
|
90
104
|
*/
|
|
91
105
|
async loadLocale(locale) {
|
|
92
|
-
|
|
93
|
-
|
|
106
|
+
const code = resolveFrameworkLocale(locale);
|
|
107
|
+
if (!code || this.loadedLocales.has(code))
|
|
108
|
+
return;
|
|
109
|
+
let pending = this.pendingLoads.get(code);
|
|
110
|
+
if (!pending) {
|
|
111
|
+
pending = localeLoaders[code]()
|
|
112
|
+
.then((module) => {
|
|
113
|
+
this.messages[code] = module.default;
|
|
114
|
+
this.loadedLocales.add(code);
|
|
115
|
+
})
|
|
116
|
+
.finally(() => {
|
|
117
|
+
this.pendingLoads.delete(code);
|
|
118
|
+
});
|
|
119
|
+
this.pendingLoads.set(code, pending);
|
|
94
120
|
}
|
|
95
121
|
try {
|
|
96
|
-
|
|
97
|
-
if (!loader) {
|
|
98
|
-
throw new Error(`Locale '${locale}' is not a framework locale`);
|
|
99
|
-
}
|
|
100
|
-
const module = await loader();
|
|
101
|
-
this.messages[locale] = module.default;
|
|
102
|
-
this.loadedLocales.add(locale);
|
|
122
|
+
await pending;
|
|
103
123
|
}
|
|
104
124
|
catch (error) {
|
|
105
125
|
console.error(`[i18n] Failed to load locale '${locale}':`, error);
|
|
106
126
|
throw error;
|
|
107
127
|
}
|
|
108
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* Whether every catalog a locale needs is resident: true for a tag no
|
|
131
|
+
* framework catalog serves, since there is nothing to load.
|
|
132
|
+
*/
|
|
133
|
+
isLocaleLoaded(locale) {
|
|
134
|
+
const code = resolveFrameworkLocale(locale);
|
|
135
|
+
return !code || this.loadedLocales.has(code);
|
|
136
|
+
}
|
|
109
137
|
/**
|
|
110
138
|
* Set current locale
|
|
111
139
|
* For framework locales, loadLocale() should be called first.
|
|
112
140
|
* For custom locales, translations should be provided via customMessages.
|
|
113
141
|
*/
|
|
114
142
|
setLocale(locale) {
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
if (!this.loadedLocales.has(locale) && !this.customMessages[locale]) {
|
|
143
|
+
const hasCustom = Object.keys(this.customMessages).some((tag) => localeLookupSequence(locale).includes(normalizeLanguageTag(tag)));
|
|
144
|
+
if (!this.isLocaleLoaded(locale) && !hasCustom) {
|
|
118
145
|
console.warn(`[i18n] Locale '${locale}' not loaded and no custom messages provided. Using fallback locale.`);
|
|
119
146
|
}
|
|
120
147
|
this.currentLocale = locale;
|
|
@@ -145,9 +172,12 @@ export class DefaultI18nProvider {
|
|
|
145
172
|
}
|
|
146
173
|
if (!interpolationValues)
|
|
147
174
|
return message;
|
|
148
|
-
//
|
|
175
|
+
// Replace {key} with values[key]; numbers take the locale's digits
|
|
149
176
|
return message.replace(/\{(\w+)\}/g, (match, k) => {
|
|
150
|
-
|
|
177
|
+
const value = interpolationValues[k];
|
|
178
|
+
if (typeof value === 'number')
|
|
179
|
+
return this.formatNumber(value);
|
|
180
|
+
return String(value ?? match);
|
|
151
181
|
});
|
|
152
182
|
}
|
|
153
183
|
/**
|
|
@@ -177,12 +207,7 @@ export class DefaultI18nProvider {
|
|
|
177
207
|
selectPluralCategory(count) {
|
|
178
208
|
let rules = DefaultI18nProvider.pluralRules.get(this.currentLocale);
|
|
179
209
|
if (!rules) {
|
|
180
|
-
|
|
181
|
-
rules = new Intl.PluralRules(this.currentLocale);
|
|
182
|
-
}
|
|
183
|
-
catch {
|
|
184
|
-
return count === 1 ? 'one' : 'other';
|
|
185
|
-
}
|
|
210
|
+
rules = new Intl.PluralRules(intlLocale(this.currentLocale));
|
|
186
211
|
DefaultI18nProvider.pluralRules.set(this.currentLocale, rules);
|
|
187
212
|
}
|
|
188
213
|
return rules.select(count);
|
|
@@ -193,19 +218,7 @@ export class DefaultI18nProvider {
|
|
|
193
218
|
* @example getDirection() => 'rtl' for ar-SA, 'ltr' for en-US
|
|
194
219
|
*/
|
|
195
220
|
getDirection() {
|
|
196
|
-
|
|
197
|
-
// textInfo is the authoritative CLDR answer where the engine has it
|
|
198
|
-
const textInfo = new Intl.Locale(this.currentLocale)
|
|
199
|
-
.textInfo;
|
|
200
|
-
if (textInfo?.direction === 'rtl' || textInfo?.direction === 'ltr') {
|
|
201
|
-
return textInfo.direction;
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
catch {
|
|
205
|
-
// Not a tag Intl.Locale accepts; the subtag check below still works
|
|
206
|
-
}
|
|
207
|
-
const language = this.currentLocale.toLowerCase().split(/[-_]/)[0] ?? '';
|
|
208
|
-
return RTL_LANGUAGES.has(language) ? 'rtl' : 'ltr';
|
|
221
|
+
return languageDirection(this.currentLocale);
|
|
209
222
|
}
|
|
210
223
|
/**
|
|
211
224
|
* A view of this provider fixed to another locale
|
|
@@ -215,51 +228,68 @@ export class DefaultI18nProvider {
|
|
|
215
228
|
* catalog is parsed twice. This is what lets two players on one page render
|
|
216
229
|
* different locales from one provider: the locale is per-view, the catalogs
|
|
217
230
|
* are per-provider.
|
|
231
|
+
*
|
|
232
|
+
* When the catalog its locale negotiates to is not resident, the view loads
|
|
233
|
+
* it and `ready` settles when that load does; until then it renders through
|
|
234
|
+
* the English fallback. A view over a resident catalog has no `ready`.
|
|
218
235
|
*/
|
|
219
236
|
withLocale(locale) {
|
|
220
|
-
if (locale === this.currentLocale)
|
|
237
|
+
if (locale === this.currentLocale && this.isLocaleLoaded(locale))
|
|
221
238
|
return this;
|
|
222
239
|
const view = new DefaultI18nProvider(locale, this.customMessages);
|
|
223
|
-
// The constructor prefers a persisted locale; an explicit view must not.
|
|
224
|
-
view.currentLocale = locale;
|
|
225
240
|
view.messages = this.messages;
|
|
226
241
|
view.loadedLocales = this.loadedLocales;
|
|
242
|
+
view.pendingLoads = this.pendingLoads;
|
|
243
|
+
if (!view.isLocaleLoaded(locale)) {
|
|
244
|
+
// loadLocale() has already logged a failure; the view falls back to English.
|
|
245
|
+
view.ready = view.loadLocale(locale).catch(() => { });
|
|
246
|
+
}
|
|
227
247
|
return view;
|
|
228
248
|
}
|
|
229
249
|
/**
|
|
230
|
-
* Format number
|
|
250
|
+
* Format a number in the locale's pinned numbering system
|
|
251
|
+
*
|
|
252
|
+
* @example formatNumber(1234.5) => "1,234.5" for ar, "١٬٢٣٤٫٥" for ar-EG
|
|
231
253
|
*/
|
|
232
254
|
formatNumber(value, options) {
|
|
233
|
-
return new Intl.NumberFormat(this.currentLocale, options).format(value);
|
|
255
|
+
return new Intl.NumberFormat(formattingLocale(this.currentLocale), options).format(value);
|
|
234
256
|
}
|
|
235
257
|
/**
|
|
236
|
-
* Format date
|
|
258
|
+
* Format a date in the locale's pinned numbering system, on the Gregorian
|
|
259
|
+
* calendar unless the locale carries `-u-ca-`
|
|
237
260
|
*/
|
|
238
261
|
formatDate(date, options) {
|
|
239
|
-
return new Intl.DateTimeFormat(this.currentLocale, options).format(date);
|
|
262
|
+
return new Intl.DateTimeFormat(formattingLocale(this.currentLocale), options).format(date);
|
|
240
263
|
}
|
|
241
264
|
/**
|
|
242
265
|
* Get nested message by dot notation key
|
|
243
|
-
*
|
|
266
|
+
*
|
|
267
|
+
* Walks the active locale's negotiation sequence, then the English fallback's.
|
|
268
|
+
* At each step custom messages come before the framework catalog, so for
|
|
269
|
+
* `es-MX` the order is custom `es-MX`, custom `es`, framework `es`, custom
|
|
270
|
+
* `en-US`, custom `en`, framework `en`.
|
|
244
271
|
*/
|
|
245
272
|
getMessage(key) {
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
273
|
+
return this.lookupMessage(key, this.currentLocale) ?? this.lookupMessage(key, FALLBACK_LOCALE);
|
|
274
|
+
}
|
|
275
|
+
lookupMessage(key, locale) {
|
|
276
|
+
const customTags = Object.keys(this.customMessages);
|
|
277
|
+
for (const step of localeLookupSequence(locale)) {
|
|
278
|
+
for (const tag of customTags) {
|
|
279
|
+
if (normalizeLanguageTag(tag) !== step || !stepServes(locale, step, tag))
|
|
280
|
+
continue;
|
|
281
|
+
const custom = this.getMessageFromObject(key, this.customMessages[tag]);
|
|
282
|
+
if (custom !== undefined)
|
|
283
|
+
return custom;
|
|
284
|
+
}
|
|
285
|
+
const code = catalogsByStep.get(step);
|
|
286
|
+
if (code && stepServes(locale, step, code)) {
|
|
287
|
+
const message = this.getMessageFromObject(key, this.messages[code]);
|
|
288
|
+
if (message !== undefined)
|
|
289
|
+
return message;
|
|
290
|
+
}
|
|
256
291
|
}
|
|
257
|
-
|
|
258
|
-
const customFallback = this.getMessageFromObject(key, this.customMessages[this.fallbackLocale]);
|
|
259
|
-
if (customFallback !== undefined)
|
|
260
|
-
return customFallback;
|
|
261
|
-
// 4. Try framework fallback locale
|
|
262
|
-
return this.getMessageFromFallback(key);
|
|
292
|
+
return undefined;
|
|
263
293
|
}
|
|
264
294
|
/**
|
|
265
295
|
* Get message from a specific messages object
|
|
@@ -283,13 +313,6 @@ export class DefaultI18nProvider {
|
|
|
283
313
|
}
|
|
284
314
|
return typeof current === 'string' ? current : undefined;
|
|
285
315
|
}
|
|
286
|
-
/**
|
|
287
|
-
* Get message from fallback locale (framework defaults)
|
|
288
|
-
*/
|
|
289
|
-
getMessageFromFallback(key) {
|
|
290
|
-
const messages = this.messages[this.fallbackLocale];
|
|
291
|
-
return this.getMessageFromObject(key, messages);
|
|
292
|
-
}
|
|
293
316
|
/**
|
|
294
317
|
* Add or update custom messages for a locale
|
|
295
318
|
* This allows clients to provide their own translations or override defaults
|
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,IAAI,MAAM,qBAAqB,CAAC;AAEvC;;;;;;;;;;;;;GAaG;AACH,MAAM,aAAa,GAA4E;IAC9F,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO,EA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*\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, FrameworkLocaleCode, MessageKey, LocaleMessages } from './types.js';\nimport enUS from '../locales/en-US.js';\n\n/**\n * Lazy loaders for the framework locales.\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.\n *\n * en-US 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<FrameworkLocaleCode, () => Promise<{ default: LocaleMessages }>> = {\n\t'en-US': () => Promise.resolve({ default: enUS }),\n\t'ar-SA': () => import('../locales/ar-SA.js'),\n\t'es-ES': () => import('../locales/es-ES.js'),\n\t'fr-FR': () => import('../locales/fr-FR.js'),\n\t'nl-NL': () => import('../locales/nl-NL.js'),\n\t'ro-RO': () => import('../locales/ro-RO.js'),\n\t'th-TH': () => import('../locales/th-TH.js'),\n\t'zh-CN': () => import('../locales/zh-CN.js'),\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\n/**\n * Right-to-left primary language subtags.\n *\n * Only consulted when `Intl.Locale.prototype.textInfo` is unavailable — it is the\n * authoritative source but shipped late in Safari, and an assessment rendered\n * left-to-right for an Arabic reader is not a graceful degradation.\n */\nconst RTL_LANGUAGES = new Set([\n\t'ar', // Arabic\n\t'ckb', // Central Kurdish\n\t'dv', // Dhivehi\n\t'fa', // Persian\n\t'he',\n\t'iw', // Hebrew (current and legacy subtags)\n\t'ks', // Kashmiri\n\t'ku', // Kurdish\n\t'nqo', // N'Ko\n\t'ps', // Pashto\n\t'sd', // Sindhi\n\t'syr', // Syriac\n\t'ug', // Uyghur\n\t'ur', // Urdu\n\t'yi', // Yiddish\n]);\n\nexport class DefaultI18nProvider implements I18nProvider {\n\t/** Shared across instances: constructing Intl.PluralRules is not cheap */\n\tprivate static pluralRules: Map<LocaleCode, Intl.PluralRules> = new Map();\n\n\tprivate currentLocale: LocaleCode;\n\tprivate messages: Record<LocaleCode, LocaleMessages>;\n\tprivate customMessages: Record<string, LocaleMessages>; // Client-provided translations\n\tprivate fallbackLocale: LocaleCode = 'en-US';\n\tprivate loadedLocales: Set<LocaleCode> = new Set();\n\n\tconstructor(locale: LocaleCode = 'en-US', customMessages?: Record<string, LocaleMessages>) {\n\t\t// Read persisted locale from localStorage if available\n\t\t// This allows locale changes to persist across page reloads\n\t\tconst storedLocale = typeof localStorage !== 'undefined'\n\t\t\t? localStorage.getItem('pie-qti-locale')\n\t\t\t: null;\n\n\t\tthis.currentLocale = (storedLocale as LocaleCode) || locale;\n\t\tthis.messages = {} as Record<LocaleCode, LocaleMessages>;\n\t\tthis.customMessages = customMessages || {};\n\n\t\t// en-US is the fallback for every other locale, so it is always present\n\t\tthis.messages['en-US'] = enUS;\n\t\tthis.loadedLocales.add('en-US');\n\t}\n\n\t/**\n\t * Load locale messages dynamically (framework locales only)\n\t * For custom locales, use the customMessages parameter in the constructor or addCustomMessages()\n\t */\n\tasync loadLocale(locale: FrameworkLocaleCode): Promise<void> {\n\t\tif (this.loadedLocales.has(locale)) {\n\t\t\treturn; // Already loaded\n\t\t}\n\n\t\ttry {\n\t\t\tconst loader = localeLoaders[locale];\n\n\t\t\tif (!loader) {\n\t\t\t\tthrow new Error(`Locale '${locale}' is not a framework locale`);\n\t\t\t}\n\n\t\t\tconst module = await loader();\n\t\t\tthis.messages[locale] = module.default;\n\t\t\tthis.loadedLocales.add(locale);\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 * 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\t// Allow setting custom locales even if not in loadedLocales\n\t\t// They will use customMessages + fallback to en-US\n\t\tif (!this.loadedLocales.has(locale as LocaleCode) && !this.customMessages[locale]) {\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// Simple interpolation: replace {key} with values[key]\n\t\treturn message.replace(/\\{(\\w+)\\}/g, (match, k) => {\n\t\t\treturn String(interpolationValues[k] ?? 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\ttry {\n\t\t\t\trules = new Intl.PluralRules(this.currentLocale);\n\t\t\t} catch {\n\t\t\t\treturn count === 1 ? 'one' : 'other';\n\t\t\t}\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\ttry {\n\t\t\t// textInfo is the authoritative CLDR answer where the engine has it\n\t\t\tconst textInfo = (new Intl.Locale(this.currentLocale) as { textInfo?: { direction?: string } })\n\t\t\t\t.textInfo;\n\t\t\tif (textInfo?.direction === 'rtl' || textInfo?.direction === 'ltr') {\n\t\t\t\treturn textInfo.direction;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Not a tag Intl.Locale accepts; the subtag check below still works\n\t\t}\n\n\t\tconst language = this.currentLocale.toLowerCase().split(/[-_]/)[0] ?? '';\n\t\treturn RTL_LANGUAGES.has(language) ? 'rtl' : 'ltr';\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\twithLocale(locale: LocaleCode): I18nProvider {\n\t\tif (locale === this.currentLocale) return this;\n\n\t\tconst view = new DefaultI18nProvider(locale, this.customMessages);\n\t\t// The constructor prefers a persisted locale; an explicit view must not.\n\t\tview.currentLocale = locale;\n\t\tview.messages = this.messages;\n\t\tview.loadedLocales = this.loadedLocales;\n\t\treturn view;\n\t}\n\n\t/**\n\t * Format number according to locale\n\t */\n\tformatNumber(value: number, options?: Intl.NumberFormatOptions): string {\n\t\treturn new Intl.NumberFormat(this.currentLocale, options).format(value);\n\t}\n\n\t/**\n\t * Format date according to locale\n\t */\n\tformatDate(date: Date, options?: Intl.DateTimeFormatOptions): string {\n\t\treturn new Intl.DateTimeFormat(this.currentLocale, options).format(date);\n\t}\n\n\t/**\n\t * Get nested message by dot notation key\n\t * Priority: custom messages > current locale > fallback locale\n\t */\n\tprivate getMessage(key: string): string | undefined {\n\t\t// 1. Try custom messages first (client overrides)\n\t\tconst customMessage = this.getMessageFromObject(key, this.customMessages[this.currentLocale]);\n\t\tif (customMessage !== undefined) return customMessage;\n\n\t\t// 2. Try current locale from framework defaults\n\t\tconst messages = this.messages[this.currentLocale];\n\t\tif (messages) {\n\t\t\tconst message = this.getMessageFromObject(key, messages);\n\t\t\tif (message !== undefined) return message;\n\t\t}\n\n\t\t// 3. Try custom fallback locale\n\t\tconst customFallback = this.getMessageFromObject(key, this.customMessages[this.fallbackLocale]);\n\t\tif (customFallback !== undefined) return customFallback;\n\n\t\t// 4. Try framework fallback locale\n\t\treturn this.getMessageFromFallback(key);\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\t/**\n\t * Get message from fallback locale (framework defaults)\n\t */\n\tprivate getMessageFromFallback(key: string): string | undefined {\n\t\tconst messages = this.messages[this.fallbackLocale];\n\t\treturn this.getMessageFromObject(key, messages);\n\t}\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"],"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,kBAAkB,CAAC;IACpC,EAAE,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,kBAAkB,CAAC;IACpC,SAAS,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,uBAAuB,CAAC;CAChD,CAAC;AAEF,6EAA6E;AAC7E,MAAM,cAAc,GAAG,IAAI,GAAG,CAC7B,kBAAkB,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,oBAAoB,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,CAC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AC;YACxB,IAAI,OAAO,KAAK,SAAS;gBAAE,OAAO,SAAS,CAAC;QAC7C,CAAC;QAED,OAAO,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;IAC1D,CAAC;IAGD;;;OAGG;IACH,iBAAiB,CAAC,MAAc,EAAE,QAAwB;QACzD,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,SAAS,CAC3C,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,IAAI,EAAE,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 { 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"]}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export interface I18nProvider {
|
|
9
9
|
/**
|
|
10
|
-
* Get the current locale
|
|
10
|
+
* Get the current locale tag as the host set it (e.g., 'en-US', 'fr', 'ar_SA')
|
|
11
11
|
*/
|
|
12
12
|
getLocale(): string;
|
|
13
13
|
/**
|
|
@@ -53,6 +53,14 @@ export interface I18nProvider {
|
|
|
53
53
|
* @param locale - BCP 47 locale code for the view
|
|
54
54
|
*/
|
|
55
55
|
withLocale?(locale: string): I18nProvider;
|
|
56
|
+
/**
|
|
57
|
+
* Optional: Settles once the catalog for this provider's locale is loaded
|
|
58
|
+
*
|
|
59
|
+
* Set on a `withLocale()` view whose catalog is not yet resident. A caller
|
|
60
|
+
* renders immediately (English fills the gap) and renders again, once, when
|
|
61
|
+
* this settles. It never rejects: a failed load leaves the English fallback.
|
|
62
|
+
*/
|
|
63
|
+
readonly ready?: Promise<void>;
|
|
56
64
|
/**
|
|
57
65
|
* Optional: Format number according to locale
|
|
58
66
|
* @param value - Number to format
|
|
@@ -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
|
|
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"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the accessible names and live-region messages components compose.
|
|
3
|
+
*
|
|
4
|
+
* A message is never assembled from translated fragments: word order, list
|
|
5
|
+
* joining and sentence punctuation differ by language. Each key is a whole
|
|
6
|
+
* phrase or a whole sentence with named placeholders, and a label built from
|
|
7
|
+
* several states joins complete sentences, each of which carries its own
|
|
8
|
+
* punctuation in its translation (`accessibility.sentence` turns a bare label
|
|
9
|
+
* into one).
|
|
10
|
+
*/
|
|
11
|
+
import type { I18nProvider } from './I18nProvider.js';
|
|
12
|
+
type Values = Record<string, unknown>;
|
|
13
|
+
/**
|
|
14
|
+
* Translate `key`, or interpolate the English `fallback` when the component was
|
|
15
|
+
* mounted without a provider.
|
|
16
|
+
*/
|
|
17
|
+
export declare function translate(i18n: I18nProvider | undefined, key: string, fallback: string, values?: Values): string;
|
|
18
|
+
/**
|
|
19
|
+
* Pluralize the plural group `key` for `count`, or pick from the English
|
|
20
|
+
* `fallback` forms when the component was mounted without a provider.
|
|
21
|
+
*/
|
|
22
|
+
export declare function translatePlural(i18n: I18nProvider | undefined, key: string, fallback: {
|
|
23
|
+
one: string;
|
|
24
|
+
other: string;
|
|
25
|
+
}, count: number, values?: Record<string, string | number>): string;
|
|
26
|
+
/** Join complete sentences, skipping the conditions that did not apply. */
|
|
27
|
+
export declare function joinSentences(...sentences: Array<string | false | null | undefined>): string;
|
|
28
|
+
/** A conjunction list in the provider's locale: "A, B and C", "A، B وC". */
|
|
29
|
+
export declare function formatList(i18n: I18nProvider | undefined, items: string[]): string;
|
|
30
|
+
/**
|
|
31
|
+
* True while an input method editor is composing, when Escape and Enter belong
|
|
32
|
+
* to the IME (cancel or commit the candidate) and a handler must not act on
|
|
33
|
+
* them. `keyCode` 229 covers engines that end composition before the event.
|
|
34
|
+
*/
|
|
35
|
+
export declare function isImeComposing(event: KeyboardEvent): boolean;
|
|
36
|
+
export {};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the accessible names and live-region messages components compose.
|
|
3
|
+
*
|
|
4
|
+
* A message is never assembled from translated fragments: word order, list
|
|
5
|
+
* joining and sentence punctuation differ by language. Each key is a whole
|
|
6
|
+
* phrase or a whole sentence with named placeholders, and a label built from
|
|
7
|
+
* several states joins complete sentences, each of which carries its own
|
|
8
|
+
* punctuation in its translation (`accessibility.sentence` turns a bare label
|
|
9
|
+
* into one).
|
|
10
|
+
*/
|
|
11
|
+
function interpolate(message, values) {
|
|
12
|
+
if (!values)
|
|
13
|
+
return message;
|
|
14
|
+
return message.replace(/\{(\w+)\}/g, (match, key) => (key in values ? String(values[key]) : match));
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Translate `key`, or interpolate the English `fallback` when the component was
|
|
18
|
+
* mounted without a provider.
|
|
19
|
+
*/
|
|
20
|
+
export function translate(i18n, key, fallback, values) {
|
|
21
|
+
return i18n ? i18n.t(key, fallback, values) : interpolate(fallback, values);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Pluralize the plural group `key` for `count`, or pick from the English
|
|
25
|
+
* `fallback` forms when the component was mounted without a provider.
|
|
26
|
+
*/
|
|
27
|
+
export function translatePlural(i18n, key, fallback, count, values) {
|
|
28
|
+
if (i18n?.plural)
|
|
29
|
+
return i18n.plural(key, { ...values, count });
|
|
30
|
+
const form = count === 1 ? 'one' : 'other';
|
|
31
|
+
return translate(i18n, `${key}.${form}`, fallback[form], { ...values, count });
|
|
32
|
+
}
|
|
33
|
+
/** Join complete sentences, skipping the conditions that did not apply. */
|
|
34
|
+
export function joinSentences(...sentences) {
|
|
35
|
+
return sentences.filter((sentence) => !!sentence).join(' ');
|
|
36
|
+
}
|
|
37
|
+
/** A conjunction list in the provider's locale: "A, B and C", "A، B وC". */
|
|
38
|
+
export function formatList(i18n, items) {
|
|
39
|
+
try {
|
|
40
|
+
return new Intl.ListFormat(i18n?.getLocale().replace(/_/g, '-') || 'en', { type: 'conjunction' }).format(items);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return items.join(', ');
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* True while an input method editor is composing, when Escape and Enter belong
|
|
48
|
+
* to the IME (cancel or commit the candidate) and a handler must not act on
|
|
49
|
+
* them. `keyCode` 229 covers engines that end composition before the event.
|
|
50
|
+
*/
|
|
51
|
+
export function isImeComposing(event) {
|
|
52
|
+
return event.isComposing || event.keyCode === 229;
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=accessible-text.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accessible-text.js","sourceRoot":"","sources":["../../src/core/accessible-text.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH,SAAS,WAAW,CAAC,OAAe,EAAE,MAAe;IACpD,IAAI,CAAC,MAAM;QAAE,OAAO,OAAO,CAAC;IAC5B,OAAO,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,IAAI,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AACrG,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,IAA8B,EAAE,GAAW,EAAE,QAAgB,EAAE,MAAe;IACvG,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAC7E,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,eAAe,CAC9B,IAA8B,EAC9B,GAAW,EACX,QAAwC,EACxC,KAAa,EACb,MAAwC;IAExC,IAAI,IAAI,EAAE,MAAM;QAAE,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IAChE,MAAM,IAAI,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC;IAC3C,OAAO,SAAS,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,IAAI,EAAE,EAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;AAChF,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,aAAa,CAAC,GAAG,SAAmD;IACnF,OAAO,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\nfunction interpolate(message: string, values?: Values): string {\n\tif (!values) return message;\n\treturn message.replace(/\\{(\\w+)\\}/g, (match, key) => (key in values ? String(values[key]) : match));\n}\n\n/**\n * Translate `key`, or interpolate the English `fallback` when the component was\n * mounted without a provider.\n */\nexport function translate(i18n: I18nProvider | undefined, key: string, fallback: string, values?: Values): string {\n\treturn i18n ? i18n.t(key, fallback, values) : interpolate(fallback, values);\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.\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\tif (i18n?.plural) return i18n.plural(key, { ...values, count });\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"]}
|