Skip to content

Multilingual

The Multilingual module provides capabilities for system locale detection, locking, and runtime language pack management. It serves as the underlying logic support that enables @techui/locales to function automatically.

Import Method

javascript
import { initLang, lockLang, tLang } from "@techui/utils";

Initialization and Locking

initLang(val)

Initializes or retrieves the current system language.

  • Automatic Mode (when val is empty): Priority is given to checking if a language is already locked in session storage. If not locked, it automatically detects the browser environment via the Intl API or navigator.language and normalizes it into standard codes such as cn (Simplified Chinese), hk (Traditional Chinese/Hong Kong), or en (English).
  • Manual Mode (when val has a value): Forcefully sets and locks the current language, which is equivalent to calling lockLang(val).
javascript
// Automatic detection and initialization
const browserLang = initLang(); 

// Force initialization to English
initLang('en');

lockLang(lang)

Locks the language preference.

This writes the target language code into SessionStorage and marks sysLangLock as true. This ensures that the user's selection maintains the highest priority even if the page is refreshed or the browser's language settings change.

javascript
// Called when a user clicks to switch languages
lockLang('jp');

Resource Management

tLang is a singleton instance of the I18nManager class, responsible for temporarily storing and managing currently loaded language data in memory.

tLang.register(config)

Registers a language pack. This is typically called automatically by various language pack files in @techui/locales when they are imported.

  • config: A configuration object containing value (language identifier) and data (translation data).
javascript
tLang.register({
  value: 'cn',
  data: { 
    welcome: 'Welcome',
    start: 'Start'
  }
});

tLang.getData()

Retrieves the language translation data object currently registered in memory.

javascript
const messages = tLang.getData();
console.log(messages.welcome); // "Welcome"

tLang.getValue()

Retrieves the currently registered language code identifier (e.g., cn, en).

javascript
const currentCode = tLang.getValue();

tLang.hasLang()

Checks whether valid language data already exists in memory. This is commonly used to determine if a network request is needed to dynamically load a language pack.

javascript
if (!tLang.hasLang()) {
  // Execute dynamic loading logic...
}

Released under the MIT License.