day-localization 0.6.4

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! day-localization: the core localization engine (DESIGN.md §12), low enough in the crate graph that even
//! the central crates (day-pieces' dialogs, menu-role labels) can localize their own UI strings.
//!
//! Two tiers of global Fluent bundles:
//! - **core**: a built-in catalog (`catalog/*.ftl`) of the standard strings the framework itself
//!   emits (dialog OK/Cancel, standard menu commands), shipped in several languages. Always present.
//! - **app**: the locales an app registers with [`install`]. These take precedence over core, so an
//!   app can override any `day_*` string, and core is the fallback for keys the app didn't define.
//!
//! Private [`Catalog`] namespaces live alongside these tiers. They share the locale signal,
//! but never merge their messages into app/core or each other.
//!
//! The current locale is a [`Signal`], so every `format`/binding re-runs on a locale switch. The
//! piece-facing reactive `tr()` wrapper lives one layer up in `day-localization-ui` (which re-exports this).

use std::cell::RefCell;
use std::collections::HashMap;

day_reactive::tls_root! {
    collate: crate::collate::TlsGroupSlots,
    datetime: crate::datetime::TlsGroupSlots,
    decimal: crate::decimal::TlsGroupSlots,
    root: crate::TlsGroupSlots,
}

use day_reactive::Signal;
use fluent_bundle::{FluentArgs, FluentBundle, FluentResource, FluentValue};
use unic_langid::LanguageIdentifier;

mod collate;
mod datetime;
mod decimal;
mod intl;
mod search;

pub use collate::{compare, compare_in, sort_localized};
pub use datetime::{DateFields, format_date, format_date_in};
pub use decimal::{format_decimal, format_decimal_in, format_percent, format_percent_in};
pub use search::{matches_search, matches_search_in};

/// The built-in core catalog: standard UI strings the framework needs, per language. Apps override
/// individual keys by defining them in their own catalog (see [`install`]).
const CORE_CATALOG: &[(&str, &str)] = &[
    ("en", include_str!("../catalog/en.ftl")),
    ("fr", include_str!("../catalog/fr.ftl")),
    ("es", include_str!("../catalog/es.ftl")),
    ("de", include_str!("../catalog/de.ftl")),
    ("ja", include_str!("../catalog/ja.ftl")),
    ("zh", include_str!("../catalog/zh.ftl")),
    ("ar", include_str!("../catalog/ar.ftl")),
];

// `key::<name>` and the `__core_strings!` accessors, generated from catalog/en.ftl by build.rs.
include!(concat!(env!("OUT_DIR"), "/core_strings.rs"));

/// An embedded, private Fluent namespace. Generated by `day_build::generate_locales`.
/// Catalog identity is its static address, so identical keys in different crates never collide.
/// `name` is only the qualified lookup name used by scripting (`crate::file::key`).
pub struct Catalog {
    pub name: &'static str,
    pub default: &'static str,
    pub locales: &'static [(&'static str, &'static str)],
}

struct ScopedBundles {
    catalog: &'static Catalog,
    bundles: HashMap<String, FluentBundle<FluentResource>>,
}

struct State {
    scoped: HashMap<usize, ScopedBundles>,
    /// App-registered bundles (from `install`), keyed by locale; take precedence over `core`.
    app: HashMap<String, FluentBundle<FluentResource>>,
    /// Built-in core catalog bundles, keyed by locale; the fallback for `day_*` keys.
    core: HashMap<String, FluentBundle<FluentResource>>,
    default: String,
    locale: Signal<String>,
}

day_reactive::tls_slots! {
    root;
    static STATE: RefCell<Option<State>> = const { RefCell::new(None) };

    /// The host's ordered locale preference, set by the platform entry before `install` runs:
    /// the entry point for hosts with no process environment (web-dom seeds it from the page's
    /// `?locale=`, native backends from the OS). The `DAY_LOCALE` environment variable, where one
    /// exists, still wins.
    static LAUNCH_LOCALES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };

}

