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