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 let active: String = self.get_locale().get();
141 let fallback: String = self.get_fallback_locale().get();
142 let guard: std::sync::RwLockReadGuard<'static, HashMap<String, HashMap<String, String>>> =
143 messages_lock().read().unwrap_or_else(|e| e.into_inner());
144 if let Some(message) = guard
145 .get(&active)
146 .and_then(|m: &HashMap<String, String>| m.get(key))
147 {
148 return message.clone();
149 }
150 if let Some(message) = guard
151 .get(&fallback)
152 .and_then(|m: &HashMap<String, String>| m.get(key))
153 {
154 return message.clone();
155 }
156 key.to_string()
157 }
158
159 /// Translates `key` and substitutes `{name}`-style
160 /// placeholders from `vars`.
161 ///
162 /// Placeholders that are present in `vars` are
163 /// replaced with their corresponding value.
164 /// Placeholders that are missing from `vars` are left
165 /// as the literal `{name}` token — matching the
166 /// i18next default behavior. No escaping is
167 /// supported; add it when a real use case shows up.
168 ///
169 /// # Arguments
170 ///
171 /// - `&str` - Shared reference to a `str`.
172 /// - `&HashMap<&'static str, &'static str>` - Shared reference to a `HashMap<&'static str, &'static str>`.
173 ///
174 /// # Returns
175 ///
176 /// - `String` - A `String` value.
177 pub fn t_with(&self, key: &str, vars: &HashMap<&'static str, &'static str>) -> String {
178 let template: String = self.t(key);
179 interpolate(&template, vars)
180 }
181
182 /// Returns the number of locales currently registered
183 /// (i.e. the number of distinct keys in the messages
184 /// map's outer level).
185 ///
186 /// OPT 22 (tail): borrows through [`I18N_MESSAGES`]
187 /// read guard instead of cloning the whole table.
188 ///
189 /// # Returns
190 ///
191 /// - `usize` - Count of registered locales.
192 pub fn locale_count(&self) -> usize {
193 let guard: std::sync::RwLockReadGuard<'static, HashMap<String, HashMap<String, String>>> =
194 messages_lock().read().unwrap_or_else(|e| e.into_inner());
195 guard.len()
196 }
197
198 /// Returns the number of messages registered for the
199 /// active locale.
200 ///
201 /// OPT 22 (tail): borrows through [`I18N_MESSAGES`]
202 /// read guard instead of cloning the whole table.
203 ///
204 /// # Returns
205 ///
206 /// - `usize` - Count of currently-registered messages.
207 pub fn active_message_count(&self) -> usize {
208 let active: String = self.get_locale().get();
209 let guard: std::sync::RwLockReadGuard<'static, HashMap<String, HashMap<String, String>>> =
210 messages_lock().read().unwrap_or_else(|e| e.into_inner());
211 guard
212 .get(&active)
213 .map(|m: &HashMap<String, String>| m.len())
214 .unwrap_or_default()
215 }
216}
217
218/// `I18n` is `Copy` because every remaining field is a
219/// `Signal`, which is already `Copy` — the registry hands
220/// out cheap `usize` addresses for any `T: Clone + PartialEq
221/// + 'static`.
222impl Copy for I18n {}