Skip to main content

swls_core/util/
lang_text.rs

1//! Human-readable literals in several languages.
2//!
3//! Labels, comments, titles and descriptions often come in several languages
4//! (`"Name"@en`, `"Naam"@nl`). The server does not know the editor's language,
5//! so everywhere text is shown, one language is chosen: untagged text first,
6//! then English (`en`, `en-GB`, …), then the first language found.
7
8use std::borrow::Cow;
9
10use crate::util::triple::{MyTerm, TermContext};
11
12/// Language tag of a literal term, if any.
13pub fn term_language<'a>(term: &'a MyTerm<'_>) -> Option<&'a str> {
14    match &term.context {
15        TermContext::LangTag(tag) => Some(tag.as_ref()),
16        _ => None,
17    }
18}
19
20fn is_english(tag: &str) -> bool {
21    let tag = tag.to_ascii_lowercase();
22    tag == "en" || tag.starts_with("en-")
23}
24
25/// The language to show among `languages` (`None` = untagged).
26fn preferred<'a>(
27    languages: impl Iterator<Item = Option<&'a str>> + Clone,
28) -> Option<Option<&'a str>> {
29    if languages.clone().any(|l| l.is_none()) {
30        return Some(None);
31    }
32    if let Some(en) = languages
33        .clone()
34        .flatten()
35        .find(|l| l.eq_ignore_ascii_case("en"))
36    {
37        return Some(Some(en));
38    }
39    if let Some(en) = languages.clone().flatten().find(|l| is_english(l)) {
40        return Some(Some(en));
41    }
42    languages.into_iter().next()
43}
44
45/// Whether `tag` belongs to the language `chosen` (case-insensitive).
46fn same_language(tag: Option<&str>, chosen: Option<&str>) -> bool {
47    match (tag, chosen) {
48        (None, None) => true,
49        (Some(a), Some(b)) => a.eq_ignore_ascii_case(b),
50        _ => false,
51    }
52}
53
54/// Literals with their language tags. Insertion order is kept and duplicates
55/// are dropped.
56#[derive(Debug, Clone, Default, PartialEq, Eq)]
57pub struct LangTexts(Vec<(String, Option<String>)>);
58
59impl LangTexts {
60    pub fn insert(&mut self, value: impl Into<String>, language: Option<&str>) {
61        let value = value.into();
62        let language = language.map(str::to_string);
63        if !self.0.iter().any(|(v, l)| *v == value && *l == language) {
64            self.0.push((value, language));
65        }
66    }
67
68    /// Add a literal term (other terms are ignored).
69    pub fn insert_term(&mut self, term: &MyTerm<'_>) {
70        if term.ty == Some(sophia_api::term::TermKind::Literal) {
71            self.insert(term.value.to_string(), term_language(term));
72        }
73    }
74
75    pub fn is_empty(&self) -> bool {
76        self.0.is_empty()
77    }
78
79    /// Every text in the preferred language, in insertion order.
80    pub fn preferred(&self) -> Vec<&str> {
81        let Some(chosen) = preferred(self.0.iter().map(|(_, l)| l.as_deref())) else {
82            return Vec::new();
83        };
84        self.0
85            .iter()
86            .filter(|(_, l)| same_language(l.as_deref(), chosen))
87            .map(|(v, _)| v.as_str())
88            .collect()
89    }
90
91    /// The first text in the preferred language.
92    pub fn first(&self) -> Option<&str> {
93        self.preferred().into_iter().next()
94    }
95}
96
97impl<'a> FromIterator<&'a MyTerm<'a>> for LangTexts {
98    fn from_iter<T: IntoIterator<Item = &'a MyTerm<'a>>>(iter: T) -> Self {
99        let mut out = LangTexts::default();
100        for t in iter {
101            out.insert_term(t);
102        }
103        out
104    }
105}
106
107/// Collapse runs of whitespace (multi-line `"""…"""` literals) to single spaces.
108pub fn normalize_ws(s: &str) -> Cow<'_, str> {
109    if s.split_whitespace().count() <= 1 && !s.contains(char::is_whitespace) {
110        return Cow::Borrowed(s);
111    }
112    Cow::Owned(s.split_whitespace().collect::<Vec<_>>().join(" "))
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    fn texts(items: &[(&str, Option<&str>)]) -> LangTexts {
120        let mut t = LangTexts::default();
121        for (v, l) in items {
122            t.insert(*v, *l);
123        }
124        t
125    }
126
127    #[test]
128    fn untagged_wins() {
129        let t = texts(&[("Naam", Some("nl")), ("Name", None), ("Name", Some("en"))]);
130        assert_eq!(t.preferred(), vec!["Name"]);
131    }
132
133    #[test]
134    fn english_then_regional_english() {
135        let t = texts(&[
136            ("Naam", Some("nl")),
137            ("Colour", Some("en-GB")),
138            ("Name", Some("EN")),
139        ]);
140        assert_eq!(t.preferred(), vec!["Name"]);
141        let t = texts(&[("Naam", Some("nl")), ("Colour", Some("en-GB"))]);
142        assert_eq!(t.preferred(), vec!["Colour"]);
143    }
144
145    #[test]
146    fn otherwise_the_first_language() {
147        let t = texts(&[
148            ("Naam", Some("nl")),
149            ("Nom", Some("fr")),
150            ("Benaming", Some("nl")),
151        ]);
152        assert_eq!(t.preferred(), vec!["Naam", "Benaming"]);
153        assert_eq!(t.first(), Some("Naam"));
154        assert!(LangTexts::default().preferred().is_empty());
155    }
156}