fn build_bundles(locales: &[(&str, &str)]) -> HashMap<String, FluentBundle<FluentResource>> {
    let mut bundles = HashMap::new();
    for (name, src) in locales {
        let langid: LanguageIdentifier = name.parse().unwrap_or_else(|_| "en".parse().unwrap());
        let mut bundle = FluentBundle::new(vec![langid]);
        // icu4x-backed NUMBER()/DATETIME() + the bundle-wide number formatter (src/intl.rs).
        intl::register(&mut bundle);
        // Overriding the same key across resources (app > core when merged) is expected; Fluent
        // errors on duplicate adds, so we keep app and core in separate bundles and pick at lookup.
        match FluentResource::try_new((*src).to_string()) {
            Ok(res) => {
                let _ = bundle.add_resource(res);
            }
            Err((res, errs)) => {
                log::warn!("day-localization: {name}: {} syntax error(s)", errs.len());
                let _ = bundle.add_resource(res);
            }
        }
        bundles.insert((*name).to_string(), bundle);
    }
    bundles
}

/// Lazily create the state with the core catalog loaded, so core strings (and `format_in`) work even
/// before an app calls [`install`]. The initial locale honors `DAY_LOCALE`.
fn ensure_state() {
    STATE.with(|s| {
        if s.borrow().is_some() {
            return;
        }
        let initial = std::env::var("DAY_LOCALE")
            .ok()
            .map(normalize)
            .unwrap_or_else(|| "en".to_string());
        *s.borrow_mut() = Some(State {
            app: HashMap::new(),
            scoped: HashMap::new(),
            core: build_bundles(CORE_CATALOG),
            default: "en".to_string(),
            // ROOT-scoped: this is a process-global signal, but `ensure_state` runs on the
            // First touch of any l10n API, which can be inside a transient scope (a cover's
            // presented content calling `t()` was the first observed case; the signal then
            // died with that cover and every later read panicked). Globals must never
            // inherit a caller's scope.
            locale: Signal::global(initial),
        });
    });
}

/// Record the host's launch locale before [`install`] runs. Platform glue only; apps pick
/// locales with `set_locale`. No-op once `install` has resolved the initial locale.
pub fn set_launch_locale(locale: &str) {
    set_launch_locales(&[locale.to_string()]);
}

/// Append the host's ordered preference after anything already recorded.
///
/// The two sources arrive in that order and both matter: a host override (web-dom's `?locale=`,
/// set by the page glue) is a deliberate choice and stays first; the OS preference the backend
/// reports is the fallback behind it. Duplicates are dropped, so a repeat call cannot reorder.
pub fn add_launch_locales(locales: &[String]) {
    LAUNCH_LOCALES.with(|l| {
        let mut l = l.borrow_mut();
        for loc in locales {
            if !l.contains(loc) {
                l.push(loc.clone());
            }
        }
    });
}

/// Record the host's ordered locale preference (`["fr-CA", "fr", "en"]`) before [`install`] runs.
///
/// An OS answers with a list, not a locale, and the app's catalogs are not registered yet, so the
/// list is kept whole and [`install`] picks the first entry it can serve. Taking only the
/// first would drop a user whose phone reads "Canadian French, then French" for an app that ships
/// `fr` but not `fr-CA`.
pub fn set_launch_locales(locales: &[String]) {
    LAUNCH_LOCALES.with(|l| *l.borrow_mut() = locales.to_vec());
}

