1use std::collections::BTreeMap;
14#[cfg(feature = "threads")]
15use std::path::Path;
16
17const ENGLISH: &str = include_str!("../locales/en.ftl");
18const SPANISH: &str = include_str!("../locales/es.ftl");
19
20#[derive(Clone, Debug)]
22pub struct Localizer {
28 locale: String,
29 messages: BTreeMap<String, String>,
30 fallback: BTreeMap<String, String>,
31}
32
33impl Default for Localizer {
34 fn default() -> Self {
35 Self::builtin("en")
36 }
37}
38
39impl Localizer {
40 pub fn builtin(locale: &str) -> Self {
42 let messages = match locale {
43 "es" => parse(SPANISH),
44 _ => parse(ENGLISH),
45 };
46 Self {
47 locale: locale.to_owned(),
48 messages,
49 fallback: parse(ENGLISH),
50 }
51 }
52
53 #[cfg(feature = "threads")]
54 pub fn load(directory: impl AsRef<Path>, locale: &str) -> Result<Self, LocalizationError> {
59 let plain = !locale.is_empty()
62 && locale.len() <= 32
63 && locale
64 .bytes()
65 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
66 if !plain {
67 return Ok(Self::builtin("en"));
68 }
69 let path = directory.as_ref().join(format!("{locale}.ftl"));
70 if path.is_file() {
71 let text = std::fs::read_to_string(&path).map_err(|error| LocalizationError::Io(error.to_string()))?;
72 let mut messages = Self::builtin(locale).messages;
73 messages.extend(parse(&text));
74 Ok(Self {
75 locale: locale.to_owned(),
76 messages,
77 fallback: parse(ENGLISH),
78 })
79 } else {
80 Ok(Self::builtin(locale))
81 }
82 }
83
84 pub fn locale(&self) -> &str {
86 &self.locale
87 }
88
89 pub fn is_rtl(&self) -> bool {
91 matches!(
92 self.locale.split(['-', '_']).next().unwrap_or(""),
93 "ar" | "he" | "fa" | "ur"
94 )
95 }
96
97 pub fn text(&self, key: &str) -> String {
99 self.translate(key, &[])
100 }
101
102 pub fn translate(&self, key: &str, args: &[(&str, &str)]) -> String {
104 let raw = self
105 .messages
106 .get(key)
107 .or_else(|| self.fallback.get(key))
108 .cloned()
109 .unwrap_or_else(|| key.to_owned());
110 interpolate(&raw, args)
111 }
112
113 pub fn plural(&self, key: &str, count: i64) -> String {
115 let raw = self
116 .messages
117 .get(key)
118 .or_else(|| self.fallback.get(key))
119 .cloned()
120 .unwrap_or_else(|| key.to_owned());
121 let category = if count == 1 { "one" } else { "other" };
122 let selected = select_plural(&raw, category).unwrap_or(raw);
123 interpolate(&selected, &[("count", &count.to_string())])
124 }
125}
126
127#[derive(Clone, Debug)]
129#[non_exhaustive]
130pub struct LocalizationState {
136 pub localizer: Localizer,
138}
139
140impl Default for LocalizationState {
141 fn default() -> Self {
142 Self::new("en")
143 }
144}
145
146impl LocalizationState {
147 pub fn new(locale: &str) -> Self {
149 Self {
150 localizer: Localizer::builtin(locale),
151 }
152 }
153
154 pub fn set_locale(&mut self, locale: &str) {
156 self.localizer = Localizer::builtin(locale);
157 }
158
159 pub fn t(&self, key: &str) -> String {
161 self.localizer.text(key)
162 }
163
164 pub fn locale(&self) -> &str {
166 self.localizer.locale()
167 }
168
169 pub fn is_rtl(&self) -> bool {
171 self.localizer.is_rtl()
172 }
173}
174
175#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
177#[non_exhaustive]
178pub enum LocalizationError {
184 #[error("{0}")]
186 Io(String),
187}
188
189fn parse(text: &str) -> BTreeMap<String, String> {
190 let mut messages = BTreeMap::new();
191 let mut key: Option<String> = None;
192 let mut value = String::new();
193 for line in text.lines() {
194 if line.trim_start().starts_with('#') {
195 continue;
196 }
197 if !line.starts_with(char::is_whitespace) && line.contains('=') {
198 if let Some(key) = key.take() {
199 messages.insert(key, value.trim().to_owned());
200 }
201 let (name, rest) = line.split_once('=').unwrap_or((line, ""));
202 key = Some(name.trim().to_owned());
203 value = rest.trim_start().to_owned();
204 } else if key.is_some() {
205 value.push('\n');
206 value.push_str(line);
207 }
208 }
209 if let Some(key) = key {
210 messages.insert(key, value.trim().to_owned());
211 }
212 messages
213}
214
215fn interpolate(text: &str, args: &[(&str, &str)]) -> String {
216 let mut result = String::with_capacity(text.len());
219 let mut rest = text;
220 while let Some(start) = rest.find("{ $") {
221 result.push_str(rest.get(..start).unwrap_or_default());
222 let after = rest.get(start + 3..).unwrap_or_default();
223 let replaced = after.find(" }").and_then(|end| {
224 let name = after.get(..end).unwrap_or_default();
225 args.iter()
226 .find(|(key, _)| *key == name)
227 .map(|(_, value)| (end + 2, *value))
228 });
229 match replaced {
230 Some((consumed, value)) => {
231 result.push_str(value);
232 rest = after.get(consumed..).unwrap_or_default();
233 }
234 None => {
235 result.push_str("{ $");
236 rest = after;
237 }
238 }
239 }
240 result.push_str(rest);
241 result
242}
243
244fn select_plural(raw: &str, category: &str) -> Option<String> {
245 let start = raw.find("->")?;
246 let block = raw.get(start + 2..).unwrap_or_default();
247 let mut current: Option<String> = None;
248 let mut values: Vec<(String, String)> = Vec::new();
249 for line in block.lines() {
250 let trimmed = line.trim();
251 let selector = trimmed
252 .strip_prefix('[')
253 .or_else(|| trimmed.strip_prefix("*["))
254 .and_then(|rest| rest.split_once(']'));
255 if let Some((name, rest)) = selector {
256 let name = name.trim().to_owned();
257 current = Some(name.clone());
258 let text = rest.trim();
259 if !text.is_empty() {
260 values.push((name, text.to_owned()));
261 }
262 } else if let Some(name) = ¤t {
263 let text = trimmed.trim_end_matches('}').trim();
264 if text.is_empty() {
265 continue;
266 }
267 if let Some(entry) = values.iter_mut().find(|(key, _)| key == name) {
268 if !entry.1.is_empty() {
269 entry.1.push(' ');
270 }
271 entry.1.push_str(text);
272 } else {
273 values.push((name.clone(), text.to_owned()));
274 }
275 }
276 }
277 values
278 .into_iter()
279 .find(|(name, _)| name == category)
280 .map(|(_, value)| value)
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 #[test]
288 fn english_and_spanish_strings_switch_at_runtime() {
289 let mut state = LocalizationState::new("en");
290 assert_eq!(state.t("app.save"), "Save");
291 state.set_locale("es");
292 assert_eq!(state.t("app.save"), "Guardar");
293 assert_eq!(state.t("devtools.performance"), "Rendimiento");
294 assert!(!state.is_rtl());
295 assert_eq!(state.t("missing.key"), "missing.key");
296 }
297
298 #[test]
299 fn plurals_use_one_and_other() {
300 let english = Localizer::builtin("en");
301 assert_eq!(english.plural("items", 1), "1 item");
302 assert_eq!(english.plural("items", 3), "3 items");
303 let spanish = Localizer::builtin("es");
304 assert_eq!(spanish.plural("files", 1), "1 archivo");
305 assert_eq!(spanish.plural("files", 2), "2 archivos");
306 assert!(Localizer::builtin("ar").is_rtl());
307 }
308
309 #[cfg(feature = "threads")]
310 #[test]
311 fn an_ftl_file_overrides_a_builtin() {
312 let directory = std::path::PathBuf::from("/tmp").join("crisol-locale-test");
313 std::fs::create_dir_all(&directory).expect("dir");
314 std::fs::write(directory.join("es.ftl"), "app.save = Guardar como\n").expect("write");
315 let localizer = Localizer::load(&directory, "es").expect("load");
316 assert_eq!(localizer.text("app.save"), "Guardar como");
317 assert_eq!(localizer.text("app.cancel"), "Cancelar");
318 let _ = std::fs::remove_dir_all(directory);
319 }
320
321 #[cfg(feature = "threads")]
322 #[test]
323 fn a_path_like_locale_falls_back_instead_of_escaping() {
324 let localizer = Localizer::load("/tmp", "../../etc/passwd").expect("fallback");
325 assert_eq!(localizer.locale(), "en");
326 }
327}