All files / src/i18n i18n.ts

100% Statements 21/21
100% Branches 1/1
100% Functions 5/5
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 8024x 24x 24x   24x       24x 24x             9x               3x 3x           24x             90x             90x 90x               4x 4x 4x       4x 9x 9x   2x                       4x      
import i18next, { InitOptions } from 'i18next';
import merge from 'lodash.merge';
import { Config } from '../config';
import { IDictionary } from '../utils';
import { Messages } from './messages';
/**
 * Class to manipulate the i18next library
 */
export class I18n {
	private static listeners: ((...args: any) => any)[] = [];
 
	/**
	 * Register listener
	 * @param handler
	 */
	public static registerChangeListener(handler: (...args: any) => any) {
		I18n.listeners.push(handler);
	}
 
	/**
	 * Remove a listener
	 * @param handler
	 */
	public static unregisterChangeListener(handler: (...args: any) => any) {
		const index = I18n.listeners.indexOf(handler);
		I18n.listeners.splice(index, 1);
	}
 
	/**
	 * i18next instance
	 */
	public static instance = i18next;
 
	/**
	 * Initiates i18next
	 * @param options
	 */
	public static init(options?: InitOptions) {
		const defaultOptions: InitOptions = {
			lng: window.navigator.language,
			fallbackLng: Config.language,
			resources: Messages.get(),
			keySeparator: '::',
			nsSeparator: ':::',
		};
		const i18nOptions = merge(defaultOptions, options);
		i18next.init(i18nOptions);
	}
 
	/**
	 * Change the i18next language
	 * @param lang
	 */
	public static changeLanguage(lang: string) {
		i18next.changeLanguage(lang);
		try {
			document.documentElement.setAttribute('lang', lang);
		} catch {
			// do nothing
		}
		for (const listener of I18n.listeners) {
			try {
				listener();
			} catch {
				I18n.unregisterChangeListener(listener);
			}
		}
	}
 
	/**
	 * Translate any message passing the key as a parameter.
	 * @param message
	 * @param variables
	 * @returns
	 */
	public static translate(message: string | string[], variables: IDictionary<any> = {}) {
		return i18next.t(message, variables);
	}
}