/// Register an app's locales from `.ftl` sources and set the current locale from (1) the `DAY_LOCALE`
/// launch override, (2) the platform's [`set_launch_locale`] hint, (3) `default`. Call once, before
/// building the root piece. The built-in core catalog is preserved (and remains the fallback); the
/// app's strings take precedence over it, and re-registering reuses the existing locale [`Signal`]
/// so bindings created earlier keep working.
pub fn install(default: &str, locales: &[(&str, &str)]) {
    ensure_state();
    STATE.with(|s| {
        let mut st = s.borrow_mut();
        let st = st.as_mut().unwrap();
        st.app = build_bundles(locales);
        st.default = default.to_string();
        // Accept the first candidate that resolves (exactly, sans `-u-…` extension, or by
        // language half, `fr-FR` → `fr`), mirroring `message_from`'s lookup, so a regional or
        // extension-carrying candidate isn't silently dropped to the default.
        // The app's catalogs decide the app's language. The core catalog ships more languages
        // than most apps translate into, and letting it answer would hand a German phone an app
        // whose own text is English and whose framework strings are German, a mix no user asked
        // for. Core decides only when the app registered nothing at all.
        let serves = |l: &str| {
            let lang = l.split('-').next().unwrap_or(l);
            let keys = [l, base_locale(l), lang];
            let catalogs = if st.app.is_empty() { &st.core } else { &st.app };
            keys.iter().any(|k| catalogs.contains_key(*k)) || is_pseudo(l)
        };
        let candidates = std::env::var("DAY_LOCALE")
            .ok()
            .map(|l| vec![l])
            .unwrap_or_else(|| LAUNCH_LOCALES.with(|l| l.borrow().clone()));
        let initial = candidates
            .into_iter()
            .map(normalize)
            .find(|l| serves(l))
            .unwrap_or_else(|| default.to_string());
        st.locale.set(initial);
    });
}

fn normalize(l: String) -> String {
    // fr_FR / fr-FR → try exact, else the language half.
    l.replace('_', "-")
}

/// The locale string without any `-u-…` Unicode extension: `"zh-u-co-stroke"` → `"zh"`. Bundle
/// lookup uses the base (translations don't vary by collation/numbering preferences); the
/// collator ([`compare_in`]) keeps the full string so extensions still select tailorings.
fn base_locale(l: &str) -> &str {
    l.split("-u-").next().unwrap_or(l)
}

/// The current locale (a tracked read inside bindings).
pub fn locale() -> Signal<String> {
    ensure_state();
    STATE.with(|s| s.borrow().as_ref().unwrap().locale)
}

/// Switch the locale at runtime; every `tr`/binding re-runs.
pub fn set_locale(l: &str) {
    locale().set(normalize(l.to_string()));
}

#[derive(Clone)]
pub enum FArg {
    Str(String),
    Num(f64),
    SigStr(Signal<String>),
    SigI64(Signal<i64>),
    SigF64(Signal<f64>),
}

impl FArg {
    /// Tracked resolution (signal args subscribe the binding).
    fn resolve(&self) -> FluentValue<'static> {
        match self {
            FArg::Str(s) => FluentValue::from(s.clone()),
            FArg::Num(n) => FluentValue::from(*n),
            FArg::SigStr(s) => FluentValue::from(s.get()),
            FArg::SigI64(s) => FluentValue::from(s.get()),
            FArg::SigF64(s) => FluentValue::from(s.get()),
        }
    }
}

/// Disjoint-marker conversion for `.arg` values (the same E0119 dodge as `IntoText`).
pub trait IntoFArg<M> {
    fn into_farg(self) -> FArg;
}
pub struct ValM;
pub struct SigM;
impl IntoFArg<ValM> for &str {
    fn into_farg(self) -> FArg {
        FArg::Str(self.to_owned())
    }
}
impl IntoFArg<ValM> for String {
    fn into_farg(self) -> FArg {
        FArg::Str(self)
    }
}
impl IntoFArg<ValM> for i64 {
    fn into_farg(self) -> FArg {
        FArg::Num(self as f64)
    }
}
impl IntoFArg<ValM> for f64 {
    fn into_farg(self) -> FArg {
        FArg::Num(self)
    }
}
impl IntoFArg<SigM> for Signal<String> {
    fn into_farg(self) -> FArg {
        FArg::SigStr(self)
    }
}
impl IntoFArg<SigM> for Signal<i64> {
    fn into_farg(self) -> FArg {
        FArg::SigI64(self)
    }
}
impl IntoFArg<SigM> for Signal<f64> {
    fn into_farg(self) -> FArg {
        FArg::SigF64(self)
    }
}

/// Marker for [`IntoFArg`] values that carry a **number**, required for a Fluent variable used as a
/// plural / `select` selector, where CLDR plural rules select on a number (so a string can't be
/// passed there by mistake). Implemented for the numeric `IntoFArg` types only (`i64`, `f64`, and
/// their `Signal`s); the generated `res::str::<key>(…)` functions (§18.5) type such parameters as
/// `impl IntoNumberFArg` instead of `impl IntoFArg`.
pub trait IntoNumberFArg<M>: IntoFArg<M> {}
impl IntoNumberFArg<ValM> for i64 {}
impl IntoNumberFArg<ValM> for f64 {}
impl IntoNumberFArg<SigM> for Signal<i64> {}
impl IntoNumberFArg<SigM> for Signal<f64> {}

