Skip to main content

sim_core/
i18n.rs

1//! Translation tables in the simple-message subset of the Fluent format: `key = text`, `#` comments,
2//! `{ $arg }` as the one placeholder.
3
4use std::collections::BTreeMap;
5
6/// (language code, translation file contents) for the keys the core itself uses.
7pub static I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
8
9#[derive(Debug, Clone, Default)]
10pub struct Translations(BTreeMap<String, String>);
11
12impl Translations {
13    pub fn parse(ftl: &str) -> Self {
14        let mut out = Self::default();
15        out.add(ftl);
16        out
17    }
18
19    pub fn add(&mut self, ftl: &str) {
20        for line in ftl.lines() {
21            let line = line.trim();
22            if line.starts_with('#') {
23                continue;
24            }
25            if let Some((key, text)) = line.split_once('=') {
26                self.0.insert(key.trim().into(), text.trim().into());
27            }
28        }
29    }
30
31    pub fn has(&self, key: &str) -> bool {
32        self.0.contains_key(key)
33    }
34
35    /// A missing key shows as the key itself, so a gap is visible instead of blank.
36    pub fn tr<'a>(&'a self, key: &'a str) -> &'a str {
37        self.0.get(key).map_or(key, String::as_str)
38    }
39
40    /// A message with its argument; one that has no place for it (a machine's reason why a pose cannot be reached,
41    /// given with the config value it was found at) shows it in front: "arg: message".
42    pub fn tr_arg(&self, key: &str, arg: &str) -> String {
43        let text = self.tr(key);
44        if arg.is_empty() || text.contains("{ $arg }") {
45            text.replace("{ $arg }", arg)
46        } else {
47            format!("{arg}: {text}")
48        }
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn parses_messages_and_placeholders() {
58        let t = Translations::parse("# comment\nhello = Hallo\nbad-path = Fehlt: { $arg }\n");
59        assert_eq!(t.tr("hello"), "Hallo");
60        assert_eq!(t.tr("missing"), "missing");
61        assert_eq!(t.tr_arg("bad-path", "a.b"), "Fehlt: a.b");
62        assert_eq!(t.tr_arg("hello", "a.b"), "a.b: Hallo");
63        assert_eq!(t.tr_arg("hello", ""), "Hallo");
64        assert!(t.has("hello") && !t.has("comment"));
65    }
66}