12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- import { LanguageService } from './LanguageService';
- import { StringTypes } from './StringTypes';
- type LangInfo = {[id: string]: string};
- type LangData = {[id: string]: LangInfo};
- type LangObject = {[id: string]: LangData}
- export class LocalizedStrings {
- private document: Document = document;
- constructor (private service: LanguageService, private i18nData: LangObject, private listenToChange = false) {
- if(this.listenToChange) {
- service.registerLanguageChangeListener( () => {
- this.updateTagText();
- });
- }
- }
- getString (id: string, type: string): string {
- let i18nObj = this.i18nData[this.service.getLang()];
- if (!!!i18nObj) {
- console.warn(`Internal Error. The language set at ivprog.lang is not valid: ${this.service.getLang()}`);
- i18nObj = this.i18nData[this.service.getDefaultLang()];
- }
- if (!!!i18nObj[type]) {
- return "{MISSING_I18N_TYPE_IDENTIFIER}";
- } else if (!!!i18nObj[type][id]) {
- return "{MISSING_I18N_IDENTIFIER}";
- } else {
- return i18nObj[type][id];
- }
- }
- getOR (): String {
- return this.getUI('string_join_or');
- }
- getError (id: string, context: [] = []) {
- const text = this.getString(id, StringTypes.ERROR);
- return this.processString(text, context)
- }
- getMessage (id: string, context: [] = []) {
- const text = this.getString(id, StringTypes.MESSAGE);
- return this.processString(text, context)
- }
- getUI (id: string, context: [] = []) {
- const text = this.getString(id, StringTypes.UI);
- return this.processString(text, context)
- }
- processString (text: string, context: []) {
- for (let i = 0; i < context.length; i++) {
- const v = context[i];
- text = text.replace('\$' + i, v);
- }
- return text;
- }
- updateTagText (func: ((str: string | null) => string) | null = null): void {
- if (this.document !== null) {
- const list = this.document.querySelectorAll("data.i18n");
- list.forEach(node => {
- if (func === null) {
- node.innerHTML = this.processTagTex(node.getAttribute("value"));
- } else {
- node.innerHTML = func(node.getAttribute("value"));
- }
- })
- }
- }
- processTagTex (text: string | null): string {
- if (text === null) {
- return "<Invalid i18n identifier>";
- }
- const opts = text.split(':');
- const type = opts[0].toLowerCase();
- const id = opts[1];
- if (StringTypes.ERROR === type) {
- return this.getError(id);
- } else if (StringTypes.MESSAGE === type) {
- return this.getMessage(id);
- } else if (StringTypes.UI === type) {
- return this.getUI(id);
- } else {
- console.warn(" A string has been passed to the i18n helper function that was not in the form type:id -> " + text);
- return this.getString(id, type);
- }
- }
- }
|