/// Resolve `key` in the given locale from one bundle map (exact locale, then the language half).
fn message_from(
    map: &HashMap<String, FluentBundle<FluentResource>>,
    locale_name: &str,
    key: &str,
    args: &FluentArgs,
) -> Option<String> {
    let bundle = map
        .get(locale_name)
        .or_else(|| map.get(base_locale(locale_name)))
        .or_else(|| {
            let lang = locale_name.split('-').next().unwrap_or(locale_name);
            map.get(lang)
        })
        .or_else(|| {
            // Apple uses script tags while stores commonly use region tags.
            let base = base_locale(locale_name);
            let alias = match base {
                "zh-Hans" | "zh-Hans-CN" | "zh-SG" => "zh-CN",
                "zh-Hant" | "zh-Hant-TW" => "zh-TW",
                _ => return None,
            };
            map.get(alias)
        })?;
    // `message.attribute` reaches a Fluent attribute (a message id itself can never contain
    // a dot, so the split is unambiguous). This is how localized keyboard-shortcut keys resolve
    // (`menu_group.key`, docs/localization.md): the attribute lives beside its command's
    // label, and a locale that omits it falls through this chain to the default's.
    let (msg_key, attr) = match key.split_once('.') {
        Some((m, a)) => (m, Some(a)),
        None => (key, None),
    };
    let msg = bundle.get_message(msg_key)?;
    let pattern = match attr {
        Some(a) => msg.get_attribute(a)?.value(),
        None => msg.value()?,
    };
    let mut errs = Vec::new();
    Some(
        bundle
            .format_pattern(pattern, Some(args), &mut errs)
            .into_owned(),
    )
}

/// Make a catalog available for qualified scripting lookups. Generated accessors call this
/// automatically. Registration never changes the app locale or its default catalog.
pub fn register_catalog(catalog: &'static Catalog) {
    ensure_state();
    STATE.with(|s| {
        s.borrow_mut()
            .as_mut()
            .unwrap()
            .scoped
            .entry(catalog as *const Catalog as usize)
            .or_insert_with(|| ScopedBundles {
                catalog,
                bundles: build_bundles(catalog.locales),
            });
    });
}

/// Format within one private namespace; missing keys fall back only to this catalog's default.
/// App/core catalogs cannot accidentally supply a similarly named key from another component.
pub fn format_catalog(
    catalog: &'static Catalog,
    locale_name: &str,
    key: &str,
    args: &[(String, FArg)],
) -> String {
    register_catalog(catalog);
    STATE.with(|s| {
        let st = s.borrow();
        let scope = &st.as_ref().unwrap().scoped[&(catalog as *const Catalog as usize)];
        resolve_scoped(scope, locale_name, key, args)
    })
}

fn resolve_scoped(
    scope: &ScopedBundles,
    locale_name: &str,
    key: &str,
    args: &[(String, FArg)],
) -> String {
    let mut fargs = FluentArgs::new();
    for (k, v) in args {
        fargs.set(k.clone(), v.resolve());
    }
    let base = locale_name.strip_suffix(PSEUDO_SUFFIX);
    let lookup = base.unwrap_or(locale_name);
    match message_from(&scope.bundles, lookup, key, &fargs)
        .or_else(|| message_from(&scope.bundles, scope.catalog.default, key, &fargs))
    {
        Some(out) if base.is_some() => pseudolocalize(&out),
        Some(out) => out,
        None => format!("⟨{}::{key}⟩", scope.catalog.name),
    }
}

