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: RwLockWriteGuard<'static, HashMap<String, HashMap<String, String>>> =
67            messages_lock().write().unwrap_or_else(
68                |e: PoisonError<
69                    RwLockWriteGuard<'static, HashMap<String, HashMap<String, String>>>,
70                >| e.into_inner(),
71            );
72        let entry_map: &mut HashMap<String, String> = guard.entry(locale.to_string()).or_default();
73        for (key, value) in entries {
74            entry_map.insert((*key).to_string(), (*value).to_string());
75        }
76    }
77
78    /// Removes every entry for `locale`. After this
79    /// call, `t(key)` for any key will skip this locale
80    /// in its lookup chain.
81    ///
82    /// OPT 22 (tail): see `add_messages` — writes through
83    /// the static lock.
84    ///
85    /// # Arguments
86    ///
87    /// - `&str` - Shared reference to a `str`.
88    pub fn remove_locale(&self, locale: &str) {
89        let mut guard: RwLockWriteGuard<'static, HashMap<String, HashMap<String, String>>> =
90            messages_lock().write().unwrap_or_else(
91                |e: PoisonError<
92                    RwLockWriteGuard<'static, HashMap<String, HashMap<String, String>>>,
93                >| e.into_inner(),
94            );
95        guard.remove(locale);
96    }
97
98    /// Removes a single message from a locale. After this
99    /// call, `t(key)` for this key in this locale will
100    /// fall back to `fallback_locale`.
101    ///
102    /// OPT 22 (tail): see `add_messages` — writes through
103    /// the static lock.
104    ///
105    /// # Arguments
106    ///
107    /// - `&str` - Shared reference to a `str`.
108    /// - `&str` - Shared reference to a `str`.
109    pub fn remove_message(&self, locale: &str, key: &str) {
110        let mut guard: RwLockWriteGuard<'static, HashMap<String, HashMap<String, String>>> =
111            messages_lock().write().unwrap_or_else(
112                |e: PoisonError<
113                    RwLockWriteGuard<'static, HashMap<String, HashMap<String, String>>>,
114                >| e.into_inner(),
115            );
116        if let Some(entry_map) = guard.get_mut(locale) {
117            entry_map.remove(key);
118        }
119    }
120
121    /// Translates `key` to a string under the active
122    /// locale, falling back to `fallback_locale` if the
123    /// active locale has no entry. Returns `key` itself
124    /// if neither locale has an entry (debug-friendly).
125    ///
126    /// This is the reactive read — calling it inside a
127    /// render closure subscribes that closure to locale
128    /// changes. The messages table itself is not reactive
129    /// (it lives behind [`I18N_MESSAGES`]).
130    ///
131    /// OPT 22 (tail): previously the read cloned the
132    /// entire translation table out of a `Signal` on every
133    /// call (a `HashMap<String, HashMap<String, String>>`
134    /// per `t()`). Now the read takes the read guard and
135    /// clones at most a single `String` (the message
136    /// itself) before dropping the guard.
137    ///
138    /// # Arguments
139    ///
140    /// - `&str` - Shared reference to a `str`.
141    ///
142    /// # Returns
143    ///
144    /// - `String` - A `String` value.
145    pub fn t(&self, key: &str) -> String {
146        // Borrow both locale signals via `Signal::with` instead of paying
147        // two `String` clones per call (per `t()` per render).
148        self.get_locale().with(|active: &String| {
149            self.get_fallback_locale().with(|fallback: &String| {
150                let guard: RwLockReadGuard<'static, HashMap<String, HashMap<String, String>>> =
151                    messages_lock().read().unwrap_or_else(
152                        |e: PoisonError<
153                            RwLockReadGuard<'static, HashMap<String, HashMap<String, String>>>,
154                        >| e.into_inner(),
155                    );
156                if let Some(message) = guard
157                    .get(active.as_str())
158                    .and_then(|m: &HashMap<String, String>| m.get(key))
159                {
160                    return message.clone();
161                }
162                if let Some(message) = guard
163                    .get(fallback.as_str())
164                    .and_then(|m: &HashMap<String, String>| m.get(key))
165                {
166                    return message.clone();
167                }
168                key.to_string()
169            })
170        })
171    }
172
173    /// Translates `key` and substitutes `{name}`-style
174    /// placeholders from `vars`.
175    ///
176    /// Placeholders that are present in `vars` are
177    /// replaced with their corresponding value.
178    /// Placeholders that are missing from `vars` are left
179    /// as the literal `{name}` token — matching the
180    /// i18next default behavior. No escaping is
181    /// supported; add it when a real use case shows up.
182    ///
183    /// # Arguments
184    ///
185    /// - `&str` - Shared reference to a `str`.
186    /// - `&HashMap<&'static str, &'static str>` - Shared reference to a `HashMap<&'static str, &'static str>`.
187    ///
188    /// # Returns
189    ///
190    /// - `String` - A `String` value.
191    pub fn t_with(&self, key: &str, vars: &HashMap<&'static str, &'static str>) -> String {
192        let template: String = self.t(key);
193        interpolate(&template, vars)
194    }
195
196    /// Returns the number of locales currently registered
197    /// (i.e. the number of distinct keys in the messages
198    /// map's outer level).
199    ///
200    /// OPT 22 (tail): borrows through [`I18N_MESSAGES`]
201    /// read guard instead of cloning the whole table.
202    ///
203    /// # Returns
204    ///
205    /// - `usize` - Count of registered locales.
206    pub fn locale_count(&self) -> usize {
207        let guard: RwLockReadGuard<'static, HashMap<String, HashMap<String, String>>> =
208            messages_lock().read().unwrap_or_else(
209                |e: PoisonError<
210                    RwLockReadGuard<'static, HashMap<String, HashMap<String, String>>>,
211                >| e.into_inner(),
212            );
213        guard.len()
214    }
215
216    /// Returns the number of messages registered for the
217    /// active locale.
218    ///
219    /// OPT 22 (tail): borrows through [`I18N_MESSAGES`]
220    /// read guard instead of cloning the whole table.
221    ///
222    /// # Returns
223    ///
224    /// - `usize` - Count of currently-registered messages.
225    pub fn active_message_count(&self) -> usize {
226        self.get_locale().with(|active: &String| {
227            let guard: RwLockReadGuard<'static, HashMap<String, HashMap<String, String>>> =
228                messages_lock().read().unwrap_or_else(
229                    |e: PoisonError<
230                        RwLockReadGuard<'static, HashMap<String, HashMap<String, String>>>,
231                    >| e.into_inner(),
232                );
233            guard
234                .get(active.as_str())
235                .map(|m: &HashMap<String, String>| m.len())
236                .unwrap_or_default()
237        })
238    }
239}
240
241/// `I18n` is `Copy` because every remaining field is a
242/// `Signal`, which is already `Copy` — the registry hands
243/// out cheap `usize` addresses for any `T: Clone + PartialEq
244/// + 'static`.
245impl Copy for I18n {}