César Calvo
2017-03-15 abb9cc75e166c32cfa97244c497e6a69d14ea114
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
import { Http } from '@angular/http';
import { ModuleWithProviders, NgModule, Inject, Injectable, Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';
declare var navigator:any;
// Use as reference: https://github.com/ngx-translate/core/tree/master/src
@Injectable()
export class LocaleService {
    get URL_TPL() {return  'src/lang/messages_{0}.json'};
    
   private _devLang : string = 'en';
   private _currentLang : string = null;
    private _messages : any = null;
    private _elements = new Array<ElementRef>();
    private constructor(private http: Http, @Inject('INITIAL_LANG') initLang: string) {
       this.lang = initLang || this.getBrowserLang();
    }
    
    get lang() : string {
        return this._currentLang;
    }
    set lang(newLang: string) {
        this._currentLang = newLang;
        this.http.get(this._format(this.URL_TPL, newLang)).subscribe((data) => {
            this._messages = data.json();
            this.reloadTexts();
        }); 
    }
    
    isLoaded() : boolean {
        return !!this._messages
    }
    
    getBrowserLang() : string {
        var l;
        if (!navigator) return 'en';
        
        if (navigator.languages && navigator.languages.length) {
            l = navigator.languages[0];
        } else {
            l = navigator.language || 'en';
        }
        l = l.replace(/-.*/gi, '');
        if (l !== 'en' && l !== 'es')
            return 'en';        
        return l;
    }
    /**
     * It works similar to MessageFormat in Java
     */
    _format(str: string, ...params: string[]) {
        
        return str.replace(/\{(\d+)\}/g, function(match, index) {
            return params[index];
        });
    };
    reloadTexts() : void {
        this._elements.forEach((ele: ElementRef) => {
           
            var txt = ele.nativeElement.getAttribute('i18n');
            if (!!txt) {
                ele.nativeElement.textContent = this.get(txt);
           }
        })
    }
    
    add(ele: ElementRef) {
        this._elements.push(ele);
    }
    
    /**
     * It accepts direct messages and templates:
     * {
     *  "hello": "hola",
     *  "Hello {0}!!: "Hola {0}!!"
     *  }
     * $L.get('hello'); // This returns "hola"
     * $L.get('Hello {0}!!', 'John'); // This returns: "Hola John!!" if language is spanish
     */
    get(msg: string, ...params: string[] ) : string {
        if (msg == null) {
            return '';
        }
        msg = msg.trim();
        var trans_msg = msg;
        
        if (this.isLoaded()) {
            if (this._messages[msg]) {
                trans_msg = this._messages[msg];
            } else if (this._messages[msg.toLowerCase()]) {
                trans_msg = this._messages[msg.toLowerCase()];
            } else { 
                (this._currentLang !== this._devLang) && console.error("Missing i18 key: " + msg);
                trans_msg = msg;
            }
        }
        // Enviar evento cuando el idioma cambia al $rootScope
        
        if (arguments.length === 1) return trans_msg;
        return this._format(trans_msg, ...params);
    }
    
}
@Directive({ selector: '[i18n]' })
export class I18nDirective {
    constructor(private el: ElementRef, private renderer: Renderer, private $L: LocaleService) {
    }
   ngAfterViewChecked() {
        var txt = this.el.nativeElement.getAttribute('i18n') || this.el.nativeElement.textContent;
        this.renderer.setElementProperty(this.el.nativeElement, 'i18n', txt.trim());
        this.$L.add(this.el);
        this.renderer.setElementProperty(this.el.nativeElement, 'innerHTML', this.$L.get(txt));
    }
}
@NgModule({
    providers: [ <any>LocaleService ]
})
export class LocaleServiceModule {
    static withConfig(initLang?: string): ModuleWithProviders {
        return {
            ngModule: LocaleServiceModule,
            providers: [
                { provide: 'INITIAL_LANG', useValue: initLang }
            ]
        }
    }
}