Skip to main content

renox_core/
i18n.rs

1//! Translations for app texts, and the language of each request.
2//!
3//! Renox ships English texts; an app adds its own languages as
4//! `resources/lang/{locale}.json` files (`LANG_PATH`, e.g. `es.json`), nested or flat:
5//!
6//! ```json
7//! { "products": { "saved": ":name guardado", "count": "Un producto|:count productos" } }
8//! ```
9//!
10//! ```
11//! # use renox::prelude::*;
12//! // templates: {{ t('products.saved', name='Coffee') }}  {{ t('products.count', count=3) }}
13//! async fn store(lang: Lang, session: Session, back: Back) -> Result<Back> {
14//!     session.flash("status", lang.t("products.saved", &[("name", &"Coffee")]))?;
15//!     Ok(back)
16//! }
17//! # fn demo(session: &Session) -> Result {
18//! renox::i18n::remember_locale(&session, "en")?;   // this visitor's language from now on
19//! # Ok(()) }
20//! ```
21//!
22//! A request's language is the one stored with `remember_locale`, else `APP_LOCALE`.
23//! Missing keys fall back to `APP_FALLBACK_LOCALE`, then to the key itself.
24//! Renox's own texts can be replaced or translated from the same files:
25//! `renox.validation.required`, `renox.validation.attributes.email` and
26//! `renox.auth.login_title` (see the built-in pages for the other keys).
27
28use std::collections::HashMap;
29use std::convert::Infallible;
30use std::fmt::Display;
31use std::path::{Path, PathBuf};
32use std::sync::{Arc, RwLock};
33use std::time::{Duration, Instant, SystemTime};
34
35use anyhow::Context;
36use axum::extract::{FromRequestParts, Request, State};
37use axum::http::request::Parts;
38use axum::middleware::Next;
39use axum::response::Response;
40use serde_json::Value;
41
42use crate::{AppState, Result, Session};
43
44const SESSION_KEY: &str = "_locale";
45/// How often debug mode looks for changed translation files.
46const RELOAD_CHECK: Duration = Duration::from_secs(1);
47
48pub(crate) type Texts = Arc<HashMap<String, String>>;
49
50struct Loaded {
51    locales: HashMap<String, Texts>,
52    fingerprint: Vec<(PathBuf, SystemTime)>,
53    checked: Instant,
54}
55
56/// Every locale's texts, keyed by dotted path.
57pub struct Translator {
58    dir: PathBuf,
59    reload: bool,
60    loaded: RwLock<Loaded>,
61}
62
63fn fingerprint(dir: &Path) -> Vec<(PathBuf, SystemTime)> {
64    let mut files: Vec<_> = std::fs::read_dir(dir)
65        .into_iter()
66        .flatten()
67        .flatten()
68        .map(|e| e.path())
69        .filter(|p| p.extension().is_some_and(|e| e == "json"))
70        .map(|p| {
71            let modified = p
72                .metadata()
73                .and_then(|m| m.modified())
74                .unwrap_or(SystemTime::UNIX_EPOCH);
75            (p, modified)
76        })
77        .collect();
78    files.sort();
79    files
80}
81
82fn flatten(prefix: &str, value: &Value, out: &mut HashMap<String, String>) {
83    match value {
84        Value::Object(map) => {
85            for (key, value) in map {
86                let key = if prefix.is_empty() {
87                    key.clone()
88                } else {
89                    format!("{prefix}.{key}")
90                };
91                flatten(&key, value, out);
92            }
93        }
94        Value::String(text) => {
95            out.insert(prefix.to_owned(), text.clone());
96        }
97        Value::Null => {}
98        other => {
99            out.insert(prefix.to_owned(), other.to_string());
100        }
101    }
102}
103
104fn parse(locales: &mut HashMap<String, Texts>, file: &str, text: &str) -> anyhow::Result<()> {
105    let locale = file.strip_suffix(".json").unwrap_or(file).to_owned();
106    let json: Value =
107        serde_json::from_str(text).with_context(|| format!("{file} is not valid JSON"))?;
108    let mut flat = HashMap::new();
109    flatten("", &json, &mut flat);
110    locales.insert(locale, Arc::new(flat));
111    Ok(())
112}
113
114fn read(dir: &Path) -> anyhow::Result<HashMap<String, Texts>> {
115    let mut locales = HashMap::new();
116    for (path, _) in fingerprint(dir) {
117        let locale = path
118            .file_stem()
119            .and_then(|s| s.to_str())
120            .unwrap_or_default()
121            .to_owned();
122        let text = std::fs::read_to_string(&path)
123            .with_context(|| format!("could not read {}", path.display()))?;
124        let json: Value = serde_json::from_str(&text)
125            .with_context(|| format!("{} is not valid JSON", path.display()))?;
126        let mut flat = HashMap::new();
127        flatten("", &json, &mut flat);
128        locales.insert(locale, Arc::new(flat));
129    }
130    Ok(locales)
131}
132
133impl Translator {
134    /// Uses translation files compiled into the binary.
135    pub(crate) fn embedded(files: &[(&str, &str)]) -> anyhow::Result<Self> {
136        let mut locales = HashMap::new();
137        for (file, text) in files
138            .iter()
139            .filter(|(f, _)| f.ends_with(".json") && !f.contains('/'))
140        {
141            parse(&mut locales, file, text)?;
142        }
143        Ok(Self {
144            dir: PathBuf::new(),
145            reload: false,
146            loaded: RwLock::new(Loaded {
147                locales,
148                fingerprint: Vec::new(),
149                checked: Instant::now(),
150            }),
151        })
152    }
153
154    /// Loads `dir`; a file that isn't valid JSON is an error.
155    pub(crate) fn load(dir: &Path, reload: bool) -> anyhow::Result<Self> {
156        Ok(Self {
157            dir: dir.to_path_buf(),
158            reload,
159            loaded: RwLock::new(Loaded {
160                locales: read(dir)?,
161                fingerprint: fingerprint(dir),
162                checked: Instant::now(),
163            }),
164        })
165    }
166
167    fn refresh(&self) {
168        if !self.reload {
169            return;
170        }
171        {
172            let loaded = self.loaded.read().unwrap_or_else(|e| e.into_inner());
173            if loaded.checked.elapsed() < RELOAD_CHECK {
174                return;
175            }
176        }
177        let mut loaded = self.loaded.write().unwrap_or_else(|e| e.into_inner());
178        loaded.checked = Instant::now();
179        let now = fingerprint(&self.dir);
180        if now != loaded.fingerprint {
181            match read(&self.dir) {
182                Ok(locales) => loaded.locales = locales,
183                Err(err) => tracing::error!(error = ?err, "keeping the previous translations"),
184            }
185            loaded.fingerprint = now;
186        }
187    }
188
189    /// The texts of one locale (empty if there is no file for it).
190    pub(crate) fn texts(&self, locale: &str) -> Texts {
191        self.refresh();
192        let loaded = self.loaded.read().unwrap_or_else(|e| e.into_inner());
193        loaded.locales.get(locale).cloned().unwrap_or_default()
194    }
195
196    /// Locales with a translation file.
197    pub fn locales(&self) -> Vec<String> {
198        self.refresh();
199        let loaded = self.loaded.read().unwrap_or_else(|e| e.into_inner());
200        let mut locales: Vec<_> = loaded.locales.keys().cloned().collect();
201        locales.sort();
202        locales
203    }
204
205    /// The text for `key` in `locale`, else in `fallback`, else the key itself.
206    pub fn get(&self, locale: &str, fallback: &str, key: &str) -> String {
207        if let Some(text) = self.texts(locale).get(key) {
208            return text.clone();
209        }
210        self.texts(fallback)
211            .get(key)
212            .cloned()
213            .or_else(|| {
214                builtin(locale)
215                    .or_else(|| builtin(fallback))?
216                    .get(key)
217                    .map(|t| (*t).to_owned())
218            })
219            .unwrap_or_else(|| key.to_owned())
220    }
221}
222
223/// A built-in text of `locale` (English when it has none), else the key.
224pub(crate) fn builtin_text(locale: &str, key: &str) -> String {
225    builtin(locale)
226        .and_then(|texts| texts.get(key))
227        .or_else(|| builtin("en")?.get(key))
228        .map_or_else(|| key.to_owned(), |t| (*t).to_owned())
229}
230
231/// Texts Renox's own templates use (the UI kit), in English; an app's
232/// `lang/*.json` can change them or add other languages.
233fn builtin(locale: &str) -> Option<&'static HashMap<&'static str, &'static str>> {
234    static EN: std::sync::LazyLock<HashMap<&str, &str>> = std::sync::LazyLock::new(|| {
235        HashMap::from([
236            ("ui.optional", "optional"),
237            ("ui.cancel", "Cancel"),
238            ("ui.close", "Close"),
239            ("ui.dismiss", "Dismiss"),
240            ("ui.request_failed", "That didn't work. Try again."),
241            ("ui.more", "More"),
242            ("ui.skip", "Skip to content"),
243            ("ui.main_navigation", "Main"),
244            ("ui.sections", "Sections"),
245            ("ui.sidebar.pin", "Keep the sidebar open"),
246            ("ui.sidebar.unpin", "Shrink the sidebar to icons"),
247            ("ui.errors_title", "Please check the highlighted fields."),
248            ("ui.show_password", "Show password"),
249            ("ui.hide_password", "Hide password"),
250            ("ui.copy", "Copy"),
251            ("ui.copied", "Copied"),
252            ("ui.choose_file", "Choose a file or drop it here"),
253            ("ui.choose_files", "Choose files or drop them here"),
254            ("ui.current_file", "Current file"),
255            ("ui.choose_date", "Choose a date"),
256            (
257                "ui.date_unavailable",
258                "That day can't be chosen: pick another one.",
259            ),
260            ("ui.previous_month", "Previous month"),
261            ("ui.next_month", "Next month"),
262            ("ui.search", "Search"),
263            ("ui.no_results", "No matches"),
264            ("ui.remove", "Remove"),
265            ("ui.add_row", "Add row"),
266            ("ui.move_up", "Move up"),
267            ("ui.move_down", "Move down"),
268            ("ui.key", "Key"),
269            ("ui.value", "Value"),
270            ("ui.back", "Back"),
271            ("ui.actions", "Actions"),
272            ("ui.import.file", "File"),
273            ("ui.import.columns", "Columns:"),
274            ("ui.import.template", "Download a template"),
275            ("ui.import.row", "Row"),
276            ("ui.import.problem", "Problem"),
277            ("ui.import.more", "…and :count more rows."),
278            ("ui.import.done", "One row imported.|:count rows imported."),
279            (
280                "ui.import.partial",
281                ":imported imported, one row left out.|:imported imported, :count rows left out.",
282            ),
283            (
284                "ui.import.nothing",
285                "Nothing was imported: one row has errors.|Nothing was imported: :count rows have errors.",
286            ),
287            (
288                "ui.import.check.done",
289                "The check found no problems: one row can be imported.|The check found no problems: :count rows can be imported.",
290            ),
291            (
292                "ui.import.check.partial",
293                "Check done, nothing was written: :imported can be imported, one row has errors.|Check done, nothing was written: :imported can be imported, :count rows have errors.",
294            ),
295            (
296                "ui.import.check.nothing",
297                "Check done, nothing was written: nothing can be imported, one row has errors.|Check done, nothing was written: nothing can be imported, :count rows have errors.",
298            ),
299            (
300                "ui.import.check_first",
301                "Check the file first (nothing is written)",
302            ),
303            ("ui.import.error_column", "Error"),
304            ("ui.import.download_failed", "Download the rows that failed"),
305            (
306                "ui.import.download_whole",
307                "Download the whole file with an error column",
308            ),
309            (
310                "ui.import.not_xlsx",
311                "The file is not a readable Excel workbook (.xlsx).",
312            ),
313            (
314                "ui.import.no_sheet",
315                "The workbook has no sheet called :sheet.",
316            ),
317            (
318                "ui.import.xlsx_unsupported",
319                "Excel files can't be read here: save the sheet as CSV.",
320            ),
321            ("ui.import.undo.unknown", "This import is not known."),
322            ("ui.import.undo.done", "This import was already undone."),
323            (
324                "ui.import.undo.expired",
325                "This import can no longer be undone: the time allowed for it has passed.",
326            ),
327            (
328                "ui.import.undo.deleted",
329                "The import can't be undone: the :table row :key was deleted after it.",
330            ),
331            (
332                "ui.import.undo.changed",
333                "The import can't be undone: the :table row :key was changed after it.",
334            ),
335            (
336                "ui.import.undo.in_use",
337                "The import can't be undone: the :table row :key is still used by :by.",
338            ),
339            ("ui.import.not_utf8", "The file must be CSV text (UTF-8)."),
340            ("ui.import.empty", "The file has no rows to import."),
341            ("ui.import.too_many", "The file has more than :count rows."),
342            (
343                "ui.import.duplicate",
344                "A value of this row must be unique, and is already taken.",
345            ),
346            ("ui.import.not_saved", "This row could not be saved."),
347            ("ui.next", "Next"),
348            ("ui.since.now", "just now"),
349            ("ui.since.past", ":time ago"),
350            ("ui.since.future", "in :time"),
351            ("ui.since.minutes", "a minute|:count minutes"),
352            ("ui.since.hours", "an hour|:count hours"),
353            ("ui.since.days", "a day|:count days"),
354            ("ui.since.months", "a month|:count months"),
355            ("ui.since.years", "a year|:count years"),
356            ("ui.show_more", "Show :count more"),
357            ("ui.yes", "Yes"),
358            ("ui.no", "No"),
359            ("ui.loading", "Loading…"),
360            ("ui.chart.show_data", "Show the data"),
361            ("ui.chart.other", "Other"),
362            ("ui.chart.series", "Series"),
363            ("ui.chart.size", "Size"),
364            ("ui.chart.axes", ":y by :x"),
365            ("ui.chart.less", "Less"),
366            ("ui.chart.more", "More"),
367            ("ui.stat.vs_previous", "vs previous period"),
368            ("ui.period.label", "Period"),
369            ("ui.period.7d", "7 days"),
370            ("ui.period.30d", "30 days"),
371            ("ui.period.90d", "90 days"),
372            ("ui.period.12w", "12 weeks"),
373            ("ui.period.12m", "12 months"),
374            ("ui.period.mtd", "This month"),
375            ("ui.period.ytd", "This year"),
376            ("ui.period.custom", "Custom"),
377            ("ui.period.custom_label", "Custom range"),
378            ("ui.period.from", "From"),
379            ("ui.period.to", "To"),
380            ("ui.period.apply", "Apply"),
381            (
382                "ui.period.invalid",
383                "Choose a start date on or before the end date, at most three years apart.",
384            ),
385            ("ui.notifications.title", "Notifications"),
386            ("ui.notifications.bell", "Notifications"),
387            ("ui.notifications.unread", ":count unread"),
388            ("ui.notifications.unread_marker", "unread"),
389            ("ui.notifications.mark_all_read", "Mark all as read"),
390            ("ui.notifications.clear", "Clear all"),
391            ("ui.notifications.mark_read", "Mark as read"),
392            ("ui.notifications.mark_unread", "Mark as unread"),
393            ("ui.notifications.delete", "Delete"),
394            ("ui.notifications.empty", "No notifications"),
395            ("ui.notifications.empty_hint", "You're all caught up."),
396            ("ui.notifications.see_all", "See all"),
397            ("ui.notifications.older", "Older"),
398            ("ui.notifications.newest", "Newest"),
399            ("ui.notifications.open", "Open"),
400            ("ui.notifications.loading", "Loading…"),
401            ("ui.searching", "Searching…"),
402            ("ui.load_failed", "Couldn't load the options."),
403            ("ui.add_option", "Add “:value”"),
404            ("ui.edit", "Edit"),
405            ("ui.editing", "Editing “:value”: Enter saves, Esc cancels."),
406            ("ui.save_failed", "Couldn't save it."),
407            (
408                "ui.offline.waiting",
409                "One waiting to send|:count waiting to send",
410            ),
411            (
412                "ui.offline.attention",
413                "One needs attention|:count need attention",
414            ),
415            (
416                "ui.offline.saved",
417                "No connection: saved on this device, it will be sent when you are back online.",
418            ),
419            ("ui.offline.sent", "Everything was sent."),
420            ("ui.offline.sending", "Sending…"),
421            ("ui.offline.sign_in", "Sign in to send."),
422            ("ui.offline.failed", "It could not be saved on this device."),
423            ("ui.offline.review", "Review"),
424            ("ui.offline.resend", "Send again"),
425            ("ui.offline.discard", "Discard"),
426            ("ui.offline.problem", "The server did not accept it."),
427            ("ui.grid.columns", "Columns"),
428            ("ui.grid.filter", "Filter"),
429            ("ui.grid.apply", "Apply"),
430            ("ui.grid.clear", "Clear"),
431            ("ui.grid.clear_all", "Clear filters"),
432            ("ui.grid.contains", "Contains"),
433            ("ui.grid.starts", "Starts with"),
434            ("ui.grid.ends", "Ends with"),
435            ("ui.grid.equals", "Equals"),
436            (
437                "ui.grid.pattern_hint",
438                "% matches anything: cof% starts with “cof”.",
439            ),
440            ("ui.grid.currency", "Currency"),
441            ("ui.grid.unit", "Unit"),
442            ("ui.grid.min", "From"),
443            ("ui.grid.max", "To"),
444            ("ui.grid.from", "From"),
445            ("ui.grid.to", "To"),
446            ("ui.grid.yes", "Yes"),
447            ("ui.grid.no", "No"),
448            ("ui.grid.rows", "Rows"),
449            ("ui.grid.row_word", "row|rows"),
450            ("ui.grid.of", "of"),
451            ("ui.grid.previous", "Previous page"),
452            ("ui.grid.next", "Next page"),
453            ("ui.grid.page", "Page"),
454            ("ui.grid.empty", "Nothing matches these filters."),
455            ("ui.grid.empty_all", "No rows yet."),
456            ("ui.grid.sort", "Sort"),
457            ("ui.grid.show", "Show on this screen"),
458            ("ui.grid.freeze", "Freeze"),
459            ("ui.grid.freeze_left", "Left"),
460            ("ui.grid.freeze_none", "None"),
461            ("ui.grid.freeze_right", "Right"),
462            ("ui.grid.move_up", "Move up"),
463            ("ui.grid.move_down", "Move down"),
464            ("ui.grid.reset", "Reset columns"),
465            ("ui.grid.filtered", "filtered"),
466            ("ui.grid.loading", "Loading…"),
467            ("ui.grid.advanced", "Advanced filter"),
468            ("ui.grid.match", "Show rows matching"),
469            ("ui.grid.match_all", "all of the rules"),
470            ("ui.grid.match_any", "any of the rules"),
471            ("ui.grid.add_rule", "Add a rule"),
472            ("ui.grid.remove_rule", "Remove the rule"),
473            ("ui.grid.rule_column", "Column"),
474            ("ui.grid.rule_op", "Condition"),
475            ("ui.grid.rule_value", "Value"),
476            ("ui.grid.rule_word", "rule|rules"),
477            ("ui.grid.op.contains", "contains"),
478            ("ui.grid.op.not_contains", "doesn't contain"),
479            ("ui.grid.op.equals", "is"),
480            ("ui.grid.op.not_equals", "isn't"),
481            ("ui.grid.op.starts", "starts with"),
482            ("ui.grid.op.ends", "ends with"),
483            ("ui.grid.op.empty", "is empty"),
484            ("ui.grid.op.not_empty", "isn't empty"),
485            ("ui.grid.op.eq", "="),
486            ("ui.grid.op.ne", "≠"),
487            ("ui.grid.op.gt", ">"),
488            ("ui.grid.op.gte", "≥"),
489            ("ui.grid.op.lt", "<"),
490            ("ui.grid.op.lte", "≤"),
491            ("ui.grid.op.on", "is on"),
492            ("ui.grid.op.before", "is before"),
493            ("ui.grid.op.after", "is after"),
494            ("ui.grid.op.is_true", "is yes"),
495            ("ui.grid.op.is_false", "is no"),
496            ("ui.grid.op.is", "is"),
497            ("ui.grid.op.is_not", "isn't"),
498            ("ui.grid.copy", "Copy"),
499            ("ui.grid.copied", "Copied"),
500            ("ui.grid.sum", "Total"),
501            ("ui.grid.average", "Average"),
502            ("ui.grid.range", "Range"),
503            ("ui.grid.count", "Count"),
504            ("ui.grid.group_by", "Group"),
505            ("ui.grid.no_groups", "No groups"),
506            ("ui.grid.all_rows", "All rows"),
507            ("ui.grid.group_rows", "This group"),
508            ("ui.grid.select_page", "Select every row on this page"),
509            ("ui.grid.select_row", "Select row"),
510            ("ui.grid.selected", "selected"),
511            ("ui.grid.select_matching", "Select all :total matching"),
512            ("ui.grid.select_none", "Clear selection"),
513            ("ui.grid.actions", "Actions"),
514            ("ui.grid.confirm", "Continue"),
515            ("ui.grid.all_matching", "all matching"),
516            ("ui.grid.search", "Search"),
517            ("ui.grid.active_filters", "Active filters"),
518            ("ui.grid.open", "Open"),
519            ("ui.grid.resize", "Column width"),
520            (
521                "ui.grid.resize_hint",
522                "Drag to resize, double-click for the automatic width; drag the heading to move the column",
523            ),
524            ("ui.grid.export", "Export"),
525            (
526                "ui.grid.export_hint",
527                "Every row the filters match, in your columns.",
528            ),
529            ("ui.grid.print", "Print or save as PDF"),
530            ("ui.grid.printed", "printed"),
531            ("ui.grid.back", "Back"),
532            ("ui.grid.created", "Created"),
533            ("ui.grid.updated", "Last updated"),
534            ("ui.grid.details", "Details"),
535            ("ui.grid.edit", "Edit row"),
536            ("ui.grid.save", "Save"),
537            ("ui.grid.move", "Drag to reorder (or use the arrow keys)"),
538            ("ui.grid.sort_to_move", "Sort by order to move rows"),
539            ("ui.grid.row_tools", "Row"),
540        ])
541    });
542    match locale {
543        "en" => Some(&EN),
544        _ => None,
545    }
546}
547
548/// Fills `:name` (and `:Name`, capitalised) placeholders, and picks the
549/// singular or plural side of `one|many` texts when `count` is given, or
550/// the matching range of `{0} none|[1,5] a few|[6,*] many` texts (Laravel's
551/// `trans_choice` ranges: `{n}` exactly, `[a,b]` from a to b, `*` open).
552pub fn format(text: &str, params: &[(&str, String)], count: Option<i64>) -> String {
553    let text = match (count, text.split_once('|')) {
554        (Some(count), Some(_)) if has_ranges(text) => choose_range(text, count),
555        (Some(1), Some((one, _))) => one.to_owned(),
556        (Some(_), Some((_, many))) => many.to_owned(),
557        _ => text.to_owned(),
558    };
559    let mut params: Vec<(String, String)> = params
560        .iter()
561        .map(|(k, v)| ((*k).to_owned(), v.clone()))
562        .collect();
563    if let Some(count) = count {
564        params.push(("count".into(), count.to_string()));
565    }
566    // Longest names first, so `:name` doesn't eat the start of `:names`.
567    params.sort_by_key(|(k, _)| std::cmp::Reverse(k.len()));
568    let mut out = text;
569    for (name, value) in params {
570        let mut capitalised = value.clone();
571        if let Some(first) = capitalised.get_mut(0..1) {
572            first.make_ascii_uppercase();
573        }
574        let mut upper_name = name.clone();
575        if let Some(first) = upper_name.get_mut(0..1) {
576            first.make_ascii_uppercase();
577        }
578        out = out
579            .replace(&format!(":{upper_name}"), &capitalised)
580            .replace(&format!(":{name}"), &value);
581    }
582    out
583}
584
585/// Whether a `|` text uses ranges (`{0} …|[1,*] …`).
586fn has_ranges(text: &str) -> bool {
587    text.split('|')
588        .any(|part| part.trim_start().starts_with(['{', '[']))
589}
590
591/// The part of a ranged text whose range holds `count`; the last part when
592/// none does. The range itself is left out.
593fn choose_range(text: &str, count: i64) -> String {
594    let parts: Vec<&str> = text.split('|').collect();
595    for part in &parts {
596        let part = part.trim_start();
597        let (range, rest) = if let Some(inner) = part.strip_prefix('{') {
598            match inner.split_once('}') {
599                Some((exact, rest)) => ((exact, exact), rest),
600                None => continue,
601            }
602        } else if let Some(inner) = part.strip_prefix('[') {
603            match inner.split_once(']').and_then(|(range, rest)| {
604                range.split_once(',').map(|(from, to)| ((from, to), rest))
605            }) {
606                Some(found) => found,
607                None => continue,
608            }
609        } else {
610            continue;
611        };
612        let bound = |text: &str, open: i64| match text.trim() {
613            "*" => Some(open),
614            number => number.parse::<i64>().ok(),
615        };
616        let (Some(from), Some(to)) = (bound(range.0, i64::MIN), bound(range.1, i64::MAX)) else {
617            continue;
618        };
619        if (from..=to).contains(&count) {
620            return rest.trim_start().to_owned();
621        }
622    }
623    let last = parts.last().copied().unwrap_or_default().trim_start();
624    // Without a matching range, the last text, minus its range.
625    match last.find([']', '}']) {
626        Some(end) if last.starts_with(['{', '[']) => last[end + 1..].trim_start().to_owned(),
627        _ => last.to_owned(),
628    }
629}
630
631/// The language chosen for the current request, kept in the request's
632/// extensions by Renox's language middleware (session choice, then
633/// `Accept-Language` with `App::detect_locale`, then `APP_LOCALE`).
634///
635/// A layer added with `App::layer` runs after it and may change the language
636/// of the rest of the request, e.g. to the signed-in user's own:
637///
638/// ```
639/// # use renox::prelude::*;
640/// use renox::i18n::RequestLocale;
641/// use renox::axum::{extract::Request, middleware::Next};
642///
643/// async fn account_language(mut req: Request, next: Next) -> Response {
644///     if let Some(chosen) = req.extensions().get::<RequestLocale>() {
645///         println!("chosen so far: {}", chosen.as_str());
646///     }
647///     RequestLocale::switch(&mut req, "es");
648///     next.run(req).await
649/// }
650/// # let _ = App::new().layer(renox::axum::middleware::from_fn(account_language));
651/// ```
652#[derive(Debug, Clone, PartialEq, Eq)]
653#[non_exhaustive]
654pub struct RequestLocale(String);
655
656impl RequestLocale {
657    /// A locale value, e.g. `es`.
658    pub fn new(locale: impl Into<String>) -> Self {
659        Self(locale.into())
660    }
661
662    /// The locale, e.g. `en`.
663    pub fn as_str(&self) -> &str {
664        &self.0
665    }
666
667    /// Makes `locale` the language of the rest of this request: the `Lang`
668    /// extractor, validation messages, `t()` in views, mails and
669    /// [`current_locale`] all follow. Call it from a layer; it does not
670    /// check that the locale has a translation file (texts fall back to
671    /// `APP_FALLBACK_LOCALE`, then to the key).
672    pub fn switch(req: &mut Request, locale: &str) {
673        set_current_locale(locale);
674        req.extensions_mut().insert(RequestLocale::new(locale));
675    }
676}
677
678impl std::ops::Deref for RequestLocale {
679    type Target = str;
680
681    fn deref(&self) -> &str {
682        &self.0
683    }
684}
685
686/// The request's language in [`crate::context`], for code without the
687/// request (mail views, notifications).
688#[derive(Debug, Clone)]
689struct ContextLocale(String);
690
691thread_local! {
692    /// Set while a notification builds its messages for a recipient.
693    static OVERRIDE: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
694}
695
696/// The language to use now: the recipient's while a notification is built,
697/// else the current request's (or the one a job set with
698/// [`with_locale`]), else `APP_LOCALE`.
699pub fn current_locale(state: &AppState) -> String {
700    OVERRIDE
701        .with(|o| o.borrow().clone())
702        .or_else(|| crate::context::get::<ContextLocale>().map(|l| l.0))
703        .unwrap_or_else(|| state.config.locale.clone())
704}
705
706/// Runs `f` (synchronous code, e.g. building a mail) in `locale`; `None`
707/// leaves the language as it is.
708pub fn with_locale<T>(locale: Option<&str>, f: impl FnOnce() -> T) -> T {
709    let Some(locale) = locale else { return f() };
710    let previous = OVERRIDE.with(|o| o.borrow_mut().replace(locale.to_owned()));
711    struct Restore(Option<String>);
712    impl Drop for Restore {
713        fn drop(&mut self) {
714            let previous = self.0.take();
715            OVERRIDE.with(|o| *o.borrow_mut() = previous);
716        }
717    }
718    let _restore = Restore(previous);
719    f()
720}
721
722/// Makes `locale` the language of the rest of this request, job or task
723/// (e.g. a job that mails a user in their language).
724pub fn set_current_locale(locale: &str) {
725    crate::context::set(ContextLocale(locale.to_owned()));
726}
727
728/// Makes `locale` this visitor's language from the next request on.
729pub fn remember_locale(session: &Session, locale: &str) -> Result {
730    session.put(SESSION_KEY, locale)
731}
732
733/// Picks the request's language: the session's choice if Renox knows the
734/// locale (a translation file or a built-in language), else `APP_LOCALE`.
735pub(crate) async fn middleware(
736    State(state): State<AppState>,
737    mut req: Request,
738    next: Next,
739) -> Response {
740    // In a block: nothing borrowing `req` may live across `next.run(req)` (§4.2).
741    let locale = {
742        let available =
743            |locale: &str| locale == "en" || state.translator.locales().iter().any(|l| l == locale);
744        let chosen = req
745            .extensions()
746            .get::<Session>()
747            .and_then(|s| s.get::<String>(SESSION_KEY))
748            .filter(|locale| available(locale));
749        let chosen = chosen.or_else(|| {
750            if !state.detect_locale {
751                return None;
752            }
753            req.headers()
754                .get(axum::http::header::ACCEPT_LANGUAGE)
755                .and_then(|v| v.to_str().ok())
756                .and_then(|header| from_accept_language(header, available))
757        });
758        chosen.unwrap_or_else(|| state.config.locale.clone())
759    };
760    set_current_locale(&locale);
761    req.extensions_mut().insert(RequestLocale::new(locale));
762    let mut res = next.run(req).await;
763    if state.detect_locale {
764        res.headers_mut().append(
765            axum::http::header::VARY,
766            axum::http::HeaderValue::from_static("Accept-Language"),
767        );
768    }
769    res
770}
771
772/// The locale for a request that runs before sessions: the best
773/// `Accept-Language` match when the app detects it, else `APP_LOCALE`.
774pub(crate) fn header_locale(state: &AppState, headers: &axum::http::HeaderMap) -> String {
775    let available =
776        |locale: &str| locale == "en" || state.translator.locales().iter().any(|l| l == locale);
777    state
778        .detect_locale
779        .then(|| {
780            headers
781                .get(axum::http::header::ACCEPT_LANGUAGE)
782                .and_then(|v| v.to_str().ok())
783                .and_then(|header| from_accept_language(header, available))
784        })
785        .flatten()
786        .unwrap_or_else(|| state.config.locale.clone())
787}
788
789/// The first language of an `Accept-Language` header (`es-MX,es;q=0.9,
790/// en;q=0.8`) that `available` accepts, by quality: the whole tag
791/// (`pt-br`), then its language (`pt`).
792fn from_accept_language(header: &str, available: impl Fn(&str) -> bool) -> Option<String> {
793    let mut wanted: Vec<(f32, usize, String)> = header
794        .split(',')
795        .enumerate()
796        .filter_map(|(order, item)| {
797            let mut parts = item.split(';');
798            let tag = parts.next()?.trim().to_ascii_lowercase();
799            let quality = parts
800                .find_map(|p| p.trim().strip_prefix("q="))
801                .map_or(Some(1.0), |q| q.trim().parse::<f32>().ok())?;
802            (!tag.is_empty() && tag != "*" && quality > 0.0).then_some((quality, order, tag))
803        })
804        .collect();
805    // Highest quality first; the header's order among equals.
806    wanted.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
807    wanted.into_iter().find_map(|(_, _, tag)| {
808        if available(&tag) {
809            return Some(tag);
810        }
811        let language = tag.split(['-', '_']).next()?;
812        available(language).then(|| language.to_owned())
813    })
814}
815
816pub(crate) fn request_locale(extensions: &axum::http::Extensions, state: &AppState) -> String {
817    extensions
818        .get::<RequestLocale>()
819        .map(|l| l.0.clone())
820        .unwrap_or_else(|| state.config.locale.clone())
821}
822
823/// The current request's language and its texts.
824///
825/// ```
826/// # use renox::prelude::*;
827/// async fn index(lang: Lang) -> String { lang.t("welcome", &[("name", &"Anna")]) }
828/// ```
829#[derive(Clone)]
830pub struct Lang {
831    /// The request's locale, e.g. `en`.
832    pub locale: String,
833    pub(crate) state: AppState,
834}
835
836impl Lang {
837    /// The request's language, for code that has the state but no request.
838    pub(crate) fn of(state: &AppState, locale: &str) -> Self {
839        Self {
840            locale: locale.to_owned(),
841            state: state.clone(),
842        }
843    }
844
845    pub(crate) fn texts(&self) -> Texts {
846        self.state.translator.texts(&self.locale)
847    }
848
849    /// Translates `key`, replacing `:name` placeholders with `params`; falls
850    /// back to `APP_FALLBACK_LOCALE`, then to the key itself.
851    pub fn t(&self, key: &str, params: &[(&str, &dyn Display)]) -> String {
852        let params: Vec<(&str, String)> = params.iter().map(|(k, v)| (*k, v.to_string())).collect();
853        format(&self.raw(key), &params, None)
854    }
855
856    /// Like `t`, choosing the `one|many` side by `count` and filling `:count`.
857    pub fn choice(&self, key: &str, count: i64, params: &[(&str, &dyn Display)]) -> String {
858        let params: Vec<(&str, String)> = params.iter().map(|(k, v)| (*k, v.to_string())).collect();
859        format(&self.raw(key), &params, Some(count))
860    }
861
862    fn raw(&self, key: &str) -> String {
863        self.state
864            .translator
865            .get(&self.locale, &self.state.config.fallback_locale, key)
866    }
867}
868
869/// The writing direction of a language.
870#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
871#[non_exhaustive]
872pub enum Direction {
873    /// Left to right.
874    Ltr,
875    /// Right to left (Arabic, Hebrew, Persian, ...).
876    Rtl,
877}
878
879impl Direction {
880    /// The value of the HTML `dir` attribute: `"ltr"` or `"rtl"`.
881    ///
882    /// ```
883    /// use renox::i18n::{direction, Direction};
884    /// assert_eq!(direction("ar").as_str(), "rtl");
885    /// assert_eq!(Direction::Ltr.as_str(), "ltr");
886    /// ```
887    pub fn as_str(self) -> &'static str {
888        match self {
889            Self::Ltr => "ltr",
890            Self::Rtl => "rtl",
891        }
892    }
893}
894
895/// Base languages written right to left, used unless `App::rtl_locales`
896/// replaces them.
897const RTL_LOCALES: &[&str] = &["ar", "he", "fa", "ur", "ps", "yi", "dv", "ckb"];
898
899fn base_subtag(locale: &str) -> String {
900    locale
901        .split(['-', '_'])
902        .next()
903        .unwrap_or_default()
904        .trim()
905        .to_ascii_lowercase()
906}
907
908/// The writing direction of `locale` (`ar`, `ar-AE` and `ar_AE` are all
909/// right to left; `en`, `es` and the empty string are left to right),
910/// judged by its base language against Arabic, Hebrew, Persian, Urdu,
911/// Pashto, Yiddish, Divehi and Central Kurdish. An app that changed the
912/// list with `App::rtl_locales` gets it through [`AppState::direction`].
913///
914/// ```
915/// use renox::i18n::{direction, Direction};
916/// assert_eq!(direction("ar-AE"), Direction::Rtl);
917/// assert_eq!(direction("en"), Direction::Ltr);
918/// ```
919pub fn direction(locale: &str) -> Direction {
920    let base = base_subtag(locale);
921    if RTL_LOCALES.contains(&base.as_str()) {
922        Direction::Rtl
923    } else {
924        Direction::Ltr
925    }
926}
927
928impl AppState {
929    /// The writing direction of `locale`, honouring `App::rtl_locales`
930    /// when the app set it, else [`direction`].
931    pub fn direction(&self, locale: &str) -> Direction {
932        match &self.rtl_locales {
933            Some(list) => {
934                let base = base_subtag(locale);
935                if list.iter().any(|l| base_subtag(l) == base) {
936                    Direction::Rtl
937                } else {
938                    Direction::Ltr
939                }
940            }
941            None => direction(locale),
942        }
943    }
944
945    /// The texts of `locale`, for code without a request (a job, a mail
946    /// to someone in another language).
947    pub fn lang(&self, locale: &str) -> Lang {
948        Lang::of(self, locale)
949    }
950
951    /// The texts of the [`current_locale`].
952    pub fn current_lang(&self) -> Lang {
953        Lang::of(self, &current_locale(self))
954    }
955}
956
957impl<S: Send + Sync> FromRequestParts<S> for Lang {
958    type Rejection = Infallible;
959
960    async fn from_request_parts(parts: &mut Parts, _: &S) -> std::result::Result<Self, Infallible> {
961        let state = parts
962            .extensions
963            .get::<AppState>()
964            .cloned()
965            .expect("the auth middleware puts AppState in every request");
966        Ok(Self {
967            locale: request_locale(&parts.extensions, &state),
968            state,
969        })
970    }
971}
972
973#[cfg(test)]
974mod tests {
975    use super::*;
976
977    /// Renox's own texts: English, English for a language without its own,
978    /// and the key itself for a text there isn't.
979    #[test]
980    fn builtin_texts_fall_back_to_english_then_the_key() {
981        assert_eq!(super::builtin_text("en", "ui.cancel"), "Cancel");
982        assert_eq!(super::builtin_text("xx", "ui.cancel"), "Cancel");
983        assert_eq!(
984            super::builtin_text("en", "ui.no-such-text"),
985            "ui.no-such-text"
986        );
987    }
988
989    #[test]
990    fn direction_follows_the_base_language() {
991        for rtl in ["ar", "ar-AE", "ar_AE", "AR", "he", "fa", "ckb"] {
992            assert_eq!(direction(rtl), Direction::Rtl, "{rtl}");
993        }
994        for ltr in ["en", "es", "pt-br", "", "arx"] {
995            assert_eq!(direction(ltr), Direction::Ltr, "{ltr}");
996        }
997        assert_eq!(Direction::Rtl.as_str(), "rtl");
998        assert_eq!(Direction::Ltr.as_str(), "ltr");
999    }
1000
1001    #[test]
1002    fn accept_language_picks_the_first_available() {
1003        let ours = |l: &str| matches!(l, "en" | "es" | "pt-br");
1004        assert_eq!(
1005            from_accept_language("es-MX,es;q=0.9,en;q=0.8", ours).as_deref(),
1006            Some("es")
1007        );
1008        assert_eq!(
1009            from_accept_language("fr, en;q=0.5", ours).as_deref(),
1010            Some("en")
1011        );
1012        assert_eq!(
1013            from_accept_language("en;q=0.2, es;q=0.9", ours).as_deref(),
1014            Some("es")
1015        );
1016        assert_eq!(
1017            from_accept_language("PT-BR", ours).as_deref(),
1018            Some("pt-br")
1019        );
1020        assert_eq!(from_accept_language("de, fr;q=0.8", ours), None);
1021        assert_eq!(from_accept_language("es;q=0, *", ours), None);
1022        assert_eq!(from_accept_language("", ours), None);
1023        assert_eq!(from_accept_language("en;q=abc", ours), None);
1024    }
1025
1026    #[test]
1027    fn formats_placeholders_and_plurals() {
1028        let p = [("name", "coffee".to_owned())];
1029        assert_eq!(format(":Name, :name!", &p, None), "Coffee, coffee!");
1030        assert_eq!(
1031            format("One product|:count products", &[], Some(1)),
1032            "One product"
1033        );
1034        assert_eq!(
1035            format("One product|:count products", &[], Some(4)),
1036            "4 products"
1037        );
1038        // Like Laravel: 0 and negative counts take the plural form.
1039        assert_eq!(
1040            format("One product|:count products", &[], Some(0)),
1041            "0 products"
1042        );
1043        assert_eq!(format("one|:count many", &[], Some(-1)), "-1 many");
1044        // Without a plural form the text is used as it is.
1045        assert_eq!(format(":count item", &[], Some(3)), "3 item");
1046        // Laravel's ranges.
1047        let ranged = "{0} No messages yet|[1,5] :count messages|[6,*] Many messages (:count)";
1048        assert_eq!(format(ranged, &[], Some(0)), "No messages yet");
1049        assert_eq!(format(ranged, &[], Some(1)), "1 messages");
1050        assert_eq!(format(ranged, &[], Some(5)), "5 messages");
1051        assert_eq!(format(ranged, &[], Some(40)), "Many messages (40)");
1052        assert_eq!(
1053            format("[*,-1] minus|{0} zero|[1,*] :count", &[], Some(-3)),
1054            "minus"
1055        );
1056        // No range matches: the last text.
1057        assert_eq!(format("{1} one|{2} two", &[], Some(7)), "two");
1058        // Without a count, ranged texts are left alone.
1059        assert_eq!(format("{0} a|[1,*] b", &[], None), "{0} a|[1,*] b");
1060        assert_eq!(
1061            format(
1062                ":name :names",
1063                &[("name", "a".into()), ("names", "b".into())],
1064                None
1065            ),
1066            "a b"
1067        );
1068    }
1069
1070    #[test]
1071    fn flattens_nested_files() {
1072        let json = serde_json::json!({ "a": { "b": "x", "n": 3 }, "c": "y" });
1073        let mut out = HashMap::new();
1074        flatten("", &json, &mut out);
1075        assert_eq!(out["a.b"], "x");
1076        assert_eq!(out["a.n"], "3");
1077        assert_eq!(out["c"], "y");
1078    }
1079
1080    /// Parts that aren't ranges, or whose ranges don't read, are skipped;
1081    /// with no match the last part is used as it is.
1082    #[test]
1083    fn ranges_that_dont_read_are_skipped() {
1084        let text = "{0 unclosed|[1 no end|plain|[a,b] letters|[1,2] few|the rest";
1085        assert_eq!(choose_range(text, 1), "few");
1086        assert_eq!(choose_range(text, 9), "the rest");
1087    }
1088
1089    /// A lang file broken while the app runs (a half-saved edit): the
1090    /// previous translations stay until the file reads again.
1091    #[test]
1092    fn a_lang_file_broken_while_reloading_keeps_the_previous_texts() {
1093        let dir = tempfile::tempdir().unwrap();
1094        let file = dir.path().join("es.json");
1095        std::fs::write(&file, r#"{"hi": "Hola"}"#).unwrap();
1096        let translator = Translator::load(dir.path(), true).unwrap();
1097        assert_eq!(translator.get("es", "en", "hi"), "Hola");
1098        std::fs::write(&file, r#"{"hi": "Hola de nue"#).unwrap();
1099        std::thread::sleep(RELOAD_CHECK + Duration::from_millis(100));
1100        assert_eq!(translator.get("es", "en", "hi"), "Hola");
1101        std::fs::write(&file, r#"{"hi": "Hola de nuevo"}"#).unwrap();
1102        std::thread::sleep(RELOAD_CHECK + Duration::from_millis(100));
1103        assert_eq!(translator.get("es", "en", "hi"), "Hola de nuevo");
1104    }
1105}