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

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,214 @@
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
+ readonly range: string;
16
+ readonly quality: number;
17
+ }
18
+
19
+ /** Parses an `Accept-Language` header into ranges ordered by quality, dropping those with quality zero. */
20
+ export function parseAcceptLanguage(header: string | null | undefined): LanguageRange[]
21
+ {
22
+ if (header === null || header === undefined || header.trim() === "")
23
+ {
24
+ return [];
25
+ }
26
+ const ranges: LanguageRange[] = [];
27
+ for (const [index, part] of header.split(",").entries())
28
+ {
29
+ const [rawRange = "", ...parameters] = part.split(";");
30
+ const range = rawRange.trim();
31
+ if (range === "")
32
+ {
33
+ continue;
34
+ }
35
+ let quality = 1;
36
+ for (const parameter of parameters)
37
+ {
38
+ const [key = "", value = ""] = parameter.split("=");
39
+ if (key.trim().toLowerCase() === "q")
40
+ {
41
+ const parsed = Number(value.trim());
42
+ quality = Number.isFinite(parsed) ? Math.min(1, Math.max(0, parsed)) : 0;
43
+ }
44
+ }
45
+ if (quality > 0)
46
+ {
47
+ ranges.push({ range, quality: quality - index * 1e-9 });
48
+ }
49
+ }
50
+ return ranges.toSorted((a, b) => b.quality - a.quality).map(({ range, quality }) => ({ range, quality: Math.round(quality * 1000) / 1000 }));
51
+ }
52
+
53
+ function canonical(tag: string): string
54
+ {
55
+ try
56
+ {
57
+ return Intl.getCanonicalLocales(tag)[0] ?? tag;
58
+ }
59
+ catch
60
+ {
61
+ return tag;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Picks the supported locale that best matches what was requested: an
67
+ * `Accept-Language` header, `navigator.languages`, or one tag. Each range
68
+ * is tried in order of quality, first as an exact match, then by dropping
69
+ * subtags from the end as RFC 4647 lookup does, then as the language of a
70
+ * more specific supported locale. `*` and no match at all give `fallback`.
71
+ */
72
+ export function negotiateLocale(requested: string | readonly string[] | null | undefined, supported: readonly string[], fallback: string): string
73
+ {
74
+ const ranges = typeof requested === "string" ? parseAcceptLanguage(requested).map((entry) => entry.range) : [...(requested ?? [])];
75
+ const candidates = supported.map((tag) => ({ tag, lower: canonical(tag).toLowerCase() }));
76
+ for (const range of ranges)
77
+ {
78
+ const wanted = canonical(range).toLowerCase();
79
+ if (wanted === "*")
80
+ {
81
+ return fallback;
82
+ }
83
+ for (let prefix = wanted; prefix !== ""; prefix = prefix.includes("-") ? prefix.slice(0, prefix.lastIndexOf("-")) : "")
84
+ {
85
+ const exact = candidates.find((candidate) => candidate.lower === prefix);
86
+ if (exact !== undefined)
87
+ {
88
+ return exact.tag;
89
+ }
90
+ }
91
+ const language = wanted.split("-")[0] ?? wanted;
92
+ const related = candidates.find((candidate) => candidate.lower.startsWith(`${language}-`));
93
+ if (related !== undefined)
94
+ {
95
+ return related.tag;
96
+ }
97
+ }
98
+ return fallback;
99
+ }
100
+
101
+ const RTL_LANGUAGES = new Set(["ar", "arc", "ckb", "dv", "fa", "he", "iw", "ks", "ku", "nqo", "pa-arab", "ps", "sd", "syr", "ug", "ur", "yi"]);
102
+
103
+ /** The writing direction of a locale, from `Intl.Locale` where the engine provides it and from the script or language otherwise. */
104
+ export function localeDirection(locale: string): "ltr" | "rtl"
105
+ {
106
+ try
107
+ {
108
+ const parsed = new Intl.Locale(locale);
109
+ const withInfo = parsed as Intl.Locale & { getTextInfo?: () => { direction: string }; textInfo?: { direction: string } };
110
+ const info = withInfo.getTextInfo?.() ?? withInfo.textInfo;
111
+ if (info !== undefined)
112
+ {
113
+ return info.direction === "rtl" ? "rtl" : "ltr";
114
+ }
115
+ const language = parsed.language.toLowerCase();
116
+ const script = parsed.script?.toLowerCase();
117
+ if (script === "arab" || script === "hebr" || script === "thaa" || script === "syrc" || script === "nkoo")
118
+ {
119
+ return "rtl";
120
+ }
121
+ return RTL_LANGUAGES.has(language) || RTL_LANGUAGES.has(`${language}-${script ?? ""}`) ? "rtl" : "ltr";
122
+ }
123
+ catch
124
+ {
125
+ return "ltr";
126
+ }
127
+ }
128
+
129
+ /** Options for `createLocale`. */
130
+ export interface LocaleOptions
131
+ {
132
+ /** The locales the application ships, most preferred first. */
133
+ supported: readonly string[];
134
+ /** The locale used when nothing matches. Defaults to the first supported one. */
135
+ fallback?: string;
136
+ /** What to negotiate from at first: an `Accept-Language` header, `navigator.languages`, or a tag. Defaults to the fallback. */
137
+ initial?: string | readonly string[] | null;
138
+ }
139
+
140
+ /** The current locale as state. */
141
+ export interface LocaleState
142
+ {
143
+ /** The current locale, always one of `supported`. */
144
+ readonly locale: ReadableSignal<string>;
145
+ /** The writing direction of the current locale. */
146
+ readonly direction: ReadableSignal<"ltr" | "rtl">;
147
+ readonly supported: readonly string[];
148
+ /** Switches locales after negotiating the request against `supported`. */
149
+ set(requested: string | readonly string[]): void;
150
+ }
151
+
152
+ /** Creates the locale state for an application. */
153
+ export function createLocale(options: LocaleOptions): LocaleState
154
+ {
155
+ const supported = [...options.supported];
156
+ const fallback = options.fallback ?? supported[0] ?? "en";
157
+ const locale: Signal<string> = signal(negotiateLocale(options.initial ?? fallback, supported, fallback), { name: "locale" });
158
+ return {
159
+ locale,
160
+ direction: computed(() => localeDirection(locale.get())),
161
+ supported,
162
+ set(requested)
163
+ {
164
+ locale.set(negotiateLocale(requested, supported, fallback));
165
+ }
166
+ };
167
+ }
168
+
169
+ /** Keeps the document's `lang` and `dir` attributes in step with the locale; returns the effect's disposer. */
170
+ export function applyLocale(state: LocaleState, doc: Document = document): () => void
171
+ {
172
+ return effect(() =>
173
+ {
174
+ doc.documentElement.lang = state.locale.get();
175
+ doc.documentElement.dir = state.direction.get();
176
+ });
177
+ }
178
+
179
+ /** Formatters for the current locale; each reads the locale signal when called, so a computed value or template re-renders on a locale change. */
180
+ export interface Formatters
181
+ {
182
+ number(value: number, options?: Intl.NumberFormatOptions): string;
183
+ date(value: Date | number, options?: Intl.DateTimeFormatOptions): string;
184
+ relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;
185
+ list(values: Iterable<string>, options?: Intl.ListFormatOptions): string;
186
+ plural(value: number, options?: Intl.PluralRulesOptions): Intl.LDMLPluralRule;
187
+ }
188
+
189
+ const cache = new Map<string, unknown>();
190
+
191
+ function cached<T>(kind: string, locale: string, options: object | undefined, create: () => T): T
192
+ {
193
+ const key = `${kind}\u0000${locale}\u0000${options === undefined ? "" : JSON.stringify(options)}`;
194
+ let instance = cache.get(key) as T | undefined;
195
+ if (instance === undefined)
196
+ {
197
+ instance = create();
198
+ cache.set(key, instance);
199
+ }
200
+ return instance;
201
+ }
202
+
203
+ /** Creates formatters over a locale, given as a signal or as a fixed tag. Instances are cached per locale and options. */
204
+ export function formatters(locale: ReadableSignal<string> | string): Formatters
205
+ {
206
+ const current = (): string => (typeof locale === "string" ? locale : locale.get());
207
+ return {
208
+ number: (value, options) => cached("number", current(), options, () => new Intl.NumberFormat(current(), options)).format(value),
209
+ date: (value, options) => cached("date", current(), options, () => new Intl.DateTimeFormat(current(), options)).format(value),
210
+ relative: (value, unit, options) => cached("relative", current(), options, () => new Intl.RelativeTimeFormat(current(), options)).format(value, unit),
211
+ list: (values, options) => cached("list", current(), options, () => new Intl.ListFormat(current(), options)).format(values),
212
+ plural: (value, options) => cached("plural", current(), options, () => new Intl.PluralRules(current(), options)).select(value)
213
+ };
214
+ }