All files / modules language.ts

82.68% Statements 191/231
67.1% Branches 51/76
92.1% Functions 35/38
82.35% Lines 182/221

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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 65011x 11x   11x   11x 11x   11x 11x           11x               2x 2x 2x   2x 2x 2x       2x 2x   2x           3x     3x       1x                   14x 14x 14x 14x 14x               12x                         3x 1x     3x 3x 2x   3x 1x     3x 3x               14x                         14x 14x   14x 14x 2x     14x 14x                           17x 17x                               2x       2x 2x 2x 2x 1x     1x 1x       1x                             3x   3x 3x 3x 3x 3x 2x     3x                     10x 17x 17x     17x                           17x 17x 17x   17x 17x   10x 10x 10x 10x               10x                                       11x 13x   13x 13x               10x 10x                     13x     13x 13x 13x   13x 13x 13x 52x 13x       13x 13x 13x   13x           13x 13x   13x                                   13x                     2x       2x 2x         2x                   14x               13x             13x                   15x   15x 15x 15x     15x   8x   8x     8x 8x     8x                     14x       14x 14x 14x                         14x 14x       14x 14x 1x 1x         14x 14x 14x     14x                     15x 8x     7x                         3x 3x 3x 3x       3x                       11x 18x   18x 18x     18x   18x                   18x 18x   18x   7x   7x 7x   7x 7x       18x                   13x 12x   13x                       2x       2x 1x     1x 1x 3x 3x     1x                                                               4x 2x 2x 1x     1x 1x 1x   1x     2x   2x 2x             2x 2x 2x 2x 2x 1x       1x            
import { InjectionToken } from '@angular/core';
import { Injectable, Inject } from '@angular/core';
import { ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
 
import { Subject, Subscription } from 'rxjs';
import { take } from 'rxjs/operators';
 
import { AppConstants} from '@unpispas/upp-defs';
import { HttpClient } from '@angular/common/http';
 
/**
 * @const {InjectionToken<string>} langsPath
 * @description Injection token representing the base path where language JSON files are stored.
 */
export const langsPath = new InjectionToken<string>('langsPath');
 
/** @internal */ type __tstring = string | null;
/** @internal */ type __targs = Array <string | number | null | undefined>;
/** @internal */ type __trinfo = { tr: string, args: __targs };
 
/** @internal */
class __trString{
    private _id: __tstring = null;
    private _args: __targs = [];
    private _tr: __tstring = null;
    
    constructor(private lang: _translator, id: __tstring, args: __targs){
        this._id = id;
        this._args = args;
    }
 
    get value() {
        if (!this._tr){
            this._tr = String(this.lang._translate(this._id, this._args));
        }
        return this._tr;
    }    
}
 
/** @internal */
class __erString{
    private _str = "";
    
    constructor(str: string){
        this._str = str;    
    }
    
    get value() {
        return this._str;
    }
}
 
/**
 * @internal
 * @class _translator
 * @description Internal class to handle translation management, including loading modules, caching, and error handling.
 */
class _translator {    
    private strings = new Map <string, __trinfo> ();
    private current: string | null = null;
    private modules = new Set <string> ();
    private trcache = new Map <string, __trString> ();
    private loading = 0;
 
    /**
     * @getter _strings
     * @description Returns the map of all translation strings currently loaded.
     * @returns {Map<string, __trinfo>} The map of translation strings.
     */    
    get _strings(){
        return this.strings;
    }
    
    /**
     * @private
     * @method _trerror
     * @description Handles translation errors by generating a fallback string and optionally logging the error to the console.
     * @param {string} id - The ID of the translation string.
     * @param {__targs} args - The arguments provided for the translation placeholders.
     * @param {__tstring} errstr - Optional error message to log to the console.
     * @returns {string} The generated fallback string.
     */    
    private _trerror(id: string,  args: __targs, errstr: __tstring) {
        if(errstr) {
            console.error(errstr);
        }
 
        let tr = id + " [ ";
        for(let i=0; i < args.length; i++) {
            tr += args[i] + ", ";
        }
        if (args.length > 0) {
            tr = tr.slice(0, -2);
        }
        
        tr += " ]";
        return tr;
    }
    
    /**
     * @constructor
     * @param {HttpClient} http - Angular HttpClient for API requests.
     * @param {string} langspath - Base path for loading language JSON files.
     */    
    constructor(private http: HttpClient, private langspath: string) { 
        // nothing to do (initialized when language is set)
    }
    
    /**
     * @public
     * @method SetLanguage
     * @description Sets the current language and loads the required translation modules.
     * @param {string} language - The target language code.
     * @param {Set<string>} modules - Set of module names to load.
     * @returns {Promise<boolean>} Whether the language was successfully set.
     */    
    public async SetLanguage(language: string, modules: Set <string>) : Promise <boolean> {
        if (language != this.current){
            this.current = language;
 
            const _promises =  [];
            for(const module of modules){
                _promises.push(this.LoadModule(module));
            }
 
            const results = await Promise.all(_promises);
            return results.every(result => result === true);
        }
 
        return true;
    }
 
    /**
     * @public
     * @method LoadModule
     * @description Loads translation strings for a specific module.
     * @param {string} name - The name of the module.
     * @returns {Promise<boolean>} Whether the module was successfully loaded.
     */    
    public LoadModule(name: string) : Promise <boolean> {
        if (this.current){
            return this._load_module(name, this.current, false);
        }
 
        console.error("LANGUAGE] Could not load module before setting the language");
        return Promise.resolve(false);;
    }
 
    /**
     * @public
     * @method _translate
     * @description Resolves a translation string by ID and replaces placeholders with provided arguments.
     * @param {__tstring} id - The ID of the translation string.
     * @param {__targs} args - Arguments to replace placeholders in the string.
     * @returns {string | null} The resolved translation string, or null if not found.
     */    
    public _translate(id: __tstring, args: __targs): string | null {
        Iif (id == null){
            return null;
        }
 
        const trinfo = this.strings.get(id) || null;
        if (trinfo){
            Iif (!trinfo.args) trinfo.args = [];     // add empty arguments list as default
            if (trinfo.args.length != args.length) {
                return this._trerror(id, args, "ERROR: invalid number of arguments for translation [" + id + "]");
            }
            
            let tr = trinfo.tr;
            for (let i=0; i < trinfo.args.length; i++) {
                const re = new RegExp("{{" + trinfo.args[i] + "}}", "g");
                tr = tr.replace(re, String(args[i]));
            }
            return tr;
        }
 
        return null;
    }
 
    /**
     * @public
     * @method tr
     * @description Translates a string ID with optional arguments. Uses a cache for optimization.
     * @param {string} id - The ID of the string to translate.
     * @param {__targs} args - Optional arguments to replace placeholders in the translation string.
     * @returns {string} The translated string, or an error placeholder if the ID is not found.
     */    
    public tr(id: string, args: __targs = []): string {
        let _str: __trString | __erString | null = null;
 
        const _key = JSON.stringify({ id: id, args: args });
        _str = this.trcache.get(_key) || null;
        if (!_str){
            _str = new __erString((this.loading > 0) ? '...' : this._trerror(id, args, null));
            if (this.strings.has(id)){
                this.trcache.set(_key, _str = new __trString(this, id, args));
            }
        }
        return _str.value;
    }
 
    /**
     * @private
     * @method _load_json
     * @description Loads translation strings from a JSON object into the internal string map.
     * @param {any} json - The JSON object containing translation strings.
     * @param {boolean} replace - Whether to replace existing strings with new ones.
     */    
    private _load_json(json: any, replace: boolean) {
        for(let i=0; i < json.length; i++){
            const entry = json[i];
            Iif (!replace && this.strings.has(entry.id)){
                console.warn("WARNING: existing string '" + entry.id + "'");
            }
            this.strings.set(entry.id, { args: entry.args, tr: entry.tr });
        }
    }
    
    /**
     * @private
     * @method _load_module
     * @description Loads translation strings for a specific module and language.
     * @param {string} name - The module name.
     * @param {string} language - The language code.
     * @param {boolean} replace - Whether to replace existing strings.
     * @returns {Promise<boolean>} Resolves to true if the module is successfully loaded; otherwise, false.
     */    
    private _load_module(name: string, language: string, replace: boolean): Promise <boolean> {
        return new Promise <boolean> ((resolve) => {
            if (!this.modules.has(name)){
                this.loading++;    
 
                const _request = this.http.get(this.langspath + '/' + name + '/' + language.toLowerCase() + '.json');
                _request.pipe(take(1)).subscribe({
                    next: (data) => {
                        this._load_json(data, replace);
                        console.info("[LANGUAGE] Module '" + name + "' strings loaded for language '" + language + "'");
                        this.modules.add(name);
                        resolve(true);    
                    },
                    error: (error) => {
                        console.error("LANGUAGE] Could not load strings for module '" + name + "'.");
                        console.error(error);
                        resolve(false);    
                    },
                    complete: () => {
                        this.loading--; 
                    }
                });          
            }
            else E{
                resolve(false);  // already loaded
            }
        });
    }    
}
 
/**
 * @class languageService
 * @description A service to manage language translations and language-related settings for the application.
 * The service loads translation strings for various modules and supports switching between different languages.
 * It also provides translation functionality with caching mechanisms for optimized performance.
 */
@Injectable({
    providedIn: 'root'
})
export class languageService {
    private _lngsets: { [key: string]: _translator } = {}
 
    private _current: string | null = null; 
    private modules = new Set <string> ();
 
    /**
     * @getter _strings
     * @description Retrieves the map of translation strings for the current language.
     * @returns {Map<string, __trinfo>} The map of loaded translation strings.
     */    
    get _strings(){
        if (this._current){
            return this._lngsets[this._current]._strings;
        }
        return new Map <string, __trinfo> ();
    }    
 
   /**
     * @constructor
     * @param {HttpClient} http - Angular HttpClient for fetching translation files.
     * @param {string} langspath - The base path for translation JSON files.
     * @param {ActivatedRoute} route - Angular ActivatedRoute for accessing URL parameters.
     */    
    constructor(private http: HttpClient, @Inject(langsPath) private langspath: string, private route: ActivatedRoute) { 
 
        // first option - user browser language
        let _userLang = navigator.language || AppConstants.defaultLanguage.toUpperCase(); 
        if (_userLang){
            _userLang = _userLang.substring(0, 2).toUpperCase();
            
            console.info("[BROWSER LANGUAGE]: " + _userLang);
            let _supported = null;
            for (const _lang of this.GetLanguages()){
                if (_userLang == _lang.lang){
                    _supported = _lang.lang;
                }
            }
 
            _supported = _supported || AppConstants.defaultLanguage.toUpperCase();
            if (_supported){
                this.AddLanguage(_supported).then(
                () => {
                    this.SetLanguage(_supported, true);
                });
            }
        }
 
        // second option - user URL language
        this.route.queryParams.subscribe(params => {
            const _urlLang = params['lang'];
 
            Iif (_urlLang) {  // use url language
                console.info("[URL GET LANGUAGE]: " + _urlLang);
 
                let _supported = null;
                for (const _lang of this.GetLanguages()) {
                    Iif (_urlLang === _lang.lang) {
                        _supported = _lang.lang;
                    }
                }
 
                Iif (_supported) {
                    this.AddLanguage(_supported).then(() => {
                        this.SetLanguage(_supported, true);
                    });       
                }
            }
        });
 
        this.LoadModule('base');
    }    
 
    /**
     * @public
     * @method StrInfo
     * @description Retrieves detailed translation information for a given string ID in the current language.
     * @param {string} id - The ID of the translation string.
     * @returns {__trinfo | null} Translation information, or null if the string ID is not found.
     */    
    public StrInfo(id: string){
        Iif (!this._current){
            return null;
        }
 
        const _lang = this._lngsets[this._current];
        Iif (!_lang){
            console.error("[TRANSLATE]: No current language is set")
            return null;
        }
 
        return _lang._strings.get(id);
    }
 
    /**
     * @public
     * @method GetLanguages
     * @description Retrieves the list of supported languages.
     * @returns {Array<{ lang: string, flag: string }>} An array of supported language objects.
     */    
    public GetLanguages(){
        return [
            { lang: 'ES', flag: 'ES' },
            { lang: 'EU', flag: 'ES-PV' },
            { lang: 'EN', flag: 'GB' },
            { lang: 'ZH', flag: 'CN' }
        ];
    }
 
    private _onSetLanguage = new Subject <void> ();
 
    /**
     * @public
     * @property OnSetLanguage
     * @description Observable that emits notifications whenever the active language changes.
     */    
    public OnSetLanguage = this._onSetLanguage.asObservable();
 
    /**
     * @public
     * @method LoadModule
     * @description Loads translation strings for a specified module in all available languages.
     * @param {string} name - The name of the module to load.
     * @returns {Promise<boolean>} Resolves to true if the module was successfully loaded; otherwise, false.
     */    
    public async LoadModule(name: string): Promise <boolean> {
        this.modules.add(name);
 
        const _promises = [];        
        for (const _language in this._lngsets){
            _promises.push(this._lngsets[_language].LoadModule(name));
        }
 
        const _loaded = await Promise.all(_promises);
 
        const _allok = _loaded.every(
        (result) => {
            return result === true
        });
 
        if (_allok){
            this._onSetLanguage.next();
        }
 
        return _allok;
    }
 
    /**
     * @private
     * @method AddLanguage
     * @description Adds a new language to the service and loads its translation strings.
     * @param {string} language - The language code to add.
     * @returns {Promise<boolean>} Resolves to true if the language was successfully added; otherwise, false.
     */    
    private async AddLanguage(language: string): Promise <boolean> {
        Iif (language in this._lngsets){
            return true;     // already included
        }
 
        this._lngsets[language] = new _translator(this.http, this.langspath);
        if (this._lngsets[language]){
            return await this._lngsets[language].SetLanguage(language, this.modules);
        }
 
        return false;
    }
 
    /**
     * @private
     * @method AddLanguage
     * @description Adds a new language to the service and loads its translation strings.
     * @param {string} language - The language code to add.
     * @returns {Promise<boolean>} Resolves to true if the language was successfully added; otherwise, false.
     */    
    public async SetLanguage(language: string, global = true): Promise <boolean>  {
        Iif (this._current == language){
            return true;
        }
 
        const _lang = this._lngsets[language];
        if (!_lang){
            const success = await this.AddLanguage(language);
            Iif (!success){
                return false;
            }
        }
 
        if (global){
            this._current = language;
            this._onSetLanguage.next();
        }
 
        return true;
    }
 
    /**
     * @public
     * @method GetLanguage
     * @description Retrieves the current active language.
     * @param {boolean} [toUpper=false] - Whether to return the language code in uppercase.
     * @returns {string} The active language code, or the default language if no language is set.
     */    
    public GetLanguage(toUpper = false): string {
        if (this._current){
            return (toUpper)? this._current.toUpperCase() : this._current;
        }
 
        return AppConstants.defaultLanguage.toUpperCase();
    }
    
    /**
     * @public
     * @method tr
     * @description Translates a string ID into the corresponding translation using the current or specified language.
     * @param {string} id - The ID of the translation string.
     * @param {__targs} [args=[]] - Optional arguments to replace placeholders in the translation.
     * @param {string | null} [language=null] - Optional target language for the translation.
     * @returns {string} The translated string, or "..." if the language is still loading.
     */    
    public tr(id: string, args: __targs = [], language: string | null = null): string {
        const _target = language || this._current;
        if (_target){
            const _lang = this._lngsets[_target];
            Iif (!_lang){
                return "...";   // strings are being loaded
            }    
 
            return _lang.tr(id, args);
        }
 
        return "...";    // no language provided
    }
}
 
/**
 * @class languageSupport
 * @description A utility class that facilitates the integration of language translation with Angular components.
 * This class observes language changes and provides methods for translating strings with caching and argument support.
 */
export class languageSupport {
    public language: string | null = null;
 
    private _strcache = new Map <string, string> ();
    private _argcache = new Map <string, __trinfo>();
 
    public _lang: languageService;
    public _chng: ChangeDetectorRef | null = null;
 
    private _language_subscription: Subscription | null = null;
 
    /**
     * @constructor
     * @description Initializes the language support instance, subscribes to language change notifications,
     * and binds the provided `languageService` and `ChangeDetectorRef`.
     * @param {languageService} lang - The language service to use for translations.
     * @param {ChangeDetectorRef | null} chng - The Angular change detector for triggering view updates.
     */    
    constructor(lang: languageService, chng: ChangeDetectorRef | null){
        this._lang = lang;
        this._chng = chng;
 
        this._language_subscription = this._lang.OnSetLanguage.subscribe(
        () => {
            this.language = this._lang.GetLanguage();
 
            this._strcache.clear();
            this._argcache.clear();
 
            if (this._chng){
                this._chng.detectChanges();
            }
        });        
 
        this.language = this._lang.GetLanguage();
    }
    
    /**
     * @public
     * @method OnDestroy
     * @description Cleans up the subscription to the language change observable when the component is destroyed.
     * @returns {void}
     */    
    OnDestroy(){
        if (this._language_subscription){
            this._language_subscription.unsubscribe();
        }
        this._language_subscription = null;
    }
 
    /**
     * @private
     * @method _translate
     * @description Resolves a translation string by replacing placeholders with provided arguments.
     * @param {__trinfo} trinfo - Translation information containing placeholders and the base string.
     * @param {__targs} args - Arguments to replace the placeholders in the translation string.
     * @returns {string | null} The resolved translation string, or null if arguments do not match placeholders.
     */
    private _translate(trinfo: __trinfo, args: __targs) {
        Iif (!trinfo.args) { // add empty arguments list as default
            trinfo.args = [];     
        }
 
        if (trinfo.args.length != args.length) {
            return null;
        }
        
        let tr = trinfo.tr;
        for (let i=0; i < trinfo.args.length; i++) {
            const re = new RegExp("{{" + trinfo.args[i] + "}}", "g");
            tr = tr.replace(re, String(args[i]));
        }
        
        return tr;
    }
 
    /**
     * @public
     * @method SetLanguage
     * @description Sets the current language and updates translations for the component. 
     * Clears the cache and triggers a view update if a new language is set.
     * @param {string} language - The language code to set as current.
     * @returns {Promise<void>} Resolves once the language is set and view updated.
     */    
    public async SetLanguage(language: string){
        Iif ((language != this.language) && await this._lang.SetLanguage(language, false)){
            this.language = language;
            this._strcache.clear();
 
            Iif (this._chng){
                this._chng.detectChanges();    
            }
        }
    }
 
    /**
     * @public
     * @method tr
     * @description Translates a string ID to its corresponding translated value, using the provided arguments (if any).
     * If no arguments are provided, the translation is cached for optimized future access.
     * @param {string} id - The ID of the translation string.
     * @param {Array<any>} [args=[]] - Optional arguments to replace placeholders in the translation.
     * @returns {string} The translated string.
     */        
    public tr(id: string, args: __targs = []): string {
        if (args.length == 0){
            let _str = this._strcache.get(id) || null;
            if (_str){
                return _str;
            }
 
            _str = this._lang.tr(id, args, this.language);
            if (_str && (_str[0] != '@') && (args.length == 0)) {   // not translated or has arguments (do not cache)
                this._strcache.set(id, _str); 
            }
            return _str;
        }
        else {
            let _trinfo: __trinfo | undefined | null = null; 
 
            _trinfo = this._argcache.get(id);
            Iif (_trinfo){
                const _str = this._translate(_trinfo, args);
                Iif (_str){
                    return _str;
                }        
            }
 
            _trinfo = this._lang.StrInfo(id);
            if (_trinfo){
                this._argcache.set(id, _trinfo);
                const _str = this._translate(_trinfo, args);
                if (_str){
                    return _str;
                }
            }
 
            return this._lang.tr(id, args, this.language);
        }
    }
}