/// Resolve `key`: app bundle for the locale, then app-default, then the built-in core catalog for the
/// locale, then core English. A pseudo-locale (`en-XA`, `fr-XA`: any locale with the `-XA` suffix)
/// resolves against the locale under the suffix and accents the result. Signal args are tracked
/// reads.
pub fn format_in(locale_name: &str, key: &str, args: &[(String, FArg)]) -> String {
    ensure_state();
    STATE.with(|s| {
        let st = s.borrow();
        let st = st.as_ref().unwrap();
        // Qualified keys are explicit: never search unrelated catalogs by a bare key.
        if let Some((name, local_key)) = key.rsplit_once("::") {
            let mut matches = st.scoped.values().filter(|s| s.catalog.name == name);
            if let Some(scope) = matches.next()
                && matches.next().is_none()
            {
                return resolve_scoped(scope, locale_name, local_key, args);
            }
            return format!("⟨{key}⟩");
        }
        let mut fargs = FluentArgs::new();
        for (k, v) in args {
            fargs.set(k.clone(), v.resolve());
        }
        let base = locale_name.strip_suffix(PSEUDO_SUFFIX);
        let pseudo = base.is_some();
        let lookup = base.unwrap_or(locale_name);
        let out = message_from(&st.app, lookup, key, &fargs)
            .or_else(|| message_from(&st.app, &st.default, key, &fargs))
            .or_else(|| message_from(&st.core, lookup, key, &fargs))
            .or_else(|| message_from(&st.core, "en", key, &fargs));
        match out {
            Some(out) => {
                if pseudo {
                    pseudolocalize(&out)
                } else {
                    out
                }
            }
            None => format!("⟨{key}⟩"),
        }
    })
}

/// Resolve `key` in the current locale (no args): the one-shot form the framework's own strings use
/// (dialog buttons, menu-role labels), which are resolved once at present/build time. The key is
/// always a generated name, `t(key::day_cancel)`, never a string literal.
pub fn t(key: &str) -> String {
    format_in(&locale().get(), key, &[])
}

/// The suffix that turns any locale into its pseudo-locale (`fr` → `fr-XA`): the strings of the
/// locale underneath, accented and expanded (docs/localization.md).
const PSEUDO_SUFFIX: &str = "-XA";

/// Whether `l` is a pseudo-locale.
fn is_pseudo(l: &str) -> bool {
    l.ends_with(PSEUDO_SUFFIX)
}

/// Accent + expansion transform for layout-stress testing (the `-XA` pseudo-locales).
fn pseudolocalize(s: &str) -> String {
    let mut out: String = s
        .chars()
        .map(|c| match c {
            'a' => 'á',
            'e' => 'é',
            'i' => 'í',
            'o' => 'ó',
            'u' => 'ú',
            'y' => 'ý',
            'A' => 'Á',
            'E' => 'É',
            'I' => 'Í',
            'O' => 'Ó',
            'U' => 'Ú',
            'Y' => 'Ý',
            other => other,
        })
        .collect();
    out.push_str(" ・ロング");
    out
}

/// Strip Fluent's FSI/PDI isolation marks (dayscript text comparison, §14.3).
pub fn strip_isolates(s: &str) -> String {
    s.chars()
        .filter(|c| !matches!(c, '\u{2068}' | '\u{2069}'))
        .collect()
}

#[cfg(test)]
mod launch_locale_tests {
    use super::*;

    /// The device answers with a list and its first entry is often regional. Both facts have to
    /// survive: `fr-CA` must reach an app that ships only `fr`, and a language the app does not
    /// have at all must fall through to the next preference rather than to the default.
    #[test]
    fn install_picks_the_first_preference_it_can_serve() {
        set_launch_locales(&[
            "de-DE".to_string(), // not shipped
            "fr-CA".to_string(), // shipped as `fr`
            "en".to_string(),
        ]);
        install(
            "en",
            &[("en", "hello = Hello\n"), ("fr", "hello = Bonjour\n")],
        );
        assert_eq!(locale().get(), "fr-CA");
        assert_eq!(
            t("hello"),
            "Bonjour",
            "and it resolves through the language half"
        );
    }

