# misc/languagepack (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/misc/languagepack/

Language pack. (screen text languages kept as asset tables, imported as LanguagePack)
- Unlike Localization (tables in code), keeps text in asset JSON files. Used for games with many languages where translators edit the files separately.
- Paths are set with setLanguagePaths. (initially ./assets/localization/languages.json and its folder)
- What to do after a language is loaded (fetching that language's font, etc.) is hooked with setLanguageLoadedHandler.

Text lives in asset tables, not in source. The language list is languages.json,
and each language has one file (key → text). Every language file has the same keys as the default language file.
If the setting's language is empty, it follows the language the platform reported, then the device (browser) language, and if that is not in the list, the default language (English).
Keys missing from the chosen language's table use the default language's text, and if missing there too, the key itself.
Paths are written as literal strings so the build's cache busting attaches fingerprints. (the build attaches the language file fingerprints to the list)

Example: Set the list and tables without files and get text

```js
import { LanguagePack } from "./build/vanilla.js";

LanguagePack.setLanguageList({
	fallbackLanguage: "en",
	languages: [
		{ code: "en", name: "English", englishName: "English", direction: "ltr", aliases: [], file: "en.json" },
		{ code: "ar", name: "Arabic", englishName: "Arabic", direction: "rtl", aliases: ["ar-eg"], file: "ar.json" }
	]
});
const englishTexts = { "hud.restart": "Restart {seconds}", "hud.ammo": "{count}/{limit}" };
LanguagePack.setLanguageTexts("en", englishTexts, englishTexts);
console.log(LanguagePack.readLanguageCode(), LanguagePack.translate("hud.restart"), LanguagePack.formatText("hud.restart", { seconds: 3 }));
const matchedLanguage = LanguagePack.matchLanguageTag("ar-EG");
console.log(matchedLanguage.code, LanguagePack.readTextDirection(), LanguagePack.resolveLanguageCode("ar"));
```

## Functions and constants

- `async loadLanguageList()` (method, since 0.4.0): Loads the language list. (once only)
- `readLanguages()` (method, since 0.4.0): Returns the language list. (empty array if it could not be read)
  - returns object[]: Array of rows of the language list. (empty if not loaded)
- `findLanguage(languageCode)` (method, since 0.4.0): Finds a language. (code is case-insensitive, null if none)
  - `languageCode` string: Language code to look for.
  - returns object | null: That language's row in the list. null if missing.
- `matchLanguageTag(languageTag)` (method, since 0.4.0): Language matching a language tag. ("pt-BR" → pt, "zh-Hant-TW" → zh-Hant, strips trailing subtags one by one and checks codes and aliases, null if none)
  - `languageTag` string: Language tag. (in a form like "pt-BR", underscores accepted)
  - returns object | null: The matching language row. null if none.
- `setPreferredLanguageTag(languageTag)` (method, since 0.4.0): Sets the preferred language tag. (the user's language reported by the platform, checked before the device language, "" if none)
  - `languageTag` string: Language tag to prefer. ("" if not a string)
- `resolveDeviceLanguageCode()` (method, since 0.4.0): Device (browser) language. (the first language in the list in the device's preference order, default language if none)
  - returns string: The chosen language code. (the default language code if none matches)
- `readFallbackLanguageCode()` (method, since 0.4.0): Default language code.
  - returns string: The default language code. ("en" if there is no list or it is not set)
- `resolveLanguageCode(settingLanguageCode)` (method, since 0.4.0): Language setting → code of the language to use. (device language if empty or not in the list)
  - `settingLanguageCode` string: Language code saved in the settings. (the device language if empty or not in the list)
  - returns string: Language code to use.
- `async loadLanguage(languageCode)` (method, since 0.4.0): Loads a language. (that language's table and the default language's table, default language if the code is not in the list)
  - `languageCode` string: Language code to load. (the default language if not in the list)
- `async applyLanguageSetting(settingLanguageCode)` (method, since 0.4.0): Applies the language setting. (decides the language to use, loads its table, and calls the function registered with setLanguageLoadedHandler)
  - `settingLanguageCode` string: "" means the device language.
- `readLanguage()` (method, since 0.4.0): Current language. (a row of the list, null if none yet)
  - returns object | null: The current language row. null if none yet.
- `readLanguageCode()` (method, since 0.4.0): Current language code. (default language if none yet)
  - returns string: The current language code. The default language code if none yet.
- `readTextDirection()` (method, since 0.4.0): Text direction of the current language. ("ltr" or "rtl", direction in the language list, "ltr" if none yet)
  
  For right-to-left languages (Arabic, Persian, Hebrew, etc.), on-screen text is baked in that direction and the layout is mirrored horizontally.
  - returns string: "ltr" or "rtl".
- `isRightToLeft()` (method, since 0.4.0): Whether the current language is written right to left. (true if readTextDirection is "rtl")
  - returns boolean: True if written right to left.
- `mirrorLayoutX(x, width, parentWidth)` (method, since 0.4.0): Horizontal layout position. (for right-to-left languages, the left edge mirrored within the parent width, otherwise unchanged)
  
  Used to mirror the left and right placement of windows and tables to match the language direction. Not called for things that should not be mirrored, such as screen-corner positions or slider direction.
  - `x` number: Left for a left-to-right language.
  - `width` number: Width of the thing being placed.
  - `parentWidth` number: Width of the parent.
  - returns number: Left position matched to the current language direction.
- `readLayoutTextAlign(textAlign)` (method, since 0.4.0): Layout text alignment. (for right-to-left languages, swaps "left" and "right", others unchanged)
  - `textAlign` string: "left", "center", "right", "start", "end"
  - returns string: Alignment value matched to the current language direction.
- `isolateText(text)` (method, since 0.4.0): Wraps a value inserted into text. (for right-to-left languages, wraps it with the directional isolate characters FSI ... PDI, otherwise unchanged)
  
  So that numbers and units (e.g. 123°/s, +60%, 88 / 1.5s) or person names inside right-to-left text do not get mixed with and scattered among the surrounding text,
  a wrapped value is laid out as one block in its own direction (the first strong directional character, left to right if digits only).
  - `text` string: Text of the value to wrap.
  - returns string: Text wrapped in directional isolate characters for right-to-left languages, otherwise unchanged. (empty text is unchanged)
- `translate(key)` (method, since 0.4.0): Text for a key. (current language → default language → the key itself)
  - `key` string: Key of the text.
  - returns string: Text in the current language. The default language text if missing, or the key itself if missing there too.
- `formatText(key, values)` (method, since 0.4.0): Inserts values into a key's text. ("Restart {seconds}" + { seconds: 3 } → "Restart 3")
  
  For right-to-left languages, inserted values are wrapped with directional isolate characters. (isolateText)
  Values joined only by slashes ("{count}/{limit}") are wrapped once as a whole, not per value. Wrapping each value lays the two blocks out from the right, so 1/40 shows as 40/1.
  - `key` string: Key of the text.
  - `values` object: Placeholder name → value.
  - returns string: Text with placeholders filled.
- `readAllTexts()` (method, since 0.4.0): All text of the current language. (used to prefetch font subsets)
  - returns string: All texts of the current language table joined together.
- `setLanguageList(data)` (method, since 0.4.0): Sets the language list. (For giving it directly without a file, same shape as languages.json, true if set)
  - The file read by loadLanguageList also goes through here. Rows whose code is not a string are dropped, missing aliases and countries become empty arrays, and their strings are lowercased.
  - `data` object: { fallbackLanguage, languages: [...] }
  - returns boolean: True if the list was set. (false if there is no languages array)

  Example: Accept rows without aliases

  ```js
  import { LanguagePack } from "./build/vanilla.js";
  
  const isLanguageListSet = LanguagePack.setLanguageList({
  	fallbackLanguage: "en",
  	languages: [
  		{ code: "en", name: "English", file: "en.json" },
  		{ code: "pt", name: "Portugues", aliases: ["PT-BR"], file: "pt.json" }
  	]
  });
  const englishLanguage = LanguagePack.matchLanguageTag("en-US");
  const portugueseLanguage = LanguagePack.matchLanguageTag("pt_BR");
  console.log(isLanguageListSet, englishLanguage.code, englishLanguage.aliases.length, portugueseLanguage.code);
  ```

- `setLanguageTexts(languageCode, texts, fallbackTextTable)` (method, since 0.4.0): Sets the current language's table. (when given directly without a file, together with the default language table. false if the language is not in the list)
  - `languageCode` string: Code to set as the current language. (must be in the list)
  - `texts` object: Key → text.
  - `fallbackTextTable` object: Default language key → text.
  - returns boolean: True if set. False if the language is not in the list.
- `setLanguagePaths(listPath, directoryPath)` (method, since 0.4.0): Sets the paths. (language list file, folder containing the language files, call before loading)
  - `listPath` string: Path of the language list file (languages.json).
  - `directoryPath` string: Ends with "/".
- `setDocumentTitleKey(titleKey)` (method, since 0.4.0): Sets the key of the text used as the tab title. ("" leaves the tab title unchanged)
  - `titleKey` string: Key of the text that becomes the tab title. (the tab title is not changed if "")
- `setLanguageLoadedHandler(handler)` (method, since 0.4.0): Sets the function to call after a language is loaded. (called by applyLanguageSetting, e.g. to fetch that language's font, null for none)
  - `handler` function(object, string): Promise<void> | void | null: (a row of the language, all text)
