Skip to content

Localizer

hhh edited this page Dec 20, 2022 · 3 revisions

Localizer

/**
 * Type of options for {@link Localizer}.
 * (One of `defaultLanguage` and `language`
 * must be provided; if both are present,
 * `language` takes precedence.)
 */
interface LocalizerOptions<DictType extends Dict = Dict, DictNameType extends DictName = DictName> {
    dicts: Record<DictNameType, DictType>;
    defaultLanguage?: DictNameType;
    language?: Ref<DictNameType>;
}

/**
 * Class of localizers.
 */
class Localizer<DictType extends Dict = Dict, DictNameType extends DictName = DictName> {

    /**
     * Constructor of {@link Localizer}.
     */
    constructor(options: LocalizerOptions<DictType, DictNameType>);

    /**
     * The ref that stores current language.
     * (You can modify the value of this ref
     * to select the dictionary to use.)
     *
     * @example
     * ```vue
     * <select v-model="language">
     *     <!-- options here... -->
     * </select>
     * ```
     */
    readonly language: Ref<DictNameType>;

    /**
     * Current dictionary.
     * (You should define translated texts in `dicts`
     * and use `dict` to access them responsively.)
     *
     * @example
     * ```vue
     * <h1>{{ dict.TITLE }}</h1>
     * <p>{{ dict.DESCRIPTION }}</p>
     * ```
     */
    readonly dict: ComputedRef<DictType>;

    /**
     * Defined dictionaries.
     *
     * @example
     * ```js
     * localizer.dicts = {
     *     'en-US': {
     *         HELLO: 'Hello!',
     *     },
     *     'zh-CN': {
     *         HELLO: '你好!',
     *     },
     * };
     * ```
     */
    dicts: Record<DictNameType, DictType>;

    /**
     * Default language to use.
     */
    defaultLanguage: DictNameType;
}
Clone this wiki locally