@barqjs/aria 0.0.0-stage → 0.2.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +293 -2
- package/package.json +347 -4
- package/src/breadcrumbs.tsx +296 -0
- package/src/button.tsx +342 -0
- package/src/calendar.tsx +1389 -0
- package/src/checkbox.tsx +570 -0
- package/src/collections.ts +976 -0
- package/src/color.ts +562 -0
- package/src/colorpicker.tsx +1478 -0
- package/src/combobox.tsx +2481 -0
- package/src/command.tsx +1184 -0
- package/src/date.ts +652 -0
- package/src/datefield.tsx +951 -0
- package/src/datepicker.tsx +556 -0
- package/src/dialog.tsx +890 -0
- package/src/disclosure.tsx +659 -0
- package/src/dom.ts +706 -0
- package/src/drawer.ts +674 -0
- package/src/focus.ts +1370 -0
- package/src/form.tsx +94 -0
- package/src/gridlist.tsx +563 -0
- package/src/i18n.ts +823 -0
- package/src/index.ts +1270 -0
- package/src/interactions/description.ts +73 -0
- package/src/interactions/flags.ts +35 -0
- package/src/interactions/focus-events.ts +218 -0
- package/src/interactions/focusable.ts +86 -0
- package/src/interactions/hover.ts +213 -0
- package/src/interactions/interact-outside.ts +123 -0
- package/src/interactions/keyboard.ts +105 -0
- package/src/interactions/listeners.ts +78 -0
- package/src/interactions/long-press.ts +160 -0
- package/src/interactions/modality.ts +416 -0
- package/src/interactions/move.ts +257 -0
- package/src/interactions/open-link.ts +193 -0
- package/src/interactions/press.ts +898 -0
- package/src/interactions/prevent-focus.ts +102 -0
- package/src/interactions/scroll-wheel.ts +43 -0
- package/src/interactions/text-selection.ts +77 -0
- package/src/interactions.ts +81 -0
- package/src/label.ts +128 -0
- package/src/link.tsx +381 -0
- package/src/listbox.tsx +721 -0
- package/src/live.ts +204 -0
- package/src/menu.tsx +2290 -0
- package/src/menubar.tsx +575 -0
- package/src/navigation.ts +735 -0
- package/src/numberfield.tsx +838 -0
- package/src/otp.ts +430 -0
- package/src/overlays.ts +1247 -0
- package/src/platform.ts +74 -0
- package/src/presence.ts +164 -0
- package/src/questionnaire.tsx +1712 -0
- package/src/radio.tsx +567 -0
- package/src/register-dom.ts +12 -0
- package/src/scroller.ts +1165 -0
- package/src/select.tsx +1665 -0
- package/src/selection.ts +1415 -0
- package/src/slider.tsx +1042 -0
- package/src/splitter.ts +1152 -0
- package/src/static-collection.ts +211 -0
- package/src/switch.tsx +186 -0
- package/src/table.tsx +0 -0
- package/src/tabs.tsx +1018 -0
- package/src/tag.tsx +452 -0
- package/src/textfield.tsx +417 -0
- package/src/toast.ts +658 -0
- package/src/toggle-input.tsx +48 -0
- package/src/toggle.ts +321 -0
- package/src/togglegroup.ts +365 -0
- package/src/toolbar.tsx +179 -0
- package/src/tooltip.tsx +657 -0
- package/src/utils.ts +758 -0
- package/src/validation.ts +447 -0
- package/src/virtualizer.tsx +674 -0
package/src/i18n.ts
ADDED
|
@@ -0,0 +1,823 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The locale, and everything that depends on it.
|
|
3
|
+
*
|
|
4
|
+
* Three things a widget cannot do with a plain string comparison:
|
|
5
|
+
*
|
|
6
|
+
* - Sort or search text. `"résumé".startsWith("resume")` is false, and a
|
|
7
|
+
* typeahead that answers that way is broken for most of the world. `Intl.Collator`
|
|
8
|
+
* with `usage: "search"` answers it correctly, per locale.
|
|
9
|
+
* - Choose left or right. Arrow keys in a listbox, the side a submenu opens on,
|
|
10
|
+
* and which end of a slider is the minimum all flip in a right-to-left locale.
|
|
11
|
+
* - Say a number or a date. `aria-valuetext` on a slider showing a currency has
|
|
12
|
+
* to be formatted, not concatenated.
|
|
13
|
+
*
|
|
14
|
+
* The locale is a signal, so a page that switches language updates every
|
|
15
|
+
* formatter without re-rendering anything that does not read one.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import {
|
|
19
|
+
type Accessor,
|
|
20
|
+
createContext,
|
|
21
|
+
getContext,
|
|
22
|
+
getOwner,
|
|
23
|
+
install,
|
|
24
|
+
createSignal,
|
|
25
|
+
} from "@barqjs/core";
|
|
26
|
+
import { isServer } from "@barqjs/web";
|
|
27
|
+
import { tryCleanup } from "@barqjs/primitives/utils";
|
|
28
|
+
import { access, type MaybeAccessor } from "./utils.ts";
|
|
29
|
+
|
|
30
|
+
export interface Locale {
|
|
31
|
+
/** A BCP 47 language tag. */
|
|
32
|
+
locale: string;
|
|
33
|
+
/** Which way the text runs. */
|
|
34
|
+
direction: "ltr" | "rtl";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// https://en.wikipedia.org/wiki/Right-to-left
|
|
38
|
+
const RTL_SCRIPTS = new Set([
|
|
39
|
+
"Adlm",
|
|
40
|
+
"Arab",
|
|
41
|
+
"Hebr",
|
|
42
|
+
"Mand",
|
|
43
|
+
"Mend",
|
|
44
|
+
"Nkoo",
|
|
45
|
+
"Rohg",
|
|
46
|
+
"Samr",
|
|
47
|
+
"Syrc",
|
|
48
|
+
"Thaa",
|
|
49
|
+
]);
|
|
50
|
+
|
|
51
|
+
const RTL_LANGUAGES = new Set([
|
|
52
|
+
"ae",
|
|
53
|
+
"ar",
|
|
54
|
+
"arc",
|
|
55
|
+
"bcc",
|
|
56
|
+
"bqi",
|
|
57
|
+
"ckb",
|
|
58
|
+
"dv",
|
|
59
|
+
"fa",
|
|
60
|
+
"glk",
|
|
61
|
+
"he",
|
|
62
|
+
"ku",
|
|
63
|
+
"mzn",
|
|
64
|
+
"nqo",
|
|
65
|
+
"pnb",
|
|
66
|
+
"ps",
|
|
67
|
+
"sd",
|
|
68
|
+
"ug",
|
|
69
|
+
"ur",
|
|
70
|
+
"yi",
|
|
71
|
+
]);
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Whether the locale is read right to left.
|
|
75
|
+
*
|
|
76
|
+
* By script rather than by language where the platform can tell us: Kurdish is
|
|
77
|
+
* written in both Arabic and Latin scripts, and the language tag alone gets it
|
|
78
|
+
* wrong half the time.
|
|
79
|
+
*/
|
|
80
|
+
export function isRTL(tag: string): boolean {
|
|
81
|
+
if (typeof Intl.Locale === "function") {
|
|
82
|
+
const locale = new Intl.Locale(tag).maximize();
|
|
83
|
+
const info = locale as Intl.Locale & {
|
|
84
|
+
getTextInfo?: () => { direction: string };
|
|
85
|
+
textInfo?: { direction: string };
|
|
86
|
+
};
|
|
87
|
+
const textInfo = typeof info.getTextInfo === "function" ? info.getTextInfo() : info.textInfo;
|
|
88
|
+
if (textInfo !== undefined) return textInfo.direction === "rtl";
|
|
89
|
+
if (locale.script !== undefined) return RTL_SCRIPTS.has(locale.script);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return RTL_LANGUAGES.has(tag.split("-")[0] as string);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The locale set on the page by a server-side localisation provider. */
|
|
96
|
+
const LOCALE_SYMBOL = Symbol.for("barq.aria.locale");
|
|
97
|
+
|
|
98
|
+
/** The browser's locale, right now. */
|
|
99
|
+
export function defaultLocale(): Locale {
|
|
100
|
+
let tag =
|
|
101
|
+
(typeof window !== "undefined" &&
|
|
102
|
+
(window as unknown as Record<symbol, string | undefined>)[LOCALE_SYMBOL]) ||
|
|
103
|
+
(typeof navigator !== "undefined" && navigator.language) ||
|
|
104
|
+
"en-US";
|
|
105
|
+
|
|
106
|
+
try {
|
|
107
|
+
Intl.DateTimeFormat.supportedLocalesOf([tag]);
|
|
108
|
+
} catch {
|
|
109
|
+
tag = "en-US";
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return { locale: tag, direction: isRTL(tag) ? "rtl" : "ltr" };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const [browserLocale, setBrowserLocale] = createSignal<Locale>(defaultLocale());
|
|
116
|
+
let languageListeners = 0;
|
|
117
|
+
|
|
118
|
+
function watchLanguage(): () => void {
|
|
119
|
+
if (isServer || typeof window === "undefined") return () => {};
|
|
120
|
+
const update = (): void => {
|
|
121
|
+
setBrowserLocale(defaultLocale());
|
|
122
|
+
};
|
|
123
|
+
if (languageListeners === 0) window.addEventListener("languagechange", update);
|
|
124
|
+
languageListeners++;
|
|
125
|
+
return () => {
|
|
126
|
+
languageListeners--;
|
|
127
|
+
if (languageListeners === 0) window.removeEventListener("languagechange", update);
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The locale every widget below reads. */
|
|
132
|
+
export const LocaleContext = createContext<Accessor<Locale> | null>(null);
|
|
133
|
+
|
|
134
|
+
export type ReadingDirection = "ltr" | "rtl";
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* A direction declared for a subtree on its own.
|
|
138
|
+
*
|
|
139
|
+
* Apart from the locale because the two are not the same decision: an English
|
|
140
|
+
* page mirrored to check a layout, or a left-to-right code sample inside an
|
|
141
|
+
* Arabic article, changes which way things run and not what language they are
|
|
142
|
+
* in. Every widget reads the direction through {@link useLocale}, so one
|
|
143
|
+
* declaration reaches the arrow keys, the submenu side and the slider's minimum
|
|
144
|
+
* end alike.
|
|
145
|
+
*/
|
|
146
|
+
export const DirectionContext = createContext<Accessor<ReadingDirection> | null>(null);
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* The locale in scope: the one an ancestor declared, or the browser's.
|
|
150
|
+
*
|
|
151
|
+
* ```tsx
|
|
152
|
+
* const locale = useLocale();
|
|
153
|
+
* <div dir={() => locale().direction} />
|
|
154
|
+
* ```
|
|
155
|
+
*/
|
|
156
|
+
export function useLocale(): Accessor<Locale> {
|
|
157
|
+
const provided = getContext(LocaleContext);
|
|
158
|
+
const declared = getContext(DirectionContext);
|
|
159
|
+
let base: Accessor<Locale>;
|
|
160
|
+
if (provided !== null && provided !== undefined) {
|
|
161
|
+
base = provided;
|
|
162
|
+
} else {
|
|
163
|
+
tryCleanup(watchLanguage());
|
|
164
|
+
base = browserLocale;
|
|
165
|
+
}
|
|
166
|
+
if (declared === null || declared === undefined) return base;
|
|
167
|
+
|
|
168
|
+
return (): Locale => {
|
|
169
|
+
const locale = base();
|
|
170
|
+
const direction = declared();
|
|
171
|
+
return locale.direction === direction ? locale : { locale: locale.locale, direction };
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Declare the locale for a subtree.
|
|
177
|
+
*
|
|
178
|
+
* Returns the props for the element that wraps it: `lang` and `dir` are not
|
|
179
|
+
* decoration, they are what tells the engine which way to lay text out and
|
|
180
|
+
* which font to pick.
|
|
181
|
+
*
|
|
182
|
+
* ```tsx
|
|
183
|
+
* const localeProps = provideLocale(() => "ar-EG");
|
|
184
|
+
* <div {...localeProps}>{props.children}</div>
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
export function provideLocale(tag: MaybeAccessor<string>): {
|
|
188
|
+
lang: Accessor<string>;
|
|
189
|
+
dir: Accessor<"ltr" | "rtl">;
|
|
190
|
+
} {
|
|
191
|
+
const value = (): Locale => {
|
|
192
|
+
const resolved = access(tag);
|
|
193
|
+
return { locale: resolved, direction: isRTL(resolved) ? "rtl" : "ltr" };
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const owner = getOwner();
|
|
197
|
+
if (owner !== null) {
|
|
198
|
+
install(owner, LocaleContext, () => value);
|
|
199
|
+
// The nearest declaration wins, so a locale declared under a direction
|
|
200
|
+
// has to replace it rather than be overridden by it.
|
|
201
|
+
install(owner, DirectionContext, () => () => value().direction);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return { lang: () => value().locale, dir: () => value().direction };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The direction in scope: the one an ancestor declared, or the locale's.
|
|
209
|
+
*
|
|
210
|
+
* ```tsx
|
|
211
|
+
* const direction = useDirection();
|
|
212
|
+
* const back = () => (direction() === "rtl" ? "ArrowRight" : "ArrowLeft");
|
|
213
|
+
* ```
|
|
214
|
+
*/
|
|
215
|
+
export function useDirection(): Accessor<ReadingDirection> {
|
|
216
|
+
const locale = useLocale();
|
|
217
|
+
return () => locale().direction;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* The direction declared for this subtree, or `undefined` where none was.
|
|
222
|
+
*
|
|
223
|
+
* For an element drawn outside the one that carries `dir`: a dialog or a menu
|
|
224
|
+
* is appended to the body, and nothing there says which way the text runs. It
|
|
225
|
+
* writes this as its own `dir`. Where nothing was declared it writes none,
|
|
226
|
+
* because the page's own `dir` is then the only statement there is and the
|
|
227
|
+
* browser's language must not be read over it.
|
|
228
|
+
*/
|
|
229
|
+
export function declaredDirection(): Accessor<ReadingDirection | undefined> {
|
|
230
|
+
const declared = getContext(DirectionContext);
|
|
231
|
+
return () => (declared === null || declared === undefined ? undefined : declared());
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Declare the direction for a subtree, leaving the locale as it is.
|
|
236
|
+
*
|
|
237
|
+
* Returns the `dir` for the element that wraps it, which is what makes the
|
|
238
|
+
* engine lay the text out that way too.
|
|
239
|
+
*
|
|
240
|
+
* ```tsx
|
|
241
|
+
* const directionProps = provideDirection(() => "rtl");
|
|
242
|
+
* <div {...directionProps}>{props.children}</div>
|
|
243
|
+
* ```
|
|
244
|
+
*/
|
|
245
|
+
export function provideDirection(direction: MaybeAccessor<ReadingDirection>): {
|
|
246
|
+
dir: Accessor<ReadingDirection>;
|
|
247
|
+
} {
|
|
248
|
+
const value = (): ReadingDirection => access(direction);
|
|
249
|
+
|
|
250
|
+
const owner = getOwner();
|
|
251
|
+
if (owner !== null) install(owner, DirectionContext, () => value);
|
|
252
|
+
|
|
253
|
+
return { dir: value };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
// Formatters
|
|
258
|
+
// ---------------------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* One instance per locale and option set, kept for the life of the page.
|
|
262
|
+
*
|
|
263
|
+
* Constructing an `Intl` formatter is expensive — tens of microseconds — and a
|
|
264
|
+
* list of a thousand rows formatting a number per row constructs a thousand of
|
|
265
|
+
* them unless something remembers.
|
|
266
|
+
*/
|
|
267
|
+
function memoised<O extends object, T>(
|
|
268
|
+
create: (locale: string, options?: O) => T,
|
|
269
|
+
): (locale: string, options?: O) => T {
|
|
270
|
+
const cache = new Map<string, T>();
|
|
271
|
+
return (locale: string, options?: O): T => {
|
|
272
|
+
const key = options === undefined ? locale : `${locale}:${JSON.stringify(options)}`;
|
|
273
|
+
let value = cache.get(key);
|
|
274
|
+
if (value === undefined) {
|
|
275
|
+
value = create(locale, options);
|
|
276
|
+
cache.set(key, value);
|
|
277
|
+
}
|
|
278
|
+
return value;
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const collators = memoised(
|
|
283
|
+
(locale: string, options?: Intl.CollatorOptions) => new Intl.Collator(locale, options),
|
|
284
|
+
);
|
|
285
|
+
|
|
286
|
+
/** An `Intl.Collator` for the locale in scope, cached. */
|
|
287
|
+
export function collator(options?: Intl.CollatorOptions): Accessor<Intl.Collator> {
|
|
288
|
+
const locale = useLocale();
|
|
289
|
+
return () => collators(locale().locale, options);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export interface Filter {
|
|
293
|
+
startsWith: (text: string, substring: string) => boolean;
|
|
294
|
+
endsWith: (text: string, substring: string) => boolean;
|
|
295
|
+
contains: (text: string, substring: string) => boolean;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Locale-aware substring matching, for a typeahead or an autocomplete.
|
|
300
|
+
*
|
|
301
|
+
* `String.prototype.includes` compares code points, so "resume" does not match
|
|
302
|
+
* "résumé" and "STRASSE" does not match "Straße". A search collator says both
|
|
303
|
+
* match, which is what a user typing without diacritics expects.
|
|
304
|
+
*/
|
|
305
|
+
export function filter(options?: Intl.CollatorOptions): Filter {
|
|
306
|
+
const search = collator({ usage: "search", ...options });
|
|
307
|
+
|
|
308
|
+
const compare = (a: string, b: string): boolean => search().compare(a, b) === 0;
|
|
309
|
+
|
|
310
|
+
return {
|
|
311
|
+
startsWith(text, substring) {
|
|
312
|
+
if (substring.length === 0) return true;
|
|
313
|
+
const normalised = text.normalize("NFC");
|
|
314
|
+
const needle = substring.normalize("NFC");
|
|
315
|
+
return compare(normalised.slice(0, needle.length), needle);
|
|
316
|
+
},
|
|
317
|
+
|
|
318
|
+
endsWith(text, substring) {
|
|
319
|
+
if (substring.length === 0) return true;
|
|
320
|
+
const normalised = text.normalize("NFC");
|
|
321
|
+
const needle = substring.normalize("NFC");
|
|
322
|
+
return compare(normalised.slice(-needle.length), needle);
|
|
323
|
+
},
|
|
324
|
+
|
|
325
|
+
contains(text, substring) {
|
|
326
|
+
if (substring.length === 0) return true;
|
|
327
|
+
const normalised = text.normalize("NFC");
|
|
328
|
+
const needle = substring.normalize("NFC");
|
|
329
|
+
// A sliding window rather than `indexOf`: the collator can call two
|
|
330
|
+
// strings of the same length equal without them being identical.
|
|
331
|
+
for (let at = 0; at + needle.length <= normalised.length; at++) {
|
|
332
|
+
if (compare(needle, normalised.slice(at, at + needle.length))) return true;
|
|
333
|
+
}
|
|
334
|
+
return false;
|
|
335
|
+
},
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const numberFormatters = memoised(
|
|
340
|
+
(locale: string, options?: Intl.NumberFormatOptions) => new Intl.NumberFormat(locale, options),
|
|
341
|
+
);
|
|
342
|
+
|
|
343
|
+
/** An `Intl.NumberFormat` for the locale in scope, cached. */
|
|
344
|
+
export function numberFormatter(options?: Intl.NumberFormatOptions): Accessor<Intl.NumberFormat> {
|
|
345
|
+
const locale = useLocale();
|
|
346
|
+
return () => numberFormatters(locale().locale, options);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// ---------------------------------------------------------------------------
|
|
350
|
+
// Parsing a number back
|
|
351
|
+
// ---------------------------------------------------------------------------
|
|
352
|
+
|
|
353
|
+
/** The characters a locale writes a number with. */
|
|
354
|
+
interface NumberSymbols {
|
|
355
|
+
minusSign: string;
|
|
356
|
+
plusSign?: string;
|
|
357
|
+
decimal?: string;
|
|
358
|
+
group?: string;
|
|
359
|
+
/** Everything in a formatted number that is not part of its VALUE. */
|
|
360
|
+
literals: RegExp;
|
|
361
|
+
numeral: RegExp;
|
|
362
|
+
index: (digit: string) => string;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const NON_LITERAL = new Set(["decimal", "fraction", "integer", "minusSign", "plusSign", "group"]);
|
|
366
|
+
|
|
367
|
+
/** Numbering systems worth trying when the locale's own does not match. */
|
|
368
|
+
const NUMBERING_SYSTEMS = ["latn", "arab", "hanidec", "deva", "beng", "fullwide"];
|
|
369
|
+
|
|
370
|
+
const ACCOUNTING_NEGATIVE = /^.*\(.*\).*$/;
|
|
371
|
+
|
|
372
|
+
function escapeRegex(value: string): string {
|
|
373
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function symbolsFor(
|
|
377
|
+
locale: string,
|
|
378
|
+
resolved: Intl.ResolvedNumberFormatOptions,
|
|
379
|
+
given: Intl.NumberFormatOptions,
|
|
380
|
+
): NumberSymbols {
|
|
381
|
+
// Every symbol at once: a negative number with a group separator and a
|
|
382
|
+
// fraction produces the minus sign, the group and the decimal in one pass,
|
|
383
|
+
// and a positive one produces the plus sign a `signDisplay` asked for.
|
|
384
|
+
const wide = new Intl.NumberFormat(locale, {
|
|
385
|
+
...resolved,
|
|
386
|
+
minimumSignificantDigits: 1,
|
|
387
|
+
maximumSignificantDigits: 21,
|
|
388
|
+
roundingIncrement: 1,
|
|
389
|
+
useGrouping: true,
|
|
390
|
+
});
|
|
391
|
+
const negative = wide.formatToParts(-10000.111);
|
|
392
|
+
const positive = wide.formatToParts(10000.111);
|
|
393
|
+
|
|
394
|
+
const minusSign = negative.find((part) => part.type === "minusSign")?.value ?? "-";
|
|
395
|
+
let plusSign = positive.find((part) => part.type === "plusSign")?.value;
|
|
396
|
+
if (
|
|
397
|
+
plusSign === undefined &&
|
|
398
|
+
(given.signDisplay === "always" || given.signDisplay === "exceptZero")
|
|
399
|
+
) {
|
|
400
|
+
plusSign = "+";
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// A percent format has no fraction digits by default and a significant-digit
|
|
404
|
+
// one may have none either, so the decimal separator is asked for
|
|
405
|
+
// separately.
|
|
406
|
+
const decimal = new Intl.NumberFormat(locale, {
|
|
407
|
+
...resolved,
|
|
408
|
+
minimumFractionDigits: 2,
|
|
409
|
+
maximumFractionDigits: 2,
|
|
410
|
+
})
|
|
411
|
+
.formatToParts(0.001)
|
|
412
|
+
.find((part) => part.type === "decimal")?.value;
|
|
413
|
+
|
|
414
|
+
const literalValues = [
|
|
415
|
+
...new Set(
|
|
416
|
+
negative.filter((part) => !NON_LITERAL.has(part.type)).map((part) => escapeRegex(part.value)),
|
|
417
|
+
),
|
|
418
|
+
].toSorted((a, b) => b.length - a.length);
|
|
419
|
+
|
|
420
|
+
// Whitespace and format characters go too: a narrow no-break space between
|
|
421
|
+
// the number and its currency symbol is not part of the number.
|
|
422
|
+
const literals =
|
|
423
|
+
literalValues.length === 0
|
|
424
|
+
? /\p{White_Space}|\p{Cf}/gu
|
|
425
|
+
: new RegExp(`${literalValues.join("|")}|\\p{White_Space}|\\p{Cf}`, "gu");
|
|
426
|
+
|
|
427
|
+
const digits = Array.from(
|
|
428
|
+
new Intl.NumberFormat(resolved.locale, { useGrouping: false }).format(9876543210),
|
|
429
|
+
).toReversed();
|
|
430
|
+
const indexes = new Map(digits.map((digit, at) => [digit, at]));
|
|
431
|
+
|
|
432
|
+
return {
|
|
433
|
+
minusSign,
|
|
434
|
+
plusSign,
|
|
435
|
+
decimal,
|
|
436
|
+
group: negative.find((part) => part.type === "group")?.value,
|
|
437
|
+
literals,
|
|
438
|
+
numeral: new RegExp(`[${digits.join("")}]`, "g"),
|
|
439
|
+
index: (digit) => String(indexes.get(digit)),
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
class NumberParserImpl {
|
|
444
|
+
readonly locale: string;
|
|
445
|
+
readonly formatter: Intl.NumberFormat;
|
|
446
|
+
readonly options: Intl.ResolvedNumberFormatOptions;
|
|
447
|
+
readonly symbols: NumberSymbols;
|
|
448
|
+
|
|
449
|
+
constructor(locale: string, options: Intl.NumberFormatOptions = {}) {
|
|
450
|
+
this.locale = locale;
|
|
451
|
+
this.formatter = new Intl.NumberFormat(locale, options);
|
|
452
|
+
this.options = this.formatter.resolvedOptions();
|
|
453
|
+
this.symbols = symbolsFor(locale, this.options, options);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* What is left after everything that is not the number itself.
|
|
458
|
+
*
|
|
459
|
+
* Also the place where a keyboard the locale does not have is forgiven: an
|
|
460
|
+
* ASCII minus for a locale that writes U+2212, a plain apostrophe for Swiss
|
|
461
|
+
* currency's U+2019 group, a comma for Arabic's decimal.
|
|
462
|
+
*/
|
|
463
|
+
sanitize(value: string): string {
|
|
464
|
+
const grouped = this.formatter.resolvedOptions().useGrouping !== false;
|
|
465
|
+
let text = value.replace(this.symbols.literals, "");
|
|
466
|
+
|
|
467
|
+
if (this.symbols.minusSign !== "-") text = text.split("-").join(this.symbols.minusSign);
|
|
468
|
+
|
|
469
|
+
if (this.options.numberingSystem === "arab") {
|
|
470
|
+
if (this.symbols.decimal !== undefined) {
|
|
471
|
+
text = text.split(",").join(this.symbols.decimal);
|
|
472
|
+
text = text.split(String.fromCharCode(1548)).join(this.symbols.decimal);
|
|
473
|
+
}
|
|
474
|
+
if (this.symbols.group !== undefined && grouped) {
|
|
475
|
+
text = text.split(".").join(this.symbols.group);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
if (this.symbols.group === "\u2019" && text.includes("'") && grouped) {
|
|
480
|
+
text = text.split("'").join(this.symbols.group);
|
|
481
|
+
}
|
|
482
|
+
if (this.symbols.group === "'" && text.includes("\u2019") && grouped) {
|
|
483
|
+
text = text.split("\u2019").join(this.symbols.group);
|
|
484
|
+
}
|
|
485
|
+
// The French group separator is a narrow no-break space, which no French
|
|
486
|
+
// keyboard has; an ordinary space and a no-break one both mean it.
|
|
487
|
+
if (this.symbols.group === "\u202f" && grouped) {
|
|
488
|
+
text = text.split(" ").join(this.symbols.group);
|
|
489
|
+
text = text.split("\u00a0").join(this.symbols.group);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
return text;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
parse(value: string): number {
|
|
496
|
+
const grouped = this.formatter.resolvedOptions().useGrouping !== false;
|
|
497
|
+
let text = this.sanitize(value);
|
|
498
|
+
|
|
499
|
+
if (this.symbols.group !== undefined) {
|
|
500
|
+
// A group separator where grouping is off is not a number at all.
|
|
501
|
+
if (!grouped && text.includes(this.symbols.group)) return Number.NaN;
|
|
502
|
+
text = text.split(this.symbols.group).join("");
|
|
503
|
+
}
|
|
504
|
+
if (this.symbols.decimal !== undefined) text = text.replace(this.symbols.decimal, ".");
|
|
505
|
+
text = text.replace(this.symbols.minusSign, "-");
|
|
506
|
+
text = text.replace(this.symbols.numeral, this.symbols.index);
|
|
507
|
+
|
|
508
|
+
if (this.options.style === "percent") {
|
|
509
|
+
// Divided on the STRING. Dividing 1.1 by 100 in binary floating point
|
|
510
|
+
// gives 0.011000000000000001, and the field would show it.
|
|
511
|
+
const negative = text.includes("-");
|
|
512
|
+
text = text.replace("-", "").replace("+", "");
|
|
513
|
+
let point = text.indexOf(".");
|
|
514
|
+
if (point === -1) point = text.length;
|
|
515
|
+
text = text.replace(".", "");
|
|
516
|
+
if (point - 2 === 0) text = `0.${text}`;
|
|
517
|
+
else if (point - 2 === -1) text = `0.0${text}`;
|
|
518
|
+
else if (point - 2 <= -2) text = "0.00";
|
|
519
|
+
else text = `${text.slice(0, point - 2)}.${text.slice(point - 2)}`;
|
|
520
|
+
if (negative) text = `-${text}`;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const parsed = text === "" ? Number.NaN : Number(text);
|
|
524
|
+
if (Number.isNaN(parsed)) return Number.NaN;
|
|
525
|
+
|
|
526
|
+
// A negative accounting value is written in parentheses, which sanitising
|
|
527
|
+
// strips along with every other literal.
|
|
528
|
+
if (this.options.currencySign === "accounting" && ACCOUNTING_NEGATIVE.test(value)) {
|
|
529
|
+
return -parsed;
|
|
530
|
+
}
|
|
531
|
+
return parsed;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Whether this could still BECOME a number.
|
|
536
|
+
*
|
|
537
|
+
* A field that rejected every keystroke that is not yet a number would
|
|
538
|
+
* reject the minus sign, and then the decimal point after it.
|
|
539
|
+
*/
|
|
540
|
+
isValidPartialNumber(value: string, minValue = -Infinity, maxValue = Infinity): boolean {
|
|
541
|
+
const grouped = this.formatter.resolvedOptions().useGrouping !== false;
|
|
542
|
+
let text = this.sanitize(value);
|
|
543
|
+
|
|
544
|
+
if (text.startsWith(this.symbols.minusSign) && minValue < 0) {
|
|
545
|
+
text = text.slice(this.symbols.minusSign.length);
|
|
546
|
+
} else if (
|
|
547
|
+
this.symbols.plusSign !== undefined &&
|
|
548
|
+
text.startsWith(this.symbols.plusSign) &&
|
|
549
|
+
maxValue > 0
|
|
550
|
+
) {
|
|
551
|
+
text = text.slice(this.symbols.plusSign.length);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
if (
|
|
555
|
+
this.symbols.decimal !== undefined &&
|
|
556
|
+
text.includes(this.symbols.decimal) &&
|
|
557
|
+
this.options.maximumFractionDigits === 0
|
|
558
|
+
) {
|
|
559
|
+
return false;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
if (this.symbols.group !== undefined && grouped) {
|
|
563
|
+
text = text.split(this.symbols.group).join("");
|
|
564
|
+
}
|
|
565
|
+
text = text.replace(this.symbols.numeral, "");
|
|
566
|
+
if (this.symbols.decimal !== undefined) text = text.replace(this.symbols.decimal, "");
|
|
567
|
+
|
|
568
|
+
return text.length === 0;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
const numberParsers = memoised(
|
|
573
|
+
(locale: string, options?: Intl.NumberFormatOptions) => new NumberParserImpl(locale, options),
|
|
574
|
+
);
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Reading a number back out of what a locale wrote.
|
|
578
|
+
*
|
|
579
|
+
* `Number("1.234,5")` is NaN in every locale that writes it that way, and
|
|
580
|
+
* `parseFloat` silently reads "1.234" instead, which is a hundredth of what
|
|
581
|
+
* the user typed. The symbols come from `Intl.NumberFormat.formatToParts`, so
|
|
582
|
+
* they are the ones the same options would have PRODUCED, and the numbering
|
|
583
|
+
* system is detected from the text rather than assumed.
|
|
584
|
+
*/
|
|
585
|
+
export class NumberParser {
|
|
586
|
+
#locale: string;
|
|
587
|
+
#options: Intl.NumberFormatOptions;
|
|
588
|
+
|
|
589
|
+
constructor(locale: string, options: Intl.NumberFormatOptions = {}) {
|
|
590
|
+
this.#locale = locale;
|
|
591
|
+
this.#options = options;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** The parser whose numbering system this text is written in. */
|
|
595
|
+
#for(value: string): NumberParserImpl {
|
|
596
|
+
const own = numberParsers(this.#locale, this.#options);
|
|
597
|
+
if (this.#locale.includes("-nu-") || own.isValidPartialNumber(value)) return own;
|
|
598
|
+
|
|
599
|
+
for (const system of NUMBERING_SYSTEMS) {
|
|
600
|
+
if (system === own.options.numberingSystem) continue;
|
|
601
|
+
const tagged = `${this.#locale}${this.#locale.includes("-u-") ? "-nu-" : "-u-nu-"}${system}`;
|
|
602
|
+
const parser = numberParsers(tagged, this.#options);
|
|
603
|
+
if (parser.isValidPartialNumber(value)) return parser;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
return own;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** The number, or NaN when the text is not one. */
|
|
610
|
+
parse(value: string): number {
|
|
611
|
+
return this.#for(value).parse(value);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** Whether the text could still become a number as the user keeps typing. */
|
|
615
|
+
isValidPartialNumber(value: string, minValue?: number, maxValue?: number): boolean {
|
|
616
|
+
return this.#for(value).isValidPartialNumber(value, minValue, maxValue);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** Which numbering system the text is written in. */
|
|
620
|
+
getNumberingSystem(value: string): string {
|
|
621
|
+
return this.#for(value).options.numberingSystem;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** A {@link NumberParser} for the locale in scope. */
|
|
626
|
+
export function numberParser(options?: Intl.NumberFormatOptions): Accessor<NumberParser> {
|
|
627
|
+
const locale = useLocale();
|
|
628
|
+
return () => new NumberParser(locale().locale, options);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
const dateFormatters = memoised(
|
|
632
|
+
(locale: string, options?: Intl.DateTimeFormatOptions) =>
|
|
633
|
+
new Intl.DateTimeFormat(locale, options),
|
|
634
|
+
);
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* An `Intl.DateTimeFormat` for the locale in scope, cached.
|
|
638
|
+
*
|
|
639
|
+
* The locale in scope can only be found while there is an owner. A caller that
|
|
640
|
+
* formats later, from an event handler, passes the one it read during setup.
|
|
641
|
+
*/
|
|
642
|
+
export function dateFormatter(
|
|
643
|
+
options?: Intl.DateTimeFormatOptions,
|
|
644
|
+
locale: Accessor<Locale> = useLocale(),
|
|
645
|
+
): Accessor<Intl.DateTimeFormat> {
|
|
646
|
+
return () => dateFormatters(locale().locale, options);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
const listFormatters = memoised(
|
|
650
|
+
(locale: string, options?: Intl.ListFormatOptions) => new Intl.ListFormat(locale, options),
|
|
651
|
+
);
|
|
652
|
+
|
|
653
|
+
/** An `Intl.ListFormat` for the locale in scope, cached. */
|
|
654
|
+
export function listFormatter(options?: Intl.ListFormatOptions): Accessor<Intl.ListFormat> {
|
|
655
|
+
const locale = useLocale();
|
|
656
|
+
return () => listFormatters(locale().locale, options);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// ---------------------------------------------------------------------------
|
|
660
|
+
// Localized strings
|
|
661
|
+
// ---------------------------------------------------------------------------
|
|
662
|
+
|
|
663
|
+
export type Variables = Record<string, string | number | boolean> | undefined;
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* One message. A function when it needs the count, the gender or a number
|
|
667
|
+
* formatted, which is most of the messages a widget produces.
|
|
668
|
+
*/
|
|
669
|
+
export type LocalizedString = string | ((variables: Variables, format: StringFormatter) => string);
|
|
670
|
+
|
|
671
|
+
export type LocalizedStrings<K extends string = string> = Record<
|
|
672
|
+
string,
|
|
673
|
+
Record<K, LocalizedString>
|
|
674
|
+
>;
|
|
675
|
+
|
|
676
|
+
function languageOf(tag: string): string {
|
|
677
|
+
if (typeof Intl.Locale === "function") return new Intl.Locale(tag).language;
|
|
678
|
+
return tag.split("-")[0] as string;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
function scriptOf(tag: string): string | undefined {
|
|
682
|
+
if (typeof Intl.Locale === "function") return new Intl.Locale(tag).script;
|
|
683
|
+
return undefined;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Every translation of a widget's strings, with the fallback rules.
|
|
688
|
+
*
|
|
689
|
+
* A locale with no exact entry falls back by script first and language second:
|
|
690
|
+
* `sr-Latn-RS` must reach `sr-Latn` rather than `sr`, because the two are
|
|
691
|
+
* written in different alphabets and one is unreadable to a reader of the
|
|
692
|
+
* other.
|
|
693
|
+
*/
|
|
694
|
+
export class StringDictionary<K extends string = string> {
|
|
695
|
+
#strings: LocalizedStrings<K>;
|
|
696
|
+
#fallback: string;
|
|
697
|
+
|
|
698
|
+
constructor(strings: LocalizedStrings<K>, fallback = "en-US") {
|
|
699
|
+
// Entries a locale-pruning build step emptied are dropped, not kept as
|
|
700
|
+
// an empty object that would shadow the fallback.
|
|
701
|
+
this.#strings = Object.fromEntries(Object.entries(strings).filter(([, value]) => value));
|
|
702
|
+
this.#fallback = fallback;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
forLocale(locale: string): Record<K, LocalizedString> {
|
|
706
|
+
const cached = this.#strings[locale];
|
|
707
|
+
if (cached !== undefined) return cached;
|
|
708
|
+
|
|
709
|
+
const resolved = this.#resolve(locale);
|
|
710
|
+
this.#strings[locale] = resolved;
|
|
711
|
+
return resolved;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
get(key: K, locale: string): LocalizedString {
|
|
715
|
+
const string = this.forLocale(locale)[key];
|
|
716
|
+
if (string === undefined) {
|
|
717
|
+
throw new Error(`No message "${key}" for locale "${locale}".`);
|
|
718
|
+
}
|
|
719
|
+
return string;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
#resolve(locale: string): Record<K, LocalizedString> {
|
|
723
|
+
const language = languageOf(locale);
|
|
724
|
+
|
|
725
|
+
const script = scriptOf(locale);
|
|
726
|
+
if (script !== undefined) {
|
|
727
|
+
const withScript = this.#strings[`${language}-${script}`];
|
|
728
|
+
if (withScript !== undefined) return withScript;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
const byLanguage = this.#strings[language];
|
|
732
|
+
if (byLanguage !== undefined) return byLanguage;
|
|
733
|
+
|
|
734
|
+
for (const key in this.#strings) {
|
|
735
|
+
if (key.startsWith(`${language}-`)) return this.#strings[key] as Record<K, LocalizedString>;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
return this.#strings[this.#fallback] as Record<K, LocalizedString>;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
const pluralRules = new Map<string, Intl.PluralRules>();
|
|
743
|
+
|
|
744
|
+
/** Formats one dictionary's messages for one locale. */
|
|
745
|
+
export class StringFormatter<K extends string = string> {
|
|
746
|
+
#locale: string;
|
|
747
|
+
#strings: StringDictionary<K>;
|
|
748
|
+
|
|
749
|
+
constructor(locale: string, strings: StringDictionary<K>) {
|
|
750
|
+
this.#locale = locale;
|
|
751
|
+
this.#strings = strings;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
format(key: K, variables?: Variables): string {
|
|
755
|
+
const message = this.#strings.get(key, this.#locale);
|
|
756
|
+
return typeof message === "function" ? message(variables, this) : message;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** The branch for `count`, by the locale's own plural categories. */
|
|
760
|
+
plural(
|
|
761
|
+
count: number,
|
|
762
|
+
options: Record<string, string | (() => string)>,
|
|
763
|
+
type: Intl.PluralRuleType = "cardinal",
|
|
764
|
+
): string {
|
|
765
|
+
// An exact form wins: "no items" reads better than "0 items".
|
|
766
|
+
const exact = options[`=${count}`];
|
|
767
|
+
if (exact !== undefined) return typeof exact === "function" ? exact() : exact;
|
|
768
|
+
|
|
769
|
+
const key = `${this.#locale}:${type}`;
|
|
770
|
+
let rules = pluralRules.get(key);
|
|
771
|
+
if (rules === undefined) {
|
|
772
|
+
rules = new Intl.PluralRules(this.#locale, { type });
|
|
773
|
+
pluralRules.set(key, rules);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const branch = options[rules.select(count)] ?? options.other;
|
|
777
|
+
if (branch === undefined) return "";
|
|
778
|
+
return typeof branch === "function" ? branch() : branch;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/** The branch for a value that is not a number: a gender, a state. */
|
|
782
|
+
select(options: Record<string, string | (() => string)>, value: string): string {
|
|
783
|
+
const branch = options[value] ?? options.other;
|
|
784
|
+
if (branch === undefined) return "";
|
|
785
|
+
return typeof branch === "function" ? branch() : branch;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
number(value: number): string {
|
|
789
|
+
return numberFormatters(this.#locale).format(value);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
const formatterCache = new WeakMap<StringDictionary, Map<string, StringFormatter>>();
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* A formatter for a dictionary, in the locale in scope.
|
|
797
|
+
*
|
|
798
|
+
* ```ts
|
|
799
|
+
* const strings = new StringDictionary({ "en-US": { close: "Close" } });
|
|
800
|
+
* const message = stringFormatter(strings);
|
|
801
|
+
* <button aria-label={() => message().format("close")} />
|
|
802
|
+
* ```
|
|
803
|
+
*/
|
|
804
|
+
export function stringFormatter<K extends string>(
|
|
805
|
+
strings: StringDictionary<K>,
|
|
806
|
+
): Accessor<StringFormatter<K>> {
|
|
807
|
+
const locale = useLocale();
|
|
808
|
+
|
|
809
|
+
return () => {
|
|
810
|
+
const tag = locale().locale;
|
|
811
|
+
let byLocale = formatterCache.get(strings);
|
|
812
|
+
if (byLocale === undefined) {
|
|
813
|
+
byLocale = new Map();
|
|
814
|
+
formatterCache.set(strings, byLocale);
|
|
815
|
+
}
|
|
816
|
+
let formatter = byLocale.get(tag);
|
|
817
|
+
if (formatter === undefined) {
|
|
818
|
+
formatter = new StringFormatter(tag, strings);
|
|
819
|
+
byLocale.set(tag, formatter);
|
|
820
|
+
}
|
|
821
|
+
return formatter;
|
|
822
|
+
};
|
|
823
|
+
}
|