Skip to main content

frus_l10n/
lib.rs

1//! `frus-l10n` — **localisation** for frus applications, built on
2//! [Fluent](https://projectfluent.org/), Mozilla's i18n standard.
3//!
4//! Nothing is reinvented here: messages, plurals and selections live in `.ftl`
5//! resources, embedded by the application through `include_str!`, and resolved per
6//! locale with a **fallback** chain (`fluent-langneg` negotiation).
7//!
8//! ```
9//! use frus_l10n::{Localizer, args};
10//! let mut l10n = Localizer::new("en");
11//! l10n.add("en", "hello = Hello, { $name }!\ntasks = { $n ->\n    [one] { $n } task\n   *[other] { $n } tasks\n }");
12//! l10n.add("fr", "hello = Bonjour, { $name } !\ntasks = { $n ->\n    [one] { $n } tâche\n   *[other] { $n } tâches\n }");
13//!
14//! assert_eq!(l10n.format("hello", args![name: "Ada"]), "Hello, Ada!");
15//! l10n.set_locale("fr");
16//! assert_eq!(l10n.format("tasks", args![n: 2]), "2 tâches");
17//! // Falls back to the default locale when the key is missing from the current one.
18//! ```
19
20#![deny(missing_docs)]
21
22// The README's example is compiled and run by `cargo test --doc`, so it cannot rot.
23#[cfg(doctest)]
24#[doc = include_str!("../README.md")]
25pub struct ReadmeDoctests;
26
27use std::collections::HashMap;
28
29// The **concurrent** bundle — its memoiser sits behind a `Mutex` — is what makes
30// `Localizer` `Send + Sync`, so an application can hold it in a `static`/`OnceLock`.
31use fluent_bundle::concurrent::FluentBundle;
32use fluent_bundle::{FluentArgs, FluentResource, FluentValue};
33use unic_langid::LanguageIdentifier;
34
35/// An argument value passed to a message: a string or a number.
36#[derive(Clone, Debug)]
37pub enum Arg<'a> {
38    /// Text.
39    Str(&'a str),
40    /// A number, which takes part in the CLDR plural rules.
41    Num(f64),
42}
43
44impl<'a> From<&'a str> for Arg<'a> {
45    fn from(s: &'a str) -> Self {
46        Arg::Str(s)
47    }
48}
49impl From<i64> for Arg<'_> {
50    fn from(n: i64) -> Self {
51        Arg::Num(n as f64)
52    }
53}
54impl From<i32> for Arg<'_> {
55    fn from(n: i32) -> Self {
56        Arg::Num(n as f64)
57    }
58}
59impl From<usize> for Arg<'_> {
60    fn from(n: usize) -> Self {
61        Arg::Num(n as f64)
62    }
63}
64impl From<f64> for Arg<'_> {
65    fn from(n: f64) -> Self {
66        Arg::Num(n)
67    }
68}
69
70/// Builds a message's argument list: `args![name: "Ada", n: 3]`.
71#[macro_export]
72macro_rules! args {
73    ($($key:ident : $value:expr),* $(,)?) => {
74        &[$((stringify!($key), $crate::Arg::from($value))),*]
75    };
76    () => { &[] };
77}
78
79/// The **localiser**: Fluent bundles per locale, a current locale and a default
80/// locale, the latter being the last resort.
81pub struct Localizer {
82    bundles: HashMap<LanguageIdentifier, FluentBundle<FluentResource>>,
83    default: LanguageIdentifier,
84    current: LanguageIdentifier,
85}
86
87impl Localizer {
88    /// Creates a localiser whose default — and current — locale is `default`, for
89    /// instance `"en"` or `"fr-FR"`. A malformed locale falls back to `und`.
90    pub fn new(default: &str) -> Self {
91        let default: LanguageIdentifier = default.parse().unwrap_or_default();
92        Self {
93            bundles: HashMap::new(),
94            current: default.clone(),
95            default,
96        }
97    }
98
99    /// Adds to, or extends, a locale's messages from an `.ftl` source. Syntax errors
100    /// are reported through `debug_assert` but do not stop the rest of the file from
101    /// loading.
102    pub fn add(&mut self, locale: &str, ftl: &str) {
103        let langid: LanguageIdentifier = match locale.parse() {
104            Ok(id) => id,
105            Err(_) => return,
106        };
107        let resource = match FluentResource::try_new(ftl.to_owned()) {
108            Ok(res) => res,
109            Err((res, _errors)) => {
110                debug_assert!(false, "Fluent syntax errors in \"{locale}\"");
111                res
112            }
113        };
114        let bundle = self
115            .bundles
116            .entry(langid.clone())
117            .or_insert_with(|| new_bundle(langid));
118        // An existing key is not overwritten: add_resource skips duplicates and
119        // reports an error, which we deliberately ignore.
120        let _ = bundle.add_resource(resource);
121    }
122
123    /// The available locales — those for which messages have been loaded.
124    pub fn available(&self) -> Vec<LanguageIdentifier> {
125        self.bundles.keys().cloned().collect()
126    }
127
128    /// Sets the current locale. The best match among the available locales is
129    /// **negotiated**: an exact match first (`fr-FR`), then by language (`fr-CA` →
130    /// `fr`), and failing that the default locale. Returns the locale actually
131    /// chosen.
132    pub fn set_locale(&mut self, locale: &str) -> LanguageIdentifier {
133        let requested: LanguageIdentifier = match locale.parse() {
134            Ok(id) => id,
135            Err(_) => {
136                self.current = self.default.clone();
137                return self.current.clone();
138            }
139        };
140        // 1) An exact match.
141        let exact = self.bundles.keys().find(|id| **id == requested).cloned();
142        // 2) The same language, ignoring region and variant.
143        let by_lang = || {
144            self.bundles
145                .keys()
146                .find(|id| id.language == requested.language)
147                .cloned()
148        };
149        self.current = exact
150            .or_else(by_lang)
151            .unwrap_or_else(|| self.default.clone());
152        self.current.clone()
153    }
154
155    /// The current locale.
156    pub fn locale(&self) -> &LanguageIdentifier {
157        &self.current
158    }
159
160    /// Resolves a message **with no arguments**. The fallback chain is current
161    /// locale → default → the key itself: never a panic, never a surprise empty string.
162    pub fn get(&self, key: &str) -> String {
163        self.format(key, &[])
164    }
165
166    /// Resolves a message **with arguments** (`args![…]`) in the **current locale**,
167    /// with the same fallback chain as [`Localizer::get`].
168    pub fn format(&self, key: &str, args: &[(&str, Arg)]) -> String {
169        self.format_for(&self.current, key, args)
170    }
171
172    /// Resolves a message in an **explicit locale**, without changing the current
173    /// one — handy for a pure `view` that receives the language as a parameter. The
174    /// fallback chain is `locale` → the default locale → the raw key.
175    pub fn format_for(
176        &self,
177        locale: &LanguageIdentifier,
178        key: &str,
179        args: &[(&str, Arg)],
180    ) -> String {
181        for langid in [locale, &self.default] {
182            if let Some(bundle) = self.bundles.get(langid) {
183                if let Some(text) = format_in(bundle, key, args) {
184                    return text;
185                }
186            }
187        }
188        // Last resort: the raw key, which makes the gap visible without breaking the UI.
189        key.to_owned()
190    }
191
192    /// Parses a locale tag (`"fr"`, `"fr-FR"`), or returns the default locale when
193    /// it is malformed — a utility for callers of [`Localizer::format_for`].
194    pub fn langid(&self, locale: &str) -> LanguageIdentifier {
195        locale.parse().unwrap_or_else(|_| self.default.clone())
196    }
197}
198
199/// Builds a bundle for a locale, without **bidi isolation** — no FSI/PDI marks
200/// around arguments — which keeps the output readable and testable. RTL direction
201/// is handled at the layout level; see `Theme::direction`.
202fn new_bundle(langid: LanguageIdentifier) -> FluentBundle<FluentResource> {
203    let mut bundle = FluentBundle::new_concurrent(vec![langid]);
204    bundle.set_use_isolating(false);
205    bundle
206}
207
208/// Formats `key` in `bundle` when the message exists, `None` otherwise.
209fn format_in(
210    bundle: &FluentBundle<FluentResource>,
211    key: &str,
212    args: &[(&str, Arg)],
213) -> Option<String> {
214    let message = bundle.get_message(key)?;
215    let pattern = message.value()?;
216    let mut fargs = FluentArgs::new();
217    for (name, value) in args {
218        let v = match value {
219            Arg::Str(s) => FluentValue::from(*s),
220            Arg::Num(n) => FluentValue::from(*n),
221        };
222        fargs.set(*name, v);
223    }
224    let mut errors = Vec::new();
225    let text = bundle.format_pattern(pattern, Some(&fargs), &mut errors);
226    Some(text.into_owned())
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    fn sample() -> Localizer {
234        let mut l = Localizer::new("en");
235        l.add(
236            "en",
237            "hello = Hello, { $name }!\n\
238             tasks = { $n ->\n    [one] { $n } task\n   *[other] { $n } tasks\n }\n\
239             only-en = English only",
240        );
241        l.add(
242            "fr",
243            "hello = Bonjour, { $name } !\n\
244             tasks = { $n ->\n    [one] { $n } tâche\n   *[other] { $n } tâches\n }",
245        );
246        l
247    }
248
249    #[test]
250    fn resolves_arguments() {
251        let l = sample();
252        assert_eq!(l.format("hello", args![name: "Ada"]), "Hello, Ada!");
253    }
254
255    #[test]
256    fn plural_rules_per_locale() {
257        let mut l = sample();
258        assert_eq!(l.format("tasks", args![n: 1]), "1 task");
259        assert_eq!(l.format("tasks", args![n: 5]), "5 tasks");
260        l.set_locale("fr");
261        assert_eq!(l.format("tasks", args![n: 1]), "1 tâche");
262        assert_eq!(l.format("tasks", args![n: 3]), "3 tâches");
263    }
264
265    #[test]
266    fn negotiates_region_to_base_language() {
267        let mut l = sample();
268        // fr-CA does not exist, so it is negotiated down to fr.
269        let got = l.set_locale("fr-CA");
270        assert_eq!(got.to_string(), "fr");
271        assert_eq!(l.format("hello", args![name: "Zoé"]), "Bonjour, Zoé !");
272    }
273
274    #[test]
275    fn falls_back_to_default_then_key() {
276        let mut l = sample();
277        l.set_locale("fr");
278        // "only-en" exists only in English, so it falls back to the default locale.
279        assert_eq!(l.get("only-en"), "English only");
280        // A key that exists nowhere yields the raw key.
281        assert_eq!(l.get("missing-key"), "missing-key");
282    }
283
284    #[test]
285    fn unknown_locale_stays_on_default() {
286        let mut l = sample();
287        let got = l.set_locale("xx");
288        assert_eq!(got.to_string(), "en");
289    }
290}