angular-l10n
Version:
An Angular library to translate messages, dates and numbers
1,447 lines (1,434 loc) • 182 kB
JavaScript
/**
* @license Angular l10n
* Copyright Roberto Simonetti
* MIT license
* https://github.com/robisim74/angular-l10n
*/
import { Injector, Injectable, InjectionToken, Inject, Optional, ChangeDetectorRef, Pipe, Input, Directive, ElementRef, Renderer2, forwardRef, Component, HostBinding, NgModule } from '@angular/core';
import { ReplaySubject, Subject, race, combineLatest, Observable, merge, concat, BehaviorSubject } from 'rxjs';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { Location } from '@angular/common';
import { filter, timeout, map, takeUntil } from 'rxjs/operators';
import { __awaiter, __generator, __extends } from 'tslib';
import { HttpParams, HttpClient, HttpHeaders, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Title, Meta, DomSanitizer } from '@angular/platform-browser';
import { NG_VALIDATORS } from '@angular/forms';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* Allows to get the dependencies at the root level.
*/
var InjectorRef = /** @class */ (function () {
function InjectorRef(injector) {
this.injector = injector;
/**
* TranslationService instances.
*/
this.translations = [];
InjectorRef.injector = this.injector;
}
/**
* @template T
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
InjectorRef.get = /**
* @template T
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
function (token, notFoundValue) {
return InjectorRef.injector.get(token, notFoundValue);
};
InjectorRef.injector = Injector.NULL;
InjectorRef.decorators = [
{ type: Injectable }
];
/** @nocollapse */
InjectorRef.ctorParameters = function () { return [
{ type: Injector }
]; };
return InjectorRef;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** @type {?} */
var L10N_CONFIG = new InjectionToken('L10N_CONFIG');
/**
* @param {?} l10nConfig
* @return {?}
*/
function l10nConfigFactory(l10nConfig) {
return {
locale: l10nConfig.locale || {},
translation: l10nConfig.translation || {},
logger: l10nConfig.logger || {},
localizedRouting: l10nConfig.localizedRouting || {},
search: l10nConfig.search || {},
localeInterceptor: l10nConfig.localeInterceptor || {}
};
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** @enum {number} */
var StorageStrategy = {
Session: 0,
Local: 1,
Cookie: 2,
Disabled: 3,
};
StorageStrategy[StorageStrategy.Session] = 'Session';
StorageStrategy[StorageStrategy.Local] = 'Local';
StorageStrategy[StorageStrategy.Cookie] = 'Cookie';
StorageStrategy[StorageStrategy.Disabled] = 'Disabled';
/** @enum {number} */
var ProviderType = {
Fallback: 0,
Static: 1,
WebAPI: 2,
};
ProviderType[ProviderType.Fallback] = 'Fallback';
ProviderType[ProviderType.Static] = 'Static';
ProviderType[ProviderType.WebAPI] = 'WebAPI';
/** @enum {string} */
var ISOCode = {
Language: 'languageCode',
Country: 'countryCode',
Script: 'scriptCode',
};
/** @enum {string} */
var ExtraCode = {
NumberingSystem: 'numberingSystem',
Calendar: 'calendar',
Currency: 'currency',
Timezone: 'timezone',
};
/** @enum {string} */
var LogLevel = {
Error: 'error',
Warn: 'warn',
Info: 'info',
Log: 'log',
Off: 'off',
};
/** @enum {number} */
var NumberFormatStyle = {
Decimal: 0,
Percent: 1,
Currency: 2,
};
NumberFormatStyle[NumberFormatStyle.Decimal] = 'Decimal';
NumberFormatStyle[NumberFormatStyle.Percent] = 'Percent';
NumberFormatStyle[NumberFormatStyle.Currency] = 'Currency';
/** @type {?} */
var NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(\-(\d+))?)?$/;
/** @type {?} */
var ISO8601_DATE_REGEX = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
/** @type {?} */
var FORMAT_ALIASES = {
'short': { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' },
'medium': { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' },
'long': { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' },
'full': { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' },
'shortDate': { year: 'numeric', month: 'numeric', day: 'numeric' },
'mediumDate': { year: 'numeric', month: 'short', day: 'numeric' },
'longDate': { year: 'numeric', month: 'long', day: 'numeric' },
'fullDate': { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' },
'shortTime': { hour: 'numeric', minute: 'numeric' },
'mediumTime': { hour: 'numeric', minute: 'numeric', second: 'numeric' }
};
/** @type {?} */
var LOG_MESSAGES = {
'missingOnInit': "Missing 'ngOnInit' method: required by AoT compilation",
'missingOnDestroy': "Missing 'ngOnDestroy' method to cancel subscriptions: required by AoT compilation",
'missingLang': "Missing 'lang' parameter",
'missingDefaultLocale': "Missing 'defaultLocale' parameter",
'missingCurrency': "Missing 'currency' parameter",
'invalidNumberFormatAlias': "Invalid number format alias: the default format will be used",
'invalidDateFormatAlias': "Invalid date format alias: the default format will be used"
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var Logger = /** @class */ (function () {
function Logger(configuration) {
var _this = this;
this.configuration = configuration;
Logger.level = this.configuration.logger.level || LogLevel.Off;
if (Logger.level != LogLevel.Off) {
Logger.buffer.subscribe(function (log) {
_this.send(log);
});
}
}
/**
* @param {?} name
* @param {?} message
* @return {?}
*/
Logger.log = /**
* @param {?} name
* @param {?} message
* @return {?}
*/
function (name, message) {
if (Logger.level == LogLevel.Off)
return;
Logger.buffer.next({ name: name, message: message });
};
/**
* @param {?} log
* @return {?}
*/
Logger.prototype.send = /**
* @param {?} log
* @return {?}
*/
function (log) {
/** @type {?} */
var message = "angular-l10n (" + log.name + "): " + LOG_MESSAGES[log.message];
((/** @type {?} */ (console)))[(/** @type {?} */ (Logger.level))](message);
};
Logger.level = null;
Logger.buffer = new ReplaySubject();
Logger.decorators = [
{ type: Injectable }
];
/** @nocollapse */
Logger.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: Inject, args: [L10N_CONFIG,] }] }
]; };
return Logger;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var Caching = /** @class */ (function () {
function Caching() {
this.cache = {};
}
/**
* @param {?} key
* @param {?} request
* @return {?}
*/
Caching.prototype.read = /**
* @param {?} key
* @param {?} request
* @return {?}
*/
function (key, request) {
var _this = this;
/** @type {?} */
var cached = this.cache[key];
if (cached)
return cached;
/** @type {?} */
var buffer = new ReplaySubject(1);
request.subscribe(function (value) { return buffer.next(value); }, function (error) {
buffer.error(error);
_this.cache[key] = undefined;
}, function () { return buffer.complete(); });
/** @type {?} */
var response = buffer.asObservable();
this.cache[key] = response;
return response;
};
Caching.decorators = [
{ type: Injectable }
];
return Caching;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* Provides the methods to check if Intl APIs are supported.
*/
var /**
* Provides the methods to check if Intl APIs are supported.
*/
IntlAPI = /** @class */ (function () {
function IntlAPI() {
}
/**
* @return {?}
*/
IntlAPI.hasIntl = /**
* @return {?}
*/
function () {
/** @type {?} */
var hasIntl = typeof Intl === "object" && !!Intl;
return hasIntl;
};
/**
* @return {?}
*/
IntlAPI.hasDateTimeFormat = /**
* @return {?}
*/
function () {
return IntlAPI.hasIntl() && Intl.hasOwnProperty("DateTimeFormat");
};
/**
* @return {?}
*/
IntlAPI.hasTimezone = /**
* @return {?}
*/
function () {
if (IntlAPI.hasIntl() && IntlAPI.hasDateTimeFormat()) {
try {
new Intl.DateTimeFormat('en-US', { timeZone: 'America/Los_Angeles' }).format(new Date());
}
catch (e) {
return false;
}
return true;
}
return false;
};
/**
* @return {?}
*/
IntlAPI.hasNumberFormat = /**
* @return {?}
*/
function () {
return IntlAPI.hasIntl() && Intl.hasOwnProperty("NumberFormat");
};
/**
* @return {?}
*/
IntlAPI.hasCollator = /**
* @return {?}
*/
function () {
return IntlAPI.hasIntl() && Intl.hasOwnProperty("Collator");
};
/**
* @return {?}
*/
IntlAPI.hasRelativeTimeFormat = /**
* @return {?}
*/
function () {
return IntlAPI.hasIntl() && Intl.hasOwnProperty("RelativeTimeFormat");
};
return IntlAPI;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* @param {?} name
* @return {?}
*/
function getLocalStorage(name) {
return localStorage.getItem(name);
}
/**
* @param {?} name
* @return {?}
*/
function getSessionStorage(name) {
return sessionStorage.getItem(name);
}
/**
* @param {?} name
* @return {?}
*/
function getCookie(name) {
/** @type {?} */
var result = null;
if (typeof document !== "undefined") {
result = new RegExp("(?:^|; )" + encodeURIComponent(name) + "=([^;]*)").exec(document.cookie);
}
return result ? result[1] : null;
}
/**
* @param {?} name
* @param {?} value
* @return {?}
*/
function setLocalStorage(name, value) {
localStorage.setItem(name, value);
}
/**
* @param {?} name
* @param {?} value
* @return {?}
*/
function setSessionStorage(name, value) {
sessionStorage.setItem(name, value);
}
/**
* @param {?} name
* @param {?} value
* @param {?=} expiration
* @return {?}
*/
function setCookie(name, value, expiration) {
/** @type {?} */
var expires = "";
if (expiration != null) {
/** @type {?} */
var expirationDate = new Date();
expirationDate.setTime(expirationDate.getTime() +
(expiration * 24 * 60 * 60 * 1000));
expires = "; expires=" + expirationDate.toUTCString();
}
if (typeof document !== "undefined") {
document.cookie = name + "=" + value + expires + "; path=/";
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* Implement this class-interface to create a custom storage for default locale, currency & timezone.
* @abstract
*/
var LocaleStorage = /** @class */ (function () {
function LocaleStorage() {
}
LocaleStorage.decorators = [
{ type: Injectable }
];
return LocaleStorage;
}());
var L10nStorage = /** @class */ (function () {
function L10nStorage(configuration) {
this.configuration = configuration;
this.hasCookie = typeof navigator !== "undefined" && navigator.cookieEnabled;
this.hasStorage = typeof Storage !== "undefined";
}
/**
* @param {?} name
* @return {?}
*/
L10nStorage.prototype.read = /**
* @param {?} name
* @return {?}
*/
function (name) {
return __awaiter(this, void 0, void 0, function () {
var value;
return __generator(this, function (_a) {
value = null;
if (this.configuration.locale.storage != StorageStrategy.Disabled) {
if (this.configuration.locale.storage == StorageStrategy.Local && this.hasStorage) {
value = getLocalStorage(this.getName(name));
}
else if (this.configuration.locale.storage == StorageStrategy.Session && this.hasStorage) {
value = getSessionStorage(this.getName(name));
}
else if (this.configuration.locale.storage == StorageStrategy.Cookie && this.hasCookie) {
value = getCookie(this.getName(name));
}
}
return [2 /*return*/, value];
});
});
};
/**
* @param {?} name
* @param {?} value
* @return {?}
*/
L10nStorage.prototype.write = /**
* @param {?} name
* @param {?} value
* @return {?}
*/
function (name, value) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (this.configuration.locale.storage != StorageStrategy.Disabled) {
if (this.configuration.locale.storage == StorageStrategy.Local && this.hasStorage) {
setLocalStorage(this.getName(name), value);
}
else if (this.configuration.locale.storage == StorageStrategy.Session && this.hasStorage) {
setSessionStorage(this.getName(name), value);
}
else if (this.configuration.locale.storage == StorageStrategy.Cookie && this.hasCookie) {
setCookie(this.getName(name), value, this.configuration.locale.cookieExpiration);
}
}
return [2 /*return*/];
});
});
};
/**
* @param {?} name
* @return {?}
*/
L10nStorage.prototype.getName = /**
* @param {?} name
* @return {?}
*/
function (name) {
if (this.configuration.locale.storageNames) {
return ((/** @type {?} */ (this.configuration.locale.storageNames)))[name] || name;
}
return name;
};
L10nStorage.decorators = [
{ type: Injectable }
];
/** @nocollapse */
L10nStorage.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: Inject, args: [L10N_CONFIG,] }] }
]; };
return L10nStorage;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var DefaultLocale = /** @class */ (function () {
function DefaultLocale() {
}
Object.defineProperty(DefaultLocale.prototype, "value", {
get: /**
* @return {?}
*/
function () {
return this.formattedValue;
},
set: /**
* @param {?} defaultLocale
* @return {?}
*/
function (defaultLocale) {
this.formattedValue = defaultLocale;
this.parseValue();
},
enumerable: true,
configurable: true
});
/**
* @param {?} languageCode
* @param {?=} countryCode
* @param {?=} scriptCode
* @param {?=} numberingSystem
* @param {?=} calendar
* @return {?}
*/
DefaultLocale.prototype.build = /**
* @param {?} languageCode
* @param {?=} countryCode
* @param {?=} scriptCode
* @param {?=} numberingSystem
* @param {?=} calendar
* @return {?}
*/
function (languageCode, countryCode, scriptCode, numberingSystem, calendar) {
this.languageCode = languageCode;
this.scriptCode = scriptCode;
this.countryCode = countryCode;
this.numberingSystem = numberingSystem;
this.calendar = calendar;
/** @type {?} */
var value = languageCode;
value += !!scriptCode ? "-" + scriptCode : "";
value += !!countryCode ? "-" + countryCode : "";
// Adds the 'u' (Unicode) extension.
value += (!!numberingSystem || !!calendar) ? "-u" : "";
value += !!numberingSystem ? "-nu-" + numberingSystem : "";
value += !!calendar ? "-ca-" + calendar : "";
this.formattedValue = value;
};
/**
* @return {?}
*/
DefaultLocale.prototype.parseValue = /**
* @return {?}
*/
function () {
if (!!this.value) {
/** @type {?} */
var value = this.value;
// Looks for the 'u' (Unicode) extension.
/** @type {?} */
var index = value.search("-u");
if (index != -1) {
/** @type {?} */
var extensions = value.substring(index + 1).split("-");
switch (extensions.length) {
case 3:
if (extensions[1] == "nu") {
this.numberingSystem = extensions[2];
this.calendar = undefined;
}
else if (extensions[1] == "ca") {
this.numberingSystem = undefined;
this.calendar = extensions[2];
}
break;
default:
this.numberingSystem = extensions[2];
this.calendar = extensions[4];
}
// Extracts the codes.
value = value.substring(0, index);
}
/** @type {?} */
var codes = value.split("-");
switch (codes.length) {
case 1:
this.languageCode = codes[0];
this.scriptCode = undefined;
this.countryCode = undefined;
break;
case 2:
this.languageCode = codes[0];
this.scriptCode = undefined;
this.countryCode = codes[1];
break;
default:
this.languageCode = codes[0];
this.scriptCode = codes[1];
this.countryCode = codes[2];
}
}
};
return DefaultLocale;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var IntlFormatter = /** @class */ (function () {
function IntlFormatter() {
}
/**
* @param {?} value
* @param {?} defaultLocale
* @param {?} style
* @param {?=} digits
* @param {?=} currency
* @param {?=} currencyDisplay
* @return {?}
*/
IntlFormatter.formatNumber = /**
* @param {?} value
* @param {?} defaultLocale
* @param {?} style
* @param {?=} digits
* @param {?=} currency
* @param {?=} currencyDisplay
* @return {?}
*/
function (value, defaultLocale, style, digits, currency, currencyDisplay) {
if (!IntlAPI.hasNumberFormat())
return currency ? value + " " + currency : value;
value = typeof value === "string" && !isNaN(+value - parseFloat(value)) ? +value : value;
return IntlFormatter.numberFormatter(value, defaultLocale, style, digits, currency, currencyDisplay);
};
/**
* @param {?} value
* @param {?} defaultLocale
* @param {?} format
* @param {?=} timezone
* @return {?}
*/
IntlFormatter.formatDate = /**
* @param {?} value
* @param {?} defaultLocale
* @param {?} format
* @param {?=} timezone
* @return {?}
*/
function (value, defaultLocale, format, timezone) {
if (!IntlAPI.hasDateTimeFormat())
return value;
/** @type {?} */
var date;
if (typeof value === "string") {
value = value.trim();
}
if (IntlFormatter.isDate(value)) {
date = value;
}
else if (!isNaN(value - parseFloat(value))) {
date = new Date(parseFloat(value));
}
else if (typeof value === "string" && /^(\d{4}-\d{1,2}-\d{1,2})$/.test(value)) {
var _a = value.split('-').map(function (val) { return parseInt(val, 10); }), y = _a[0], m = _a[1], d = _a[2];
date = new Date(y, m - 1, d);
}
else {
date = new Date(value);
}
if (!IntlFormatter.isDate(date)) {
/** @type {?} */
var match = void 0;
if ((typeof value === "string") && (match = value.match(ISO8601_DATE_REGEX))) {
date = IntlFormatter.isoStringToDate(match);
}
}
return IntlFormatter.dateTimeFormatter(date, defaultLocale, format, timezone);
};
/**
* @param {?} value
* @param {?} unit
* @param {?} defaultLocale
* @param {?=} format
* @return {?}
*/
IntlFormatter.formatRelativeTime = /**
* @param {?} value
* @param {?} unit
* @param {?} defaultLocale
* @param {?=} format
* @return {?}
*/
function (value, unit, defaultLocale, format) {
if (!IntlAPI.hasRelativeTimeFormat())
return value + " " + unit;
value = typeof value === "string" && !isNaN(+value - parseFloat(value)) ? +value : value;
return IntlFormatter.relativeTimeFormatter(value, unit, defaultLocale, format);
};
/**
* @param {?} num
* @param {?} defaultLocale
* @param {?} style
* @param {?=} digits
* @param {?=} currency
* @param {?=} currencyDisplay
* @return {?}
*/
IntlFormatter.numberFormatter = /**
* @param {?} num
* @param {?} defaultLocale
* @param {?} style
* @param {?=} digits
* @param {?=} currency
* @param {?=} currencyDisplay
* @return {?}
*/
function (num, defaultLocale, style, digits, currency, currencyDisplay) {
/** @type {?} */
var options = {};
if (digits) {
if (typeof digits === "string") {
/** @type {?} */
var digitsOptions = formatDigitsAliases(digits);
if (digitsOptions != null) {
options = digitsOptions;
}
else {
Logger.log('IntlFormatter', 'invalidNumberFormatAlias');
}
}
else {
options = digits;
}
}
options.style = NumberFormatStyle[style].toLowerCase();
if (style == NumberFormatStyle.Currency) {
options.currency = currency;
options.currencyDisplay = currencyDisplay;
}
return new Intl.NumberFormat(defaultLocale, options).format(num);
};
/**
* @param {?} date
* @param {?} defaultLocale
* @param {?} format
* @param {?=} timezone
* @return {?}
*/
IntlFormatter.dateTimeFormatter = /**
* @param {?} date
* @param {?} defaultLocale
* @param {?} format
* @param {?=} timezone
* @return {?}
*/
function (date, defaultLocale, format, timezone) {
/** @type {?} */
var options = {};
if (format) {
if (typeof format === "string") {
/** @type {?} */
var dateTimeOptions = FORMAT_ALIASES[format];
if (dateTimeOptions) {
options = dateTimeOptions;
}
else {
Logger.log('IntlFormatter', 'invalidDateFormatAlias');
}
}
else {
options = format;
}
}
options.timeZone = IntlAPI.hasTimezone() ? timezone : 'UTC';
return new Intl.DateTimeFormat(defaultLocale, options).format(date).replace(/[\u200e\u200f]/g, "");
};
/**
* @param {?} value
* @param {?} unit
* @param {?} defaultLocale
* @param {?=} format
* @return {?}
*/
IntlFormatter.relativeTimeFormatter = /**
* @param {?} value
* @param {?} unit
* @param {?} defaultLocale
* @param {?=} format
* @return {?}
*/
function (value, unit, defaultLocale, format) {
/** @type {?} */
var options = {};
if (format) {
options = format;
}
return new Intl.RelativeTimeFormat(defaultLocale, options).format(value, unit);
};
/**
* @param {?} value
* @return {?}
*/
IntlFormatter.isDate = /**
* @param {?} value
* @return {?}
*/
function (value) {
return value instanceof Date && !isNaN(value.valueOf());
};
/**
* @param {?} match
* @return {?}
*/
IntlFormatter.isoStringToDate = /**
* @param {?} match
* @return {?}
*/
function (match) {
/** @type {?} */
var date = new Date(0);
/** @type {?} */
var tzHour = 0;
/** @type {?} */
var tzMin = 0;
/** @type {?} */
var dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear;
/** @type {?} */
var timeSetter = match[8] ? date.setUTCHours : date.setHours;
if (match[9]) {
tzHour = +(match[9] + match[10]);
tzMin = +(match[9] + match[11]);
}
dateSetter.call(date, +(match[1]), +(match[2]) - 1, +(match[3]));
/** @type {?} */
var h = +(match[4] || '0') - tzHour;
/** @type {?} */
var m = +(match[5] || '0') - tzMin;
/** @type {?} */
var s = +(match[6] || '0');
/** @type {?} */
var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
timeSetter.call(date, h, m, s, ms);
return date;
};
return IntlFormatter;
}());
/**
* @param {?} digits
* @return {?}
*/
function formatDigitsAliases(digits) {
/** @type {?} */
var parts = digits.match(NUMBER_FORMAT_REGEXP);
if (parts == null)
return null;
/** @type {?} */
var digitsOptions = {};
if (parts[1] != null) {
digitsOptions.minimumIntegerDigits = parseInt(parts[1]);
}
if (parts[3] != null) {
digitsOptions.minimumFractionDigits = parseInt(parts[3]);
}
if (parts[5] != null) {
digitsOptions.maximumFractionDigits = parseInt(parts[5]);
}
return digitsOptions;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* Manages language, default locale, currency & timezone.
*/
var LocaleService = /** @class */ (function () {
function LocaleService(configuration, storage) {
this.configuration = configuration;
this.storage = storage;
/**
* Fired when the language changes. Returns the language code.
*/
this.languageCodeChanged = new Subject();
/**
* Fired when the default locale changes. Returns the default locale.
*/
this.defaultLocaleChanged = new Subject();
/**
* Fired when the currency changes. Returns the currency code.
*/
this.currencyCodeChanged = new Subject();
/**
* Fired when the timezone changes. Returns the timezone.
*/
this.timezoneChanged = new Subject();
this.defaultLocale = new DefaultLocale();
}
/**
* @return {?}
*/
LocaleService.prototype.getConfiguration = /**
* @return {?}
*/
function () {
return this.configuration.locale;
};
/**
* @return {?}
*/
LocaleService.prototype.init = /**
* @return {?}
*/
function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.initLanguage()];
case 1:
_a.sent();
return [4 /*yield*/, this.initDefaultLocale()];
case 2:
_a.sent();
return [4 /*yield*/, this.initCurrency()];
case 3:
_a.sent();
return [4 /*yield*/, this.initTimezone()];
case 4:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* @return {?}
*/
LocaleService.prototype.getBrowserLanguage = /**
* @return {?}
*/
function () {
/** @type {?} */
var browserLanguage = null;
if (typeof navigator !== "undefined" && navigator.language) {
browserLanguage = navigator.language;
}
if (browserLanguage != null) {
browserLanguage = browserLanguage.split("-")[0];
}
return browserLanguage;
};
/**
* @return {?}
*/
LocaleService.prototype.getAvailableLanguages = /**
* @return {?}
*/
function () {
/** @type {?} */
var languages = [];
if (this.configuration.locale.languages) {
languages = this.configuration.locale.languages.map(function (language) { return language.code; });
}
return languages;
};
/**
* @param {?=} languageCode
* @return {?}
*/
LocaleService.prototype.getLanguageDirection = /**
* @param {?=} languageCode
* @return {?}
*/
function (languageCode) {
if (languageCode === void 0) { languageCode = this.defaultLocale.languageCode; }
/** @type {?} */
var matchedLanguage = this.matchLanguage(languageCode);
return matchedLanguage ? matchedLanguage.dir : "";
};
/**
* @return {?}
*/
LocaleService.prototype.getCurrentLanguage = /**
* @return {?}
*/
function () {
return this.defaultLocale.languageCode;
};
/**
* @return {?}
*/
LocaleService.prototype.getCurrentCountry = /**
* @return {?}
*/
function () {
return this.defaultLocale.countryCode || "";
};
/**
* @return {?}
*/
LocaleService.prototype.getCurrentScript = /**
* @return {?}
*/
function () {
return this.defaultLocale.scriptCode || "";
};
/**
* Returns the well formatted locale as {languageCode}[-scriptCode][-countryCode]
*/
/**
* Returns the well formatted locale as {languageCode}[-scriptCode][-countryCode]
* @return {?}
*/
LocaleService.prototype.getCurrentLocale = /**
* Returns the well formatted locale as {languageCode}[-scriptCode][-countryCode]
* @return {?}
*/
function () {
/** @type {?} */
var locale = this.defaultLocale.languageCode;
locale += !!this.defaultLocale.scriptCode ? "-" + this.defaultLocale.scriptCode : "";
locale += !!this.defaultLocale.countryCode ? "-" + this.defaultLocale.countryCode : "";
return locale;
};
/**
* @return {?}
*/
LocaleService.prototype.getCurrentNumberingSystem = /**
* @return {?}
*/
function () {
return this.defaultLocale.numberingSystem || "";
};
/**
* @return {?}
*/
LocaleService.prototype.getCurrentCalendar = /**
* @return {?}
*/
function () {
return this.defaultLocale.calendar || "";
};
/**
* @return {?}
*/
LocaleService.prototype.getDefaultLocale = /**
* @return {?}
*/
function () {
return this.defaultLocale.value;
};
/**
* @return {?}
*/
LocaleService.prototype.getCurrentCurrency = /**
* @return {?}
*/
function () {
return this.currencyCode;
};
/**
* @param {?} currencyDisplay
* @param {?=} defaultLocale
* @param {?=} currency
* @return {?}
*/
LocaleService.prototype.getCurrencySymbol = /**
* @param {?} currencyDisplay
* @param {?=} defaultLocale
* @param {?=} currency
* @return {?}
*/
function (currencyDisplay, defaultLocale, currency) {
/** @type {?} */
var currencySymbol = this.currencyCode;
if (IntlAPI.hasNumberFormat()) {
/** @type {?} */
var localeZero = this.formatDecimal(0, '1.0-0', defaultLocale);
/** @type {?} */
var localeValue = this.formatCurrency(0, '1.0-0', currencyDisplay, defaultLocale, currency);
currencySymbol = localeValue.replace(localeZero, "");
currencySymbol = currencySymbol.trim();
}
return currencySymbol;
};
/**
* @return {?}
*/
LocaleService.prototype.getCurrentTimezone = /**
* @return {?}
*/
function () {
return this.timezone;
};
/**
* @param {?} languageCode
* @return {?}
*/
LocaleService.prototype.setCurrentLanguage = /**
* @param {?} languageCode
* @return {?}
*/
function (languageCode) {
if (this.defaultLocale.languageCode != languageCode) {
this.rollbackLanguageCode = this.defaultLocale.languageCode;
this.defaultLocale.build(languageCode);
this.releaseLanguage();
}
};
/**
* @param {?} languageCode
* @param {?=} countryCode
* @param {?=} scriptCode
* @param {?=} numberingSystem
* @param {?=} calendar
* @return {?}
*/
LocaleService.prototype.setDefaultLocale = /**
* @param {?} languageCode
* @param {?=} countryCode
* @param {?=} scriptCode
* @param {?=} numberingSystem
* @param {?=} calendar
* @return {?}
*/
function (languageCode, countryCode, scriptCode, numberingSystem, calendar) {
if (this.defaultLocale.languageCode != languageCode ||
this.defaultLocale.countryCode != countryCode ||
this.defaultLocale.scriptCode != scriptCode ||
this.defaultLocale.numberingSystem != numberingSystem ||
this.defaultLocale.calendar != calendar) {
this.rollbackDefaultLocale = this.defaultLocale.value;
this.defaultLocale.build(languageCode, countryCode, scriptCode, numberingSystem, calendar);
this.releaseDefaultLocale();
}
};
/**
* @param {?} currencyCode
* @return {?}
*/
LocaleService.prototype.setCurrentCurrency = /**
* @param {?} currencyCode
* @return {?}
*/
function (currencyCode) {
if (this.currencyCode != currencyCode) {
this.rollbackCurrencyCode = this.currencyCode;
this.currencyCode = currencyCode;
this.releaseCurrency();
}
};
/**
* @param {?} zoneName
* @return {?}
*/
LocaleService.prototype.setCurrentTimezone = /**
* @param {?} zoneName
* @return {?}
*/
function (zoneName) {
if (this.timezone != zoneName) {
this.rollbackTimezone = this.timezone;
this.timezone = zoneName;
this.releaseTimezone();
}
};
/**
* Formats a date according to default locale.
* @param value A Date, a number (milliseconds since UTC epoch) or an ISO string
* @param format An alias or a DateTimeOptions object of the format. Default is 'mediumDate'
* @param defaultLocale The default locale to use. Default is the current locale
* @param timezone The time zone name. Default is the current timezone
*/
/**
* Formats a date according to default locale.
* @param {?} value A Date, a number (milliseconds since UTC epoch) or an ISO string
* @param {?=} format An alias or a DateTimeOptions object of the format. Default is 'mediumDate'
* @param {?=} defaultLocale The default locale to use. Default is the current locale
* @param {?=} timezone The time zone name. Default is the current timezone
* @return {?}
*/
LocaleService.prototype.formatDate = /**
* Formats a date according to default locale.
* @param {?} value A Date, a number (milliseconds since UTC epoch) or an ISO string
* @param {?=} format An alias or a DateTimeOptions object of the format. Default is 'mediumDate'
* @param {?=} defaultLocale The default locale to use. Default is the current locale
* @param {?=} timezone The time zone name. Default is the current timezone
* @return {?}
*/
function (value, format, defaultLocale, timezone) {
return IntlFormatter.formatDate(value, defaultLocale || this.defaultLocale.value, format || 'mediumDate', timezone || this.timezone);
};
/**
* Formats a relative time according to default locale.
* @param value Negative (or positive) number
* @param unit Unit of the value. Possible values are: 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'
* @param format RelativeTimeOptions object of the format
* @param defaultLocale The default locale to use. Default is the current locale
*/
/**
* Formats a relative time according to default locale.
* @param {?} value Negative (or positive) number
* @param {?} unit Unit of the value. Possible values are: 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'
* @param {?=} format RelativeTimeOptions object of the format
* @param {?=} defaultLocale The default locale to use. Default is the current locale
* @return {?}
*/
LocaleService.prototype.formatRelativeTime = /**
* Formats a relative time according to default locale.
* @param {?} value Negative (or positive) number
* @param {?} unit Unit of the value. Possible values are: 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'
* @param {?=} format RelativeTimeOptions object of the format
* @param {?=} defaultLocale The default locale to use. Default is the current locale
* @return {?}
*/
function (value, unit, format, defaultLocale) {
return IntlFormatter.formatRelativeTime(value, unit, defaultLocale || this.defaultLocale.value, format);
};
/**
* Formats a decimal number according to default locale.
* @param value The number to be formatted
* @param digits An alias or a DigitsOptions object of the format
* @param defaultLocale The default locale to use. Default is the current locale
*/
/**
* Formats a decimal number according to default locale.
* @param {?} value The number to be formatted
* @param {?=} digits An alias or a DigitsOptions object of the format
* @param {?=} defaultLocale The default locale to use. Default is the current locale
* @return {?}
*/
LocaleService.prototype.formatDecimal = /**
* Formats a decimal number according to default locale.
* @param {?} value The number to be formatted
* @param {?=} digits An alias or a DigitsOptions object of the format
* @param {?=} defaultLocale The default locale to use. Default is the current locale
* @return {?}
*/
function (value, digits, defaultLocale) {
return IntlFormatter.formatNumber(value, defaultLocale || this.defaultLocale.value, NumberFormatStyle.Decimal, digits);
};
/**
* Formats a number as a percentage according to default locale.
* @param value The number to be formatted
* @param digits An alias or a DigitsOptions object of the format
* @param defaultLocale The default locale to use. Default is the current locale
*/
/**
* Formats a number as a percentage according to default locale.
* @param {?} value The number to be formatted
* @param {?=} digits An alias or a DigitsOptions object of the format
* @param {?=} defaultLocale The default locale to use. Default is the current locale
* @return {?}
*/
LocaleService.prototype.formatPercent = /**
* Formats a number as a percentage according to default locale.
* @param {?} value The number to be formatted
* @param {?=} digits An alias or a DigitsOptions object of the format
* @param {?=} defaultLocale The default locale to use. Default is the current locale
* @return {?}
*/
function (value, digits, defaultLocale) {
return IntlFormatter.formatNumber(value, defaultLocale || this.defaultLocale.value, NumberFormatStyle.Percent, digits);
};
/**
* Formats a number as a currency according to default locale.
* @param value The number to be formatted
* @param digits An alias or a DigitsOptions object of the format
* @param currencyDisplay The format for the currency. Possible values are 'code', 'symbol', 'name'. Default is 'symbol'
* @param defaultLocale The default locale to use. Default is the current locale
* @param currency The currency to use. Default is the current currency
*/
/**
* Formats a number as a currency according to default locale.
* @param {?} value The number to be formatted
* @param {?=} digits An alias or a DigitsOptions object of the format
* @param {?=} currencyDisplay The format for the currency. Possible values are 'code', 'symbol', 'name'. Default is 'symbol'
* @param {?=} defaultLocale The default locale to use. Default is the current locale
* @param {?=} currency The currency to use. Default is the current currency
* @return {?}
*/
LocaleService.prototype.formatCurrency = /**
* Formats a number as a currency according to default locale.
* @param {?} value The number to be formatted
* @param {?=} digits An alias or a DigitsOptions object of the format
* @param {?=} currencyDisplay The format for the currency. Possible values are 'code', 'symbol', 'name'. Default is 'symbol'
* @param {?=} defaultLocale The default locale to use. Default is the current locale
* @param {?=} currency The currency to use. Default is the current currency
* @return {?}
*/
function (value, digits, currencyDisplay, defaultLocale, currency) {
return IntlFormatter.formatNumber(value, defaultLocale || this.defaultLocale.value, NumberFormatStyle.Currency, digits, currency || this.currencyCode, currencyDisplay || 'symbol');
};
/**
* @param {?} codes
* @return {?}
*/
LocaleService.prototype.composeLocale = /**
* @param {?} codes
* @return {?}
*/
function (codes) {
/** @type {?} */
var locale = "";
if (this.defaultLocale.languageCode) {
for (var _i = 0, codes_1 = codes; _i < codes_1.length; _i++) {
var code = codes_1[_i];
switch (code) {
case ISOCode.Script:
locale += "-" + this.defaultLocale.scriptCode;
break;
case ISOCode.Country:
locale += "-" + this.defaultLocale.countryCode;
break;
default:
locale += this.defaultLocale.languageCode;
}
}
}
return locale;
};
/**
* Rollbacks to previous language, default locale, currency & timezone.
*/
/**
* Rollbacks to previous language, default locale, currency & timezone.
* @return {?}
*/
LocaleService.prototype.rollback = /**
* Rollbacks to previous language, default locale, currency & timezone.
* @return {?}
*/
function () {
if (this.rollbackLanguageCode && this.rollbackLanguageCode != this.defaultLocale.languageCode) {
this.defaultLocale.value = this.rollbackLanguageCode;
this.releaseLanguage();
}
if (this.rollbackDefaultLocale && this.rollbackDefaultLocale != this.defaultLocale.value) {
this.defaultLocale.value = this.rollbackDefaultLocale;
this.releaseDefaultLocale();
}
if (this.rollbackCurrencyCode && this.rollbackCurrencyCode != this.currencyCode) {
this.currencyCode = this.rollbackCurrencyCode;
this.releaseCurrency();
}
if (this.rollbackTimezone && this.rollbackTimezone != this.timezone) {
this.timezone = this.rollbackTimezone;
this.releaseTimezone();
}
};
/**
* @return {?}
*/
LocaleService.prototype.initLanguage = /**
* @return {?}
*/
function () {
return __awaiter(this, void 0, void 0, function () {
var defaultLocale, browserLanguage, matchedLanguage;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.configuration.locale.language) return [3 /*break*/, 2];
if (!!this.defaultLocale.languageCode) return [3 /*break*/, 2];
// Tries to get the language from the storage.
return [4 /*yield*/, this.storage.read("defaultLocale")];
case 1:
defaultLocale = _a.sent();
if (!!defaultLocale) {
this.defaultLocale.value = defaultLocale;
}
else {
// Tries to get the language from the browser.
browserLanguage = this.getBrowserLanguage();
matchedLanguage = this.matchLanguage(browserLanguage);
if (!!browserLanguage && matchedLanguage) {
this.defaultLocale.build(browserLanguage);
}
else {
// Uses the language set in the configuration.
this.defaultLocale.build(this.configuration.locale.language);
}
this.storage.write("defaultLocale", this.defaultLocale.value);
}
this.rollbackLanguageCode = this.defaultLocale.languageCode;
this.sendLanguageEvents();
_a.label = 2;
case 2: return [2 /*return*/];
}
});
});
};
/**
* @return {?}
*/
LocaleService.prototype.initDefaultLocale = /**
* @return {?}
*/
function () {
return __awaiter(this, void 0, void 0, function () {
var defaultLocale;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.configuration.locale.defaultLocale) return [3 /*break*/, 2];
if (!!this.defaultLocale.value) return [3 /*break*/, 2];
return [4 /*yield*/, this.storage.read("defaultLocale")];
case 1:
defaultLocale = _a.sent();
if (!!defaultLocale) {
this.defaultLocale.value = defaultLocale;
}
else {
this.defaultLocale.build(this.configuration.locale.defaultLocale.languageCode, this.configuration.locale.defaultLocale.countryCode, this.configuration.locale.defaultLocale.scriptCode, this.configuration.locale.defaultLocale.numberingSystem, this.configuration.locale.defaultLocale.calendar);
this.storage.write("defaultLocale", this.defaultLocale.value);
}
this.rollbackDefaultLocale = this.defaultLocale.value;
this.sendDefaultLocaleEvents();
_a.label = 2;
case 2: return [2 /*return*/];
}
});
});
};
/**
* @return {?}
*/