@zerolith/i18n 0.0.0-stage → 0.1.0-alpha.10

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/src/index.ts ADDED
@@ -0,0 +1,241 @@
1
+ /**
2
+ * @zerolith/i18n: the locale layer, built on `Intl` with nothing shipped.
3
+ * Negotiation of the request's or the browser's languages against the
4
+ * locales an application supports, the current locale and its direction
5
+ * as signals, the document's `lang` and `dir`, and formatters cached per
6
+ * locale. Message catalogs are compiled ahead of time by
7
+ * `@zerolith/i18n/compile` into plain functions, so no message runtime
8
+ * exists here either.
9
+ */
10
+ import { type ReadableSignal, type Signal, computed, effect, signal } from "zerolith";
11
+
12
+ /** One entry of an `Accept-Language` header or of `navigator.languages`. */
13
+ export interface LanguageRange
14
+ {
15
+ /** The language tag, or `*` for any language, as written before any `;` parameters. */
16
+ readonly range: string;
17
+ /** The entry's `q` weight between 0 and 1, rounded to three decimals; 1 when the entry gives none. */
18
+ readonly quality: number;
19
+ }
20
+
21
+ /** Parses an `Accept-Language` header into ranges ordered by quality, dropping those with quality zero. */
22
+ export function parseAcceptLanguage(header: string | null | undefined): LanguageRange[]
23
+ {
24
+ if (header === null || header === undefined || header.trim() === "")
25
+ {
26
+ return [];
27
+ }
28
+ const ranges: LanguageRange[] = [];
29
+ for (const [index, part] of header.split(",").entries())
30
+ {
31
+ const [rawRange = "", ...parameters] = part.split(";");
32
+ const range = rawRange.trim();
33
+ if (range === "")
34
+ {
35
+ continue;
36
+ }
37
+ let quality = 1;
38
+ for (const parameter of parameters)
39
+ {
40
+ const [key = "", value = ""] = parameter.split("=");
41
+ if (key.trim().toLowerCase() === "q")
42
+ {
43
+ const parsed = Number(value.trim());
44
+ quality = Number.isFinite(parsed) ? Math.min(1, Math.max(0, parsed)) : 0;
45
+ }
46
+ }
47
+ if (quality > 0)
48
+ {
49
+ ranges.push({ range, quality: quality - index * 1e-9 });
50
+ }
51
+ }
52
+ return ranges.toSorted((a, b) => b.quality - a.quality).map(({ range, quality }) => ({ range, quality: Math.round(quality * 1000) / 1000 }));
53
+ }
54
+
55
+ function canonical(tag: string): string
56
+ {
57
+ try
58
+ {
59
+ return Intl.getCanonicalLocales(tag)[0] ?? tag;
60
+ }
61
+ catch
62
+ {
63
+ return tag;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Picks the supported locale that best matches what was requested: an
69
+ * `Accept-Language` header, `navigator.languages`, or one tag. Each range
70
+ * is tried in order of quality, first as an exact match, then by dropping
71
+ * subtags from the end as RFC 4647 lookup does, then as the language of a
72
+ * more specific supported locale, preferring one written in the same
73
+ * script, so `zh-HK` finds `zh-TW` before `zh-CN`. `*` and no match at all
74
+ * give `fallback`.
75
+ */
76
+ export function negotiateLocale(requested: string | readonly string[] | null | undefined, supported: readonly string[], fallback: string): string
77
+ {
78
+ const ranges = typeof requested === "string" ? parseAcceptLanguage(requested).map((entry) => entry.range) : [...(requested ?? [])];
79
+ const candidates = supported.map((tag) => ({ tag, lower: canonical(tag).toLowerCase() }));
80
+ for (const range of ranges)
81
+ {
82
+ const wanted = canonical(range).toLowerCase();
83
+ if (wanted === "*")
84
+ {
85
+ return fallback;
86
+ }
87
+ for (let prefix = wanted; prefix !== ""; prefix = prefix.includes("-") ? prefix.slice(0, prefix.lastIndexOf("-")) : "")
88
+ {
89
+ const exact = candidates.find((candidate) => candidate.lower === prefix);
90
+ if (exact !== undefined)
91
+ {
92
+ return exact.tag;
93
+ }
94
+ }
95
+ const language = wanted.split("-")[0] ?? wanted;
96
+ const related = candidates.filter((candidate) => candidate.lower.startsWith(`${language}-`));
97
+ if (related.length > 0)
98
+ {
99
+ const script = scriptOf(range);
100
+ return (related.find((candidate) => scriptOf(candidate.tag) === script) ?? related[0])?.tag ?? fallback;
101
+ }
102
+ }
103
+ return fallback;
104
+ }
105
+
106
+ /** The script a locale is written in, with the likely script filled in, as `Hant` for `zh-TW`; undefined for a tag that does not parse. */
107
+ function scriptOf(tag: string): string | undefined
108
+ {
109
+ try
110
+ {
111
+ return new Intl.Locale(tag).maximize().script;
112
+ }
113
+ catch
114
+ {
115
+ return undefined;
116
+ }
117
+ }
118
+
119
+ /** The scripts written right to left, by their ISO 15924 codes in lowercase. */
120
+ const RTL_SCRIPTS: ReadonlySet<string> = new Set(["adlm", "arab", "hebr", "mand", "mend", "nkoo", "rohg", "samr", "syrc", "thaa", "yezi"]);
121
+
122
+ /** The writing direction of a locale, from `Intl.Locale` where the engine provides it and otherwise from its script, the likely one when the tag names none, as engines decide. */
123
+ export function localeDirection(locale: string): "ltr" | "rtl"
124
+ {
125
+ try
126
+ {
127
+ const parsed = new Intl.Locale(locale);
128
+ const withInfo = parsed as Intl.Locale & { getTextInfo?: () => { direction: string }; textInfo?: { direction: string } };
129
+ const info = withInfo.getTextInfo?.() ?? withInfo.textInfo;
130
+ if (info !== undefined)
131
+ {
132
+ return info.direction === "rtl" ? "rtl" : "ltr";
133
+ }
134
+ return RTL_SCRIPTS.has((parsed.maximize().script ?? "").toLowerCase()) ? "rtl" : "ltr";
135
+ }
136
+ catch
137
+ {
138
+ return "ltr";
139
+ }
140
+ }
141
+
142
+ /** Options for `createLocale`. */
143
+ export interface LocaleOptions
144
+ {
145
+ /** The locales the application ships, most preferred first. */
146
+ supported: readonly string[];
147
+ /** The locale used when nothing matches, one of `supported`. Defaults to the first supported one. */
148
+ fallback?: string;
149
+ /** What to negotiate from at first: an `Accept-Language` header, `navigator.languages`, or a tag. Defaults to the fallback. */
150
+ initial?: string | readonly string[] | null;
151
+ }
152
+
153
+ /** The current locale as state. */
154
+ export interface LocaleState
155
+ {
156
+ /** The current locale, always one of `supported`. */
157
+ readonly locale: ReadableSignal<string>;
158
+ /** The writing direction of the current locale. */
159
+ readonly direction: ReadableSignal<"ltr" | "rtl">;
160
+ /** A copy of the `supported` option, in the same order; `set` negotiates against it. */
161
+ readonly supported: readonly string[];
162
+ /** Switches locales after negotiating the request against `supported`. */
163
+ set(requested: string | readonly string[]): void;
164
+ }
165
+
166
+ /** Creates the locale state for an application. Throws a `TypeError` when `supported` is empty or `fallback` is not one of its locales, since the locale must always be one of them. */
167
+ export function createLocale(options: LocaleOptions): LocaleState
168
+ {
169
+ const supported = [...options.supported];
170
+ if (supported.length === 0)
171
+ {
172
+ throw new TypeError("zerolith/i18n: createLocale needs at least one supported locale");
173
+ }
174
+ const fallback = options.fallback === undefined ? (supported[0] ?? "") : supported.find((tag) => canonical(tag).toLowerCase() === canonical(options.fallback ?? "").toLowerCase());
175
+ if (fallback === undefined)
176
+ {
177
+ throw new TypeError(`zerolith/i18n: the fallback ${options.fallback ?? ""} is not one of the supported locales, ${supported.join(", ")}`);
178
+ }
179
+ const locale: Signal<string> = signal(negotiateLocale(options.initial ?? fallback, supported, fallback), { name: "locale" });
180
+ return {
181
+ locale,
182
+ direction: computed(() => localeDirection(locale.get())),
183
+ supported,
184
+ set(requested)
185
+ {
186
+ locale.set(negotiateLocale(requested, supported, fallback));
187
+ }
188
+ };
189
+ }
190
+
191
+ /** Keeps the document's `lang` and `dir` attributes in step with the locale; returns the effect's disposer. */
192
+ export function applyLocale(state: LocaleState, doc: Document = document): () => void
193
+ {
194
+ return effect(() =>
195
+ {
196
+ doc.documentElement.lang = state.locale.get();
197
+ doc.documentElement.dir = state.direction.get();
198
+ });
199
+ }
200
+
201
+ /** Formatters for the current locale; each reads the locale signal when called, so a computed value or template re-renders on a locale change. */
202
+ export interface Formatters
203
+ {
204
+ /** Formats a number with `Intl.NumberFormat`. */
205
+ number(value: number, options?: Intl.NumberFormatOptions): string;
206
+ /** Formats a `Date`, or a timestamp in milliseconds since the epoch, with `Intl.DateTimeFormat`. */
207
+ date(value: Date | number, options?: Intl.DateTimeFormatOptions): string;
208
+ /** Formats a time `value` units of `unit` away from now with `Intl.RelativeTimeFormat`, such as `in 2 hours`; a negative value lies in the past. */
209
+ relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;
210
+ /** Joins strings into a list with `Intl.ListFormat`, such as `a, b, and c` in English. */
211
+ list(values: Iterable<string>, options?: Intl.ListFormatOptions): string;
212
+ /** Selects the plural category of a number with `Intl.PluralRules`, such as `one` or `other`, for choosing a message variant. */
213
+ plural(value: number, options?: Intl.PluralRulesOptions): Intl.LDMLPluralRule;
214
+ }
215
+
216
+ const cache = new Map<string, unknown>();
217
+
218
+ function cached<T>(kind: string, locale: string, options: object | undefined, create: () => T): T
219
+ {
220
+ const key = `${kind}\u0000${locale}\u0000${options === undefined ? "" : JSON.stringify(options)}`;
221
+ let instance = cache.get(key) as T | undefined;
222
+ if (instance === undefined)
223
+ {
224
+ instance = create();
225
+ cache.set(key, instance);
226
+ }
227
+ return instance;
228
+ }
229
+
230
+ /** Creates formatters over a locale, given as a signal or as a fixed tag. Instances are cached per locale and options. */
231
+ export function formatters(locale: ReadableSignal<string> | string): Formatters
232
+ {
233
+ const current = (): string => (typeof locale === "string" ? locale : locale.get());
234
+ return {
235
+ number: (value, options) => cached("number", current(), options, () => new Intl.NumberFormat(current(), options)).format(value),
236
+ date: (value, options) => cached("date", current(), options, () => new Intl.DateTimeFormat(current(), options)).format(value),
237
+ relative: (value, unit, options) => cached("relative", current(), options, () => new Intl.RelativeTimeFormat(current(), options)).format(value, unit),
238
+ list: (values, options) => cached("list", current(), options, () => new Intl.ListFormat(current(), options)).format(values),
239
+ plural: (value, options) => cached("plural", current(), options, () => new Intl.PluralRules(current(), options)).select(value)
240
+ };
241
+ }