    /// An explicit host override stays in front of whatever the OS reports.
    #[test]
    fn an_explicit_override_outranks_the_device() {
        set_launch_locales(&[]);
        set_launch_locale("fr");
        add_launch_locales(&["en-US".to_string()]);
        install(
            "en",
            &[("en", "hello = Hello\n"), ("fr", "hello = Bonjour\n")],
        );
        assert_eq!(t("hello"), "Bonjour");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn core_catalog_resolves_without_install_and_across_locales() {
        // Works before any `install`; the core catalog self-initializes.
        assert_eq!(
            strip_isolates(&format_in("en", key::day_cancel, &[])),
            "Cancel"
        );
        assert_eq!(
            strip_isolates(&format_in("fr", key::day_cancel, &[])),
            "Annuler"
        );
        assert_eq!(
            strip_isolates(&format_in("de", key::day_cancel, &[])),
            "Abbrechen"
        );
        assert_eq!(strip_isolates(&format_in("ja", key::day_ok, &[])), "OK");
        // Unknown locale → English core fallback.
        assert_eq!(strip_isolates(&format_in("xx", key::day_copy, &[])), "Copy");
        // Unknown key → visible marker, never a panic.
        assert_eq!(format_in("en", "nope", &[]), "⟨nope⟩");
    }

    #[test]
    fn shortcut_key_attributes_resolve_and_fall_back_across_locales() {
        install(
            "en",
            &[
                ("en", "menu_group = Group\n    .key = g\n"),
                // fr omits the attribute, so the shortcut stays the default locale's, which is
                // the industry posture (letters stay stable across languages)…
                ("fr", "menu_group = Grouper\n"),
                // …while a locale that needs to differ declares it.
                ("de", "menu_group = Gruppieren\n    .key = r\n"),
            ],
        );
        assert_eq!(strip_isolates(&format_in("en", "menu_group.key", &[])), "g");
        assert_eq!(
            strip_isolates(&format_in("fr", "menu_group.key", &[])),
            "g",
            "an omitted attribute falls back to the default locale's"
        );
        assert_eq!(
            strip_isolates(&format_in("de", "menu_group.key", &[])),
            "r",
            "a locale may deliberately override"
        );
        assert_eq!(
            strip_isolates(&format_in("fr", "menu_group", &[])),
            "Grouper",
            "the message value is untouched"
        );
        assert_eq!(format_in("en", "menu_group.nope", &[]), "⟨menu_group.nope⟩");
        install("en", &[]); // leave the thread's shared state clean for other tests
    }

    #[test]
    fn menu_role_labels_and_interpolated_app_commands_localize() {
        let app = |lang, key, val: &str| {
            let out = format_in(lang, key, &[("app".to_string(), FArg::Str("Day".into()))]);
            assert_eq!(strip_isolates(&out), val, "{lang}/{key}");
        };
        // Standard menu-command labels (used by day-pieces `lower_menu` for role items).
        assert_eq!(
            strip_isolates(&format_in("fr", key::day_cut, &[])),
            "Couper"
        );
        assert_eq!(
            strip_isolates(&format_in("de", key::day_paste, &[])),
            "Einfügen"
        );
        assert_eq!(
            strip_isolates(&format_in("es", key::day_select_all, &[])),
            "Seleccionar todo"
        );
        // Interpolated App-menu commands with per-language word order (AppKit About/Quit).
        app("en", key::day_quit_app, "Quit Day");
        app("fr", key::day_quit_app, "Quitter Day");
        app("de", key::day_quit_app, "Day beenden");
        app("ja", key::day_quit_app, "Dayを終了");
        app("fr", key::day_about_app, "À propos de Day");
    }

    #[test]
    fn app_bundle_overrides_core_but_core_is_the_fallback() {
        install("en", &[("en", "day_cancel = Dismiss\ngreeting = Hi")]);
        // App key wins for its own strings.
        assert_eq!(strip_isolates(&format_in("en", "greeting", &[])), "Hi");
        // App override of a core key wins.
        assert_eq!(
            strip_isolates(&format_in("en", key::day_cancel, &[])),
            "Dismiss"
        );
        // A core key the app didn't define still resolves from the built-in catalog.
        assert_eq!(strip_isolates(&format_in("en", key::day_ok, &[])), "OK");
    }
}

#[cfg(test)]
mod scoped_tests {
    use super::*;
    static A: Catalog = Catalog {
        name: "game_a",
        default: "en",
        locales: &[
            (
                "en",
                "game_title = Alpha\nonly_a = Private\ngreeting = Hello { $name }\nmenu = Menu\n    .key = a\n",
            ),
            (
                "fr",
                "game_title = Alphabète\ngreeting = Bonjour { $name }\n",
            ),
            ("zh-CN", "game_title = 阿尔法\n"),
        ],
    };
    static B: Catalog = Catalog {
        name: "game_b",
        default: "en",
        locales: &[("en", "game_title = Beta\n")],
    };

