angular-l10n
Version:
An Angular library to translate messages, dates and numbers
1,317 lines (1,298 loc) • 209 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('rxjs'), require('@angular/router'), require('@angular/common'), require('rxjs/operators'), require('@angular/common/http'), require('@angular/platform-browser'), require('@angular/forms')) :
typeof define === 'function' && define.amd ? define('angular-l10n', ['exports', '@angular/core', 'rxjs', '@angular/router', '@angular/common', 'rxjs/operators', '@angular/common/http', '@angular/platform-browser', '@angular/forms'], factory) :
(global = global || self, factory((global.ng = global.ng || {}, global.ng.l10n = {}), global.ng.core, global.rxjs, global.ng.router, global.ng.common, global.rxjs.operators, global.ng.commmon.http, global.ng.platformBrowser, global.ng.forms));
}(this, function (exports, core, rxjs, router, common, operators, http, platformBrowser, forms) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
/**
* @license Angular l10n
* Copyright Roberto Simonetti
* MIT license
* https://github.com/robisim74/angular-l10n
*/
/**
* @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 = core.Injector.NULL;
InjectorRef.decorators = [
{ type: core.Injectable }
];
/** @nocollapse */
InjectorRef.ctorParameters = function () { return [
{ type: core.Injector }
]; };
return InjectorRef;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** @type {?} */
var L10N_CONFIG = new core.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 rxjs.ReplaySubject();
Logger.decorators = [
{ type: core.Injectable }
];
/** @nocollapse */
Logger.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: core.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 rxjs.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: core.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: core.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: core.Injectable }
];
/** @nocollapse */
L10nStorage.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: core.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 rxjs.Subject();
/**
* Fired when the default locale changes. Returns the default locale.
*/
this.defaultLocaleChanged = new rxjs.Subject();
/**
* Fired when the currency changes. Returns the currency code.
*/
this.currencyCodeChanged = new rxjs.Subject();
/**
* Fired when the timezone changes. Returns the timezone.
*/
this.timezoneChanged = new rxjs.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 {?=