@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
54 lines (53 loc) • 2.08 kB
TypeScript
import type { StringMap } from '../../types.js';
export type MissingTranslationHandler = (key: string, params?: StringMap<any>) => string;
export declare const defaultMissingTranslationHandler: MissingTranslationHandler;
export interface TranslationServiceCfg {
defaultLocale: string;
supportedLocales: string[];
/**
* It is allowed to set it later. Will default to `defaultLocale` in that case.
*/
currentLocale?: string;
translationLoader: TranslationLoader;
/**
* Defaults to `defaultMissingTranslationHandler` that returns `[${key}]` and emits console warning.
*/
missingTranslationHandler?: MissingTranslationHandler;
}
export interface TranslationServiceCfgComplete extends TranslationServiceCfg {
missingTranslationHandler: MissingTranslationHandler;
}
export interface TranslationLoader {
load: (locale: string) => Promise<StringMap>;
}
export declare class TranslationService {
constructor(cfg: TranslationServiceCfg, preloadedLocales?: StringMap<StringMap>);
cfg: TranslationServiceCfgComplete;
/**
* Cache of loaded locales
*/
locales: StringMap<StringMap>;
currentLocale: string;
/**
* Manually set locale data, bypassing the TranslationLoader.
*/
setLocale(localeName: string, locale: StringMap): void;
getLocale(locale: string): StringMap | undefined;
/**
* Loads locale(s) (if not already cached) via configured TranslationLoader.
* Resolves promise when done (ready to be used).
*/
loadLocale(locale: string | string[]): Promise<void>;
/**
* Will invoke `missingTranslationHandler` on missing tranlation.
*
* Does NOT do any locale loading. The locale needs to be loaded beforehand:
* either pre-loaded and passed to the constructor,
* or `await loadLocale(locale)`.
*/
translate(key: string, params?: StringMap): string;
/**
* Does NOT invoke `missingTranslationHandler`, returns `undefined` instead.
*/
translateIfExists(key: string, _params?: StringMap): string | undefined;
}