    #[test]
    fn private_keys_do_not_leak_or_depend_on_registration_order() {
        install(
            "en",
            &[("en", "game_title = Application\nonly_a = App impostor\n")],
        );
        for catalog in [&B, &A, &B, &A] {
            let expected = if std::ptr::eq(catalog, &A) {
                "Alpha"
            } else {
                "Beta"
            };
            assert_eq!(format_catalog(catalog, "en", "game_title", &[]), expected);
        }
        assert_eq!(format_in("en", "game_title", &[]), "Application");
        assert_eq!(format_catalog(&B, "en", "only_a", &[]), "⟨game_b::only_a⟩");
        assert_eq!(
            format_catalog(&B, "en", key::day_ok, &[]),
            "⟨game_b::day_ok⟩"
        );
        install("en", &[]);
        assert_eq!(format_catalog(&A, "en", "game_title", &[]), "Alpha");
    }

    #[test]
    fn scope_fallback_attributes_pseudo_and_regional_locales() {
        assert_eq!(
            format_catalog(&A, "fr-CA-u-nu-latn", "game_title", &[]),
            "Alphabète"
        );
        assert_eq!(format_catalog(&A, "fr", "only_a", &[]), "Private");
        assert_eq!(format_catalog(&A, "xx", "game_title", &[]), "Alpha");
        assert_eq!(format_catalog(&A, "fr", "menu.key", &[]), "a");
        assert_eq!(
            format_catalog(&A, "fr-XA", "game_title", &[]),
            pseudolocalize("Alphabète")
        );
        for locale in ["zh-CN", "zh-Hans", "zh-Hans-CN", "zh-SG"] {
            assert_eq!(format_catalog(&A, locale, "game_title", &[]), "阿尔法");
        }
    }

    #[test]
    fn qualified_scripts_are_explicit_and_ambiguous_names_fail_closed() {
        register_catalog(&A);
        register_catalog(&B);
        assert_eq!(format_in("en", "game_a::game_title", &[]), "Alpha");
        assert_eq!(format_in("en", "game_b::game_title", &[]), "Beta");
        assert_eq!(
            format_in("en", "absent::game_title", &[]),
            "⟨absent::game_title⟩"
        );
        static DUPLICATE: Catalog = Catalog {
            name: "game_a",
            default: "en",
            locales: &[("en", "game_title = Other version\n")],
        };
        register_catalog(&DUPLICATE);
        assert_eq!(
            format_in("en", "game_a::game_title", &[]),
            "⟨game_a::game_title⟩"
        );
        assert_eq!(format_catalog(&A, "en", "game_title", &[]), "Alpha");
        assert_eq!(
            format_catalog(&DUPLICATE, "en", "game_title", &[]),
            "Other version"
        );
    }

    #[test]
    fn shared_locale_and_signal_arguments_react_without_reinstalling_catalogs() {
        use std::rc::Rc;
        set_locale("en");
        let name = Signal::new("Ada".to_string());
        let observed = Rc::new(RefCell::new(Vec::new()));
        let values = observed.clone();
        let scope = day_reactive::Scope::child();
        scope.enter(|| {
            day_reactive::Effect::new(move || {
                values.borrow_mut().push(strip_isolates(&format_catalog(
                    &A,
                    &locale().get(),
                    "greeting",
                    &[("name".into(), FArg::SigStr(name))],
                )));
            });
        });
        day_reactive::batch(|| set_locale("fr"));
        day_reactive::batch(|| name.set("Grace".to_string()));
        assert_eq!(
            *observed.borrow(),
            ["Hello Ada", "Bonjour Ada", "Bonjour Grace"]
        );
        scope.dispose();
    }
}