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