# misc/localization (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/misc/localization/

Localization.
- A port of the original misc/localization.js. Gathers automatic language detection, translation tables, {0}{1} placeholder substitution, and fallback in one place.
- Keys can be the source text as is. If a key is not in the table, the source text (the key) is returned as is, so you can translate bit by bit.
- Usage:
  ```text
    Localization::set_table("en", [("Confirm", "OK"), ("{0} points earned", "Got {0} points")]);
    Localization::set_language(&Localization::detect_language(&["ko", "en"], "ko"));
    Localization::text("{0} points earned", &[&120]);
  ```
- Differences from the original:
  The original holds the tables in static fields of the class. The Rust version holds them in thread-local global state. (the engine runs on one thread)
  A table value is one string or a list of strings (LocalizationValue). A JSON table (read with JsonAsset) is put in with set_table_from_json.
  The variadic arguments of text are a list of Display references (&[&dyn Display]).
- Brought into the engine from Exoplanet Miner: matching language tags by dropping trailing parts one by one, and aliases (set_language_aliases),
  right-to-left languages (is_right_to_left, set_right_to_left) and wrapping inserted values in directional isolate characters (isolate_text),
  filling named placeholders (text_named, "{seconds}" style, values joined only by slashes are wrapped once as a whole).
  Layout mirroring (mirror_layout_x, read_layout_text_align, mirrorLayoutX, readLayoutTextAlign of the original LanguagePack).
  On the web detect_language reads navigator.languages as in the original, and on desktop it reads the system's preferred language order with sys-locale.
    (Windows GetUserPreferredUILanguages, Mac CFLocaleCopyPreferredLanguages, Linux LANGUAGE / LC_ALL / LC_MESSAGES / LANG environment variables)

## LocalizationTable (type)

Translation table. (key (source text) → translated value)

```rust
pub type LocalizationTable = HashMap<String, LocalizationValue>
```

## Localization (struct)

Localization. (a set of static functions)
- The state is thread-local global. On first use, the current language and the fallback language are "ko".

Example: Put in a table, pick a language, and translate

```rust
use vanilla::Localization;

Localization::set_table("fr", [("OK", "D'accord"), ("Got {0} points", "{0} points gagnes")]);
Localization::set_language(&Localization::detect_language(&["fr"], "fr"));
assert_eq!(Localization::get_language(), "fr");
assert_eq!(Localization::text("OK", &[]), "D'accord");
assert_eq!(Localization::text("Got {0} points", &[&120]), "120 points gagnes");
assert_eq!(Localization::text("Not translated yet", &[]), "Not translated yet");
```

- `pub fn detect_language(supported_language_codes: &[&str], default_language_code: &str) -> String` (static, since 0.3.2): Detects the user language. (the first language in preferred order that is in the supported list, otherwise the default language)
  - Regional forms like "zh-TW" are matched in the order "zh-tw" → "zh".
  - Preferred languages are navigator.languages on the web, and the system preferred language order on desktop.
  - `supported_language_codes` &[&str]: List of language codes the game supports. (case insensitive)
  - `default_language_code` &str: Language code to use when nothing matches.
  - returns String: The matched language code. (lowercase) default_language_code as is if none.
