aboutsummaryrefslogtreecommitdiff
path: root/ui/src/locale.rs
blob: a2fdce0113d4df624da19eee1084e1010cd29db2 (plain)
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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/
use jellycommon::*;
use std::{collections::HashMap, sync::LazyLock};

static LANG_TABLES: LazyLock<HashMap<Language, HashMap<&'static str, &'static str>>> =
    LazyLock::new(|| {
        let mut k = HashMap::new();
        for (lang, source) in [
            (LANG_ENG.0, include_str!("../../locale/en.ini")),
            (LANG_DEU.0, include_str!("../../locale/de.ini")),
        ] {
            // TODO fallback to english
            let tr_map = source
                .lines()
                .filter_map(|line| {
                    let (key, value) = line.split_once("=")?;
                    Some((key.trim(), value.trim()))
                })
                .collect::<HashMap<&'static str, &'static str>>();
            k.insert(lang, tr_map);
        }
        k
    });

pub fn tr(lang: Language, key: &str) -> &'static str {
    let tr_map = LANG_TABLES.get(&lang).unwrap();
    tr_map.get(key).copied().unwrap_or("MISSING TRANSLATION")
}

pub fn get_translation_table(lang: &Language) -> &'static HashMap<&'static str, &'static str> {
    LANG_TABLES.get(lang).unwrap()
}

pub fn escape(str: &str) -> String {
    let mut o = String::with_capacity(str.len());
    let mut last = 0;
    for (index, byte) in str.bytes().enumerate() {
        if let Some(esc) = match byte {
            b'<' => Some("&lt;"),
            b'>' => Some("&gt;"),
            b'&' => Some("&amp;"),
            b'"' => Some("&quot;"),
            _ => None,
        } {
            o += &str[last..index];
            o += esc;
            last = index + 1;
        }
    }
    o += &str[last..];
    o
}