日本語

Writing a text

A text is a struct literal with one field per language, so a missing translation is a compile error.

A text is a struct literal

ByLang { en: "Settings", ja: "設定" }   // ByLang<&str>
lang.pick(text)                            // &str

A text is a value of the Text<T> of Locale, here the ByLang of Declare the languages, and Locale::pick returns the translation for one language. Rust requires a struct literal to give every field, so a text without its Japanese fails to compile with E0063:

// `Lang` and `ByLang` are the ones the Overview declares.
// error[E0063]: missing field `ja` in initializer of `ByLang<_>`
let title = ByLang { en: "Settings" };

What pick returns goes wherever text goes: El::text, Page::new, format!. Text set with El::text is escaped like any other, so a < in a translation appears on the page as the character <.

Adding a language

To add French, add the variant Fr to Lang and the field fr to ByLang. Then the match in pick fails with E0004 until it has the arm for Fr, and every text fails with E0063 until it has its fr field. cargo build lists each text that still needs a translation:

use hypersig::Segment;
use hypersig_i18n::Locale;
use serde::{Deserialize, Serialize};

#[derive(Segment, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
#[serde(rename_all = "lowercase")]
enum Lang {
    En,
    Ja,
    Fr, // added
}

struct ByLang<T> {
    en: T,
    ja: T,
    fr: T, // added
}

impl Locale for Lang {
    type Text<T> = ByLang<T>;

    fn pick<T>(self, text: ByLang<T>) -> T {
        // error[E0004]: non-exhaustive patterns: `Lang::Fr` not covered
        match self {
            Self::En => text.en,
            Self::Ja => text.ja,
        }
    }
}

// error[E0063]: missing field `fr` in initializer of `ByLang<_>`
const SETTINGS: ByLang<&str> = ByLang { en: "Settings", ja: "設定" };

Adding the field to ByLang is what makes every text fail. A variant added to Lang without the field fails only in pick, where there is no field to return.

Where texts live

A text used in one place is written where it is used, inside the function that renders it. A text shared by several pages is a const, which can sit in a module of its own. pick takes the text by value, and each use of a const is a new value, so one constant can be picked any number of times. A static cannot be passed by value, so texts are consts, not statics:

// `Lang` and `ByLang` are the ones the Overview declares.
// Texts shared by several pages, as constants.
const SAVE: ByLang<&str> = ByLang { en: "Save", ja: "保存" };
const CANCEL: ByLang<&str> = ByLang { en: "Cancel", ja: "キャンセル" };

// A text used in one place, written where it is used.
fn heading(lang: Lang) -> &'static str {
    lang.pick(ByLang { en: "Settings", ja: "設定" })
}

// Each use of a constant is a new value, so `pick` can take it by value again.
assert_eq!(Lang::Ja.pick(SAVE), "保存");
assert_eq!(Lang::En.pick(SAVE), "Save");
assert_eq!(Lang::Ja.pick(CANCEL), "キャンセル");
assert_eq!(heading(Lang::Ja), "設定");

A text in a let binding is moved by the first pick, and a second pick of it is E0382. Write it as a const, or derive Clone and Copy on ByLang.

Texts that are not strings

Text<T> takes any T, so a value that differs per language is written the same way: a SafeUrl to the documentation in each language, a NumberFormat, or an element. A sentence with a link inside is an element per language, because the link sits at a different place in each:

// `Lang` and `ByLang` are the ones the Overview declares.
use hypersig::html::{El, a, p};
use hypersig::{Page, SafeUrl, Signals};

#[derive(Signals, Serialize, Deserialize)]
struct Help {}

// A URL per language.
const GUIDE: ByLang<SafeUrl> = ByLang {
    en: SafeUrl::new("https://example.com/en/guide"),
    ja: SafeUrl::new("https://example.com/ja/guide"),
};

// A sentence with a link inside, whose position differs between the languages.
fn read_the_guide(lang: Lang) -> El<Help> {
    let link = || a().href(lang.pick(GUIDE));
    lang.pick(ByLang {
        en: p().text("Read ").child(link().text("the guide")).text(" first."),
        ja: p().text("まず").child(link().text("ガイド")).text("を読んでください。"),
    })
}

let html = Page::new("Help", Help {}).child(read_the_guide(Lang::Ja)).render();

For Lang::Ja, the page's body holds:

<p>まず<a href="https://example.com/ja/guide">ガイド</a>を読んでください。</p>

A struct literal evaluates every field, so both elements are built and pick drops the English one. That costs little for a short element. Where building a translation is expensive, make each field a function, as Texts with values does, so only the chosen one runs.

What stays unchecked

  • The content of a translation. A Japanese field that holds English, an empty string, or a translation that says something else compiles, and the page shows it as written.
  • Text outside a ByLang. A string literal passed straight to El::text compiles and is shown in every language.
  • The T of a text is the same in every language, so each translation has the same type, but not the same length or shape: a German label longer than its English one can overflow a button.

Example

A page whose title and paragraph are texts, from A page in two languages:

// `Lang` and `ByLang` are the ones declared above.
use axum::Router;
use hypersig::html::{h1, p};
use hypersig::{Page, Route, RouterExt, Signals};
use hypersig_i18n::LocaleRouterExt;

#[derive(Signals, Serialize, Deserialize)]
struct Home {}

hypersig::routes! {
    fn pages(Router<()>);
    // `/en` and `/ja`. Any other first segment answers 404.
    const HOME: Route<Lang> = "/{lang}" => home;
}

async fn home((): (), lang: Lang) -> Page<Home> {
    Page::new(lang.pick(ByLang { en: "Welcome", ja: "ようこそ" }), Home {})
        .lang(lang.tag())
        .child(h1().text(lang.pick(ByLang { en: "Welcome", ja: "ようこそ" })))
        .child(p().text(lang.pick(ByLang { en: "Hello.", ja: "こんにちは。" })))
}

// `GET /` redirects to `/en` or `/ja` by the `Accept-Language` header.
let app: Router = pages(Router::new())
    .redirect_to_locale(HOME)
    .hypersig_runtime();

Next, Texts with values covers a text that puts a number or a name inside it.