Skip to main content

teksilo_i18n/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Internationalization runtime for Teksilo.
5//!
6//! Implements §12 of `docs/architecture.md`. This crate is the
7//! runtime half of the i18n stack: `LocalizedString`, `I18nConfig`,
8//! `I18nManager`, locale resolution, and the thread-local that bridges
9//! macro-expanded code into the active translation bundles.
10//!
11//! The compile-time `tr!` / `tr_widget!` proc macros live in the sister
12//! `teksilo-i18n-macros` crate (Phase C) and are re-exported here as part of
13//! `teksilo-i18n`'s public surface.
14
15pub mod config;
16pub mod direction;
17pub mod display_names;
18pub mod file_watcher;
19pub mod format;
20pub mod localized_string;
21pub mod manager;
22pub mod resolve;
23/// Process/thread-local handle to the active `I18nManager`.
24///
25/// Hidden from rustdoc because it's primarily an internal wiring
26/// module: `TeksiloAppBuilder` calls `install` / `clear`, `LocalizedString`
27/// and `resolve_message` reach into it via `with_active`, and the
28/// `current_*` signal accessors are re-exported at the crate root.
29/// Application code should prefer the crate-root `current_locale()`,
30/// `current_direction()`, and `current_version_signal()` functions;
31/// direct access to `install` / `clear` is still available for
32/// test-harness use.
33#[doc(hidden)]
34pub mod thread_local;
35
36pub use config::I18nConfig;
37pub use direction::rtl_from_locale;
38pub use display_names::language_endonym;
39pub use file_watcher::{FtlFileWatcher, ReloadSink};
40pub use fluent_bundle::FluentValue;
41pub use format::{
42    CalendarSystem, DateFields, DateStyle, NumberFormatter, NumberStyle, NumberSymbols,
43    TeksiloDateTime, TeksiloDateTimeFormatter, TimeStyle, delocalize_number,
44};
45pub use localized_string::{LocalizedString, localized};
46pub use manager::{I18nManager, LocaleSwitchOutcome, ReloadError};
47#[doc(hidden)]
48pub use resolve::format_source_fallback;
49pub use resolve::{resolve_message, resolve_message_widget};
50pub use teksilo_core::environment::LayoutDirection;
51pub use teksilo_core::signal::{Signal, WeakSignal};
52pub use teksilo_i18n_macros::{tr, tr_signal, tr_signal_widget, tr_widget};
53pub use thread_local::{
54    current_direction, current_locale, current_supported_locales, current_version_signal,
55};
56pub use unic_langid::LanguageIdentifier;
57
58/// Declarative sugar for populating `I18nConfig::compile_in` when an
59/// application ships many locales × many `.ftl` files per locale.
60///
61/// # Example
62///
63/// ```ignore
64/// use teksilo_i18n::{compile_in_locales, I18nConfig};
65///
66/// let cfg = I18nConfig::new()
67///     .compile_in(compile_in_locales!(
68///         base = "../locales/",
69///         locales = ["en-US", "fr-FR", "es-ES", "ar-SA"],
70///         files = ["main.ftl", "auth.ftl", "editor.ftl"],
71///     ));
72/// ```
73///
74/// expands to:
75///
76/// ```text
77/// &[
78///     ("en-US", &[
79///         include_str!("../locales/en-US/main.ftl"),
80///         include_str!("../locales/en-US/auth.ftl"),
81///         include_str!("../locales/en-US/editor.ftl"),
82///     ]),
83///     ("fr-FR", &[ /* … same files … */ ]),
84///     // …
85/// ]
86/// ```
87///
88/// Every `locale × file` combination must exist on disk (the expansion
89/// uses `include_str!`, which fails at compile time if the file is
90/// missing). If a locale ships a different subset of files, fall back
91/// to writing the explicit slice by hand — the sugar assumes uniform
92/// coverage.
93///
94/// # Path resolution
95///
96/// `base` is **relative to the source file where `compile_in_locales!`
97/// is invoked**, not to the crate root. This follows from `include_str!`'s
98/// own resolution rules (which `macro_rules!` propagates): the path in
99/// the expanded `include_str!(concat!(...))` is resolved against the
100/// caller's file, not the definition file of the macro. For a binary
101/// crate with `main.rs` in `src/` and locales in `locales/`, the
102/// correct base is `"../locales/"`. For a test file in `tests/foo.rs`
103/// pointing at `tests/fixtures/`, it is `"fixtures/"`. When in doubt,
104/// mentally replace `compile_in_locales!(base = "X", ...)` with
105/// `include_str!(concat!("X", locale, "/", file))` written where the
106/// invocation appears.
107///
108/// The macro joins `base`, `locale`, `/`, and `file` via the compiler
109/// built-in `concat!`, producing a literal path suitable for
110/// `include_str!`.
111#[macro_export]
112macro_rules! compile_in_locales {
113    (
114        base = $base:literal,
115        locales = [$($locale:literal),* $(,)?],
116        files = $files:tt $(,)?
117    ) => {
118        &[
119            $(
120                $crate::compile_in_locales!(@one $base, $locale, $files),
121            )*
122        ] as &'static [(&'static str, &'static [&'static str])]
123    };
124    // Internal helper: expand one locale's entry. The file list is
125    // captured as a `tt` at the outer site so it survives the outer
126    // `$(...)*` unchanged, then destructured here where `$locale` is
127    // a fixed literal — sidestepping `macro_rules!`'s inability to
128    // express a Cartesian product in a single nested repetition.
129    (@one $base:literal, $locale:literal, [$($file:literal),* $(,)?]) => {
130        (
131            $locale,
132            &[
133                $(
134                    include_str!(concat!($base, $locale, "/", $file)),
135                )*
136            ] as &'static [&'static str],
137        )
138    };
139}
140
141/// Wrap an intentionally **untranslated** string as a [`LocalizedString`].
142///
143/// This is the explicit marker for UI strings that are deliberately not
144/// localized — debug labels, scaffolding, developer-facing names, or
145/// runtime-formatted text that isn't part of a translated sentence. Use
146/// `tr!(...)` for anything user-facing that should follow the locale.
147///
148/// `lit!(x)` is shorthand for [`LocalizedString::literal(x)`] and accepts
149/// anything `impl Into<String>` (`&str`, `String`, `format!(...)`, …). The
150/// value is captured once and frozen — it does **not** observe locale
151/// changes. Dynamic values that must refresh belong in a `Signal<String>`
152/// bound via a widget's `bind_*` method, not in `lit!`.
153///
154/// Unlike `tr!` / `tr_widget!` (proc macros that resolve against a Fluent
155/// bundle and therefore need separate app/framework variants), `lit!` is a
156/// `macro_rules!` that resolves against no bundle and uses `$crate`, so a
157/// single macro works in framework crates and external apps alike.
158///
159/// [`LocalizedString::literal(x)`]: crate::LocalizedString::literal
160#[macro_export]
161macro_rules! lit {
162    ($e:expr $(,)?) => {
163        $crate::LocalizedString::literal($e)
164    };
165}