]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/core/locale.service.ts
LP#1775466 Angular(6) base application
[Evergreen.git] / Open-ILS / src / eg2 / src / app / core / locale.service.ts
1 import {Injectable} from '@angular/core';
2 import {Location} from '@angular/common';
3 import {environment} from '../../environments/environment';
4 import {Observable} from 'rxjs/Observable';
5 import {of} from 'rxjs';
6 import {CookieService} from 'ngx-cookie';
7 import {IdlObject} from '@eg/core/idl.service';
8 import {PcrudService} from '@eg/core/pcrud.service';
9
10 @Injectable({providedIn: 'root'})
11 export class LocaleService {
12
13     constructor(
14         private ngLocation: Location,
15         private cookieService: CookieService,
16         private pcrud: PcrudService) {
17     }
18
19     setLocale(code: string) {
20         let url = this.ngLocation.prepareExternalUrl('/');
21
22         // The last part of the base path will be the locale
23         // Replace it with the selected locale
24         url = url.replace(/\/[a-z]{2}-[A-Z]{2}\/$/, `/${code}`);
25
26         // Finally tack the path of the current page back onto the URL
27         // which is more friendly than forcing them back to the splash page.
28         url += this.ngLocation.path();
29
30         // Set a 10-year locale cookie to maintain compatibility
31         // with the AngularJS client.
32         // Cookie takes the form aa_bb instead of aa-BB
33         const cookie = code.replace(/-/, '_').toLowerCase();
34         this.cookieService.put('eg_locale',
35             cookie, {path : '/', secure: true, expires: '+10y'});
36
37         window.location.href = url;
38     }
39
40     // Returns codes supported for the current environment.
41     supportedLocaleCodes(): string[] {
42         return environment.locales || [];
43     }
44
45     // Returns i18n_l objects matching the locales supported
46     // in the current environment.
47     supportedLocales(): Observable<IdlObject> {
48         const locales = this.supportedLocaleCodes();
49
50         if (locales.length === 0) {
51             return of();
52         }
53
54         return this.pcrud.search('i18n_l', {code: locales});
55     }
56
57     // Extract the local from the URL.
58     // It's the last component of the base path.
59     // Note we don't extract it from the cookie since using cookies
60     // to store the locale will not be necessary when AngularJS
61     // is deprecated.
62     currentLocaleCode(): string {
63         const base = this.ngLocation.prepareExternalUrl('/');
64         const code = base.match(/\/([a-z]{2}-[A-Z]{2})\/$/);
65         return code ? code[1] : '';
66     }
67 }
68
69