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
import { initLang, lockLang, tLang } from "@techui/utils";Initialization and Locking
initLang(val)
Initializes or retrieves the current system language.
- Automatic Mode (when
valis 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 theIntlAPI ornavigator.languageand normalizes it into standard codes such ascn(Simplified Chinese),hk(Traditional Chinese/Hong Kong), oren(English). - Manual Mode (when
valhas a value): Forcefully sets and locks the current language, which is equivalent to callinglockLang(val).
// 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.
// 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) anddata(translation data).
tLang.register({
value: 'cn',
data: {
welcome: 'Welcome',
start: 'Start'
}
});tLang.getData()
Retrieves the language translation data object currently registered in memory.
const messages = tLang.getData();
console.log(messages.welcome); // "Welcome"tLang.getValue()
Retrieves the currently registered language code identifier (e.g., cn, en).
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.
if (!tLang.hasLang()) {
// Execute dynamic loading logic...
}