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