ocre/i18n.rs
1//! Translations: `locales/*.yml`, `%{name}` interpolation, plurals, locale per request.
2//!
3//! Works like Rails' `I18n.t`: YAML files in `locales/` compiled into the
4//! Worker, `%{name}` interpolation, CLDR plurals, fallback to the default
5//! locale and locale selection per request.
6//!
7//! ```yaml
8//! # locales/fr.yml (a YAML subset: nested keys and strings)
9//! fr:
10//! posts:
11//! created: "Article créé."
12//! greeting: "Bonjour %{name} !"
13//! count:
14//! one: "%{count} article" # CLDR categories: zero, one, two, few, many, other
15//! other: "%{count} articles"
16//! ```
17//!
18//! An app declares its locales once in `src/lib.rs` (`ocre g locale en fr`
19//! writes it) and adds [`layer`] at the end of
20//! `routes()`; handlers then take the [`I18n`] extractor:
21//!
22//! ```ignore
23//! // Not compiled here: `locales!` includes `locales/en.yml` and `locales/fr.yml` from the app's root.
24//! static LOCALES: ocre::i18n::Locales = ocre::locales!("en", "fr");
25//! ```
26//!
27//! ```
28//! use std::sync::LazyLock;
29//! use axum::{Router, routing::get};
30//! use ocre::{Ctx, i18n::{Catalog, I18n, Locales}};
31//!
32//! // `ocre::locales!("en", "fr")` expands to this, with the files' contents.
33//! static LOCALES: Locales = LazyLock::new(|| {
34//! Catalog::load(&[
35//! ("en", "en:\n posts:\n count:\n one: \"%{count} post\"\n other: \"%{count} posts\"\n"),
36//! ("fr", "fr:\n posts:\n count:\n one: \"%{count} article\"\n other: \"%{count} articles\"\n"),
37//! ])
38//! });
39//!
40//! async fn home(i18n: I18n) -> String {
41//! i18n.t("posts.count").count(3).to_string() // "3 articles" for French visitors
42//! }
43//!
44//! fn routes() -> Router<Ctx> {
45//! Router::new()
46//! .route("/", get(home))
47//! // ocre:routes
48//! .layer(ocre::i18n::layer(&LOCALES))
49//! }
50//! # let _ = routes;
51//!
52//! // Outside requests (mailers, jobs):
53//! assert_eq!(LOCALES.locale("fr").t("posts.count").count(3).to_string(), "3 articles");
54//! ```
55//!
56//! In templates, translations are [`Display`](std::fmt::Display) values that
57//! askama writes (escaped) straight into the page:
58//! `<p>{{ i18n.t("posts.greeting").arg("name", user.name) }}</p>`. Never mark
59//! them `|safe`; for a translation containing markup, end with
60//! [`.html()`](Translation::html), which escapes the values only.
61//!
62//! Beyond `t`: [`I18n::l`] formats dates and times, [`I18n::number`] and
63//! [`I18n::currency`] numbers, [`I18n::model_name`] and [`I18n::attribute`]
64//! name models and fields, [`I18n::error_message`] translates validation
65//! errors, and [`I18n::time_ago_in_words`] durations. Their texts come from
66//! the app's files first, then from built-in translations (compiled in, no
67//! parsing) for English, French, German, Spanish, Italian, Portuguese and
68//! Dutch, under the rails-i18n keys (`date.formats.short`,
69//! `errors.messages.blank`...).
70//!
71//! Each file is parsed once per Worker instance, the first time a key of its
72//! locale is looked up (a request in French parses `fr`, and the default
73//! locale's file only for a key `fr` lacks), not every declared locale, by a
74//! small parser for this YAML subset; lookups are a `BTreeMap` search.
75//! No D1, KV or other billed resource is used. [`I18n`] picks the locale from
76//! a `{locale}` path segment, then the `locale` cookie, then
77//! `Accept-Language`, then the default locale. A key missing from the
78//! request's locale falls back to the default locale in release builds
79//! (`ocre deploy`); debug builds (`ocre dev`) show
80//! `translation missing: fr.posts.created` instead, so gaps are visible.
81//! `ocre i18n missing` lists them (see [`check`]).
82
83mod builtin;
84mod format;
85mod model;
86mod plural;
87mod yaml;
88
89use std::{
90 borrow::Cow,
91 collections::{BTreeMap, BTreeSet},
92 fmt,
93 sync::{LazyLock, OnceLock},
94};
95
96use axum::{
97 Extension, Router,
98 extract::{FromRequestParts, RawPathParams, Request},
99 http::{HeaderMap, HeaderValue, Method, header, request::Parts},
100 middleware::{Next, from_fn},
101 response::{IntoResponse, Redirect, Response},
102};
103
104use crate::{Error, Result};
105use plural::{Category, Rule};
106
107/// Name of the cookie that remembers a visitor's chosen locale.
108///
109/// [`I18n`] reads it after the path segment; [`I18n::cookie`] builds its
110/// `Set-Cookie` value.
111pub const LOCALE_COOKIE: &str = "locale";
112
113/// Name of the path parameter [`I18n`] reads the locale from.
114///
115/// Nest localized routes under it: `.nest("/{locale}", pages())`. An unknown
116/// code in the path is a 404.
117pub const LOCALE_PARAM: &str = "locale";
118
119/// The app's translations: a [`Catalog`] parsed on first use, declared once as a `static`.
120///
121/// Build it with [`locales!`](crate::locales), which compiles the files into
122/// the binary; the first access in a Worker instance parses them, once, and
123/// later accesses reuse the parsed tables.
124///
125/// # Examples
126///
127/// ```ignore
128/// // Not compiled here: `locales!` includes `locales/*.yml` from the app's root.
129/// static LOCALES: ocre::i18n::Locales = ocre::locales!("en", "fr");
130/// ```
131///
132/// Without files, e.g. in tests:
133///
134/// ```
135/// use std::sync::LazyLock;
136/// static LOCALES: ocre::i18n::Locales =
137/// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n title: Posts\n")]));
138/// assert_eq!(LOCALES.locale("en").t("title").to_string(), "Posts");
139/// ```
140pub type Locales = LazyLock<Catalog>;
141
142/// Declares the app's locales as a [`Locales`] static, compiling `locales/<code>.yml` into the binary.
143///
144/// `ocre::locales!("en", "fr")` includes `locales/en.yml` and
145/// `locales/fr.yml` (paths from the app root, `CARGO_MANIFEST_DIR`) with
146/// `include_str!` and hands them to [`Catalog::load`](crate::i18n::Catalog::load)
147/// on first use. The first code is the default locale, used for fallbacks. A
148/// missing file is a compile error; a file that does not parse is logged and
149/// listed in [`Catalog::errors`](crate::i18n::Catalog::errors) (`ocre dev` and
150/// `ocre deploy` refuse it earlier).
151///
152/// Options follow the codes after a `;`: `unprefixed_default` serves the
153/// default locale's pages without a prefix ([`Catalog::unprefixed_default`](crate::i18n::Catalog::unprefixed_default)).
154///
155/// # Examples
156///
157/// ```ignore
158/// // Not compiled here: needs `locales/en.yml` and `locales/fr.yml` next to the app's Cargo.toml.
159/// static LOCALES: ocre::i18n::Locales = ocre::locales!("en", "fr");
160/// // `/pricing` in English, `/fr/pricing` in French:
161/// static LOCALES: ocre::i18n::Locales = ocre::locales!("en", "fr"; unprefixed_default);
162/// ```
163#[macro_export]
164macro_rules! locales {
165 ($($code:literal),+ $(,)? $(; $option:ident)*) => {
166 ::std::sync::LazyLock::new(|| {
167 $crate::i18n::Catalog::load(&[$((
168 $code,
169 ::std::include_str!(::std::concat!(::std::env!("CARGO_MANIFEST_DIR"), "/locales/", $code, ".yml")),
170 )),+])
171 $(.$option())*
172 })
173 };
174}
175
176/// Makes the catalog available to the [`I18n`] extractor, as an axum layer.
177///
178/// Forces `locales` (the files themselves are parsed on first use) and returns
179/// an [`Extension`] holding it. Add it last in `routes()`, after the
180/// `// ocre:routes` marker, so it covers every route; without it, [`I18n`]
181/// fails with a 500 whose log line names this fix.
182///
183/// # Examples
184///
185/// ```
186/// use std::sync::LazyLock;
187/// use axum::{Router, routing::get};
188/// use ocre::{Ctx, i18n::{Catalog, I18n, Locales}};
189///
190/// static LOCALES: Locales = LazyLock::new(|| Catalog::load(&[("en", "en:\n title: Posts\n")]));
191///
192/// async fn home(i18n: I18n) -> String {
193/// i18n.t("title").to_string()
194/// }
195///
196/// let _app: Router<Ctx> = Router::new()
197/// .route("/", get(home))
198/// // ocre:routes
199/// .layer(ocre::i18n::layer(&LOCALES));
200/// ```
201pub fn layer(locales: &'static Locales) -> Extension<&'static Catalog> {
202 Extension(LazyLock::force(locales))
203}
204
205/// A translated string (text or plural forms).
206#[derive(Debug, Clone, PartialEq)]
207enum Value<'t> {
208 Text(Cow<'t, str>),
209 /// Indexed like [`Category::ALL`].
210 Plural([Option<Cow<'t, str>>; 6]),
211}
212
213/// One locale file, parsed on first use: a Worker instance only pays for
214/// the locales its requests use (the default one and the visitor's).
215#[derive(Debug)]
216struct Table {
217 code: &'static str,
218 rule: Rule,
219 source: &'static str,
220 parsed: OnceLock<Parsed>,
221}
222
223/// A parsed file: its values (empty when it does not parse) and the parse error.
224#[derive(Debug)]
225struct Parsed {
226 values: BTreeMap<String, Value<'static>>,
227 error: Option<String>,
228}
229
230impl Table {
231 fn new(code: &'static str, source: &'static str) -> Self {
232 Self { code, rule: Rule::for_locale(code), source, parsed: OnceLock::new() }
233 }
234
235 /// Parses the file the first time; a parse error is logged once.
236 fn parsed(&self) -> &Parsed {
237 self.parsed.get_or_init(|| match yaml::parse_locale(self.code, self.source) {
238 Ok(entries) => Parsed { values: group(entries), error: None },
239 Err(err) => {
240 let error = format!("locales/{}.yml line {}: {}", self.code, err.line, err.message);
241 crate::error::log_internal(&error);
242 Parsed { values: BTreeMap::new(), error: Some(error) }
243 }
244 })
245 }
246
247 fn values(&self) -> &BTreeMap<String, Value<'static>> {
248 &self.parsed().values
249 }
250
251 /// Tables live in a `static` [`Locales`], so their strings are `'static`.
252 fn get(&'static self, key: &str, count: Option<i64>) -> Option<&'static str> {
253 let text = match (self.values().get(key)?, count) {
254 (Value::Text(text), _) => text,
255 (Value::Plural(forms), Some(0)) if forms[Category::Zero as usize].is_some() => {
256 forms[Category::Zero as usize].as_ref()?
257 }
258 (Value::Plural(forms), Some(n)) => {
259 forms[self.rule.category(n) as usize].as_ref().or(forms[Category::Other as usize].as_ref())?
260 }
261 (Value::Plural(forms), None) => forms[Category::Other as usize].as_ref()?,
262 };
263 Some(text)
264 }
265}
266
267const NO_LOCALES: &str = "no locales: declare them with ocre::locales!(\"en\")";
268
269/// All locales of an app: one table of dotted keys per locale code, the first being the default.
270///
271/// Built by [`locales!`](crate::locales) inside a [`Locales`] static. Each
272/// file is parsed the first time one of its keys is looked up, so adding
273/// locales costs a Worker instance nothing until a request uses them. Files
274/// that fail to parse are empty (so every key falls back to the default
275/// locale), logged to the Worker logs when first used and listed in
276/// [`errors`](Self::errors). [`locale`](Self::locale) gives translations
277/// outside requests; in handlers, the [`I18n`] extractor picks the locale.
278///
279/// # Examples
280///
281/// ```
282/// use std::sync::LazyLock;
283/// use ocre::i18n::{Catalog, Locales};
284///
285/// static LOCALES: Locales = LazyLock::new(|| {
286/// Catalog::load(&[("en", "en:\n hello: \"Hello %{name}\"\n"), ("fr", "fr:\n hello: \"Bonjour %{name}\"\n")])
287/// });
288///
289/// assert_eq!(LOCALES.default_locale(), "en");
290/// assert_eq!(LOCALES.codes().collect::<Vec<_>>(), ["en", "fr"]);
291/// assert_eq!(LOCALES.locale("fr").t("hello").arg("name", "Ada").to_string(), "Bonjour Ada");
292/// ```
293#[derive(Debug)]
294pub struct Catalog {
295 tables: Vec<Table>,
296 /// No locale was declared.
297 undeclared: bool,
298 errors: OnceLock<Vec<String>>,
299 /// The default locale's URLs carry no prefix (`/pricing`, `/fr/pricing`).
300 unprefixed_default: bool,
301}
302
303impl Catalog {
304 /// Builds a catalog of `(code, file contents)` pairs; the first pair is the default locale.
305 ///
306 /// Each file must start with its code as the root key (`en:`); plural
307 /// rules come from the code (`fr-CH` uses French rules). Files are
308 /// parsed on first use; one that does not parse becomes an empty table
309 /// and one entry in [`errors`](Self::errors), logged. An empty `sources`
310 /// gives an empty `en` catalog with an error telling to declare locales.
311 /// Never fails: missing translations show up at lookup time instead.
312 ///
313 /// # Examples
314 ///
315 /// ```
316 /// let catalog = ocre::i18n::Catalog::load(&[("en", "en:\n title: Posts\n")]);
317 /// assert!(catalog.errors().is_empty());
318 /// ```
319 pub fn load(sources: &[(&'static str, &'static str)]) -> Self {
320 let mut tables: Vec<Table> = sources.iter().map(|(code, text)| Table::new(code, text)).collect();
321 let undeclared = tables.is_empty();
322 if undeclared {
323 crate::error::log_internal(NO_LOCALES);
324 tables.push(Table::new("en", "en:\n"));
325 }
326 Self { tables, undeclared, errors: OnceLock::new(), unprefixed_default: false }
327 }
328
329 /// Serves the default locale's pages without a locale prefix: `/pricing` in English, `/fr/pricing` in French.
330 ///
331 /// By default every locale has its prefix (`/en/pricing`). With this
332 /// option, [`I18n::path`], [`I18n::alternates`] and
333 /// [`I18n::alternate_links`] leave the default locale's paths as they
334 /// are, and [`localized`] serves pages both ways. Declare it with the
335 /// locales: `ocre::locales!("en", "fr"; unprefixed_default)`.
336 ///
337 /// # Examples
338 ///
339 /// ```
340 /// use std::sync::LazyLock;
341 /// static LOCALES: ocre::i18n::Locales =
342 /// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n"), ("fr", "fr:\n")]).unprefixed_default());
343 /// assert_eq!(LOCALES.locale("en").path("/pricing"), "/pricing");
344 /// assert_eq!(LOCALES.locale("fr").path("/pricing"), "/fr/pricing");
345 /// ```
346 pub fn unprefixed_default(mut self) -> Self {
347 self.unprefixed_default = true;
348 self
349 }
350
351 /// Parse errors of the locale files, one line each (`locales/fr.yml line 3: ...`).
352 ///
353 /// Parses every file not parsed yet. Empty when every file parsed.
354 /// `ocre dev` and `ocre deploy` check the same files before building, so
355 /// a deployed app normally has none.
356 ///
357 /// # Examples
358 ///
359 /// ```
360 /// let catalog = ocre::i18n::Catalog::load(&[("en", "en:\n title: [Posts]\n")]);
361 /// assert_eq!(catalog.errors().len(), 1);
362 /// assert!(catalog.errors()[0].starts_with("locales/en.yml line 2: "));
363 /// ```
364 pub fn errors(&self) -> &[String] {
365 self.errors.get_or_init(|| {
366 let parse_errors = self.tables.iter().filter_map(|table| table.parsed().error.clone());
367 if self.undeclared { vec![NO_LOCALES.to_owned()] } else { parse_errors.collect() }
368 })
369 }
370
371 /// Returns the default locale code: the first code given to [`locales!`](crate::locales).
372 ///
373 /// Keys missing from another locale fall back to it in release builds,
374 /// and requests without a usable locale get it.
375 ///
376 /// # Examples
377 ///
378 /// ```
379 /// let catalog = ocre::i18n::Catalog::load(&[("fr", "fr:\n"), ("en", "en:\n")]);
380 /// assert_eq!(catalog.default_locale(), "fr");
381 /// ```
382 pub fn default_locale(&self) -> &'static str {
383 self.tables[0].code
384 }
385
386 /// Returns every locale code, default first, e.g. for a language switcher.
387 ///
388 /// # Examples
389 ///
390 /// ```
391 /// let catalog = ocre::i18n::Catalog::load(&[("en", "en:\n"), ("pt-BR", "pt-BR:\n")]);
392 /// assert_eq!(catalog.codes().collect::<Vec<_>>(), ["en", "pt-BR"]);
393 /// ```
394 pub fn codes(&self) -> impl Iterator<Item = &'static str> + '_ {
395 self.tables.iter().map(|table| table.code)
396 }
397
398 /// Returns translations in locale `code`, for code outside requests such as mailers and jobs.
399 ///
400 /// `code` matches case-insensitively and exactly (`fr-CH` does not match
401 /// `fr` here, unlike `Accept-Language`); an unknown code gives the
402 /// default locale. Requires a `'static` catalog, i.e. a [`Locales`]
403 /// static.
404 ///
405 /// # Examples
406 ///
407 /// ```
408 /// use std::sync::LazyLock;
409 /// static LOCALES: ocre::i18n::Locales = LazyLock::new(|| {
410 /// ocre::i18n::Catalog::load(&[("en", "en:\n subject: Welcome\n"), ("fr", "fr:\n subject: Bienvenue\n")])
411 /// });
412 ///
413 /// let user_locale = "FR";
414 /// assert_eq!(LOCALES.locale(user_locale).t("subject").to_string(), "Bienvenue");
415 /// assert_eq!(LOCALES.locale("de").locale(), "en");
416 /// ```
417 pub fn locale(&'static self, code: &str) -> I18n {
418 I18n { catalog: self, index: self.find(code).unwrap_or(0), scope: "" }
419 }
420
421 fn find(&self, code: &str) -> Option<usize> {
422 self.tables.iter().position(|table| table.code.eq_ignore_ascii_case(code))
423 }
424
425 /// Best locale for an `Accept-Language` header: by quality, exact code
426 /// first, then the same language (`fr-CH` matches `fr`, `pt` matches `pt-BR`).
427 fn negotiate(&self, accept_language: &str) -> Option<usize> {
428 let mut ranges: Vec<(&str, f32)> = accept_language
429 .split(',')
430 .filter_map(|part| {
431 let mut pieces = part.split(';');
432 let tag = pieces.next().unwrap_or_default().trim();
433 let quality = pieces
434 .find_map(|param| param.trim().strip_prefix("q="))
435 .map_or(1.0, |q| q.trim().parse::<f32>().unwrap_or(0.0));
436 (!tag.is_empty() && tag != "*" && quality > 0.0).then_some((tag, quality))
437 })
438 .collect();
439 ranges.sort_by(|a, b| b.1.total_cmp(&a.1));
440 ranges.iter().find_map(|(tag, _)| {
441 self.find(tag).or_else(|| {
442 let language = primary(tag);
443 self.tables.iter().position(|table| primary(table.code).eq_ignore_ascii_case(language))
444 })
445 })
446 }
447}
448
449/// `fr` of `fr-CH`.
450fn primary(tag: &str) -> &str {
451 tag.split(['-', '_']).next().unwrap_or(tag)
452}
453
454/// Turns `posts.count.one`/`posts.count.other` into one plural value. A
455/// mapping is plural when every child is a CLDR category name (`zero`,
456/// `one`, `two`, `few`, `many`, `other`).
457fn group<'t>(entries: Vec<(String, Cow<'t, str>)>) -> BTreeMap<String, Value<'t>> {
458 let flat: BTreeMap<String, Cow<'t, str>> = entries.into_iter().collect();
459 let candidates: BTreeSet<&str> = flat
460 .keys()
461 .filter_map(|key| key.rsplit_once('.'))
462 .filter(|(_, last)| Category::from_name(last).is_some())
463 .map(|(parent, _)| parent)
464 .collect();
465 let plural: BTreeSet<String> = candidates
466 .into_iter()
467 .filter(|parent| {
468 let prefix = format!("{parent}.");
469 flat.range(prefix.clone()..)
470 .take_while(|(key, _)| key.starts_with(&prefix))
471 .all(|(key, _)| Category::from_name(&key[prefix.len()..]).is_some())
472 })
473 .map(str::to_owned)
474 .collect();
475 let mut values = BTreeMap::new();
476 for (key, text) in flat {
477 match key.rsplit_once('.').filter(|(parent, _)| plural.contains(*parent)) {
478 Some((parent, last)) => {
479 let category = Category::from_name(last).expect("plural children are categories");
480 let entry = values.entry(parent.to_owned()).or_insert_with(|| Value::Plural(Default::default()));
481 if let Value::Plural(forms) = entry {
482 forms[category as usize] = Some(text);
483 }
484 }
485 None => {
486 values.insert(key, Value::Text(text));
487 }
488 }
489 }
490 values
491}
492
493/// A problem in the locale files, found by [`check`].
494///
495/// Displays as one line pointing at the file, as `ocre i18n missing` prints
496/// it: `locales/fr.yml: missing posts.title`.
497///
498/// # Examples
499///
500/// ```
501/// use ocre::i18n::Problem;
502///
503/// let missing = Problem::Missing { locale: "fr".into(), key: "posts.title".into() };
504/// assert_eq!(missing.to_string(), "locales/fr.yml: missing posts.title");
505/// let invalid = Problem::Invalid { locale: "fr".into(), line: 3, message: "expected `key: value`".into() };
506/// assert_eq!(invalid.to_string(), "locales/fr.yml:3: expected `key: value`");
507/// ```
508#[derive(Debug, Clone, PartialEq)]
509pub enum Problem {
510 /// The file is not valid locale YAML; nothing in it is used.
511 Invalid {
512 /// Locale code of the file, e.g. `fr` for `locales/fr.yml`.
513 locale: String,
514 /// 1-based line of the first error.
515 line: usize,
516 /// What is wrong, and how to fix it.
517 message: String,
518 },
519 /// A key of the default locale (or a plural form this language needs)
520 /// is missing from `locale`.
521 Missing {
522 /// Locale code of the file lacking the key.
523 locale: String,
524 /// Full dotted key, e.g. `posts.title` or `posts.count.few`.
525 key: String,
526 },
527}
528
529impl fmt::Display for Problem {
530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
531 match self {
532 Self::Invalid { locale, line, message } => write!(f, "locales/{locale}.yml:{line}: {message}"),
533 Self::Missing { locale, key } => write!(f, "locales/{locale}.yml: missing {key}"),
534 }
535 }
536}
537
538/// Checks locale files for syntax errors and keys missing from non-default locales.
539///
540/// Reads `(code, file contents)` pairs the way [`Catalog::load`] does: first
541/// the syntax of each file ([`Problem::Invalid`]), then every key of the
542/// default (first) locale in every other one ([`Problem::Missing`]), with the
543/// plural forms each language needs (Russian needs `one`, `few`, `many` and
544/// `other`; Japanese only `other`). A plural key present as plain text counts
545/// as present. When the default file is invalid, only syntax problems are
546/// reported. Nothing is logged; `ocre i18n missing` prints the result and
547/// fails when it is not empty.
548///
549/// # Examples
550///
551/// ```
552/// use ocre::i18n::{Problem, check};
553///
554/// let problems = check(&[
555/// ("en", "en:\n title: Posts\n count:\n one: \"%{count} post\"\n other: \"%{count} posts\"\n"),
556/// ("fr", "fr:\n count:\n one: \"%{count} article\"\n other: \"%{count} articles\"\n"),
557/// ]);
558/// assert_eq!(problems, [Problem::Missing { locale: "fr".into(), key: "title".into() }]);
559///
560/// // Russian needs more plural forms than English.
561/// let problems = check(&[
562/// ("en", "en:\n count:\n one: \"%{count} post\"\n other: \"%{count} posts\"\n"),
563/// ("ru", "ru:\n count:\n one: \"%{count} пост\"\n other: \"%{count} поста\"\n"),
564/// ]);
565/// let lines: Vec<String> = problems.iter().map(ToString::to_string).collect();
566/// assert_eq!(lines, ["locales/ru.yml: missing count.few", "locales/ru.yml: missing count.many"]);
567/// ```
568pub fn check(sources: &[(&str, &str)]) -> Vec<Problem> {
569 let mut problems = Vec::new();
570 let mut parsed = Vec::with_capacity(sources.len());
571 for (code, text) in sources {
572 match yaml::parse_locale(code, text) {
573 Ok(entries) => parsed.push(Some(entries)),
574 Err(err) => {
575 problems.push(Problem::Invalid { locale: (*code).to_owned(), line: err.line, message: err.message });
576 parsed.push(None);
577 }
578 }
579 }
580 let Some(Some(default)) = parsed.first() else {
581 return problems;
582 };
583 let default = group(default.clone());
584 for ((code, _), entries) in sources.iter().zip(&parsed).skip(1) {
585 let Some(entries) = entries else { continue };
586 let present: BTreeSet<&str> = entries.iter().map(|(key, _)| key.as_str()).collect();
587 for (key, value) in &default {
588 let required: Vec<String> = match value {
589 Value::Text(_) => vec![key.clone()],
590 Value::Plural(_) if present.contains(key.as_str()) => vec![],
591 Value::Plural(_) => Rule::for_locale(code)
592 .categories()
593 .iter()
594 .map(|category| format!("{key}.{}", category.name()))
595 .collect(),
596 };
597 for key in required.into_iter().filter(|key| !present.contains(key.as_str())) {
598 problems.push(Problem::Missing { locale: (*code).to_owned(), key });
599 }
600 }
601 }
602 problems
603}
604
605/// Axum extractor giving translations in the request's locale, like Rails' `I18n.t` with a per-request locale.
606///
607/// The locale comes from the `{locale}` path segment (routes nested with
608/// `.nest("/{locale}", ..)`, see [`LOCALE_PARAM`]), else the `locale` cookie
609/// ([`LOCALE_COOKIE`]), else `Accept-Language` (by quality; `fr-CH` matches
610/// `fr`, `pt` matches `pt-BR`), else the default locale. It is `Copy`: pass
611/// it by value to template structs, where `{{ i18n.t("posts.title") }}`
612/// writes the text. Selecting the locale reads headers only; no billed
613/// resource is used.
614///
615/// Rejections render as HTML pages in full-stack apps and as JSON in
616/// API-only apps:
617/// - [`Error::NotFound`] (404) when the `{locale}`
618/// path segment is not one of the app's locales;
619/// - [`Error::Internal`] (500) when [`layer`] is
620/// missing; the log line names the fix.
621///
622/// # Examples
623///
624/// ```
625/// use axum::{Router, routing::get};
626/// use ocre::{Ctx, i18n::I18n};
627///
628/// async fn title(i18n: I18n) -> String {
629/// i18n.t("posts.title").to_string()
630/// }
631///
632/// // `/en/posts`, `/fr/posts`; `/de/posts` is a 404 unless the app has German.
633/// fn routes() -> Router<Ctx> {
634/// Router::new().nest("/{locale}", Router::new().route("/posts", get(title)))
635/// }
636/// # let _ = routes;
637/// ```
638#[derive(Clone, Copy)]
639pub struct I18n {
640 catalog: &'static Catalog,
641 index: usize,
642 /// Prefix of keys starting with `.`, set by [`scope`](Self::scope).
643 scope: &'static str,
644}
645
646impl fmt::Debug for I18n {
647 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
648 f.debug_struct("I18n").field("locale", &self.locale()).finish()
649 }
650}
651
652impl I18n {
653 /// Returns the locale code, e.g. for `<html lang="{{ i18n.locale() }}">`.
654 ///
655 /// # Examples
656 ///
657 /// ```
658 /// # use std::sync::LazyLock;
659 /// static LOCALES: ocre::i18n::Locales = LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n")]));
660 /// assert_eq!(LOCALES.locale("en").locale(), "en");
661 /// ```
662 pub fn locale(&self) -> &'static str {
663 self.catalog.tables[self.index].code
664 }
665
666 /// Returns every locale code of the app, default first, e.g. for a language switcher.
667 ///
668 /// # Examples
669 ///
670 /// ```
671 /// # use std::sync::LazyLock;
672 /// static LOCALES: ocre::i18n::Locales =
673 /// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n"), ("fr", "fr:\n")]));
674 /// assert_eq!(LOCALES.locale("fr").codes().collect::<Vec<_>>(), ["en", "fr"]);
675 /// ```
676 pub fn codes(&self) -> impl Iterator<Item = &'static str> + 'static {
677 self.catalog.codes()
678 }
679
680 /// Starts the translation of a dotted key, like Rails' `t("posts.created")`.
681 ///
682 /// The returned [`Translation`] is a [`Display`](fmt::Display) value:
683 /// askama writes it (escaped) into the page without an extra `String`,
684 /// `.to_string()` gives one (for flashes, emails). Add `%{name}` values
685 /// with [`Translation::arg`] and the plural count with
686 /// [`Translation::count`]. The lookup happens when it is displayed.
687 ///
688 /// # Examples
689 ///
690 /// ```
691 /// # use std::sync::LazyLock;
692 /// static LOCALES: ocre::i18n::Locales = LazyLock::new(|| {
693 /// ocre::i18n::Catalog::load(&[("en", "en:\n posts:\n created: Post was successfully created.\n")])
694 /// });
695 /// let i18n = LOCALES.locale("en");
696 /// assert_eq!(i18n.t("posts.created").to_string(), "Post was successfully created.");
697 /// ```
698 pub fn t<'a>(&self, key: &'a str) -> Translation<'a> {
699 Translation {
700 i18n: *self,
701 key: self.resolve(key),
702 alternatives: Vec::new(),
703 default: None,
704 count: None,
705 args: Vec::new(),
706 }
707 }
708
709 /// Returns the same translations with `scope` as the prefix of keys starting with `.` (Rails' lazy lookup).
710 ///
711 /// `i18n.scope("posts.index").t(".title")` looks up `posts.index.title`;
712 /// keys without a leading dot stay absolute. Rails derives the scope from
713 /// the view's path; in Ocre, the handler sets it before passing `i18n` to
714 /// its template. A scope replaces the previous one.
715 ///
716 /// # Examples
717 ///
718 /// ```
719 /// # use std::sync::LazyLock;
720 /// static LOCALES: ocre::i18n::Locales = LazyLock::new(|| {
721 /// ocre::i18n::Catalog::load(&[("en", "en:\n app:\n name: Blog\n posts:\n index:\n title: Posts\n")])
722 /// });
723 /// let i18n = LOCALES.locale("en").scope("posts.index");
724 /// assert_eq!(i18n.t(".title").to_string(), "Posts");
725 /// assert_eq!(i18n.t("app.name").to_string(), "Blog");
726 /// ```
727 pub fn scope(&self, scope: &'static str) -> Self {
728 Self { scope, ..*self }
729 }
730
731 /// Returns the same translations in locale `code` (Rails' `locale:` option), keeping the scope.
732 ///
733 /// `code` matches like [`Catalog::locale`]: exactly, case-insensitively,
734 /// and an unknown code gives the default locale.
735 ///
736 /// # Examples
737 ///
738 /// ```
739 /// # use std::sync::LazyLock;
740 /// static LOCALES: ocre::i18n::Locales = LazyLock::new(|| {
741 /// ocre::i18n::Catalog::load(&[("en", "en:\n hello: Hello\n"), ("fr", "fr:\n hello: Bonjour\n")])
742 /// });
743 /// let i18n = LOCALES.locale("en");
744 /// assert_eq!(i18n.in_locale("fr").t("hello").to_string(), "Bonjour");
745 /// assert_eq!(i18n.in_locale("de").locale(), "en");
746 /// ```
747 pub fn in_locale(&self, code: &str) -> Self {
748 Self { index: self.catalog.find(code).unwrap_or(0), ..*self }
749 }
750
751 /// Whether `key` has a translation: in the locale, the default locale or the built-in translations.
752 ///
753 /// Keys starting with `.` are relative to the [`scope`](Self::scope).
754 ///
755 /// # Examples
756 ///
757 /// ```
758 /// # use std::sync::LazyLock;
759 /// static LOCALES: ocre::i18n::Locales =
760 /// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n posts:\n title: Posts\n")]));
761 /// let i18n = LOCALES.locale("en");
762 /// assert!(i18n.exists("posts.title"));
763 /// assert!(i18n.exists("errors.messages.blank"), "built in");
764 /// assert!(!i18n.exists("posts"), "a namespace is not a translation");
765 /// ```
766 pub fn exists(&self, key: &str) -> bool {
767 self.lookup(&[&self.resolve(key)], None, false).is_some()
768 }
769
770 /// Returns every translation under `prefix`, by key relative to it (Rails' namespace lookup).
771 ///
772 /// Nested keys keep their dots (`form.submit`); plural keys give their
773 /// `other` form. Only the app's files are read. Release builds add the
774 /// default locale's keys missing from the locale, as [`t`](Self::t) falls
775 /// back to them. Keys starting with `.` are relative to the
776 /// [`scope`](Self::scope). Handy to hand a group of texts to JavaScript:
777 /// `Json(i18n.namespace("editor"))`.
778 ///
779 /// # Examples
780 ///
781 /// ```
782 /// # use std::sync::LazyLock;
783 /// static LOCALES: ocre::i18n::Locales = LazyLock::new(|| {
784 /// ocre::i18n::Catalog::load(&[("en", "en:\n editor:\n bold: Bold\n link:\n title: Link\n other: x\n")])
785 /// });
786 /// let texts = LOCALES.locale("en").namespace("editor");
787 /// assert_eq!(texts.into_iter().collect::<Vec<_>>(), [("bold", "Bold"), ("link.title", "Link")]);
788 /// ```
789 pub fn namespace(&self, prefix: &str) -> BTreeMap<&'static str, &'static str> {
790 self.namespace_in(prefix, cfg!(debug_assertions))
791 }
792
793 fn namespace_in(&self, prefix: &str, strict: bool) -> BTreeMap<&'static str, &'static str> {
794 let start = format!("{}.", self.resolve(prefix));
795 let mut texts = BTreeMap::new();
796 let tables = if strict || self.index == 0 { &[self.index][..] } else { &[0, self.index][..] };
797 for &index in tables {
798 let table: &'static Table = &self.catalog.tables[index];
799 for (key, _) in table.values().range(start.clone()..).take_while(|(key, _)| key.starts_with(&start)) {
800 if let Some(text) = table.get(key, None) {
801 texts.insert(&key[start.len()..], text);
802 }
803 }
804 }
805 texts
806 }
807
808 /// Prefixes `path` with the locale, for routes nested under `/{locale}` (Rails' `default_url_options`).
809 ///
810 /// `i18n.path("/posts")` is `/fr/posts` for French visitors, so links
811 /// keep the locale; `"/"` gives `/fr`. Use it in templates:
812 /// `<a href="{{ i18n.path("/posts") }}">`. With
813 /// [`unprefixed_default`](Catalog::unprefixed_default), the default
814 /// locale's paths stay as they are (`/posts`).
815 ///
816 /// # Examples
817 ///
818 /// ```
819 /// # use std::sync::LazyLock;
820 /// static LOCALES: ocre::i18n::Locales =
821 /// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n"), ("fr", "fr:\n")]));
822 /// let i18n = LOCALES.locale("fr");
823 /// assert_eq!(i18n.path("/posts/3"), "/fr/posts/3");
824 /// assert_eq!(i18n.path("/"), "/fr");
825 /// ```
826 pub fn path(&self, path: &str) -> String {
827 let rest = path.trim_start_matches('/');
828 match rest {
829 _ if self.catalog.unprefixed_default && self.index == 0 => format!("/{rest}"),
830 "" => format!("/{}", self.locale()),
831 rest => format!("/{}/{rest}", self.locale()),
832 }
833 }
834
835 /// The text direction of the locale, `rtl` or `ltr`, for `<html dir="{{ i18n.dir() }}">`.
836 ///
837 /// Right to left for Arabic, Hebrew, Persian, Urdu, Pashto, Sindhi,
838 /// Uyghur, Yiddish, Dhivehi and Central Kurdish (by language, so `ar-EG`
839 /// too).
840 ///
841 /// # Examples
842 ///
843 /// ```
844 /// # use std::sync::LazyLock;
845 /// static LOCALES: ocre::i18n::Locales =
846 /// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n"), ("ar-EG", "ar-EG:\n")]));
847 /// assert_eq!(LOCALES.locale("ar-EG").dir(), "rtl");
848 /// assert_eq!(LOCALES.locale("en").dir(), "ltr");
849 /// ```
850 pub fn dir(&self) -> &'static str {
851 const RTL: [&str; 10] = ["ar", "he", "fa", "ur", "ps", "sd", "ug", "yi", "dv", "ckb"];
852 if RTL.iter().any(|language| primary(self.locale()).eq_ignore_ascii_case(language)) { "rtl" } else { "ltr" }
853 }
854
855 /// The absolute URL of `path` in every locale, the default first:
856 /// `(code, base_url + "/<code>" + path)`, for a sitemap's alternates
857 /// ([`Sitemap::add_localized`](crate::seo::Sitemap::add_localized)).
858 ///
859 /// # Examples
860 ///
861 /// ```
862 /// # use std::sync::LazyLock;
863 /// static LOCALES: ocre::i18n::Locales =
864 /// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n"), ("zh-Hans", "zh-Hans:\n")]));
865 /// let urls = LOCALES.locale("zh-Hans").alternates("https://ex.com/", "/pricing");
866 /// assert_eq!(urls, [("en", "https://ex.com/en/pricing".to_owned()), ("zh-Hans", "https://ex.com/zh-Hans/pricing".to_owned())]);
867 /// ```
868 pub fn alternates(&self, base_url: &str, path: &str) -> Vec<(&'static str, String)> {
869 let base = base_url.trim_end_matches('/');
870 self.codes().map(|code| (code, format!("{base}{}", self.in_locale(code).path(path)))).collect()
871 }
872
873 /// The `<link>` elements a localized page's `<head>` needs: `canonical`
874 /// (this locale's URL), one `alternate` per locale with its `hreflang`,
875 /// and `x-default` (the default locale's URL). `base_url` is the app's
876 /// public origin (`APP_URL`, [`ocre::mail::url`](crate::mail::url)),
877 /// `path` the page without its locale prefix. Values are escaped; in
878 /// askama: `{{ i18n.alternate_links(base_url, "/pricing")|safe }}`.
879 ///
880 /// # Examples
881 ///
882 /// ```
883 /// # use std::sync::LazyLock;
884 /// static LOCALES: ocre::i18n::Locales =
885 /// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n"), ("fr", "fr:\n")]));
886 /// assert_eq!(
887 /// LOCALES.locale("fr").alternate_links("https://ex.com", "/"),
888 /// "<link rel=\"canonical\" href=\"https://ex.com/fr\">\n\
889 /// <link rel=\"alternate\" hreflang=\"en\" href=\"https://ex.com/en\">\n\
890 /// <link rel=\"alternate\" hreflang=\"fr\" href=\"https://ex.com/fr\">\n\
891 /// <link rel=\"alternate\" hreflang=\"x-default\" href=\"https://ex.com/en\">"
892 /// );
893 /// ```
894 pub fn alternate_links(&self, base_url: &str, path: &str) -> String {
895 let base = base_url.trim_end_matches('/');
896 let attribute = |text: &str| text.replace('&', "&").replace('"', """).replace('<', "<");
897 let mut links =
898 vec![format!("<link rel=\"canonical\" href=\"{}\">", attribute(&format!("{base}{}", self.path(path))))];
899 let alternates = self.alternates(base, path);
900 for (code, url) in &alternates {
901 links.push(format!(
902 "<link rel=\"alternate\" hreflang=\"{}\" href=\"{}\">",
903 attribute(code),
904 attribute(url)
905 ));
906 }
907 if let Some((_, default)) = alternates.first() {
908 links.push(format!("<link rel=\"alternate\" hreflang=\"x-default\" href=\"{}\">", attribute(default)));
909 }
910 links.join("\n")
911 }
912
913 /// `.title` with the scope `posts.index` is `posts.index.title`.
914 fn resolve<'a>(&self, key: &'a str) -> Cow<'a, str> {
915 match key.strip_prefix('.') {
916 Some(rest) if !self.scope.is_empty() => Cow::Owned(format!("{}.{rest}", self.scope)),
917 Some(rest) => Cow::Borrowed(rest),
918 None => Cow::Borrowed(key),
919 }
920 }
921
922 /// The first of `keys` found in: the locale's file, the built-in
923 /// translations of its language, then (unless `strict`) the default
924 /// locale's file and its built-in translations, then built-in English.
925 fn lookup(&self, keys: &[&str], count: Option<i64>, strict: bool) -> Option<&'static str> {
926 let catalog: &'static Catalog = self.catalog;
927 let own = &catalog.tables[self.index];
928 let default = &catalog.tables[0];
929 let app = |table: &'static Table| keys.iter().find_map(|key| table.get(key, count));
930 let built_in = |code: &str| keys.iter().find_map(|key| builtin::get(code, key, count));
931 app(own)
932 .or_else(|| built_in(own.code))
933 .or_else(|| if strict { None } else { app(default).or_else(|| built_in(default.code)) })
934 .or_else(|| built_in("en"))
935 }
936
937 /// Returns a `Set-Cookie` value remembering this locale for a year.
938 ///
939 /// The cookie is `locale=<code>; Path=/; Max-Age=31536000; SameSite=Lax`;
940 /// later requests without a `{locale}` path segment use it. Send it
941 /// when the visitor picks a language.
942 ///
943 /// # Examples
944 ///
945 /// ```
946 /// use std::sync::LazyLock;
947 /// use axum::{extract::Path, http::header, response::{IntoResponse, Redirect}};
948 ///
949 /// static LOCALES: ocre::i18n::Locales =
950 /// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n"), ("fr", "fr:\n")]));
951 ///
952 /// // POST /locale/{code}
953 /// async fn switch(Path(code): Path<String>) -> impl IntoResponse {
954 /// let cookie = LOCALES.locale(&code).cookie(); // unknown codes give the default
955 /// ([(header::SET_COOKIE, cookie)], Redirect::to("/"))
956 /// }
957 /// # let _ = switch;
958 ///
959 /// assert_eq!(LOCALES.locale("fr").cookie(), "locale=fr; Path=/; Max-Age=31536000; SameSite=Lax");
960 /// ```
961 pub fn cookie(&self) -> String {
962 format!("{LOCALE_COOKIE}={}; Path=/; Max-Age=31536000; SameSite=Lax", self.locale())
963 }
964
965 /// The extractor's logic: the catalog put there by [`layer`], then [`select`](Self::select).
966 fn from_parts(
967 catalog: Option<&'static Catalog>,
968 path: Option<&str>,
969 default_page: bool,
970 headers: &HeaderMap,
971 ) -> Result<Self> {
972 let catalog = catalog.ok_or_else(|| {
973 Error::internal(
974 "the I18n extractor needs the catalog. Fix: add `.layer(ocre::i18n::layer(&LOCALES))` at the end of \
975 routes() in src/lib.rs (`ocre g locale` does it)",
976 )
977 })?;
978 if default_page {
979 return Ok(Self { catalog, index: 0, scope: "" });
980 }
981 Self::select(catalog, path, headers)
982 }
983
984 /// The locale of a request: path segment, cookie, `Accept-Language`, default.
985 fn select(catalog: &'static Catalog, path: Option<&str>, headers: &HeaderMap) -> Result<Self> {
986 if let Some(code) = path {
987 return catalog.find(code).map(|index| Self { catalog, index, scope: "" }).ok_or(Error::NotFound);
988 }
989 Ok(Self { catalog, index: catalog.preferred(headers).unwrap_or(0), scope: "" })
990 }
991}
992
993impl Catalog {
994 /// The visitor's locale from the `locale` cookie, else `Accept-Language`.
995 fn preferred(&self, headers: &HeaderMap) -> Option<usize> {
996 self.cookie_locale(headers).or_else(|| {
997 let accept = headers.get(header::ACCEPT_LANGUAGE)?.to_str().ok()?;
998 self.negotiate(accept)
999 })
1000 }
1001
1002 /// The locale the `locale` cookie names, if it is one of the app's.
1003 fn cookie_locale(&self, headers: &HeaderMap) -> Option<usize> {
1004 headers
1005 .get_all(header::COOKIE)
1006 .iter()
1007 .filter_map(|value| value.to_str().ok())
1008 .flat_map(|value| value.split(';'))
1009 .filter_map(|pair| pair.trim().strip_prefix(LOCALE_COOKIE)?.strip_prefix('='))
1010 .find_map(|code| self.find(code))
1011 }
1012
1013 /// [`locale`](Self::locale) by index, on a `'static` catalog.
1014 fn locale_ref(&'static self, index: usize) -> I18n {
1015 I18n { catalog: self, index, scope: "" }
1016 }
1017}
1018
1019/// Marks a request served by the unprefixed copy of [`localized`] pages: the URL says the default locale.
1020#[derive(Debug, Clone, Copy)]
1021struct DefaultLocalePage;
1022
1023/// Serves `pages` in every locale: `/path` in the default locale, `/<code>/path` in the others.
1024///
1025/// For public pages search engines index in each language (Rails' `scope
1026/// "(:locale)"`), with the catalog declared `unprefixed_default`
1027/// (`ocre::locales!("en", "fr"; unprefixed_default)`): the URL decides the
1028/// language, so each page has one address per locale for `hreflang`
1029/// ([`I18n::alternate_links`]).
1030///
1031/// - `/pricing` is the default locale's page. A visitor whose `locale`
1032/// cookie or `Accept-Language` prefers another locale of the app gets a
1033/// `303 See Other` to it (`/fr/pricing`); crawlers send neither, so they index each
1034/// URL in its own language. Only `GET` and `HEAD` are redirected.
1035/// - `/fr/pricing` is French, and remembers the choice in the `locale`
1036/// cookie, so the visitor's next unprefixed URL leads back to French.
1037/// - `/en/pricing` (the default locale's code) answers `308 Permanent Redirect` to `/pricing`;
1038/// an unknown code (`/xx/pricing`) is a `404`.
1039///
1040/// Pages outside `localized` keep the usual choice (cookie, then
1041/// `Accept-Language`). A language switcher sets the cookie with
1042/// [`I18n::cookie`] and links to [`I18n::path`]. No billed resource is
1043/// used: headers only.
1044///
1045/// # Errors
1046///
1047/// A request answers 500 when [`layer`] is missing or the catalog is not
1048/// declared `unprefixed_default`; the log line names the fix.
1049///
1050/// # Examples
1051///
1052/// ```
1053/// use std::sync::LazyLock;
1054/// use axum::{Router, routing::get};
1055/// use ocre::{Ctx, i18n::{Catalog, I18n, Locales}};
1056///
1057/// static LOCALES: Locales =
1058/// LazyLock::new(|| Catalog::load(&[("en", "en:\n title: Pricing\n"), ("fr", "fr:\n title: Tarifs\n")]).unprefixed_default());
1059///
1060/// async fn pricing(i18n: I18n) -> String {
1061/// i18n.t("title").to_string()
1062/// }
1063///
1064/// fn routes() -> Router<Ctx> {
1065/// let pages = Router::new().route("/pricing", get(pricing));
1066/// Router::new()
1067/// .merge(ocre::i18n::localized(pages)) // /pricing, /fr/pricing
1068/// // ocre:routes
1069/// .layer(ocre::i18n::layer(&LOCALES))
1070/// }
1071/// # let _ = routes;
1072/// ```
1073pub fn localized<S: Clone + Send + Sync + 'static>(pages: Router<S>) -> Router<S> {
1074 let prefixed = Router::new().nest(&format!("/{{{LOCALE_PARAM}}}"), pages.clone().layer(from_fn(prefixed_page)));
1075 pages.layer(from_fn(default_page)).merge(prefixed)
1076}
1077
1078/// The catalog of a request, or the error naming the missing layer or option.
1079fn localized_catalog(request: &Request) -> Result<&'static Catalog> {
1080 let catalog = request.extensions().get::<&'static Catalog>().copied().ok_or_else(|| {
1081 Error::internal(
1082 "localized pages need the catalog. Fix: add `.layer(ocre::i18n::layer(&LOCALES))` at the end of routes() \
1083 in src/lib.rs (`ocre g locale` does it)",
1084 )
1085 })?;
1086 if !catalog.unprefixed_default {
1087 return Err(Error::internal(
1088 "ocre::i18n::localized serves the default locale without a prefix. Fix: declare the locales with \
1089 `ocre::locales!(\"en\", \"fr\"; unprefixed_default)` in src/lib.rs",
1090 ));
1091 }
1092 Ok(catalog)
1093}
1094
1095/// The unprefixed copy: the default locale, or a redirect to the visitor's preferred one.
1096async fn default_page(mut request: Request, next: Next) -> Response {
1097 let catalog = match localized_catalog(&request) {
1098 Ok(catalog) => catalog,
1099 Err(err) => return crate::session::reject(err).into_response(),
1100 };
1101 let read = matches!(*request.method(), Method::GET | Method::HEAD);
1102 if let Some(index) = catalog.preferred(request.headers()).filter(|&index| index != 0 && read) {
1103 let uri = request.uri();
1104 let query = uri.query().map(|query| format!("?{query}")).unwrap_or_default();
1105 return Redirect::to(&format!("{}{query}", catalog.locale_ref(index).path(uri.path()))).into_response();
1106 }
1107 request.extensions_mut().insert(DefaultLocalePage);
1108 next.run(request).await
1109}
1110
1111/// The prefixed copy: `/en/...` to the unprefixed URL, unknown codes to 404, and the choice remembered.
1112async fn prefixed_page(params: RawPathParams, request: Request, next: Next) -> Response {
1113 let catalog = match localized_catalog(&request) {
1114 Ok(catalog) => catalog,
1115 Err(err) => return crate::session::reject(err).into_response(),
1116 };
1117 let code = params.iter().find(|(name, _)| *name == LOCALE_PARAM).map(|(_, code)| code).unwrap_or_default();
1118 let Some(index) = catalog.find(code) else { return crate::session::reject(Error::NotFound).into_response() };
1119 if index == 0 {
1120 // Inside the nested router, the URI is the page's own path, without the locale.
1121 let uri = request.uri();
1122 let query = uri.query().map(|query| format!("?{query}")).unwrap_or_default();
1123 return Redirect::permanent(&format!("{}{query}", uri.path())).into_response();
1124 }
1125 let remembered = catalog.cookie_locale(request.headers()) == Some(index);
1126 let mut response = next.run(request).await;
1127 if !remembered && let Ok(cookie) = HeaderValue::from_str(&catalog.locale_ref(index).cookie()) {
1128 response.headers_mut().append(header::SET_COOKIE, cookie);
1129 }
1130 response
1131}
1132
1133/// Failures render as HTML pages in full-stack apps and as JSON in API-only apps.
1134impl<S: Send + Sync> FromRequestParts<S> for I18n {
1135 type Rejection = crate::session::Rejection;
1136
1137 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
1138 let params = RawPathParams::from_request_parts(parts, state).await.ok();
1139 let path = params.as_ref().and_then(|params| params.iter().find(|(name, _)| *name == LOCALE_PARAM));
1140 Self::from_parts(
1141 parts.extensions.get::<&'static Catalog>().copied(),
1142 path.map(|(_, code)| code),
1143 parts.extensions.get::<DefaultLocalePage>().is_some(),
1144 &parts.headers,
1145 )
1146 .map_err(crate::session::reject)
1147 }
1148}
1149
1150/// A translation being built by [`I18n::t`], displayed (looked up and interpolated) when written.
1151///
1152/// Add `%{name}` values with [`arg`](Self::arg) and the plural count with
1153/// [`count`](Self::count). Displaying it looks the key up in the locale,
1154/// then (release builds only) in the default locale, and replaces each
1155/// `%{name}` with its value; a placeholder without a value stays as written.
1156/// A key missing everywhere, and in debug builds (`ocre dev`, tests) a key
1157/// missing from the locale, displays as `translation missing: fr.posts.title`.
1158/// The text is not escaped here: askama escapes it when it writes it.
1159///
1160/// # Examples
1161///
1162/// ```
1163/// # use std::sync::LazyLock;
1164/// static LOCALES: ocre::i18n::Locales = LazyLock::new(|| {
1165/// ocre::i18n::Catalog::load(&[(
1166/// "en",
1167/// "en:\n inbox:\n zero: \"No messages, %{name}\"\n one: \"One message\"\n other: \"%{count} messages\"\n",
1168/// )])
1169/// });
1170/// let i18n = LOCALES.locale("en");
1171/// assert_eq!(i18n.t("inbox").count(0).arg("name", "Ada").to_string(), "No messages, Ada");
1172/// assert_eq!(i18n.t("inbox").count(1).to_string(), "One message");
1173/// assert_eq!(i18n.t("inbox").count(12).to_string(), "12 messages");
1174/// assert_eq!(i18n.t("nope").to_string(), "translation missing: en.nope");
1175/// ```
1176#[derive(Debug, Clone)]
1177pub struct Translation<'a> {
1178 i18n: I18n,
1179 key: Cow<'a, str>,
1180 alternatives: Vec<Cow<'a, str>>,
1181 default: Option<Cow<'a, str>>,
1182 count: Option<i64>,
1183 args: Vec<(&'a str, String)>,
1184}
1185
1186impl<'a> Translation<'a> {
1187 /// Sets the value for the `%{name}` placeholder.
1188 ///
1189 /// `value` is formatted with [`Display`](fmt::Display) right away.
1190 /// Calling it twice with the same name keeps the first value.
1191 ///
1192 /// # Examples
1193 ///
1194 /// ```
1195 /// # use std::sync::LazyLock;
1196 /// static LOCALES: ocre::i18n::Locales =
1197 /// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n hi: \"Hi %{name}\"\n")]));
1198 /// assert_eq!(LOCALES.locale("en").t("hi").arg("name", "Ada").to_string(), "Hi Ada");
1199 /// ```
1200 pub fn arg(mut self, name: &'a str, value: impl fmt::Display) -> Self {
1201 self.args.push((name, value.to_string()));
1202 self
1203 }
1204
1205 /// Sets the plural count: picks the form for `n` and fills `%{count}`.
1206 ///
1207 /// The form follows the locale's CLDR rule (French: 0 and 1 are `one`;
1208 /// Russian: `one`, `few`, `many`); a `zero` form, when present, wins
1209 /// for 0. A missing form falls back to `other`. An explicit
1210 /// [`arg`](Self::arg)`("count", ..)` overrides the `%{count}` text.
1211 ///
1212 /// # Examples
1213 ///
1214 /// ```
1215 /// # use std::sync::LazyLock;
1216 /// static LOCALES: ocre::i18n::Locales = LazyLock::new(|| {
1217 /// ocre::i18n::Catalog::load(&[("fr", "fr:\n posts:\n one: \"%{count} article\"\n other: \"%{count} articles\"\n")])
1218 /// });
1219 /// assert_eq!(LOCALES.locale("fr").t("posts").count(0).to_string(), "0 article");
1220 /// assert_eq!(LOCALES.locale("fr").t("posts").count(2_usize).to_string(), "2 articles");
1221 /// ```
1222 pub fn count(mut self, n: impl Count) -> Self {
1223 self.count = Some(n.to_count());
1224 self
1225 }
1226
1227 /// Tries another key when this one has no translation (Rails' `default: :"other.key"`).
1228 ///
1229 /// Alternatives are tried in the order given, each like the first key
1230 /// (locale, then default locale in release builds); a leading `.` is
1231 /// relative to the [`scope`](I18n::scope).
1232 ///
1233 /// # Examples
1234 ///
1235 /// ```
1236 /// # use std::sync::LazyLock;
1237 /// static LOCALES: ocre::i18n::Locales =
1238 /// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n actions:\n save: Save\n")]));
1239 /// let i18n = LOCALES.locale("en");
1240 /// assert_eq!(i18n.t("posts.form.save").or_key("actions.save").to_string(), "Save");
1241 /// ```
1242 pub fn or_key(mut self, key: &'a str) -> Self {
1243 self.alternatives.push(self.i18n.resolve(key));
1244 self
1245 }
1246
1247 /// Uses `text` when neither the key nor its alternatives have a translation (Rails' `default: "text"`).
1248 ///
1249 /// It replaces `translation missing: ...` in every build (debug builds
1250 /// included, where a key missing from the locale shows `text` rather
1251 /// than the default locale's translation). `%{name}` placeholders in
1252 /// `text` are filled like in a translation.
1253 ///
1254 /// # Examples
1255 ///
1256 /// ```
1257 /// # use std::sync::LazyLock;
1258 /// static LOCALES: ocre::i18n::Locales = LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n")]));
1259 /// let i18n = LOCALES.locale("en");
1260 /// assert_eq!(i18n.t("posts.empty").or("No posts yet, %{name}").arg("name", "Ada").to_string(), "No posts yet, Ada");
1261 /// ```
1262 pub fn or(mut self, text: impl Into<Cow<'a, str>>) -> Self {
1263 self.default = Some(text.into());
1264 self
1265 }
1266
1267 /// Marks the translation as HTML: its text is written as is, the values of [`arg`](Self::arg) escaped.
1268 ///
1269 /// Rails' `_html` keys: for translations containing markup, such as
1270 /// `terms: "I accept the <a href=\"/terms\">terms</a>, %{name}"`. askama
1271 /// writes the result without escaping it again (feature `html`); the
1272 /// `%{name}` values are escaped, so user input stays text. Use it only
1273 /// for keys whose text you wrote, never for text from users.
1274 ///
1275 /// # Examples
1276 ///
1277 /// ```
1278 /// # use std::sync::LazyLock;
1279 /// static LOCALES: ocre::i18n::Locales = LazyLock::new(|| {
1280 /// ocre::i18n::Catalog::load(&[("en", "en:\n welcome: \"Hello <b>%{name}</b>\"\n")])
1281 /// });
1282 /// let i18n = LOCALES.locale("en");
1283 /// assert_eq!(i18n.t("welcome").arg("name", "<script>").html().to_string(), "Hello <b><script></b>");
1284 /// ```
1285 pub fn html(self) -> HtmlTranslation<'a> {
1286 HtmlTranslation(self)
1287 }
1288
1289 fn write(&self, f: &mut fmt::Formatter<'_>, strict: bool) -> fmt::Result {
1290 self.write_with(f, strict, false)
1291 }
1292
1293 fn write_with(&self, f: &mut fmt::Formatter<'_>, strict: bool, escape: bool) -> fmt::Result {
1294 let mut keys = Vec::with_capacity(1 + self.alternatives.len());
1295 keys.push(self.key.as_ref());
1296 keys.extend(self.alternatives.iter().map(AsRef::as_ref));
1297 let text = match (self.i18n.lookup(&keys, self.count, strict), &self.default) {
1298 (Some(text), _) => text,
1299 (None, Some(default)) => default,
1300 (None, None) => return write!(f, "translation missing: {}.{}", self.i18n.locale(), self.key),
1301 };
1302 interpolate(f, text, &self.args, self.count, escape)
1303 }
1304}
1305
1306/// Writes `text` with each `%{name}` replaced by its value in `args` (or
1307/// `count` for `%{count}`), HTML-escaped when `escape`; a placeholder without
1308/// a value stays as written.
1309fn interpolate(
1310 out: &mut impl fmt::Write,
1311 text: &str,
1312 args: &[(&str, String)],
1313 count: Option<i64>,
1314 escape: bool,
1315) -> fmt::Result {
1316 let mut rest = text;
1317 while let Some(start) = rest.find("%{") {
1318 let Some(len) = rest[start..].find('}') else { break };
1319 out.write_str(&rest[..start])?;
1320 let name = &rest[start + 2..start + len];
1321 match args.iter().find(|(arg, _)| *arg == name) {
1322 Some((_, value)) if escape => write_escaped(out, value)?,
1323 Some((_, value)) => out.write_str(value)?,
1324 None => match count {
1325 Some(count) if name == "count" => write!(out, "{count}")?,
1326 _ => out.write_str(&rest[start..=start + len])?,
1327 },
1328 }
1329 rest = &rest[start + len + 1..];
1330 }
1331 out.write_str(rest)
1332}
1333
1334fn write_escaped(out: &mut impl fmt::Write, text: &str) -> fmt::Result {
1335 let mut done = 0;
1336 for (at, c) in text.char_indices() {
1337 let entity = match c {
1338 '&' => "&",
1339 '<' => "<",
1340 '>' => ">",
1341 '"' => """,
1342 '\'' => "'",
1343 _ => continue,
1344 };
1345 out.write_str(&text[done..at])?;
1346 out.write_str(entity)?;
1347 done = at + 1;
1348 }
1349 out.write_str(&text[done..])
1350}
1351
1352/// A [`Translation`] written as HTML, from [`Translation::html`]: the text as is, every value escaped.
1353///
1354/// askama writes it without escaping (it implements
1355/// `askama::filters::HtmlSafe` with the `html` feature), so
1356/// `{{ i18n.t("terms").arg("name", user.name).html() }}` keeps the
1357/// translation's markup while `user.name` stays text.
1358///
1359/// # Examples
1360///
1361/// ```
1362/// # use std::sync::LazyLock;
1363/// static LOCALES: ocre::i18n::Locales =
1364/// LazyLock::new(|| ocre::i18n::Catalog::load(&[("en", "en:\n note: \"<em>%{text}</em>\"\n")]));
1365/// let html = LOCALES.locale("en").t("note").arg("text", "a & b").html();
1366/// assert_eq!(html.to_string(), "<em>a & b</em>");
1367/// ```
1368#[derive(Debug, Clone)]
1369pub struct HtmlTranslation<'a>(Translation<'a>);
1370
1371impl fmt::Display for HtmlTranslation<'_> {
1372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1373 self.0.write_with(f, cfg!(debug_assertions), true)
1374 }
1375}
1376
1377#[cfg(feature = "html")]
1378impl askama::filters::HtmlSafe for HtmlTranslation<'_> {}
1379
1380/// English `datetime.distance_in_words.<key>` for `count`, as [`helpers`](crate::helpers) writes it.
1381pub(crate) fn english_distance(key: &str, count: i64) -> String {
1382 let text = builtin::get("en", &format!("datetime.distance_in_words.{key}"), Some(count)).unwrap_or(key);
1383 let mut out = String::new();
1384 interpolate(&mut out, text, &[], Some(count), false).expect("writing to a String");
1385 out
1386}
1387
1388/// A number [`Translation::count`] accepts: every integer type, and references to them.
1389///
1390/// References are accepted because askama passes template fields by
1391/// reference. Values outside the `i64` range count as `i64::MAX`.
1392///
1393/// # Examples
1394///
1395/// ```
1396/// use ocre::i18n::Count;
1397/// assert_eq!(3_usize.to_count(), 3);
1398/// assert_eq!((&-2_i32).to_count(), -2);
1399/// assert_eq!(u64::MAX.to_count(), i64::MAX);
1400/// ```
1401pub trait Count {
1402 /// Returns the number as `i64`, or `i64::MAX` when it does not fit.
1403 ///
1404 /// # Examples
1405 ///
1406 /// ```
1407 /// use ocre::i18n::Count;
1408 /// assert_eq!(7_u8.to_count(), 7);
1409 /// ```
1410 fn to_count(&self) -> i64;
1411}
1412
1413macro_rules! count_via_try_from {
1414 ($($ty:ty),*) => {$(
1415 impl Count for $ty {
1416 fn to_count(&self) -> i64 {
1417 i64::try_from(*self).unwrap_or(i64::MAX)
1418 }
1419 }
1420 )*};
1421}
1422
1423count_via_try_from!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
1424
1425impl<T: Count + ?Sized> Count for &T {
1426 fn to_count(&self) -> i64 {
1427 (**self).to_count()
1428 }
1429}
1430
1431/// Debug builds (`ocre dev`) show missing translations instead of falling back.
1432impl fmt::Display for Translation<'_> {
1433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1434 self.write(f, cfg!(debug_assertions))
1435 }
1436}
1437
1438#[cfg(test)]
1439#[path = "../tests/i18n.rs"]
1440mod tests;