i18n: dependency-free message runtime, catalog checks, plugin strings, native strings
- runtime/i18n.ts: ICU-lite messages (placeholders as text, Intl.PluralRules plurals with exact
forms, selectordinal, select, number/date/time), fallback chains (pt-BR -> pt -> en, ar-x-fm ->
ar), X and legacy code aliases, RTL by locale, lazy catalogs, live onChange. Apostrophes are
literal except right before { } # or another apostrophe.
- runtime/i18nCheck.ts: rules for contributed catalogs (shape, keys, syntax, placeholder parity,
select options, markup/control characters, lengths). An argument English only uses to choose a
plural form may be dropped; missing plural forms are warnings; meta "allowEmpty" fragments.
- runtime/pluginI18n.ts: api.i18n bound per plugin (register/t/locale/dir/onChange/number/date/
relative/list); the UI kit's own words follow the app's language. pageLang.ts reports the
site's <html lang>. shell/messages.ts: shell-model words.
- waybetter-host i18n.rs: NativeStrings (validated plain text, caps, one-pass {name} fill, page
payload by prefix), system_locales via sys-locale; TabState.lang.
- JSON Schemas for catalogs and translator notes; npm exports waybetter/i18n, /i18n/check,
/i18n/plugin.
This commit is contained in:
parent
c404dd3dd0
commit
2b8161fedc
18 changed files with 1461 additions and 27 deletions
10
crates/waybetter-host/Cargo.lock
generated
10
crates/waybetter-host/Cargo.lock
generated
|
|
@ -2993,6 +2993,15 @@ dependencies = [
|
||||||
"syn 3.0.6",
|
"syn 3.0.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sys-locale"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "system-deps"
|
name = "system-deps"
|
||||||
version = "6.2.2"
|
version = "6.2.2"
|
||||||
|
|
@ -3813,6 +3822,7 @@ dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
|
"sys-locale",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"url",
|
"url",
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,8 @@ sha2 = "0.10"
|
||||||
chrono = { version = "0.4", default-features = false, features = ["clock"] }
|
chrono = { version = "0.4", default-features = false, features = ["clock"] }
|
||||||
minisign-verify = "0.2"
|
minisign-verify = "0.2"
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
|
# The OS language preference (first run, "Follow system"); no dependencies of its own on desktop.
|
||||||
|
sys-locale = "0.3"
|
||||||
tauri = { version = "2", features = ["unstable"], optional = true }
|
tauri = { version = "2", features = ["unstable"], optional = true }
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
|
|
||||||
230
crates/waybetter-host/src/i18n.rs
Normal file
230
crates/waybetter-host/src/i18n.rs
Normal file
|
|
@ -0,0 +1,230 @@
|
||||||
|
//! Native side of wayBetter i18n.
|
||||||
|
//!
|
||||||
|
//! The shell owns language: it loads the catalogs, picks the locale (follow the site, follow the
|
||||||
|
//! system, or the owner's pick) and hands native code the few strings native UI needs (dialog
|
||||||
|
//! titles, notifications, the site runtime's own words) as [`NativeStrings`]. These are data only:
|
||||||
|
//! validated here (bounded, plain text, no markup or control characters), kept in app data so the
|
||||||
|
//! next launch has them before the shell loads, and delivered to site tabs as a JSON value.
|
||||||
|
//!
|
||||||
|
//! [`system_locales`] reads the OS preference for the first run and for "Follow system".
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
/// At most this many strings reach native code (the site runtime's, the kit's, bundled plugins', native UI's).
|
||||||
|
pub const MAX_STRINGS: usize = 4000;
|
||||||
|
/// Longest message accepted.
|
||||||
|
pub const MAX_VALUE: usize = 2000;
|
||||||
|
/// Longest key accepted.
|
||||||
|
pub const MAX_KEY: usize = 96;
|
||||||
|
/// Total bytes of keys and values.
|
||||||
|
pub const MAX_TOTAL: usize = 512 * 1024;
|
||||||
|
|
||||||
|
/// A BCP 47 language tag as the catalogs use it: `tr`, `pt-BR`, `zh-Hant`, `ar-x-fm`.
|
||||||
|
pub fn valid_tag(tag: &str) -> bool {
|
||||||
|
if tag.is_empty() || tag.len() > 35 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let mut parts = tag.split('-');
|
||||||
|
let Some(language) = parts.next() else { return false };
|
||||||
|
if !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_alphabetic()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
parts.all(|part| (1..=8).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphanumeric()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writing direction of a tag (by primary language).
|
||||||
|
pub fn is_rtl(tag: &str) -> bool {
|
||||||
|
let language = tag.split('-').next().unwrap_or("").to_ascii_lowercase();
|
||||||
|
matches!(language.as_str(), "ar" | "arc" | "ckb" | "dv" | "fa" | "he" | "iw" | "ks" | "ps" | "sd" | "syr" | "ug" | "ur" | "yi")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_key(key: &str) -> bool {
|
||||||
|
!key.is_empty()
|
||||||
|
&& key.len() <= MAX_KEY
|
||||||
|
&& key.as_bytes()[0].is_ascii_lowercase()
|
||||||
|
&& key.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plain text only: no markup, no control or bidi-override characters (newlines and tabs are fine).
|
||||||
|
pub fn valid_text(value: &str) -> bool {
|
||||||
|
if value.len() > MAX_VALUE {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let lower = value.to_ascii_lowercase();
|
||||||
|
if lower.contains("javascript:") || lower.contains("<") || lower.contains("<") || lower.contains("<") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let mut chars = value.chars().peekable();
|
||||||
|
while let Some(ch) = chars.next() {
|
||||||
|
if ch == '<' {
|
||||||
|
if let Some(next) = chars.clone().find(|c| !c.is_whitespace()) {
|
||||||
|
if next.is_ascii_alphabetic() || matches!(next, '/' | '!' | '?') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let code = ch as u32;
|
||||||
|
let control = (ch.is_control() && !matches!(ch, '\n' | '\t' | '\r')) || (0x202A..=0x202E).contains(&code) || (0x2066..=0x2069).contains(&code);
|
||||||
|
if control {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The strings native code and site tabs need, in the owner's language.
|
||||||
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct NativeStrings {
|
||||||
|
/// Active locale (a catalog tag).
|
||||||
|
pub locale: String,
|
||||||
|
/// The owner's choice: `site` (follow the site's own language), `system`, or a locale tag.
|
||||||
|
pub preference: String,
|
||||||
|
pub messages: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NativeStrings {
|
||||||
|
/// Checks everything the shell sent; any bad entry refuses the whole set.
|
||||||
|
pub fn validated(self) -> Result<Self, String> {
|
||||||
|
if !valid_tag(&self.locale) {
|
||||||
|
return Err("VALIDATION: invalid locale".into());
|
||||||
|
}
|
||||||
|
if !(self.preference == "site" || self.preference == "system" || valid_tag(&self.preference)) {
|
||||||
|
return Err("VALIDATION: language preference must be \"site\", \"system\" or a locale".into());
|
||||||
|
}
|
||||||
|
if self.messages.len() > MAX_STRINGS {
|
||||||
|
return Err("VALIDATION: too many strings".into());
|
||||||
|
}
|
||||||
|
let mut total = 0;
|
||||||
|
for (key, value) in &self.messages {
|
||||||
|
if !valid_key(key) {
|
||||||
|
return Err(format!("VALIDATION: invalid string key {:?}", key.chars().take(40).collect::<String>()));
|
||||||
|
}
|
||||||
|
if !valid_text(value) {
|
||||||
|
return Err(format!("VALIDATION: string {key} is not plain text"));
|
||||||
|
}
|
||||||
|
total += key.len() + value.len();
|
||||||
|
}
|
||||||
|
if total > MAX_TOTAL {
|
||||||
|
return Err("VALIDATION: strings too large".into());
|
||||||
|
}
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The message for `key`, or `fallback` (English, compiled in) when there is none.
|
||||||
|
pub fn get<'a>(&'a self, key: &str, fallback: &'a str) -> &'a str {
|
||||||
|
self.messages.get(key).map(String::as_str).filter(|value| !value.is_empty()).unwrap_or(fallback)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `get` with `{name}` placeholders filled in, in one pass: values are inserted as text and are
|
||||||
|
/// never scanned for placeholders themselves. Unknown `{…}` stays as written.
|
||||||
|
pub fn format(&self, key: &str, fallback: &str, params: &[(&str, &str)]) -> String {
|
||||||
|
let template = self.get(key, fallback);
|
||||||
|
let mut out = String::with_capacity(template.len());
|
||||||
|
let mut rest = template;
|
||||||
|
while let Some(open) = rest.find('{') {
|
||||||
|
out.push_str(&rest[..open]);
|
||||||
|
let tail = &rest[open..];
|
||||||
|
let value = tail.find('}').and_then(|close| params.iter().find(|(name, _)| *name == &tail[1..close]).map(|(_, value)| (close, value)));
|
||||||
|
match value {
|
||||||
|
Some((close, value)) => {
|
||||||
|
out.push_str(value);
|
||||||
|
rest = &tail[close + 1..];
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
out.push('{');
|
||||||
|
rest = &tail[1..];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push_str(rest);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The strings whose keys start with one of `prefixes`, as the JSON value a site tab receives.
|
||||||
|
pub fn page_payload(&self, prefixes: &[&str]) -> serde_json::Value {
|
||||||
|
let messages: serde_json::Map<String, serde_json::Value> = self
|
||||||
|
.messages
|
||||||
|
.iter()
|
||||||
|
.filter(|(key, _)| prefixes.iter().any(|prefix| key.starts_with(prefix)))
|
||||||
|
.map(|(key, value)| (key.clone(), serde_json::Value::String(value.clone())))
|
||||||
|
.collect();
|
||||||
|
serde_json::json!({ "locale": self.locale, "dir": if is_rtl(&self.locale) { "rtl" } else { "ltr" }, "messages": messages })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The OS language preferences, most preferred first (`tr-TR`, `en-US`), as valid tags.
|
||||||
|
pub fn system_locales() -> Vec<String> {
|
||||||
|
sys_locale::get_locales()
|
||||||
|
.map(|tag| tag.replace('_', "-"))
|
||||||
|
// POSIX locales may carry an encoding or modifier (`tr_TR.UTF-8@euro`).
|
||||||
|
.map(|tag| tag.split(['.', '@']).next().unwrap_or("").to_owned())
|
||||||
|
.filter(|tag| valid_tag(tag))
|
||||||
|
.take(8)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn strings(messages: &[(&str, &str)]) -> NativeStrings {
|
||||||
|
NativeStrings {
|
||||||
|
locale: "tr".into(),
|
||||||
|
preference: "site".into(),
|
||||||
|
messages: messages.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tags_are_validated() {
|
||||||
|
for good in ["tr", "pt-BR", "zh-Hant", "ar-x-fm", "fil", "en-GB"] {
|
||||||
|
assert!(valid_tag(good), "{good}");
|
||||||
|
}
|
||||||
|
for bad in ["", "t", "english", "tr_TR", "tr-", "tr-<x>", "a-b", "zh-Hant-TW-far-too-long-for-a-language-tag"] {
|
||||||
|
assert!(!valid_tag(bad), "{bad}");
|
||||||
|
}
|
||||||
|
assert!(is_rtl("ar-x-fm") && is_rtl("he") && !is_rtl("tr"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn strings_are_plain_text_only() {
|
||||||
|
assert!(strings(&[("native.alert.title", "“{keyword}” geçti"), ("x.toast.saved", "Kaydedildi\n")]).validated().is_ok());
|
||||||
|
for bad in ["<img src=x onerror=alert(1)>", "a < b / <script>", "<b>", "javascript:alert(1)", "a\u{202e}b", "bell\u{7}"] {
|
||||||
|
assert!(strings(&[("x.a", bad)]).validated().is_err(), "{bad:?}");
|
||||||
|
}
|
||||||
|
assert!(strings(&[("x.a", "Boyut < 8 MB")]).validated().is_ok());
|
||||||
|
assert!(strings(&[("X.bad", "x")]).validated().is_err());
|
||||||
|
assert!(strings(&[("x.a", &"a".repeat(MAX_VALUE + 1))]).validated().is_err());
|
||||||
|
let mut many = strings(&[]);
|
||||||
|
for i in 0..=MAX_STRINGS {
|
||||||
|
many.messages.insert(format!("x.k{i}"), "v".into());
|
||||||
|
}
|
||||||
|
assert!(many.validated().is_err());
|
||||||
|
let mut bad_pref = strings(&[]);
|
||||||
|
bad_pref.preference = "everything".into();
|
||||||
|
assert!(bad_pref.validated().is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lookups_fall_back_to_english_and_fill_placeholders() {
|
||||||
|
let s = strings(&[("native.alert.body", "{handle}: {text}"), ("native.empty", "")]);
|
||||||
|
assert_eq!(s.get("native.missing", "Fallback"), "Fallback");
|
||||||
|
assert_eq!(s.get("native.empty", "Fallback"), "Fallback");
|
||||||
|
assert_eq!(s.format("native.alert.body", "", &[("handle", "@a"), ("text", "hi {x}")]), "@a: hi {x}");
|
||||||
|
// A value is never expanded again, even when it spells another placeholder.
|
||||||
|
assert_eq!(s.format("native.alert.body", "", &[("handle", "{text}"), ("text", "hi")]), "{text}: hi");
|
||||||
|
assert_eq!(s.format("native.missing", "{a} {b} {", &[("a", "1")]), "1 {b} {");
|
||||||
|
let payload = s.page_payload(&["native.alert"]);
|
||||||
|
assert_eq!(payload["messages"].as_object().unwrap().len(), 1);
|
||||||
|
assert_eq!(payload["dir"], "ltr");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn system_locales_are_tags() {
|
||||||
|
for tag in system_locales() {
|
||||||
|
assert!(valid_tag(&tag), "{tag}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -14,10 +14,12 @@
|
||||||
//! - [`update`]: silent-update scheduling and the crash handshake.
|
//! - [`update`]: silent-update scheduling and the crash handshake.
|
||||||
//! - [`tabs`]: tab layout/state payloads, link routing and tab-chrome validation.
|
//! - [`tabs`]: tab layout/state payloads, link routing and tab-chrome validation.
|
||||||
//! - [`layout`]: native placement bookkeeping (unchanged bounds skipped, window-resize follow).
|
//! - [`layout`]: native placement bookkeeping (unchanged bounds skipped, window-resize follow).
|
||||||
|
//! - [`i18n`]: the strings native UI and site tabs get in the owner's language (validated data), OS locale.
|
||||||
//!
|
//!
|
||||||
//! With the `tauri` feature, [`host`] adds the Tauri glue that does not depend on app state.
|
//! With the `tauri` feature, [`host`] adds the Tauri glue that does not depend on app state.
|
||||||
|
|
||||||
pub mod hotfix;
|
pub mod hotfix;
|
||||||
|
pub mod i18n;
|
||||||
pub mod layout;
|
pub mod layout;
|
||||||
pub mod plugins;
|
pub mod plugins;
|
||||||
pub mod policy;
|
pub mod policy;
|
||||||
|
|
|
||||||
|
|
@ -71,6 +71,9 @@ pub struct TabState {
|
||||||
/// A deck column's unread count (capped at [`MAX_UNREAD`]); only ever a number about this tab.
|
/// A deck column's unread count (capped at [`MAX_UNREAD`]); only ever a number about this tab.
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub unread: Option<u16>,
|
pub unread: Option<u16>,
|
||||||
|
/// The language the site's own UI is in (its `<html lang>`), a validated tag; site tabs only.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub lang: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TabState {
|
impl TabState {
|
||||||
|
|
@ -89,6 +92,7 @@ impl TabState {
|
||||||
focused,
|
focused,
|
||||||
loading: None,
|
loading: None,
|
||||||
unread: None,
|
unread: None,
|
||||||
|
lang: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
661
packages/runtime/src/i18n.ts
Normal file
661
packages/runtime/src/i18n.ts
Normal file
|
|
@ -0,0 +1,661 @@
|
||||||
|
// wayBetter i18n: a small, dependency-free message runtime for the shell, the panel, the page
|
||||||
|
// runtime and plugins (published as `waybetter/i18n`).
|
||||||
|
//
|
||||||
|
// Messages are plain strings in an ICU MessageFormat subset ("ICU-lite"):
|
||||||
|
// Hello, {name}! placeholder (inserted as text, never HTML)
|
||||||
|
// {count, plural, =0 {No drafts} one {# draft} other {# drafts}} plural (Intl.PluralRules)
|
||||||
|
// {n, selectordinal, one {#st} two {#nd} few {#rd} other {#th}} ordinal
|
||||||
|
// {kind, select, post {Post} reply {Reply} other {Item}} select
|
||||||
|
// {n, number} {n, number, percent} {d, date, short} {d, time} Intl number/date formats
|
||||||
|
// '{literal}' '#' and '' (an apostrophe) ICU quoting
|
||||||
|
// An apostrophe quotes only when it comes right before { } # or another apostrophe, so ordinary
|
||||||
|
// English ("don't", "the developer's") needs no escaping.
|
||||||
|
// `#` inside a plural is the (locale-formatted) number. Numbers, dates, relative times and lists
|
||||||
|
// go through `Intl` in the active locale.
|
||||||
|
//
|
||||||
|
// Catalogs are data only: one JSON file per locale (`locales/<bcp47>.json`), English is the
|
||||||
|
// source. Lookups fall back along a chain (pt-BR -> pt -> en). Missing keys are reported once per
|
||||||
|
// key and locale through `onMissing` (development), never thrown.
|
||||||
|
|
||||||
|
export type Messages = Readonly<Record<string, string>>;
|
||||||
|
export type Dir = 'ltr' | 'rtl';
|
||||||
|
export type Params = Readonly<Record<string, unknown>>;
|
||||||
|
|
||||||
|
/** A catalog file (`locales/<bcp47>.json`). See `i18n.schema.json` in the `waybetter` package. */
|
||||||
|
export type Catalog = {
|
||||||
|
$schema?: string;
|
||||||
|
/** BCP 47 tag of this file (`tr`, `pt`, `zh-Hant`, `ar-x-fm`). */
|
||||||
|
locale: string;
|
||||||
|
/** The language's own name ("Türkçe"). */
|
||||||
|
name: string;
|
||||||
|
/** Its English name ("Turkish"). */
|
||||||
|
englishName: string;
|
||||||
|
dir?: Dir;
|
||||||
|
/** `source` (English), `machine` (machine-drafted, needs a human), `reviewed` (checked by people). */
|
||||||
|
status: 'source' | 'machine' | 'reviewed';
|
||||||
|
reviewers?: string[];
|
||||||
|
/** Falls back to this locale before English (e.g. `ar-x-fm` -> `ar`). */
|
||||||
|
fallback?: string;
|
||||||
|
messages: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------------------------
|
||||||
|
// Locales
|
||||||
|
|
||||||
|
/** Scripts written right to left, by primary language subtag. */
|
||||||
|
const RTL = new Set(['ar', 'arc', 'ckb', 'dv', 'fa', 'he', 'iw', 'ks', 'ku-arab', 'ps', 'sd', 'syr', 'ug', 'ur', 'yi']);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Site and legacy codes mapped to BCP 47: X's own settings use `msa`, `zh-cn`, `zh-tw`, `no` and
|
||||||
|
* `en-gb`; old platforms say `iw`, `in`, `tl`.
|
||||||
|
*/
|
||||||
|
const ALIASES: Record<string, string> = {
|
||||||
|
msa: 'ms',
|
||||||
|
'zh-cn': 'zh-Hans',
|
||||||
|
'zh-sg': 'zh-Hans',
|
||||||
|
zh: 'zh-Hans',
|
||||||
|
'zh-tw': 'zh-Hant',
|
||||||
|
'zh-hk': 'zh-Hant',
|
||||||
|
'zh-mo': 'zh-Hant',
|
||||||
|
no: 'nb',
|
||||||
|
nn: 'nb',
|
||||||
|
iw: 'he',
|
||||||
|
in: 'id',
|
||||||
|
tl: 'fil',
|
||||||
|
ji: 'yi',
|
||||||
|
};
|
||||||
|
|
||||||
|
const TAG = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8}){0,4}$/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A tag in canonical BCP 47 form (`en_gb` -> `en-GB`, `zh-cn` -> `zh-Hans`, `msa` -> `ms`), or null
|
||||||
|
* when it is not a language tag at all. Private-use subtags survive (`ar-x-fm`).
|
||||||
|
*/
|
||||||
|
export function normalizeLocale(input: unknown): string | null {
|
||||||
|
if (typeof input !== 'string') return null;
|
||||||
|
const raw = input.trim().replace(/_/g, '-');
|
||||||
|
if (!raw || raw.length > 35 || !TAG.test(raw)) return null;
|
||||||
|
const lower = raw.toLowerCase();
|
||||||
|
if (ALIASES[lower]) return ALIASES[lower];
|
||||||
|
// `zh-Hans-CN` / `zh-Hant-TW`: the script decides; the region is noise for our catalogs.
|
||||||
|
const parts = lower.split('-');
|
||||||
|
if (parts[0] === 'zh') {
|
||||||
|
if (parts.includes('hant') || ['tw', 'hk', 'mo'].includes(parts[1] ?? '')) return 'zh-Hant';
|
||||||
|
return 'zh-Hans';
|
||||||
|
}
|
||||||
|
const privateUse = lower.indexOf('-x-');
|
||||||
|
if (privateUse > 0) {
|
||||||
|
const base = normalizeLocale(raw.slice(0, privateUse));
|
||||||
|
return base ? `${base}-x-${lower.slice(privateUse + 3)}` : null;
|
||||||
|
}
|
||||||
|
const alias = ALIASES[parts[0]!];
|
||||||
|
const head = alias && !alias.includes('-') ? [alias, ...parts.slice(1)].join('-') : raw;
|
||||||
|
try {
|
||||||
|
return Intl.getCanonicalLocales(head)[0] ?? null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The primary language subtag (`pt-BR` -> `pt`). */
|
||||||
|
export function languageOf(locale: string): string {
|
||||||
|
return locale.split('-')[0]!.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writing direction of a locale. */
|
||||||
|
export function direction(locale: string): Dir {
|
||||||
|
const lower = locale.toLowerCase();
|
||||||
|
if (lower.startsWith('ku-arab')) return 'rtl';
|
||||||
|
return RTL.has(languageOf(lower)) ? 'rtl' : 'ltr';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where lookups go, most specific first, ending with the source locale: `pt-BR` -> [pt-BR, pt, en].
|
||||||
|
* `fallbacks` maps a locale to the one it inherits from (a catalog's `fallback`, e.g. ar-x-fm -> ar).
|
||||||
|
* Script variants never fall back to another script: `zh-Hant` does not use `zh-Hans`.
|
||||||
|
*/
|
||||||
|
export function fallbackChain(locale: string, source = 'en', fallbacks: Readonly<Record<string, string>> = {}): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
const push = (tag: string | null | undefined) => {
|
||||||
|
if (tag && !out.includes(tag)) out.push(tag);
|
||||||
|
};
|
||||||
|
let current: string | null = normalizeLocale(locale);
|
||||||
|
for (let guard = 0; current && guard < 8; guard += 1) {
|
||||||
|
push(current);
|
||||||
|
const explicit = fallbacks[current];
|
||||||
|
if (explicit) {
|
||||||
|
current = normalizeLocale(explicit);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const privateUse = current.indexOf('-x-');
|
||||||
|
if (privateUse > 0) {
|
||||||
|
current = current.slice(0, privateUse);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const parts = current.split('-');
|
||||||
|
if (parts.length <= 1) break;
|
||||||
|
// zh-Hans / zh-Hant, sr-Latn: a script subtag is its own catalog.
|
||||||
|
if (parts.length === 2 && /^[A-Z][a-z]{3}$/.test(parts[1]!)) break;
|
||||||
|
current = parts.slice(0, -1).join('-');
|
||||||
|
}
|
||||||
|
push(source);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Picks the best available locale for a list of preferences (most wanted first), by fallback chain:
|
||||||
|
* `['pt-PT', 'en']` with `pt` available -> `pt`. Returns `fallback` when nothing matches.
|
||||||
|
*/
|
||||||
|
export function matchLocale(preferred: readonly unknown[], available: readonly string[], fallback = 'en'): string {
|
||||||
|
const set = new Set(available);
|
||||||
|
for (const wanted of preferred) {
|
||||||
|
const tag = normalizeLocale(wanted);
|
||||||
|
if (!tag) continue;
|
||||||
|
for (const candidate of fallbackChain(tag, '')) {
|
||||||
|
if (candidate && set.has(candidate)) return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------------------------
|
||||||
|
// Messages (ICU-lite)
|
||||||
|
|
||||||
|
type Part =
|
||||||
|
| string
|
||||||
|
| { kind: 'arg'; name: string; format?: 'number' | 'date' | 'time'; style?: string }
|
||||||
|
| { kind: 'pound' }
|
||||||
|
| { kind: 'plural'; name: string; ordinal: boolean; offset: number; options: Record<string, Part[]> }
|
||||||
|
| { kind: 'select'; name: string; options: Record<string, Part[]> };
|
||||||
|
|
||||||
|
export class MessageSyntaxError extends Error {
|
||||||
|
readonly source: string;
|
||||||
|
readonly index: number;
|
||||||
|
constructor(message: string, source: string, index: number) {
|
||||||
|
super(`${message} at ${index} in ${JSON.stringify(source.length > 80 ? `${source.slice(0, 80)}…` : source)}`);
|
||||||
|
this.name = 'MessageSyntaxError';
|
||||||
|
this.source = source;
|
||||||
|
this.index = index;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||||
|
|
||||||
|
/** Parses a message into parts; throws `MessageSyntaxError` on malformed ICU. */
|
||||||
|
export function parseMessage(source: string): Part[] {
|
||||||
|
let i = 0;
|
||||||
|
|
||||||
|
const parseParts = (inPlural: boolean, depth: number): Part[] => {
|
||||||
|
const parts: Part[] = [];
|
||||||
|
let text = '';
|
||||||
|
const flush = () => {
|
||||||
|
if (text) parts.push(text);
|
||||||
|
text = '';
|
||||||
|
};
|
||||||
|
while (i < source.length) {
|
||||||
|
const ch = source[i]!;
|
||||||
|
if (ch === "'") {
|
||||||
|
const next = source[i + 1];
|
||||||
|
if (next === "'") { text += "'"; i += 2; continue; }
|
||||||
|
// An apostrophe only quotes before { } # (or another apostrophe); "don't" stays literal.
|
||||||
|
if (next === '{' || next === '}' || next === '#') {
|
||||||
|
// Quoted literal up to the next lone apostrophe.
|
||||||
|
i += 1;
|
||||||
|
while (i < source.length) {
|
||||||
|
if (source[i] === "'") {
|
||||||
|
if (source[i + 1] === "'") { text += "'"; i += 2; continue; }
|
||||||
|
i += 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
text += source[i];
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
text += ch;
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '}') {
|
||||||
|
if (depth > 0) break;
|
||||||
|
throw new MessageSyntaxError('unexpected }', source, i);
|
||||||
|
}
|
||||||
|
if (ch === '#' && inPlural) {
|
||||||
|
flush();
|
||||||
|
parts.push({ kind: 'pound' });
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '{') {
|
||||||
|
flush();
|
||||||
|
parts.push(parseArgument(depth));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
text += ch;
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
flush();
|
||||||
|
return parts;
|
||||||
|
};
|
||||||
|
|
||||||
|
const skipSpace = () => { while (i < source.length && /\s/.test(source[i]!)) i += 1; };
|
||||||
|
const readWord = () => {
|
||||||
|
const start = i;
|
||||||
|
while (i < source.length && /[^\s,{}]/.test(source[i]!)) i += 1;
|
||||||
|
return source.slice(start, i);
|
||||||
|
};
|
||||||
|
const expect = (ch: string) => {
|
||||||
|
if (source[i] !== ch) throw new MessageSyntaxError(`expected ${ch}`, source, i);
|
||||||
|
i += 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseOptions = (inPlural: boolean, depth: number): Record<string, Part[]> => {
|
||||||
|
const options: Record<string, Part[]> = {};
|
||||||
|
for (;;) {
|
||||||
|
skipSpace();
|
||||||
|
if (source[i] === '}') break;
|
||||||
|
const selector = readWord();
|
||||||
|
if (!selector) throw new MessageSyntaxError('expected a selector', source, i);
|
||||||
|
skipSpace();
|
||||||
|
expect('{');
|
||||||
|
options[selector] = parseParts(inPlural, depth + 1);
|
||||||
|
expect('}');
|
||||||
|
}
|
||||||
|
if (!('other' in options)) throw new MessageSyntaxError('a plural or select needs an "other" option', source, i);
|
||||||
|
return options;
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseArgument = (depth: number): Part => {
|
||||||
|
expect('{');
|
||||||
|
skipSpace();
|
||||||
|
const name = readWord();
|
||||||
|
if (!NAME.test(name)) throw new MessageSyntaxError(`invalid placeholder name ${JSON.stringify(name)}`, source, i);
|
||||||
|
skipSpace();
|
||||||
|
if (source[i] === '}') { i += 1; return { kind: 'arg', name }; }
|
||||||
|
expect(',');
|
||||||
|
skipSpace();
|
||||||
|
const type = readWord();
|
||||||
|
skipSpace();
|
||||||
|
if (type === 'plural' || type === 'selectordinal') {
|
||||||
|
expect(',');
|
||||||
|
skipSpace();
|
||||||
|
let offset = 0;
|
||||||
|
const offsetMatch = /^offset:(\d+)/.exec(source.slice(i));
|
||||||
|
if (offsetMatch) { offset = Number(offsetMatch[1]); i += offsetMatch[0].length; }
|
||||||
|
const options = parseOptions(true, depth);
|
||||||
|
expect('}');
|
||||||
|
return { kind: 'plural', name, ordinal: type === 'selectordinal', offset, options };
|
||||||
|
}
|
||||||
|
if (type === 'select') {
|
||||||
|
expect(',');
|
||||||
|
const options = parseOptions(false, depth);
|
||||||
|
expect('}');
|
||||||
|
return { kind: 'select', name, options };
|
||||||
|
}
|
||||||
|
if (type === 'number' || type === 'date' || type === 'time') {
|
||||||
|
let style: string | undefined;
|
||||||
|
if (source[i] === ',') {
|
||||||
|
i += 1;
|
||||||
|
skipSpace();
|
||||||
|
style = readWord();
|
||||||
|
skipSpace();
|
||||||
|
}
|
||||||
|
expect('}');
|
||||||
|
return { kind: 'arg', name, format: type, style };
|
||||||
|
}
|
||||||
|
throw new MessageSyntaxError(`unknown argument type ${JSON.stringify(type)}`, source, i);
|
||||||
|
};
|
||||||
|
|
||||||
|
const parts = parseParts(false, 0);
|
||||||
|
if (i < source.length) throw new MessageSyntaxError('unexpected }', source, i);
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Placeholder names a message uses (plural/select arguments included), sorted. */
|
||||||
|
export function placeholders(source: string): string[] {
|
||||||
|
const names = new Set<string>();
|
||||||
|
const walk = (parts: Part[]) => {
|
||||||
|
for (const part of parts) {
|
||||||
|
if (typeof part === 'string' || part.kind === 'pound') continue;
|
||||||
|
names.add(part.name);
|
||||||
|
if (part.kind === 'plural' || part.kind === 'select') for (const option of Object.values(part.options)) walk(option);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(parseMessage(source));
|
||||||
|
return [...names].sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plural/select structure of a message: `{ count: { kind: 'plural', options: ['one', 'other'] } }`. */
|
||||||
|
export function argumentShapes(source: string): Record<string, { kind: 'plural' | 'selectordinal' | 'select'; options: string[] }> {
|
||||||
|
const out: Record<string, { kind: 'plural' | 'selectordinal' | 'select'; options: string[] }> = {};
|
||||||
|
const walk = (parts: Part[]) => {
|
||||||
|
for (const part of parts) {
|
||||||
|
if (typeof part === 'string' || part.kind === 'pound' || part.kind === 'arg') continue;
|
||||||
|
const kind = part.kind === 'select' ? 'select' : part.ordinal ? 'selectordinal' : 'plural';
|
||||||
|
const entry = (out[part.name] ??= { kind, options: [] });
|
||||||
|
for (const [selector, option] of Object.entries(part.options)) {
|
||||||
|
if (!entry.options.includes(selector)) entry.options.push(selector);
|
||||||
|
walk(option);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(parseMessage(source));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatterCache = new Map<string, Intl.NumberFormat | Intl.DateTimeFormat | Intl.PluralRules>();
|
||||||
|
function cached<T extends Intl.NumberFormat | Intl.DateTimeFormat | Intl.PluralRules>(key: string, make: () => T): T {
|
||||||
|
let value = formatterCache.get(key) as T | undefined;
|
||||||
|
if (!value) {
|
||||||
|
value = make();
|
||||||
|
if (formatterCache.size > 256) formatterCache.clear();
|
||||||
|
formatterCache.set(key, value);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeLocale(locale: string): string {
|
||||||
|
// Private-use tags (ar-x-fm) are valid BCP 47 but Intl may not know them: format as the base.
|
||||||
|
const base = locale.split('-x-')[0]!;
|
||||||
|
try {
|
||||||
|
return Intl.getCanonicalLocales(base)[0] ?? 'en';
|
||||||
|
} catch {
|
||||||
|
return 'en';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function numberFormat(locale: string, options?: Intl.NumberFormatOptions): Intl.NumberFormat {
|
||||||
|
const tag = safeLocale(locale);
|
||||||
|
return cached(`n|${tag}|${JSON.stringify(options ?? {})}`, () => new Intl.NumberFormat(tag, options));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dateFormat(locale: string, options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {
|
||||||
|
const tag = safeLocale(locale);
|
||||||
|
return cached(`d|${tag}|${JSON.stringify(options ?? {})}`, () => new Intl.DateTimeFormat(tag, options));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pluralRules(locale: string, ordinal = false): Intl.PluralRules {
|
||||||
|
const tag = safeLocale(locale);
|
||||||
|
return cached(`p|${tag}|${ordinal}`, () => new Intl.PluralRules(tag, { type: ordinal ? 'ordinal' : 'cardinal' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** CLDR plural categories a locale uses (`tr`: one, other; `ar`: zero, one, two, few, many, other). */
|
||||||
|
export function pluralCategories(locale: string, ordinal = false): string[] {
|
||||||
|
return [...pluralRules(locale, ordinal).resolvedOptions().pluralCategories];
|
||||||
|
}
|
||||||
|
|
||||||
|
const NUMBER_STYLES: Record<string, Intl.NumberFormatOptions> = {
|
||||||
|
integer: { maximumFractionDigits: 0 },
|
||||||
|
percent: { style: 'percent' },
|
||||||
|
compact: { notation: 'compact' },
|
||||||
|
};
|
||||||
|
const DATE_STYLES: Record<string, Intl.DateTimeFormatOptions> = {
|
||||||
|
short: { dateStyle: 'short' },
|
||||||
|
medium: { dateStyle: 'medium' },
|
||||||
|
long: { dateStyle: 'long' },
|
||||||
|
full: { dateStyle: 'full' },
|
||||||
|
};
|
||||||
|
const TIME_STYLES: Record<string, Intl.DateTimeFormatOptions> = {
|
||||||
|
short: { timeStyle: 'short' },
|
||||||
|
medium: { timeStyle: 'medium' },
|
||||||
|
long: { timeStyle: 'long' },
|
||||||
|
full: { timeStyle: 'full' },
|
||||||
|
};
|
||||||
|
|
||||||
|
function toDate(value: unknown): Date | null {
|
||||||
|
const date = value instanceof Date ? value : typeof value === 'number' || typeof value === 'string' ? new Date(value) : null;
|
||||||
|
return date && Number.isFinite(date.getTime()) ? date : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(parts: Part[], params: Params, locale: string, pound: number | null, onMissingParam?: (name: string) => void): string {
|
||||||
|
let out = '';
|
||||||
|
for (const part of parts) {
|
||||||
|
if (typeof part === 'string') { out += part; continue; }
|
||||||
|
if (part.kind === 'pound') {
|
||||||
|
out += pound === null ? '#' : numberFormat(locale).format(pound);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const has = Object.prototype.hasOwnProperty.call(params, part.name);
|
||||||
|
const value = has ? params[part.name] : undefined;
|
||||||
|
if (!has || value === undefined || value === null) {
|
||||||
|
onMissingParam?.(part.name);
|
||||||
|
out += `{${part.name}}`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (part.kind === 'arg') {
|
||||||
|
if (part.format === 'number' && typeof value === 'number') {
|
||||||
|
out += numberFormat(locale, NUMBER_STYLES[part.style ?? ''] ?? undefined).format(value);
|
||||||
|
} else if ((part.format === 'date' || part.format === 'time') && toDate(value)) {
|
||||||
|
const styles = part.format === 'date' ? DATE_STYLES : TIME_STYLES;
|
||||||
|
out += dateFormat(locale, styles[part.style ?? 'medium'] ?? styles.medium).format(toDate(value)!);
|
||||||
|
} else if (typeof value === 'number') {
|
||||||
|
out += numberFormat(locale).format(value);
|
||||||
|
} else {
|
||||||
|
out += String(value);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (part.kind === 'select') {
|
||||||
|
const key = String(value);
|
||||||
|
out += render(part.options[key] ?? part.options.other!, params, locale, pound, onMissingParam);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const n = typeof value === 'number' ? value : Number(value);
|
||||||
|
if (!Number.isFinite(n)) { out += String(value); continue; }
|
||||||
|
const exact = part.options[`=${n}`];
|
||||||
|
const shifted = n - part.offset;
|
||||||
|
const option = exact ?? part.options[pluralRules(locale, part.ordinal).select(shifted)] ?? part.options.other!;
|
||||||
|
out += render(option, params, locale, shifted, onMissingParam);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const compiled = new Map<string, Part[] | Error>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats one message. Placeholder values are inserted as plain text; a malformed message renders
|
||||||
|
* as its raw text (and `onError` hears about it) rather than throwing in the UI.
|
||||||
|
*/
|
||||||
|
export function formatMessage(
|
||||||
|
source: string,
|
||||||
|
params: Params = {},
|
||||||
|
locale = 'en',
|
||||||
|
hooks: { onError?: (error: Error) => void; onMissingParam?: (name: string) => void } = {},
|
||||||
|
): string {
|
||||||
|
if (!source.includes('{') && !source.includes("'")) return source;
|
||||||
|
let parts = compiled.get(source);
|
||||||
|
if (!parts) {
|
||||||
|
try {
|
||||||
|
parts = parseMessage(source);
|
||||||
|
} catch (error) {
|
||||||
|
parts = error instanceof Error ? error : new Error(String(error));
|
||||||
|
}
|
||||||
|
if (compiled.size > 4096) compiled.clear();
|
||||||
|
compiled.set(source, parts);
|
||||||
|
}
|
||||||
|
if (parts instanceof Error) {
|
||||||
|
hooks.onError?.(parts);
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
return render(parts, params, locale, null, hooks.onMissingParam);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------------------------
|
||||||
|
// Runtime
|
||||||
|
|
||||||
|
export type I18nOptions = {
|
||||||
|
/** The source locale; its messages are complete (default `en`). */
|
||||||
|
sourceLocale?: string;
|
||||||
|
/** Source messages (English). Always loaded. */
|
||||||
|
source: Messages;
|
||||||
|
/** Locales that have catalogs (the source included). */
|
||||||
|
available: readonly string[];
|
||||||
|
/** Per-locale inheritance before the source (a catalog's `fallback`). */
|
||||||
|
fallbacks?: Readonly<Record<string, string>>;
|
||||||
|
/** Loads one locale's messages (lazy import of `locales/<tag>.json`), or null when there are none. */
|
||||||
|
load?: (locale: string) => Promise<Messages | null | undefined> | Messages | null | undefined;
|
||||||
|
/** Initial locale (default: the source). */
|
||||||
|
locale?: string;
|
||||||
|
/** A key the chain does not have, or a message that failed to parse. Once per key and locale. */
|
||||||
|
onMissing?: (key: string, locale: string, reason: 'key' | 'syntax' | 'param') => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type I18n<K extends string = string> = {
|
||||||
|
/** Active locale (a catalog tag, e.g. `pt`, `zh-Hant`). */
|
||||||
|
readonly locale: string;
|
||||||
|
readonly dir: Dir;
|
||||||
|
/** Lookup order for the active locale, ending with the source. */
|
||||||
|
readonly chain: readonly string[];
|
||||||
|
readonly available: readonly string[];
|
||||||
|
/** The message for `key` in the active locale, formatted with `params`. Unknown keys return the key. */
|
||||||
|
t(key: K, params?: Params): string;
|
||||||
|
/** Like `t` for keys built at runtime; returns `fallback` (default the key) when missing. */
|
||||||
|
tx(key: string, params?: Params, fallback?: string): string;
|
||||||
|
has(key: string): boolean;
|
||||||
|
/** Switches locale (loading its catalog and its chain's). Resolves with the effective locale. */
|
||||||
|
setLocale(locale: string): Promise<string>;
|
||||||
|
/** Adds messages for a locale (framework catalogs, plugin strings); later adds win. */
|
||||||
|
add(locale: string, messages: Messages): void;
|
||||||
|
onChange(listener: (locale: string) => void): () => void;
|
||||||
|
/** Resolved messages of the active locale for keys starting with one of `prefixes` (the chain merged). */
|
||||||
|
resolved(prefixes?: readonly string[]): Record<string, string>;
|
||||||
|
number(value: number, options?: Intl.NumberFormatOptions): string;
|
||||||
|
date(value: Date | number | string, options?: Intl.DateTimeFormatOptions): string;
|
||||||
|
/** "3 minutes ago", "in 2 days" (Intl.RelativeTimeFormat, numeric: auto). */
|
||||||
|
relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;
|
||||||
|
/** "a, b and c" (Intl.ListFormat). */
|
||||||
|
list(items: readonly string[], options?: { type?: 'conjunction' | 'disjunction' | 'unit'; style?: 'long' | 'short' | 'narrow' }): string;
|
||||||
|
plural(count: number, ordinal?: boolean): Intl.LDMLPluralRule;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createI18n<K extends string = string>(options: I18nOptions): I18n<K> {
|
||||||
|
const source = options.sourceLocale ?? 'en';
|
||||||
|
const available = Object.freeze([...new Set([source, ...options.available])]);
|
||||||
|
const tables = new Map<string, Record<string, string>>();
|
||||||
|
tables.set(source, { ...options.source });
|
||||||
|
const loaded = new Set<string>([source]);
|
||||||
|
const listeners = new Set<(locale: string) => void>();
|
||||||
|
const reported = new Set<string>();
|
||||||
|
let locale = source;
|
||||||
|
let chain: string[] = [source];
|
||||||
|
|
||||||
|
const report = (key: string, where: string, reason: 'key' | 'syntax' | 'param') => {
|
||||||
|
const id = `${reason}|${where}|${key}`;
|
||||||
|
if (reported.has(id) || !options.onMissing) return;
|
||||||
|
if (reported.size > 2048) reported.clear();
|
||||||
|
reported.add(id);
|
||||||
|
try { options.onMissing(key, where, reason); } catch { /* a reporter must not break the UI */ }
|
||||||
|
};
|
||||||
|
|
||||||
|
const chainFor = (tag: string) => fallbackChain(tag, source, options.fallbacks).filter(entry => available.includes(entry));
|
||||||
|
|
||||||
|
const lookup = (key: string): string | undefined => {
|
||||||
|
for (const entry of chain) {
|
||||||
|
const value = tables.get(entry)?.[key];
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
if (entry !== locale && locale !== source && entry === source) report(key, locale, 'key');
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
const format = (key: string, message: string, params?: Params) =>
|
||||||
|
formatMessage(message, params ?? {}, locale, {
|
||||||
|
onError: () => report(key, locale, 'syntax'),
|
||||||
|
onMissingParam: () => report(key, locale, 'param'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const i18n: I18n<K> = {
|
||||||
|
get locale() { return locale; },
|
||||||
|
get dir() { return direction(locale); },
|
||||||
|
get chain() { return chain; },
|
||||||
|
available,
|
||||||
|
t(key, params) {
|
||||||
|
const message = lookup(key);
|
||||||
|
if (message === undefined) {
|
||||||
|
report(key, locale, 'key');
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
return format(key, message, params);
|
||||||
|
},
|
||||||
|
tx(key, params, fallback) {
|
||||||
|
const message = lookup(key);
|
||||||
|
if (message === undefined) return fallback ?? key;
|
||||||
|
return format(key, message, params);
|
||||||
|
},
|
||||||
|
has: key => lookup(key) !== undefined,
|
||||||
|
async setLocale(requested) {
|
||||||
|
const target = matchLocale([requested], available, source);
|
||||||
|
const nextChain = chainFor(target);
|
||||||
|
if (options.load) {
|
||||||
|
await Promise.all(nextChain.filter(tag => !loaded.has(tag)).map(async tag => {
|
||||||
|
try {
|
||||||
|
const messages = await options.load!(tag);
|
||||||
|
if (messages) tables.set(tag, { ...messages, ...tables.get(tag) });
|
||||||
|
} catch (error) {
|
||||||
|
report(`<catalog ${tag}: ${error instanceof Error ? error.message : String(error)}>`, tag, 'key');
|
||||||
|
}
|
||||||
|
loaded.add(tag);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
const changed = target !== locale;
|
||||||
|
locale = target;
|
||||||
|
chain = nextChain;
|
||||||
|
if (changed) for (const listener of [...listeners]) {
|
||||||
|
try { listener(locale); } catch { /* listeners must not break each other */ }
|
||||||
|
}
|
||||||
|
return locale;
|
||||||
|
},
|
||||||
|
add(tag, messages) {
|
||||||
|
const key = normalizeLocale(tag) ?? tag;
|
||||||
|
tables.set(key, { ...tables.get(key), ...messages });
|
||||||
|
},
|
||||||
|
onChange(listener) {
|
||||||
|
listeners.add(listener);
|
||||||
|
return () => listeners.delete(listener);
|
||||||
|
},
|
||||||
|
resolved(prefixes) {
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
for (const entry of [...chain].reverse()) {
|
||||||
|
for (const [key, value] of Object.entries(tables.get(entry) ?? {})) {
|
||||||
|
if (!prefixes || prefixes.some(prefix => key.startsWith(prefix))) out[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
},
|
||||||
|
number: (value, opts) => numberFormat(locale, opts).format(value),
|
||||||
|
date: (value, opts) => {
|
||||||
|
const date = toDate(value);
|
||||||
|
return date ? dateFormat(locale, opts).format(date) : '';
|
||||||
|
},
|
||||||
|
relative: (value, unit, opts) => {
|
||||||
|
try {
|
||||||
|
return new Intl.RelativeTimeFormat(safeLocale(locale), { numeric: 'auto', ...opts }).format(value, unit);
|
||||||
|
} catch {
|
||||||
|
return `${value} ${unit}`;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
list: (items, opts) => {
|
||||||
|
try {
|
||||||
|
return new Intl.ListFormat(safeLocale(locale), { type: opts?.type ?? 'conjunction', style: opts?.style ?? 'long' }).format(items);
|
||||||
|
} catch {
|
||||||
|
return items.join(', ');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
plural: (count, ordinal = false) => pluralRules(locale, ordinal).select(count),
|
||||||
|
};
|
||||||
|
return i18n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Picks a relative-time unit for a timestamp: "just now" granularity down to seconds. */
|
||||||
|
export function relativeParts(then: number, now = Date.now()): { value: number; unit: Intl.RelativeTimeFormatUnit } {
|
||||||
|
const seconds = Math.round((then - now) / 1000);
|
||||||
|
const abs = Math.abs(seconds);
|
||||||
|
if (abs < 60) return { value: seconds, unit: 'second' };
|
||||||
|
if (abs < 3600) return { value: Math.round(seconds / 60), unit: 'minute' };
|
||||||
|
if (abs < 86400) return { value: Math.round(seconds / 3600), unit: 'hour' };
|
||||||
|
if (abs < 86400 * 30) return { value: Math.round(seconds / 86400), unit: 'day' };
|
||||||
|
if (abs < 86400 * 365) return { value: Math.round(seconds / (86400 * 30)), unit: 'month' };
|
||||||
|
return { value: Math.round(seconds / (86400 * 365)), unit: 'year' };
|
||||||
|
}
|
||||||
201
packages/runtime/src/i18nCheck.ts
Normal file
201
packages/runtime/src/i18nCheck.ts
Normal file
|
|
@ -0,0 +1,201 @@
|
||||||
|
// Catalog checks for translators and CI (published as `waybetter/i18n/check`): every rule a
|
||||||
|
// contributed `locales/<bcp47>.json` must pass before review. Pure functions over parsed JSON, so
|
||||||
|
// an app's `scripts/i18n-check.mjs`, its tests and editors can share them.
|
||||||
|
//
|
||||||
|
// Errors fail the check: bad file shape, keys the source does not have, malformed ICU, placeholder
|
||||||
|
// names English does not have, a missing placeholder (except an argument English only uses to choose
|
||||||
|
// a plural form, which languages without that inflection may drop), select arguments missing an
|
||||||
|
// English option, markup or control characters (catalogs are data, never HTML), empty translations
|
||||||
|
// (unless the meta file allows it for a sentence fragment). Warnings do not fail: plural forms the
|
||||||
|
// language uses but the translation leaves to `other`, untranslated keys (they fall back to
|
||||||
|
// English) and translations much longer than the source.
|
||||||
|
|
||||||
|
import { argumentShapes, direction, normalizeLocale, parseMessage, placeholders, pluralCategories, type Catalog } from './i18n.ts';
|
||||||
|
|
||||||
|
export type CatalogIssue = { level: 'error' | 'warning'; locale: string; key?: string; message: string };
|
||||||
|
|
||||||
|
/** `allowEmpty`: a sentence fragment some languages leave empty (word order moves it elsewhere). */
|
||||||
|
export type MetaEntry = { description?: string; maxLength?: number; context?: string; allowEmpty?: boolean };
|
||||||
|
export type Meta = Record<string, MetaEntry | string>;
|
||||||
|
|
||||||
|
const KEY = /^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;
|
||||||
|
/** Markup or script-ish content: tags, entities that decode to markup, `javascript:` and friends. */
|
||||||
|
const MARKUP = /<\s*\/?\s*[a-z!?]|&(?:lt|gt|#0*60|#x0*3c);|javascript:|data:text\/html/i;
|
||||||
|
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f--]/;
|
||||||
|
const STATUSES = new Set(['source', 'machine', 'reviewed']);
|
||||||
|
|
||||||
|
/** A long translation is fine up to this factor of the source length (plus some slack). */
|
||||||
|
const LENGTH_FACTOR = 1.8;
|
||||||
|
const LENGTH_SLACK = 16;
|
||||||
|
|
||||||
|
type Parts = ReturnType<typeof parseMessage>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether `name` puts text in the message: a plain `{name}` / `{name, number}` somewhere, or a `#`
|
||||||
|
* (the number itself) in one of its own plural branches. A plural argument without either only
|
||||||
|
* chooses a form.
|
||||||
|
*/
|
||||||
|
function usedAsText(source: string, name: string): boolean {
|
||||||
|
const pound = (parts: Parts): boolean => parts.some(part => typeof part !== 'string' && (part.kind === 'pound'
|
||||||
|
|| (part.kind === 'select' && Object.values(part.options).some(pound))));
|
||||||
|
const walk = (parts: Parts): boolean => parts.some(part => {
|
||||||
|
if (typeof part === 'string' || part.kind === 'pound') return false;
|
||||||
|
if (part.kind === 'arg') return part.name === name;
|
||||||
|
if (part.kind === 'plural' && part.name === name && Object.values(part.options).some(pound)) return true;
|
||||||
|
return Object.values(part.options).some(walk);
|
||||||
|
});
|
||||||
|
return walk(parseMessage(source));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Checks the file envelope (locale, names, status, reviewers, messages map). */
|
||||||
|
export function checkShape(input: unknown, file = '?'): CatalogIssue[] {
|
||||||
|
const issues: CatalogIssue[] = [];
|
||||||
|
const err = (message: string) => issues.push({ level: 'error', locale: file, message });
|
||||||
|
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
||||||
|
err('a catalog is a JSON object');
|
||||||
|
return issues;
|
||||||
|
}
|
||||||
|
const catalog = input as Partial<Catalog> & Record<string, unknown>;
|
||||||
|
const allowed = new Set(['$schema', 'locale', 'name', 'englishName', 'dir', 'status', 'reviewers', 'fallback', 'messages']);
|
||||||
|
for (const key of Object.keys(catalog)) if (!allowed.has(key)) err(`unknown field "${key}"`);
|
||||||
|
if (typeof catalog.locale !== 'string' || normalizeLocale(catalog.locale) !== catalog.locale) err(`"locale" must be a canonical BCP 47 tag (got ${JSON.stringify(catalog.locale)})`);
|
||||||
|
if (typeof catalog.name !== 'string' || !catalog.name.trim()) err('"name" (the language\'s own name) is required');
|
||||||
|
if (typeof catalog.englishName !== 'string' || !catalog.englishName.trim()) err('"englishName" is required');
|
||||||
|
if (typeof catalog.status !== 'string' || !STATUSES.has(catalog.status)) err('"status" must be "source", "machine" or "reviewed"');
|
||||||
|
if (catalog.status === 'reviewed' && (!Array.isArray(catalog.reviewers) || catalog.reviewers.length === 0)) err('a "reviewed" catalog names its reviewers');
|
||||||
|
if (catalog.reviewers !== undefined && (!Array.isArray(catalog.reviewers) || catalog.reviewers.some(r => typeof r !== 'string' || !r.trim() || r.length > 80))) err('"reviewers" is a list of names or handles');
|
||||||
|
if (catalog.dir !== undefined && catalog.dir !== 'ltr' && catalog.dir !== 'rtl') err('"dir" must be "ltr" or "rtl"');
|
||||||
|
if (typeof catalog.locale === 'string' && catalog.dir && catalog.dir !== direction(catalog.locale)) err(`"dir" says ${catalog.dir} but ${catalog.locale} is written ${direction(catalog.locale)}`);
|
||||||
|
if (catalog.fallback !== undefined && (typeof catalog.fallback !== 'string' || normalizeLocale(catalog.fallback) !== catalog.fallback)) err('"fallback" must be a canonical BCP 47 tag');
|
||||||
|
if (!catalog.messages || typeof catalog.messages !== 'object' || Array.isArray(catalog.messages)) {
|
||||||
|
err('"messages" must be an object of key -> string');
|
||||||
|
} else {
|
||||||
|
for (const [key, value] of Object.entries(catalog.messages)) {
|
||||||
|
if (!KEY.test(key) || key.length > 96) err(`invalid key ${JSON.stringify(key)} (dotted camelCase, at most 96 characters)`);
|
||||||
|
if (typeof value !== 'string') err(`${key}: value must be a string`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return issues;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Safety rules every message obeys, source included. */
|
||||||
|
export function checkMessageSafety(locale: string, key: string, value: string): CatalogIssue[] {
|
||||||
|
const issues: CatalogIssue[] = [];
|
||||||
|
if (MARKUP.test(value)) issues.push({ level: 'error', locale, key, message: 'markup is not allowed (catalogs are text, never HTML)' });
|
||||||
|
if (CONTROL.test(value)) issues.push({ level: 'error', locale, key, message: 'control or bidi-override characters are not allowed' });
|
||||||
|
if (value.length > 2000) issues.push({ level: 'error', locale, key, message: 'message is longer than 2000 characters' });
|
||||||
|
try {
|
||||||
|
parseMessage(value);
|
||||||
|
} catch (error) {
|
||||||
|
issues.push({ level: 'error', locale, key, message: `invalid message syntax: ${error instanceof Error ? error.message : String(error)}` });
|
||||||
|
}
|
||||||
|
return issues;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks one translated catalog against the source messages: extra keys, placeholder parity,
|
||||||
|
* plural categories, safety, untranslated and overlong messages.
|
||||||
|
*/
|
||||||
|
export function checkCatalog(catalog: Catalog, source: Record<string, string>, meta: Meta = {}): CatalogIssue[] {
|
||||||
|
const issues: CatalogIssue[] = [];
|
||||||
|
const locale = catalog.locale;
|
||||||
|
const push = (level: CatalogIssue['level'], key: string | undefined, message: string) => issues.push({ level, locale, key, message });
|
||||||
|
const categories = new Set(pluralCategories(locale));
|
||||||
|
const ordinals = new Set(pluralCategories(locale, true));
|
||||||
|
let missing = 0;
|
||||||
|
for (const [key, value] of Object.entries(catalog.messages)) {
|
||||||
|
const english = source[key];
|
||||||
|
if (english === undefined) {
|
||||||
|
push('error', key, 'key is not in the source catalog (removed or misspelled)');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const safety = checkMessageSafety(locale, key, value);
|
||||||
|
issues.push(...safety);
|
||||||
|
if (safety.some(issue => issue.level === 'error')) continue;
|
||||||
|
const entry = meta[key];
|
||||||
|
const allowEmpty = typeof entry === 'object' && entry.allowEmpty === true;
|
||||||
|
if (!value.trim() && english.trim() && !allowEmpty) push('error', key, 'empty translation (remove the key to fall back to English)');
|
||||||
|
const want = placeholders(english);
|
||||||
|
const have = placeholders(value);
|
||||||
|
const sourceShapes = argumentShapes(english);
|
||||||
|
// An argument English only uses to pick a plural form ("Download {count, plural, one {it} other
|
||||||
|
// {them}}") may be dropped by a language that does not inflect there; every other placeholder
|
||||||
|
// carries text the reader needs and is required.
|
||||||
|
const pluralOnly = (name: string) => {
|
||||||
|
const shape = sourceShapes[name];
|
||||||
|
return !!shape && shape.kind !== 'select' && !usedAsText(english, name);
|
||||||
|
};
|
||||||
|
const missingNames = want.filter(name => !have.includes(name) && !pluralOnly(name));
|
||||||
|
const extraNames = have.filter(name => !want.includes(name));
|
||||||
|
if (missingNames.length) push('error', key, `missing placeholder(s) ${missingNames.map(n => `{${n}}`).join(', ')}`);
|
||||||
|
if (extraNames.length) push('error', key, `unknown placeholder(s) ${extraNames.map(n => `{${n}}`).join(', ')}`);
|
||||||
|
const shapes = argumentShapes(value);
|
||||||
|
for (const [name, shape] of Object.entries(shapes)) {
|
||||||
|
const expected = sourceShapes[name];
|
||||||
|
if (expected && expected.kind !== shape.kind) {
|
||||||
|
push('error', key, `{${name}} is a ${expected.kind} in English but a ${shape.kind} here`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (shape.kind === 'select') {
|
||||||
|
for (const option of expected?.options ?? []) {
|
||||||
|
if (!shape.options.includes(option)) push('error', key, `{${name}, select} lacks the "${option}" option`);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// A form the translation leaves out falls back to its `other` branch, which is often right
|
||||||
|
// (an invariable word, an abbreviation, `=1` already covering "one"): a warning for review.
|
||||||
|
const needed = shape.kind === 'selectordinal' ? ordinals : categories;
|
||||||
|
for (const category of needed) {
|
||||||
|
if (!shape.options.includes(category)) push('warning', key, `{${name}, ${shape.kind}} has no "${category}" form (${locale} uses it; "other" is shown)`);
|
||||||
|
}
|
||||||
|
for (const option of shape.options) {
|
||||||
|
if (!option.startsWith('=') && !needed.has(option as Intl.LDMLPluralRule)) push('warning', key, `{${name}, ${shape.kind}} has a "${option}" form ${locale} never uses`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const maxLength = typeof entry === 'object' ? entry.maxLength : undefined;
|
||||||
|
const limit = maxLength ?? Math.round(english.length * LENGTH_FACTOR + LENGTH_SLACK);
|
||||||
|
if (value.length > limit) push(maxLength ? 'error' : 'warning', key, `translation is ${value.length} characters (${maxLength ? 'limit' : 'English is'} ${maxLength ?? english.length})`);
|
||||||
|
}
|
||||||
|
if (catalog.status !== 'source' && !catalog.fallback) {
|
||||||
|
for (const key of Object.keys(source)) if (!(key in catalog.messages)) missing += 1;
|
||||||
|
if (missing) push('warning', undefined, `${missing} of ${Object.keys(source).length} messages untranslated (English is shown)`);
|
||||||
|
}
|
||||||
|
return issues;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Checks the source catalog itself: safety, syntax, and that every key is described in the meta file. */
|
||||||
|
export function checkSource(catalog: Catalog, meta: Meta = {}): CatalogIssue[] {
|
||||||
|
const issues: CatalogIssue[] = [];
|
||||||
|
for (const [key, value] of Object.entries(catalog.messages)) issues.push(...checkMessageSafety(catalog.locale, key, value));
|
||||||
|
for (const key of Object.keys(meta)) {
|
||||||
|
if (!(key in catalog.messages)) issues.push({ level: 'error', locale: catalog.locale, key, message: 'described in the meta file but not in the source catalog' });
|
||||||
|
}
|
||||||
|
return issues;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Share of source keys a catalog translates (0..1), following its `fallback` catalog when given. */
|
||||||
|
export function coverage(catalog: Catalog, source: Record<string, string>, fallback?: Catalog): number {
|
||||||
|
const keys = Object.keys(source);
|
||||||
|
if (!keys.length) return 1;
|
||||||
|
const done = keys.filter(key => key in catalog.messages || (fallback ? key in fallback.messages : false)).length;
|
||||||
|
return done / keys.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TypeScript source for a key union and per-key parameter types, generated from source messages. */
|
||||||
|
export function generateKeyTypes(source: Record<string, string>, typeName = 'MessageKey'): string {
|
||||||
|
const keys = Object.keys(source).sort();
|
||||||
|
const lines = [
|
||||||
|
'// Generated from the English source catalog. Do not edit by hand.',
|
||||||
|
`export type ${typeName} =`,
|
||||||
|
...keys.map((key, index) => ` | ${JSON.stringify(key)}${index === keys.length - 1 ? ';' : ''}`),
|
||||||
|
'',
|
||||||
|
`export type ${typeName}Params = {`,
|
||||||
|
];
|
||||||
|
for (const key of keys) {
|
||||||
|
let names: string[] = [];
|
||||||
|
try { names = placeholders(source[key]!); } catch { names = []; }
|
||||||
|
lines.push(` ${JSON.stringify(key)}: ${names.length ? `{ ${names.map(name => `${name}: string | number | Date`).join('; ')} }` : 'undefined'};`);
|
||||||
|
}
|
||||||
|
lines.push('};', '');
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
28
packages/runtime/src/pageLang.ts
Normal file
28
packages/runtime/src/pageLang.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
// Tells the app which language the site's own UI is in (its `<html lang>`), so the app can follow
|
||||||
|
// it ("Follow X" in Settings → Language). Read from the document the site renders anyway; nothing is
|
||||||
|
// requested. Only a change is reported (`tab_report { lang }`); native code accepts it only from a
|
||||||
|
// site tab and only as a validated language tag.
|
||||||
|
|
||||||
|
import { normalizeLocale } from './i18n.ts';
|
||||||
|
|
||||||
|
export type Invoke = (command: string, args: Record<string, unknown>) => Promise<unknown>;
|
||||||
|
|
||||||
|
/** The page's language as a canonical tag, or null when it declares none (or nonsense). */
|
||||||
|
export function readPageLang(doc: Document): string | null {
|
||||||
|
return normalizeLocale(doc.documentElement?.getAttribute('lang') ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function installPageLangReport(win: Window & typeof globalThis, invoke?: Invoke): { dispose(): void } {
|
||||||
|
if (!invoke) return { dispose() {} };
|
||||||
|
let last = '';
|
||||||
|
const check = () => {
|
||||||
|
const lang = readPageLang(win.document);
|
||||||
|
if (!lang || lang === last) return;
|
||||||
|
last = lang;
|
||||||
|
invoke('tab_report', { report: { lang } }).catch(() => { last = ''; });
|
||||||
|
};
|
||||||
|
const observer = new win.MutationObserver(check);
|
||||||
|
if (win.document.documentElement) observer.observe(win.document.documentElement, { attributes: true, attributeFilter: ['lang'] });
|
||||||
|
check();
|
||||||
|
return { dispose: () => observer.disconnect() };
|
||||||
|
}
|
||||||
|
|
@ -134,8 +134,14 @@ export type PluginContext<T extends object> = {
|
||||||
grants(id: string): readonly string[] | null | undefined;
|
grants(id: string): readonly string[] | null | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Members bound to the plugin a view belongs to (its `i18n`, keyed by the plugin file), applied to
|
||||||
|
* every plugin's view, legacy plugins included. Not a permission: bound members are never gated.
|
||||||
|
*/
|
||||||
|
export type PluginBindings<T extends object> = (full: T, plugin: string) => Partial<T>;
|
||||||
|
|
||||||
/** Per-plugin API views for a runtime whose `api` getter returns `context.current()`. */
|
/** Per-plugin API views for a runtime whose `api` getter returns `context.current()`. */
|
||||||
export function createPluginContext<T extends object>(full: T, gates: PermissionGates = CORE_GATES): PluginContext<T> {
|
export function createPluginContext<T extends object>(full: T, gates: PermissionGates = CORE_GATES, bind?: PluginBindings<T>): PluginContext<T> {
|
||||||
const registered = new Map<string, { grants: readonly string[] | null; api: T }>();
|
const registered = new Map<string, { grants: readonly string[] | null; api: T }>();
|
||||||
const stack: T[] = [];
|
const stack: T[] = [];
|
||||||
return {
|
return {
|
||||||
|
|
@ -143,7 +149,8 @@ export function createPluginContext<T extends object>(full: T, gates: Permission
|
||||||
let entry = registered.get(id);
|
let entry = registered.get(id);
|
||||||
if (grants !== undefined || !entry) {
|
if (grants !== undefined || !entry) {
|
||||||
const list = Array.isArray(grants) ? Object.freeze(grants.filter(grant => typeof grant === 'string' && KNOWN.has(grant))) : null;
|
const list = Array.isArray(grants) ? Object.freeze(grants.filter(grant => typeof grant === 'string' && KNOWN.has(grant))) : null;
|
||||||
entry = { grants: list, api: list ? scopePluginApi(full, list, id, gates) : full };
|
const view = list ? scopePluginApi(full, list, id, gates) : full;
|
||||||
|
entry = { grants: list, api: bind ? Object.freeze({ ...view, ...bind(full, id) }) as T : view };
|
||||||
registered.set(id, entry);
|
registered.set(id, entry);
|
||||||
}
|
}
|
||||||
stack.push(entry.api);
|
stack.push(entry.api);
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,9 @@ import { createThemeApi, type ThemeApi, type ThemeSource } from './themeApi.ts';
|
||||||
import { createUiKit, type UiKit } from './ui.ts';
|
import { createUiKit, type UiKit } from './ui.ts';
|
||||||
import { adoptStyles, type RootStyles } from './styles.ts';
|
import { adoptStyles, type RootStyles } from './styles.ts';
|
||||||
import { createCommandRegistry, type CommandDefinition, type CommandInfo, type CommandRegistry } from './commands.ts';
|
import { createCommandRegistry, type CommandDefinition, type CommandInfo, type CommandRegistry } from './commands.ts';
|
||||||
|
import { createPluginI18n, type I18nSource, type PluginI18n, type PluginMessages } from './pluginI18n.ts';
|
||||||
|
|
||||||
export type { ThemeApi, ThemeSource, UiKit, CommandDefinition, CommandInfo, CommandRegistry, RootStyles };
|
export type { ThemeApi, ThemeSource, UiKit, CommandDefinition, CommandInfo, CommandRegistry, RootStyles, I18nSource, PluginI18n, PluginMessages };
|
||||||
|
|
||||||
export type Dispose = () => void;
|
export type Dispose = () => void;
|
||||||
|
|
||||||
|
|
@ -78,12 +79,20 @@ export type CorePluginApi = {
|
||||||
* this page (see commands.ts). Removed when the plugin stops.
|
* this page (see commands.ts). Removed when the plugin stops.
|
||||||
*/
|
*/
|
||||||
commands: CommandRegistry;
|
commands: CommandRegistry;
|
||||||
|
/**
|
||||||
|
* The app's language and the plugin's own strings in it (see pluginI18n.ts). In a plugin's view
|
||||||
|
* it is bound to that plugin (`plugin.<file name>.*` in the app catalog); `namespace(name)` binds
|
||||||
|
* it explicitly.
|
||||||
|
*/
|
||||||
|
i18n: PluginI18n;
|
||||||
scope(): PluginScope;
|
scope(): PluginScope;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** What the site adapter adds to the core: its theme engine, when it has one. */
|
/** What the site adapter adds to the core: its theme engine, when it has one. */
|
||||||
export type CorePluginExtras = {
|
export type CorePluginExtras = {
|
||||||
theme?: ThemeSource;
|
theme?: ThemeSource;
|
||||||
|
/** The app's active locale and catalog (plugin strings, the UI kit's own words). English without it. */
|
||||||
|
i18n?: I18nSource;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type PluginApiSite = {
|
export type PluginApiSite = {
|
||||||
|
|
@ -123,7 +132,8 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
|
||||||
const theme = createThemeApi(win, extras.theme, /^#[0-9a-f]{6}$/i.test(site.toastBackground) ? site.toastBackground : undefined);
|
const theme = createThemeApi(win, extras.theme, /^#[0-9a-f]{6}$/i.test(site.toastBackground) ? site.toastBackground : undefined);
|
||||||
// Created on first use: the kit touches the DOM only when something is shown.
|
// Created on first use: the kit touches the DOM only when something is shown.
|
||||||
let kit: ReturnType<typeof createUiKit> | null = null;
|
let kit: ReturnType<typeof createUiKit> | null = null;
|
||||||
const uiKit = () => kit ??= createUiKit(win, { theme, product: site.product, hostId: site.toastId });
|
const i18n = createPluginI18n(extras.i18n);
|
||||||
|
const uiKit = () => kit ??= createUiKit(win, { theme, product: site.product, hostId: site.toastId, text: key => extras.i18n?.message(key) });
|
||||||
const ui: UiKit = Object.freeze({
|
const ui: UiKit = Object.freeze({
|
||||||
toast: (...args: Parameters<UiKit['toast']>) => uiKit().toast(...args),
|
toast: (...args: Parameters<UiKit['toast']>) => uiKit().toast(...args),
|
||||||
alert: (...args: Parameters<UiKit['alert']>) => uiKit().alert(...args),
|
alert: (...args: Parameters<UiKit['alert']>) => uiKit().alert(...args),
|
||||||
|
|
@ -315,6 +325,7 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
|
||||||
ui,
|
ui,
|
||||||
theme,
|
theme,
|
||||||
commands,
|
commands,
|
||||||
|
i18n,
|
||||||
scope() {
|
scope() {
|
||||||
let disposers: Dispose[] = [];
|
let disposers: Dispose[] = [];
|
||||||
let scopedUi: UiKit | null = null;
|
let scopedUi: UiKit | null = null;
|
||||||
|
|
|
||||||
127
packages/runtime/src/pluginI18n.ts
Normal file
127
packages/runtime/src/pluginI18n.ts
Normal file
|
|
@ -0,0 +1,127 @@
|
||||||
|
// `api.i18n` for plugins: the app's language, and each plugin's own strings in it.
|
||||||
|
//
|
||||||
|
// const i18n = window.wayBetter.api.i18n; // bound to the running plugin
|
||||||
|
// i18n.register({ en: { saved: 'Saved {count, plural, one {# note} other {# notes}}' },
|
||||||
|
// tr: { saved: '{count, plural, one {# not} other {# not}} kaydedildi' } });
|
||||||
|
// i18n.t('saved', { count: 2 }); // in the app's language, English otherwise
|
||||||
|
// i18n.locale; i18n.dir; i18n.onChange(() => rerender());
|
||||||
|
// i18n.number(1234.5); i18n.date(Date.now(), { dateStyle: 'medium' }); i18n.relative(-3, 'minute');
|
||||||
|
//
|
||||||
|
// A plugin's key `k` is looked up in the plugin's own messages for the app's locale chain, then in
|
||||||
|
// the app's catalog as `plugin.<namespace>.k` (bundled plugins are translated there, by the same
|
||||||
|
// contributors as the app), then in the plugin's English. The namespace is the plugin file name
|
||||||
|
// without `.plugin.js`. Messages are text: placeholders are inserted as text, never parsed as HTML.
|
||||||
|
|
||||||
|
import { direction, fallbackChain, formatMessage, normalizeLocale, numberFormat, dateFormat, type Dir, type Params } from './i18n.ts';
|
||||||
|
|
||||||
|
/** What the site adapter supplies: the app's active locale and its resolved catalog. */
|
||||||
|
export type I18nSource = {
|
||||||
|
locale(): string;
|
||||||
|
/** The app catalog's message for `key` in the active locale (its fallback chain applied), if any. */
|
||||||
|
message(key: string): string | undefined;
|
||||||
|
onChange(listener: () => void): () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PluginMessages = Record<string, Record<string, string>>;
|
||||||
|
|
||||||
|
export type PluginI18n = {
|
||||||
|
readonly locale: string;
|
||||||
|
readonly dir: Dir;
|
||||||
|
/** The plugin's message `key` in the app's language, formatted with `params`; the key when unknown. */
|
||||||
|
t(key: string, params?: Params): string;
|
||||||
|
has(key: string): boolean;
|
||||||
|
/** Adds the plugin's own messages, keyed by locale (`{ en: {...}, tr: {...} }`); later calls merge. */
|
||||||
|
register(messages: PluginMessages): void;
|
||||||
|
/** Calls `listener(locale)` after the app's language changes. Returns a dispose. */
|
||||||
|
onChange(listener: (locale: string) => void): () => void;
|
||||||
|
number(value: number, options?: Intl.NumberFormatOptions): string;
|
||||||
|
date(value: Date | number | string, options?: Intl.DateTimeFormatOptions): string;
|
||||||
|
relative(value: number, unit: Intl.RelativeTimeFormatUnit): string;
|
||||||
|
list(items: readonly string[]): string;
|
||||||
|
/** The same API for another namespace (a plugin with several files, or code outside `start()`). */
|
||||||
|
namespace(name: string): PluginI18n;
|
||||||
|
};
|
||||||
|
|
||||||
|
const NAMESPACE = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
|
||||||
|
const MAX_KEYS = 2000;
|
||||||
|
const MAX_VALUE = 2000;
|
||||||
|
|
||||||
|
/** `emoji-picker.plugin.js` -> `emoji-picker`. */
|
||||||
|
export function pluginNamespace(id: string): string {
|
||||||
|
return String(id).replace(/\.plugin\.js$/i, '').replace(/[^a-z0-9._-]/gi, '-').slice(0, 64) || 'plugin';
|
||||||
|
}
|
||||||
|
|
||||||
|
const ENGLISH: I18nSource = { locale: () => 'en', message: () => undefined, onChange: () => () => {} };
|
||||||
|
|
||||||
|
export function createPluginI18n(source: I18nSource = ENGLISH, namespace = ''): PluginI18n {
|
||||||
|
// Shared per namespace so a plugin's `register` in start() is seen by every view of it.
|
||||||
|
const registry = new Map<string, Map<string, Record<string, string>>>();
|
||||||
|
|
||||||
|
const make = (ns: string): PluginI18n => {
|
||||||
|
const own = () => {
|
||||||
|
let table = registry.get(ns);
|
||||||
|
if (!table) { table = new Map(); registry.set(ns, table); }
|
||||||
|
return table;
|
||||||
|
};
|
||||||
|
const locale = () => normalizeLocale(source.locale()) ?? 'en';
|
||||||
|
const lookup = (key: string): string | undefined => {
|
||||||
|
const chain = fallbackChain(locale(), 'en');
|
||||||
|
const table = own();
|
||||||
|
// Own translations first (not English yet: the app catalog may translate a bundled plugin).
|
||||||
|
for (const tag of chain) {
|
||||||
|
if (tag === 'en') break;
|
||||||
|
const value = table.get(tag)?.[key];
|
||||||
|
if (typeof value === 'string') return value;
|
||||||
|
}
|
||||||
|
if (ns) {
|
||||||
|
const hosted = source.message(`plugin.${ns}.${key}`);
|
||||||
|
if (typeof hosted === 'string') return hosted;
|
||||||
|
}
|
||||||
|
return table.get('en')?.[key];
|
||||||
|
};
|
||||||
|
return Object.freeze({
|
||||||
|
get locale() { return locale(); },
|
||||||
|
get dir() { return direction(locale()); },
|
||||||
|
t(key: string, params?: Params) {
|
||||||
|
const message = lookup(String(key));
|
||||||
|
return message === undefined ? String(key) : formatMessage(message, params ?? {}, locale());
|
||||||
|
},
|
||||||
|
has: (key: string) => lookup(String(key)) !== undefined,
|
||||||
|
register(messages: PluginMessages) {
|
||||||
|
if (!messages || typeof messages !== 'object') return;
|
||||||
|
const table = own();
|
||||||
|
for (const [tag, entries] of Object.entries(messages)) {
|
||||||
|
const normalized = normalizeLocale(tag);
|
||||||
|
if (!normalized || !entries || typeof entries !== 'object') continue;
|
||||||
|
const target = { ...table.get(normalized) };
|
||||||
|
for (const [key, value] of Object.entries(entries)) {
|
||||||
|
if (typeof value !== 'string' || value.length > MAX_VALUE || Object.keys(target).length >= MAX_KEYS) continue;
|
||||||
|
target[key] = value;
|
||||||
|
}
|
||||||
|
table.set(normalized, target);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onChange(listener: (locale: string) => void) {
|
||||||
|
return source.onChange(() => {
|
||||||
|
try { listener(locale()); } catch (error) { console.error('[wayBetter] i18n listener failed', error); }
|
||||||
|
});
|
||||||
|
},
|
||||||
|
number: (value: number, options?: Intl.NumberFormatOptions) => numberFormat(locale(), options).format(value),
|
||||||
|
date: (value: Date | number | string, options?: Intl.DateTimeFormatOptions) => {
|
||||||
|
const date = value instanceof Date ? value : new Date(value);
|
||||||
|
return Number.isFinite(date.getTime()) ? dateFormat(locale(), options).format(date) : '';
|
||||||
|
},
|
||||||
|
relative(value: number, unit: Intl.RelativeTimeFormatUnit) {
|
||||||
|
try { return new Intl.RelativeTimeFormat(locale().split('-x-')[0], { numeric: 'auto' }).format(value, unit); } catch { return `${value} ${unit}`; }
|
||||||
|
},
|
||||||
|
list(items: readonly string[]) {
|
||||||
|
try { return new Intl.ListFormat(locale().split('-x-')[0], { type: 'conjunction' }).format(items); } catch { return items.join(', '); }
|
||||||
|
},
|
||||||
|
namespace(name: string) {
|
||||||
|
if (!NAMESPACE.test(String(name))) throw new Error(`i18n.namespace: invalid name ${JSON.stringify(name)}`);
|
||||||
|
return make(String(name));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
return make(namespace);
|
||||||
|
}
|
||||||
|
|
@ -133,8 +133,27 @@ export type UiKitOptions = {
|
||||||
zIndex?: number;
|
zIndex?: number;
|
||||||
/** Console prefix. */
|
/** Console prefix. */
|
||||||
product?: string;
|
product?: string;
|
||||||
|
/**
|
||||||
|
* The kit's own words (buttons, accessible names, default errors) in the app's language:
|
||||||
|
* called with a `kit.*` key and returns the translation, or undefined for English.
|
||||||
|
*/
|
||||||
|
text?: (key: KitKey) => string | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** The kit's default words (English source; `kit.*` keys in the framework catalogs). */
|
||||||
|
export const KIT_MESSAGES = {
|
||||||
|
'kit.ok': 'OK',
|
||||||
|
'kit.cancel': 'Cancel',
|
||||||
|
'kit.delete': 'Delete',
|
||||||
|
'kit.close': 'Close',
|
||||||
|
'kit.dismiss': 'Dismiss',
|
||||||
|
'kit.dialog': 'Dialog',
|
||||||
|
'kit.value': 'Value',
|
||||||
|
'kit.checkValue': 'Please check this value.',
|
||||||
|
'kit.failed': 'Something went wrong.',
|
||||||
|
} as const;
|
||||||
|
export type KitKey = keyof typeof KIT_MESSAGES;
|
||||||
|
|
||||||
export type RootUiKit = UiKit & {
|
export type RootUiKit = UiKit & {
|
||||||
/** A kit whose dialogs and toasts are closed by `dispose()` (a plugin's `scope.ui`). */
|
/** A kit whose dialogs and toasts are closed by `dispose()` (a plugin's `scope.ui`). */
|
||||||
scoped(): { kit: UiKit; dispose(): void };
|
scoped(): { kit: UiKit; dispose(): void };
|
||||||
|
|
@ -172,9 +191,9 @@ export function trapIndex(count: number, current: number, backwards: boolean): n
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A validator's answer as an error message (null = valid). */
|
/** A validator's answer as an error message (null = valid). */
|
||||||
export function validationMessage(result: unknown): string | null {
|
export function validationMessage(result: unknown, fallback: string = KIT_MESSAGES['kit.checkValue']): string | null {
|
||||||
if (typeof result === 'string') return result.trim() ? result : null;
|
if (typeof result === 'string') return result.trim() ? result : null;
|
||||||
if (result === false) return 'Please check this value.';
|
if (result === false) return fallback;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -358,6 +377,13 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
|
||||||
const hostTag = options.hostTag ?? 'wb-ui';
|
const hostTag = options.hostTag ?? 'wb-ui';
|
||||||
const product = options.product ?? 'wayBetter';
|
const product = options.product ?? 'wayBetter';
|
||||||
const report = (error: unknown) => console.error(`[${product}] ui callback failed`, error);
|
const report = (error: unknown) => console.error(`[${product}] ui callback failed`, error);
|
||||||
|
const word = (key: KitKey): string => {
|
||||||
|
try {
|
||||||
|
const value = options.text?.(key);
|
||||||
|
if (typeof value === 'string' && value) return value;
|
||||||
|
} catch { /* a broken translator must not break a dialog */ }
|
||||||
|
return KIT_MESSAGES[key];
|
||||||
|
};
|
||||||
const isShadowRoot = (node: unknown): node is ShadowRoot => typeof win.ShadowRoot === 'function' && node instanceof win.ShadowRoot;
|
const isShadowRoot = (node: unknown): node is ShadowRoot => typeof win.ShadowRoot === 'function' && node instanceof win.ShadowRoot;
|
||||||
const reducedMotion = () => { try { return !!win.matchMedia?.('(prefers-reduced-motion: reduce)').matches; } catch { return false; } };
|
const reducedMotion = () => { try { return !!win.matchMedia?.('(prefers-reduced-motion: reduce)').matches; } catch { return false; } };
|
||||||
|
|
||||||
|
|
@ -516,7 +542,7 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
|
||||||
const x = doc.createElement('button');
|
const x = doc.createElement('button');
|
||||||
x.type = 'button';
|
x.type = 'button';
|
||||||
x.className = 'wb-close';
|
x.className = 'wb-close';
|
||||||
x.setAttribute('aria-label', 'Close');
|
x.setAttribute('aria-label', word('kit.close'));
|
||||||
x.appendChild(svg(ICONS.close));
|
x.appendChild(svg(ICONS.close));
|
||||||
x.addEventListener('click', () => dismiss());
|
x.addEventListener('click', () => dismiss());
|
||||||
head.appendChild(x);
|
head.appendChild(x);
|
||||||
|
|
@ -524,7 +550,7 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
|
||||||
panel.appendChild(head);
|
panel.appendChild(head);
|
||||||
if (opts.title) panel.setAttribute('aria-labelledby', title.id);
|
if (opts.title) panel.setAttribute('aria-labelledby', title.id);
|
||||||
}
|
}
|
||||||
if (!opts.title) panel.setAttribute('aria-label', opts.label || opts.message || 'Dialog');
|
if (!opts.title) panel.setAttribute('aria-label', opts.label || opts.message || word('kit.dialog'));
|
||||||
if (opts.message) {
|
if (opts.message) {
|
||||||
const message = doc.createElement('p');
|
const message = doc.createElement('p');
|
||||||
message.className = 'wb-message';
|
message.className = 'wb-message';
|
||||||
|
|
@ -598,7 +624,7 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
report(err);
|
report(err);
|
||||||
handle.setError(err instanceof Error && err.message ? err.message : 'Something went wrong.');
|
handle.setError(err instanceof Error && err.message ? err.message : word('kit.failed'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
keep = result === false;
|
keep = result === false;
|
||||||
|
|
@ -801,7 +827,7 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
|
||||||
const dismissButton = doc.createElement('button');
|
const dismissButton = doc.createElement('button');
|
||||||
dismissButton.type = 'button';
|
dismissButton.type = 'button';
|
||||||
dismissButton.className = 'wb-toast-close';
|
dismissButton.className = 'wb-toast-close';
|
||||||
dismissButton.setAttribute('aria-label', 'Dismiss');
|
dismissButton.setAttribute('aria-label', word('kit.dismiss'));
|
||||||
dismissButton.appendChild(svg(ICONS.close));
|
dismissButton.appendChild(svg(ICONS.close));
|
||||||
dismissButton.addEventListener('click', () => close());
|
dismissButton.addEventListener('click', () => close());
|
||||||
element.appendChild(dismissButton);
|
element.appendChild(dismissButton);
|
||||||
|
|
@ -827,7 +853,7 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
|
||||||
const handle = modal({
|
const handle = modal({
|
||||||
role: 'alertdialog', title: text(opts.title) || undefined, message: text(opts.message) || undefined, tone: opts.tone,
|
role: 'alertdialog', title: text(opts.title) || undefined, message: text(opts.message) || undefined, tone: opts.tone,
|
||||||
width: 'sm', closeOnBackdrop: true, closeButton: false, stackActions: true,
|
width: 'sm', closeOnBackdrop: true, closeButton: false, stackActions: true,
|
||||||
actions: [{ label: opts.okLabel || 'OK', tone: 'primary', default: true, autoFocus: true, value: undefined }],
|
actions: [{ label: opts.okLabel || word('kit.ok'), tone: 'primary', default: true, autoFocus: true, value: undefined }],
|
||||||
}, owner);
|
}, owner);
|
||||||
return handle.closed.then(() => undefined);
|
return handle.closed.then(() => undefined);
|
||||||
}
|
}
|
||||||
|
|
@ -840,8 +866,8 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
|
||||||
width: 'sm', closeOnBackdrop: true, closeButton: false, stackActions: true, dismissValue: false,
|
width: 'sm', closeOnBackdrop: true, closeButton: false, stackActions: true, dismissValue: false,
|
||||||
actions: [
|
actions: [
|
||||||
// A destructive confirmation starts on Cancel, so Enter never destroys by accident.
|
// A destructive confirmation starts on Cancel, so Enter never destroys by accident.
|
||||||
{ label: opts.confirmLabel || (danger ? 'Delete' : 'OK'), tone: danger ? 'danger' : 'primary', value: true, default: !danger, autoFocus: !danger },
|
{ label: opts.confirmLabel || (danger ? word('kit.delete') : word('kit.ok')), tone: danger ? 'danger' : 'primary', value: true, default: !danger, autoFocus: !danger },
|
||||||
{ label: opts.cancelLabel || 'Cancel', tone: 'secondary', value: false, autoFocus: danger },
|
{ label: opts.cancelLabel || word('kit.cancel'), tone: 'secondary', value: false, autoFocus: danger },
|
||||||
],
|
],
|
||||||
}, owner);
|
}, owner);
|
||||||
return handle.closed.then(result => result === true);
|
return handle.closed.then(result => result === true);
|
||||||
|
|
@ -860,7 +886,7 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
|
||||||
let handle!: ModalHandle;
|
let handle!: ModalHandle;
|
||||||
const check = () => {
|
const check = () => {
|
||||||
let message: string | null = null;
|
let message: string | null = null;
|
||||||
try { message = validationMessage(opts.validate?.(field.value)); } catch (err) { message = err instanceof Error ? err.message : 'Please check this value.'; }
|
try { message = validationMessage(opts.validate?.(field.value), word('kit.checkValue')); } catch (err) { message = err instanceof Error ? err.message : word('kit.checkValue'); }
|
||||||
field.setAttribute('aria-invalid', message ? 'true' : 'false');
|
field.setAttribute('aria-invalid', message ? 'true' : 'false');
|
||||||
handle.setError(message);
|
handle.setError(message);
|
||||||
return !message;
|
return !message;
|
||||||
|
|
@ -876,13 +902,13 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
|
||||||
caption.className = 'wb-label';
|
caption.className = 'wb-label';
|
||||||
caption.textContent = opts.label;
|
caption.textContent = opts.label;
|
||||||
wrap.appendChild(caption);
|
wrap.appendChild(caption);
|
||||||
} else field.setAttribute('aria-label', text(opts.title) || 'Value');
|
} else field.setAttribute('aria-label', text(opts.title) || word('kit.value'));
|
||||||
wrap.appendChild(field);
|
wrap.appendChild(field);
|
||||||
body.appendChild(wrap);
|
body.appendChild(wrap);
|
||||||
},
|
},
|
||||||
actions: [
|
actions: [
|
||||||
{ label: opts.cancelLabel || 'Cancel', tone: 'secondary', value: null },
|
{ label: opts.cancelLabel || word('kit.cancel'), tone: 'secondary', value: null },
|
||||||
{ label: opts.confirmLabel || 'OK', tone: 'primary', default: true, onClick: () => { tried = true; return check() ? undefined : false; }, value: undefined },
|
{ label: opts.confirmLabel || word('kit.ok'), tone: 'primary', default: true, onClick: () => { tried = true; return check() ? undefined : false; }, value: undefined },
|
||||||
],
|
],
|
||||||
initialFocus: field,
|
initialFocus: field,
|
||||||
}, owner);
|
}, owner);
|
||||||
|
|
|
||||||
29
packages/shell/src/messages.ts
Normal file
29
packages/shell/src/messages.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
// The shell models' own words (account labels, the update chip) in English, with `{name}`
|
||||||
|
// placeholders. They live in the framework catalogs (`waybetter/locales/<bcp47>.json`, `wb.*`), so
|
||||||
|
// every wayBetter app shows them in its language: pass a `text(key)` translator to the models; it
|
||||||
|
// returns the translated message (placeholders not yet filled) or undefined for English.
|
||||||
|
|
||||||
|
export const SHELL_MESSAGES = {
|
||||||
|
'wb.account.notSignedIn': 'Not signed in yet',
|
||||||
|
'wb.account.signedOut': '{handle} · signed out',
|
||||||
|
'wb.account.newName': 'New account',
|
||||||
|
'wb.update.readyLabel': 'Update ready · restart',
|
||||||
|
'wb.update.readyTitle': 'Restart to update to {product} {version}. Tabs are restored.',
|
||||||
|
'wb.update.installingLabel': 'Updating…',
|
||||||
|
'wb.update.installingTitle': 'Installing {product} {version}',
|
||||||
|
'wb.update.problemLabel': 'Update problem',
|
||||||
|
'wb.update.problemTitle': 'The last update did not start correctly. Download the current version.',
|
||||||
|
} as const;
|
||||||
|
export type ShellKey = keyof typeof SHELL_MESSAGES;
|
||||||
|
/** A translator for the shell models: the message for `key` (unformatted) or undefined for English. */
|
||||||
|
export type ShellText = (key: ShellKey) => string | undefined;
|
||||||
|
|
||||||
|
/** The message for `key` with `{name}` placeholders filled in (values inserted as text). */
|
||||||
|
export function shellText(key: ShellKey, params: Record<string, string> = {}, text?: ShellText): string {
|
||||||
|
let message: string = SHELL_MESSAGES[key];
|
||||||
|
try {
|
||||||
|
const translated = text?.(key);
|
||||||
|
if (typeof translated === 'string' && translated) message = translated;
|
||||||
|
} catch { /* English */ }
|
||||||
|
return message.replace(/\{(\w+)\}/g, (whole, name: string) => (name in params ? params[name]! : whole));
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
// Pure model for account profiles (no Tauri imports, so it is unit-tested under node).
|
// Pure model for account profiles (no Tauri imports, so it is unit-tested under node).
|
||||||
// Mirrors `ProfileSettings` in waybetter-host `profiles.rs`; Rust validates again on save.
|
// Mirrors `ProfileSettings` in waybetter-host `profiles.rs`; Rust validates again on save.
|
||||||
|
|
||||||
|
import { shellText, type ShellText } from './messages.ts';
|
||||||
|
|
||||||
/** The login inside a profile, as native code last saw it (read-only here; see profiles.rs). */
|
/** The login inside a profile, as native code last saw it (read-only here; see profiles.rs). */
|
||||||
export type Account = { handle: string; name: string; avatar?: string; signedIn: boolean };
|
export type Account = { handle: string; name: string; avatar?: string; signedIn: boolean };
|
||||||
export type Profile = { id: string; name: string; color: string; account?: Account };
|
export type Profile = { id: string; name: string; color: string; account?: Account };
|
||||||
|
|
@ -60,11 +62,12 @@ export function normalizeAccount(value: unknown, rules: AccountRules): Account |
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What the switcher shows for a profile: the login once seen, the profile name before. */
|
/** What the switcher shows for a profile: the login once seen, the profile name before. */
|
||||||
export function accountLabel(profile: Profile, rules: Pick<AccountRules, 'handlePrefix'>): { title: string; detail: string; state: 'signed-in' | 'signed-out' | 'new' } {
|
export function accountLabel(profile: Profile, rules: Pick<AccountRules, 'handlePrefix'>, text?: ShellText): { title: string; detail: string; state: 'signed-in' | 'signed-out' | 'new' } {
|
||||||
if (!profile.account) return { title: profile.name, detail: 'Not signed in yet', state: 'new' };
|
if (!profile.account) return { title: profile.name, detail: shellText('wb.account.notSignedIn', {}, text), state: 'new' };
|
||||||
|
const handle = `${rules.handlePrefix}${profile.account.handle}`;
|
||||||
return {
|
return {
|
||||||
title: profile.account.name,
|
title: profile.account.name,
|
||||||
detail: `${rules.handlePrefix}${profile.account.handle}${profile.account.signedIn ? '' : ' · signed out'}`,
|
detail: profile.account.signedIn ? handle : shellText('wb.account.signedOut', { handle }, text),
|
||||||
state: profile.account.signedIn ? 'signed-in' : 'signed-out',
|
state: profile.account.signedIn ? 'signed-in' : 'signed-out',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -80,8 +83,8 @@ export function nextColor(settings: ProfileSettings): string {
|
||||||
|
|
||||||
/** Adds a profile and makes it active. Unlimited count (Rust caps absurd sizes). Its name follows the
|
/** Adds a profile and makes it active. Unlimited count (Rust caps absurd sizes). Its name follows the
|
||||||
* account once someone signs in there; until then it is a placeholder. */
|
* account once someone signs in there; until then it is a placeholder. */
|
||||||
export function addProfile(settings: ProfileSettings, name = '', id = newProfileId()): ProfileSettings {
|
export function addProfile(settings: ProfileSettings, name = '', id = newProfileId(), text?: ShellText): ProfileSettings {
|
||||||
const clean = cleanName(name) ?? 'New account';
|
const clean = cleanName(name) ?? shellText('wb.account.newName', {}, text);
|
||||||
if (!validProfileId(id) || settings.profiles.some(p => p.id === id)) throw new Error('VALIDATION: invalid profile id');
|
if (!validProfileId(id) || settings.profiles.some(p => p.id === id)) throw new Error('VALIDATION: invalid profile id');
|
||||||
return { profiles: [...settings.profiles, { id, name: clean, color: nextColor(settings) }], active: id };
|
return { profiles: [...settings.profiles, { id, name: clean, color: nextColor(settings) }], active: id };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
// Pure model for the titlebar update chip (no Tauri imports, so it is unit-tested under node).
|
// Pure model for the titlebar update chip (no Tauri imports, so it is unit-tested under node).
|
||||||
|
|
||||||
|
import { shellText, type ShellText } from './messages.ts';
|
||||||
|
|
||||||
/** Mirrors `UpdateStatus` in waybetter-host `update.rs` (serde tag "state"). */
|
/** Mirrors `UpdateStatus` in waybetter-host `update.rs` (serde tag "state"). */
|
||||||
export type UpdateStatus =
|
export type UpdateStatus =
|
||||||
| { state: 'idle' | 'checking' | 'upToDate' }
|
| { state: 'idle' | 'checking' | 'upToDate' }
|
||||||
|
|
@ -34,11 +36,11 @@ export function parseUpdateStatus(value: unknown): UpdateStatus {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Unobtrusive: nothing while checking/downloading/erroring; a chip only when action is useful. */
|
/** Unobtrusive: nothing while checking/downloading/erroring; a chip only when action is useful. */
|
||||||
export function chipFor(status: UpdateStatus, product: string): UpdateChip | null {
|
export function chipFor(status: UpdateStatus, product: string, text?: ShellText): UpdateChip | null {
|
||||||
switch (status.state) {
|
switch (status.state) {
|
||||||
case 'ready': return { kind: 'restart', label: 'Update ready · restart', title: `Restart to update to ${product} ${status.version}. Tabs are restored.` };
|
case 'ready': return { kind: 'restart', label: shellText('wb.update.readyLabel', {}, text), title: shellText('wb.update.readyTitle', { product, version: status.version }, text) };
|
||||||
case 'installing': return { kind: 'installing', label: 'Updating…', title: `Installing ${product} ${status.version}` };
|
case 'installing': return { kind: 'installing', label: shellText('wb.update.installingLabel', {}, text), title: shellText('wb.update.installingTitle', { product, version: status.version }, text) };
|
||||||
case 'problem': return { kind: 'problem', label: 'Update problem', title: 'The last update did not start correctly. Download the current version.', href: status.downloadUrl };
|
case 'problem': return { kind: 'problem', label: shellText('wb.update.problemLabel', {}, text), title: shellText('wb.update.problemTitle', {}, text), href: status.downloadUrl };
|
||||||
default: return null;
|
default: return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
26
packages/waybetter/i18n-meta.schema.json
Normal file
26
packages/waybetter/i18n-meta.schema.json
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://waybetter.fyi/schema/i18n-meta.schema.json",
|
||||||
|
"title": "wayBetter locale catalog notes (en.meta.json)",
|
||||||
|
"description": "Notes for translators, one entry per source key: where the text appears and anything that constrains it. A plain string is the description.",
|
||||||
|
"type": "object",
|
||||||
|
"properties": { "$schema": { "type": "string" } },
|
||||||
|
"patternProperties": {
|
||||||
|
"^[a-z][A-Za-z0-9]*([._-][A-Za-z0-9]+)*$": {
|
||||||
|
"oneOf": [
|
||||||
|
{ "type": "string", "minLength": 1 },
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"description": { "type": "string", "minLength": 1 },
|
||||||
|
"context": { "description": "Where it appears (button, tooltip, menu item, native dialog title).", "type": "string" },
|
||||||
|
"maxLength": { "description": "Hard limit in characters (tight buttons, menu items).", "type": "integer", "minimum": 1 },
|
||||||
|
"allowEmpty": { "description": "A sentence fragment that some languages leave empty because their word order moves it into a neighbouring string.", "type": "boolean" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
42
packages/waybetter/i18n.schema.json
Normal file
42
packages/waybetter/i18n.schema.json
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://waybetter.fyi/schema/i18n.schema.json",
|
||||||
|
"title": "wayBetter locale catalog",
|
||||||
|
"description": "One language of a wayBetter app, plugin or the framework itself: locales/<bcp47>.json. English (en.json) is the source; every other file translates some or all of its keys. Messages are plain text in an ICU MessageFormat subset ({name}, {n, plural, ...}, {x, select, ...}, {n, number}, {d, date}); never HTML.",
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"required": ["locale", "name", "englishName", "status", "messages"],
|
||||||
|
"properties": {
|
||||||
|
"$schema": { "type": "string" },
|
||||||
|
"locale": {
|
||||||
|
"description": "Canonical BCP 47 tag of this file: tr, pt, zh-Hans, zh-Hant, en-GB, ar-x-fm.",
|
||||||
|
"type": "string",
|
||||||
|
"pattern": "^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?(-x-[a-z0-9]{1,8})?$"
|
||||||
|
},
|
||||||
|
"name": { "description": "The language's own name (Türkçe, 日本語).", "type": "string", "minLength": 1, "maxLength": 60 },
|
||||||
|
"englishName": { "description": "The language's English name (Turkish, Japanese).", "type": "string", "minLength": 1, "maxLength": 60 },
|
||||||
|
"dir": { "description": "Writing direction; must match the language.", "enum": ["ltr", "rtl"] },
|
||||||
|
"status": {
|
||||||
|
"description": "source: the English source. machine: machine-drafted, needs a human review (the app shows a Help translate link). reviewed: checked by the people in reviewers.",
|
||||||
|
"enum": ["source", "machine", "reviewed"]
|
||||||
|
},
|
||||||
|
"reviewers": {
|
||||||
|
"description": "Names or handles of the people who reviewed this translation.",
|
||||||
|
"type": "array",
|
||||||
|
"items": { "type": "string", "minLength": 1, "maxLength": 80 },
|
||||||
|
"uniqueItems": true
|
||||||
|
},
|
||||||
|
"fallback": {
|
||||||
|
"description": "A locale this one inherits from before English (ar-x-fm falls back to ar, en-GB to en).",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"messages": {
|
||||||
|
"description": "Flat map of dotted keys to messages. Keys must exist in en.json; placeholders must match English.",
|
||||||
|
"type": "object",
|
||||||
|
"propertyNames": { "pattern": "^[a-z][A-Za-z0-9]*([._-][A-Za-z0-9]+)*$", "maxLength": 96 },
|
||||||
|
"additionalProperties": { "type": "string", "maxLength": 2000, "not": { "pattern": "<\\s*/?\\s*[A-Za-z!?]" } }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"if": { "properties": { "status": { "const": "reviewed" } } },
|
||||||
|
"then": { "required": ["reviewers"], "properties": { "reviewers": { "minItems": 1 } } }
|
||||||
|
}
|
||||||
|
|
@ -3,10 +3,11 @@
|
||||||
"version": "0.2.0",
|
"version": "0.2.0",
|
||||||
"license": "GPL-3.0-or-later",
|
"license": "GPL-3.0-or-later",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns) and shell models (address bar, panes, decks, profiles, palette, updates). No dependencies.",
|
"description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns, i18n: ICU-lite messages, locale fallback, plugin strings, catalog checks and JSON Schemas) and shell models (address bar, panes, decks, profiles, palette, updates). No dependencies.",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"waybetter",
|
"waybetter",
|
||||||
"tauri",
|
"tauri",
|
||||||
|
"i18n",
|
||||||
"betterdiscord",
|
"betterdiscord",
|
||||||
"plugins",
|
"plugins",
|
||||||
"theming",
|
"theming",
|
||||||
|
|
@ -24,6 +25,21 @@
|
||||||
},
|
},
|
||||||
"sideEffects": false,
|
"sideEffects": false,
|
||||||
"exports": {
|
"exports": {
|
||||||
|
"./i18n": {
|
||||||
|
"types": "./dist/runtime/i18n.d.ts",
|
||||||
|
"import": "./dist/runtime/i18n.js"
|
||||||
|
},
|
||||||
|
"./i18n/check": {
|
||||||
|
"types": "./dist/runtime/i18nCheck.d.ts",
|
||||||
|
"import": "./dist/runtime/i18nCheck.js"
|
||||||
|
},
|
||||||
|
"./i18n/plugin": {
|
||||||
|
"types": "./dist/runtime/pluginI18n.d.ts",
|
||||||
|
"import": "./dist/runtime/pluginI18n.js"
|
||||||
|
},
|
||||||
|
"./i18n.schema.json": "./i18n.schema.json",
|
||||||
|
"./i18n-meta.schema.json": "./i18n-meta.schema.json",
|
||||||
|
"./locales/*.json": "./locales/*.json",
|
||||||
"./runtime/accountReport": {
|
"./runtime/accountReport": {
|
||||||
"types": "./dist/runtime/accountReport.d.ts",
|
"types": "./dist/runtime/accountReport.d.ts",
|
||||||
"import": "./dist/runtime/accountReport.js"
|
"import": "./dist/runtime/accountReport.js"
|
||||||
|
|
@ -80,6 +96,10 @@
|
||||||
"types": "./dist/runtime/*.d.ts",
|
"types": "./dist/runtime/*.d.ts",
|
||||||
"import": "./dist/runtime/*.js"
|
"import": "./dist/runtime/*.js"
|
||||||
},
|
},
|
||||||
|
"./shell/messages": {
|
||||||
|
"types": "./dist/shell/messages.d.ts",
|
||||||
|
"import": "./dist/shell/messages.js"
|
||||||
|
},
|
||||||
"./shell/addressModel": {
|
"./shell/addressModel": {
|
||||||
"types": "./dist/shell/addressModel.d.ts",
|
"types": "./dist/shell/addressModel.d.ts",
|
||||||
"import": "./dist/shell/addressModel.js"
|
"import": "./dist/shell/addressModel.js"
|
||||||
|
|
@ -126,6 +146,9 @@
|
||||||
"files": [
|
"files": [
|
||||||
"dist",
|
"dist",
|
||||||
"theme.schema.json",
|
"theme.schema.json",
|
||||||
|
"i18n.schema.json",
|
||||||
|
"i18n-meta.schema.json",
|
||||||
|
"locales",
|
||||||
"README.md",
|
"README.md",
|
||||||
"LICENSE"
|
"LICENSE"
|
||||||
],
|
],
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue