Skip to main content

euv_ui/hook/i18n/
impl.rs

1use super::*;
2
3/// Implements [`HookContextI18nExt`] for [`HookContext`].
4impl HookContextI18nExt for HookContext {
5    /// Returns a fresh [`I18n`] bound to the current component scope.
6    ///
7    /// # Returns
8    ///
9    /// - `I18n` - A `I18n` value.
10    fn i18n() -> I18n {
11        HookContext::use_hook(|| {
12            I18n::new(
13                Signal::create(String::from("en")),
14                Signal::create(String::from("en")),
15            )
16        })
17    }
18}
19
20/// Inherent implementation of [`I18n`].
21impl I18n {
22    /// Sets the active locale to `locale`. Triggers a
23    /// reactive update so any reactive `t(key)` read
24    /// re-evaluates.
25    ///
26    /// Named `change_locale` (not `set_locale`) to avoid
27    /// colliding with the `set_locale` getter generated by
28    /// `#[derive(Data)]` on the struct field.
29    ///
30    /// # Arguments
31    ///
32    /// - `&str` - Shared reference to a `str`.
33    pub fn change_locale(&self, locale: &str) {
34        self.get_locale().set(locale.to_string());
35    }
36
37    /// Sets the fallback locale. Trigger a reactive
38    /// update for any `t(key)` whose key is missing in
39    /// the active locale — they may now resolve to a
40    /// different fallback value.
41    ///
42    /// Named `change_fallback_locale` (not
43    /// `set_fallback_locale`) for the same reason as
44    /// `change_locale`.
45    ///
46    /// # Arguments
47    ///
48    /// - `&str` - Shared reference to a `str`.
49    pub fn change_fallback_locale(&self, locale: &str) {
50        self.get_fallback_locale().set(locale.to_string());
51    }
52
53    /// Adds a batch of `(key, message)` entries to the
54    /// translation table for `locale`. Existing entries
55    /// for that locale are overwritten (last-write-wins).
56    ///
57    /// OPT 22 (tail): writes through the process-wide
58    /// [`I18N_MESSAGES`] lock instead of cloning the whole
59    /// table out of a `Signal` and re-setting it.
60    ///
61    /// # Arguments
62    ///
63    /// - `&str` - Shared reference to a `str`.
64    /// - `&[MessageEntry]` - Shared reference to a `[MessageEntry]`.
65    pub fn add_messages(&self, locale: &str, entries: &[MessageEntry]) {
66        let mut guard: std::sync::RwLockWriteGuard<
67            'static,
68            HashMap<String, HashMap<String, String>>,
69        > = messages_lock().write().unwrap_or_else(|e| e.into_inner());
70        let entry_map: &mut HashMap<String, String> = guard.entry(locale.to_string()).or_default();
71        for (key, value) in entries {
72            entry_map.insert((*key).to_string(), (*value).to_string());
73        }
74    }
75
76    /// Removes every entry for `locale`. After this
77    /// call, `t(key)` for any key will skip this locale
78    /// in its lookup chain.
79    ///
80    /// OPT 22 (tail): see `add_messages` — writes through
81    /// the static lock.
82    ///
83    /// # Arguments
84    ///
85    /// - `&str` - Shared reference to a `str`.
86    pub fn remove_locale(&self, locale: &str) {
87        let mut guard: std::sync::RwLockWriteGuard<
88            'static,
89            HashMap<String, HashMap<String, String>>,
90        > = messages_lock().write().unwrap_or_else(|e| e.into_inner());
91        guard.remove(locale);
92    }
93
94    /// Removes a single message from a locale. After this
95    /// call, `t(key)` for this key in this locale will
96    /// fall back to `fallback_locale`.
97    ///
98    /// OPT 22 (tail): see `add_messages` — writes through
99    /// the static lock.
100    ///
101    /// # Arguments
102    ///
103    /// - `&str` - Shared reference to a `str`.
104    /// - `&str` - Shared reference to a `str`.
105    pub fn remove_message(&self, locale: &str, key: &str) {
106        let mut guard: std::sync::RwLockWriteGuard<
107            'static,
108            HashMap<String, HashMap<String, String>>,
109        > = messages_lock().write().unwrap_or_else(|e| e.into_inner());
110        if let Some(entry_map) = guard.get_mut(locale) {
111            entry_map.remove(key);
112        }
113    }
114
115    /// Translates `key` to a string under the active
116    /// locale, falling back to `fallback_locale` if the
117    /// active locale has no entry. Returns `key` itself
118    /// if neither locale has an entry (debug-friendly).
119    ///
120    /// This is the reactive read — calling it inside a
121    /// render closure subscribes that closure to locale
122    /// changes. The messages table itself is not reactive
123    /// (it lives behind [`I18N_MESSAGES`]).
124    ///
125    /// OPT 22 (tail): previously the read cloned the
126    /// entire translation table out of a `Signal` on every
127    /// call (a `HashMap<String, HashMap<String, String>>`
128    /// per `t()`). Now the read takes the read guard and
129    /// clones at most a single `String` (the message
130    /// itself) before dropping the guard.
131    ///
132    /// # Arguments
133    ///
134    /// - `&str` - Shared reference to a `str`.
135    ///
136    /// # Returns
137    ///
138    /// - `String` - A `String` value.
139    pub fn t(&self, key: &str) -> String {
140        // Borrow both locale signals via `Signal::with` instead of paying
141        // two `String` clones per call (per `t()` per render).
142        self.get_locale().with(|active: &String| {
143            self.get_fallback_locale().with(|fallback: &String| {
144                let guard: std::sync::RwLockReadGuard<
145                    'static,
146                    HashMap<String, HashMap<String, String>>,
147                > = messages_lock().read().unwrap_or_else(|e| e.into_inner());
148                if let Some(message) = guard
149                    .get(active.as_str())
150                    .and_then(|m: &HashMap<String, String>| m.get(key))
151                {
152                    return message.clone();
153                }
154                if let Some(message) = guard
155                    .get(fallback.as_str())
156                    .and_then(|m: &HashMap<String, String>| m.get(key))
157                {
158                    return message.clone();
159                }
160                key.to_string()
161            })
162        })
163    }
164
165    /// Translates `key` and substitutes `{name}`-style
166    /// placeholders from `vars`.
167    ///
168    /// Placeholders that are present in `vars` are
169    /// replaced with their corresponding value.
170    /// Placeholders that are missing from `vars` are left
171    /// as the literal `{name}` token — matching the
172    /// i18next default behavior. No escaping is
173    /// supported; add it when a real use case shows up.
174    ///
175    /// # Arguments
176    ///
177    /// - `&str` - Shared reference to a `str`.
178    /// - `&HashMap<&'static str, &'static str>` - Shared reference to a `HashMap<&'static str, &'static str>`.
179    ///
180    /// # Returns
181    ///
182    /// - `String` - A `String` value.
183    pub fn t_with(&self, key: &str, vars: &HashMap<&'static str, &'static str>) -> String {
184        let template: String = self.t(key);
185        interpolate(&template, vars)
186    }
187
188    /// Returns the number of locales currently registered
189    /// (i.e. the number of distinct keys in the messages
190    /// map's outer level).
191    ///
192    /// OPT 22 (tail): borrows through [`I18N_MESSAGES`]
193    /// read guard instead of cloning the whole table.
194    ///
195    /// # Returns
196    ///
197    /// - `usize` - Count of registered locales.
198    pub fn locale_count(&self) -> usize {
199        let guard: std::sync::RwLockReadGuard<'static, HashMap<String, HashMap<String, String>>> =
200            messages_lock().read().unwrap_or_else(|e| e.into_inner());
201        guard.len()
202    }
203
204    /// Returns the number of messages registered for the
205    /// active locale.
206    ///
207    /// OPT 22 (tail): borrows through [`I18N_MESSAGES`]
208    /// read guard instead of cloning the whole table.
209    ///
210    /// # Returns
211    ///
212    /// - `usize` - Count of currently-registered messages.
213    pub fn active_message_count(&self) -> usize {
214        self.get_locale().with(|active: &String| {
215            let guard: std::sync::RwLockReadGuard<
216                'static,
217                HashMap<String, HashMap<String, String>>,
218            > = messages_lock().read().unwrap_or_else(|e| e.into_inner());
219            guard
220                .get(active.as_str())
221                .map(|m: &HashMap<String, String>| m.len())
222                .unwrap_or_default()
223        })
224    }
225}
226
227/// `I18n` is `Copy` because every remaining field is a
228/// `Signal`, which is already `Copy` — the registry hands
229/// out cheap `usize` addresses for any `T: Clone + PartialEq
230/// + 'static`.
231impl Copy for I18n {}