- `pub fn select_language(candidate_list: &[String], supported_language_codes: &[&str], default_language_code: &str) -> String` (static, since 0.3.2): Picks the first supported language from a preferred language list. (the matching part of detect_language)
  - Drops trailing parts of the tag one by one and checks the codes and aliases of the supported list. ("zh-Hant-TW" → "zh-hant-tw", "zh-hant", "zh", underscores become hyphens)
  - `candidate_list` &[String]: List of preferred language tags. (earlier first)
  - `supported_language_codes` &[&str]: List of supported language codes. (case insensitive)
  - `default_language_code` &str: Language code to use when nothing matches.
  - returns String: The first matched supported language code. (lowercase, the alias's language if matched by an alias) default_language_code as is if none.

  Example: Match by shortening regional tags

  ```rust
  use vanilla::Localization;
  
  let candidate_list = vec![String::from("zh-TW"), String::from("en-US")];
  assert_eq!(Localization::select_language(&candidate_list, &["ko", "zh-tw", "en"], "ko"), "zh-tw");
  assert_eq!(Localization::select_language(&candidate_list, &["ko", "en"], "ko"), "en");
  assert_eq!(Localization::select_language(&candidate_list, &["ko"], "ko"), "ko");
  ```

- `pub fn set_language_aliases(language_code: &str, alias_list: &[&str])` (static, since 0.4.0): Sets aliases for a language. (e.g. "zh-tw", "zh-hk" for "zh-hant", aliases are treated as that language when matching tags)
  - `language_code` &str: Language code the aliases point to. (stored lowercased)
  - `alias_list` &[&str]: List of aliases. (stored lowercased with underscores turned into hyphens. An existing identical alias is replaced)

  Example: Taiwan and Hong Kong tags to Traditional Chinese

  ```rust
  use vanilla::Localization;
  
  Localization::set_language_aliases("zh-hant", &["zh-tw", "zh_HK"]);
  assert_eq!(Localization::select_language(&[String::from("zh_HK")], &["en", "zh-hant"], "en"), "zh-hant");
  ```

- `pub fn set_right_to_left(language_code: &str, is_right_to_left: bool)` (static, since 0.4.0): Marks or unmarks a language as right-to-left. (initially ar, fa, he, ur, ps, yi, dv)
  - `language_code` &str: Language code. (only the first part is used, "ar-EG" is "ar")
  - `is_right_to_left` bool: Adds if true, removes if false.
- `pub fn is_right_to_left() -> bool` (static, since 0.4.0): Whether the current language is written right to left. (when baking text in that direction and mirroring the layout left to right)
  - Like set_right_to_left, looks at the first segment read in lowercase with underscores as hyphens. ("ar_EG" is also ar)
  - returns bool: true if the first part of the current language code is in the right-to-left language list.
- `pub fn mirror_layout_x(x: f64, width: f64, parent_width: f64) -> f64` (static, since 0.4.0): Horizontal layout position. (the left position mirrored within the parent width for right-to-left languages, otherwise unchanged)
  - Used to mirror the left and right placement of windows and tables to match the language direction. Do not call it for things that should not be mirrored, like screen corner positions or slider directions.
  - `x` f64: Left position for left-to-right languages. (pixels, relative to the parent's left)
  - `width` f64: Width of the thing being placed. (pixels)
  - `parent_width` f64: Parent width. (pixels)
  - returns f64: parent_width - x - width for right-to-left languages, otherwise x.

  Example: Mirrors left and right in Arabic

  ```rust
  use vanilla::{Localization, TextAlign};
  
  Localization::set_language("en");
  assert_eq!(Localization::mirror_layout_x(10.0, 20.0, 100.0), 10.0);
  Localization::set_language("ar");
  assert_eq!(Localization::mirror_layout_x(10.0, 20.0, 100.0), 70.0);
  assert_eq!(Localization::read_layout_text_align(TextAlign::Left), TextAlign::Right);
  ```

- `pub fn read_layout_text_align(text_align: TextAlign) -> TextAlign` (static, since 0.4.0): Text alignment of the layout. (swaps Left and Right for right-to-left languages, others unchanged)
  - `text_align` TextAlign: Alignment for left-to-right languages.
  - returns TextAlign: Alignment matching the current language direction.
- `pub fn isolate_text(text: &str) -> String` (static, since 0.4.0): Wraps a value inserted into text. (wraps it in directional isolate characters for right-to-left languages, otherwise unchanged)
  - Keeps numbers and units (123°/s, +60%) or people's names in one piece in their own direction instead of scattering among the surrounding text.
  - `text` &str: Text of the value to insert.
  - returns String: Text wrapped in U+2068 and U+2069 for right-to-left languages. Unchanged otherwise or if empty.

  Example: Wraps only in Arabic

  ```rust
  use vanilla::Localization;
  
  Localization::set_language("en");
  assert_eq!(Localization::isolate_text("+60%"), "+60%");
  Localization::set_language("ar");
  assert_eq!(Localization::isolate_text("+60%"), "\u{2068}+60%\u{2069}");
  ```

- `pub fn text_named(key: &str, values: &[(&str, &dyn Display)]) -> String` (static, since 0.4.0): Fills named placeholders. ("Restart {seconds}" + [("seconds", &3)] → "Restart 3")
  - For right-to-left languages, wraps inserted values in directional isolate characters.
  - Values joined only by slashes ("{count}/{limit}") are wrapped once as a whole, not per value. (wrapping per value shows 1/40 as 40/1)
  - Placeholders with no matching name are left as is.
  - Like text, the key is looked up in the current language, the fallback language, then the key source text. Names may only contain letters and digits.
  - `key` &str: Translation key. (source text)
  - `values` &[(&str, &dyn Display)]: List of (name, value). If a name appears more than once, the first is used.
  - returns String: Translated text with named placeholders filled.

  Example: Fill named placeholders

  ```rust
  use vanilla::Localization;
  
  Localization::set_language("en");
  Localization::set_table("en", [("restart", "Restart {seconds}"), ("count", "{count}/{limit} workers")]);
  assert_eq!(Localization::text_named("restart", &[("seconds", &3)]), "Restart 3");
  assert_eq!(Localization::text_named("count", &[("count", &1), ("limit", &40)]), "1/40 workers");
  assert_eq!(Localization::text_named("{who} and {other}", &[("who", &"Ann")]), "Ann and {other}");
  ```

- `pub fn set_table<K, V>(language_code: &str, table: impl IntoIterator<Item = (K, V)>) where K: Into<String>, V: Into<LocalizationValue>,` (static, since 0.3.2): Sets a translation table. (the language code is stored lowercased. An existing table for the same language is replaced)
  - `language_code` &str: Language code.
  - `table` impl IntoIterator<Item = (K, V)>: List of (key, value). Keys convertible to String, values convertible to a string or a list of strings (LocalizationValue).

  Example: Put in strings and string lists together

  ```rust
  use vanilla::{Localization, LocalizationValue};
  
  Localization::set_table("en", [
  	("title", LocalizationValue::from("Mine")),
  	("intro", LocalizationValue::from(vec!["First line", "Second line"])),
  ]);
  Localization::set_language("en");
  assert_eq!(Localization::text("title", &[]), "Mine");
  assert_eq!(Localization::text_list("intro"), vec!["First line", "Second line"]);
  ```

- `pub fn set_table_from_json(language_code: &str, table_json: &serde_json::Value)` (static, since 0.3.2): Sets a translation table from a JSON object. (string values become strings, string arrays become lists. Other values are skipped)
  - Non-string values inside arrays are dropped. If it is not an object, the table is empty.
  - `language_code` &str: Language code.
  - `table_json` &serde_json::Value: A JSON object of the form { key: string or string array }.

  Example: Put in a table from a JSON object

  ```rust
  use vanilla::Localization;
  
  Localization::set_table_from_json("fr", &serde_json::json!({ "OK": "D'accord", "lines": ["a", "b"], "number": 3 }));
  Localization::set_language("fr");
  assert_eq!(Localization::text("OK", &[]), "D'accord");
  assert_eq!(Localization::text_list("lines"), vec!["a", "b"]);
  assert_eq!(Localization::text("number", &[]), "number");
  ```

- `pub fn set_language(language_code: &str)` (static, since 0.3.2): Sets the current language. (lowercased)
  - `language_code` &str: Language code. (must equal a table's language code to use that table)
- `pub fn get_language() -> String` (static, since 0.3.2): Returns the current language.
  - returns String: The current language code. (lowercase, "ko" at first)
- `pub fn set_fallback_language(language_code: &str)` (static, since 0.3.2): Sets the fallback language. (this language's table is checked when the current language's table lacks the key)
  - `language_code` &str: Fallback language code. (stored lowercased, initially "ko")
- `pub fn text(key: &str, substitutions: &[&dyn Display]) -> String` (static, since 0.3.2): Looks up a translation. (in order: current language → fallback language → key source text, replacing {0} {1} ... with the arguments)
  - If the value is a list, the key is used, as in the original.
  - `key` &str: Translation key. (source text)
  - `substitutions` &[&dyn Display]: List of values to put into {0}, {1} ... in order. (turned into text with Display)
  - returns String: Translated text with placeholders replaced. If not in the table, the key source text with placeholders replaced.

  Example: Translation with the placeholder order swapped

  ```rust
  use vanilla::Localization;
  
  Localization::set_table("en", [("{0}/{1}", "{1} of {0}")]);
  Localization::set_language("en");
  assert_eq!(Localization::text("{0}/{1}", &[&3, &"ten"]), "ten of 3");
  assert_eq!(Localization::text("Missing {0}", &[&1.5]), "Missing 1.5");
  ```

- `pub fn text_list(key: &str) -> Vec<String>` (static, since 0.3.2): Looks up a list translation. (an entry with several lines, like a dialogue list. A single string gives a one-line list, none gives `[key]`)
  - `key` &str: Translation key.
  - returns Vec<String>: The found list of strings. Placeholders are not replaced.
- `pub fn lookup(key: &str) -> Option<LocalizationValue>` (static, since 0.3.2): Looks up the raw value. (current language → fallback language, None if none)
  - `key` &str: Translation key.
  - returns Option<LocalizationValue>: A copy of the found value. None if in neither table.
- `pub fn clear()` (static, since 0.3.2): Clears all tables. (for tests, the language settings stay)

## LocalizationValue (enum) (Clone, Debug, PartialEq, Eq, From<&str>, From<String>, From<Vec<String>>, From<Vec<&str>>)

Translation value. (a value of the original table: a string or an array of strings)

- `Text` = `Text(String)`: One string. (read with text)
- `TextList` = `TextList(Vec<String>)`: List of strings. (an entry with several lines, like dialogue, read with text_list)
