| Server IP : 157.230.181.24 / Your IP : 216.73.217.11 Web Server : Apache/2.4.58 (Ubuntu) System : Linux conductive 6.8.0-117-generic #117-Ubuntu SMP PREEMPT_DYNAMIC Tue May 5 19:26:24 UTC 2026 x86_64 User : ( 1000) PHP Version : 8.3.31 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : OFF Directory : /var/www/vhosts/dev-conductive-digital/public/kove/ |
Upload File : |
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["vendor"],{
/***/ "./node_modules/@angular/common/__ivy_ngcc__/fesm2015/common.js":
/*!**********************************************************************!*\
!*** ./node_modules/@angular/common/__ivy_ngcc__/fesm2015/common.js ***!
\**********************************************************************/
/*! exports provided: APP_BASE_HREF, AsyncPipe, CommonModule, CurrencyPipe, DOCUMENT, DatePipe, DecimalPipe, FormStyle, FormatWidth, HashLocationStrategy, I18nPluralPipe, I18nSelectPipe, JsonPipe, KeyValuePipe, LOCATION_INITIALIZED, Location, LocationStrategy, LowerCasePipe, NgClass, NgComponentOutlet, NgForOf, NgForOfContext, NgIf, NgIfContext, NgLocaleLocalization, NgLocalization, NgPlural, NgPluralCase, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet, NumberFormatStyle, NumberSymbol, PathLocationStrategy, PercentPipe, PlatformLocation, Plural, SlicePipe, TitleCasePipe, TranslationWidth, UpperCasePipe, VERSION, ViewportScroller, WeekDay, formatCurrency, formatDate, formatNumber, formatPercent, getCurrencySymbol, getLocaleCurrencyCode, getLocaleCurrencyName, getLocaleCurrencySymbol, getLocaleDateFormat, getLocaleDateTimeFormat, getLocaleDayNames, getLocaleDayPeriods, getLocaleDirection, getLocaleEraNames, getLocaleExtraDayPeriodRules, getLocaleExtraDayPeriods, getLocaleFirstDayOfWeek, getLocaleId, getLocaleMonthNames, getLocaleNumberFormat, getLocaleNumberSymbol, getLocalePluralCase, getLocaleTimeFormat, getLocaleWeekEndRange, getNumberOfCurrencyDigits, isPlatformBrowser, isPlatformServer, isPlatformWorkerApp, isPlatformWorkerUi, registerLocaleData, ɵBrowserPlatformLocation, ɵDomAdapter, ɵNullViewportScroller, ɵPLATFORM_BROWSER_ID, ɵPLATFORM_SERVER_ID, ɵPLATFORM_WORKER_APP_ID, ɵPLATFORM_WORKER_UI_ID, ɵangular_packages_common_common_a, ɵangular_packages_common_common_b, ɵangular_packages_common_common_c, ɵangular_packages_common_common_d, ɵangular_packages_common_common_e, ɵangular_packages_common_common_f, ɵgetDOM, ɵparseCookieValue, ɵsetRootDomAdapter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_BASE_HREF", function() { return APP_BASE_HREF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncPipe", function() { return AsyncPipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CommonModule", function() { return CommonModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CurrencyPipe", function() { return CurrencyPipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DOCUMENT", function() { return DOCUMENT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DatePipe", function() { return DatePipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DecimalPipe", function() { return DecimalPipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormStyle", function() { return FormStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormatWidth", function() { return FormatWidth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HashLocationStrategy", function() { return HashLocationStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "I18nPluralPipe", function() { return I18nPluralPipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "I18nSelectPipe", function() { return I18nSelectPipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JsonPipe", function() { return JsonPipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyValuePipe", function() { return KeyValuePipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LOCATION_INITIALIZED", function() { return LOCATION_INITIALIZED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationStrategy", function() { return LocationStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LowerCasePipe", function() { return LowerCasePipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgClass", function() { return NgClass; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgComponentOutlet", function() { return NgComponentOutlet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgForOf", function() { return NgForOf; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgForOfContext", function() { return NgForOfContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgIf", function() { return NgIf; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgIfContext", function() { return NgIfContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgLocaleLocalization", function() { return NgLocaleLocalization; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgLocalization", function() { return NgLocalization; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgPlural", function() { return NgPlural; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgPluralCase", function() { return NgPluralCase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgStyle", function() { return NgStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgSwitch", function() { return NgSwitch; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgSwitchCase", function() { return NgSwitchCase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgSwitchDefault", function() { return NgSwitchDefault; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgTemplateOutlet", function() { return NgTemplateOutlet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NumberFormatStyle", function() { return NumberFormatStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NumberSymbol", function() { return NumberSymbol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PathLocationStrategy", function() { return PathLocationStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PercentPipe", function() { return PercentPipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlatformLocation", function() { return PlatformLocation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Plural", function() { return Plural; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SlicePipe", function() { return SlicePipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TitleCasePipe", function() { return TitleCasePipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TranslationWidth", function() { return TranslationWidth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UpperCasePipe", function() { return UpperCasePipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return VERSION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViewportScroller", function() { return ViewportScroller; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WeekDay", function() { return WeekDay; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatCurrency", function() { return formatCurrency; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatDate", function() { return formatDate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatNumber", function() { return formatNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatPercent", function() { return formatPercent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCurrencySymbol", function() { return getCurrencySymbol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleCurrencyCode", function() { return getLocaleCurrencyCode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleCurrencyName", function() { return getLocaleCurrencyName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleCurrencySymbol", function() { return getLocaleCurrencySymbol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleDateFormat", function() { return getLocaleDateFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleDateTimeFormat", function() { return getLocaleDateTimeFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleDayNames", function() { return getLocaleDayNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleDayPeriods", function() { return getLocaleDayPeriods; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleDirection", function() { return getLocaleDirection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleEraNames", function() { return getLocaleEraNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleExtraDayPeriodRules", function() { return getLocaleExtraDayPeriodRules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleExtraDayPeriods", function() { return getLocaleExtraDayPeriods; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleFirstDayOfWeek", function() { return getLocaleFirstDayOfWeek; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleId", function() { return getLocaleId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleMonthNames", function() { return getLocaleMonthNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleNumberFormat", function() { return getLocaleNumberFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleNumberSymbol", function() { return getLocaleNumberSymbol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocalePluralCase", function() { return getLocalePluralCase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleTimeFormat", function() { return getLocaleTimeFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleWeekEndRange", function() { return getLocaleWeekEndRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNumberOfCurrencyDigits", function() { return getNumberOfCurrencyDigits; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPlatformBrowser", function() { return isPlatformBrowser; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPlatformServer", function() { return isPlatformServer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPlatformWorkerApp", function() { return isPlatformWorkerApp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPlatformWorkerUi", function() { return isPlatformWorkerUi; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerLocaleData", function() { return registerLocaleData; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵBrowserPlatformLocation", function() { return BrowserPlatformLocation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵDomAdapter", function() { return DomAdapter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNullViewportScroller", function() { return NullViewportScroller; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵPLATFORM_BROWSER_ID", function() { return PLATFORM_BROWSER_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵPLATFORM_SERVER_ID", function() { return PLATFORM_SERVER_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵPLATFORM_WORKER_APP_ID", function() { return PLATFORM_WORKER_APP_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵPLATFORM_WORKER_UI_ID", function() { return PLATFORM_WORKER_UI_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_common_common_a", function() { return useBrowserPlatformLocation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_common_common_b", function() { return createBrowserPlatformLocation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_common_common_c", function() { return createLocation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_common_common_d", function() { return provideLocationStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_common_common_e", function() { return COMMON_DIRECTIVES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_common_common_f", function() { return COMMON_PIPES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetDOM", function() { return getDOM; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵparseCookieValue", function() { return parseCookieValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵsetRootDomAdapter", function() { return setRootDomAdapter; });
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js");
/**
* @license Angular v9.1.13
* (c) 2010-2020 Google LLC. https://angular.io/
* License: MIT
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/dom_adapter.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @type {?} */
let _DOM = (/** @type {?} */ (null));
/**
* @return {?}
*/
function getDOM() {
return _DOM;
}
/**
* @param {?} adapter
* @return {?}
*/
function setDOM(adapter) {
_DOM = adapter;
}
/**
* @param {?} adapter
* @return {?}
*/
function setRootDomAdapter(adapter) {
if (!_DOM) {
_DOM = adapter;
}
}
/* tslint:disable:requireParameterType */
/**
* Provides DOM operations in an environment-agnostic way.
*
* \@security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
* @abstract
*/
class DomAdapter {
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/dom_tokens.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A DI Token representing the main rendering context. In a browser this is the DOM Document.
*
* Note: Document might not be available in the Application Context when Application and Rendering
* Contexts are not the same (e.g. when running the application in a Web Worker).
*
* \@publicApi
* @type {?}
*/
const DOCUMENT = new _angular_core__WEBPACK_IMPORTED_MODULE_0__["InjectionToken"]('DocumentToken');
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/location/platform_location.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* This class should not be used directly by an application developer. Instead, use
* {\@link Location}.
*
* `PlatformLocation` encapsulates all calls to DOM APIs, which allows the Router to be
* platform-agnostic.
* This means that we can have different implementation of `PlatformLocation` for the different
* platforms that Angular supports. For example, `\@angular/platform-browser` provides an
* implementation specific to the browser environment, while `\@angular/platform-server` provides
* one suitable for use with server-side rendering.
*
* The `PlatformLocation` class is used directly by all implementations of {\@link LocationStrategy}
* when they need to interact with the DOM APIs like pushState, popState, etc.
*
* {\@link LocationStrategy} in turn is used by the {\@link Location} service which is used directly
* by the {\@link Router} in order to navigate between routes. Since all interactions between {\@link
* Router} /
* {\@link Location} / {\@link LocationStrategy} and DOM APIs flow through the `PlatformLocation`
* class, they are all platform-agnostic.
*
* \@publicApi
* @abstract
*/
class PlatformLocation {
}
PlatformLocation.ɵfac = function PlatformLocation_Factory(t) { return new (t || PlatformLocation)(); };
/** @nocollapse */ PlatformLocation.ɵprov = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"])({ factory: useBrowserPlatformLocation, token: PlatformLocation, providedIn: "platform" });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](PlatformLocation, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injectable"],
args: [{
providedIn: 'platform',
// See #23917
useFactory: useBrowserPlatformLocation
}]
}], null, null); })();
if (false) {}
/**
* @return {?}
*/
function useBrowserPlatformLocation() {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(BrowserPlatformLocation);
}
/**
* \@description
* Indicates when a location is initialized.
*
* \@publicApi
* @type {?}
*/
const LOCATION_INITIALIZED = new _angular_core__WEBPACK_IMPORTED_MODULE_0__["InjectionToken"]('Location Initialized');
/**
* \@description
* A serializable version of the event from `onPopState` or `onHashChange`
*
* \@publicApi
* @record
*/
function LocationChangeEvent() { }
if (false) {}
/**
* \@publicApi
* @record
*/
function LocationChangeListener() { }
/**
* `PlatformLocation` encapsulates all of the direct calls to platform APIs.
* This class should not be used directly by an application developer. Instead, use
* {\@link Location}.
*/
class BrowserPlatformLocation extends PlatformLocation {
/**
* @param {?} _doc
*/
constructor(_doc) {
super();
this._doc = _doc;
this._init();
}
// This is moved to its own method so that `MockPlatformLocationStrategy` can overwrite it
/**
* \@internal
* @return {?}
*/
_init() {
((/** @type {?} */ (this))).location = getDOM().getLocation();
this._history = getDOM().getHistory();
}
/**
* @return {?}
*/
getBaseHrefFromDOM() {
return (/** @type {?} */ (getDOM().getBaseHref(this._doc)));
}
/**
* @param {?} fn
* @return {?}
*/
onPopState(fn) {
getDOM().getGlobalEventTarget(this._doc, 'window').addEventListener('popstate', fn, false);
}
/**
* @param {?} fn
* @return {?}
*/
onHashChange(fn) {
getDOM().getGlobalEventTarget(this._doc, 'window').addEventListener('hashchange', fn, false);
}
/**
* @return {?}
*/
get href() {
return this.location.href;
}
/**
* @return {?}
*/
get protocol() {
return this.location.protocol;
}
/**
* @return {?}
*/
get hostname() {
return this.location.hostname;
}
/**
* @return {?}
*/
get port() {
return this.location.port;
}
/**
* @return {?}
*/
get pathname() {
return this.location.pathname;
}
/**
* @return {?}
*/
get search() {
return this.location.search;
}
/**
* @return {?}
*/
get hash() {
return this.location.hash;
}
/**
* @param {?} newPath
* @return {?}
*/
set pathname(newPath) {
this.location.pathname = newPath;
}
/**
* @param {?} state
* @param {?} title
* @param {?} url
* @return {?}
*/
pushState(state, title, url) {
if (supportsState()) {
this._history.pushState(state, title, url);
}
else {
this.location.hash = url;
}
}
/**
* @param {?} state
* @param {?} title
* @param {?} url
* @return {?}
*/
replaceState(state, title, url) {
if (supportsState()) {
this._history.replaceState(state, title, url);
}
else {
this.location.hash = url;
}
}
/**
* @return {?}
*/
forward() {
this._history.forward();
}
/**
* @return {?}
*/
back() {
this._history.back();
}
/**
* @return {?}
*/
getState() {
return this._history.state;
}
}
BrowserPlatformLocation.ɵfac = function BrowserPlatformLocation_Factory(t) { return new (t || BrowserPlatformLocation)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](DOCUMENT)); };
/** @nocollapse */
BrowserPlatformLocation.ctorParameters = () => [
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [DOCUMENT,] }] }
];
/** @nocollapse */ BrowserPlatformLocation.ɵprov = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"])({ factory: createBrowserPlatformLocation, token: BrowserPlatformLocation, providedIn: "platform" });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](BrowserPlatformLocation, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injectable"],
args: [{
providedIn: 'platform',
// See #23917
useFactory: createBrowserPlatformLocation
}]
}], function () { return [{ type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"],
args: [DOCUMENT]
}] }]; }, null); })();
if (false) {}
/**
* @return {?}
*/
function supportsState() {
return !!window.history.pushState;
}
/**
* @return {?}
*/
function createBrowserPlatformLocation() {
return new BrowserPlatformLocation(Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(DOCUMENT));
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/private_export.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/location/util.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Joins two parts of a URL with a slash if needed.
*
* @param {?} start URL string
* @param {?} end URL string
*
*
* @return {?} The joined URL string.
*/
function joinWithSlash(start, end) {
if (start.length == 0) {
return end;
}
if (end.length == 0) {
return start;
}
/** @type {?} */
let slashes = 0;
if (start.endsWith('/')) {
slashes++;
}
if (end.startsWith('/')) {
slashes++;
}
if (slashes == 2) {
return start + end.substring(1);
}
if (slashes == 1) {
return start + end;
}
return start + '/' + end;
}
/**
* Removes a trailing slash from a URL string if needed.
* Looks for the first occurrence of either `#`, `?`, or the end of the
* line as `/` characters and removes the trailing slash if one exists.
*
* @param {?} url URL string.
*
* @return {?} The URL string, modified if needed.
*/
function stripTrailingSlash(url) {
/** @type {?} */
const match = url.match(/#|\?|$/);
/** @type {?} */
const pathEndIdx = match && match.index || url.length;
/** @type {?} */
const droppedSlashIdx = pathEndIdx - (url[pathEndIdx - 1] === '/' ? 1 : 0);
return url.slice(0, droppedSlashIdx) + url.slice(pathEndIdx);
}
/**
* Normalizes URL parameters by prepending with `?` if needed.
*
* @param {?} params String of URL parameters.
*
* @return {?} The normalized URL parameters string.
*/
function normalizeQueryParams(params) {
return params && params[0] !== '?' ? '?' + params : params;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/location/location_strategy.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Enables the `Location` service to read route state from the browser's URL.
* Angular provides two strategies:
* `HashLocationStrategy` and `PathLocationStrategy`.
*
* Applications should use the `Router` or `Location` services to
* interact with application route state.
*
* For instance, `HashLocationStrategy` produces URLs like
* <code class="no-auto-link">http://example.com#/foo</code>,
* and `PathLocationStrategy` produces
* <code class="no-auto-link">http://example.com/foo</code> as an equivalent URL.
*
* See these two classes for more.
*
* \@publicApi
* @abstract
*/
class LocationStrategy {
}
LocationStrategy.ɵfac = function LocationStrategy_Factory(t) { return new (t || LocationStrategy)(); };
/** @nocollapse */ LocationStrategy.ɵprov = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"])({ factory: provideLocationStrategy, token: LocationStrategy, providedIn: "root" });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](LocationStrategy, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injectable"],
args: [{ providedIn: 'root', useFactory: provideLocationStrategy }]
}], null, null); })();
if (false) {}
/**
* @param {?} platformLocation
* @return {?}
*/
function provideLocationStrategy(platformLocation) {
// See #23917
/** @type {?} */
const location = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(DOCUMENT).location;
return new PathLocationStrategy(Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])((/** @type {?} */ (PlatformLocation))), location && location.origin || '');
}
/**
* A predefined [DI token](guide/glossary#di-token) for the base href
* to be used with the `PathLocationStrategy`.
* The base href is the URL prefix that should be preserved when generating
* and recognizing URLs.
*
* \@usageNotes
*
* The following example shows how to use this token to configure the root app injector
* with a base href value, so that the DI framework can supply the dependency anywhere in the app.
*
* ```typescript
* import {Component, NgModule} from '\@angular/core';
* import {APP_BASE_HREF} from '\@angular/common';
*
* \@NgModule({
* providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
* })
* class AppModule {}
* ```
*
* \@publicApi
* @type {?}
*/
const APP_BASE_HREF = new _angular_core__WEBPACK_IMPORTED_MODULE_0__["InjectionToken"]('appBaseHref');
/**
* \@description
* A {\@link LocationStrategy} used to configure the {\@link Location} service to
* represent its state in the
* [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the
* browser's URL.
*
* If you're using `PathLocationStrategy`, you must provide a {\@link APP_BASE_HREF}
* or add a base element to the document. This URL prefix that will be preserved
* when generating and recognizing URLs.
*
* For instance, if you provide an `APP_BASE_HREF` of `'/my/app'` and call
* `location.go('/foo')`, the browser's URL will become
* `example.com/my/app/foo`.
*
* Similarly, if you add `<base href='/my/app'/>` to the document and call
* `location.go('/foo')`, the browser's URL will become
* `example.com/my/app/foo`.
*
* \@usageNotes
*
* ### Example
*
* {\@example common/location/ts/path_location_component.ts region='LocationComponent'}
*
* \@publicApi
*/
class PathLocationStrategy extends LocationStrategy {
/**
* @param {?} _platformLocation
* @param {?=} href
*/
constructor(_platformLocation, href) {
super();
this._platformLocation = _platformLocation;
if (href == null) {
href = this._platformLocation.getBaseHrefFromDOM();
}
if (href == null) {
throw new Error(`No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.`);
}
this._baseHref = href;
}
/**
* @param {?} fn
* @return {?}
*/
onPopState(fn) {
this._platformLocation.onPopState(fn);
this._platformLocation.onHashChange(fn);
}
/**
* @return {?}
*/
getBaseHref() {
return this._baseHref;
}
/**
* @param {?} internal
* @return {?}
*/
prepareExternalUrl(internal) {
return joinWithSlash(this._baseHref, internal);
}
/**
* @param {?=} includeHash
* @return {?}
*/
path(includeHash = false) {
/** @type {?} */
const pathname = this._platformLocation.pathname + normalizeQueryParams(this._platformLocation.search);
/** @type {?} */
const hash = this._platformLocation.hash;
return hash && includeHash ? `${pathname}${hash}` : pathname;
}
/**
* @param {?} state
* @param {?} title
* @param {?} url
* @param {?} queryParams
* @return {?}
*/
pushState(state, title, url, queryParams) {
/** @type {?} */
const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams));
this._platformLocation.pushState(state, title, externalUrl);
}
/**
* @param {?} state
* @param {?} title
* @param {?} url
* @param {?} queryParams
* @return {?}
*/
replaceState(state, title, url, queryParams) {
/** @type {?} */
const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams));
this._platformLocation.replaceState(state, title, externalUrl);
}
/**
* @return {?}
*/
forward() {
this._platformLocation.forward();
}
/**
* @return {?}
*/
back() {
this._platformLocation.back();
}
}
PathLocationStrategy.ɵfac = function PathLocationStrategy_Factory(t) { return new (t || PathLocationStrategy)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](PlatformLocation), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](APP_BASE_HREF, 8)); };
PathLocationStrategy.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({ token: PathLocationStrategy, factory: PathLocationStrategy.ɵfac });
/** @nocollapse */
PathLocationStrategy.ctorParameters = () => [
{ type: PlatformLocation },
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Optional"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [APP_BASE_HREF,] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](PathLocationStrategy, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injectable"]
}], function () { return [{ type: PlatformLocation }, { type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Optional"]
}, {
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"],
args: [APP_BASE_HREF]
}] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/location/hash_location_strategy.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@description
* A {\@link LocationStrategy} used to configure the {\@link Location} service to
* represent its state in the
* [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax)
* of the browser's URL.
*
* For instance, if you call `location.go('/foo')`, the browser's URL will become
* `example.com#/foo`.
*
* \@usageNotes
*
* ### Example
*
* {\@example common/location/ts/hash_location_component.ts region='LocationComponent'}
*
* \@publicApi
*/
class HashLocationStrategy extends LocationStrategy {
/**
* @param {?} _platformLocation
* @param {?=} _baseHref
*/
constructor(_platformLocation, _baseHref) {
super();
this._platformLocation = _platformLocation;
this._baseHref = '';
if (_baseHref != null) {
this._baseHref = _baseHref;
}
}
/**
* @param {?} fn
* @return {?}
*/
onPopState(fn) {
this._platformLocation.onPopState(fn);
this._platformLocation.onHashChange(fn);
}
/**
* @return {?}
*/
getBaseHref() {
return this._baseHref;
}
/**
* @param {?=} includeHash
* @return {?}
*/
path(includeHash = false) {
// the hash value is always prefixed with a `#`
// and if it is empty then it will stay empty
/** @type {?} */
let path = this._platformLocation.hash;
if (path == null)
path = '#';
return path.length > 0 ? path.substring(1) : path;
}
/**
* @param {?} internal
* @return {?}
*/
prepareExternalUrl(internal) {
/** @type {?} */
const url = joinWithSlash(this._baseHref, internal);
return url.length > 0 ? ('#' + url) : url;
}
/**
* @param {?} state
* @param {?} title
* @param {?} path
* @param {?} queryParams
* @return {?}
*/
pushState(state, title, path, queryParams) {
/** @type {?} */
let url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams));
if (url.length == 0) {
url = this._platformLocation.pathname;
}
this._platformLocation.pushState(state, title, url);
}
/**
* @param {?} state
* @param {?} title
* @param {?} path
* @param {?} queryParams
* @return {?}
*/
replaceState(state, title, path, queryParams) {
/** @type {?} */
let url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams));
if (url.length == 0) {
url = this._platformLocation.pathname;
}
this._platformLocation.replaceState(state, title, url);
}
/**
* @return {?}
*/
forward() {
this._platformLocation.forward();
}
/**
* @return {?}
*/
back() {
this._platformLocation.back();
}
}
HashLocationStrategy.ɵfac = function HashLocationStrategy_Factory(t) { return new (t || HashLocationStrategy)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](PlatformLocation), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](APP_BASE_HREF, 8)); };
HashLocationStrategy.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({ token: HashLocationStrategy, factory: HashLocationStrategy.ɵfac });
/** @nocollapse */
HashLocationStrategy.ctorParameters = () => [
{ type: PlatformLocation },
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Optional"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [APP_BASE_HREF,] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](HashLocationStrategy, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injectable"]
}], function () { return [{ type: PlatformLocation }, { type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Optional"]
}, {
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"],
args: [APP_BASE_HREF]
}] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/location/location.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@publicApi
* @record
*/
function PopStateEvent() { }
if (false) {}
/**
* \@description
*
* A service that applications can use to interact with a browser's URL.
*
* Depending on the `LocationStrategy` used, `Location` persists
* to the URL's path or the URL's hash segment.
*
* \@usageNotes
*
* It's better to use the `Router#navigate` service to trigger route changes. Use
* `Location` only if you need to interact with or create normalized URLs outside of
* routing.
*
* `Location` is responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*
* ### Example
*
* <code-example path='common/location/ts/path_location_component.ts'
* region='LocationComponent'></code-example>
*
* \@publicApi
*/
class Location {
/**
* @param {?} platformStrategy
* @param {?} platformLocation
*/
constructor(platformStrategy, platformLocation) {
/**
* \@internal
*/
this._subject = new _angular_core__WEBPACK_IMPORTED_MODULE_0__["EventEmitter"]();
/**
* \@internal
*/
this._urlChangeListeners = [];
this._platformStrategy = platformStrategy;
/** @type {?} */
const browserBaseHref = this._platformStrategy.getBaseHref();
this._platformLocation = platformLocation;
this._baseHref = stripTrailingSlash(_stripIndexHtml(browserBaseHref));
this._platformStrategy.onPopState((/**
* @param {?} ev
* @return {?}
*/
(ev) => {
this._subject.emit({
'url': this.path(true),
'pop': true,
'state': ev.state,
'type': ev.type,
});
}));
}
/**
* Normalizes the URL path for this location.
*
* @param {?=} includeHash True to include an anchor fragment in the path.
*
* @return {?} The normalized URL path.
*/
// TODO: vsavkin. Remove the boolean flag and always include hash once the deprecated router is
// removed.
path(includeHash = false) {
return this.normalize(this._platformStrategy.path(includeHash));
}
/**
* Reports the current state of the location history.
* @return {?} The current value of the `history.state` object.
*/
getState() {
return this._platformLocation.getState();
}
/**
* Normalizes the given path and compares to the current normalized path.
*
* @param {?} path The given URL path.
* @param {?=} query Query parameters.
*
* @return {?} True if the given URL path is equal to the current normalized path, false
* otherwise.
*/
isCurrentPathEqualTo(path, query = '') {
return this.path() == this.normalize(path + normalizeQueryParams(query));
}
/**
* Normalizes a URL path by stripping any trailing slashes.
*
* @param {?} url String representing a URL.
*
* @return {?} The normalized URL string.
*/
normalize(url) {
return Location.stripTrailingSlash(_stripBaseHref(this._baseHref, _stripIndexHtml(url)));
}
/**
* Normalizes an external URL path.
* If the given URL doesn't begin with a leading slash (`'/'`), adds one
* before normalizing. Adds a hash if `HashLocationStrategy` is
* in use, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use.
*
* @param {?} url String representing a URL.
*
* @return {?} A normalized platform-specific URL.
*/
prepareExternalUrl(url) {
if (url && url[0] !== '/') {
url = '/' + url;
}
return this._platformStrategy.prepareExternalUrl(url);
}
// TODO: rename this method to pushState
/**
* Changes the browser's URL to a normalized version of a given URL, and pushes a
* new item onto the platform's history.
*
* @param {?} path URL path to normalize.
* @param {?=} query Query parameters.
* @param {?=} state Location history state.
*
* @return {?}
*/
go(path, query = '', state = null) {
this._platformStrategy.pushState(state, '', path, query);
this._notifyUrlChangeListeners(this.prepareExternalUrl(path + normalizeQueryParams(query)), state);
}
/**
* Changes the browser's URL to a normalized version of the given URL, and replaces
* the top item on the platform's history stack.
*
* @param {?} path URL path to normalize.
* @param {?=} query Query parameters.
* @param {?=} state Location history state.
* @return {?}
*/
replaceState(path, query = '', state = null) {
this._platformStrategy.replaceState(state, '', path, query);
this._notifyUrlChangeListeners(this.prepareExternalUrl(path + normalizeQueryParams(query)), state);
}
/**
* Navigates forward in the platform's history.
* @return {?}
*/
forward() {
this._platformStrategy.forward();
}
/**
* Navigates back in the platform's history.
* @return {?}
*/
back() {
this._platformStrategy.back();
}
/**
* Registers a URL change listener. Use to catch updates performed by the Angular
* framework that are not detectible through "popstate" or "hashchange" events.
*
* @param {?} fn The change handler function, which take a URL and a location history state.
* @return {?}
*/
onUrlChange(fn) {
this._urlChangeListeners.push(fn);
this.subscribe((/**
* @param {?} v
* @return {?}
*/
v => {
this._notifyUrlChangeListeners(v.url, v.state);
}));
}
/**
* \@internal
* @param {?=} url
* @param {?=} state
* @return {?}
*/
_notifyUrlChangeListeners(url = '', state) {
this._urlChangeListeners.forEach((/**
* @param {?} fn
* @return {?}
*/
fn => fn(url, state)));
}
/**
* Subscribes to the platform's `popState` events.
*
* @param {?} onNext
* @param {?=} onThrow
* @param {?=} onReturn
* @return {?} Subscribed events.
*/
subscribe(onNext, onThrow, onReturn) {
return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });
}
}
Location.ɵfac = function Location_Factory(t) { return new (t || Location)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](LocationStrategy), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](PlatformLocation)); };
/**
* Normalizes URL parameters by prepending with `?` if needed.
*
* @param params String of URL parameters.
*
* @return The normalized URL parameters string.
*/
Location.normalizeQueryParams = normalizeQueryParams;
/**
* Joins two parts of a URL with a slash if needed.
*
* @param start URL string
* @param end URL string
*
*
* @return The joined URL string.
*/
Location.joinWithSlash = joinWithSlash;
/**
* Removes a trailing slash from a URL string if needed.
* Looks for the first occurrence of either `#`, `?`, or the end of the
* line as `/` characters and removes the trailing slash if one exists.
*
* @param url URL string.
*
* @return The URL string, modified if needed.
*/
Location.stripTrailingSlash = stripTrailingSlash;
/** @nocollapse */
Location.ctorParameters = () => [
{ type: LocationStrategy },
{ type: PlatformLocation }
];
/** @nocollapse */ Location.ɵprov = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"])({ factory: createLocation, token: Location, providedIn: "root" });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](Location, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injectable"],
args: [{
providedIn: 'root',
// See #23917
useFactory: createLocation
}]
}], function () { return [{ type: LocationStrategy }, { type: PlatformLocation }]; }, null); })();
if (false) {}
/**
* @return {?}
*/
function createLocation() {
return new Location(Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])((/** @type {?} */ (LocationStrategy))), Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])((/** @type {?} */ (PlatformLocation))));
}
/**
* @param {?} baseHref
* @param {?} url
* @return {?}
*/
function _stripBaseHref(baseHref, url) {
return baseHref && url.startsWith(baseHref) ? url.substring(baseHref.length) : url;
}
/**
* @param {?} url
* @return {?}
*/
function _stripIndexHtml(url) {
return url.replace(/\/index.html$/, '');
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/location/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/i18n/currencies.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
/**
* \@internal
* @type {?}
*/
const CURRENCIES_EN = {
'ADP': [undefined, undefined, 0],
'AFN': [undefined, undefined, 0],
'ALL': [undefined, undefined, 0],
'AMD': [undefined, undefined, 2],
'AOA': [undefined, 'Kz'],
'ARS': [undefined, '$'],
'AUD': ['A$', '$'],
'BAM': [undefined, 'KM'],
'BBD': [undefined, '$'],
'BDT': [undefined, '৳'],
'BHD': [undefined, undefined, 3],
'BIF': [undefined, undefined, 0],
'BMD': [undefined, '$'],
'BND': [undefined, '$'],
'BOB': [undefined, 'Bs'],
'BRL': ['R$'],
'BSD': [undefined, '$'],
'BWP': [undefined, 'P'],
'BYN': [undefined, 'р.', 2],
'BYR': [undefined, undefined, 0],
'BZD': [undefined, '$'],
'CAD': ['CA$', '$', 2],
'CHF': [undefined, undefined, 2],
'CLF': [undefined, undefined, 4],
'CLP': [undefined, '$', 0],
'CNY': ['CN¥', '¥'],
'COP': [undefined, '$', 2],
'CRC': [undefined, '₡', 2],
'CUC': [undefined, '$'],
'CUP': [undefined, '$'],
'CZK': [undefined, 'Kč', 2],
'DJF': [undefined, undefined, 0],
'DKK': [undefined, 'kr', 2],
'DOP': [undefined, '$'],
'EGP': [undefined, 'E£'],
'ESP': [undefined, '₧', 0],
'EUR': ['€'],
'FJD': [undefined, '$'],
'FKP': [undefined, '£'],
'GBP': ['£'],
'GEL': [undefined, '₾'],
'GIP': [undefined, '£'],
'GNF': [undefined, 'FG', 0],
'GTQ': [undefined, 'Q'],
'GYD': [undefined, '$', 2],
'HKD': ['HK$', '$'],
'HNL': [undefined, 'L'],
'HRK': [undefined, 'kn'],
'HUF': [undefined, 'Ft', 2],
'IDR': [undefined, 'Rp', 2],
'ILS': ['₪'],
'INR': ['₹'],
'IQD': [undefined, undefined, 0],
'IRR': [undefined, undefined, 0],
'ISK': [undefined, 'kr', 0],
'ITL': [undefined, undefined, 0],
'JMD': [undefined, '$'],
'JOD': [undefined, undefined, 3],
'JPY': ['¥', undefined, 0],
'KHR': [undefined, '៛'],
'KMF': [undefined, 'CF', 0],
'KPW': [undefined, '₩', 0],
'KRW': ['₩', undefined, 0],
'KWD': [undefined, undefined, 3],
'KYD': [undefined, '$'],
'KZT': [undefined, '₸'],
'LAK': [undefined, '₭', 0],
'LBP': [undefined, 'L£', 0],
'LKR': [undefined, 'Rs'],
'LRD': [undefined, '$'],
'LTL': [undefined, 'Lt'],
'LUF': [undefined, undefined, 0],
'LVL': [undefined, 'Ls'],
'LYD': [undefined, undefined, 3],
'MGA': [undefined, 'Ar', 0],
'MGF': [undefined, undefined, 0],
'MMK': [undefined, 'K', 0],
'MNT': [undefined, '₮', 2],
'MRO': [undefined, undefined, 0],
'MUR': [undefined, 'Rs', 2],
'MXN': ['MX$', '$'],
'MYR': [undefined, 'RM'],
'NAD': [undefined, '$'],
'NGN': [undefined, '₦'],
'NIO': [undefined, 'C$'],
'NOK': [undefined, 'kr', 2],
'NPR': [undefined, 'Rs'],
'NZD': ['NZ$', '$'],
'OMR': [undefined, undefined, 3],
'PHP': [undefined, '₱'],
'PKR': [undefined, 'Rs', 2],
'PLN': [undefined, 'zł'],
'PYG': [undefined, '₲', 0],
'RON': [undefined, 'lei'],
'RSD': [undefined, undefined, 0],
'RUB': [undefined, '₽'],
'RUR': [undefined, 'р.'],
'RWF': [undefined, 'RF', 0],
'SBD': [undefined, '$'],
'SEK': [undefined, 'kr', 2],
'SGD': [undefined, '$'],
'SHP': [undefined, '£'],
'SLL': [undefined, undefined, 0],
'SOS': [undefined, undefined, 0],
'SRD': [undefined, '$'],
'SSP': [undefined, '£'],
'STD': [undefined, undefined, 0],
'STN': [undefined, 'Db'],
'SYP': [undefined, '£', 0],
'THB': [undefined, '฿'],
'TMM': [undefined, undefined, 0],
'TND': [undefined, undefined, 3],
'TOP': [undefined, 'T$'],
'TRL': [undefined, undefined, 0],
'TRY': [undefined, '₺'],
'TTD': [undefined, '$'],
'TWD': ['NT$', '$', 2],
'TZS': [undefined, undefined, 2],
'UAH': [undefined, '₴'],
'UGX': [undefined, undefined, 0],
'USD': ['$'],
'UYI': [undefined, undefined, 0],
'UYU': [undefined, '$'],
'UYW': [undefined, undefined, 4],
'UZS': [undefined, undefined, 2],
'VEF': [undefined, 'Bs', 2],
'VND': ['₫', undefined, 0],
'VUV': [undefined, undefined, 0],
'XAF': ['FCFA', undefined, 0],
'XCD': ['EC$', '$'],
'XOF': ['CFA', undefined, 0],
'XPF': ['CFPF', undefined, 0],
'XXX': ['¤'],
'YER': [undefined, undefined, 0],
'ZAR': [undefined, 'R'],
'ZMK': [undefined, undefined, 0],
'ZMW': [undefined, 'ZK'],
'ZWD': [undefined, undefined, 0]
};
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/i18n/locale_data_api.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @enum {number} */
const NumberFormatStyle = {
Decimal: 0,
Percent: 1,
Currency: 2,
Scientific: 3,
};
NumberFormatStyle[NumberFormatStyle.Decimal] = 'Decimal';
NumberFormatStyle[NumberFormatStyle.Percent] = 'Percent';
NumberFormatStyle[NumberFormatStyle.Currency] = 'Currency';
NumberFormatStyle[NumberFormatStyle.Scientific] = 'Scientific';
/** @enum {number} */
const Plural = {
Zero: 0,
One: 1,
Two: 2,
Few: 3,
Many: 4,
Other: 5,
};
Plural[Plural.Zero] = 'Zero';
Plural[Plural.One] = 'One';
Plural[Plural.Two] = 'Two';
Plural[Plural.Few] = 'Few';
Plural[Plural.Many] = 'Many';
Plural[Plural.Other] = 'Other';
/** @enum {number} */
const FormStyle = {
Format: 0,
Standalone: 1,
};
FormStyle[FormStyle.Format] = 'Format';
FormStyle[FormStyle.Standalone] = 'Standalone';
/** @enum {number} */
const TranslationWidth = {
/** 1 character for `en-US`. For example: 'S' */
Narrow: 0,
/** 3 characters for `en-US`. For example: 'Sun' */
Abbreviated: 1,
/** Full length for `en-US`. For example: "Sunday" */
Wide: 2,
/** 2 characters for `en-US`, For example: "Su" */
Short: 3,
};
TranslationWidth[TranslationWidth.Narrow] = 'Narrow';
TranslationWidth[TranslationWidth.Abbreviated] = 'Abbreviated';
TranslationWidth[TranslationWidth.Wide] = 'Wide';
TranslationWidth[TranslationWidth.Short] = 'Short';
/** @enum {number} */
const FormatWidth = {
/**
* For `en-US`, 'M/d/yy, h:mm a'`
* (Example: `6/15/15, 9:03 AM`)
*/
Short: 0,
/**
* For `en-US`, `'MMM d, y, h:mm:ss a'`
* (Example: `Jun 15, 2015, 9:03:01 AM`)
*/
Medium: 1,
/**
* For `en-US`, `'MMMM d, y, h:mm:ss a z'`
* (Example: `June 15, 2015 at 9:03:01 AM GMT+1`)
*/
Long: 2,
/**
* For `en-US`, `'EEEE, MMMM d, y, h:mm:ss a zzzz'`
* (Example: `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00`)
*/
Full: 3,
};
FormatWidth[FormatWidth.Short] = 'Short';
FormatWidth[FormatWidth.Medium] = 'Medium';
FormatWidth[FormatWidth.Long] = 'Long';
FormatWidth[FormatWidth.Full] = 'Full';
/** @enum {number} */
const NumberSymbol = {
/**
* Decimal separator.
* For `en-US`, the dot character.
* Example : 2,345`.`67
*/
Decimal: 0,
/**
* Grouping separator, typically for thousands.
* For `en-US`, the comma character.
* Example: 2`,`345.67
*/
Group: 1,
/**
* List-item separator.
* Example: "one, two, and three"
*/
List: 2,
/**
* Sign for percentage (out of 100).
* Example: 23.4%
*/
PercentSign: 3,
/**
* Sign for positive numbers.
* Example: +23
*/
PlusSign: 4,
/**
* Sign for negative numbers.
* Example: -23
*/
MinusSign: 5,
/**
* Computer notation for exponential value (n times a power of 10).
* Example: 1.2E3
*/
Exponential: 6,
/**
* Human-readable format of exponential.
* Example: 1.2x103
*/
SuperscriptingExponent: 7,
/**
* Sign for permille (out of 1000).
* Example: 23.4‰
*/
PerMille: 8,
/**
* Infinity, can be used with plus and minus.
* Example: ∞, +∞, -∞
*/
Infinity: 9,
/**
* Not a number.
* Example: NaN
*/
NaN: 10,
/**
* Symbol used between time units.
* Example: 10:52
*/
TimeSeparator: 11,
/**
* Decimal separator for currency values (fallback to `Decimal`).
* Example: $2,345.67
*/
CurrencyDecimal: 12,
/**
* Group separator for currency values (fallback to `Group`).
* Example: $2,345.67
*/
CurrencyGroup: 13,
};
NumberSymbol[NumberSymbol.Decimal] = 'Decimal';
NumberSymbol[NumberSymbol.Group] = 'Group';
NumberSymbol[NumberSymbol.List] = 'List';
NumberSymbol[NumberSymbol.PercentSign] = 'PercentSign';
NumberSymbol[NumberSymbol.PlusSign] = 'PlusSign';
NumberSymbol[NumberSymbol.MinusSign] = 'MinusSign';
NumberSymbol[NumberSymbol.Exponential] = 'Exponential';
NumberSymbol[NumberSymbol.SuperscriptingExponent] = 'SuperscriptingExponent';
NumberSymbol[NumberSymbol.PerMille] = 'PerMille';
NumberSymbol[NumberSymbol.Infinity] = 'Infinity';
NumberSymbol[NumberSymbol.NaN] = 'NaN';
NumberSymbol[NumberSymbol.TimeSeparator] = 'TimeSeparator';
NumberSymbol[NumberSymbol.CurrencyDecimal] = 'CurrencyDecimal';
NumberSymbol[NumberSymbol.CurrencyGroup] = 'CurrencyGroup';
/** @enum {number} */
const WeekDay = {
Sunday: 0,
Monday: 1,
Tuesday: 2,
Wednesday: 3,
Thursday: 4,
Friday: 5,
Saturday: 6,
};
WeekDay[WeekDay.Sunday] = 'Sunday';
WeekDay[WeekDay.Monday] = 'Monday';
WeekDay[WeekDay.Tuesday] = 'Tuesday';
WeekDay[WeekDay.Wednesday] = 'Wednesday';
WeekDay[WeekDay.Thursday] = 'Thursday';
WeekDay[WeekDay.Friday] = 'Friday';
WeekDay[WeekDay.Saturday] = 'Saturday';
/**
* Retrieves the locale ID from the currently loaded locale.
* The loaded locale could be, for example, a global one rather than a regional one.
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code, such as `fr-FR`.
* @return {?} The locale code. For example, `fr`.
*/
function getLocaleId(locale) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale)[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].LocaleId];
}
/**
* Retrieves day period strings for the given locale.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @param {?} formStyle The required grammatical form.
* @param {?} width The required character width.
* @return {?} An array of localized period strings. For example, `[AM, PM]` for `en-US`.
*/
function getLocaleDayPeriods(locale, formStyle, width) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
/** @type {?} */
const amPmData = (/** @type {?} */ ([
data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DayPeriodsFormat], data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DayPeriodsStandalone]
]));
/** @type {?} */
const amPm = getLastDefinedValue(amPmData, formStyle);
return getLastDefinedValue(amPm, width);
}
/**
* Retrieves days of the week for the given locale, using the Gregorian calendar.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @param {?} formStyle The required grammatical form.
* @param {?} width The required character width.
* @return {?} An array of localized name strings.
* For example,`[Sunday, Monday, ... Saturday]` for `en-US`.
*/
function getLocaleDayNames(locale, formStyle, width) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
/** @type {?} */
const daysData = (/** @type {?} */ ([data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DaysFormat], data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DaysStandalone]]));
/** @type {?} */
const days = getLastDefinedValue(daysData, formStyle);
return getLastDefinedValue(days, width);
}
/**
* Retrieves months of the year for the given locale, using the Gregorian calendar.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @param {?} formStyle The required grammatical form.
* @param {?} width The required character width.
* @return {?} An array of localized name strings.
* For example, `[January, February, ...]` for `en-US`.
*/
function getLocaleMonthNames(locale, formStyle, width) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
/** @type {?} */
const monthsData = (/** @type {?} */ ([data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].MonthsFormat], data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].MonthsStandalone]]));
/** @type {?} */
const months = getLastDefinedValue(monthsData, formStyle);
return getLastDefinedValue(months, width);
}
/**
* Retrieves Gregorian-calendar eras for the given locale.
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @param {?} width The required character width.
* @return {?} An array of localized era strings.
* For example, `[AD, BC]` for `en-US`.
*/
function getLocaleEraNames(locale, width) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
/** @type {?} */
const erasData = (/** @type {?} */ (data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].Eras]));
return getLastDefinedValue(erasData, width);
}
/**
* Retrieves the first day of the week for the given locale.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @return {?} A day index number, using the 0-based week-day index for `en-US`
* (Sunday = 0, Monday = 1, ...).
* For example, for `fr-FR`, returns 1 to indicate that the first day is Monday.
*/
function getLocaleFirstDayOfWeek(locale) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].FirstDayOfWeek];
}
/**
* Range of week days that are considered the week-end for the given locale.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @return {?} The range of day values, `[startDay, endDay]`.
*/
function getLocaleWeekEndRange(locale) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].WeekendRange];
}
/**
* Retrieves a localized date-value formating string.
*
* @see `FormatWidth` / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @param {?} width The format type.
* @return {?} The localized formating string.
*/
function getLocaleDateFormat(locale, width) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
return getLastDefinedValue(data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DateFormat], width);
}
/**
* Retrieves a localized time-value formatting string.
*
* @see `FormatWidth` / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @param {?} width The format type.
* @return {?} The localized formatting string.
*/
function getLocaleTimeFormat(locale, width) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
return getLastDefinedValue(data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].TimeFormat], width);
}
/**
* Retrieves a localized date-time formatting string.
*
* @see `FormatWidth` / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @param {?} width The format type.
* @return {?} The localized formatting string.
*/
function getLocaleDateTimeFormat(locale, width) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
/** @type {?} */
const dateTimeFormatData = (/** @type {?} */ (data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DateTimeFormat]));
return getLastDefinedValue(dateTimeFormatData, width);
}
/**
* Retrieves a localized number symbol that can be used to replace placeholders in number formats.
* @see `NumberSymbol` / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale The locale code.
* @param {?} symbol The symbol to localize.
* @return {?} The character for the localized symbol.
*/
function getLocaleNumberSymbol(locale, symbol) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
/** @type {?} */
const res = data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].NumberSymbols][symbol];
if (typeof res === 'undefined') {
if (symbol === NumberSymbol.CurrencyDecimal) {
return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].NumberSymbols][NumberSymbol.Decimal];
}
else if (symbol === NumberSymbol.CurrencyGroup) {
return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].NumberSymbols][NumberSymbol.Group];
}
}
return res;
}
/**
* Retrieves a number format for a given locale.
*
* Numbers are formatted using patterns, like `#,###.00`. For example, the pattern `#,###.00`
* when used to format the number 12345.678 could result in "12'345,678". That would happen if the
* grouping separator for your language is an apostrophe, and the decimal separator is a comma.
*
* <b>Important:</b> The characters `.` `,` `0` `#` (and others below) are special placeholders
* that stand for the decimal separator, and so on, and are NOT real characters.
* You must NOT "translate" the placeholders. For example, don't change `.` to `,` even though in
* your language the decimal point is written with a comma. The symbols should be replaced by the
* local equivalents, using the appropriate `NumberSymbol` for your language.
*
* Here are the special characters used in number patterns:
*
* | Symbol | Meaning |
* |--------|---------|
* | . | Replaced automatically by the character used for the decimal point. |
* | , | Replaced by the "grouping" (thousands) separator. |
* | 0 | Replaced by a digit (or zero if there aren't enough digits). |
* | # | Replaced by a digit (or nothing if there aren't enough). |
* | ¤ | Replaced by a currency symbol, such as $ or USD. |
* | % | Marks a percent format. The % symbol may change position, but must be retained. |
* | E | Marks a scientific format. The E symbol may change position, but must be retained. |
* | ' | Special characters used as literal characters are quoted with ASCII single quotes. |
*
* @see `NumberFormatStyle` / [CLDR website](http://cldr.unicode.org/translation/number-patterns) / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @param {?} type The type of numeric value to be formatted (such as `Decimal` or `Currency`.)
* @return {?} The localized format string.
*/
function getLocaleNumberFormat(locale, type) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].NumberFormats][type];
}
/**
* Retrieves the symbol used to represent the currency for the main country
* corresponding to a given locale. For example, '$' for `en-US`.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @return {?} The localized symbol character,
* or `null` if the main country cannot be determined.
*/
function getLocaleCurrencySymbol(locale) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].CurrencySymbol] || null;
}
/**
* Retrieves the name of the currency for the main country corresponding
* to a given locale. For example, 'US Dollar' for `en-US`.
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @return {?} The currency name,
* or `null` if the main country cannot be determined.
*/
function getLocaleCurrencyName(locale) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].CurrencyName] || null;
}
/**
* Retrieves the default currency code for the given locale.
*
* The default is defined as the first currency which is still in use.
*
* \@publicApi
* @param {?} locale The code of the locale whose currency code we want.
* @return {?} The code of the default currency for the given locale.
*
*/
function getLocaleCurrencyCode(locale) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵgetLocaleCurrencyCode"])(locale);
}
/**
* Retrieves the currency values for a given locale.
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
* @param {?} locale A locale code for the locale format rules to use.
* @return {?} The currency values.
*/
function getLocaleCurrencies(locale) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].Currencies];
}
/**
* \@alias core/ɵgetLocalePluralCase
* \@publicApi
* @type {?}
*/
const getLocalePluralCase = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵgetLocalePluralCase"];
/**
* @param {?} data
* @return {?}
*/
function checkFullData(data) {
if (!data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].ExtraData]) {
throw new Error(`Missing extra locale data for the locale "${data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"]
.LocaleId]}". Use "registerLocaleData" to load new data. See the "I18n guide" on angular.io to know more.`);
}
}
/**
* Retrieves locale-specific rules used to determine which day period to use
* when more than one period is defined for a locale.
*
* There is a rule for each defined day period. The
* first rule is applied to the first day period and so on.
* Fall back to AM/PM when no rules are available.
*
* A rule can specify a period as time range, or as a single time value.
*
* This functionality is only available when you have loaded the full locale data.
* See the ["I18n guide"](guide/i18n#i18n-pipes).
*
* @see `getLocaleExtraDayPeriods()` / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @return {?} The rules for the locale, a single time value or array of *from-time, to-time*,
* or null if no periods are available.
*
*/
function getLocaleExtraDayPeriodRules(locale) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
checkFullData(data);
/** @type {?} */
const rules = data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].ExtraData][2 /* ExtraDayPeriodsRules */] || [];
return rules.map((/**
* @param {?} rule
* @return {?}
*/
(rule) => {
if (typeof rule === 'string') {
return extractTime(rule);
}
return [extractTime(rule[0]), extractTime(rule[1])];
}));
}
/**
* Retrieves locale-specific day periods, which indicate roughly how a day is broken up
* in different languages.
* For example, for `en-US`, periods are morning, noon, afternoon, evening, and midnight.
*
* This functionality is only available when you have loaded the full locale data.
* See the ["I18n guide"](guide/i18n#i18n-pipes).
*
* @see `getLocaleExtraDayPeriodRules()` / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} locale A locale code for the locale format rules to use.
* @param {?} formStyle The required grammatical form.
* @param {?} width The required character width.
* @return {?} The translated day-period strings.
*/
function getLocaleExtraDayPeriods(locale, formStyle, width) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
checkFullData(data);
/** @type {?} */
const dayPeriodsData = (/** @type {?} */ ([
data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].ExtraData][0 /* ExtraDayPeriodFormats */],
data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].ExtraData][1 /* ExtraDayPeriodStandalone */]
]));
/** @type {?} */
const dayPeriods = getLastDefinedValue(dayPeriodsData, formStyle) || [];
return getLastDefinedValue(dayPeriods, width) || [];
}
/**
* Retrieves the writing direction of a specified locale
* \@publicApi
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
* @param {?} locale A locale code for the locale format rules to use.
* @return {?} 'rtl' or 'ltr'
*/
function getLocaleDirection(locale) {
/** @type {?} */
const data = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale);
return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].Directionality];
}
/**
* Retrieves the first value that is defined in an array, going backwards from an index position.
*
* To avoid repeating the same data (as when the "format" and "standalone" forms are the same)
* add the first value to the locale data arrays, and add other values only if they are different.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @template T
* @param {?} data The data array to retrieve from.
* @param {?} index A 0-based index into the array to start from.
* @return {?} The value immediately before the given index position.
*/
function getLastDefinedValue(data, index) {
for (let i = index; i > -1; i--) {
if (typeof data[i] !== 'undefined') {
return data[i];
}
}
throw new Error('Locale data API: locale data undefined');
}
/**
* Extracts the hours and minutes from a string like "15:45"
* @param {?} time
* @return {?}
*/
function extractTime(time) {
const [h, m] = time.split(':');
return { hours: +h, minutes: +m };
}
/**
* Retrieves the currency symbol for a given currency code.
*
* For example, for the default `en-US` locale, the code `USD` can
* be represented by the narrow symbol `$` or the wide symbol `US$`.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} code The currency code.
* @param {?} format The format, `wide` or `narrow`.
* @param {?=} locale A locale code for the locale format rules to use.
*
* @return {?} The symbol, or the currency code if no symbol is available.
*/
function getCurrencySymbol(code, format, locale = 'en') {
/** @type {?} */
const currency = getLocaleCurrencies(locale)[code] || CURRENCIES_EN[code] || [];
/** @type {?} */
const symbolNarrow = currency[1 /* SymbolNarrow */];
if (format === 'narrow' && typeof symbolNarrow === 'string') {
return symbolNarrow;
}
return currency[0 /* Symbol */] || code;
}
// Most currencies have cents, that's why the default is 2
/** @type {?} */
const DEFAULT_NB_OF_CURRENCY_DIGITS = 2;
/**
* Reports the number of decimal digits for a given currency.
* The value depends upon the presence of cents in that particular currency.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} code The currency code.
* @return {?} The number of decimal digits, typically 0 or 2.
*/
function getNumberOfCurrencyDigits(code) {
/** @type {?} */
let digits;
/** @type {?} */
const currency = CURRENCIES_EN[code];
if (currency) {
digits = currency[2 /* NbOfDigits */];
}
return typeof digits === 'number' ? digits : DEFAULT_NB_OF_CURRENCY_DIGITS;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/i18n/format_date.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const ISO8601_DATE_REGEX = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
// 1 2 3 4 5 6 7 8 9 10 11
/** @type {?} */
const NAMED_FORMATS = {};
/** @type {?} */
const DATE_FORMATS_SPLIT = /((?:[^GyMLwWdEabBhHmsSzZO']+)|(?:'(?:[^']|'')*')|(?:G{1,5}|y{1,4}|M{1,5}|L{1,5}|w{1,2}|W{1}|d{1,2}|E{1,6}|a{1,5}|b{1,5}|B{1,5}|h{1,2}|H{1,2}|m{1,2}|s{1,2}|S{1,3}|z{1,4}|Z{1,5}|O{1,4}))([\s\S]*)/;
/** @enum {number} */
const ZoneWidth = {
Short: 0,
ShortGMT: 1,
Long: 2,
Extended: 3,
};
ZoneWidth[ZoneWidth.Short] = 'Short';
ZoneWidth[ZoneWidth.ShortGMT] = 'ShortGMT';
ZoneWidth[ZoneWidth.Long] = 'Long';
ZoneWidth[ZoneWidth.Extended] = 'Extended';
/** @enum {number} */
const DateType = {
FullYear: 0,
Month: 1,
Date: 2,
Hours: 3,
Minutes: 4,
Seconds: 5,
FractionalSeconds: 6,
Day: 7,
};
DateType[DateType.FullYear] = 'FullYear';
DateType[DateType.Month] = 'Month';
DateType[DateType.Date] = 'Date';
DateType[DateType.Hours] = 'Hours';
DateType[DateType.Minutes] = 'Minutes';
DateType[DateType.Seconds] = 'Seconds';
DateType[DateType.FractionalSeconds] = 'FractionalSeconds';
DateType[DateType.Day] = 'Day';
/** @enum {number} */
const TranslationType = {
DayPeriods: 0,
Days: 1,
Months: 2,
Eras: 3,
};
TranslationType[TranslationType.DayPeriods] = 'DayPeriods';
TranslationType[TranslationType.Days] = 'Days';
TranslationType[TranslationType.Months] = 'Months';
TranslationType[TranslationType.Eras] = 'Eras';
/**
* \@ngModule CommonModule
* \@description
*
* Formats a date according to locale rules.
*
* @see `DatePipe` / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} value The date to format, as a Date, or a number (milliseconds since UTC epoch)
* or an [ISO date-time string](https://www.w3.org/TR/NOTE-datetime).
* @param {?} format The date-time components to include. See `DatePipe` for details.
* @param {?} locale A locale code for the locale format rules to use.
* @param {?=} timezone The time zone. A time zone offset from GMT (such as `'+0430'`),
* or a standard UTC/GMT or continental US time zone abbreviation.
* If not specified, uses host system settings.
*
* @return {?} The formatted date string.
*
*/
function formatDate(value, format, locale, timezone) {
/** @type {?} */
let date = toDate(value);
/** @type {?} */
const namedFormat = getNamedFormat(locale, format);
format = namedFormat || format;
/** @type {?} */
let parts = [];
/** @type {?} */
let match;
while (format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = parts.concat(match.slice(1));
/** @type {?} */
const part = parts.pop();
if (!part) {
break;
}
format = part;
}
else {
parts.push(format);
break;
}
}
/** @type {?} */
let dateTimezoneOffset = date.getTimezoneOffset();
if (timezone) {
dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
date = convertTimezoneToLocal(date, timezone, true);
}
/** @type {?} */
let text = '';
parts.forEach((/**
* @param {?} value
* @return {?}
*/
value => {
/** @type {?} */
const dateFormatter = getDateFormatter(value);
text += dateFormatter ?
dateFormatter(date, locale, dateTimezoneOffset) :
value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
}));
return text;
}
/**
* @param {?} locale
* @param {?} format
* @return {?}
*/
function getNamedFormat(locale, format) {
/** @type {?} */
const localeId = getLocaleId(locale);
NAMED_FORMATS[localeId] = NAMED_FORMATS[localeId] || {};
if (NAMED_FORMATS[localeId][format]) {
return NAMED_FORMATS[localeId][format];
}
/** @type {?} */
let formatValue = '';
switch (format) {
case 'shortDate':
formatValue = getLocaleDateFormat(locale, FormatWidth.Short);
break;
case 'mediumDate':
formatValue = getLocaleDateFormat(locale, FormatWidth.Medium);
break;
case 'longDate':
formatValue = getLocaleDateFormat(locale, FormatWidth.Long);
break;
case 'fullDate':
formatValue = getLocaleDateFormat(locale, FormatWidth.Full);
break;
case 'shortTime':
formatValue = getLocaleTimeFormat(locale, FormatWidth.Short);
break;
case 'mediumTime':
formatValue = getLocaleTimeFormat(locale, FormatWidth.Medium);
break;
case 'longTime':
formatValue = getLocaleTimeFormat(locale, FormatWidth.Long);
break;
case 'fullTime':
formatValue = getLocaleTimeFormat(locale, FormatWidth.Full);
break;
case 'short':
/** @type {?} */
const shortTime = getNamedFormat(locale, 'shortTime');
/** @type {?} */
const shortDate = getNamedFormat(locale, 'shortDate');
formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Short), [shortTime, shortDate]);
break;
case 'medium':
/** @type {?} */
const mediumTime = getNamedFormat(locale, 'mediumTime');
/** @type {?} */
const mediumDate = getNamedFormat(locale, 'mediumDate');
formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Medium), [mediumTime, mediumDate]);
break;
case 'long':
/** @type {?} */
const longTime = getNamedFormat(locale, 'longTime');
/** @type {?} */
const longDate = getNamedFormat(locale, 'longDate');
formatValue =
formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Long), [longTime, longDate]);
break;
case 'full':
/** @type {?} */
const fullTime = getNamedFormat(locale, 'fullTime');
/** @type {?} */
const fullDate = getNamedFormat(locale, 'fullDate');
formatValue =
formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Full), [fullTime, fullDate]);
break;
}
if (formatValue) {
NAMED_FORMATS[localeId][format] = formatValue;
}
return formatValue;
}
/**
* @param {?} str
* @param {?} opt_values
* @return {?}
*/
function formatDateTime(str, opt_values) {
if (opt_values) {
str = str.replace(/\{([^}]+)}/g, (/**
* @param {?} match
* @param {?} key
* @return {?}
*/
function (match, key) {
return (opt_values != null && key in opt_values) ? opt_values[key] : match;
}));
}
return str;
}
/**
* @param {?} num
* @param {?} digits
* @param {?=} minusSign
* @param {?=} trim
* @param {?=} negWrap
* @return {?}
*/
function padNumber(num, digits, minusSign = '-', trim, negWrap) {
/** @type {?} */
let neg = '';
if (num < 0 || (negWrap && num <= 0)) {
if (negWrap) {
num = -num + 1;
}
else {
num = -num;
neg = minusSign;
}
}
/** @type {?} */
let strNum = String(num);
while (strNum.length < digits) {
strNum = '0' + strNum;
}
if (trim) {
strNum = strNum.substr(strNum.length - digits);
}
return neg + strNum;
}
/**
* @param {?} milliseconds
* @param {?} digits
* @return {?}
*/
function formatFractionalSeconds(milliseconds, digits) {
/** @type {?} */
const strMs = padNumber(milliseconds, 3);
return strMs.substr(0, digits);
}
/**
* Returns a date formatter that transforms a date into its locale digit representation
* @param {?} name
* @param {?} size
* @param {?=} offset
* @param {?=} trim
* @param {?=} negWrap
* @return {?}
*/
function dateGetter(name, size, offset = 0, trim = false, negWrap = false) {
return (/**
* @param {?} date
* @param {?} locale
* @return {?}
*/
function (date, locale) {
/** @type {?} */
let part = getDatePart(name, date);
if (offset > 0 || part > -offset) {
part += offset;
}
if (name === DateType.Hours) {
if (part === 0 && offset === -12) {
part = 12;
}
}
else if (name === DateType.FractionalSeconds) {
return formatFractionalSeconds(part, size);
}
/** @type {?} */
const localeMinus = getLocaleNumberSymbol(locale, NumberSymbol.MinusSign);
return padNumber(part, size, localeMinus, trim, negWrap);
});
}
/**
* @param {?} part
* @param {?} date
* @return {?}
*/
function getDatePart(part, date) {
switch (part) {
case DateType.FullYear:
return date.getFullYear();
case DateType.Month:
return date.getMonth();
case DateType.Date:
return date.getDate();
case DateType.Hours:
return date.getHours();
case DateType.Minutes:
return date.getMinutes();
case DateType.Seconds:
return date.getSeconds();
case DateType.FractionalSeconds:
return date.getMilliseconds();
case DateType.Day:
return date.getDay();
default:
throw new Error(`Unknown DateType value "${part}".`);
}
}
/**
* Returns a date formatter that transforms a date into its locale string representation
* @param {?} name
* @param {?} width
* @param {?=} form
* @param {?=} extended
* @return {?}
*/
function dateStrGetter(name, width, form = FormStyle.Format, extended = false) {
return (/**
* @param {?} date
* @param {?} locale
* @return {?}
*/
function (date, locale) {
return getDateTranslation(date, locale, name, width, form, extended);
});
}
/**
* Returns the locale translation of a date for a given form, type and width
* @param {?} date
* @param {?} locale
* @param {?} name
* @param {?} width
* @param {?} form
* @param {?} extended
* @return {?}
*/
function getDateTranslation(date, locale, name, width, form, extended) {
switch (name) {
case TranslationType.Months:
return getLocaleMonthNames(locale, form, width)[date.getMonth()];
case TranslationType.Days:
return getLocaleDayNames(locale, form, width)[date.getDay()];
case TranslationType.DayPeriods:
/** @type {?} */
const currentHours = date.getHours();
/** @type {?} */
const currentMinutes = date.getMinutes();
if (extended) {
/** @type {?} */
const rules = getLocaleExtraDayPeriodRules(locale);
/** @type {?} */
const dayPeriods = getLocaleExtraDayPeriods(locale, form, width);
/** @type {?} */
let result;
rules.forEach((/**
* @param {?} rule
* @param {?} index
* @return {?}
*/
(rule, index) => {
if (Array.isArray(rule)) {
// morning, afternoon, evening, night
const { hours: hoursFrom, minutes: minutesFrom } = rule[0];
const { hours: hoursTo, minutes: minutesTo } = rule[1];
if (currentHours >= hoursFrom && currentMinutes >= minutesFrom &&
(currentHours < hoursTo ||
(currentHours === hoursTo && currentMinutes < minutesTo))) {
result = dayPeriods[index];
}
}
else { // noon or midnight
// noon or midnight
const { hours, minutes } = rule;
if (hours === currentHours && minutes === currentMinutes) {
result = dayPeriods[index];
}
}
}));
if (result) {
return result;
}
}
// if no rules for the day periods, we use am/pm by default
return getLocaleDayPeriods(locale, form, (/** @type {?} */ (width)))[currentHours < 12 ? 0 : 1];
case TranslationType.Eras:
return getLocaleEraNames(locale, (/** @type {?} */ (width)))[date.getFullYear() <= 0 ? 0 : 1];
default:
// This default case is not needed by TypeScript compiler, as the switch is exhaustive.
// However Closure Compiler does not understand that and reports an error in typed mode.
// The `throw new Error` below works around the problem, and the unexpected: never variable
// makes sure tsc still checks this code is unreachable.
/** @type {?} */
const unexpected = name;
throw new Error(`unexpected translation type ${unexpected}`);
}
}
/**
* Returns a date formatter that transforms a date and an offset into a timezone with ISO8601 or
* GMT format depending on the width (eg: short = +0430, short:GMT = GMT+4, long = GMT+04:30,
* extended = +04:30)
* @param {?} width
* @return {?}
*/
function timeZoneGetter(width) {
return (/**
* @param {?} date
* @param {?} locale
* @param {?} offset
* @return {?}
*/
function (date, locale, offset) {
/** @type {?} */
const zone = -1 * offset;
/** @type {?} */
const minusSign = getLocaleNumberSymbol(locale, NumberSymbol.MinusSign);
/** @type {?} */
const hours = zone > 0 ? Math.floor(zone / 60) : Math.ceil(zone / 60);
switch (width) {
case ZoneWidth.Short:
return ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) +
padNumber(Math.abs(zone % 60), 2, minusSign);
case ZoneWidth.ShortGMT:
return 'GMT' + ((zone >= 0) ? '+' : '') + padNumber(hours, 1, minusSign);
case ZoneWidth.Long:
return 'GMT' + ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) + ':' +
padNumber(Math.abs(zone % 60), 2, minusSign);
case ZoneWidth.Extended:
if (offset === 0) {
return 'Z';
}
else {
return ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) + ':' +
padNumber(Math.abs(zone % 60), 2, minusSign);
}
default:
throw new Error(`Unknown zone width "${width}"`);
}
});
}
/** @type {?} */
const JANUARY = 0;
/** @type {?} */
const THURSDAY = 4;
/**
* @param {?} year
* @return {?}
*/
function getFirstThursdayOfYear(year) {
/** @type {?} */
const firstDayOfYear = (new Date(year, JANUARY, 1)).getDay();
return new Date(year, 0, 1 + ((firstDayOfYear <= THURSDAY) ? THURSDAY : THURSDAY + 7) - firstDayOfYear);
}
/**
* @param {?} datetime
* @return {?}
*/
function getThursdayThisWeek(datetime) {
return new Date(datetime.getFullYear(), datetime.getMonth(), datetime.getDate() + (THURSDAY - datetime.getDay()));
}
/**
* @param {?} size
* @param {?=} monthBased
* @return {?}
*/
function weekGetter(size, monthBased = false) {
return (/**
* @param {?} date
* @param {?} locale
* @return {?}
*/
function (date, locale) {
/** @type {?} */
let result;
if (monthBased) {
/** @type {?} */
const nbDaysBefore1stDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).getDay() - 1;
/** @type {?} */
const today = date.getDate();
result = 1 + Math.floor((today + nbDaysBefore1stDayOfMonth) / 7);
}
else {
/** @type {?} */
const firstThurs = getFirstThursdayOfYear(date.getFullYear());
/** @type {?} */
const thisThurs = getThursdayThisWeek(date);
/** @type {?} */
const diff = thisThurs.getTime() - firstThurs.getTime();
result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
}
return padNumber(result, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
});
}
/** @type {?} */
const DATE_FORMATS = {};
// Based on CLDR formats:
// See complete list: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
// See also explanations: http://cldr.unicode.org/translation/date-time
// TODO(ocombe): support all missing cldr formats: Y, U, Q, D, F, e, c, j, J, C, A, v, V, X, x
/**
* @param {?} format
* @return {?}
*/
function getDateFormatter(format) {
if (DATE_FORMATS[format]) {
return DATE_FORMATS[format];
}
/** @type {?} */
let formatter;
switch (format) {
// Era name (AD/BC)
case 'G':
case 'GG':
case 'GGG':
formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Abbreviated);
break;
case 'GGGG':
formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Wide);
break;
case 'GGGGG':
formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Narrow);
break;
// 1 digit representation of the year, e.g. (AD 1 => 1, AD 199 => 199)
case 'y':
formatter = dateGetter(DateType.FullYear, 1, 0, false, true);
break;
// 2 digit representation of the year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
case 'yy':
formatter = dateGetter(DateType.FullYear, 2, 0, true, true);
break;
// 3 digit representation of the year, padded (000-999). (e.g. AD 2001 => 01, AD 2010 => 10)
case 'yyy':
formatter = dateGetter(DateType.FullYear, 3, 0, false, true);
break;
// 4 digit representation of the year (e.g. AD 1 => 0001, AD 2010 => 2010)
case 'yyyy':
formatter = dateGetter(DateType.FullYear, 4, 0, false, true);
break;
// Month of the year (1-12), numeric
case 'M':
case 'L':
formatter = dateGetter(DateType.Month, 1, 1);
break;
case 'MM':
case 'LL':
formatter = dateGetter(DateType.Month, 2, 1);
break;
// Month of the year (January, ...), string, format
case 'MMM':
formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Abbreviated);
break;
case 'MMMM':
formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Wide);
break;
case 'MMMMM':
formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Narrow);
break;
// Month of the year (January, ...), string, standalone
case 'LLL':
formatter =
dateStrGetter(TranslationType.Months, TranslationWidth.Abbreviated, FormStyle.Standalone);
break;
case 'LLLL':
formatter =
dateStrGetter(TranslationType.Months, TranslationWidth.Wide, FormStyle.Standalone);
break;
case 'LLLLL':
formatter =
dateStrGetter(TranslationType.Months, TranslationWidth.Narrow, FormStyle.Standalone);
break;
// Week of the year (1, ... 52)
case 'w':
formatter = weekGetter(1);
break;
case 'ww':
formatter = weekGetter(2);
break;
// Week of the month (1, ...)
case 'W':
formatter = weekGetter(1, true);
break;
// Day of the month (1-31)
case 'd':
formatter = dateGetter(DateType.Date, 1);
break;
case 'dd':
formatter = dateGetter(DateType.Date, 2);
break;
// Day of the Week
case 'E':
case 'EE':
case 'EEE':
formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Abbreviated);
break;
case 'EEEE':
formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Wide);
break;
case 'EEEEE':
formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Narrow);
break;
case 'EEEEEE':
formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Short);
break;
// Generic period of the day (am-pm)
case 'a':
case 'aa':
case 'aaa':
formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated);
break;
case 'aaaa':
formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide);
break;
case 'aaaaa':
formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow);
break;
// Extended period of the day (midnight, at night, ...), standalone
case 'b':
case 'bb':
case 'bbb':
formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated, FormStyle.Standalone, true);
break;
case 'bbbb':
formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide, FormStyle.Standalone, true);
break;
case 'bbbbb':
formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow, FormStyle.Standalone, true);
break;
// Extended period of the day (midnight, night, ...), standalone
case 'B':
case 'BB':
case 'BBB':
formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated, FormStyle.Format, true);
break;
case 'BBBB':
formatter =
dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide, FormStyle.Format, true);
break;
case 'BBBBB':
formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow, FormStyle.Format, true);
break;
// Hour in AM/PM, (1-12)
case 'h':
formatter = dateGetter(DateType.Hours, 1, -12);
break;
case 'hh':
formatter = dateGetter(DateType.Hours, 2, -12);
break;
// Hour of the day (0-23)
case 'H':
formatter = dateGetter(DateType.Hours, 1);
break;
// Hour in day, padded (00-23)
case 'HH':
formatter = dateGetter(DateType.Hours, 2);
break;
// Minute of the hour (0-59)
case 'm':
formatter = dateGetter(DateType.Minutes, 1);
break;
case 'mm':
formatter = dateGetter(DateType.Minutes, 2);
break;
// Second of the minute (0-59)
case 's':
formatter = dateGetter(DateType.Seconds, 1);
break;
case 'ss':
formatter = dateGetter(DateType.Seconds, 2);
break;
// Fractional second
case 'S':
formatter = dateGetter(DateType.FractionalSeconds, 1);
break;
case 'SS':
formatter = dateGetter(DateType.FractionalSeconds, 2);
break;
case 'SSS':
formatter = dateGetter(DateType.FractionalSeconds, 3);
break;
// Timezone ISO8601 short format (-0430)
case 'Z':
case 'ZZ':
case 'ZZZ':
formatter = timeZoneGetter(ZoneWidth.Short);
break;
// Timezone ISO8601 extended format (-04:30)
case 'ZZZZZ':
formatter = timeZoneGetter(ZoneWidth.Extended);
break;
// Timezone GMT short format (GMT+4)
case 'O':
case 'OO':
case 'OOO':
// Should be location, but fallback to format O instead because we don't have the data yet
case 'z':
case 'zz':
case 'zzz':
formatter = timeZoneGetter(ZoneWidth.ShortGMT);
break;
// Timezone GMT long format (GMT+0430)
case 'OOOO':
case 'ZZZZ':
// Should be location, but fallback to format O instead because we don't have the data yet
case 'zzzz':
formatter = timeZoneGetter(ZoneWidth.Long);
break;
default:
return null;
}
DATE_FORMATS[format] = formatter;
return formatter;
}
/**
* @param {?} timezone
* @param {?} fallback
* @return {?}
*/
function timezoneToOffset(timezone, fallback) {
// Support: IE 9-11 only, Edge 13-15+
// IE/Edge do not "understand" colon (`:`) in timezone
timezone = timezone.replace(/:/g, '');
/** @type {?} */
const requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
}
/**
* @param {?} date
* @param {?} minutes
* @return {?}
*/
function addDateMinutes(date, minutes) {
date = new Date(date.getTime());
date.setMinutes(date.getMinutes() + minutes);
return date;
}
/**
* @param {?} date
* @param {?} timezone
* @param {?} reverse
* @return {?}
*/
function convertTimezoneToLocal(date, timezone, reverse) {
/** @type {?} */
const reverseValue = reverse ? -1 : 1;
/** @type {?} */
const dateTimezoneOffset = date.getTimezoneOffset();
/** @type {?} */
const timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
return addDateMinutes(date, reverseValue * (timezoneOffset - dateTimezoneOffset));
}
/**
* Converts a value to date.
*
* Supported input formats:
* - `Date`
* - number: timestamp
* - string: numeric (e.g. "1234"), ISO and date strings in a format supported by
* [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse).
* Note: ISO strings without time return a date without timeoffset.
*
* Throws if unable to convert to a date.
* @param {?} value
* @return {?}
*/
function toDate(value) {
if (isDate(value)) {
return value;
}
if (typeof value === 'number' && !isNaN(value)) {
return new Date(value);
}
if (typeof value === 'string') {
value = value.trim();
/** @type {?} */
const parsedNb = parseFloat(value);
// any string that only contains numbers, like "1234" but not like "1234hello"
if (!isNaN((/** @type {?} */ (value)) - parsedNb)) {
return new Date(parsedNb);
}
if (/^(\d{4}-\d{1,2}-\d{1,2})$/.test(value)) {
/* For ISO Strings without time the day, month and year must be extracted from the ISO String
before Date creation to avoid time offset and errors in the new Date.
If we only replace '-' with ',' in the ISO String ("2015,01,01"), and try to create a new
date, some browsers (e.g. IE 9) will throw an invalid Date error.
If we leave the '-' ("2015-01-01") and try to create a new Date("2015-01-01") the timeoffset
is applied.
Note: ISO months are 0 for January, 1 for February, ... */
const [y, m, d] = value.split('-').map((/**
* @param {?} val
* @return {?}
*/
(val) => +val));
return new Date(y, m - 1, d);
}
/** @type {?} */
let match;
if (match = value.match(ISO8601_DATE_REGEX)) {
return isoStringToDate(match);
}
}
/** @type {?} */
const date = new Date((/** @type {?} */ (value)));
if (!isDate(date)) {
throw new Error(`Unable to convert "${value}" into a date`);
}
return date;
}
/**
* Converts a date in ISO8601 to a Date.
* Used instead of `Date.parse` because of browser discrepancies.
* @param {?} match
* @return {?}
*/
function isoStringToDate(match) {
/** @type {?} */
const date = new Date(0);
/** @type {?} */
let tzHour = 0;
/** @type {?} */
let tzMin = 0;
// match[8] means that the string contains "Z" (UTC) or a timezone like "+01:00" or "+0100"
/** @type {?} */
const dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear;
/** @type {?} */
const timeSetter = match[8] ? date.setUTCHours : date.setHours;
// if there is a timezone defined like "+01:00" or "+0100"
if (match[9]) {
tzHour = Number(match[9] + match[10]);
tzMin = Number(match[9] + match[11]);
}
dateSetter.call(date, Number(match[1]), Number(match[2]) - 1, Number(match[3]));
/** @type {?} */
const h = Number(match[4] || 0) - tzHour;
/** @type {?} */
const m = Number(match[5] || 0) - tzMin;
/** @type {?} */
const s = Number(match[6] || 0);
/** @type {?} */
const ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
timeSetter.call(date, h, m, s, ms);
return date;
}
/**
* @param {?} value
* @return {?}
*/
function isDate(value) {
return value instanceof Date && !isNaN(value.valueOf());
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/i18n/format_number.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
/** @type {?} */
const MAX_DIGITS = 22;
/** @type {?} */
const DECIMAL_SEP = '.';
/** @type {?} */
const ZERO_CHAR = '0';
/** @type {?} */
const PATTERN_SEP = ';';
/** @type {?} */
const GROUP_SEP = ',';
/** @type {?} */
const DIGIT_CHAR = '#';
/** @type {?} */
const CURRENCY_CHAR = '¤';
/** @type {?} */
const PERCENT_CHAR = '%';
/**
* Transforms a number to a locale string based on a style and a format.
* @param {?} value
* @param {?} pattern
* @param {?} locale
* @param {?} groupSymbol
* @param {?} decimalSymbol
* @param {?=} digitsInfo
* @param {?=} isPercent
* @return {?}
*/
function formatNumberToLocaleString(value, pattern, locale, groupSymbol, decimalSymbol, digitsInfo, isPercent = false) {
/** @type {?} */
let formattedText = '';
/** @type {?} */
let isZero = false;
if (!isFinite(value)) {
formattedText = getLocaleNumberSymbol(locale, NumberSymbol.Infinity);
}
else {
/** @type {?} */
let parsedNumber = parseNumber(value);
if (isPercent) {
parsedNumber = toPercent(parsedNumber);
}
/** @type {?} */
let minInt = pattern.minInt;
/** @type {?} */
let minFraction = pattern.minFrac;
/** @type {?} */
let maxFraction = pattern.maxFrac;
if (digitsInfo) {
/** @type {?} */
const parts = digitsInfo.match(NUMBER_FORMAT_REGEXP);
if (parts === null) {
throw new Error(`${digitsInfo} is not a valid digit info`);
}
/** @type {?} */
const minIntPart = parts[1];
/** @type {?} */
const minFractionPart = parts[3];
/** @type {?} */
const maxFractionPart = parts[5];
if (minIntPart != null) {
minInt = parseIntAutoRadix(minIntPart);
}
if (minFractionPart != null) {
minFraction = parseIntAutoRadix(minFractionPart);
}
if (maxFractionPart != null) {
maxFraction = parseIntAutoRadix(maxFractionPart);
}
else if (minFractionPart != null && minFraction > maxFraction) {
maxFraction = minFraction;
}
}
roundNumber(parsedNumber, minFraction, maxFraction);
/** @type {?} */
let digits = parsedNumber.digits;
/** @type {?} */
let integerLen = parsedNumber.integerLen;
/** @type {?} */
const exponent = parsedNumber.exponent;
/** @type {?} */
let decimals = [];
isZero = digits.every((/**
* @param {?} d
* @return {?}
*/
d => !d));
// pad zeros for small numbers
for (; integerLen < minInt; integerLen++) {
digits.unshift(0);
}
// pad zeros for small numbers
for (; integerLen < 0; integerLen++) {
digits.unshift(0);
}
// extract decimals digits
if (integerLen > 0) {
decimals = digits.splice(integerLen, digits.length);
}
else {
decimals = digits;
digits = [0];
}
// format the integer digits with grouping separators
/** @type {?} */
const groups = [];
if (digits.length >= pattern.lgSize) {
groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
}
while (digits.length > pattern.gSize) {
groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
}
if (digits.length) {
groups.unshift(digits.join(''));
}
formattedText = groups.join(getLocaleNumberSymbol(locale, groupSymbol));
// append the decimal digits
if (decimals.length) {
formattedText += getLocaleNumberSymbol(locale, decimalSymbol) + decimals.join('');
}
if (exponent) {
formattedText += getLocaleNumberSymbol(locale, NumberSymbol.Exponential) + '+' + exponent;
}
}
if (value < 0 && !isZero) {
formattedText = pattern.negPre + formattedText + pattern.negSuf;
}
else {
formattedText = pattern.posPre + formattedText + pattern.posSuf;
}
return formattedText;
}
/**
* \@ngModule CommonModule
* \@description
*
* Formats a number as currency using locale rules.
*
* @see `formatNumber()` / `DecimalPipe` / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} value The number to format.
* @param {?} locale A locale code for the locale format rules to use.
* @param {?} currency A string containing the currency symbol or its name,
* such as "$" or "Canadian Dollar". Used in output string, but does not affect the operation
* of the function.
* @param {?=} currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217)
* currency code, such as `USD` for the US dollar and `EUR` for the euro.
* Used to determine the number of digits in the decimal part.
* @param {?=} digitsInfo
* @return {?} The formatted currency value.
*
*/
function formatCurrency(value, locale, currency, currencyCode, digitsInfo) {
/** @type {?} */
const format = getLocaleNumberFormat(locale, NumberFormatStyle.Currency);
/** @type {?} */
const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
pattern.minFrac = getNumberOfCurrencyDigits((/** @type {?} */ (currencyCode)));
pattern.maxFrac = pattern.minFrac;
/** @type {?} */
const res = formatNumberToLocaleString(value, pattern, locale, NumberSymbol.CurrencyGroup, NumberSymbol.CurrencyDecimal, digitsInfo);
return res
.replace(CURRENCY_CHAR, currency)
// if we have 2 time the currency character, the second one is ignored
.replace(CURRENCY_CHAR, '')
// If there is a spacing between currency character and the value and
// the currency character is supressed by passing an empty string, the
// spacing character would remain as part of the string. Then we
// should remove it.
.trim();
}
/**
* \@ngModule CommonModule
* \@description
*
* Formats a number as a percentage according to locale rules.
*
* @see `formatNumber()` / `DecimalPipe` / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
* \@publicApi
*
* @param {?} value The number to format.
* @param {?} locale A locale code for the locale format rules to use.
* @param {?=} digitsInfo
* @return {?} The formatted percentage value.
*
*/
function formatPercent(value, locale, digitsInfo) {
/** @type {?} */
const format = getLocaleNumberFormat(locale, NumberFormatStyle.Percent);
/** @type {?} */
const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
/** @type {?} */
const res = formatNumberToLocaleString(value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo, true);
return res.replace(new RegExp(PERCENT_CHAR, 'g'), getLocaleNumberSymbol(locale, NumberSymbol.PercentSign));
}
/**
* \@ngModule CommonModule
* \@description
*
* Formats a number as text, with group sizing, separator, and other
* parameters based on the locale.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
*
* \@publicApi
* @param {?} value The number to format.
* @param {?} locale A locale code for the locale format rules to use.
* @param {?=} digitsInfo
* @return {?} The formatted text string.
*/
function formatNumber(value, locale, digitsInfo) {
/** @type {?} */
const format = getLocaleNumberFormat(locale, NumberFormatStyle.Decimal);
/** @type {?} */
const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
return formatNumberToLocaleString(value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo);
}
/**
* @record
*/
function ParsedNumberFormat() { }
if (false) {}
/**
* @param {?} format
* @param {?=} minusSign
* @return {?}
*/
function parseNumberFormat(format, minusSign = '-') {
/** @type {?} */
const p = {
minInt: 1,
minFrac: 0,
maxFrac: 0,
posPre: '',
posSuf: '',
negPre: '',
negSuf: '',
gSize: 0,
lgSize: 0
};
/** @type {?} */
const patternParts = format.split(PATTERN_SEP);
/** @type {?} */
const positive = patternParts[0];
/** @type {?} */
const negative = patternParts[1];
/** @type {?} */
const positiveParts = positive.indexOf(DECIMAL_SEP) !== -1 ?
positive.split(DECIMAL_SEP) :
[
positive.substring(0, positive.lastIndexOf(ZERO_CHAR) + 1),
positive.substring(positive.lastIndexOf(ZERO_CHAR) + 1)
];
/** @type {?} */
const integer = positiveParts[0];
/** @type {?} */
const fraction = positiveParts[1] || '';
p.posPre = integer.substr(0, integer.indexOf(DIGIT_CHAR));
for (let i = 0; i < fraction.length; i++) {
/** @type {?} */
const ch = fraction.charAt(i);
if (ch === ZERO_CHAR) {
p.minFrac = p.maxFrac = i + 1;
}
else if (ch === DIGIT_CHAR) {
p.maxFrac = i + 1;
}
else {
p.posSuf += ch;
}
}
/** @type {?} */
const groups = integer.split(GROUP_SEP);
p.gSize = groups[1] ? groups[1].length : 0;
p.lgSize = (groups[2] || groups[1]) ? (groups[2] || groups[1]).length : 0;
if (negative) {
/** @type {?} */
const trunkLen = positive.length - p.posPre.length - p.posSuf.length;
/** @type {?} */
const pos = negative.indexOf(DIGIT_CHAR);
p.negPre = negative.substr(0, pos).replace(/'/g, '');
p.negSuf = negative.substr(pos + trunkLen).replace(/'/g, '');
}
else {
p.negPre = minusSign + p.posPre;
p.negSuf = p.posSuf;
}
return p;
}
/**
* @record
*/
function ParsedNumber() { }
if (false) {}
// Transforms a parsed number into a percentage by multiplying it by 100
/**
* @param {?} parsedNumber
* @return {?}
*/
function toPercent(parsedNumber) {
// if the number is 0, don't do anything
if (parsedNumber.digits[0] === 0) {
return parsedNumber;
}
// Getting the current number of decimals
/** @type {?} */
const fractionLen = parsedNumber.digits.length - parsedNumber.integerLen;
if (parsedNumber.exponent) {
parsedNumber.exponent += 2;
}
else {
if (fractionLen === 0) {
parsedNumber.digits.push(0, 0);
}
else if (fractionLen === 1) {
parsedNumber.digits.push(0);
}
parsedNumber.integerLen += 2;
}
return parsedNumber;
}
/**
* Parses a number.
* Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/
* @param {?} num
* @return {?}
*/
function parseNumber(num) {
/** @type {?} */
let numStr = Math.abs(num) + '';
/** @type {?} */
let exponent = 0;
/** @type {?} */
let digits;
/** @type {?} */
let integerLen;
/** @type {?} */
let i;
/** @type {?} */
let j;
/** @type {?} */
let zeros;
// Decimal point?
if ((integerLen = numStr.indexOf(DECIMAL_SEP)) > -1) {
numStr = numStr.replace(DECIMAL_SEP, '');
}
// Exponential form?
if ((i = numStr.search(/e/i)) > 0) {
// Work out the exponent.
if (integerLen < 0)
integerLen = i;
integerLen += +numStr.slice(i + 1);
numStr = numStr.substring(0, i);
}
else if (integerLen < 0) {
// There was no decimal point or exponent so it is an integer.
integerLen = numStr.length;
}
// Count the number of leading zeros.
for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */
}
if (i === (zeros = numStr.length)) {
// The digits are all zero.
digits = [0];
integerLen = 1;
}
else {
// Count the number of trailing zeros
zeros--;
while (numStr.charAt(zeros) === ZERO_CHAR)
zeros--;
// Trailing zeros are insignificant so ignore them
integerLen -= i;
digits = [];
// Convert string to array of digits without leading/trailing zeros.
for (j = 0; i <= zeros; i++, j++) {
digits[j] = Number(numStr.charAt(i));
}
}
// If the number overflows the maximum allowed digits then use an exponent.
if (integerLen > MAX_DIGITS) {
digits = digits.splice(0, MAX_DIGITS - 1);
exponent = integerLen - 1;
integerLen = 1;
}
return { digits, exponent, integerLen };
}
/**
* Round the parsed number to the specified number of decimal places
* This function changes the parsedNumber in-place
* @param {?} parsedNumber
* @param {?} minFrac
* @param {?} maxFrac
* @return {?}
*/
function roundNumber(parsedNumber, minFrac, maxFrac) {
if (minFrac > maxFrac) {
throw new Error(`The minimum number of digits after fraction (${minFrac}) is higher than the maximum (${maxFrac}).`);
}
/** @type {?} */
let digits = parsedNumber.digits;
/** @type {?} */
let fractionLen = digits.length - parsedNumber.integerLen;
/** @type {?} */
const fractionSize = Math.min(Math.max(minFrac, fractionLen), maxFrac);
// The index of the digit to where rounding is to occur
/** @type {?} */
let roundAt = fractionSize + parsedNumber.integerLen;
/** @type {?} */
let digit = digits[roundAt];
if (roundAt > 0) {
// Drop fractional digits beyond `roundAt`
digits.splice(Math.max(parsedNumber.integerLen, roundAt));
// Set non-fractional digits beyond `roundAt` to 0
for (let j = roundAt; j < digits.length; j++) {
digits[j] = 0;
}
}
else {
// We rounded to zero so reset the parsedNumber
fractionLen = Math.max(0, fractionLen);
parsedNumber.integerLen = 1;
digits.length = Math.max(1, roundAt = fractionSize + 1);
digits[0] = 0;
for (let i = 1; i < roundAt; i++)
digits[i] = 0;
}
if (digit >= 5) {
if (roundAt - 1 < 0) {
for (let k = 0; k > roundAt; k--) {
digits.unshift(0);
parsedNumber.integerLen++;
}
digits.unshift(1);
parsedNumber.integerLen++;
}
else {
digits[roundAt - 1]++;
}
}
// Pad out with zeros to get the required fraction length
for (; fractionLen < Math.max(0, fractionSize); fractionLen++)
digits.push(0);
/** @type {?} */
let dropTrailingZeros = fractionSize !== 0;
// Minimal length = nb of decimals required + current nb of integers
// Any number besides that is optional and can be removed if it's a trailing 0
/** @type {?} */
const minLen = minFrac + parsedNumber.integerLen;
// Do any carrying, e.g. a digit was rounded up to 10
/** @type {?} */
const carry = digits.reduceRight((/**
* @param {?} carry
* @param {?} d
* @param {?} i
* @param {?} digits
* @return {?}
*/
function (carry, d, i, digits) {
d = d + carry;
digits[i] = d < 10 ? d : d - 10; // d % 10
if (dropTrailingZeros) {
// Do not keep meaningless fractional trailing zeros (e.g. 15.52000 --> 15.52)
if (digits[i] === 0 && i >= minLen) {
digits.pop();
}
else {
dropTrailingZeros = false;
}
}
return d >= 10 ? 1 : 0; // Math.floor(d / 10);
}), 0);
if (carry) {
digits.unshift(carry);
parsedNumber.integerLen++;
}
}
/**
* @param {?} text
* @return {?}
*/
function parseIntAutoRadix(text) {
/** @type {?} */
const result = parseInt(text);
if (isNaN(result)) {
throw new Error('Invalid integer literal when parsing ' + text);
}
return result;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/i18n/localization.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@publicApi
* @abstract
*/
class NgLocalization {
}
if (false) {}
/**
* Returns the plural category for a given value.
* - "=value" when the case exists,
* - the plural category otherwise
* @param {?} value
* @param {?} cases
* @param {?} ngLocalization
* @param {?=} locale
* @return {?}
*/
function getPluralCategory(value, cases, ngLocalization, locale) {
/** @type {?} */
let key = `=${value}`;
if (cases.indexOf(key) > -1) {
return key;
}
key = ngLocalization.getPluralCategory(value, locale);
if (cases.indexOf(key) > -1) {
return key;
}
if (cases.indexOf('other') > -1) {
return 'other';
}
throw new Error(`No plural message found for value "${value}"`);
}
/**
* Returns the plural case based on the locale
*
* \@publicApi
*/
class NgLocaleLocalization extends NgLocalization {
/**
* @param {?} locale
*/
constructor(locale) {
super();
this.locale = locale;
}
/**
* @param {?} value
* @param {?=} locale
* @return {?}
*/
getPluralCategory(value, locale) {
/** @type {?} */
const plural = getLocalePluralCase(locale || this.locale)(value);
switch (plural) {
case Plural.Zero:
return 'zero';
case Plural.One:
return 'one';
case Plural.Two:
return 'two';
case Plural.Few:
return 'few';
case Plural.Many:
return 'many';
default:
return 'other';
}
}
}
NgLocaleLocalization.ɵfac = function NgLocaleLocalization_Factory(t) { return new (t || NgLocaleLocalization)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"])); };
NgLocaleLocalization.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({ token: NgLocaleLocalization, factory: NgLocaleLocalization.ɵfac });
/** @nocollapse */
NgLocaleLocalization.ctorParameters = () => [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgLocaleLocalization, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injectable"]
}], function () { return [{ type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"],
args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"]]
}] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/i18n/locale_data.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Register global data to be used internally by Angular. See the
* ["I18n guide"](guide/i18n#i18n-pipes) to know how to import additional locale data.
*
* The signature registerLocaleData(data: any, extraData?: any) is deprecated since v5.1
*
* \@publicApi
* @param {?} data
* @param {?=} localeId
* @param {?=} extraData
* @return {?}
*/
function registerLocaleData(data, localeId, extraData) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵregisterLocaleData"])(data, localeId, extraData);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/cookie.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} cookieStr
* @param {?} name
* @return {?}
*/
function parseCookieValue(cookieStr, name) {
name = encodeURIComponent(name);
for (const cookie of cookieStr.split(';')) {
/** @type {?} */
const eqIndex = cookie.indexOf('=');
const [cookieName, cookieValue] = eqIndex == -1 ? [cookie, ''] : [cookie.slice(0, eqIndex), cookie.slice(eqIndex + 1)];
if (cookieName.trim() === name) {
return decodeURIComponent(cookieValue);
}
}
return null;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/directives/ng_class.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@ngModule CommonModule
*
* \@usageNotes
* ```
* <some-element [ngClass]="'first second'">...</some-element>
*
* <some-element [ngClass]="['first', 'second']">...</some-element>
*
* <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
*
* <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
*
* <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
* ```
*
* \@description
*
* Adds and removes CSS classes on an HTML element.
*
* The CSS classes are updated as follows, depending on the type of the expression evaluation:
* - `string` - the CSS classes listed in the string (space delimited) are added,
* - `Array` - the CSS classes declared as Array elements are added,
* - `Object` - keys are CSS classes that get added when the expression given in the value
* evaluates to a truthy value, otherwise they are removed.
*
* \@publicApi
*/
class NgClass {
/**
* @param {?} _iterableDiffers
* @param {?} _keyValueDiffers
* @param {?} _ngEl
* @param {?} _renderer
*/
constructor(_iterableDiffers, _keyValueDiffers, _ngEl, _renderer) {
this._iterableDiffers = _iterableDiffers;
this._keyValueDiffers = _keyValueDiffers;
this._ngEl = _ngEl;
this._renderer = _renderer;
this._iterableDiffer = null;
this._keyValueDiffer = null;
this._initialClasses = [];
this._rawClass = null;
}
/**
* @param {?} value
* @return {?}
*/
set klass(value) {
this._removeClasses(this._initialClasses);
this._initialClasses = typeof value === 'string' ? value.split(/\s+/) : [];
this._applyClasses(this._initialClasses);
this._applyClasses(this._rawClass);
}
/**
* @param {?} value
* @return {?}
*/
set ngClass(value) {
this._removeClasses(this._rawClass);
this._applyClasses(this._initialClasses);
this._iterableDiffer = null;
this._keyValueDiffer = null;
this._rawClass = typeof value === 'string' ? value.split(/\s+/) : value;
if (this._rawClass) {
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵisListLikeIterable"])(this._rawClass)) {
this._iterableDiffer = this._iterableDiffers.find(this._rawClass).create();
}
else {
this._keyValueDiffer = this._keyValueDiffers.find(this._rawClass).create();
}
}
}
/**
* @return {?}
*/
ngDoCheck() {
if (this._iterableDiffer) {
/** @type {?} */
const iterableChanges = this._iterableDiffer.diff((/** @type {?} */ (this._rawClass)));
if (iterableChanges) {
this._applyIterableChanges(iterableChanges);
}
}
else if (this._keyValueDiffer) {
/** @type {?} */
const keyValueChanges = this._keyValueDiffer.diff((/** @type {?} */ (this._rawClass)));
if (keyValueChanges) {
this._applyKeyValueChanges(keyValueChanges);
}
}
}
/**
* @private
* @param {?} changes
* @return {?}
*/
_applyKeyValueChanges(changes) {
changes.forEachAddedItem((/**
* @param {?} record
* @return {?}
*/
(record) => this._toggleClass(record.key, record.currentValue)));
changes.forEachChangedItem((/**
* @param {?} record
* @return {?}
*/
(record) => this._toggleClass(record.key, record.currentValue)));
changes.forEachRemovedItem((/**
* @param {?} record
* @return {?}
*/
(record) => {
if (record.previousValue) {
this._toggleClass(record.key, false);
}
}));
}
/**
* @private
* @param {?} changes
* @return {?}
*/
_applyIterableChanges(changes) {
changes.forEachAddedItem((/**
* @param {?} record
* @return {?}
*/
(record) => {
if (typeof record.item === 'string') {
this._toggleClass(record.item, true);
}
else {
throw new Error(`NgClass can only toggle CSS classes expressed as strings, got ${Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵstringify"])(record.item)}`);
}
}));
changes.forEachRemovedItem((/**
* @param {?} record
* @return {?}
*/
(record) => this._toggleClass(record.item, false)));
}
/**
* Applies a collection of CSS classes to the DOM element.
*
* For argument of type Set and Array CSS class names contained in those collections are always
* added.
* For argument of type Map CSS class name in the map's key is toggled based on the value (added
* for truthy and removed for falsy).
* @private
* @param {?} rawClassVal
* @return {?}
*/
_applyClasses(rawClassVal) {
if (rawClassVal) {
if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) {
((/** @type {?} */ (rawClassVal))).forEach((/**
* @param {?} klass
* @return {?}
*/
(klass) => this._toggleClass(klass, true)));
}
else {
Object.keys(rawClassVal).forEach((/**
* @param {?} klass
* @return {?}
*/
klass => this._toggleClass(klass, !!rawClassVal[klass])));
}
}
}
/**
* Removes a collection of CSS classes from the DOM element. This is mostly useful for cleanup
* purposes.
* @private
* @param {?} rawClassVal
* @return {?}
*/
_removeClasses(rawClassVal) {
if (rawClassVal) {
if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) {
((/** @type {?} */ (rawClassVal))).forEach((/**
* @param {?} klass
* @return {?}
*/
(klass) => this._toggleClass(klass, false)));
}
else {
Object.keys(rawClassVal).forEach((/**
* @param {?} klass
* @return {?}
*/
klass => this._toggleClass(klass, false)));
}
}
}
/**
* @private
* @param {?} klass
* @param {?} enabled
* @return {?}
*/
_toggleClass(klass, enabled) {
klass = klass.trim();
if (klass) {
klass.split(/\s+/g).forEach((/**
* @param {?} klass
* @return {?}
*/
klass => {
if (enabled) {
this._renderer.addClass(this._ngEl.nativeElement, klass);
}
else {
this._renderer.removeClass(this._ngEl.nativeElement, klass);
}
}));
}
}
}
NgClass.ɵfac = function NgClass_Factory(t) { return new (t || NgClass)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["IterableDiffers"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["KeyValueDiffers"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["ElementRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["Renderer2"])); };
NgClass.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgClass, selectors: [["", "ngClass", ""]], inputs: { klass: ["class", "klass"], ngClass: "ngClass" } });
/** @nocollapse */
NgClass.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["IterableDiffers"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["KeyValueDiffers"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ElementRef"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Renderer2"] }
];
NgClass.propDecorators = {
klass: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"], args: ['class',] }],
ngClass: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"], args: ['ngClass',] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgClass, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngClass]' }]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["IterableDiffers"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["KeyValueDiffers"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ElementRef"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Renderer2"] }]; }, { klass: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"],
args: ['class']
}], ngClass: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"],
args: ['ngClass']
}] }); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/directives/ng_component_outlet.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Instantiates a single {\@link Component} type and inserts its Host View into current View.
* `NgComponentOutlet` provides a declarative approach for dynamic component creation.
*
* `NgComponentOutlet` requires a component type, if a falsy value is set the view will clear and
* any existing component will get destroyed.
*
* \@usageNotes
*
* ### Fine tune control
*
* You can control the component creation process by using the following optional attributes:
*
* * `ngComponentOutletInjector`: Optional custom {\@link Injector} that will be used as parent for
* the Component. Defaults to the injector of the current view container.
*
* * `ngComponentOutletContent`: Optional list of projectable nodes to insert into the content
* section of the component, if exists.
*
* * `ngComponentOutletNgModuleFactory`: Optional module factory to allow dynamically loading other
* module, then load a component from that module.
*
* ### Syntax
*
* Simple
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression"></ng-container>
* ```
*
* Customized injector/content
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression;
* injector: injectorExpression;
* content: contentNodesExpression;">
* </ng-container>
* ```
*
* Customized ngModuleFactory
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression;
* ngModuleFactory: moduleFactory;">
* </ng-container>
* ```
*
* ### A simple example
*
* {\@example common/ngComponentOutlet/ts/module.ts region='SimpleExample'}
*
* A more complete example with additional options:
*
* {\@example common/ngComponentOutlet/ts/module.ts region='CompleteExample'}
*
* \@publicApi
* \@ngModule CommonModule
*/
class NgComponentOutlet {
/**
* @param {?} _viewContainerRef
*/
constructor(_viewContainerRef) {
this._viewContainerRef = _viewContainerRef;
this._componentRef = null;
this._moduleRef = null;
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
this._viewContainerRef.clear();
this._componentRef = null;
if (this.ngComponentOutlet) {
/** @type {?} */
const elInjector = this.ngComponentOutletInjector || this._viewContainerRef.parentInjector;
if (changes['ngComponentOutletNgModuleFactory']) {
if (this._moduleRef)
this._moduleRef.destroy();
if (this.ngComponentOutletNgModuleFactory) {
/** @type {?} */
const parentModule = elInjector.get(_angular_core__WEBPACK_IMPORTED_MODULE_0__["NgModuleRef"]);
this._moduleRef = this.ngComponentOutletNgModuleFactory.create(parentModule.injector);
}
else {
this._moduleRef = null;
}
}
/** @type {?} */
const componentFactoryResolver = this._moduleRef ? this._moduleRef.componentFactoryResolver :
elInjector.get(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ComponentFactoryResolver"]);
/** @type {?} */
const componentFactory = componentFactoryResolver.resolveComponentFactory(this.ngComponentOutlet);
this._componentRef = this._viewContainerRef.createComponent(componentFactory, this._viewContainerRef.length, elInjector, this.ngComponentOutletContent);
}
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this._moduleRef)
this._moduleRef.destroy();
}
}
NgComponentOutlet.ɵfac = function NgComponentOutlet_Factory(t) { return new (t || NgComponentOutlet)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"])); };
NgComponentOutlet.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgComponentOutlet, selectors: [["", "ngComponentOutlet", ""]], inputs: { ngComponentOutlet: "ngComponentOutlet", ngComponentOutletInjector: "ngComponentOutletInjector", ngComponentOutletContent: "ngComponentOutletContent", ngComponentOutletNgModuleFactory: "ngComponentOutletNgModuleFactory" }, features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵNgOnChangesFeature"]] });
/** @nocollapse */
NgComponentOutlet.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] }
];
NgComponentOutlet.propDecorators = {
ngComponentOutlet: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }],
ngComponentOutletInjector: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }],
ngComponentOutletContent: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }],
ngComponentOutletNgModuleFactory: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgComponentOutlet, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngComponentOutlet]' }]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] }]; }, { ngComponentOutlet: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}], ngComponentOutletInjector: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}], ngComponentOutletContent: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}], ngComponentOutletNgModuleFactory: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}] }); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/directives/ng_for_of.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@publicApi
* @template T, U
*/
class NgForOfContext {
/**
* @param {?} $implicit
* @param {?} ngForOf
* @param {?} index
* @param {?} count
*/
constructor($implicit, ngForOf, index, count) {
this.$implicit = $implicit;
this.ngForOf = ngForOf;
this.index = index;
this.count = count;
}
/**
* @return {?}
*/
get first() {
return this.index === 0;
}
/**
* @return {?}
*/
get last() {
return this.index === this.count - 1;
}
/**
* @return {?}
*/
get even() {
return this.index % 2 === 0;
}
/**
* @return {?}
*/
get odd() {
return !this.even;
}
}
if (false) {}
/**
* A [structural directive](guide/structural-directives) that renders
* a template for each item in a collection.
* The directive is placed on an element, which becomes the parent
* of the cloned templates.
*
* The `ngForOf` directive is generally used in the
* [shorthand form](guide/structural-directives#the-asterisk--prefix) `*ngFor`.
* In this form, the template to be rendered for each iteration is the content
* of an anchor element containing the directive.
*
* The following example shows the shorthand syntax with some options,
* contained in an `<li>` element.
*
* ```
* <li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li>
* ```
*
* The shorthand form expands into a long form that uses the `ngForOf` selector
* on an `<ng-template>` element.
* The content of the `<ng-template>` element is the `<li>` element that held the
* short-form directive.
*
* Here is the expanded version of the short-form example.
*
* ```
* <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn">
* <li>...</li>
* </ng-template>
* ```
*
* Angular automatically expands the shorthand syntax as it compiles the template.
* The context for each embedded view is logically merged to the current component
* context according to its lexical position.
*
* When using the shorthand syntax, Angular allows only [one structural directive
* on an element](guide/structural-directives#one-structural-directive-per-host-element).
* If you want to iterate conditionally, for example,
* put the `*ngIf` on a container element that wraps the `*ngFor` element.
* For futher discussion, see
* [Structural Directives](guide/structural-directives#one-per-element).
*
* \@usageNotes
*
* ### Local variables
*
* `NgForOf` provides exported values that can be aliased to local variables.
* For example:
*
* ```
* <li *ngFor="let user of users; index as i; first as isFirst">
* {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span>
* </li>
* ```
*
* The following exported values can be aliased to local variables:
*
* - `$implicit: T`: The value of the individual items in the iterable (`ngForOf`).
* - `ngForOf: NgIterable<T>`: The value of the iterable expression. Useful when the expression is
* more complex then a property access, for example when using the async pipe (`userStreams |
* async`).
* - `index: number`: The index of the current item in the iterable.
* - `count: number`: The length of the iterable.
* - `first: boolean`: True when the item is the first item in the iterable.
* - `last: boolean`: True when the item is the last item in the iterable.
* - `even: boolean`: True when the item has an even index in the iterable.
* - `odd: boolean`: True when the item has an odd index in the iterable.
*
* ### Change propagation
*
* When the contents of the iterator changes, `NgForOf` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
*
* Angular uses object identity to track insertions and deletions within the iterator and reproduce
* those changes in the DOM. This has important implications for animations and any stateful
* controls that are present, such as `<input>` elements that accept user input. Inserted rows can
* be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state
* such as user input.
* For more on animations, see [Transitions and Triggers](guide/transition-and-triggers).
*
* The identities of elements in the iterator can change while the data does not.
* This can happen, for example, if the iterator is produced from an RPC to the server, and that
* RPC is re-run. Even if the data hasn't changed, the second response produces objects with
* different identities, and Angular must tear down the entire DOM and rebuild it (as if all old
* elements were deleted and all new elements inserted).
*
* To avoid this expensive operation, you can customize the default tracking algorithm.
* by supplying the `trackBy` option to `NgForOf`.
* `trackBy` takes a function that has two arguments: `index` and `item`.
* If `trackBy` is given, Angular tracks changes by the return value of the function.
*
* @see [Structural Directives](guide/structural-directives)
* \@ngModule CommonModule
* \@publicApi
* @template T, U
*/
class NgForOf {
/**
* @param {?} _viewContainer
* @param {?} _template
* @param {?} _differs
*/
constructor(_viewContainer, _template, _differs) {
this._viewContainer = _viewContainer;
this._template = _template;
this._differs = _differs;
this._ngForOf = null;
this._ngForOfDirty = true;
this._differ = null;
}
/**
* The value of the iterable expression, which can be used as a
* [template input variable](guide/structural-directives#template-input-variable).
* @param {?} ngForOf
* @return {?}
*/
set ngForOf(ngForOf) {
this._ngForOf = ngForOf;
this._ngForOfDirty = true;
}
/**
* A function that defines how to track changes for items in the iterable.
*
* When items are added, moved, or removed in the iterable,
* the directive must re-render the appropriate DOM nodes.
* To minimize churn in the DOM, only nodes that have changed
* are re-rendered.
*
* By default, the change detector assumes that
* the object instance identifies the node in the iterable.
* When this function is supplied, the directive uses
* the result of calling this function to identify the item node,
* rather than the identity of the object itself.
*
* The function receives two inputs,
* the iteration index and the node object ID.
* @param {?} fn
* @return {?}
*/
set ngForTrackBy(fn) {
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["isDevMode"])() && fn != null && typeof fn !== 'function') {
// TODO(vicb): use a log service once there is a public one available
if ((/** @type {?} */ (console)) && (/** @type {?} */ (console.warn))) {
console.warn(`trackBy must be a function, but received ${JSON.stringify(fn)}. ` +
`See https://angular.io/api/common/NgForOf#change-propagation for more information.`);
}
}
this._trackByFn = fn;
}
/**
* @return {?}
*/
get ngForTrackBy() {
return this._trackByFn;
}
/**
* A reference to the template that is stamped out for each item in the iterable.
* @see [template reference variable](guide/template-syntax#template-reference-variables--var-)
* @param {?} value
* @return {?}
*/
set ngForTemplate(value) {
// TODO(TS2.1): make TemplateRef<Partial<NgForRowOf<T>>> once we move to TS v2.1
// The current type is too restrictive; a template that just uses index, for example,
// should be acceptable.
if (value) {
this._template = value;
}
}
/**
* Applies the changes when needed.
* @return {?}
*/
ngDoCheck() {
if (this._ngForOfDirty) {
this._ngForOfDirty = false;
// React on ngForOf changes only once all inputs have been initialized
/** @type {?} */
const value = this._ngForOf;
if (!this._differ && value) {
try {
this._differ = this._differs.find(value).create(this.ngForTrackBy);
}
catch (_a) {
throw new Error(`Cannot find a differ supporting object '${value}' of type '${getTypeName(value)}'. NgFor only supports binding to Iterables such as Arrays.`);
}
}
}
if (this._differ) {
/** @type {?} */
const changes = this._differ.diff(this._ngForOf);
if (changes)
this._applyChanges(changes);
}
}
/**
* @private
* @param {?} changes
* @return {?}
*/
_applyChanges(changes) {
/** @type {?} */
const insertTuples = [];
changes.forEachOperation((/**
* @param {?} item
* @param {?} adjustedPreviousIndex
* @param {?} currentIndex
* @return {?}
*/
(item, adjustedPreviousIndex, currentIndex) => {
if (item.previousIndex == null) {
// NgForOf is never "null" or "undefined" here because the differ detected
// that a new item needs to be inserted from the iterable. This implies that
// there is an iterable value for "_ngForOf".
/** @type {?} */
const view = this._viewContainer.createEmbeddedView(this._template, new NgForOfContext((/** @type {?} */ (null)), (/** @type {?} */ (this._ngForOf)), -1, -1), currentIndex === null ? undefined : currentIndex);
/** @type {?} */
const tuple = new RecordViewTuple(item, view);
insertTuples.push(tuple);
}
else if (currentIndex == null) {
this._viewContainer.remove(adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex);
}
else if (adjustedPreviousIndex !== null) {
/** @type {?} */
const view = (/** @type {?} */ (this._viewContainer.get(adjustedPreviousIndex)));
this._viewContainer.move(view, currentIndex);
/** @type {?} */
const tuple = new RecordViewTuple(item, (/** @type {?} */ (view)));
insertTuples.push(tuple);
}
}));
for (let i = 0; i < insertTuples.length; i++) {
this._perViewChange(insertTuples[i].view, insertTuples[i].record);
}
for (let i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
/** @type {?} */
const viewRef = (/** @type {?} */ (this._viewContainer.get(i)));
viewRef.context.index = i;
viewRef.context.count = ilen;
viewRef.context.ngForOf = (/** @type {?} */ (this._ngForOf));
}
changes.forEachIdentityChange((/**
* @param {?} record
* @return {?}
*/
(record) => {
/** @type {?} */
const viewRef = (/** @type {?} */ (this._viewContainer.get(record.currentIndex)));
viewRef.context.$implicit = record.item;
}));
}
/**
* @private
* @param {?} view
* @param {?} record
* @return {?}
*/
_perViewChange(view, record) {
view.context.$implicit = record.item;
}
/**
* Asserts the correct type of the context for the template that `NgForOf` will render.
*
* The presence of this method is a signal to the Ivy template type-check compiler that the
* `NgForOf` structural directive renders its template with a specific context type.
* @template T, U
* @param {?} dir
* @param {?} ctx
* @return {?}
*/
static ngTemplateContextGuard(dir, ctx) {
return true;
}
}
NgForOf.ɵfac = function NgForOf_Factory(t) { return new (t || NgForOf)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["IterableDiffers"])); };
NgForOf.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgForOf, selectors: [["", "ngFor", "", "ngForOf", ""]], inputs: { ngForOf: "ngForOf", ngForTrackBy: "ngForTrackBy", ngForTemplate: "ngForTemplate" } });
/** @nocollapse */
NgForOf.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["IterableDiffers"] }
];
NgForOf.propDecorators = {
ngForOf: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }],
ngForTrackBy: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }],
ngForTemplate: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgForOf, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngFor][ngForOf]' }]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["IterableDiffers"] }]; }, { ngForOf: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}], ngForTrackBy: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}], ngForTemplate: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}] }); })();
if (false) {}
/**
* @template T, U
*/
class RecordViewTuple {
/**
* @param {?} record
* @param {?} view
*/
constructor(record, view) {
this.record = record;
this.view = view;
}
}
if (false) {}
/**
* @param {?} type
* @return {?}
*/
function getTypeName(type) {
return type['name'] || typeof type;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/directives/ng_if.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A structural directive that conditionally includes a template based on the value of
* an expression coerced to Boolean.
* When the expression evaluates to true, Angular renders the template
* provided in a `then` clause, and when false or null,
* Angular renders the template provided in an optional `else` clause. The default
* template for the `else` clause is blank.
*
* A [shorthand form](guide/structural-directives#the-asterisk--prefix) of the directive,
* `*ngIf="condition"`, is generally used, provided
* as an attribute of the anchor element for the inserted template.
* Angular expands this into a more explicit version, in which the anchor element
* is contained in an `<ng-template>` element.
*
* Simple form with shorthand syntax:
*
* ```
* <div *ngIf="condition">Content to render when condition is true.</div>
* ```
*
* Simple form with expanded syntax:
*
* ```
* <ng-template [ngIf]="condition"><div>Content to render when condition is
* true.</div></ng-template>
* ```
*
* Form with an "else" block:
*
* ```
* <div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
* <ng-template #elseBlock>Content to render when condition is false.</ng-template>
* ```
*
* Shorthand form with "then" and "else" blocks:
*
* ```
* <div *ngIf="condition; then thenBlock else elseBlock"></div>
* <ng-template #thenBlock>Content to render when condition is true.</ng-template>
* <ng-template #elseBlock>Content to render when condition is false.</ng-template>
* ```
*
* Form with storing the value locally:
*
* ```
* <div *ngIf="condition as value; else elseBlock">{{value}}</div>
* <ng-template #elseBlock>Content to render when value is null.</ng-template>
* ```
*
* \@usageNotes
*
* The `*ngIf` directive is most commonly used to conditionally show an inline template,
* as seen in the following example.
* The default `else` template is blank.
*
* {\@example common/ngIf/ts/module.ts region='NgIfSimple'}
*
* ### Showing an alternative template using `else`
*
* To display a template when `expression` evaluates to false, use an `else` template
* binding as shown in the following example.
* The `else` binding points to an `<ng-template>` element labeled `#elseBlock`.
* The template can be defined anywhere in the component view, but is typically placed right after
* `ngIf` for readability.
*
* {\@example common/ngIf/ts/module.ts region='NgIfElse'}
*
* ### Using an external `then` template
*
* In the previous example, the then-clause template is specified inline, as the content of the
* tag that contains the `ngIf` directive. You can also specify a template that is defined
* externally, by referencing a labeled `<ng-template>` element. When you do this, you can
* change which template to use at runtime, as shown in the following example.
*
* {\@example common/ngIf/ts/module.ts region='NgIfThenElse'}
*
* ### Storing a conditional result in a variable
*
* You might want to show a set of properties from the same object. If you are waiting
* for asynchronous data, the object can be undefined.
* In this case, you can use `ngIf` and store the result of the condition in a local
* variable as shown in the the following example.
*
* {\@example common/ngIf/ts/module.ts region='NgIfAs'}
*
* This code uses only one `AsyncPipe`, so only one subscription is created.
* The conditional statement stores the result of `userStream|async` in the local variable `user`.
* You can then bind the local `user` repeatedly.
*
* The conditional displays the data only if `userStream` returns a value,
* so you don't need to use the
* [safe-navigation-operator](guide/template-syntax#safe-navigation-operator) (`?.`)
* to guard against null values when accessing properties.
* You can display an alternative template while waiting for the data.
*
* ### Shorthand syntax
*
* The shorthand syntax `*ngIf` expands into two separate template specifications
* for the "then" and "else" clauses. For example, consider the following shorthand statement,
* that is meant to show a loading page while waiting for data to be loaded.
*
* ```
* <div class="hero-list" *ngIf="heroes else loading">
* ...
* </div>
*
* <ng-template #loading>
* <div>Loading...</div>
* </ng-template>
* ```
*
* You can see that the "else" clause references the `<ng-template>`
* with the `#loading` label, and the template for the "then" clause
* is provided as the content of the anchor element.
*
* However, when Angular expands the shorthand syntax, it creates
* another `<ng-template>` tag, with `ngIf` and `ngIfElse` directives.
* The anchor element containing the template for the "then" clause becomes
* the content of this unlabeled `<ng-template>` tag.
*
* ```
* <ng-template [ngIf]="heroes" [ngIfElse]="loading">
* <div class="hero-list">
* ...
* </div>
* </ng-template>
*
* <ng-template #loading>
* <div>Loading...</div>
* </ng-template>
* ```
*
* The presence of the implicit template object has implications for the nesting of
* structural directives. For more on this subject, see
* [Structural Directives](https://angular.io/guide/structural-directives#one-per-element).
*
* \@ngModule CommonModule
* \@publicApi
* @template T
*/
class NgIf {
/**
* @param {?} _viewContainer
* @param {?} templateRef
*/
constructor(_viewContainer, templateRef) {
this._viewContainer = _viewContainer;
this._context = new NgIfContext();
this._thenTemplateRef = null;
this._elseTemplateRef = null;
this._thenViewRef = null;
this._elseViewRef = null;
this._thenTemplateRef = templateRef;
}
/**
* The Boolean expression to evaluate as the condition for showing a template.
* @param {?} condition
* @return {?}
*/
set ngIf(condition) {
this._context.$implicit = this._context.ngIf = condition;
this._updateView();
}
/**
* A template to show if the condition expression evaluates to true.
* @param {?} templateRef
* @return {?}
*/
set ngIfThen(templateRef) {
assertTemplate('ngIfThen', templateRef);
this._thenTemplateRef = templateRef;
this._thenViewRef = null; // clear previous view if any.
this._updateView();
}
/**
* A template to show if the condition expression evaluates to false.
* @param {?} templateRef
* @return {?}
*/
set ngIfElse(templateRef) {
assertTemplate('ngIfElse', templateRef);
this._elseTemplateRef = templateRef;
this._elseViewRef = null; // clear previous view if any.
this._updateView();
}
/**
* @private
* @return {?}
*/
_updateView() {
if (this._context.$implicit) {
if (!this._thenViewRef) {
this._viewContainer.clear();
this._elseViewRef = null;
if (this._thenTemplateRef) {
this._thenViewRef =
this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
}
}
}
else {
if (!this._elseViewRef) {
this._viewContainer.clear();
this._thenViewRef = null;
if (this._elseTemplateRef) {
this._elseViewRef =
this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context);
}
}
}
}
/**
* Asserts the correct type of the context for the template that `NgIf` will render.
*
* The presence of this method is a signal to the Ivy template type-check compiler that the
* `NgIf` structural directive renders its template with a specific context type.
* @template T
* @param {?} dir
* @param {?} ctx
* @return {?}
*/
static ngTemplateContextGuard(dir, ctx) {
return true;
}
}
NgIf.ɵfac = function NgIf_Factory(t) { return new (t || NgIf)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"])); };
NgIf.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgIf, selectors: [["", "ngIf", ""]], inputs: { ngIf: "ngIf", ngIfThen: "ngIfThen", ngIfElse: "ngIfElse" } });
/** @nocollapse */
NgIf.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"] }
];
NgIf.propDecorators = {
ngIf: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }],
ngIfThen: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }],
ngIfElse: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgIf, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngIf]' }]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"] }]; }, { ngIf: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}], ngIfThen: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}], ngIfElse: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}] }); })();
if (false) {}
/**
* \@publicApi
* @template T
*/
class NgIfContext {
constructor() {
this.$implicit = (/** @type {?} */ (null));
this.ngIf = (/** @type {?} */ (null));
}
}
if (false) {}
/**
* @param {?} property
* @param {?} templateRef
* @return {?}
*/
function assertTemplate(property, templateRef) {
/** @type {?} */
const isTemplateRefOrNull = !!(!templateRef || templateRef.createEmbeddedView);
if (!isTemplateRefOrNull) {
throw new Error(`${property} must be a TemplateRef, but received '${Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵstringify"])(templateRef)}'.`);
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/directives/ng_switch.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class SwitchView {
/**
* @param {?} _viewContainerRef
* @param {?} _templateRef
*/
constructor(_viewContainerRef, _templateRef) {
this._viewContainerRef = _viewContainerRef;
this._templateRef = _templateRef;
this._created = false;
}
/**
* @return {?}
*/
create() {
this._created = true;
this._viewContainerRef.createEmbeddedView(this._templateRef);
}
/**
* @return {?}
*/
destroy() {
this._created = false;
this._viewContainerRef.clear();
}
/**
* @param {?} created
* @return {?}
*/
enforceState(created) {
if (created && !this._created) {
this.create();
}
else if (!created && this._created) {
this.destroy();
}
}
}
if (false) {}
/**
* \@ngModule CommonModule
*
* \@description
* The `[ngSwitch]` directive on a container specifies an expression to match against.
* The expressions to match are provided by `ngSwitchCase` directives on views within the container.
* - Every view that matches is rendered.
* - If there are no matches, a view with the `ngSwitchDefault` directive is rendered.
* - Elements within the `[NgSwitch]` statement but outside of any `NgSwitchCase`
* or `ngSwitchDefault` directive are preserved at the location.
*
* \@usageNotes
* Define a container element for the directive, and specify the switch expression
* to match against as an attribute:
*
* ```
* <container-element [ngSwitch]="switch_expression">
* ```
*
* Within the container, `*ngSwitchCase` statements specify the match expressions
* as attributes. Include `*ngSwitchDefault` as the final case.
*
* ```
* <container-element [ngSwitch]="switch_expression">
* <some-element *ngSwitchCase="match_expression_1">...</some-element>
* ...
* <some-element *ngSwitchDefault>...</some-element>
* </container-element>
* ```
*
* ### Usage Examples
*
* The following example shows how to use more than one case to display the same view:
*
* ```
* <container-element [ngSwitch]="switch_expression">
* <!-- the same view can be shown in more than one case -->
* <some-element *ngSwitchCase="match_expression_1">...</some-element>
* <some-element *ngSwitchCase="match_expression_2">...</some-element>
* <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
* <!--default case when there are no matches -->
* <some-element *ngSwitchDefault>...</some-element>
* </container-element>
* ```
*
* The following example shows how cases can be nested:
* ```
* <container-element [ngSwitch]="switch_expression">
* <some-element *ngSwitchCase="match_expression_1">...</some-element>
* <some-element *ngSwitchCase="match_expression_2">...</some-element>
* <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
* <ng-container *ngSwitchCase="match_expression_3">
* <!-- use a ng-container to group multiple root nodes -->
* <inner-element></inner-element>
* <inner-other-element></inner-other-element>
* </ng-container>
* <some-element *ngSwitchDefault>...</some-element>
* </container-element>
* ```
*
* \@publicApi
* @see `NgSwitchCase`
* @see `NgSwitchDefault`
* @see [Structural Directives](guide/structural-directives)
*
*/
class NgSwitch {
constructor() {
this._defaultUsed = false;
this._caseCount = 0;
this._lastCaseCheckIndex = 0;
this._lastCasesMatched = false;
}
/**
* @param {?} newValue
* @return {?}
*/
set ngSwitch(newValue) {
this._ngSwitch = newValue;
if (this._caseCount === 0) {
this._updateDefaultCases(true);
}
}
/**
* \@internal
* @return {?}
*/
_addCase() {
return this._caseCount++;
}
/**
* \@internal
* @param {?} view
* @return {?}
*/
_addDefault(view) {
if (!this._defaultViews) {
this._defaultViews = [];
}
this._defaultViews.push(view);
}
/**
* \@internal
* @param {?} value
* @return {?}
*/
_matchCase(value) {
/** @type {?} */
const matched = value == this._ngSwitch;
this._lastCasesMatched = this._lastCasesMatched || matched;
this._lastCaseCheckIndex++;
if (this._lastCaseCheckIndex === this._caseCount) {
this._updateDefaultCases(!this._lastCasesMatched);
this._lastCaseCheckIndex = 0;
this._lastCasesMatched = false;
}
return matched;
}
/**
* @private
* @param {?} useDefault
* @return {?}
*/
_updateDefaultCases(useDefault) {
if (this._defaultViews && useDefault !== this._defaultUsed) {
this._defaultUsed = useDefault;
for (let i = 0; i < this._defaultViews.length; i++) {
/** @type {?} */
const defaultView = this._defaultViews[i];
defaultView.enforceState(useDefault);
}
}
}
}
NgSwitch.ɵfac = function NgSwitch_Factory(t) { return new (t || NgSwitch)(); };
NgSwitch.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgSwitch, selectors: [["", "ngSwitch", ""]], inputs: { ngSwitch: "ngSwitch" } });
NgSwitch.propDecorators = {
ngSwitch: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgSwitch, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngSwitch]' }]
}], function () { return []; }, { ngSwitch: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}] }); })();
if (false) {}
/**
* \@ngModule CommonModule
*
* \@description
* Provides a switch case expression to match against an enclosing `ngSwitch` expression.
* When the expressions match, the given `NgSwitchCase` template is rendered.
* If multiple match expressions match the switch expression value, all of them are displayed.
*
* \@usageNotes
*
* Within a switch container, `*ngSwitchCase` statements specify the match expressions
* as attributes. Include `*ngSwitchDefault` as the final case.
*
* ```
* <container-element [ngSwitch]="switch_expression">
* <some-element *ngSwitchCase="match_expression_1">...</some-element>
* ...
* <some-element *ngSwitchDefault>...</some-element>
* </container-element>
* ```
*
* Each switch-case statement contains an in-line HTML template or template reference
* that defines the subtree to be selected if the value of the match expression
* matches the value of the switch expression.
*
* Unlike JavaScript, which uses strict equality, Angular uses loose equality.
* This means that the empty string, `""` matches 0.
*
* \@publicApi
* @see `NgSwitch`
* @see `NgSwitchDefault`
*
*/
class NgSwitchCase {
/**
* @param {?} viewContainer
* @param {?} templateRef
* @param {?} ngSwitch
*/
constructor(viewContainer, templateRef, ngSwitch) {
this.ngSwitch = ngSwitch;
ngSwitch._addCase();
this._view = new SwitchView(viewContainer, templateRef);
}
/**
* Performs case matching. For internal use only.
* @return {?}
*/
ngDoCheck() {
this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase));
}
}
NgSwitchCase.ɵfac = function NgSwitchCase_Factory(t) { return new (t || NgSwitchCase)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgSwitch, 1)); };
NgSwitchCase.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgSwitchCase, selectors: [["", "ngSwitchCase", ""]], inputs: { ngSwitchCase: "ngSwitchCase" } });
/** @nocollapse */
NgSwitchCase.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"] },
{ type: NgSwitch, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Host"] }] }
];
NgSwitchCase.propDecorators = {
ngSwitchCase: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgSwitchCase, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngSwitchCase]' }]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"] }, { type: NgSwitch, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Host"]
}] }]; }, { ngSwitchCase: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}] }); })();
if (false) {}
/**
* \@ngModule CommonModule
*
* \@description
*
* Creates a view that is rendered when no `NgSwitchCase` expressions
* match the `NgSwitch` expression.
* This statement should be the final case in an `NgSwitch`.
*
* \@publicApi
* @see `NgSwitch`
* @see `NgSwitchCase`
*
*/
class NgSwitchDefault {
/**
* @param {?} viewContainer
* @param {?} templateRef
* @param {?} ngSwitch
*/
constructor(viewContainer, templateRef, ngSwitch) {
ngSwitch._addDefault(new SwitchView(viewContainer, templateRef));
}
}
NgSwitchDefault.ɵfac = function NgSwitchDefault_Factory(t) { return new (t || NgSwitchDefault)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgSwitch, 1)); };
NgSwitchDefault.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgSwitchDefault, selectors: [["", "ngSwitchDefault", ""]] });
/** @nocollapse */
NgSwitchDefault.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"] },
{ type: NgSwitch, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Host"] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgSwitchDefault, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngSwitchDefault]' }]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"] }, { type: NgSwitch, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Host"]
}] }]; }, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/directives/ng_plural.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@ngModule CommonModule
*
* \@usageNotes
* ```
* <some-element [ngPlural]="value">
* <ng-template ngPluralCase="=0">there is nothing</ng-template>
* <ng-template ngPluralCase="=1">there is one</ng-template>
* <ng-template ngPluralCase="few">there are a few</ng-template>
* </some-element>
* ```
*
* \@description
*
* Adds / removes DOM sub-trees based on a numeric value. Tailored for pluralization.
*
* Displays DOM sub-trees that match the switch expression value, or failing that, DOM sub-trees
* that match the switch expression's pluralization category.
*
* To use this directive you must provide a container element that sets the `[ngPlural]` attribute
* to a switch expression. Inner elements with a `[ngPluralCase]` will display based on their
* expression:
* - if `[ngPluralCase]` is set to a value starting with `=`, it will only display if the value
* matches the switch expression exactly,
* - otherwise, the view will be treated as a "category match", and will only display if exact
* value matches aren't found and the value maps to its category for the defined locale.
*
* See http://cldr.unicode.org/index/cldr-spec/plural-rules
*
* \@publicApi
*/
class NgPlural {
/**
* @param {?} _localization
*/
constructor(_localization) {
this._localization = _localization;
this._caseViews = {};
}
/**
* @param {?} value
* @return {?}
*/
set ngPlural(value) {
this._switchValue = value;
this._updateView();
}
/**
* @param {?} value
* @param {?} switchView
* @return {?}
*/
addCase(value, switchView) {
this._caseViews[value] = switchView;
}
/**
* @private
* @return {?}
*/
_updateView() {
this._clearViews();
/** @type {?} */
const cases = Object.keys(this._caseViews);
/** @type {?} */
const key = getPluralCategory(this._switchValue, cases, this._localization);
this._activateView(this._caseViews[key]);
}
/**
* @private
* @return {?}
*/
_clearViews() {
if (this._activeView)
this._activeView.destroy();
}
/**
* @private
* @param {?} view
* @return {?}
*/
_activateView(view) {
if (view) {
this._activeView = view;
this._activeView.create();
}
}
}
NgPlural.ɵfac = function NgPlural_Factory(t) { return new (t || NgPlural)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgLocalization)); };
NgPlural.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgPlural, selectors: [["", "ngPlural", ""]], inputs: { ngPlural: "ngPlural" } });
/** @nocollapse */
NgPlural.ctorParameters = () => [
{ type: NgLocalization }
];
NgPlural.propDecorators = {
ngPlural: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgPlural, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngPlural]' }]
}], function () { return [{ type: NgLocalization }]; }, { ngPlural: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}] }); })();
if (false) {}
/**
* \@ngModule CommonModule
*
* \@description
*
* Creates a view that will be added/removed from the parent {\@link NgPlural} when the
* given expression matches the plural expression according to CLDR rules.
*
* \@usageNotes
* ```
* <some-element [ngPlural]="value">
* <ng-template ngPluralCase="=0">...</ng-template>
* <ng-template ngPluralCase="other">...</ng-template>
* </some-element>
* ```
*
* See {\@link NgPlural} for more details and example.
*
* \@publicApi
*/
class NgPluralCase {
/**
* @param {?} value
* @param {?} template
* @param {?} viewContainer
* @param {?} ngPlural
*/
constructor(value, template, viewContainer, ngPlural) {
this.value = value;
/** @type {?} */
const isANumber = !isNaN(Number(value));
ngPlural.addCase(isANumber ? `=${value}` : value, new SwitchView(viewContainer, template));
}
}
NgPluralCase.ɵfac = function NgPluralCase_Factory(t) { return new (t || NgPluralCase)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinjectAttribute"]('ngPluralCase'), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgPlural, 1)); };
NgPluralCase.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgPluralCase, selectors: [["", "ngPluralCase", ""]] });
/** @nocollapse */
NgPluralCase.ctorParameters = () => [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Attribute"], args: ['ngPluralCase',] }] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] },
{ type: NgPlural, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Host"] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgPluralCase, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngPluralCase]' }]
}], function () { return [{ type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Attribute"],
args: ['ngPluralCase']
}] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["TemplateRef"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] }, { type: NgPlural, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Host"]
}] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/directives/ng_style.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@ngModule CommonModule
*
* \@usageNotes
*
* Set the font of the containing element to the result of an expression.
*
* ```
* <some-element [ngStyle]="{'font-style': styleExp}">...</some-element>
* ```
*
* Set the width of the containing element to a pixel value returned by an expression.
*
* ```
* <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>
* ```
*
* Set a collection of style values using an expression that returns key-value pairs.
*
* ```
* <some-element [ngStyle]="objExp">...</some-element>
* ```
*
* \@description
*
* An attribute directive that updates styles for the containing HTML element.
* Sets one or more style properties, specified as colon-separated key-value pairs.
* The key is a style name, with an optional `.<unit>` suffix
* (such as 'top.px', 'font-style.em').
* The value is an expression to be evaluated.
* The resulting non-null value, expressed in the given unit,
* is assigned to the given style property.
* If the result of evaluation is null, the corresponding style is removed.
*
* \@publicApi
*/
class NgStyle {
/**
* @param {?} _ngEl
* @param {?} _differs
* @param {?} _renderer
*/
constructor(_ngEl, _differs, _renderer) {
this._ngEl = _ngEl;
this._differs = _differs;
this._renderer = _renderer;
this._ngStyle = null;
this._differ = null;
}
/**
* @param {?} values
* @return {?}
*/
set ngStyle(values) {
this._ngStyle = values;
if (!this._differ && values) {
this._differ = this._differs.find(values).create();
}
}
/**
* @return {?}
*/
ngDoCheck() {
if (this._differ) {
/** @type {?} */
const changes = this._differ.diff((/** @type {?} */ (this._ngStyle)));
if (changes) {
this._applyChanges(changes);
}
}
}
/**
* @private
* @param {?} nameAndUnit
* @param {?} value
* @return {?}
*/
_setStyle(nameAndUnit, value) {
const [name, unit] = nameAndUnit.split('.');
value = value != null && unit ? `${value}${unit}` : value;
if (value != null) {
this._renderer.setStyle(this._ngEl.nativeElement, name, (/** @type {?} */ (value)));
}
else {
this._renderer.removeStyle(this._ngEl.nativeElement, name);
}
}
/**
* @private
* @param {?} changes
* @return {?}
*/
_applyChanges(changes) {
changes.forEachRemovedItem((/**
* @param {?} record
* @return {?}
*/
(record) => this._setStyle(record.key, null)));
changes.forEachAddedItem((/**
* @param {?} record
* @return {?}
*/
(record) => this._setStyle(record.key, record.currentValue)));
changes.forEachChangedItem((/**
* @param {?} record
* @return {?}
*/
(record) => this._setStyle(record.key, record.currentValue)));
}
}
NgStyle.ɵfac = function NgStyle_Factory(t) { return new (t || NgStyle)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["ElementRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["KeyValueDiffers"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["Renderer2"])); };
NgStyle.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgStyle, selectors: [["", "ngStyle", ""]], inputs: { ngStyle: "ngStyle" } });
/** @nocollapse */
NgStyle.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ElementRef"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["KeyValueDiffers"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Renderer2"] }
];
NgStyle.propDecorators = {
ngStyle: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"], args: ['ngStyle',] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgStyle, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngStyle]' }]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ElementRef"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["KeyValueDiffers"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Renderer2"] }]; }, { ngStyle: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"],
args: ['ngStyle']
}] }); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/directives/ng_template_outlet.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@ngModule CommonModule
*
* \@description
*
* Inserts an embedded view from a prepared `TemplateRef`.
*
* You can attach a context object to the `EmbeddedViewRef` by setting `[ngTemplateOutletContext]`.
* `[ngTemplateOutletContext]` should be an object, the object's keys will be available for binding
* by the local template `let` declarations.
*
* \@usageNotes
* ```
* <ng-container *ngTemplateOutlet="templateRefExp; context: contextExp"></ng-container>
* ```
*
* Using the key `$implicit` in the context object will set its value as default.
*
* ### Example
*
* {\@example common/ngTemplateOutlet/ts/module.ts region='NgTemplateOutlet'}
*
* \@publicApi
*/
class NgTemplateOutlet {
/**
* @param {?} _viewContainerRef
*/
constructor(_viewContainerRef) {
this._viewContainerRef = _viewContainerRef;
this._viewRef = null;
/**
* A context object to attach to the {\@link EmbeddedViewRef}. This should be an
* object, the object's keys will be available for binding by the local template `let`
* declarations.
* Using the key `$implicit` in the context object will set its value as default.
*/
this.ngTemplateOutletContext = null;
/**
* A string defining the template reference and optionally the context object for the template.
*/
this.ngTemplateOutlet = null;
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
/** @type {?} */
const recreateView = this._shouldRecreateView(changes);
if (recreateView) {
/** @type {?} */
const viewContainerRef = this._viewContainerRef;
if (this._viewRef) {
viewContainerRef.remove(viewContainerRef.indexOf(this._viewRef));
}
this._viewRef = this.ngTemplateOutlet ?
viewContainerRef.createEmbeddedView(this.ngTemplateOutlet, this.ngTemplateOutletContext) :
null;
}
else if (this._viewRef && this.ngTemplateOutletContext) {
this._updateExistingContext(this.ngTemplateOutletContext);
}
}
/**
* We need to re-create existing embedded view if:
* - templateRef has changed
* - context has changes
*
* We mark context object as changed when the corresponding object
* shape changes (new properties are added or existing properties are removed).
* In other words we consider context with the same properties as "the same" even
* if object reference changes (see https://github.com/angular/angular/issues/13407).
* @private
* @param {?} changes
* @return {?}
*/
_shouldRecreateView(changes) {
/** @type {?} */
const ctxChange = changes['ngTemplateOutletContext'];
return !!changes['ngTemplateOutlet'] || (ctxChange && this._hasContextShapeChanged(ctxChange));
}
/**
* @private
* @param {?} ctxChange
* @return {?}
*/
_hasContextShapeChanged(ctxChange) {
/** @type {?} */
const prevCtxKeys = Object.keys(ctxChange.previousValue || {});
/** @type {?} */
const currCtxKeys = Object.keys(ctxChange.currentValue || {});
if (prevCtxKeys.length === currCtxKeys.length) {
for (let propName of currCtxKeys) {
if (prevCtxKeys.indexOf(propName) === -1) {
return true;
}
}
return false;
}
return true;
}
/**
* @private
* @param {?} ctx
* @return {?}
*/
_updateExistingContext(ctx) {
for (let propName of Object.keys(ctx)) {
((/** @type {?} */ ((/** @type {?} */ (this._viewRef)).context)))[propName] = ((/** @type {?} */ (this.ngTemplateOutletContext)))[propName];
}
}
}
NgTemplateOutlet.ɵfac = function NgTemplateOutlet_Factory(t) { return new (t || NgTemplateOutlet)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"])); };
NgTemplateOutlet.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgTemplateOutlet, selectors: [["", "ngTemplateOutlet", ""]], inputs: { ngTemplateOutletContext: "ngTemplateOutletContext", ngTemplateOutlet: "ngTemplateOutlet" }, features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵNgOnChangesFeature"]] });
/** @nocollapse */
NgTemplateOutlet.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] }
];
NgTemplateOutlet.propDecorators = {
ngTemplateOutletContext: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }],
ngTemplateOutlet: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgTemplateOutlet, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Directive"],
args: [{ selector: '[ngTemplateOutlet]' }]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ViewContainerRef"] }]; }, { ngTemplateOutletContext: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}], ngTemplateOutlet: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Input"]
}] }); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/directives/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A collection of Angular directives that are likely to be used in each and every Angular
* application.
* @type {?}
*/
const COMMON_DIRECTIVES = [
NgClass,
NgComponentOutlet,
NgForOf,
NgIf,
NgTemplateOutlet,
NgStyle,
NgSwitch,
NgSwitchCase,
NgSwitchDefault,
NgPlural,
NgPluralCase,
];
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/invalid_pipe_argument_error.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} type
* @param {?} value
* @return {?}
*/
function invalidPipeArgumentError(type, value) {
return Error(`InvalidPipeArgument: '${value}' for pipe '${Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵstringify"])(type)}'`);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/async_pipe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @record
*/
function SubscriptionStrategy() { }
if (false) {}
class ObservableStrategy {
/**
* @param {?} async
* @param {?} updateLatestValue
* @return {?}
*/
createSubscription(async, updateLatestValue) {
return async.subscribe({
next: updateLatestValue,
error: (/**
* @param {?} e
* @return {?}
*/
(e) => {
throw e;
})
});
}
/**
* @param {?} subscription
* @return {?}
*/
dispose(subscription) {
subscription.unsubscribe();
}
/**
* @param {?} subscription
* @return {?}
*/
onDestroy(subscription) {
subscription.unsubscribe();
}
}
class PromiseStrategy {
/**
* @param {?} async
* @param {?} updateLatestValue
* @return {?}
*/
createSubscription(async, updateLatestValue) {
return async.then(updateLatestValue, (/**
* @param {?} e
* @return {?}
*/
e => {
throw e;
}));
}
/**
* @param {?} subscription
* @return {?}
*/
dispose(subscription) { }
/**
* @param {?} subscription
* @return {?}
*/
onDestroy(subscription) { }
}
/** @type {?} */
const _promiseStrategy = new PromiseStrategy();
/** @type {?} */
const _observableStrategy = new ObservableStrategy();
/**
* \@ngModule CommonModule
* \@description
*
* Unwraps a value from an asynchronous primitive.
*
* The `async` pipe subscribes to an `Observable` or `Promise` and returns the latest value it has
* emitted. When a new value is emitted, the `async` pipe marks the component to be checked for
* changes. When the component gets destroyed, the `async` pipe unsubscribes automatically to avoid
* potential memory leaks.
*
* \@usageNotes
*
* ### Examples
*
* This example binds a `Promise` to the view. Clicking the `Resolve` button resolves the
* promise.
*
* {\@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'}
*
* It's also possible to use `async` with Observables. The example below binds the `time` Observable
* to the view. The Observable continuously updates the view with the current time.
*
* {\@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'}
*
* \@publicApi
*/
class AsyncPipe {
/**
* @param {?} _ref
*/
constructor(_ref) {
this._ref = _ref;
this._latestValue = null;
this._latestReturnedValue = null;
this._subscription = null;
this._obj = null;
this._strategy = (/** @type {?} */ (null));
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this._subscription) {
this._dispose();
}
}
/**
* @param {?} obj
* @return {?}
*/
transform(obj) {
if (!this._obj) {
if (obj) {
this._subscribe(obj);
}
this._latestReturnedValue = this._latestValue;
return this._latestValue;
}
if (obj !== this._obj) {
this._dispose();
return this.transform((/** @type {?} */ (obj)));
}
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵlooseIdentical"])(this._latestValue, this._latestReturnedValue)) {
return this._latestReturnedValue;
}
this._latestReturnedValue = this._latestValue;
return _angular_core__WEBPACK_IMPORTED_MODULE_0__["WrappedValue"].wrap(this._latestValue);
}
/**
* @private
* @param {?} obj
* @return {?}
*/
_subscribe(obj) {
this._obj = obj;
this._strategy = this._selectStrategy(obj);
this._subscription = this._strategy.createSubscription(obj, (/**
* @param {?} value
* @return {?}
*/
(value) => this._updateLatestValue(obj, value)));
}
/**
* @private
* @param {?} obj
* @return {?}
*/
_selectStrategy(obj) {
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵisPromise"])(obj)) {
return _promiseStrategy;
}
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵisObservable"])(obj)) {
return _observableStrategy;
}
throw invalidPipeArgumentError(AsyncPipe, obj);
}
/**
* @private
* @return {?}
*/
_dispose() {
this._strategy.dispose((/** @type {?} */ (this._subscription)));
this._latestValue = null;
this._latestReturnedValue = null;
this._subscription = null;
this._obj = null;
}
/**
* @private
* @param {?} async
* @param {?} value
* @return {?}
*/
_updateLatestValue(async, value) {
if (async === this._obj) {
this._latestValue = value;
this._ref.markForCheck();
}
}
}
AsyncPipe.ɵfac = function AsyncPipe_Factory(t) { return new (t || AsyncPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinjectPipeChangeDetectorRef"]()); };
AsyncPipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "async", type: AsyncPipe, pure: false });
/** @nocollapse */
AsyncPipe.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ChangeDetectorRef"] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](AsyncPipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'async', pure: false }]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ChangeDetectorRef"] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/case_conversion_pipes.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Transforms text to all lower case.
*
* @see `UpperCasePipe`
* @see `TitleCasePipe`
* \@usageNotes
*
* The following example defines a view that allows the user to enter
* text, and then uses the pipe to convert the input text to all lower case.
*
* <code-example path="common/pipes/ts/lowerupper_pipe.ts" region='LowerUpperPipe'></code-example>
*
* \@ngModule CommonModule
* \@publicApi
*/
class LowerCasePipe {
/**
* @param {?} value The string to transform to lower case.
* @return {?}
*/
transform(value) {
if (!value)
return value;
if (typeof value !== 'string') {
throw invalidPipeArgumentError(LowerCasePipe, value);
}
return value.toLowerCase();
}
}
LowerCasePipe.ɵfac = function LowerCasePipe_Factory(t) { return new (t || LowerCasePipe)(); };
LowerCasePipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "lowercase", type: LowerCasePipe, pure: true });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](LowerCasePipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'lowercase' }]
}], null, null); })();
//
// Regex below matches any Unicode word and compatible with ES5. In ES2018 the same result
// can be achieved by using /\p{L}\S*/gu and also known as Unicode Property Escapes
// (http://2ality.com/2017/07/regexp-unicode-property-escapes.html). Since there is no
// transpilation of this functionality down to ES5 without external tool, the only solution is
// to use already transpiled form. Example can be found here -
// https://mothereff.in/regexpu#input=var+regex+%3D+/%5Cp%7BL%7D/u%3B&unicodePropertyEscape=1
//
/** @type {?} */
const unicodeWordMatch = /(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])\S*/g;
/**
* Transforms text to title case.
* Capitalizes the first letter of each word and transforms the
* rest of the word to lower case.
* Words are delimited by any whitespace character, such as a space, tab, or line-feed character.
*
* @see `LowerCasePipe`
* @see `UpperCasePipe`
*
* \@usageNotes
* The following example shows the result of transforming various strings into title case.
*
* <code-example path="common/pipes/ts/titlecase_pipe.ts" region='TitleCasePipe'></code-example>
*
* \@ngModule CommonModule
* \@publicApi
*/
class TitleCasePipe {
/**
* @param {?} value The string to transform to title case.
* @return {?}
*/
transform(value) {
if (!value)
return value;
if (typeof value !== 'string') {
throw invalidPipeArgumentError(TitleCasePipe, value);
}
return value.replace(unicodeWordMatch, ((/**
* @param {?} txt
* @return {?}
*/
txt => txt[0].toUpperCase() + txt.substr(1).toLowerCase())));
}
}
TitleCasePipe.ɵfac = function TitleCasePipe_Factory(t) { return new (t || TitleCasePipe)(); };
TitleCasePipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "titlecase", type: TitleCasePipe, pure: true });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](TitleCasePipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'titlecase' }]
}], null, null); })();
/**
* Transforms text to all upper case.
* @see `LowerCasePipe`
* @see `TitleCasePipe`
*
* \@ngModule CommonModule
* \@publicApi
*/
class UpperCasePipe {
/**
* @param {?} value The string to transform to upper case.
* @return {?}
*/
transform(value) {
if (!value)
return value;
if (typeof value !== 'string') {
throw invalidPipeArgumentError(UpperCasePipe, value);
}
return value.toUpperCase();
}
}
UpperCasePipe.ɵfac = function UpperCasePipe_Factory(t) { return new (t || UpperCasePipe)(); };
UpperCasePipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "uppercase", type: UpperCasePipe, pure: true });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](UpperCasePipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'uppercase' }]
}], null, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/date_pipe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// clang-format off
/**
* \@ngModule CommonModule
* \@description
*
* Formats a date value according to locale rules.
*
* Only the `en-US` locale data comes with Angular. To localize dates
* in another language, you must import the corresponding locale data.
* See the [I18n guide](guide/i18n#i18n-pipes) for more information.
*
* @see `formatDate()`
*
*
* \@usageNotes
*
* The result of this pipe is not reevaluated when the input is mutated. To avoid the need to
* reformat the date on every change-detection cycle, treat the date as an immutable object
* and change the reference when the pipe needs to run again.
*
* ### Pre-defined format options
*
* Examples are given in `en-US` locale.
*
* - `'short'`: equivalent to `'M/d/yy, h:mm a'` (`6/15/15, 9:03 AM`).
* - `'medium'`: equivalent to `'MMM d, y, h:mm:ss a'` (`Jun 15, 2015, 9:03:01 AM`).
* - `'long'`: equivalent to `'MMMM d, y, h:mm:ss a z'` (`June 15, 2015 at 9:03:01 AM
* GMT+1`).
* - `'full'`: equivalent to `'EEEE, MMMM d, y, h:mm:ss a zzzz'` (`Monday, June 15, 2015 at
* 9:03:01 AM GMT+01:00`).
* - `'shortDate'`: equivalent to `'M/d/yy'` (`6/15/15`).
* - `'mediumDate'`: equivalent to `'MMM d, y'` (`Jun 15, 2015`).
* - `'longDate'`: equivalent to `'MMMM d, y'` (`June 15, 2015`).
* - `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` (`Monday, June 15, 2015`).
* - `'shortTime'`: equivalent to `'h:mm a'` (`9:03 AM`).
* - `'mediumTime'`: equivalent to `'h:mm:ss a'` (`9:03:01 AM`).
* - `'longTime'`: equivalent to `'h:mm:ss a z'` (`9:03:01 AM GMT+1`).
* - `'fullTime'`: equivalent to `'h:mm:ss a zzzz'` (`9:03:01 AM GMT+01:00`).
*
* ### Custom format options
*
* You can construct a format string using symbols to specify the components
* of a date-time value, as described in the following table.
* Format details depend on the locale.
* Fields marked with (*) are only available in the extra data set for the given locale.
*
* | Field type | Format | Description | Example Value |
* |--------------------|-------------|---------------------------------------------------------------|------------------------------------------------------------|
* | Era | G, GG & GGG | Abbreviated | AD |
* | | GGGG | Wide | Anno Domini |
* | | GGGGG | Narrow | A |
* | Year | y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 |
* | | yy | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 |
* | | yyy | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 |
* | | yyyy | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 |
* | Month | M | Numeric: 1 digit | 9, 12 |
* | | MM | Numeric: 2 digits + zero padded | 09, 12 |
* | | MMM | Abbreviated | Sep |
* | | MMMM | Wide | September |
* | | MMMMM | Narrow | S |
* | Month standalone | L | Numeric: 1 digit | 9, 12 |
* | | LL | Numeric: 2 digits + zero padded | 09, 12 |
* | | LLL | Abbreviated | Sep |
* | | LLLL | Wide | September |
* | | LLLLL | Narrow | S |
* | Week of year | w | Numeric: minimum digits | 1... 53 |
* | | ww | Numeric: 2 digits + zero padded | 01... 53 |
* | Week of month | W | Numeric: 1 digit | 1... 5 |
* | Day of month | d | Numeric: minimum digits | 1 |
* | | dd | Numeric: 2 digits + zero padded | 01 |
* | Week day | E, EE & EEE | Abbreviated | Tue |
* | | EEEE | Wide | Tuesday |
* | | EEEEE | Narrow | T |
* | | EEEEEE | Short | Tu |
* | Period | a, aa & aaa | Abbreviated | am/pm or AM/PM |
* | | aaaa | Wide (fallback to `a` when missing) | ante meridiem/post meridiem |
* | | aaaaa | Narrow | a/p |
* | Period* | B, BB & BBB | Abbreviated | mid. |
* | | BBBB | Wide | am, pm, midnight, noon, morning, afternoon, evening, night |
* | | BBBBB | Narrow | md |
* | Period standalone* | b, bb & bbb | Abbreviated | mid. |
* | | bbbb | Wide | am, pm, midnight, noon, morning, afternoon, evening, night |
* | | bbbbb | Narrow | md |
* | Hour 1-12 | h | Numeric: minimum digits | 1, 12 |
* | | hh | Numeric: 2 digits + zero padded | 01, 12 |
* | Hour 0-23 | H | Numeric: minimum digits | 0, 23 |
* | | HH | Numeric: 2 digits + zero padded | 00, 23 |
* | Minute | m | Numeric: minimum digits | 8, 59 |
* | | mm | Numeric: 2 digits + zero padded | 08, 59 |
* | Second | s | Numeric: minimum digits | 0... 59 |
* | | ss | Numeric: 2 digits + zero padded | 00... 59 |
* | Fractional seconds | S | Numeric: 1 digit | 0... 9 |
* | | SS | Numeric: 2 digits + zero padded | 00... 99 |
* | | SSS | Numeric: 3 digits + zero padded (= milliseconds) | 000... 999 |
* | Zone | z, zz & zzz | Short specific non location format (fallback to O) | GMT-8 |
* | | zzzz | Long specific non location format (fallback to OOOO) | GMT-08:00 |
* | | Z, ZZ & ZZZ | ISO8601 basic format | -0800 |
* | | ZZZZ | Long localized GMT format | GMT-8:00 |
* | | ZZZZZ | ISO8601 extended format + Z indicator for offset 0 (= XXXXX) | -08:00 |
* | | O, OO & OOO | Short localized GMT format | GMT-8 |
* | | OOOO | Long localized GMT format | GMT-08:00 |
*
* Note that timezone correction is not applied to an ISO string that has no time component, such as "2016-09-19"
*
* ### Format examples
*
* These examples transform a date into various formats,
* assuming that `dateObj` is a JavaScript `Date` object for
* year: 2015, month: 6, day: 15, hour: 21, minute: 43, second: 11,
* given in the local time for the `en-US` locale.
*
* ```
* {{ dateObj | date }} // output is 'Jun 15, 2015'
* {{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM'
* {{ dateObj | date:'shortTime' }} // output is '9:43 PM'
* {{ dateObj | date:'mm:ss' }} // output is '43:11'
* ```
*
* ### Usage example
*
* The following component uses a date pipe to display the current date in different formats.
*
* ```
* \@Component({
* selector: 'date-pipe',
* template: `<div>
* <p>Today is {{today | date}}</p>
* <p>Or if you prefer, {{today | date:'fullDate'}}</p>
* <p>The time is {{today | date:'h:mm a z'}}</p>
* </div>`
* })
* // Get the current date and time as a date-time value.
* export class DatePipeComponent {
* today: number = Date.now();
* }
* ```
*
* \@publicApi
*/
// clang-format on
class DatePipe {
/**
* @param {?} locale
*/
constructor(locale) {
this.locale = locale;
}
/**
* @param {?} value The date expression: a `Date` object, a number
* (milliseconds since UTC epoch), or an ISO string (https://www.w3.org/TR/NOTE-datetime).
* @param {?=} format The date/time components to include, using predefined options or a
* custom format string.
* @param {?=} timezone A timezone offset (such as `'+0430'`), or a standard
* UTC/GMT or continental US timezone abbreviation.
* When not supplied, uses the end-user's local system timezone.
* @param {?=} locale A locale code for the locale format rules to use.
* When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
* See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app).
* @return {?} A date string in the desired format.
*/
transform(value, format = 'mediumDate', timezone, locale) {
if (value == null || value === '' || value !== value)
return null;
try {
return formatDate(value, format, locale || this.locale, timezone);
}
catch (error) {
throw invalidPipeArgumentError(DatePipe, error.message);
}
}
}
DatePipe.ɵfac = function DatePipe_Factory(t) { return new (t || DatePipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"])); };
DatePipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "date", type: DatePipe, pure: true });
/** @nocollapse */
DatePipe.ctorParameters = () => [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](DatePipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'date', pure: true }]
}], function () { return [{ type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"],
args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"]]
}] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/i18n_plural_pipe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const _INTERPOLATION_REGEXP = /#/g;
/**
* \@ngModule CommonModule
* \@description
*
* Maps a value to a string that pluralizes the value according to locale rules.
*
* \@usageNotes
*
* ### Example
*
* {\@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'}
*
* \@publicApi
*/
class I18nPluralPipe {
/**
* @param {?} _localization
*/
constructor(_localization) {
this._localization = _localization;
}
/**
* @param {?} value the number to be formatted
* @param {?} pluralMap an object that mimics the ICU format, see
* http://userguide.icu-project.org/formatparse/messages.
* @param {?=} locale a `string` defining the locale to use (uses the current {\@link LOCALE_ID} by
* default).
* @return {?}
*/
transform(value, pluralMap, locale) {
if (value == null)
return '';
if (typeof pluralMap !== 'object' || pluralMap === null) {
throw invalidPipeArgumentError(I18nPluralPipe, pluralMap);
}
/** @type {?} */
const key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale);
return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString());
}
}
I18nPluralPipe.ɵfac = function I18nPluralPipe_Factory(t) { return new (t || I18nPluralPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgLocalization)); };
I18nPluralPipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "i18nPlural", type: I18nPluralPipe, pure: true });
/** @nocollapse */
I18nPluralPipe.ctorParameters = () => [
{ type: NgLocalization }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](I18nPluralPipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'i18nPlural', pure: true }]
}], function () { return [{ type: NgLocalization }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/i18n_select_pipe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@ngModule CommonModule
* \@description
*
* Generic selector that displays the string that matches the current value.
*
* If none of the keys of the `mapping` match the `value`, then the content
* of the `other` key is returned when present, otherwise an empty string is returned.
*
* \@usageNotes
*
* ### Example
*
* {\@example common/pipes/ts/i18n_pipe.ts region='I18nSelectPipeComponent'}
*
* \@publicApi
*/
class I18nSelectPipe {
/**
* @param {?} value a string to be internationalized.
* @param {?} mapping an object that indicates the text that should be displayed
* for different values of the provided `value`.
* @return {?}
*/
transform(value, mapping) {
if (value == null)
return '';
if (typeof mapping !== 'object' || typeof value !== 'string') {
throw invalidPipeArgumentError(I18nSelectPipe, mapping);
}
if (mapping.hasOwnProperty(value)) {
return mapping[value];
}
if (mapping.hasOwnProperty('other')) {
return mapping['other'];
}
return '';
}
}
I18nSelectPipe.ɵfac = function I18nSelectPipe_Factory(t) { return new (t || I18nSelectPipe)(); };
I18nSelectPipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "i18nSelect", type: I18nSelectPipe, pure: true });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](I18nSelectPipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'i18nSelect', pure: true }]
}], null, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/json_pipe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@ngModule CommonModule
* \@description
*
* Converts a value into its JSON-format representation. Useful for debugging.
*
* \@usageNotes
*
* The following component uses a JSON pipe to convert an object
* to JSON format, and displays the string in both formats for comparison.
*
* {\@example common/pipes/ts/json_pipe.ts region='JsonPipe'}
*
* \@publicApi
*/
class JsonPipe {
/**
* @param {?} value A value of any type to convert into a JSON-format string.
* @return {?}
*/
transform(value) {
return JSON.stringify(value, null, 2);
}
}
JsonPipe.ɵfac = function JsonPipe_Factory(t) { return new (t || JsonPipe)(); };
JsonPipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "json", type: JsonPipe, pure: false });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](JsonPipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'json', pure: false }]
}], null, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/keyvalue_pipe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @template K, V
* @param {?} key
* @param {?} value
* @return {?}
*/
function makeKeyValuePair(key, value) {
return { key: key, value: value };
}
/**
* A key value pair.
* Usually used to represent the key value pairs from a Map or Object.
*
* \@publicApi
* @record
* @template K, V
*/
function KeyValue() { }
if (false) {}
/**
* \@ngModule CommonModule
* \@description
*
* Transforms Object or Map into an array of key value pairs.
*
* The output array will be ordered by keys.
* By default the comparator will be by Unicode point value.
* You can optionally pass a compareFn if your keys are complex types.
*
* \@usageNotes
* ### Examples
*
* This examples show how an Object or a Map can be iterated by ngFor with the use of this keyvalue
* pipe.
*
* {\@example common/pipes/ts/keyvalue_pipe.ts region='KeyValuePipe'}
*
* \@publicApi
*/
class KeyValuePipe {
/**
* @param {?} differs
*/
constructor(differs) {
this.differs = differs;
this.keyValues = [];
}
/**
* @template K, V
* @param {?} input
* @param {?=} compareFn
* @return {?}
*/
transform(input, compareFn = defaultComparator) {
if (!input || (!(input instanceof Map) && typeof input !== 'object')) {
return null;
}
if (!this.differ) {
// make a differ for whatever type we've been passed in
this.differ = this.differs.find(input).create();
}
/** @type {?} */
const differChanges = this.differ.diff((/** @type {?} */ (input)));
if (differChanges) {
this.keyValues = [];
differChanges.forEachItem((/**
* @param {?} r
* @return {?}
*/
(r) => {
this.keyValues.push(makeKeyValuePair(r.key, (/** @type {?} */ (r.currentValue))));
}));
this.keyValues.sort(compareFn);
}
return this.keyValues;
}
}
KeyValuePipe.ɵfac = function KeyValuePipe_Factory(t) { return new (t || KeyValuePipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["KeyValueDiffers"])); };
KeyValuePipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "keyvalue", type: KeyValuePipe, pure: false });
/** @nocollapse */
KeyValuePipe.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["KeyValueDiffers"] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](KeyValuePipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'keyvalue', pure: false }]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["KeyValueDiffers"] }]; }, null); })();
if (false) {}
/**
* @template K, V
* @param {?} keyValueA
* @param {?} keyValueB
* @return {?}
*/
function defaultComparator(keyValueA, keyValueB) {
/** @type {?} */
const a = keyValueA.key;
/** @type {?} */
const b = keyValueB.key;
// if same exit with 0;
if (a === b)
return 0;
// make sure that undefined are at the end of the sort.
if (a === undefined)
return 1;
if (b === undefined)
return -1;
// make sure that nulls are at the end of the sort.
if (a === null)
return 1;
if (b === null)
return -1;
if (typeof a == 'string' && typeof b == 'string') {
return a < b ? -1 : 1;
}
if (typeof a == 'number' && typeof b == 'number') {
return a - b;
}
if (typeof a == 'boolean' && typeof b == 'boolean') {
return a < b ? -1 : 1;
}
// `a` and `b` are of different types. Compare their string values.
/** @type {?} */
const aString = String(a);
/** @type {?} */
const bString = String(b);
return aString == bString ? 0 : aString < bString ? -1 : 1;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/number_pipe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@ngModule CommonModule
* \@description
*
* Transforms a number into a string,
* formatted according to locale rules that determine group sizing and
* separator, decimal-point character, and other locale-specific
* configurations.
*
* If no parameters are specified, the function rounds off to the nearest value using this
* [rounding method](https://en.wikibooks.org/wiki/Arithmetic/Rounding).
* The behavior differs from that of the JavaScript ```Math.round()``` function.
* In the following case for example, the pipe rounds down where
* ```Math.round()``` rounds up:
*
* ```html
* -2.5 | number:'1.0-0'
* > -3
* Math.round(-2.5)
* > -2
* ```
*
* @see `formatNumber()`
*
* \@usageNotes
* The following code shows how the pipe transforms numbers
* into text strings, according to various format specifications,
* where the caller's default locale is `en-US`.
*
* ### Example
*
* <code-example path="common/pipes/ts/number_pipe.ts" region='NumberPipe'></code-example>
*
* \@publicApi
*/
class DecimalPipe {
/**
* @param {?} _locale
*/
constructor(_locale) {
this._locale = _locale;
}
/**
* @param {?} value The number to be formatted.
* @param {?=} digitsInfo Decimal representation options, specified by a string
* in the following format:<br>
* <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>.
* - `minIntegerDigits`: The minimum number of integer digits before the decimal point.
* Default is `1`.
* - `minFractionDigits`: The minimum number of digits after the decimal point.
* Default is `0`.
* - `maxFractionDigits`: The maximum number of digits after the decimal point.
* Default is `3`.
* @param {?=} locale A locale code for the locale format rules to use.
* When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
* See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app).
* @return {?}
*/
transform(value, digitsInfo, locale) {
if (isEmpty(value))
return null;
locale = locale || this._locale;
try {
/** @type {?} */
const num = strToNumber(value);
return formatNumber(num, locale, digitsInfo);
}
catch (error) {
throw invalidPipeArgumentError(DecimalPipe, error.message);
}
}
}
DecimalPipe.ɵfac = function DecimalPipe_Factory(t) { return new (t || DecimalPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"])); };
DecimalPipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "number", type: DecimalPipe, pure: true });
/** @nocollapse */
DecimalPipe.ctorParameters = () => [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](DecimalPipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'number' }]
}], function () { return [{ type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"],
args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"]]
}] }]; }, null); })();
if (false) {}
/**
* \@ngModule CommonModule
* \@description
*
* Transforms a number to a percentage
* string, formatted according to locale rules that determine group sizing and
* separator, decimal-point character, and other locale-specific
* configurations.
*
* @see `formatPercent()`
*
* \@usageNotes
* The following code shows how the pipe transforms numbers
* into text strings, according to various format specifications,
* where the caller's default locale is `en-US`.
*
* <code-example path="common/pipes/ts/percent_pipe.ts" region='PercentPipe'></code-example>
*
* \@publicApi
*/
class PercentPipe {
/**
* @param {?} _locale
*/
constructor(_locale) {
this._locale = _locale;
}
/**
*
* @param {?} value The number to be formatted as a percentage.
* @param {?=} digitsInfo Decimal representation options, specified by a string
* in the following format:<br>
* <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>.
* - `minIntegerDigits`: The minimum number of integer digits before the decimal point.
* Default is `1`.
* - `minFractionDigits`: The minimum number of digits after the decimal point.
* Default is `0`.
* - `maxFractionDigits`: The maximum number of digits after the decimal point.
* Default is `0`.
* @param {?=} locale A locale code for the locale format rules to use.
* When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
* See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app).
* @return {?}
*/
transform(value, digitsInfo, locale) {
if (isEmpty(value))
return null;
locale = locale || this._locale;
try {
/** @type {?} */
const num = strToNumber(value);
return formatPercent(num, locale, digitsInfo);
}
catch (error) {
throw invalidPipeArgumentError(PercentPipe, error.message);
}
}
}
PercentPipe.ɵfac = function PercentPipe_Factory(t) { return new (t || PercentPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"])); };
PercentPipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "percent", type: PercentPipe, pure: true });
/** @nocollapse */
PercentPipe.ctorParameters = () => [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](PercentPipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'percent' }]
}], function () { return [{ type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"],
args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"]]
}] }]; }, null); })();
if (false) {}
/**
* \@ngModule CommonModule
* \@description
*
* Transforms a number to a currency string, formatted according to locale rules
* that determine group sizing and separator, decimal-point character,
* and other locale-specific configurations.
*
* {\@a currency-code-deprecation}
* <div class="alert is-helpful">
*
* **Deprecation notice:**
*
* The default currency code is currently always `USD` but this is deprecated from v9.
*
* **In v11 the default currency code will be taken from the current locale identified by
* the `LOCAL_ID` token. See the [i18n guide](guide/i18n#setting-up-the-locale-of-your-app) for
* more information.**
*
* If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in
* your application `NgModule`:
*
* ```ts
* {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'}
* ```
*
* </div>
*
* @see `getCurrencySymbol()`
* @see `formatCurrency()`
*
* \@usageNotes
* The following code shows how the pipe transforms numbers
* into text strings, according to various format specifications,
* where the caller's default locale is `en-US`.
*
* <code-example path="common/pipes/ts/currency_pipe.ts" region='CurrencyPipe'></code-example>
*
* \@publicApi
*/
class CurrencyPipe {
/**
* @param {?} _locale
* @param {?=} _defaultCurrencyCode
*/
constructor(_locale, _defaultCurrencyCode = 'USD') {
this._locale = _locale;
this._defaultCurrencyCode = _defaultCurrencyCode;
}
/**
*
* @param {?} value The number to be formatted as currency.
* @param {?=} currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code,
* such as `USD` for the US dollar and `EUR` for the euro. The default currency code can be
* configured using the `DEFAULT_CURRENCY_CODE` injection token.
* @param {?=} display The format for the currency indicator. One of the following:
* - `code`: Show the code (such as `USD`).
* - `symbol`(default): Show the symbol (such as `$`).
* - `symbol-narrow`: Use the narrow symbol for locales that have two symbols for their
* currency.
* For example, the Canadian dollar CAD has the symbol `CA$` and the symbol-narrow `$`. If the
* locale has no narrow symbol, uses the standard symbol for the locale.
* - String: Use the given string value instead of a code or a symbol.
* For example, an empty string will suppress the currency & symbol.
* - Boolean (marked deprecated in v5): `true` for symbol and false for `code`.
*
* @param {?=} digitsInfo Decimal representation options, specified by a string
* in the following format:<br>
* <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>.
* - `minIntegerDigits`: The minimum number of integer digits before the decimal point.
* Default is `1`.
* - `minFractionDigits`: The minimum number of digits after the decimal point.
* Default is `2`.
* - `maxFractionDigits`: The maximum number of digits after the decimal point.
* Default is `2`.
* If not provided, the number will be formatted with the proper amount of digits,
* depending on what the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) specifies.
* For example, the Canadian dollar has 2 digits, whereas the Chilean peso has none.
* @param {?=} locale A locale code for the locale format rules to use.
* When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
* See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app).
* @return {?}
*/
transform(value, currencyCode, display = 'symbol', digitsInfo, locale) {
if (isEmpty(value))
return null;
locale = locale || this._locale;
if (typeof display === 'boolean') {
if ((/** @type {?} */ (console)) && (/** @type {?} */ (console.warn))) {
console.warn(`Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are "code", "symbol" or "symbol-narrow".`);
}
display = display ? 'symbol' : 'code';
}
/** @type {?} */
let currency = currencyCode || this._defaultCurrencyCode;
if (display !== 'code') {
if (display === 'symbol' || display === 'symbol-narrow') {
currency = getCurrencySymbol(currency, display === 'symbol' ? 'wide' : 'narrow', locale);
}
else {
currency = display;
}
}
try {
/** @type {?} */
const num = strToNumber(value);
return formatCurrency(num, locale, currency, currencyCode, digitsInfo);
}
catch (error) {
throw invalidPipeArgumentError(CurrencyPipe, error.message);
}
}
}
CurrencyPipe.ɵfac = function CurrencyPipe_Factory(t) { return new (t || CurrencyPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["DEFAULT_CURRENCY_CODE"])); };
CurrencyPipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "currency", type: CurrencyPipe, pure: true });
/** @nocollapse */
CurrencyPipe.ctorParameters = () => [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] },
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["DEFAULT_CURRENCY_CODE"],] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](CurrencyPipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'currency' }]
}], function () { return [{ type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"],
args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"]]
}] }, { type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"],
args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["DEFAULT_CURRENCY_CODE"]]
}] }]; }, null); })();
if (false) {}
/**
* @param {?} value
* @return {?}
*/
function isEmpty(value) {
return value == null || value === '' || value !== value;
}
/**
* Transforms a string into a number (if needed).
* @param {?} value
* @return {?}
*/
function strToNumber(value) {
// Convert strings to numbers
if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) {
return Number(value);
}
if (typeof value !== 'number') {
throw new Error(`${value} is not a number`);
}
return value;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/slice_pipe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@ngModule CommonModule
* \@description
*
* Creates a new `Array` or `String` containing a subset (slice) of the elements.
*
* \@usageNotes
*
* All behavior is based on the expected behavior of the JavaScript API `Array.prototype.slice()`
* and `String.prototype.slice()`.
*
* When operating on an `Array`, the returned `Array` is always a copy even when all
* the elements are being returned.
*
* When operating on a blank value, the pipe returns the blank value.
*
* ### List Example
*
* This `ngFor` example:
*
* {\@example common/pipes/ts/slice_pipe.ts region='SlicePipe_list'}
*
* produces the following:
*
* ```html
* <li>b</li>
* <li>c</li>
* ```
*
* ### String Examples
*
* {\@example common/pipes/ts/slice_pipe.ts region='SlicePipe_string'}
*
* \@publicApi
*/
class SlicePipe {
/**
* @param {?} value
* @param {?} start
* @param {?=} end
* @return {?}
*/
transform(value, start, end) {
if (value == null)
return value;
if (!this.supports(value)) {
throw invalidPipeArgumentError(SlicePipe, value);
}
return value.slice(start, end);
}
/**
* @private
* @param {?} obj
* @return {?}
*/
supports(obj) {
return typeof obj === 'string' || Array.isArray(obj);
}
}
SlicePipe.ɵfac = function SlicePipe_Factory(t) { return new (t || SlicePipe)(); };
SlicePipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "slice", type: SlicePipe, pure: false });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](SlicePipe, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"],
args: [{ name: 'slice', pure: false }]
}], null, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/pipes/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A collection of Angular pipes that are likely to be used in each and every application.
* @type {?}
*/
const COMMON_PIPES = [
AsyncPipe,
UpperCasePipe,
LowerCasePipe,
JsonPipe,
SlicePipe,
DecimalPipe,
PercentPipe,
TitleCasePipe,
CurrencyPipe,
DatePipe,
I18nPluralPipe,
I18nSelectPipe,
KeyValuePipe,
];
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/common_module.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// Note: This does not contain the location providers,
// as they need some platform specific implementations to work.
/**
* Exports all the basic Angular directives and pipes,
* such as `NgIf`, `NgForOf`, `DecimalPipe`, and so on.
* Re-exported by `BrowserModule`, which is included automatically in the root
* `AppModule` when you create a new app with the CLI `new` command.
*
* * The `providers` options configure the NgModule's injector to provide
* localization dependencies to members.
* * The `exports` options make the declared directives and pipes available for import
* by other NgModules.
*
* \@publicApi
*/
class CommonModule {
}
CommonModule.ɵmod = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineNgModule"]({ type: CommonModule });
CommonModule.ɵinj = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjector"]({ factory: function CommonModule_Factory(t) { return new (t || CommonModule)(); }, providers: [
{ provide: NgLocalization, useClass: NgLocaleLocalization },
] });
(function () { (typeof ngJitMode === "undefined" || ngJitMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵsetNgModuleScope"](CommonModule, { declarations: [NgClass,
NgComponentOutlet,
NgForOf,
NgIf,
NgTemplateOutlet,
NgStyle,
NgSwitch,
NgSwitchCase,
NgSwitchDefault,
NgPlural,
NgPluralCase,
AsyncPipe,
UpperCasePipe,
LowerCasePipe,
JsonPipe,
SlicePipe,
DecimalPipe,
PercentPipe,
TitleCasePipe,
CurrencyPipe,
DatePipe,
I18nPluralPipe,
I18nSelectPipe,
KeyValuePipe], exports: [NgClass,
NgComponentOutlet,
NgForOf,
NgIf,
NgTemplateOutlet,
NgStyle,
NgSwitch,
NgSwitchCase,
NgSwitchDefault,
NgPlural,
NgPluralCase,
AsyncPipe,
UpperCasePipe,
LowerCasePipe,
JsonPipe,
SlicePipe,
DecimalPipe,
PercentPipe,
TitleCasePipe,
CurrencyPipe,
DatePipe,
I18nPluralPipe,
I18nSelectPipe,
KeyValuePipe] }); })();
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](CommonModule, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["NgModule"],
args: [{
declarations: [COMMON_DIRECTIVES, COMMON_PIPES],
exports: [COMMON_DIRECTIVES, COMMON_PIPES],
providers: [
{ provide: NgLocalization, useClass: NgLocaleLocalization },
]
}]
}], null, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/platform_id.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @type {?} */
const PLATFORM_BROWSER_ID = 'browser';
/** @type {?} */
const PLATFORM_SERVER_ID = 'server';
/** @type {?} */
const PLATFORM_WORKER_APP_ID = 'browserWorkerApp';
/** @type {?} */
const PLATFORM_WORKER_UI_ID = 'browserWorkerUi';
/**
* Returns whether a platform id represents a browser platform.
* \@publicApi
* @param {?} platformId
* @return {?}
*/
function isPlatformBrowser(platformId) {
return platformId === PLATFORM_BROWSER_ID;
}
/**
* Returns whether a platform id represents a server platform.
* \@publicApi
* @param {?} platformId
* @return {?}
*/
function isPlatformServer(platformId) {
return platformId === PLATFORM_SERVER_ID;
}
/**
* Returns whether a platform id represents a web worker app platform.
* \@publicApi
* @param {?} platformId
* @return {?}
*/
function isPlatformWorkerApp(platformId) {
return platformId === PLATFORM_WORKER_APP_ID;
}
/**
* Returns whether a platform id represents a web worker UI platform.
* \@publicApi
* @param {?} platformId
* @return {?}
*/
function isPlatformWorkerUi(platformId) {
return platformId === PLATFORM_WORKER_UI_ID;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/version.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@publicApi
* @type {?}
*/
const VERSION = new _angular_core__WEBPACK_IMPORTED_MODULE_0__["Version"]('9.1.13');
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/viewport_scroller.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Defines a scroll position manager. Implemented by `BrowserViewportScroller`.
*
* \@publicApi
* @abstract
*/
class ViewportScroller {
}
// De-sugared tree-shakable injection
// See #23917
/** @nocollapse */
ViewportScroller.ɵprov = Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"])({
token: ViewportScroller,
providedIn: 'root',
factory: (/**
* @return {?}
*/
() => new BrowserViewportScroller(Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(DOCUMENT), window, Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ErrorHandler"])))
});
if (false) {}
/**
* Manages the scroll position for a browser window.
*/
class BrowserViewportScroller {
/**
* @param {?} document
* @param {?} window
* @param {?} errorHandler
*/
constructor(document, window, errorHandler) {
this.document = document;
this.window = window;
this.errorHandler = errorHandler;
this.offset = (/**
* @return {?}
*/
() => [0, 0]);
}
/**
* Configures the top offset used when scrolling to an anchor.
* @param {?} offset A position in screen coordinates (a tuple with x and y values)
* or a function that returns the top offset position.
*
* @return {?}
*/
setOffset(offset) {
if (Array.isArray(offset)) {
this.offset = (/**
* @return {?}
*/
() => offset);
}
else {
this.offset = offset;
}
}
/**
* Retrieves the current scroll position.
* @return {?} The position in screen coordinates.
*/
getScrollPosition() {
if (this.supportScrollRestoration()) {
return [this.window.scrollX, this.window.scrollY];
}
else {
return [0, 0];
}
}
/**
* Sets the scroll position.
* @param {?} position The new position in screen coordinates.
* @return {?}
*/
scrollToPosition(position) {
if (this.supportScrollRestoration()) {
this.window.scrollTo(position[0], position[1]);
}
}
/**
* Scrolls to an anchor element.
* @param {?} anchor The ID of the anchor element.
* @return {?}
*/
scrollToAnchor(anchor) {
if (this.supportScrollRestoration()) {
// Escape anything passed to `querySelector` as it can throw errors and stop the application
// from working if invalid values are passed.
if (this.window.CSS && this.window.CSS.escape) {
anchor = this.window.CSS.escape(anchor);
}
else {
anchor = anchor.replace(/(\"|\'\ |:|\.|\[|\]|,|=)/g, '\\$1');
}
try {
/** @type {?} */
const elSelectedById = this.document.querySelector(`#${anchor}`);
if (elSelectedById) {
this.scrollToElement(elSelectedById);
return;
}
/** @type {?} */
const elSelectedByName = this.document.querySelector(`[name='${anchor}']`);
if (elSelectedByName) {
this.scrollToElement(elSelectedByName);
return;
}
}
catch (e) {
this.errorHandler.handleError(e);
}
}
}
/**
* Disables automatic scroll restoration provided by the browser.
* @param {?} scrollRestoration
* @return {?}
*/
setHistoryScrollRestoration(scrollRestoration) {
if (this.supportScrollRestoration()) {
/** @type {?} */
const history = this.window.history;
if (history && history.scrollRestoration) {
history.scrollRestoration = scrollRestoration;
}
}
}
/**
* @private
* @param {?} el
* @return {?}
*/
scrollToElement(el) {
/** @type {?} */
const rect = el.getBoundingClientRect();
/** @type {?} */
const left = rect.left + this.window.pageXOffset;
/** @type {?} */
const top = rect.top + this.window.pageYOffset;
/** @type {?} */
const offset = this.offset();
this.window.scrollTo(left - offset[0], top - offset[1]);
}
/**
* We only support scroll restoration when we can get a hold of window.
* This means that we do not support this behavior when running in a web worker.
*
* Lifting this restriction right now would require more changes in the dom adapter.
* Since webworkers aren't widely used, we will lift it once RouterScroller is
* battle-tested.
* @private
* @return {?}
*/
supportScrollRestoration() {
try {
return !!this.window && !!this.window.scrollTo;
}
catch (_a) {
return false;
}
}
}
if (false) {}
/**
* Provides an empty implementation of the viewport scroller. This will
* live in \@angular/common as it will be used by both platform-server and platform-webworker.
*/
class NullViewportScroller {
/**
* Empty implementation
* @param {?} offset
* @return {?}
*/
setOffset(offset) { }
/**
* Empty implementation
* @return {?}
*/
getScrollPosition() {
return [0, 0];
}
/**
* Empty implementation
* @param {?} position
* @return {?}
*/
scrollToPosition(position) { }
/**
* Empty implementation
* @param {?} anchor
* @return {?}
*/
scrollToAnchor(anchor) { }
/**
* Empty implementation
* @param {?} scrollRestoration
* @return {?}
*/
setHistoryScrollRestoration(scrollRestoration) { }
}
/**
* @fileoverview added by tsickle
* Generated from: packages/common/src/common.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/common/public_api.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/common/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Generated bundle index. Do not edit.
*/
//# sourceMappingURL=common.js.map
/***/ }),
/***/ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js":
/*!******************************************************************!*\
!*** ./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js ***!
\******************************************************************/
/*! exports provided: ANALYZE_FOR_ENTRY_COMPONENTS, APP_BOOTSTRAP_LISTENER, APP_ID, APP_INITIALIZER, ApplicationInitStatus, ApplicationModule, ApplicationRef, Attribute, COMPILER_OPTIONS, CUSTOM_ELEMENTS_SCHEMA, ChangeDetectionStrategy, ChangeDetectorRef, Compiler, CompilerFactory, Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, ContentChild, ContentChildren, DEFAULT_CURRENCY_CODE, DebugElement, DebugEventListener, DebugNode, DefaultIterableDiffer, Directive, ElementRef, EmbeddedViewRef, ErrorHandler, EventEmitter, Host, HostBinding, HostListener, INJECTOR, Inject, InjectFlags, Injectable, InjectionToken, Injector, Input, IterableDiffers, KeyValueDiffers, LOCALE_ID, MissingTranslationStrategy, ModuleWithComponentFactories, NO_ERRORS_SCHEMA, NgModule, NgModuleFactory, NgModuleFactoryLoader, NgModuleRef, NgProbeToken, NgZone, Optional, Output, PACKAGE_ROOT_URL, PLATFORM_ID, PLATFORM_INITIALIZER, Pipe, PlatformRef, Query, QueryList, ReflectiveInjector, ReflectiveKey, Renderer2, RendererFactory2, RendererStyleFlags2, ResolvedReflectiveFactory, Sanitizer, SecurityContext, Self, SimpleChange, SkipSelf, SystemJsNgModuleLoader, SystemJsNgModuleLoaderConfig, TRANSLATIONS, TRANSLATIONS_FORMAT, TemplateRef, Testability, TestabilityRegistry, Type, VERSION, Version, ViewChild, ViewChildren, ViewContainerRef, ViewEncapsulation, ViewRef, WrappedValue, asNativeElements, assertPlatform, createPlatform, createPlatformFactory, defineInjectable, destroyPlatform, enableProdMode, forwardRef, getDebugNode, getModuleFactory, getPlatform, inject, isDevMode, platformCore, resolveForwardRef, setTestabilityGetter, ɵALLOW_MULTIPLE_PLATFORMS, ɵAPP_ID_RANDOM_PROVIDER, ɵChangeDetectorStatus, ɵCodegenComponentFactoryResolver, ɵCompiler_compileModuleAndAllComponentsAsync__POST_R3__, ɵCompiler_compileModuleAndAllComponentsSync__POST_R3__, ɵCompiler_compileModuleAsync__POST_R3__, ɵCompiler_compileModuleSync__POST_R3__, ɵComponentFactory, ɵConsole, ɵDEFAULT_LOCALE_ID, ɵEMPTY_ARRAY, ɵEMPTY_MAP, ɵINJECTOR_IMPL__POST_R3__, ɵINJECTOR_SCOPE, ɵLifecycleHooksFeature, ɵLocaleDataIndex, ɵNG_COMP_DEF, ɵNG_DIR_DEF, ɵNG_ELEMENT_ID, ɵNG_INJ_DEF, ɵNG_MOD_DEF, ɵNG_PIPE_DEF, ɵNG_PROV_DEF, ɵNOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR, ɵNO_CHANGE, ɵNgModuleFactory, ɵNoopNgZone, ɵReflectionCapabilities, ɵRender3ComponentFactory, ɵRender3ComponentRef, ɵRender3NgModuleRef, ɵSWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__, ɵSWITCH_COMPILE_COMPONENT__POST_R3__, ɵSWITCH_COMPILE_DIRECTIVE__POST_R3__, ɵSWITCH_COMPILE_INJECTABLE__POST_R3__, ɵSWITCH_COMPILE_NGMODULE__POST_R3__, ɵSWITCH_COMPILE_PIPE__POST_R3__, ɵSWITCH_ELEMENT_REF_FACTORY__POST_R3__, ɵSWITCH_IVY_ENABLED__POST_R3__, ɵSWITCH_RENDERER2_FACTORY__POST_R3__, ɵSWITCH_TEMPLATE_REF_FACTORY__POST_R3__, ɵSWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__, ɵ_sanitizeHtml, ɵ_sanitizeStyle, ɵ_sanitizeUrl, ɵallowSanitizationBypassAndThrow, ɵand, ɵangular_packages_core_core_a, ɵangular_packages_core_core_b, ɵangular_packages_core_core_ba, ɵangular_packages_core_core_bb, ɵangular_packages_core_core_bc, ɵangular_packages_core_core_bd, ɵangular_packages_core_core_bf, ɵangular_packages_core_core_bg, ɵangular_packages_core_core_bh, ɵangular_packages_core_core_bi, ɵangular_packages_core_core_bj, ɵangular_packages_core_core_bk, ɵangular_packages_core_core_bl, ɵangular_packages_core_core_bm, ɵangular_packages_core_core_bn, ɵangular_packages_core_core_bp, ɵangular_packages_core_core_bq, ɵangular_packages_core_core_c, ɵangular_packages_core_core_d, ɵangular_packages_core_core_e, ɵangular_packages_core_core_f, ɵangular_packages_core_core_g, ɵangular_packages_core_core_h, ɵangular_packages_core_core_i, ɵangular_packages_core_core_j, ɵangular_packages_core_core_k, ɵangular_packages_core_core_l, ɵangular_packages_core_core_m, ɵangular_packages_core_core_n, ɵangular_packages_core_core_o, ɵangular_packages_core_core_p, ɵangular_packages_core_core_q, ɵangular_packages_core_core_r, ɵangular_packages_core_core_s, ɵangular_packages_core_core_t, ɵangular_packages_core_core_u, ɵangular_packages_core_core_v, ɵangular_packages_core_core_w, ɵangular_packages_core_core_x, ɵangular_packages_core_core_y, ɵangular_packages_core_core_z, ɵbypassSanitizationTrustHtml, ɵbypassSanitizationTrustResourceUrl, ɵbypassSanitizationTrustScript, ɵbypassSanitizationTrustStyle, ɵbypassSanitizationTrustUrl, ɵccf, ɵclearOverrides, ɵclearResolutionOfComponentResourcesQueue, ɵcmf, ɵcompileComponent, ɵcompileDirective, ɵcompileNgModule, ɵcompileNgModuleDefs, ɵcompileNgModuleFactory__POST_R3__, ɵcompilePipe, ɵcreateInjector, ɵcrt, ɵdefaultIterableDiffers, ɵdefaultKeyValueDiffers, ɵdetectChanges, ɵdevModeEqual, ɵdid, ɵeld, ɵfindLocaleData, ɵflushModuleScopingQueueAsMuchAsPossible, ɵgetComponentViewDefinitionFactory, ɵgetDebugNodeR2, ɵgetDebugNode__POST_R3__, ɵgetDirectives, ɵgetHostElement, ɵgetInjectableDef, ɵgetLContext, ɵgetLocaleCurrencyCode, ɵgetLocalePluralCase, ɵgetModuleFactory__POST_R3__, ɵgetSanitizationBypassType, ɵglobal, ɵinitServicesIfNeeded, ɵinlineInterpolate, ɵinterpolate, ɵisBoundToModule__POST_R3__, ɵisDefaultChangeDetectionStrategy, ɵisListLikeIterable, ɵisObservable, ɵisPromise, ɵivyEnabled, ɵlooseIdentical, ɵmakeDecorator, ɵmarkDirty, ɵmod, ɵmpd, ɵncd, ɵnov, ɵoverrideComponentView, ɵoverrideProvider, ɵpad, ɵpatchComponentDefWithScope, ɵpid, ɵpod, ɵppd, ɵprd, ɵpublishDefaultGlobalUtils, ɵpublishGlobalUtil, ɵqud, ɵregisterLocaleData, ɵregisterModuleFactory, ɵregisterNgModuleType, ɵrenderComponent, ɵresetCompiledComponents, ɵresetJitOptions, ɵresolveComponentResources, ɵsetClassMetadata, ɵsetCurrentInjector, ɵsetDocument, ɵsetLocaleId, ɵstore, ɵstringify, ɵted, ɵtransitiveScopesFor, ɵunregisterLocaleData, ɵunv, ɵunwrapSafeValue, ɵvid, ɵwhenRendered, ɵɵCopyDefinitionFeature, ɵɵInheritDefinitionFeature, ɵɵNgOnChangesFeature, ɵɵProvidersFeature, ɵɵadvance, ɵɵattribute, ɵɵattributeInterpolate1, ɵɵattributeInterpolate2, ɵɵattributeInterpolate3, ɵɵattributeInterpolate4, ɵɵattributeInterpolate5, ɵɵattributeInterpolate6, ɵɵattributeInterpolate7, ɵɵattributeInterpolate8, ɵɵattributeInterpolateV, ɵɵclassMap, ɵɵclassMapInterpolate1, ɵɵclassMapInterpolate2, ɵɵclassMapInterpolate3, ɵɵclassMapInterpolate4, ɵɵclassMapInterpolate5, ɵɵclassMapInterpolate6, ɵɵclassMapInterpolate7, ɵɵclassMapInterpolate8, ɵɵclassMapInterpolateV, ɵɵclassProp, ɵɵcomponentHostSyntheticListener, ɵɵcontentQuery, ɵɵdefaultStyleSanitizer, ɵɵdefineComponent, ɵɵdefineDirective, ɵɵdefineInjectable, ɵɵdefineInjector, ɵɵdefineNgModule, ɵɵdefinePipe, ɵɵdirectiveInject, ɵɵdisableBindings, ɵɵelement, ɵɵelementContainer, ɵɵelementContainerEnd, ɵɵelementContainerStart, ɵɵelementEnd, ɵɵelementStart, ɵɵenableBindings, ɵɵgetCurrentView, ɵɵgetFactoryOf, ɵɵgetInheritedFactory, ɵɵhostProperty, ɵɵi18n, ɵɵi18nApply, ɵɵi18nAttributes, ɵɵi18nEnd, ɵɵi18nExp, ɵɵi18nPostprocess, ɵɵi18nStart, ɵɵinject, ɵɵinjectAttribute, ɵɵinjectPipeChangeDetectorRef, ɵɵinvalidFactory, ɵɵinvalidFactoryDep, ɵɵlistener, ɵɵloadQuery, ɵɵnamespaceHTML, ɵɵnamespaceMathML, ɵɵnamespaceSVG, ɵɵnextContext, ɵɵpipe, ɵɵpipeBind1, ɵɵpipeBind2, ɵɵpipeBind3, ɵɵpipeBind4, ɵɵpipeBindV, ɵɵprojection, ɵɵprojectionDef, ɵɵproperty, ɵɵpropertyInterpolate, ɵɵpropertyInterpolate1, ɵɵpropertyInterpolate2, ɵɵpropertyInterpolate3, ɵɵpropertyInterpolate4, ɵɵpropertyInterpolate5, ɵɵpropertyInterpolate6, ɵɵpropertyInterpolate7, ɵɵpropertyInterpolate8, ɵɵpropertyInterpolateV, ɵɵpureFunction0, ɵɵpureFunction1, ɵɵpureFunction2, ɵɵpureFunction3, ɵɵpureFunction4, ɵɵpureFunction5, ɵɵpureFunction6, ɵɵpureFunction7, ɵɵpureFunction8, ɵɵpureFunctionV, ɵɵqueryRefresh, ɵɵreference, ɵɵresolveBody, ɵɵresolveDocument, ɵɵresolveWindow, ɵɵrestoreView, ɵɵsanitizeHtml, ɵɵsanitizeResourceUrl, ɵɵsanitizeScript, ɵɵsanitizeStyle, ɵɵsanitizeUrl, ɵɵsanitizeUrlOrResourceUrl, ɵɵselect, ɵɵsetComponentScope, ɵɵsetNgModuleScope, ɵɵstaticContentQuery, ɵɵstaticViewQuery, ɵɵstyleMap, ɵɵstyleMapInterpolate1, ɵɵstyleMapInterpolate2, ɵɵstyleMapInterpolate3, ɵɵstyleMapInterpolate4, ɵɵstyleMapInterpolate5, ɵɵstyleMapInterpolate6, ɵɵstyleMapInterpolate7, ɵɵstyleMapInterpolate8, ɵɵstyleMapInterpolateV, ɵɵstyleProp, ɵɵstylePropInterpolate1, ɵɵstylePropInterpolate2, ɵɵstylePropInterpolate3, ɵɵstylePropInterpolate4, ɵɵstylePropInterpolate5, ɵɵstylePropInterpolate6, ɵɵstylePropInterpolate7, ɵɵstylePropInterpolate8, ɵɵstylePropInterpolateV, ɵɵstyleSanitizer, ɵɵtemplate, ɵɵtemplateRefExtractor, ɵɵtext, ɵɵtextInterpolate, ɵɵtextInterpolate1, ɵɵtextInterpolate2, ɵɵtextInterpolate3, ɵɵtextInterpolate4, ɵɵtextInterpolate5, ɵɵtextInterpolate6, ɵɵtextInterpolate7, ɵɵtextInterpolate8, ɵɵtextInterpolateV, ɵɵupdateSyntheticHostBinding, ɵɵviewQuery */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ANALYZE_FOR_ENTRY_COMPONENTS", function() { return ANALYZE_FOR_ENTRY_COMPONENTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_BOOTSTRAP_LISTENER", function() { return APP_BOOTSTRAP_LISTENER; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_ID", function() { return APP_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_INITIALIZER", function() { return APP_INITIALIZER; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ApplicationInitStatus", function() { return ApplicationInitStatus; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ApplicationModule", function() { return ApplicationModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ApplicationRef", function() { return ApplicationRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Attribute", function() { return Attribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "COMPILER_OPTIONS", function() { return COMPILER_OPTIONS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CUSTOM_ELEMENTS_SCHEMA", function() { return CUSTOM_ELEMENTS_SCHEMA; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChangeDetectionStrategy", function() { return ChangeDetectionStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChangeDetectorRef", function() { return ChangeDetectorRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Compiler", function() { return Compiler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompilerFactory", function() { return CompilerFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Component", function() { return Component; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentFactory", function() { return ComponentFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentFactoryResolver", function() { return ComponentFactoryResolver; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentRef", function() { return ComponentRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContentChild", function() { return ContentChild; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContentChildren", function() { return ContentChildren; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_CURRENCY_CODE", function() { return DEFAULT_CURRENCY_CODE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DebugElement", function() { return DebugElement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DebugEventListener", function() { return DebugEventListener; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DebugNode", function() { return DebugNode$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultIterableDiffer", function() { return DefaultIterableDiffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Directive", function() { return Directive; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementRef", function() { return ElementRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmbeddedViewRef", function() { return EmbeddedViewRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorHandler", function() { return ErrorHandler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EventEmitter", function() { return EventEmitter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Host", function() { return Host; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HostBinding", function() { return HostBinding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HostListener", function() { return HostListener; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "INJECTOR", function() { return INJECTOR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Inject", function() { return Inject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InjectFlags", function() { return InjectFlags; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Injectable", function() { return Injectable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InjectionToken", function() { return InjectionToken; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Injector", function() { return Injector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Input", function() { return Input; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IterableDiffers", function() { return IterableDiffers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyValueDiffers", function() { return KeyValueDiffers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LOCALE_ID", function() { return LOCALE_ID$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MissingTranslationStrategy", function() { return MissingTranslationStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ModuleWithComponentFactories", function() { return ModuleWithComponentFactories; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NO_ERRORS_SCHEMA", function() { return NO_ERRORS_SCHEMA; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgModule", function() { return NgModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgModuleFactory", function() { return NgModuleFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgModuleFactoryLoader", function() { return NgModuleFactoryLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgModuleRef", function() { return NgModuleRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgProbeToken", function() { return NgProbeToken; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NgZone", function() { return NgZone; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Optional", function() { return Optional; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Output", function() { return Output; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PACKAGE_ROOT_URL", function() { return PACKAGE_ROOT_URL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PLATFORM_ID", function() { return PLATFORM_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PLATFORM_INITIALIZER", function() { return PLATFORM_INITIALIZER; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Pipe", function() { return Pipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlatformRef", function() { return PlatformRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Query", function() { return Query; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueryList", function() { return QueryList; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReflectiveInjector", function() { return ReflectiveInjector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReflectiveKey", function() { return ReflectiveKey; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Renderer2", function() { return Renderer2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RendererFactory2", function() { return RendererFactory2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RendererStyleFlags2", function() { return RendererStyleFlags2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ResolvedReflectiveFactory", function() { return ResolvedReflectiveFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Sanitizer", function() { return Sanitizer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SecurityContext", function() { return SecurityContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Self", function() { return Self; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SimpleChange", function() { return SimpleChange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SkipSelf", function() { return SkipSelf; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SystemJsNgModuleLoader", function() { return SystemJsNgModuleLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SystemJsNgModuleLoaderConfig", function() { return SystemJsNgModuleLoaderConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TRANSLATIONS", function() { return TRANSLATIONS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TRANSLATIONS_FORMAT", function() { return TRANSLATIONS_FORMAT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TemplateRef", function() { return TemplateRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Testability", function() { return Testability; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TestabilityRegistry", function() { return TestabilityRegistry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Type", function() { return Type; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return VERSION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Version", function() { return Version; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViewChild", function() { return ViewChild; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViewChildren", function() { return ViewChildren; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViewContainerRef", function() { return ViewContainerRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViewEncapsulation", function() { return ViewEncapsulation$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViewRef", function() { return ViewRef$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WrappedValue", function() { return WrappedValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asNativeElements", function() { return asNativeElements; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assertPlatform", function() { return assertPlatform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createPlatform", function() { return createPlatform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createPlatformFactory", function() { return createPlatformFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defineInjectable", function() { return defineInjectable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "destroyPlatform", function() { return destroyPlatform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableProdMode", function() { return enableProdMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forwardRef", function() { return forwardRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDebugNode", function() { return getDebugNode$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getModuleFactory", function() { return getModuleFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPlatform", function() { return getPlatform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inject", function() { return inject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDevMode", function() { return isDevMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "platformCore", function() { return platformCore; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resolveForwardRef", function() { return resolveForwardRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setTestabilityGetter", function() { return setTestabilityGetter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵALLOW_MULTIPLE_PLATFORMS", function() { return ALLOW_MULTIPLE_PLATFORMS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵAPP_ID_RANDOM_PROVIDER", function() { return APP_ID_RANDOM_PROVIDER; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵChangeDetectorStatus", function() { return ChangeDetectorStatus; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵCodegenComponentFactoryResolver", function() { return CodegenComponentFactoryResolver; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵCompiler_compileModuleAndAllComponentsAsync__POST_R3__", function() { return Compiler_compileModuleAndAllComponentsAsync__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵCompiler_compileModuleAndAllComponentsSync__POST_R3__", function() { return Compiler_compileModuleAndAllComponentsSync__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵCompiler_compileModuleAsync__POST_R3__", function() { return Compiler_compileModuleAsync__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵCompiler_compileModuleSync__POST_R3__", function() { return Compiler_compileModuleSync__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵComponentFactory", function() { return ComponentFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵConsole", function() { return Console; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵDEFAULT_LOCALE_ID", function() { return DEFAULT_LOCALE_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵEMPTY_ARRAY", function() { return EMPTY_ARRAY$4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵEMPTY_MAP", function() { return EMPTY_MAP; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵINJECTOR_IMPL__POST_R3__", function() { return INJECTOR_IMPL__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵINJECTOR_SCOPE", function() { return INJECTOR_SCOPE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵLifecycleHooksFeature", function() { return LifecycleHooksFeature; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵLocaleDataIndex", function() { return LocaleDataIndex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNG_COMP_DEF", function() { return NG_COMP_DEF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNG_DIR_DEF", function() { return NG_DIR_DEF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNG_ELEMENT_ID", function() { return NG_ELEMENT_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNG_INJ_DEF", function() { return NG_INJ_DEF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNG_MOD_DEF", function() { return NG_MOD_DEF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNG_PIPE_DEF", function() { return NG_PIPE_DEF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNG_PROV_DEF", function() { return NG_PROV_DEF; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR", function() { return NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNO_CHANGE", function() { return NO_CHANGE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNgModuleFactory", function() { return NgModuleFactory$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNoopNgZone", function() { return NoopNgZone; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵReflectionCapabilities", function() { return ReflectionCapabilities; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵRender3ComponentFactory", function() { return ComponentFactory$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵRender3ComponentRef", function() { return ComponentRef$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵRender3NgModuleRef", function() { return NgModuleRef$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__", function() { return SWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_COMPILE_COMPONENT__POST_R3__", function() { return SWITCH_COMPILE_COMPONENT__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_COMPILE_DIRECTIVE__POST_R3__", function() { return SWITCH_COMPILE_DIRECTIVE__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_COMPILE_INJECTABLE__POST_R3__", function() { return SWITCH_COMPILE_INJECTABLE__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_COMPILE_NGMODULE__POST_R3__", function() { return SWITCH_COMPILE_NGMODULE__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_COMPILE_PIPE__POST_R3__", function() { return SWITCH_COMPILE_PIPE__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_ELEMENT_REF_FACTORY__POST_R3__", function() { return SWITCH_ELEMENT_REF_FACTORY__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_IVY_ENABLED__POST_R3__", function() { return SWITCH_IVY_ENABLED__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_RENDERER2_FACTORY__POST_R3__", function() { return SWITCH_RENDERER2_FACTORY__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_TEMPLATE_REF_FACTORY__POST_R3__", function() { return SWITCH_TEMPLATE_REF_FACTORY__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__", function() { return SWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵ_sanitizeHtml", function() { return _sanitizeHtml; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵ_sanitizeStyle", function() { return _sanitizeStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵ_sanitizeUrl", function() { return _sanitizeUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵallowSanitizationBypassAndThrow", function() { return allowSanitizationBypassAndThrow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵand", function() { return anchorDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_a", function() { return isForwardRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_b", function() { return injectInjectorOnly; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_ba", function() { return getLView; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bb", function() { return getPreviousOrParentTNode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bc", function() { return getBindingRoot; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bd", function() { return nextContextImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bf", function() { return pureFunction1Internal; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bg", function() { return pureFunction2Internal; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bh", function() { return pureFunction3Internal; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bi", function() { return pureFunction4Internal; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bj", function() { return pureFunctionVInternal; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bk", function() { return getUrlSanitizer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bl", function() { return makeParamDecorator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bm", function() { return makePropDecorator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bn", function() { return getClosureSafeProperty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bp", function() { return noSideEffects; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_bq", function() { return getRootContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_c", function() { return NullInjector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_d", function() { return ReflectiveInjector_; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_e", function() { return ReflectiveDependency; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_f", function() { return resolveReflectiveProviders; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_g", function() { return _appIdRandomProviderFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_h", function() { return createElementRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_i", function() { return createTemplateRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_j", function() { return getModuleFactory__PRE_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_k", function() { return DebugNode__PRE_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_l", function() { return DebugElement__PRE_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_m", function() { return getDebugNodeR2__PRE_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_n", function() { return DefaultIterableDifferFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_o", function() { return DefaultKeyValueDifferFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_p", function() { return _iterableDiffersFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_q", function() { return _keyValueDiffersFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_r", function() { return _localeFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_s", function() { return APPLICATION_MODULE_PROVIDERS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_t", function() { return zoneSchedulerFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_u", function() { return USD_CURRENCY_CODE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_v", function() { return _def; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_w", function() { return DebugContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_x", function() { return SCHEDULER; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_y", function() { return injectAttributeImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_core_core_z", function() { return instructionState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵbypassSanitizationTrustHtml", function() { return bypassSanitizationTrustHtml; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵbypassSanitizationTrustResourceUrl", function() { return bypassSanitizationTrustResourceUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵbypassSanitizationTrustScript", function() { return bypassSanitizationTrustScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵbypassSanitizationTrustStyle", function() { return bypassSanitizationTrustStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵbypassSanitizationTrustUrl", function() { return bypassSanitizationTrustUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵccf", function() { return createComponentFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵclearOverrides", function() { return clearOverrides; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵclearResolutionOfComponentResourcesQueue", function() { return clearResolutionOfComponentResourcesQueue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵcmf", function() { return createNgModuleFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵcompileComponent", function() { return compileComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵcompileDirective", function() { return compileDirective; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵcompileNgModule", function() { return compileNgModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵcompileNgModuleDefs", function() { return compileNgModuleDefs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵcompileNgModuleFactory__POST_R3__", function() { return compileNgModuleFactory__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵcompilePipe", function() { return compilePipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵcreateInjector", function() { return createInjector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵcrt", function() { return createRendererType2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵdefaultIterableDiffers", function() { return defaultIterableDiffers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵdefaultKeyValueDiffers", function() { return defaultKeyValueDiffers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵdetectChanges", function() { return detectChanges; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵdevModeEqual", function() { return devModeEqual$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵdid", function() { return directiveDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵeld", function() { return elementDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵfindLocaleData", function() { return findLocaleData; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵflushModuleScopingQueueAsMuchAsPossible", function() { return flushModuleScopingQueueAsMuchAsPossible; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetComponentViewDefinitionFactory", function() { return getComponentViewDefinitionFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetDebugNodeR2", function() { return getDebugNodeR2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetDebugNode__POST_R3__", function() { return getDebugNode__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetDirectives", function() { return getDirectives; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetHostElement", function() { return getHostElement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetInjectableDef", function() { return getInjectableDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetLContext", function() { return getLContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetLocaleCurrencyCode", function() { return getLocaleCurrencyCode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetLocalePluralCase", function() { return getLocalePluralCase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetModuleFactory__POST_R3__", function() { return getModuleFactory__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵgetSanitizationBypassType", function() { return getSanitizationBypassType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵglobal", function() { return _global; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵinitServicesIfNeeded", function() { return initServicesIfNeeded; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵinlineInterpolate", function() { return inlineInterpolate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵinterpolate", function() { return interpolate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵisBoundToModule__POST_R3__", function() { return isBoundToModule__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵisDefaultChangeDetectionStrategy", function() { return isDefaultChangeDetectionStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵisListLikeIterable", function() { return isListLikeIterable$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵisObservable", function() { return isObservable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵisPromise", function() { return isPromise; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵivyEnabled", function() { return ivyEnabled; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵlooseIdentical", function() { return looseIdentical; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵmakeDecorator", function() { return makeDecorator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵmarkDirty", function() { return markDirty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵmod", function() { return moduleDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵmpd", function() { return moduleProvideDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵncd", function() { return ngContentDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵnov", function() { return nodeValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵoverrideComponentView", function() { return overrideComponentView; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵoverrideProvider", function() { return overrideProvider; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵpad", function() { return pureArrayDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵpatchComponentDefWithScope", function() { return patchComponentDefWithScope; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵpid", function() { return pipeDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵpod", function() { return pureObjectDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵppd", function() { return purePipeDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵprd", function() { return providerDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵpublishDefaultGlobalUtils", function() { return publishDefaultGlobalUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵpublishGlobalUtil", function() { return publishGlobalUtil; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵqud", function() { return queryDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵregisterLocaleData", function() { return registerLocaleData; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵregisterModuleFactory", function() { return registerModuleFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵregisterNgModuleType", function() { return registerNgModuleType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵrenderComponent", function() { return renderComponent$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵresetCompiledComponents", function() { return resetCompiledComponents; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵresetJitOptions", function() { return resetJitOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵresolveComponentResources", function() { return resolveComponentResources; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵsetClassMetadata", function() { return setClassMetadata; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵsetCurrentInjector", function() { return setCurrentInjector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵsetDocument", function() { return setDocument; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵsetLocaleId", function() { return setLocaleId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵstore", function() { return store; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵstringify", function() { return stringify; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵted", function() { return textDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵtransitiveScopesFor", function() { return transitiveScopesFor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵunregisterLocaleData", function() { return unregisterAllLocaleData; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵunv", function() { return unwrapValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵunwrapSafeValue", function() { return unwrapSafeValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵvid", function() { return viewDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵwhenRendered", function() { return whenRendered; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵCopyDefinitionFeature", function() { return ɵɵCopyDefinitionFeature; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵInheritDefinitionFeature", function() { return ɵɵInheritDefinitionFeature; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵNgOnChangesFeature", function() { return ɵɵNgOnChangesFeature; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵProvidersFeature", function() { return ɵɵProvidersFeature; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵadvance", function() { return ɵɵadvance; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵattribute", function() { return ɵɵattribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵattributeInterpolate1", function() { return ɵɵattributeInterpolate1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵattributeInterpolate2", function() { return ɵɵattributeInterpolate2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵattributeInterpolate3", function() { return ɵɵattributeInterpolate3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵattributeInterpolate4", function() { return ɵɵattributeInterpolate4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵattributeInterpolate5", function() { return ɵɵattributeInterpolate5; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵattributeInterpolate6", function() { return ɵɵattributeInterpolate6; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵattributeInterpolate7", function() { return ɵɵattributeInterpolate7; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵattributeInterpolate8", function() { return ɵɵattributeInterpolate8; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵattributeInterpolateV", function() { return ɵɵattributeInterpolateV; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassMap", function() { return ɵɵclassMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassMapInterpolate1", function() { return ɵɵclassMapInterpolate1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassMapInterpolate2", function() { return ɵɵclassMapInterpolate2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassMapInterpolate3", function() { return ɵɵclassMapInterpolate3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassMapInterpolate4", function() { return ɵɵclassMapInterpolate4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassMapInterpolate5", function() { return ɵɵclassMapInterpolate5; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassMapInterpolate6", function() { return ɵɵclassMapInterpolate6; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassMapInterpolate7", function() { return ɵɵclassMapInterpolate7; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassMapInterpolate8", function() { return ɵɵclassMapInterpolate8; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassMapInterpolateV", function() { return ɵɵclassMapInterpolateV; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵclassProp", function() { return ɵɵclassProp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵcomponentHostSyntheticListener", function() { return ɵɵcomponentHostSyntheticListener; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵcontentQuery", function() { return ɵɵcontentQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵdefaultStyleSanitizer", function() { return ɵɵdefaultStyleSanitizer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵdefineComponent", function() { return ɵɵdefineComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵdefineDirective", function() { return ɵɵdefineDirective; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵdefineInjectable", function() { return ɵɵdefineInjectable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵdefineInjector", function() { return ɵɵdefineInjector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵdefineNgModule", function() { return ɵɵdefineNgModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵdefinePipe", function() { return ɵɵdefinePipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵdirectiveInject", function() { return ɵɵdirectiveInject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵdisableBindings", function() { return ɵɵdisableBindings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵelement", function() { return ɵɵelement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵelementContainer", function() { return ɵɵelementContainer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵelementContainerEnd", function() { return ɵɵelementContainerEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵelementContainerStart", function() { return ɵɵelementContainerStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵelementEnd", function() { return ɵɵelementEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵelementStart", function() { return ɵɵelementStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵenableBindings", function() { return ɵɵenableBindings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵgetCurrentView", function() { return ɵɵgetCurrentView; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵgetFactoryOf", function() { return ɵɵgetFactoryOf; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵgetInheritedFactory", function() { return ɵɵgetInheritedFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵhostProperty", function() { return ɵɵhostProperty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵi18n", function() { return ɵɵi18n; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵi18nApply", function() { return ɵɵi18nApply; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵi18nAttributes", function() { return ɵɵi18nAttributes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵi18nEnd", function() { return ɵɵi18nEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵi18nExp", function() { return ɵɵi18nExp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵi18nPostprocess", function() { return ɵɵi18nPostprocess; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵi18nStart", function() { return ɵɵi18nStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵinject", function() { return ɵɵinject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵinjectAttribute", function() { return ɵɵinjectAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵinjectPipeChangeDetectorRef", function() { return ɵɵinjectPipeChangeDetectorRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵinvalidFactory", function() { return ɵɵinvalidFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵinvalidFactoryDep", function() { return ɵɵinvalidFactoryDep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵlistener", function() { return ɵɵlistener; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵloadQuery", function() { return ɵɵloadQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵnamespaceHTML", function() { return ɵɵnamespaceHTML; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵnamespaceMathML", function() { return ɵɵnamespaceMathML; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵnamespaceSVG", function() { return ɵɵnamespaceSVG; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵnextContext", function() { return ɵɵnextContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpipe", function() { return ɵɵpipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpipeBind1", function() { return ɵɵpipeBind1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpipeBind2", function() { return ɵɵpipeBind2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpipeBind3", function() { return ɵɵpipeBind3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpipeBind4", function() { return ɵɵpipeBind4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpipeBindV", function() { return ɵɵpipeBindV; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵprojection", function() { return ɵɵprojection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵprojectionDef", function() { return ɵɵprojectionDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵproperty", function() { return ɵɵproperty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpropertyInterpolate", function() { return ɵɵpropertyInterpolate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpropertyInterpolate1", function() { return ɵɵpropertyInterpolate1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpropertyInterpolate2", function() { return ɵɵpropertyInterpolate2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpropertyInterpolate3", function() { return ɵɵpropertyInterpolate3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpropertyInterpolate4", function() { return ɵɵpropertyInterpolate4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpropertyInterpolate5", function() { return ɵɵpropertyInterpolate5; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpropertyInterpolate6", function() { return ɵɵpropertyInterpolate6; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpropertyInterpolate7", function() { return ɵɵpropertyInterpolate7; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpropertyInterpolate8", function() { return ɵɵpropertyInterpolate8; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpropertyInterpolateV", function() { return ɵɵpropertyInterpolateV; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpureFunction0", function() { return ɵɵpureFunction0; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpureFunction1", function() { return ɵɵpureFunction1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpureFunction2", function() { return ɵɵpureFunction2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpureFunction3", function() { return ɵɵpureFunction3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpureFunction4", function() { return ɵɵpureFunction4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpureFunction5", function() { return ɵɵpureFunction5; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpureFunction6", function() { return ɵɵpureFunction6; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpureFunction7", function() { return ɵɵpureFunction7; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpureFunction8", function() { return ɵɵpureFunction8; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵpureFunctionV", function() { return ɵɵpureFunctionV; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵqueryRefresh", function() { return ɵɵqueryRefresh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵreference", function() { return ɵɵreference; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵresolveBody", function() { return ɵɵresolveBody; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵresolveDocument", function() { return ɵɵresolveDocument; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵresolveWindow", function() { return ɵɵresolveWindow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵrestoreView", function() { return ɵɵrestoreView; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵsanitizeHtml", function() { return ɵɵsanitizeHtml; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵsanitizeResourceUrl", function() { return ɵɵsanitizeResourceUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵsanitizeScript", function() { return ɵɵsanitizeScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵsanitizeStyle", function() { return ɵɵsanitizeStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵsanitizeUrl", function() { return ɵɵsanitizeUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵsanitizeUrlOrResourceUrl", function() { return ɵɵsanitizeUrlOrResourceUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵselect", function() { return ɵɵselect; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵsetComponentScope", function() { return ɵɵsetComponentScope; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵsetNgModuleScope", function() { return ɵɵsetNgModuleScope; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstaticContentQuery", function() { return ɵɵstaticContentQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstaticViewQuery", function() { return ɵɵstaticViewQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleMap", function() { return ɵɵstyleMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleMapInterpolate1", function() { return ɵɵstyleMapInterpolate1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleMapInterpolate2", function() { return ɵɵstyleMapInterpolate2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleMapInterpolate3", function() { return ɵɵstyleMapInterpolate3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleMapInterpolate4", function() { return ɵɵstyleMapInterpolate4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleMapInterpolate5", function() { return ɵɵstyleMapInterpolate5; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleMapInterpolate6", function() { return ɵɵstyleMapInterpolate6; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleMapInterpolate7", function() { return ɵɵstyleMapInterpolate7; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleMapInterpolate8", function() { return ɵɵstyleMapInterpolate8; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleMapInterpolateV", function() { return ɵɵstyleMapInterpolateV; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleProp", function() { return ɵɵstyleProp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstylePropInterpolate1", function() { return ɵɵstylePropInterpolate1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstylePropInterpolate2", function() { return ɵɵstylePropInterpolate2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstylePropInterpolate3", function() { return ɵɵstylePropInterpolate3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstylePropInterpolate4", function() { return ɵɵstylePropInterpolate4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstylePropInterpolate5", function() { return ɵɵstylePropInterpolate5; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstylePropInterpolate6", function() { return ɵɵstylePropInterpolate6; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstylePropInterpolate7", function() { return ɵɵstylePropInterpolate7; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstylePropInterpolate8", function() { return ɵɵstylePropInterpolate8; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstylePropInterpolateV", function() { return ɵɵstylePropInterpolateV; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵstyleSanitizer", function() { return ɵɵstyleSanitizer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtemplate", function() { return ɵɵtemplate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtemplateRefExtractor", function() { return ɵɵtemplateRefExtractor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtext", function() { return ɵɵtext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtextInterpolate", function() { return ɵɵtextInterpolate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtextInterpolate1", function() { return ɵɵtextInterpolate1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtextInterpolate2", function() { return ɵɵtextInterpolate2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtextInterpolate3", function() { return ɵɵtextInterpolate3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtextInterpolate4", function() { return ɵɵtextInterpolate4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtextInterpolate5", function() { return ɵɵtextInterpolate5; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtextInterpolate6", function() { return ɵɵtextInterpolate6; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtextInterpolate7", function() { return ɵɵtextInterpolate7; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtextInterpolate8", function() { return ɵɵtextInterpolate8; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵtextInterpolateV", function() { return ɵɵtextInterpolateV; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵupdateSyntheticHostBinding", function() { return ɵɵupdateSyntheticHostBinding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵɵviewQuery", function() { return ɵɵviewQuery; });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm2015/index.js");
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs/operators */ "./node_modules/rxjs/_esm2015/operators/index.js");
/**
* @license Angular v9.1.13
* (c) 2010-2020 Google LLC. https://angular.io/
* License: MIT
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Convince closure compiler that the wrapped function has no side-effects.
*
* Closure compiler always assumes that `toString` has no side-effects. We use this quirk to
* allow us to execute a function but have closure compiler mark the call as no-side-effects.
* It is important that the return value for the `noSideEffects` function be assigned
* to something which is retained otherwise the call to `noSideEffects` will be removed by closure
* compiler.
*/
function noSideEffects(fn) {
return { toString: fn }.toString();
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const ANNOTATIONS = '__annotations__';
const PARAMETERS = '__parameters__';
const PROP_METADATA = '__prop__metadata__';
/**
* @suppress {globalThis}
*/
function makeDecorator(name, props, parentClass, additionalProcessing, typeFn) {
return noSideEffects(() => {
const metaCtor = makeMetadataCtor(props);
function DecoratorFactory(...args) {
if (this instanceof DecoratorFactory) {
metaCtor.call(this, ...args);
return this;
}
const annotationInstance = new DecoratorFactory(...args);
return function TypeDecorator(cls) {
if (typeFn)
typeFn(cls, ...args);
// Use of Object.defineProperty is important since it creates non-enumerable property which
// prevents the property is copied during subclassing.
const annotations = cls.hasOwnProperty(ANNOTATIONS) ?
cls[ANNOTATIONS] :
Object.defineProperty(cls, ANNOTATIONS, { value: [] })[ANNOTATIONS];
annotations.push(annotationInstance);
if (additionalProcessing)
additionalProcessing(cls);
return cls;
};
}
if (parentClass) {
DecoratorFactory.prototype = Object.create(parentClass.prototype);
}
DecoratorFactory.prototype.ngMetadataName = name;
DecoratorFactory.annotationCls = DecoratorFactory;
return DecoratorFactory;
});
}
function makeMetadataCtor(props) {
return function ctor(...args) {
if (props) {
const values = props(...args);
for (const propName in values) {
this[propName] = values[propName];
}
}
};
}
function makeParamDecorator(name, props, parentClass) {
return noSideEffects(() => {
const metaCtor = makeMetadataCtor(props);
function ParamDecoratorFactory(...args) {
if (this instanceof ParamDecoratorFactory) {
metaCtor.apply(this, args);
return this;
}
const annotationInstance = new ParamDecoratorFactory(...args);
ParamDecorator.annotation = annotationInstance;
return ParamDecorator;
function ParamDecorator(cls, unusedKey, index) {
// Use of Object.defineProperty is important since it creates non-enumerable property which
// prevents the property is copied during subclassing.
const parameters = cls.hasOwnProperty(PARAMETERS) ?
cls[PARAMETERS] :
Object.defineProperty(cls, PARAMETERS, { value: [] })[PARAMETERS];
// there might be gaps if some in between parameters do not have annotations.
// we pad with nulls.
while (parameters.length <= index) {
parameters.push(null);
}
(parameters[index] = parameters[index] || []).push(annotationInstance);
return cls;
}
}
if (parentClass) {
ParamDecoratorFactory.prototype = Object.create(parentClass.prototype);
}
ParamDecoratorFactory.prototype.ngMetadataName = name;
ParamDecoratorFactory.annotationCls = ParamDecoratorFactory;
return ParamDecoratorFactory;
});
}
function makePropDecorator(name, props, parentClass, additionalProcessing) {
return noSideEffects(() => {
const metaCtor = makeMetadataCtor(props);
function PropDecoratorFactory(...args) {
if (this instanceof PropDecoratorFactory) {
metaCtor.apply(this, args);
return this;
}
const decoratorInstance = new PropDecoratorFactory(...args);
function PropDecorator(target, name) {
const constructor = target.constructor;
// Use of Object.defineProperty is important since it creates non-enumerable property which
// prevents the property is copied during subclassing.
const meta = constructor.hasOwnProperty(PROP_METADATA) ?
constructor[PROP_METADATA] :
Object.defineProperty(constructor, PROP_METADATA, { value: {} })[PROP_METADATA];
meta[name] = meta.hasOwnProperty(name) && meta[name] || [];
meta[name].unshift(decoratorInstance);
if (additionalProcessing)
additionalProcessing(target, name, ...args);
}
return PropDecorator;
}
if (parentClass) {
PropDecoratorFactory.prototype = Object.create(parentClass.prototype);
}
PropDecoratorFactory.prototype.ngMetadataName = name;
PropDecoratorFactory.annotationCls = PropDecoratorFactory;
return PropDecoratorFactory;
});
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/metadata.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Type of the Inject decorator / constructor function.
*
* \@publicApi
* @record
*/
function InjectDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ0 = /**
* @param {?} token
* @return {?}
*/
(token) => ({ token });
/**
* Inject decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Inject = makeParamDecorator('Inject', (ɵ0));
/**
* Type of the Optional decorator / constructor function.
*
* \@publicApi
* @record
*/
function OptionalDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
/**
* Optional decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Optional = makeParamDecorator('Optional');
/**
* Type of the Self decorator / constructor function.
*
* \@publicApi
* @record
*/
function SelfDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
/**
* Self decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Self = makeParamDecorator('Self');
/**
* Type of the SkipSelf decorator / constructor function.
*
* \@publicApi
* @record
*/
function SkipSelfDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
/**
* SkipSelf decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const SkipSelf = makeParamDecorator('SkipSelf');
/**
* Type of the Host decorator / constructor function.
*
* \@publicApi
* @record
*/
function HostDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
/**
* Host decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Host = makeParamDecorator('Host');
/**
* Type of the Attribute decorator / constructor function.
*
* \@publicApi
* @record
*/
function AttributeDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ1 = /**
* @param {?=} attributeName
* @return {?}
*/
(attributeName) => ({ attributeName });
/**
* Attribute decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Attribute = makeParamDecorator('Attribute', (ɵ1));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Injection flags for DI.
*
* @publicApi
*/
var InjectFlags;
(function (InjectFlags) {
// TODO(alxhub): make this 'const' when ngc no longer writes exports of it into ngfactory files.
/** Check self and check parent injector if needed */
InjectFlags[InjectFlags["Default"] = 0] = "Default";
/**
* Specifies that an injector should retrieve a dependency from any injector until reaching the
* host element of the current component. (Only used with Element Injector)
*/
InjectFlags[InjectFlags["Host"] = 1] = "Host";
/** Don't ascend to ancestors of the node requesting injection. */
InjectFlags[InjectFlags["Self"] = 2] = "Self";
/** Skip the node that is requesting injection. */
InjectFlags[InjectFlags["SkipSelf"] = 4] = "SkipSelf";
/** Inject `defaultValue` instead if token not found. */
InjectFlags[InjectFlags["Optional"] = 8] = "Optional";
})(InjectFlags || (InjectFlags = {}));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function getClosureSafeProperty(objWithPropertyToExtract) {
for (let key in objWithPropertyToExtract) {
if (objWithPropertyToExtract[key] === getClosureSafeProperty) {
return key;
}
}
throw Error('Could not find renamed property on target object.');
}
/**
* Sets properties on a target object from a source object, but only if
* the property doesn't already exist on the target object.
* @param target The target to set properties on
* @param source The source of the property keys and values to set
*/
function fillProperties(target, source) {
for (const key in source) {
if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Construct an `InjectableDef` which defines how a token will be constructed by the DI system, and
* in which injectors (if any) it will be available.
*
* This should be assigned to a static `ɵprov` field on a type, which will then be an
* `InjectableType`.
*
* Options:
* * `providedIn` determines which injectors will include the injectable, by either associating it
* with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be
* provided in the `'root'` injector, which will be the application-level injector in most apps.
* * `factory` gives the zero argument function which will create an instance of the injectable.
* The factory can call `inject` to access the `Injector` and request injection of dependencies.
*
* @codeGenApi
*/
function ɵɵdefineInjectable(opts) {
return {
token: opts.token,
providedIn: opts.providedIn || null,
factory: opts.factory,
value: undefined,
};
}
/**
* @deprecated in v8, delete after v10. This API should be used only be generated code, and that
* code should now use ɵɵdefineInjectable instead.
* @publicApi
*/
const defineInjectable = ɵɵdefineInjectable;
/**
* Construct an `InjectorDef` which configures an injector.
*
* This should be assigned to a static injector def (`ɵinj`) field on a type, which will then be an
* `InjectorType`.
*
* Options:
*
* * `factory`: an `InjectorType` is an instantiable type, so a zero argument `factory` function to
* create the type must be provided. If that factory function needs to inject arguments, it can
* use the `inject` function.
* * `providers`: an optional array of providers to add to the injector. Each provider must
* either have a factory or point to a type which has a `ɵprov` static property (the
* type must be an `InjectableType`).
* * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s
* whose providers will also be added to the injector. Locally provided types will override
* providers from imports.
*
* @publicApi
*/
function ɵɵdefineInjector(options) {
return {
factory: options.factory,
providers: options.providers || [],
imports: options.imports || [],
};
}
/**
* Read the injectable def (`ɵprov`) for `type` in a way which is immune to accidentally reading
* inherited value.
*
* @param type A type which may have its own (non-inherited) `ɵprov`.
*/
function getInjectableDef(type) {
return getOwnDefinition(type, type[NG_PROV_DEF]) ||
getOwnDefinition(type, type[NG_INJECTABLE_DEF]);
}
/**
* Return `def` only if it is defined directly on `type` and is not inherited from a base
* class of `type`.
*
* The function `Object.hasOwnProperty` is not sufficient to distinguish this case because in older
* browsers (e.g. IE10) static property inheritance is implemented by copying the properties.
*
* Instead, the definition's `token` is compared to the `type`, and if they don't match then the
* property was not defined directly on the type itself, and was likely inherited. The definition
* is only returned if the `type` matches the `def.token`.
*/
function getOwnDefinition(type, def) {
return def && def.token === type ? def : null;
}
/**
* Read the injectable def (`ɵprov`) for `type` or read the `ɵprov` from one of its ancestors.
*
* @param type A type which may have `ɵprov`, via inheritance.
*
* @deprecated Will be removed in v10, where an error will occur in the scenario if we find the
* `ɵprov` on an ancestor only.
*/
function getInheritedInjectableDef(type) {
// See `jit/injectable.ts#compileInjectable` for context on NG_PROV_DEF_FALLBACK.
const def = type &&
(type[NG_PROV_DEF] || type[NG_INJECTABLE_DEF] ||
(type[NG_PROV_DEF_FALLBACK] && type[NG_PROV_DEF_FALLBACK]()));
if (def) {
const typeName = getTypeName(type);
// TODO(FW-1307): Re-add ngDevMode when closure can handle it
// ngDevMode &&
console.warn(`DEPRECATED: DI is instantiating a token "${typeName}" that inherits its @Injectable decorator but does not provide one itself.\n` +
`This will become an error in v10. Please add @Injectable() to the "${typeName}" class.`);
return def;
}
else {
return null;
}
}
/** Gets the name of a type, accounting for some cross-browser differences. */
function getTypeName(type) {
// `Function.prototype.name` behaves differently between IE and other browsers. In most browsers
// it'll always return the name of the function itself, no matter how many other functions it
// inherits from. On IE the function doesn't have its own `name` property, but it takes it from
// the lowest level in the prototype chain. E.g. if we have `class Foo extends Parent` most
// browsers will evaluate `Foo.name` to `Foo` while IE will return `Parent`. We work around
// the issue by converting the function to a string and parsing its name out that way via a regex.
if (type.hasOwnProperty('name')) {
return type.name;
}
const match = ('' + type).match(/^function\s*([^\s(]+)/);
return match === null ? '' : match[1];
}
/**
* Read the injector def type in a way which is immune to accidentally reading inherited value.
*
* @param type type which may have an injector def (`ɵinj`)
*/
function getInjectorDef(type) {
return type && (type.hasOwnProperty(NG_INJ_DEF) || type.hasOwnProperty(NG_INJECTOR_DEF)) ?
type[NG_INJ_DEF] :
null;
}
const NG_PROV_DEF = getClosureSafeProperty({ ɵprov: getClosureSafeProperty });
const NG_INJ_DEF = getClosureSafeProperty({ ɵinj: getClosureSafeProperty });
// On IE10 properties defined via `defineProperty` won't be inherited by child classes,
// which will break inheriting the injectable definition from a grandparent through an
// undecorated parent class. We work around it by defining a fallback method which will be
// used to retrieve the definition. This should only be a problem in JIT mode, because in
// AOT TypeScript seems to have a workaround for static properties. When inheriting from an
// undecorated parent is no longer supported in v10, this can safely be removed.
const NG_PROV_DEF_FALLBACK = getClosureSafeProperty({ ɵprovFallback: getClosureSafeProperty });
// We need to keep these around so we can read off old defs if new defs are unavailable
const NG_INJECTABLE_DEF = getClosureSafeProperty({ ngInjectableDef: getClosureSafeProperty });
const NG_INJECTOR_DEF = getClosureSafeProperty({ ngInjectorDef: getClosureSafeProperty });
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function stringify(token) {
if (typeof token === 'string') {
return token;
}
if (Array.isArray(token)) {
return '[' + token.map(stringify).join(', ') + ']';
}
if (token == null) {
return '' + token;
}
if (token.overriddenName) {
return `${token.overriddenName}`;
}
if (token.name) {
return `${token.name}`;
}
const res = token.toString();
if (res == null) {
return '' + res;
}
const newLineIndex = res.indexOf('\n');
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
/**
* Concatenates two strings with separator, allocating new strings only when necessary.
*
* @param before before string.
* @param separator separator string.
* @param after after string.
* @returns concatenated string.
*/
function concatStringsWithSpace(before, after) {
return (before == null || before === '') ?
(after === null ? '' : after) :
((after == null || after === '') ? before : before + ' ' + after);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/forward_ref.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* An interface that a function passed into {\@link forwardRef} has to implement.
*
* \@usageNotes
* ### Example
*
* {\@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref_fn'}
* \@publicApi
* @record
*/
function ForwardRefFn() { }
/** @type {?} */
const __forward_ref__ = getClosureSafeProperty({ __forward_ref__: getClosureSafeProperty });
/**
* Allows to refer to references which are not yet defined.
*
* For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
* DI is declared, but not yet defined. It is also used when the `token` which we use when creating
* a query is not yet defined.
*
* \@usageNotes
* ### Example
* {\@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
* \@publicApi
* @param {?} forwardRefFn
* @return {?}
*/
function forwardRef(forwardRefFn) {
((/** @type {?} */ (forwardRefFn))).__forward_ref__ = forwardRef;
((/** @type {?} */ (forwardRefFn))).toString = (/**
* @return {?}
*/
function () {
return stringify(this());
});
return ((/** @type {?} */ ((/** @type {?} */ (forwardRefFn)))));
}
/**
* Lazily retrieves the reference value from a forwardRef.
*
* Acts as the identity function when given a non-forward-ref value.
*
* \@usageNotes
* ### Example
*
* {\@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
*
* @see `forwardRef`
* \@publicApi
* @template T
* @param {?} type
* @return {?}
*/
function resolveForwardRef(type) {
return isForwardRef(type) ? type() : type;
}
/**
* Checks whether a function is wrapped by a `forwardRef`.
* @param {?} fn
* @return {?}
*/
function isForwardRef(fn) {
return typeof fn === 'function' && fn.hasOwnProperty(__forward_ref__) &&
fn.__forward_ref__ === forwardRef;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const __globalThis = typeof globalThis !== 'undefined' && globalThis;
const __window = typeof window !== 'undefined' && window;
const __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
self instanceof WorkerGlobalScope && self;
const __global = typeof global !== 'undefined' && global;
// Always use __globalThis if available, which is the spec-defined global variable across all
// environments, then fallback to __global first, because in Node tests both __global and
// __window may be defined and _global should be __global in that case.
const _global = __globalThis || __global || __window || __self;
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var R3ResolvedDependencyType;
(function (R3ResolvedDependencyType) {
R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token";
R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute";
R3ResolvedDependencyType[R3ResolvedDependencyType["ChangeDetectorRef"] = 2] = "ChangeDetectorRef";
R3ResolvedDependencyType[R3ResolvedDependencyType["Invalid"] = 3] = "Invalid";
})(R3ResolvedDependencyType || (R3ResolvedDependencyType = {}));
var R3FactoryTarget;
(function (R3FactoryTarget) {
R3FactoryTarget[R3FactoryTarget["Directive"] = 0] = "Directive";
R3FactoryTarget[R3FactoryTarget["Component"] = 1] = "Component";
R3FactoryTarget[R3FactoryTarget["Injectable"] = 2] = "Injectable";
R3FactoryTarget[R3FactoryTarget["Pipe"] = 3] = "Pipe";
R3FactoryTarget[R3FactoryTarget["NgModule"] = 4] = "NgModule";
})(R3FactoryTarget || (R3FactoryTarget = {}));
var ViewEncapsulation;
(function (ViewEncapsulation) {
ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native";
ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
})(ViewEncapsulation || (ViewEncapsulation = {}));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function getCompilerFacade() {
const globalNg = _global['ng'];
if (!globalNg || !globalNg.ɵcompilerFacade) {
throw new Error(`Angular JIT compilation failed: '@angular/compiler' not loaded!\n` +
` - JIT compilation is discouraged for production use-cases! Consider AOT mode instead.\n` +
` - Did you bootstrap using '@angular/platform-browser-dynamic' or '@angular/platform-server'?\n` +
` - Alternatively provide the compiler with 'import "@angular/compiler";' before bootstrapping.`);
}
return globalNg.ɵcompilerFacade;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/fields.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const NG_COMP_DEF = getClosureSafeProperty({ ɵcmp: getClosureSafeProperty });
/** @type {?} */
const NG_DIR_DEF = getClosureSafeProperty({ ɵdir: getClosureSafeProperty });
/** @type {?} */
const NG_PIPE_DEF = getClosureSafeProperty({ ɵpipe: getClosureSafeProperty });
/** @type {?} */
const NG_MOD_DEF = getClosureSafeProperty({ ɵmod: getClosureSafeProperty });
/** @type {?} */
const NG_LOC_ID_DEF = getClosureSafeProperty({ ɵloc: getClosureSafeProperty });
/** @type {?} */
const NG_FACTORY_DEF = getClosureSafeProperty({ ɵfac: getClosureSafeProperty });
// TODO(misko): This is wrong. The NG_ELEMENT_ID should never be minified.
/**
* If a directive is diPublic, bloomAdd sets a property on the type with this constant as
* the key and the directive's unique ID as the value. This allows us to map directives to their
* bloom filter bit for DI.
* @type {?}
*/
const NG_ELEMENT_ID = getClosureSafeProperty({ __NG_ELEMENT_ID__: getClosureSafeProperty });
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function ngDevModeResetPerfCounters() {
const locationString = typeof location !== 'undefined' ? location.toString() : '';
const newCounters = {
namedConstructors: locationString.indexOf('ngDevMode=namedConstructors') != -1,
firstCreatePass: 0,
tNode: 0,
tView: 0,
rendererCreateTextNode: 0,
rendererSetText: 0,
rendererCreateElement: 0,
rendererAddEventListener: 0,
rendererSetAttribute: 0,
rendererRemoveAttribute: 0,
rendererSetProperty: 0,
rendererSetClassName: 0,
rendererAddClass: 0,
rendererRemoveClass: 0,
rendererSetStyle: 0,
rendererRemoveStyle: 0,
rendererDestroy: 0,
rendererDestroyNode: 0,
rendererMoveNode: 0,
rendererRemoveNode: 0,
rendererAppendChild: 0,
rendererInsertBefore: 0,
rendererCreateComment: 0,
};
// Make sure to refer to ngDevMode as ['ngDevMode'] for closure.
const allowNgDevModeTrue = locationString.indexOf('ngDevMode=false') === -1;
_global['ngDevMode'] = allowNgDevModeTrue && newCounters;
return newCounters;
}
/**
* This function checks to see if the `ngDevMode` has been set. If yes,
* then we honor it, otherwise we default to dev mode with additional checks.
*
* The idea is that unless we are doing production build where we explicitly
* set `ngDevMode == false` we should be helping the developer by providing
* as much early warning and errors as possible.
*
* `ɵɵdefineComponent` is guaranteed to have been called before any component template functions
* (and thus Ivy instructions), so a single initialization there is sufficient to ensure ngDevMode
* is defined for the entire instruction set.
*
* When using checking `ngDevMode` on toplevel, always init it before referencing it
* (e.g. `((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode())`), otherwise you can
* get a `ReferenceError` like in https://github.com/angular/angular/issues/31595.
*
* Details on possible values for `ngDevMode` can be found on its docstring.
*
* NOTE:
* - changes to the `ngDevMode` name must be synced with `compiler-cli/src/tooling.ts`.
*/
function initNgDevMode() {
// The below checks are to ensure that calling `initNgDevMode` multiple times does not
// reset the counters.
// If the `ngDevMode` is not an object, then it means we have not created the perf counters
// yet.
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'object') {
ngDevModeResetPerfCounters();
}
return !!ngDevMode;
}
return false;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/injection_token.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Creates a token that can be used in a DI Provider.
*
* Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
* runtime representation) such as when injecting an interface, callable type, array or
* parameterized type.
*
* `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
* the `Injector`. This provides additional level of type safety.
*
* ```
* interface MyInterface {...}
* var myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken'));
* // myInterface is inferred to be MyInterface.
* ```
*
* When creating an `InjectionToken`, you can optionally specify a factory function which returns
* (possibly by creating) a default value of the parameterized type `T`. This sets up the
* `InjectionToken` using this factory as a provider as if it was defined explicitly in the
* application's root injector. If the factory function, which takes zero arguments, needs to inject
* dependencies, it can do so using the `inject` function. See below for an example.
*
* Additionally, if a `factory` is specified you can also specify the `providedIn` option, which
* overrides the above behavior and marks the token as belonging to a particular `\@NgModule`. As
* mentioned above, `'root'` is the default value for `providedIn`.
*
* \@usageNotes
* ### Basic Example
*
* ### Plain InjectionToken
*
* {\@example core/di/ts/injector_spec.ts region='InjectionToken'}
*
* ### Tree-shakable InjectionToken
*
* {\@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
*
*
* \@publicApi
* @template T
*/
class InjectionToken {
/**
* @param {?} _desc
* @param {?=} options
*/
constructor(_desc, options) {
this._desc = _desc;
/**
* \@internal
*/
this.ngMetadataName = 'InjectionToken';
this.ɵprov = undefined;
if (typeof options == 'number') {
// This is a special hack to assign __NG_ELEMENT_ID__ to this instance.
// __NG_ELEMENT_ID__ is Used by Ivy to determine bloom filter id.
// We are using it to assign `-1` which is used to identify `Injector`.
((/** @type {?} */ (this))).__NG_ELEMENT_ID__ = options;
}
else if (options !== undefined) {
this.ɵprov = ɵɵdefineInjectable({
token: this,
providedIn: options.providedIn || 'root',
factory: options.factory,
});
}
}
/**
* @return {?}
*/
toString() {
return `InjectionToken ${this._desc}`;
}
}
if (false) {}
/**
* @record
* @template T
*/
function InjectableDefToken() { }
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/injector_compatibility.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.
*
* Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a
* project.
*
* \@publicApi
* @type {?}
*/
const INJECTOR = new InjectionToken('INJECTOR', (/** @type {?} */ (-1)));
/** @type {?} */
const _THROW_IF_NOT_FOUND = {};
/** @type {?} */
const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
/** @type {?} */
const NG_TEMP_TOKEN_PATH = 'ngTempTokenPath';
/** @type {?} */
const NG_TOKEN_PATH = 'ngTokenPath';
/** @type {?} */
const NEW_LINE = /\n/gm;
/** @type {?} */
const NO_NEW_LINE = 'ɵ';
/** @type {?} */
const SOURCE = '__source';
const ɵ0$1 = getClosureSafeProperty;
/** @type {?} */
const USE_VALUE = getClosureSafeProperty({ provide: String, useValue: ɵ0$1 });
/**
* Current injector value used by `inject`.
* - `undefined`: it is an error to call `inject`
* - `null`: `inject` can be called but there is no injector (limp-mode).
* - Injector instance: Use the injector for resolution.
* @type {?}
*/
let _currentInjector = undefined;
/**
* @param {?} injector
* @return {?}
*/
function setCurrentInjector(injector) {
/** @type {?} */
const former = _currentInjector;
_currentInjector = injector;
return former;
}
/**
* Current implementation of inject.
*
* By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed
* to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this
* way for two reasons:
* 1. `Injector` should not depend on ivy logic.
* 2. To maintain tree shake-ability we don't want to bring in unnecessary code.
* @type {?}
*/
let _injectImplementation;
/**
* Sets the current inject implementation.
* @param {?} impl
* @return {?}
*/
function setInjectImplementation(impl) {
/** @type {?} */
const previous = _injectImplementation;
_injectImplementation = impl;
return previous;
}
/**
* @template T
* @param {?} token
* @param {?=} flags
* @return {?}
*/
function injectInjectorOnly(token, flags = InjectFlags.Default) {
if (_currentInjector === undefined) {
throw new Error(`inject() must be called from an injection context`);
}
else if (_currentInjector === null) {
return injectRootLimpMode(token, undefined, flags);
}
else {
return _currentInjector.get(token, flags & InjectFlags.Optional ? null : undefined, flags);
}
}
/**
* @template T
* @param {?} token
* @param {?=} flags
* @return {?}
*/
function ɵɵinject(token, flags = InjectFlags.Default) {
return (_injectImplementation || injectInjectorOnly)(resolveForwardRef(token), flags);
}
/**
* Throws an error indicating that a factory function could not be generated by the compiler for a
* particular class.
*
* This instruction allows the actual error message to be optimized away when ngDevMode is turned
* off, saving bytes of generated code while still providing a good experience in dev mode.
*
* The name of the class is not mentioned here, but will be in the generated factory function name
* and thus in the stack trace.
*
* \@codeGenApi
* @param {?} index
* @return {?}
*/
function ɵɵinvalidFactoryDep(index) {
/** @type {?} */
const msg = ngDevMode ?
`This constructor is not compatible with Angular Dependency Injection because its dependency at index ${index} of the parameter list is invalid.
This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.
Please check that 1) the type for the parameter at index ${index} is correct and 2) the correct Angular decorators are defined for this class and its ancestors.` :
'invalid';
throw new Error(msg);
}
/**
* Injects a token from the currently active injector.
*
* Must be used in the context of a factory function such as one defined for an
* `InjectionToken`. Throws an error if not called from such a context.
*
* Within such a factory function, using this function to request injection of a dependency
* is faster and more type-safe than providing an additional array of dependencies
* (as has been common with `useFactory` providers).
*
* \@param token The injection token for the dependency to be injected.
* \@param flags Optional flags that control how injection is executed.
* The flags correspond to injection strategies that can be specified with
* parameter decorators `\@Host`, `\@Self`, `\@SkipSef`, and `\@Optional`.
* \@return True if injection is successful, null otherwise.
*
* \@usageNotes
*
* ### Example
*
* {\@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
*
* \@publicApi
* @type {?}
*/
const inject = ɵɵinject;
/**
* Injects `root` tokens in limp mode.
*
* If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to
* `"root"`. This is known as the limp mode injection. In such case the value is stored in the
* `InjectableDef`.
* @template T
* @param {?} token
* @param {?} notFoundValue
* @param {?} flags
* @return {?}
*/
function injectRootLimpMode(token, notFoundValue, flags) {
/** @type {?} */
const injectableDef = getInjectableDef(token);
if (injectableDef && injectableDef.providedIn == 'root') {
return injectableDef.value === undefined ? injectableDef.value = injectableDef.factory() :
injectableDef.value;
}
if (flags & InjectFlags.Optional)
return null;
if (notFoundValue !== undefined)
return notFoundValue;
throw new Error(`Injector: NOT_FOUND [${stringify(token)}]`);
}
/**
* @param {?} types
* @return {?}
*/
function injectArgs(types) {
/** @type {?} */
const args = [];
for (let i = 0; i < types.length; i++) {
/** @type {?} */
const arg = resolveForwardRef(types[i]);
if (Array.isArray(arg)) {
if (arg.length === 0) {
throw new Error('Arguments array must have arguments.');
}
/** @type {?} */
let type = undefined;
/** @type {?} */
let flags = InjectFlags.Default;
for (let j = 0; j < arg.length; j++) {
/** @type {?} */
const meta = arg[j];
if (meta instanceof Optional || meta.ngMetadataName === 'Optional' || meta === Optional) {
flags |= InjectFlags.Optional;
}
else if (meta instanceof SkipSelf || meta.ngMetadataName === 'SkipSelf' || meta === SkipSelf) {
flags |= InjectFlags.SkipSelf;
}
else if (meta instanceof Self || meta.ngMetadataName === 'Self' || meta === Self) {
flags |= InjectFlags.Self;
}
else if (meta instanceof Inject || meta === Inject) {
type = meta.token;
}
else {
type = meta;
}
}
args.push(ɵɵinject((/** @type {?} */ (type)), flags));
}
else {
args.push(ɵɵinject(arg));
}
}
return args;
}
class NullInjector {
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
get(token, notFoundValue = THROW_IF_NOT_FOUND) {
if (notFoundValue === THROW_IF_NOT_FOUND) {
// Intentionally left behind: With dev tools open the debugger will stop here. There is no
// reason why correctly written application should cause this exception.
// TODO(misko): uncomment the next line once `ngDevMode` works with closure.
// if (ngDevMode) debugger;
/** @type {?} */
const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`);
error.name = 'NullInjectorError';
throw error;
}
return notFoundValue;
}
}
/**
* @param {?} e
* @param {?} token
* @param {?} injectorErrorName
* @param {?} source
* @return {?}
*/
function catchInjectorError(e, token, injectorErrorName, source) {
/** @type {?} */
const tokenPath = e[NG_TEMP_TOKEN_PATH];
if (token[SOURCE]) {
tokenPath.unshift(token[SOURCE]);
}
e.message = formatError('\n' + e.message, tokenPath, injectorErrorName, source);
e[NG_TOKEN_PATH] = tokenPath;
e[NG_TEMP_TOKEN_PATH] = null;
throw e;
}
/**
* @param {?} text
* @param {?} obj
* @param {?} injectorErrorName
* @param {?=} source
* @return {?}
*/
function formatError(text, obj, injectorErrorName, source = null) {
text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.substr(2) : text;
/** @type {?} */
let context = stringify(obj);
if (Array.isArray(obj)) {
context = obj.map(stringify).join(' -> ');
}
else if (typeof obj === 'object') {
/** @type {?} */
let parts = (/** @type {?} */ ([]));
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
/** @type {?} */
let value = obj[key];
parts.push(key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify(value)));
}
}
context = `{${parts.join(', ')}}`;
}
return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\n ')}`;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/jit/environment.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A mapping of the \@angular/core API surface used in generated expressions to the actual symbols.
*
* This should be kept up to date with the public exports of \@angular/core.
* @type {?}
*/
const angularCoreDiEnv = {
'ɵɵdefineInjectable': ɵɵdefineInjectable,
'ɵɵdefineInjector': ɵɵdefineInjector,
'ɵɵinject': ɵɵinject,
'ɵɵgetFactoryOf': getFactoryOf,
'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
};
/**
* @template T
* @param {?} type
* @return {?}
*/
function getFactoryOf(type) {
/** @type {?} */
const typeAny = (/** @type {?} */ (type));
if (isForwardRef(type)) {
return (/** @type {?} */ (((/**
* @return {?}
*/
() => {
/** @type {?} */
const factory = getFactoryOf(resolveForwardRef(typeAny));
return factory ? factory() : null;
}))));
}
/** @type {?} */
const def = getInjectableDef(typeAny) || getInjectorDef(typeAny);
if (!def || def.factory === undefined) {
return null;
}
return def.factory;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/ng_module_factory.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Represents an instance of an NgModule created via a {\@link NgModuleFactory}.
*
* `NgModuleRef` provides access to the NgModule Instance as well other objects related to this
* NgModule Instance.
*
* \@publicApi
* @abstract
* @template T
*/
class NgModuleRef {
}
if (false) {}
/**
* @record
* @template T
*/
function InternalNgModuleRef() { }
if (false) {}
/**
* \@publicApi
* @abstract
* @template T
*/
class NgModuleFactory {
}
if (false) {}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function assertNumber(actual, msg) {
if (!(typeof actual === 'number')) {
throwError(msg, typeof actual, 'number', '===');
}
}
function assertNumberInRange(actual, minInclusive, maxInclusive) {
assertNumber(actual, 'Expected a number');
assertLessThanOrEqual(actual, maxInclusive, 'Expected number to be less than or equal to');
assertGreaterThanOrEqual(actual, minInclusive, 'Expected number to be greater than or equal to');
}
function assertString(actual, msg) {
if (!(typeof actual === 'string')) {
throwError(msg, actual === null ? 'null' : typeof actual, 'string', '===');
}
}
function assertEqual(actual, expected, msg) {
if (!(actual == expected)) {
throwError(msg, actual, expected, '==');
}
}
function assertNotEqual(actual, expected, msg) {
if (!(actual != expected)) {
throwError(msg, actual, expected, '!=');
}
}
function assertSame(actual, expected, msg) {
if (!(actual === expected)) {
throwError(msg, actual, expected, '===');
}
}
function assertNotSame(actual, expected, msg) {
if (!(actual !== expected)) {
throwError(msg, actual, expected, '!==');
}
}
function assertLessThan(actual, expected, msg) {
if (!(actual < expected)) {
throwError(msg, actual, expected, '<');
}
}
function assertLessThanOrEqual(actual, expected, msg) {
if (!(actual <= expected)) {
throwError(msg, actual, expected, '<=');
}
}
function assertGreaterThan(actual, expected, msg) {
if (!(actual > expected)) {
throwError(msg, actual, expected, '>');
}
}
function assertGreaterThanOrEqual(actual, expected, msg) {
if (!(actual >= expected)) {
throwError(msg, actual, expected, '>=');
}
}
function assertNotDefined(actual, msg) {
if (actual != null) {
throwError(msg, actual, null, '==');
}
}
function assertDefined(actual, msg) {
if (actual == null) {
throwError(msg, actual, null, '!=');
}
}
function throwError(msg, actual, expected, comparison) {
throw new Error(`ASSERTION ERROR: ${msg}` +
(comparison == null ? '' : ` [Expected=> ${expected} ${comparison} ${actual} <=Actual]`));
}
function assertDomNode(node) {
// If we're in a worker, `Node` will not be defined.
assertEqual((typeof Node !== 'undefined' && node instanceof Node) ||
(typeof node === 'object' && node != null &&
node.constructor.name === 'WebWorkerRenderNode'), true, `The provided value must be an instance of a DOM Node but got ${stringify(node)}`);
}
function assertDataInRange(arr, index) {
const maxLen = arr ? arr.length : 0;
assertLessThan(index, maxLen, `Index expected to be less than ${maxLen} but got ${index}`);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Equivalent to ES6 spread, add each item to an array.
*
* @param items The items to add
* @param arr The array to which you want to add the items
*/
function addAllToArray(items, arr) {
for (let i = 0; i < items.length; i++) {
arr.push(items[i]);
}
}
/**
* Flattens an array.
*/
function flatten(list, dst) {
if (dst === undefined)
dst = list;
for (let i = 0; i < list.length; i++) {
let item = list[i];
if (Array.isArray(item)) {
// we need to inline it.
if (dst === list) {
// Our assumption that the list was already flat was wrong and
// we need to clone flat since we need to write to it.
dst = list.slice(0, i);
}
flatten(item, dst);
}
else if (dst !== list) {
dst.push(item);
}
}
return dst;
}
function deepForEach(input, fn) {
input.forEach(value => Array.isArray(value) ? deepForEach(value, fn) : fn(value));
}
function addToArray(arr, index, value) {
// perf: array.push is faster than array.splice!
if (index >= arr.length) {
arr.push(value);
}
else {
arr.splice(index, 0, value);
}
}
function removeFromArray(arr, index) {
// perf: array.pop is faster than array.splice!
if (index >= arr.length - 1) {
return arr.pop();
}
else {
return arr.splice(index, 1)[0];
}
}
function newArray(size, value) {
const list = [];
for (let i = 0; i < size; i++) {
list.push(value);
}
return list;
}
/**
* Remove item from array (Same as `Array.splice()` but faster.)
*
* `Array.splice()` is not as fast because it has to allocate an array for the elements which were
* removed. This causes memory pressure and slows down code when most of the time we don't
* care about the deleted items array.
*
* https://jsperf.com/fast-array-splice (About 20x faster)
*
* @param array Array to splice
* @param index Index of element in array to remove.
* @param count Number of items to remove.
*/
function arraySplice(array, index, count) {
const length = array.length - count;
while (index < length) {
array[index] = array[index + count];
index++;
}
while (count--) {
array.pop(); // shrink the array
}
}
/**
* Same as `Array.splice(index, 0, value)` but faster.
*
* `Array.splice()` is not fast because it has to allocate an array for the elements which were
* removed. This causes memory pressure and slows down code when most of the time we don't
* care about the deleted items array.
*
* @param array Array to splice.
* @param index Index in array where the `value` should be added.
* @param value Value to add to array.
*/
function arrayInsert(array, index, value) {
ngDevMode && assertLessThanOrEqual(index, array.length, 'Can\'t insert past array end.');
let end = array.length;
while (end > index) {
const previousEnd = end - 1;
array[end] = array[previousEnd];
end = previousEnd;
}
array[index] = value;
}
/**
* Same as `Array.splice2(index, 0, value1, value2)` but faster.
*
* `Array.splice()` is not fast because it has to allocate an array for the elements which were
* removed. This causes memory pressure and slows down code when most of the time we don't
* care about the deleted items array.
*
* @param array Array to splice.
* @param index Index in array where the `value` should be added.
* @param value1 Value to add to array.
* @param value2 Value to add to array.
*/
function arrayInsert2(array, index, value1, value2) {
ngDevMode && assertLessThanOrEqual(index, array.length, 'Can\'t insert past array end.');
let end = array.length;
if (end == index) {
// inserting at the end.
array.push(value1, value2);
}
else if (end === 1) {
// corner case when we have less items in array than we have items to insert.
array.push(value2, array[0]);
array[0] = value1;
}
else {
end--;
array.push(array[end - 1], array[end]);
while (end > index) {
const previousEnd = end - 2;
array[end] = array[previousEnd];
end--;
}
array[index] = value1;
array[index + 1] = value2;
}
}
/**
* Insert a `value` into an `array` so that the array remains sorted.
*
* NOTE:
* - Duplicates are not allowed, and are ignored.
* - This uses binary search algorithm for fast inserts.
*
* @param array A sorted array to insert into.
* @param value The value to insert.
* @returns index of the inserted value.
*/
function arrayInsertSorted(array, value) {
let index = arrayIndexOfSorted(array, value);
if (index < 0) {
// if we did not find it insert it.
index = ~index;
arrayInsert(array, index, value);
}
return index;
}
/**
* Remove `value` from a sorted `array`.
*
* NOTE:
* - This uses binary search algorithm for fast removals.
*
* @param array A sorted array to remove from.
* @param value The value to remove.
* @returns index of the removed value.
* - positive index if value found and removed.
* - negative index if value not found. (`~index` to get the value where it should have been
* inserted)
*/
function arrayRemoveSorted(array, value) {
const index = arrayIndexOfSorted(array, value);
if (index >= 0) {
arraySplice(array, index, 1);
}
return index;
}
/**
* Get an index of an `value` in a sorted `array`.
*
* NOTE:
* - This uses binary search algorithm for fast removals.
*
* @param array A sorted array to binary search.
* @param value The value to look for.
* @returns index of the value.
* - positive index if value found.
* - negative index if value not found. (`~index` to get the value where it should have been
* located)
*/
function arrayIndexOfSorted(array, value) {
return _arrayIndexOfSorted(array, value, 0);
}
/**
* Set a `value` for a `key`.
*
* @param keyValueArray to modify.
* @param key The key to locate or create.
* @param value The value to set for a `key`.
* @returns index (always even) of where the value vas set.
*/
function keyValueArraySet(keyValueArray, key, value) {
let index = keyValueArrayIndexOf(keyValueArray, key);
if (index >= 0) {
// if we found it set it.
keyValueArray[index | 1] = value;
}
else {
index = ~index;
arrayInsert2(keyValueArray, index, key, value);
}
return index;
}
/**
* Retrieve a `value` for a `key` (on `undefined` if not found.)
*
* @param keyValueArray to search.
* @param key The key to locate.
* @return The `value` stored at the `key` location or `undefined if not found.
*/
function keyValueArrayGet(keyValueArray, key) {
const index = keyValueArrayIndexOf(keyValueArray, key);
if (index >= 0) {
// if we found it retrieve it.
return keyValueArray[index | 1];
}
return undefined;
}
/**
* Retrieve a `key` index value in the array or `-1` if not found.
*
* @param keyValueArray to search.
* @param key The key to locate.
* @returns index of where the key is (or should have been.)
* - positive (even) index if key found.
* - negative index if key not found. (`~index` (even) to get the index where it should have
* been inserted.)
*/
function keyValueArrayIndexOf(keyValueArray, key) {
return _arrayIndexOfSorted(keyValueArray, key, 1);
}
/**
* Delete a `key` (and `value`) from the `KeyValueArray`.
*
* @param keyValueArray to modify.
* @param key The key to locate or delete (if exist).
* @returns index of where the key was (or should have been.)
* - positive (even) index if key found and deleted.
* - negative index if key not found. (`~index` (even) to get the index where it should have
* been.)
*/
function keyValueArrayDelete(keyValueArray, key) {
const index = keyValueArrayIndexOf(keyValueArray, key);
if (index >= 0) {
// if we found it remove it.
arraySplice(keyValueArray, index, 2);
}
return index;
}
/**
* INTERNAL: Get an index of an `value` in a sorted `array` by grouping search by `shift`.
*
* NOTE:
* - This uses binary search algorithm for fast removals.
*
* @param array A sorted array to binary search.
* @param value The value to look for.
* @param shift grouping shift.
* - `0` means look at every location
* - `1` means only look at every other (even) location (the odd locations are to be ignored as
* they are values.)
* @returns index of the value.
* - positive index if value found.
* - negative index if value not found. (`~index` to get the value where it should have been
* inserted)
*/
function _arrayIndexOfSorted(array, value, shift) {
ngDevMode && assertEqual(Array.isArray(array), true, 'Expecting an array');
let start = 0;
let end = array.length >> shift;
while (end !== start) {
const middle = start + ((end - start) >> 1); // find the middle.
const current = array[middle << shift];
if (value === current) {
return (middle << shift);
}
else if (current > value) {
end = middle;
}
else {
start = middle + 1; // We already searched middle so make it non-inclusive by adding 1
}
}
return ~(end << shift);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/change_detection/constants.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @enum {number} */
const ChangeDetectionStrategy = {
/**
* Use the `CheckOnce` strategy, meaning that automatic change detection is deactivated
* until reactivated by setting the strategy to `Default` (`CheckAlways`).
* Change detection can still be explicitly invoked.
* This strategy applies to all child directives and cannot be overridden.
*/
OnPush: 0,
/**
* Use the default `CheckAlways` strategy, in which change detection is automatic until
* explicitly deactivated.
*/
Default: 1,
};
ChangeDetectionStrategy[ChangeDetectionStrategy.OnPush] = 'OnPush';
ChangeDetectionStrategy[ChangeDetectionStrategy.Default] = 'Default';
/** @enum {number} */
const ChangeDetectorStatus = {
/**
* A state in which, after calling `detectChanges()`, the change detector
* state becomes `Checked`, and must be explicitly invoked or reactivated.
*/
CheckOnce: 0,
/**
* A state in which change detection is skipped until the change detector mode
* becomes `CheckOnce`.
*/
Checked: 1,
/**
* A state in which change detection continues automatically until explicitly
* deactivated.
*/
CheckAlways: 2,
/**
* A state in which a change detector sub tree is not a part of the main tree and
* should be skipped.
*/
Detached: 3,
/**
* Indicates that the change detector encountered an error checking a binding
* or calling a directive lifecycle method and is now in an inconsistent state. Change
* detectors in this state do not detect changes.
*/
Errored: 4,
/**
* Indicates that the change detector has been destroyed.
*/
Destroyed: 5,
};
ChangeDetectorStatus[ChangeDetectorStatus.CheckOnce] = 'CheckOnce';
ChangeDetectorStatus[ChangeDetectorStatus.Checked] = 'Checked';
ChangeDetectorStatus[ChangeDetectorStatus.CheckAlways] = 'CheckAlways';
ChangeDetectorStatus[ChangeDetectorStatus.Detached] = 'Detached';
ChangeDetectorStatus[ChangeDetectorStatus.Errored] = 'Errored';
ChangeDetectorStatus[ChangeDetectorStatus.Destroyed] = 'Destroyed';
/**
* Reports whether a given strategy is currently the default for change detection.
* @see `ChangeDetectorStatus` / `ChangeDetectorRef`
* @param {?} changeDetectionStrategy The strategy to check.
* @return {?} True if the given strategy is the current default, false otherwise.
*/
function isDefaultChangeDetectionStrategy(changeDetectionStrategy) {
return changeDetectionStrategy == null ||
changeDetectionStrategy === ChangeDetectionStrategy.Default;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/metadata/view.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @enum {number} */
const ViewEncapsulation$1 = {
/**
* Emulate `Native` scoping of styles by adding an attribute containing surrogate id to the Host
* Element and pre-processing the style rules provided via {@link Component#styles styles} or
* {@link Component#styleUrls styleUrls}, and adding the new Host Element attribute to all
* selectors.
*
* This is the default option.
*/
Emulated: 0,
/**
* @deprecated v6.1.0 - use {ViewEncapsulation.ShadowDom} instead.
* Use the native encapsulation mechanism of the renderer.
*
* For the DOM this means using the deprecated [Shadow DOM
* v0](https://w3c.github.io/webcomponents/spec/shadow/) and
* creating a ShadowRoot for Component's Host Element.
*/
Native: 1,
/**
* Don't provide any template or style encapsulation.
*/
None: 2,
/**
* Use Shadow DOM to encapsulate styles.
*
* For the DOM this means using modern [Shadow
* DOM](https://w3c.github.io/webcomponents/spec/shadow/) and
* creating a ShadowRoot for Component's Host Element.
*/
ShadowDom: 3,
};
ViewEncapsulation$1[ViewEncapsulation$1.Emulated] = 'Emulated';
ViewEncapsulation$1[ViewEncapsulation$1.Native] = 'Native';
ViewEncapsulation$1[ViewEncapsulation$1.None] = 'None';
ViewEncapsulation$1[ViewEncapsulation$1.ShadowDom] = 'ShadowDom';
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/empty.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* This file contains reuseable "empty" symbols that can be used as default return values
* in different parts of the rendering code. Because the same symbols are returned, this
* allows for identity checks against these values to be consistently used by the framework
* code.
* @type {?}
*/
const EMPTY_OBJ = {};
/** @type {?} */
const EMPTY_ARRAY = [];
// freezing the values prevents any code from accidentally inserting new values in
if ((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode()) {
// These property accesses can be ignored because ngDevMode will be set to false
// when optimizing code and the whole if statement will be dropped.
// tslint:disable-next-line:no-toplevel-property-access
Object.freeze(EMPTY_OBJ);
// tslint:disable-next-line:no-toplevel-property-access
Object.freeze(EMPTY_ARRAY);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/definition.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
let _renderCompCount = 0;
/**
* Create a component definition object.
*
*
* # Example
* ```
* class MyDirective {
* // Generated by Angular Template Compiler
* // [Symbol] syntax will not be supported by TypeScript until v2.7
* static ɵcmp = defineComponent({
* ...
* });
* }
* ```
* \@codeGenApi
* @template T
* @param {?} componentDefinition
* @return {?}
*/
function ɵɵdefineComponent(componentDefinition) {
return noSideEffects((/**
* @return {?}
*/
() => {
// Initialize ngDevMode. This must be the first statement in ɵɵdefineComponent.
// See the `initNgDevMode` docstring for more information.
(typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
/** @type {?} */
const type = componentDefinition.type;
/** @type {?} */
const typePrototype = type.prototype;
/** @type {?} */
const declaredInputs = (/** @type {?} */ ({}));
/** @type {?} */
const def = {
type: type,
providersResolver: null,
decls: componentDefinition.decls,
vars: componentDefinition.vars,
factory: null,
template: componentDefinition.template || (/** @type {?} */ (null)),
consts: componentDefinition.consts || null,
ngContentSelectors: componentDefinition.ngContentSelectors,
hostBindings: componentDefinition.hostBindings || null,
hostVars: componentDefinition.hostVars || 0,
hostAttrs: componentDefinition.hostAttrs || null,
contentQueries: componentDefinition.contentQueries || null,
declaredInputs: declaredInputs,
inputs: (/** @type {?} */ (null)),
// assigned in noSideEffects
outputs: (/** @type {?} */ (null)),
// assigned in noSideEffects
exportAs: componentDefinition.exportAs || null,
onChanges: null,
onInit: typePrototype.ngOnInit || null,
doCheck: typePrototype.ngDoCheck || null,
afterContentInit: typePrototype.ngAfterContentInit || null,
afterContentChecked: typePrototype.ngAfterContentChecked || null,
afterViewInit: typePrototype.ngAfterViewInit || null,
afterViewChecked: typePrototype.ngAfterViewChecked || null,
onDestroy: typePrototype.ngOnDestroy || null,
onPush: componentDefinition.changeDetection === ChangeDetectionStrategy.OnPush,
directiveDefs: (/** @type {?} */ (null)),
// assigned in noSideEffects
pipeDefs: (/** @type {?} */ (null)),
// assigned in noSideEffects
selectors: componentDefinition.selectors || EMPTY_ARRAY,
viewQuery: componentDefinition.viewQuery || null,
features: (/** @type {?} */ (componentDefinition.features)) || null,
data: componentDefinition.data || {},
// TODO(misko): convert ViewEncapsulation into const enum so that it can be used directly in
// the next line. Also `None` should be 0 not 2.
encapsulation: componentDefinition.encapsulation || ViewEncapsulation$1.Emulated,
id: 'c',
styles: componentDefinition.styles || EMPTY_ARRAY,
_: (/** @type {?} */ (null)),
setInput: null,
schemas: componentDefinition.schemas || null,
tView: null,
};
/** @type {?} */
const directiveTypes = (/** @type {?} */ (componentDefinition.directives));
/** @type {?} */
const feature = componentDefinition.features;
/** @type {?} */
const pipeTypes = (/** @type {?} */ (componentDefinition.pipes));
def.id += _renderCompCount++;
def.inputs = invertObject(componentDefinition.inputs, declaredInputs),
def.outputs = invertObject(componentDefinition.outputs),
feature && feature.forEach((/**
* @param {?} fn
* @return {?}
*/
(fn) => fn(def)));
def.directiveDefs = directiveTypes ?
(/**
* @return {?}
*/
() => (typeof directiveTypes === 'function' ? directiveTypes() : directiveTypes)
.map(extractDirectiveDef)) :
null;
def.pipeDefs = pipeTypes ?
(/**
* @return {?}
*/
() => (typeof pipeTypes === 'function' ? pipeTypes() : pipeTypes).map(extractPipeDef)) :
null;
return (/** @type {?} */ (def));
}));
}
/**
* \@codeGenApi
* @param {?} type
* @param {?} directives
* @param {?} pipes
* @return {?}
*/
function ɵɵsetComponentScope(type, directives, pipes) {
/** @type {?} */
const def = ((/** @type {?} */ (type.ɵcmp)));
def.directiveDefs = (/**
* @return {?}
*/
() => directives.map(extractDirectiveDef));
def.pipeDefs = (/**
* @return {?}
*/
() => pipes.map(extractPipeDef));
}
/**
* @param {?} type
* @return {?}
*/
function extractDirectiveDef(type) {
/** @type {?} */
const def = getComponentDef(type) || getDirectiveDef(type);
if (ngDevMode && !def) {
throw new Error(`'${type.name}' is neither 'ComponentType' or 'DirectiveType'.`);
}
return (/** @type {?} */ (def));
}
/**
* @param {?} type
* @return {?}
*/
function extractPipeDef(type) {
/** @type {?} */
const def = getPipeDef(type);
if (ngDevMode && !def) {
throw new Error(`'${type.name}' is not a 'PipeType'.`);
}
return (/** @type {?} */ (def));
}
/** @type {?} */
const autoRegisterModuleById = {};
/**
* \@codeGenApi
* @template T
* @param {?} def
* @return {?}
*/
function ɵɵdefineNgModule(def) {
/** @type {?} */
const res = {
type: def.type,
bootstrap: def.bootstrap || EMPTY_ARRAY,
declarations: def.declarations || EMPTY_ARRAY,
imports: def.imports || EMPTY_ARRAY,
exports: def.exports || EMPTY_ARRAY,
transitiveCompileScopes: null,
schemas: def.schemas || null,
id: def.id || null,
};
if (def.id != null) {
noSideEffects((/**
* @return {?}
*/
() => {
autoRegisterModuleById[(/** @type {?} */ (def.id))] = (/** @type {?} */ ((/** @type {?} */ (def.type))));
}));
}
return (/** @type {?} */ (res));
}
/**
* Adds the module metadata that is necessary to compute the module's transitive scope to an
* existing module definition.
*
* Scope metadata of modules is not used in production builds, so calls to this function can be
* marked pure to tree-shake it from the bundle, allowing for all referenced declarations
* to become eligible for tree-shaking as well.
*
* \@codeGenApi
* @param {?} type
* @param {?} scope
* @return {?}
*/
function ɵɵsetNgModuleScope(type, scope) {
return (/** @type {?} */ (noSideEffects((/**
* @return {?}
*/
() => {
/** @type {?} */
const ngModuleDef = getNgModuleDef(type, true);
ngModuleDef.declarations = scope.declarations || EMPTY_ARRAY;
ngModuleDef.imports = scope.imports || EMPTY_ARRAY;
ngModuleDef.exports = scope.exports || EMPTY_ARRAY;
}))));
}
/**
* Inverts an inputs or outputs lookup such that the keys, which were the
* minified keys, are part of the values, and the values are parsed so that
* the publicName of the property is the new key
*
* e.g. for
*
* ```
* class Comp {
* \@Input()
* propName1: string;
*
* \@Input('publicName2')
* declaredPropName2: number;
* }
* ```
*
* will be serialized as
*
* ```
* {
* propName1: 'propName1',
* declaredPropName2: ['publicName2', 'declaredPropName2'],
* }
* ```
*
* which is than translated by the minifier as:
*
* ```
* {
* minifiedPropName1: 'propName1',
* minifiedPropName2: ['publicName2', 'declaredPropName2'],
* }
* ```
*
* becomes: (public name => minifiedName)
*
* ```
* {
* 'propName1': 'minifiedPropName1',
* 'publicName2': 'minifiedPropName2',
* }
* ```
*
* Optionally the function can take `secondary` which will result in: (public name => declared name)
*
* ```
* {
* 'propName1': 'propName1',
* 'publicName2': 'declaredPropName2',
* }
* ```
*
* @template T
* @param {?=} obj
* @param {?=} secondary
* @return {?}
*/
function invertObject(obj, secondary) {
if (obj == null)
return (/** @type {?} */ (EMPTY_OBJ));
/** @type {?} */
const newLookup = {};
for (const minifiedKey in obj) {
if (obj.hasOwnProperty(minifiedKey)) {
/** @type {?} */
let publicName = (/** @type {?} */ (obj[minifiedKey]));
/** @type {?} */
let declaredName = publicName;
if (Array.isArray(publicName)) {
declaredName = publicName[1];
publicName = publicName[0];
}
newLookup[publicName] = minifiedKey;
if (secondary) {
(secondary[publicName] = (/** @type {?} */ (declaredName)));
}
}
}
return newLookup;
}
/**
* Create a directive definition object.
*
* # Example
* ```ts
* class MyDirective {
* // Generated by Angular Template Compiler
* // [Symbol] syntax will not be supported by TypeScript until v2.7
* static ɵdir = ɵɵdefineDirective({
* ...
* });
* }
* ```
*
* \@codeGenApi
* @type {?}
*/
const ɵɵdefineDirective = (/** @type {?} */ ((/** @type {?} */ (ɵɵdefineComponent))));
/**
* Create a pipe definition object.
*
* # Example
* ```
* class MyPipe implements PipeTransform {
* // Generated by Angular Template Compiler
* static ɵpipe = definePipe({
* ...
* });
* }
* ```
* \@codeGenApi
* @template T
* @param {?} pipeDef Pipe definition generated by the compiler
*
* @return {?}
*/
function ɵɵdefinePipe(pipeDef) {
return (/** @type {?} */ (((/** @type {?} */ ({
type: pipeDef.type,
name: pipeDef.name,
factory: null,
pure: pipeDef.pure !== false,
onDestroy: pipeDef.type.prototype.ngOnDestroy || null
})))));
}
/**
* The following getter methods retrieve the definition form the type. Currently the retrieval
* honors inheritance, but in the future we may change the rule to require that definitions are
* explicit. This would require some sort of migration strategy.
* @template T
* @param {?} type
* @return {?}
*/
function getComponentDef(type) {
return type[NG_COMP_DEF] || null;
}
/**
* @template T
* @param {?} type
* @return {?}
*/
function getDirectiveDef(type) {
return type[NG_DIR_DEF] || null;
}
/**
* @template T
* @param {?} type
* @return {?}
*/
function getPipeDef(type) {
return type[NG_PIPE_DEF] || null;
}
/**
* @template T
* @param {?} type
* @param {?=} throwNotFound
* @return {?}
*/
function getFactoryDef(type, throwNotFound) {
/** @type {?} */
const hasFactoryDef = type.hasOwnProperty(NG_FACTORY_DEF);
if (!hasFactoryDef && throwNotFound === true && ngDevMode) {
throw new Error(`Type ${stringify(type)} does not have 'ɵfac' property.`);
}
return hasFactoryDef ? type[NG_FACTORY_DEF] : null;
}
/**
* @template T
* @param {?} type
* @param {?=} throwNotFound
* @return {?}
*/
function getNgModuleDef(type, throwNotFound) {
/** @type {?} */
const ngModuleDef = type[NG_MOD_DEF] || null;
if (!ngModuleDef && throwNotFound === true) {
throw new Error(`Type ${stringify(type)} does not have 'ɵmod' property.`);
}
return ngModuleDef;
}
/**
* @param {?} type
* @return {?}
*/
function getNgLocaleIdDef(type) {
return ((/** @type {?} */ (type)))[NG_LOC_ID_DEF] || null;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/view.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Below are constants for LView indices to help us look up LView members
// without having to remember the specific indices.
// Uglify will inline these when minifying so there shouldn't be a cost.
/** @type {?} */
const HOST = 0;
/** @type {?} */
const TVIEW = 1;
/** @type {?} */
const FLAGS = 2;
/** @type {?} */
const PARENT = 3;
/** @type {?} */
const NEXT = 4;
/** @type {?} */
const TRANSPLANTED_VIEWS_TO_REFRESH = 5;
/** @type {?} */
const T_HOST = 6;
/** @type {?} */
const CLEANUP = 7;
/** @type {?} */
const CONTEXT = 8;
/** @type {?} */
const INJECTOR$1 = 9;
/** @type {?} */
const RENDERER_FACTORY = 10;
/** @type {?} */
const RENDERER = 11;
/** @type {?} */
const SANITIZER = 12;
/** @type {?} */
const CHILD_HEAD = 13;
/** @type {?} */
const CHILD_TAIL = 14;
/** @type {?} */
const DECLARATION_VIEW = 15;
/** @type {?} */
const DECLARATION_COMPONENT_VIEW = 16;
/** @type {?} */
const DECLARATION_LCONTAINER = 17;
/** @type {?} */
const PREORDER_HOOK_FLAGS = 18;
/** @type {?} */
const QUERIES = 19;
/**
* Size of LView's header. Necessary to adjust for it when setting slots.
* @type {?}
*/
const HEADER_OFFSET = 20;
/**
* @record
*/
function OpaqueViewState() { }
if (false) {}
/**
* `LView` stores all of the information needed to process the instructions as
* they are invoked from the template. Each embedded view and component view has its
* own `LView`. When processing a particular view, we set the `viewData` to that
* `LView`. When that view is done processing, the `viewData` is set back to
* whatever the original `viewData` was before (the parent `LView`).
*
* Keeping separate state for each view facilities view insertion / deletion, so we
* don't have to edit the data array based on which views are present.
* @record
*/
function LView() { }
if (false) {}
/** @enum {number} */
const LViewFlags = {
/** The state of the init phase on the first 2 bits */
InitPhaseStateIncrementer: 1,
InitPhaseStateMask: 3,
/**
* Whether or not the view is in creationMode.
*
* This must be stored in the view rather than using `data` as a marker so that
* we can properly support embedded views. Otherwise, when exiting a child view
* back into the parent view, `data` will be defined and `creationMode` will be
* improperly reported as false.
*/
CreationMode: 4,
/**
* Whether or not this LView instance is on its first processing pass.
*
* An LView instance is considered to be on its "first pass" until it
* has completed one creation mode run and one update mode run. At this
* time, the flag is turned off.
*/
FirstLViewPass: 8,
/** Whether this view has default change detection strategy (checks always) or onPush */
CheckAlways: 16,
/**
* Whether or not manual change detection is turned on for onPush components.
*
* This is a special mode that only marks components dirty in two cases:
* 1) There has been a change to an @Input property
* 2) `markDirty()` has been called manually by the user
*
* Note that in this mode, the firing of events does NOT mark components
* dirty automatically.
*
* Manual mode is turned off by default for backwards compatibility, as events
* automatically mark OnPush components dirty in View Engine.
*
* TODO: Add a public API to ChangeDetectionStrategy to turn this mode on
*/
ManualOnPush: 32,
/** Whether or not this view is currently dirty (needing check) */
Dirty: 64,
/** Whether or not this view is currently attached to change detection tree. */
Attached: 128,
/** Whether or not this view is destroyed. */
Destroyed: 256,
/** Whether or not this view is the root view */
IsRoot: 512,
/**
* Whether this moved LView was needs to be refreshed at the insertion location because the
* declaration was dirty.
*/
RefreshTransplantedView: 1024,
/**
* Index of the current init phase on last 21 bits
*/
IndexWithinInitPhaseIncrementer: 2048,
IndexWithinInitPhaseShift: 11,
IndexWithinInitPhaseReset: 2047,
};
/** @enum {number} */
const InitPhaseState = {
OnInitHooksToBeRun: 0,
AfterContentInitHooksToBeRun: 1,
AfterViewInitHooksToBeRun: 2,
InitPhaseCompleted: 3,
};
/** @enum {number} */
const PreOrderHookFlags = {
/**
The index of the next pre-order hook to be called in the hooks array, on the first 16
bits
*/
IndexOfTheNextPreOrderHookMaskMask: 65535,
/**
* The number of init hooks that have already been called, on the last 16 bits
*/
NumberOfInitHooksCalledIncrementer: 65536,
NumberOfInitHooksCalledShift: 16,
NumberOfInitHooksCalledMask: 4294901760,
};
/**
* Set of instructions used to process host bindings efficiently.
*
* See VIEW_DATA.md for more information.
* @record
*/
function ExpandoInstructions() { }
/** @enum {number} */
const TViewType = {
/**
* Root `TView` is the used to bootstrap components into. It is used in conjunction with
* `LView` which takes an existing DOM node not owned by Angular and wraps it in `TView`/`LView`
* so that other components can be loaded into it.
*/
Root: 0,
/**
* `TView` associated with a Component. This would be the `TView` directly associated with the
* component view (as opposed an `Embedded` `TView` which would be a child of `Component` `TView`)
*/
Component: 1,
/**
* `TView` associated with a template. Such as `*ngIf`, `<ng-template>` etc... A `Component`
* can have zero or more `Embedede` `TView`s.
*/
Embedded: 2,
};
/**
* The static data for an LView (shared between all templates of a
* given type).
*
* Stored on the `ComponentDef.tView`.
* @record
*/
function TView() { }
if (false) {}
/** @enum {number} */
const RootContextFlags = {
Empty: 0,
DetectChanges: 1,
FlushPlayers: 2,
};
/**
* RootContext contains information which is shared for all components which
* were bootstrapped with {\@link renderComponent}.
* @record
*/
function RootContext() { }
if (false) {}
// Note: This hack is necessary so we don't erroneously get a circular dependency
// failure based on types.
/** @type {?} */
const unusedValueExportToPlacateAjd = 1;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/container.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Special location which allows easy identification of type. If we have an array which was
* retrieved from the `LView` and that array has `true` at `TYPE` location, we know it is
* `LContainer`.
* @type {?}
*/
const TYPE = 1;
/**
* Flag to signify that this `LContainer` may have transplanted views which need to be change
* detected. (see: `LView[DECLARATION_COMPONENT_VIEW])`.
*
* This flag, once set, is never unset for the `LContainer`. This means that when unset we can skip
* a lot of work in `refreshEmbeddedViews`. But when set we still need to verify
* that the `MOVED_VIEWS` are transplanted and on-push.
* @type {?}
*/
const HAS_TRANSPLANTED_VIEWS = 2;
// PARENT, NEXT, TRANSPLANTED_VIEWS_TO_REFRESH are indices 3, 4, and 5
// As we already have these constants in LView, we don't need to re-create them.
// T_HOST is index 6
// We already have this constants in LView, we don't need to re-create it.
/** @type {?} */
const NATIVE = 7;
/** @type {?} */
const VIEW_REFS = 8;
/** @type {?} */
const MOVED_VIEWS = 9;
/**
* Size of LContainer's header. Represents the index after which all views in the
* container will be inserted. We need to keep a record of current views so we know
* which views are already in the DOM (and don't need to be re-added) and so we can
* remove views from the DOM when they are no longer required.
* @type {?}
*/
const CONTAINER_HEADER_OFFSET = 10;
/**
* The state associated with a container.
*
* This is an array so that its structure is closer to LView. This helps
* when traversing the view tree (which is a mix of containers and component
* views), so we can jump to viewOrContainer[NEXT] in the same way regardless
* of type.
* @record
*/
function LContainer() { }
if (false) {}
// Note: This hack is necessary so we don't erroneously get a circular dependency
// failure based on types.
/** @type {?} */
const unusedValueExportToPlacateAjd$1 = 1;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/type_checks.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* True if `value` is `LView`.
* @param {?} value wrapped value of `RNode`, `LView`, `LContainer`
* @return {?}
*/
function isLView(value) {
return Array.isArray(value) && typeof value[TYPE] === 'object';
}
/**
* True if `value` is `LContainer`.
* @param {?} value wrapped value of `RNode`, `LView`, `LContainer`
* @return {?}
*/
function isLContainer(value) {
return Array.isArray(value) && value[TYPE] === true;
}
/**
* @param {?} tNode
* @return {?}
*/
function isContentQueryHost(tNode) {
return (tNode.flags & 8 /* hasContentQuery */) !== 0;
}
/**
* @param {?} tNode
* @return {?}
*/
function isComponentHost(tNode) {
return (tNode.flags & 2 /* isComponentHost */) === 2 /* isComponentHost */;
}
/**
* @param {?} tNode
* @return {?}
*/
function isDirectiveHost(tNode) {
return (tNode.flags & 1 /* isDirectiveHost */) === 1 /* isDirectiveHost */;
}
/**
* @template T
* @param {?} def
* @return {?}
*/
function isComponentDef(def) {
return ((/** @type {?} */ (def))).template !== null;
}
/**
* @param {?} target
* @return {?}
*/
function isRootView(target) {
return (target[FLAGS] & 512 /* IsRoot */) !== 0;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/assert.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// [Assert functions do not constraint type when they are guarded by a truthy
// expression.](https://github.com/microsoft/TypeScript/issues/37295)
/**
* @param {?} tNode
* @param {?} lView
* @return {?}
*/
function assertTNodeForLView(tNode, lView) {
tNode.hasOwnProperty('tView_') &&
assertEqual(((/** @type {?} */ ((/** @type {?} */ (tNode))))).tView_, lView[TVIEW], 'This TNode does not belong to this LView.');
}
/**
* @param {?} actual
* @param {?=} msg
* @return {?}
*/
function assertComponentType(actual, msg = 'Type passed in is not ComponentType, it does not have \'ɵcmp\' property.') {
if (!getComponentDef(actual)) {
throwError(msg);
}
}
/**
* @param {?} actual
* @param {?=} msg
* @return {?}
*/
function assertNgModuleType(actual, msg = 'Type passed in is not NgModuleType, it does not have \'ɵmod\' property.') {
if (!getNgModuleDef(actual)) {
throwError(msg);
}
}
/**
* @param {?} isParent
* @return {?}
*/
function assertPreviousIsParent(isParent) {
assertEqual(isParent, true, 'previousOrParentTNode should be a parent');
}
/**
* @param {?} tNode
* @return {?}
*/
function assertHasParent(tNode) {
assertDefined(tNode, 'previousOrParentTNode should exist!');
assertDefined((/** @type {?} */ (tNode)).parent, 'previousOrParentTNode should have a parent');
}
/**
* @param {?} lView
* @param {?} index
* @param {?=} arr
* @return {?}
*/
function assertDataNext(lView, index, arr) {
if (arr == null)
arr = lView;
assertEqual(arr.length, index, `index ${index} expected to be at the end of arr (length ${arr.length})`);
}
/**
* @param {?} value
* @return {?}
*/
function assertLContainer(value) {
assertDefined(value, 'LContainer must be defined');
assertEqual(isLContainer(value), true, 'Expecting LContainer');
}
/**
* @param {?} value
* @return {?}
*/
function assertLViewOrUndefined(value) {
value && assertEqual(isLView(value), true, 'Expecting LView or undefined or null');
}
/**
* @param {?} value
* @return {?}
*/
function assertLView(value) {
assertDefined(value, 'LView must be defined');
assertEqual(isLView(value), true, 'Expecting LView');
}
/**
* @param {?} tView
* @param {?=} errMessage
* @return {?}
*/
function assertFirstCreatePass(tView, errMessage) {
assertEqual(tView.firstCreatePass, true, errMessage || 'Should only be called in first create pass.');
}
/**
* @param {?} tView
* @param {?=} errMessage
* @return {?}
*/
function assertFirstUpdatePass(tView, errMessage) {
assertEqual(tView.firstUpdatePass, true, errMessage || 'Should only be called in first update pass.');
}
/**
* This is a basic sanity check that an object is probably a directive def. DirectiveDef is
* an interface, so we can't do a direct instanceof check.
* @template T
* @param {?} obj
* @return {?}
*/
function assertDirectiveDef(obj) {
if (obj.type === undefined || obj.selectors == undefined || obj.inputs === undefined) {
throwError(`Expected a DirectiveDef/ComponentDef and this object does not seem to have the expected shape.`);
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/namespaces.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @type {?} */
const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
/** @type {?} */
const MATH_ML_NAMESPACE = 'http://www.w3.org/1998/MathML/';
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/context.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This property will be monkey-patched on elements, components and directives
* @type {?}
*/
const MONKEY_PATCH_KEY_NAME = '__ngContext__';
/**
* The internal view context which is specific to a given DOM element, directive or
* component instance. Each value in here (besides the LView and element node details)
* can be present, null or undefined. If undefined then it implies the value has not been
* looked up yet, otherwise, if null, then a lookup was executed and nothing was found.
*
* Each value will get filled when the respective value is examined within the getContext
* function. The component, element and each directive instance will share the same instance
* of the context.
* @record
*/
function LContext() { }
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/document.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Most of the use of `document` in Angular is from within the DI system so it is possible to simply
* inject the `DOCUMENT` token and are done.
*
* Ivy is special because it does not rely upon the DI and must get hold of the document some other
* way.
*
* The solution is to define `getDocument()` and `setDocument()` top-level functions for ivy.
* Wherever ivy needs the global document, it calls `getDocument()` instead.
*
* When running ivy outside of a browser environment, it is necessary to call `setDocument()` to
* tell ivy what the global `document` is.
*
* Angular does this for us in each of the standard platforms (`Browser`, `Server`, and `WebWorker`)
* by calling `setDocument()` when providing the `DOCUMENT` token.
* @type {?}
*/
let DOCUMENT = undefined;
/**
* Tell ivy what the `document` is for this platform.
*
* It is only necessary to call this if the current platform is not a browser.
*
* @param {?} document The object representing the global `document` in this environment.
* @return {?}
*/
function setDocument(document) {
DOCUMENT = document;
}
/**
* Access the object that represents the `document` for this platform.
*
* Ivy calls this whenever it needs to access the `document` object.
* For example to create the renderer or to do sanitization.
* @return {?}
*/
function getDocument() {
if (DOCUMENT !== undefined) {
return DOCUMENT;
}
else if (typeof document !== 'undefined') {
return document;
}
// No "document" can be found. This should only happen if we are running ivy outside Angular and
// the current platform is not a browser. Since this is not a supported scenario at the moment
// this should not happen in Angular apps.
// Once we support running ivy outside of Angular we will need to publish `setDocument()` as a
// public API. Meanwhile we just return `undefined` and let the application fail.
return (/** @type {?} */ (undefined));
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/renderer.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @enum {number} */
const RendererStyleFlags3 = {
Important: 1,
DashCase: 2,
};
RendererStyleFlags3[RendererStyleFlags3.Important] = 'Important';
RendererStyleFlags3[RendererStyleFlags3.DashCase] = 'DashCase';
/**
* Object Oriented style of API needed to create elements and text nodes.
*
* This is the native browser API style, e.g. operations are methods on individual objects
* like HTMLElement. With this style, no additional code is needed as a facade
* (reducing payload size).
*
* @record
*/
function ObjectOrientedRenderer3() { }
if (false) {}
/**
* Returns whether the `renderer` is a `ProceduralRenderer3`
* @param {?} renderer
* @return {?}
*/
function isProceduralRenderer(renderer) {
return !!(((/** @type {?} */ (renderer))).listen);
}
/**
* Procedural style of API needed to create elements and text nodes.
*
* In non-native browser environments (e.g. platforms such as web-workers), this is the
* facade that enables element manipulation. This also facilitates backwards compatibility
* with Renderer2.
* @record
*/
function ProceduralRenderer3() { }
if (false) {}
/**
* @record
*/
function RendererFactory3() { }
if (false) {}
const ɵ0$2 = /**
* @param {?} hostElement
* @param {?} rendererType
* @return {?}
*/
(hostElement, rendererType) => {
return getDocument();
};
/** @type {?} */
const domRendererFactory3 = {
createRenderer: (ɵ0$2)
};
/**
* Subset of API needed for appending elements and text nodes.
* @record
*/
function RNode() { }
if (false) {}
/**
* Subset of API needed for writing attributes, properties, and setting up
* listeners on Element.
* @record
*/
function RElement() { }
if (false) {}
/**
* @record
*/
function RCssStyleDeclaration() { }
if (false) {}
/**
* @record
*/
function RDomTokenList() { }
if (false) {}
/**
* @record
*/
function RText() { }
if (false) {}
/**
* @record
*/
function RComment() { }
if (false) {}
// Note: This hack is necessary so we don't erroneously get a circular dependency
// failure based on types.
/** @type {?} */
const unusedValueExportToPlacateAjd$2 = 1;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/util/view_utils.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* For efficiency reasons we often put several different data types (`RNode`, `LView`, `LContainer`)
* in same location in `LView`. This is because we don't want to pre-allocate space for it
* because the storage is sparse. This file contains utilities for dealing with such data types.
*
* How do we know what is stored at a given location in `LView`.
* - `Array.isArray(value) === false` => `RNode` (The normal storage value)
* - `Array.isArray(value) === true` => then the `value[0]` represents the wrapped value.
* - `typeof value[TYPE] === 'object'` => `LView`
* - This happens when we have a component at a given location
* - `typeof value[TYPE] === true` => `LContainer`
* - This happens when we have `LContainer` binding at a given location.
*
*
* NOTE: it is assumed that `Array.isArray` and `typeof` operations are very efficient.
*/
/**
* Returns `RNode`.
* @param {?} value wrapped value of `RNode`, `LView`, `LContainer`
* @return {?}
*/
function unwrapRNode(value) {
while (Array.isArray(value)) {
value = (/** @type {?} */ (value[HOST]));
}
return (/** @type {?} */ (value));
}
/**
* Returns `LView` or `null` if not found.
* @param {?} value wrapped value of `RNode`, `LView`, `LContainer`
* @return {?}
*/
function unwrapLView(value) {
while (Array.isArray(value)) {
// This check is same as `isLView()` but we don't call at as we don't want to call
// `Array.isArray()` twice and give JITer more work for inlining.
if (typeof value[TYPE] === 'object')
return (/** @type {?} */ (value));
value = (/** @type {?} */ (value[HOST]));
}
return null;
}
/**
* Returns `LContainer` or `null` if not found.
* @param {?} value wrapped value of `RNode`, `LView`, `LContainer`
* @return {?}
*/
function unwrapLContainer(value) {
while (Array.isArray(value)) {
// This check is same as `isLContainer()` but we don't call at as we don't want to call
// `Array.isArray()` twice and give JITer more work for inlining.
if (value[TYPE] === true)
return (/** @type {?} */ (value));
value = (/** @type {?} */ (value[HOST]));
}
return null;
}
/**
* Retrieves an element value from the provided `viewData`, by unwrapping
* from any containers, component views, or style contexts.
* @param {?} index
* @param {?} lView
* @return {?}
*/
function getNativeByIndex(index, lView) {
return unwrapRNode(lView[index + HEADER_OFFSET]);
}
/**
* Retrieve an `RNode` for a given `TNode` and `LView`.
*
* This function guarantees in dev mode to retrieve a non-null `RNode`.
*
* @param {?} tNode
* @param {?} lView
* @return {?}
*/
function getNativeByTNode(tNode, lView) {
ngDevMode && assertTNodeForLView(tNode, lView);
ngDevMode && assertDataInRange(lView, tNode.index);
/** @type {?} */
const node = unwrapRNode(lView[tNode.index]);
ngDevMode && !isProceduralRenderer(lView[RENDERER]) && assertDomNode(node);
return node;
}
/**
* Retrieve an `RNode` or `null` for a given `TNode` and `LView`.
*
* Some `TNode`s don't have associated `RNode`s. For example `Projection`
*
* @param {?} tNode
* @param {?} lView
* @return {?}
*/
function getNativeByTNodeOrNull(tNode, lView) {
/** @type {?} */
const index = tNode.index;
if (index !== -1) {
ngDevMode && assertTNodeForLView(tNode, lView);
/** @type {?} */
const node = unwrapRNode(lView[index]);
ngDevMode && node !== null && !isProceduralRenderer(lView[RENDERER]) && assertDomNode(node);
return node;
}
return null;
}
/**
* @param {?} tView
* @param {?} index
* @return {?}
*/
function getTNode(tView, index) {
ngDevMode && assertGreaterThan(index, -1, 'wrong index for TNode');
ngDevMode && assertLessThan(index, tView.data.length, 'wrong index for TNode');
return (/** @type {?} */ (tView.data[index + HEADER_OFFSET]));
}
/**
* Retrieves a value from any `LView` or `TData`.
* @template T
* @param {?} view
* @param {?} index
* @return {?}
*/
function load(view, index) {
ngDevMode && assertDataInRange(view, index + HEADER_OFFSET);
return view[index + HEADER_OFFSET];
}
/**
* @param {?} nodeIndex
* @param {?} hostView
* @return {?}
*/
function getComponentLViewByIndex(nodeIndex, hostView) {
// Could be an LView or an LContainer. If LContainer, unwrap to find LView.
ngDevMode && assertDataInRange(hostView, nodeIndex);
/** @type {?} */
const slotValue = hostView[nodeIndex];
/** @type {?} */
const lView = isLView(slotValue) ? slotValue : slotValue[HOST];
return lView;
}
/**
* Returns the monkey-patch value data present on the target (which could be
* a component, directive or a DOM node).
* @param {?} target
* @return {?}
*/
function readPatchedData(target) {
ngDevMode && assertDefined(target, 'Target expected');
return target[MONKEY_PATCH_KEY_NAME] || null;
}
/**
* @param {?} target
* @return {?}
*/
function readPatchedLView(target) {
/** @type {?} */
const value = readPatchedData(target);
if (value) {
return Array.isArray(value) ? value : ((/** @type {?} */ (value))).lView;
}
return null;
}
/**
* Checks whether a given view is in creation mode
* @param {?} view
* @return {?}
*/
function isCreationMode(view) {
return (view[FLAGS] & 4 /* CreationMode */) === 4 /* CreationMode */;
}
/**
* Returns a boolean for whether the view is attached to the change detection tree.
*
* Note: This determines whether a view should be checked, not whether it's inserted
* into a container. For that, you'll want `viewAttachedToContainer` below.
* @param {?} view
* @return {?}
*/
function viewAttachedToChangeDetector(view) {
return (view[FLAGS] & 128 /* Attached */) === 128 /* Attached */;
}
/**
* Returns a boolean for whether the view is attached to a container.
* @param {?} view
* @return {?}
*/
function viewAttachedToContainer(view) {
return isLContainer(view[PARENT]);
}
/**
* Returns a constant from `TConstants` instance.
* @template T
* @param {?} consts
* @param {?} index
* @return {?}
*/
function getConstant(consts, index) {
return consts === null || index == null ? null : (/** @type {?} */ ((/** @type {?} */ (consts[index]))));
}
/**
* Resets the pre-order hook flags of the view.
* @param {?} lView the LView on which the flags are reset
* @return {?}
*/
function resetPreOrderHookFlags(lView) {
lView[PREORDER_HOOK_FLAGS] = 0;
}
/**
* Updates the `TRANSPLANTED_VIEWS_TO_REFRESH` counter on the `LContainer` as well as the parents
* whose
* 1. counter goes from 0 to 1, indicating that there is a new child that has a view to refresh
* or
* 2. counter goes from 1 to 0, indicating there are no more descendant views to refresh
* @param {?} lContainer
* @param {?} amount
* @return {?}
*/
function updateTransplantedViewCount(lContainer, amount) {
lContainer[TRANSPLANTED_VIEWS_TO_REFRESH] += amount;
/** @type {?} */
let viewOrContainer = lContainer;
/** @type {?} */
let parent = lContainer[PARENT];
while (parent !== null &&
((amount === 1 && viewOrContainer[TRANSPLANTED_VIEWS_TO_REFRESH] === 1) ||
(amount === -1 && viewOrContainer[TRANSPLANTED_VIEWS_TO_REFRESH] === 0))) {
parent[TRANSPLANTED_VIEWS_TO_REFRESH] += amount;
viewOrContainer = parent;
parent = parent[PARENT];
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/state.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
*
* @record
*/
function LFrame() { }
if (false) {}
/**
* All implicit instruction state is stored here.
*
* It is useful to have a single object where all of the state is stored as a mental model
* (rather it being spread across many different variables.)
*
* PERF NOTE: Turns out that writing to a true global variable is slower than
* having an intermediate object with properties.
* @record
*/
function InstructionState() { }
if (false) {}
/** @type {?} */
const instructionState = {
lFrame: createLFrame(null),
bindingsEnabled: true,
checkNoChangesMode: false,
};
/**
* @return {?}
*/
function getElementDepthCount() {
return instructionState.lFrame.elementDepthCount;
}
/**
* @return {?}
*/
function increaseElementDepthCount() {
instructionState.lFrame.elementDepthCount++;
}
/**
* @return {?}
*/
function decreaseElementDepthCount() {
instructionState.lFrame.elementDepthCount--;
}
/**
* @return {?}
*/
function getBindingsEnabled() {
return instructionState.bindingsEnabled;
}
/**
* Enables directive matching on elements.
*
* * Example:
* ```
* <my-comp my-directive>
* Should match component / directive.
* </my-comp>
* <div ngNonBindable>
* <!-- ɵɵdisableBindings() -->
* <my-comp my-directive>
* Should not match component / directive because we are in ngNonBindable.
* </my-comp>
* <!-- ɵɵenableBindings() -->
* </div>
* ```
*
* \@codeGenApi
* @return {?}
*/
function ɵɵenableBindings() {
instructionState.bindingsEnabled = true;
}
/**
* Disables directive matching on element.
*
* * Example:
* ```
* <my-comp my-directive>
* Should match component / directive.
* </my-comp>
* <div ngNonBindable>
* <!-- ɵɵdisableBindings() -->
* <my-comp my-directive>
* Should not match component / directive because we are in ngNonBindable.
* </my-comp>
* <!-- ɵɵenableBindings() -->
* </div>
* ```
*
* \@codeGenApi
* @return {?}
*/
function ɵɵdisableBindings() {
instructionState.bindingsEnabled = false;
}
/**
* Return the current `LView`.
* @return {?}
*/
function getLView() {
return instructionState.lFrame.lView;
}
/**
* Return the current `TView`.
* @return {?}
*/
function getTView() {
return instructionState.lFrame.tView;
}
/**
* Restores `contextViewData` to the given OpaqueViewState instance.
*
* Used in conjunction with the getCurrentView() instruction to save a snapshot
* of the current view and restore it when listeners are invoked. This allows
* walking the declaration view tree in listeners to get vars from parent views.
*
* \@codeGenApi
* @param {?} viewToRestore The OpaqueViewState instance to restore.
*
* @return {?}
*/
function ɵɵrestoreView(viewToRestore) {
instructionState.lFrame.contextLView = (/** @type {?} */ ((/** @type {?} */ (viewToRestore))));
}
/**
* @return {?}
*/
function getPreviousOrParentTNode() {
return instructionState.lFrame.previousOrParentTNode;
}
/**
* @param {?} tNode
* @param {?} isParent
* @return {?}
*/
function setPreviousOrParentTNode(tNode, isParent) {
instructionState.lFrame.previousOrParentTNode = tNode;
instructionState.lFrame.isParent = isParent;
}
/**
* @return {?}
*/
function getIsParent() {
return instructionState.lFrame.isParent;
}
/**
* @return {?}
*/
function setIsNotParent() {
instructionState.lFrame.isParent = false;
}
/**
* @return {?}
*/
function setIsParent() {
instructionState.lFrame.isParent = true;
}
/**
* @return {?}
*/
function getContextLView() {
return instructionState.lFrame.contextLView;
}
/**
* @return {?}
*/
function getCheckNoChangesMode() {
// TODO(misko): remove this from the LView since it is ngDevMode=true mode only.
return instructionState.checkNoChangesMode;
}
/**
* @param {?} mode
* @return {?}
*/
function setCheckNoChangesMode(mode) {
instructionState.checkNoChangesMode = mode;
}
// top level variables should not be exported for performance reasons (PERF_NOTES.md)
/**
* @return {?}
*/
function getBindingRoot() {
/** @type {?} */
const lFrame = instructionState.lFrame;
/** @type {?} */
let index = lFrame.bindingRootIndex;
if (index === -1) {
index = lFrame.bindingRootIndex = lFrame.tView.bindingStartIndex;
}
return index;
}
/**
* @return {?}
*/
function getBindingIndex() {
return instructionState.lFrame.bindingIndex;
}
/**
* @param {?} value
* @return {?}
*/
function setBindingIndex(value) {
return instructionState.lFrame.bindingIndex = value;
}
/**
* @return {?}
*/
function nextBindingIndex() {
return instructionState.lFrame.bindingIndex++;
}
/**
* @param {?} count
* @return {?}
*/
function incrementBindingIndex(count) {
/** @type {?} */
const lFrame = instructionState.lFrame;
/** @type {?} */
const index = lFrame.bindingIndex;
lFrame.bindingIndex = lFrame.bindingIndex + count;
return index;
}
/**
* Set a new binding root index so that host template functions can execute.
*
* Bindings inside the host template are 0 index. But because we don't know ahead of time
* how many host bindings we have we can't pre-compute them. For this reason they are all
* 0 index and we just shift the root so that they match next available location in the LView.
*
* @param {?} bindingRootIndex Root index for `hostBindings`
* @param {?} currentDirectiveIndex `TData[currentDirectiveIndex]` will point to the current directive
* whose `hostBindings` are being processed.
* @return {?}
*/
function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {
/** @type {?} */
const lFrame = instructionState.lFrame;
lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;
setCurrentDirectiveIndex(currentDirectiveIndex);
}
/**
* When host binding is executing this points to the directive index.
* `TView.data[getCurrentDirectiveIndex()]` is `DirectiveDef`
* `LView[getCurrentDirectiveIndex()]` is directive instance.
* @return {?}
*/
function getCurrentDirectiveIndex() {
return instructionState.lFrame.currentDirectiveIndex;
}
/**
* Sets an index of a directive whose `hostBindings` are being processed.
*
* @param {?} currentDirectiveIndex `TData` index where current directive instance can be found.
* @return {?}
*/
function setCurrentDirectiveIndex(currentDirectiveIndex) {
instructionState.lFrame.currentDirectiveIndex = currentDirectiveIndex;
}
/**
* Retrieve the current `DirectiveDef` which is active when `hostBindings` instruction is being
* executed.
*
* @param {?} tData Current `TData` where the `DirectiveDef` will be looked up at.
* @return {?}
*/
function getCurrentDirectiveDef(tData) {
/** @type {?} */
const currentDirectiveIndex = instructionState.lFrame.currentDirectiveIndex;
return currentDirectiveIndex === -1 ? null : (/** @type {?} */ (tData[currentDirectiveIndex]));
}
/**
* @return {?}
*/
function getCurrentQueryIndex() {
return instructionState.lFrame.currentQueryIndex;
}
/**
* @param {?} value
* @return {?}
*/
function setCurrentQueryIndex(value) {
instructionState.lFrame.currentQueryIndex = value;
}
/**
* This is a light weight version of the `enterView` which is needed by the DI system.
* @param {?} newView
* @param {?} tNode
* @return {?}
*/
function enterDI(newView, tNode) {
ngDevMode && assertLViewOrUndefined(newView);
/** @type {?} */
const newLFrame = allocLFrame();
instructionState.lFrame = newLFrame;
newLFrame.previousOrParentTNode = (/** @type {?} */ (tNode));
newLFrame.lView = newView;
}
/**
* Swap the current lView with a new lView.
*
* For performance reasons we store the lView in the top level of the module.
* This way we minimize the number of properties to read. Whenever a new view
* is entered we have to store the lView for later, and when the view is
* exited the state has to be restored
*
* @param {?} newView New lView to become active
* @param {?} tNode Element to which the View is a child of
* @return {?} the previously active lView;
*/
function enterView(newView, tNode) {
ngDevMode && assertLViewOrUndefined(newView);
/** @type {?} */
const newLFrame = allocLFrame();
if (ngDevMode) {
assertEqual(newLFrame.isParent, true, 'Expected clean LFrame');
assertEqual(newLFrame.lView, null, 'Expected clean LFrame');
assertEqual(newLFrame.tView, null, 'Expected clean LFrame');
assertEqual(newLFrame.selectedIndex, 0, 'Expected clean LFrame');
assertEqual(newLFrame.elementDepthCount, 0, 'Expected clean LFrame');
assertEqual(newLFrame.currentDirectiveIndex, -1, 'Expected clean LFrame');
assertEqual(newLFrame.currentNamespace, null, 'Expected clean LFrame');
assertEqual(newLFrame.currentSanitizer, null, 'Expected clean LFrame');
assertEqual(newLFrame.bindingRootIndex, -1, 'Expected clean LFrame');
assertEqual(newLFrame.currentQueryIndex, 0, 'Expected clean LFrame');
}
/** @type {?} */
const tView = newView[TVIEW];
instructionState.lFrame = newLFrame;
newLFrame.previousOrParentTNode = (/** @type {?} */ (tNode));
newLFrame.lView = newView;
newLFrame.tView = tView;
newLFrame.contextLView = (/** @type {?} */ (newView));
newLFrame.bindingIndex = tView.bindingStartIndex;
}
/**
* Allocates next free LFrame. This function tries to reuse the `LFrame`s to lower memory pressure.
* @return {?}
*/
function allocLFrame() {
/** @type {?} */
const currentLFrame = instructionState.lFrame;
/** @type {?} */
const childLFrame = currentLFrame === null ? null : currentLFrame.child;
/** @type {?} */
const newLFrame = childLFrame === null ? createLFrame(currentLFrame) : childLFrame;
return newLFrame;
}
/**
* @param {?} parent
* @return {?}
*/
function createLFrame(parent) {
/** @type {?} */
const lFrame = {
previousOrParentTNode: (/** @type {?} */ (null)),
//
isParent: true,
//
lView: (/** @type {?} */ (null)),
//
tView: (/** @type {?} */ (null)),
//
selectedIndex: 0,
//
contextLView: (/** @type {?} */ (null)),
//
elementDepthCount: 0,
//
currentNamespace: null,
//
currentSanitizer: null,
//
currentDirectiveIndex: -1,
//
bindingRootIndex: -1,
//
bindingIndex: -1,
//
currentQueryIndex: 0,
//
parent: (/** @type {?} */ (parent)),
//
child: null,
};
parent !== null && (parent.child = lFrame); // link the new LFrame for reuse.
return lFrame;
}
/**
* A lightweight version of leave which is used with DI.
*
* This function only resets `previousOrParentTNode` and `LView` as those are the only properties
* used with DI (`enterDI()`).
*
* NOTE: This function is reexported as `leaveDI`. However `leaveDI` has return type of `void` where
* as `leaveViewLight` has `LFrame`. This is so that `leaveViewLight` can be used in `leaveView`.
* @return {?}
*/
function leaveViewLight() {
/** @type {?} */
const oldLFrame = instructionState.lFrame;
instructionState.lFrame = oldLFrame.parent;
oldLFrame.previousOrParentTNode = (/** @type {?} */ (null));
oldLFrame.lView = (/** @type {?} */ (null));
return oldLFrame;
}
/**
* This is a lightweight version of the `leaveView` which is needed by the DI system.
*
* NOTE: this function is an alias so that we can change the type of the function to have `void`
* return type.
* @type {?}
*/
const leaveDI = leaveViewLight;
/**
* Leave the current `LView`
*
* This pops the `LFrame` with the associated `LView` from the stack.
*
* IMPORTANT: We must zero out the `LFrame` values here otherwise they will be retained. This is
* because for performance reasons we don't release `LFrame` but rather keep it for next use.
* @return {?}
*/
function leaveView() {
/** @type {?} */
const oldLFrame = leaveViewLight();
oldLFrame.isParent = true;
oldLFrame.tView = (/** @type {?} */ (null));
oldLFrame.selectedIndex = 0;
oldLFrame.contextLView = (/** @type {?} */ (null));
oldLFrame.elementDepthCount = 0;
oldLFrame.currentDirectiveIndex = -1;
oldLFrame.currentNamespace = null;
oldLFrame.currentSanitizer = null;
oldLFrame.bindingRootIndex = -1;
oldLFrame.bindingIndex = -1;
oldLFrame.currentQueryIndex = 0;
}
/**
* @template T
* @param {?} level
* @return {?}
*/
function nextContextImpl(level) {
/** @type {?} */
const contextLView = instructionState.lFrame.contextLView =
walkUpViews(level, (/** @type {?} */ (instructionState.lFrame.contextLView)));
return (/** @type {?} */ (contextLView[CONTEXT]));
}
/**
* @param {?} nestingLevel
* @param {?} currentView
* @return {?}
*/
function walkUpViews(nestingLevel, currentView) {
while (nestingLevel > 0) {
ngDevMode &&
assertDefined(currentView[DECLARATION_VIEW], 'Declaration view should be defined if nesting level is greater than 0.');
currentView = (/** @type {?} */ (currentView[DECLARATION_VIEW]));
nestingLevel--;
}
return currentView;
}
/**
* Gets the currently selected element index.
*
* Used with {\@link property} instruction (and more in the future) to identify the index in the
* current `LView` to act on.
* @return {?}
*/
function getSelectedIndex() {
return instructionState.lFrame.selectedIndex;
}
/**
* Sets the most recent index passed to {\@link select}
*
* Used with {\@link property} instruction (and more in the future) to identify the index in the
* current `LView` to act on.
*
* (Note that if an "exit function" was set earlier (via `setElementExitFn()`) then that will be
* run if and when the provided `index` value is different from the current selected index value.)
* @param {?} index
* @return {?}
*/
function setSelectedIndex(index) {
instructionState.lFrame.selectedIndex = index;
}
/**
* Gets the `tNode` that represents currently selected element.
* @return {?}
*/
function getSelectedTNode() {
/** @type {?} */
const lFrame = instructionState.lFrame;
return getTNode(lFrame.tView, lFrame.selectedIndex);
}
/**
* Sets the namespace used to create elements to `'http://www.w3.org/2000/svg'` in global state.
*
* \@codeGenApi
* @return {?}
*/
function ɵɵnamespaceSVG() {
instructionState.lFrame.currentNamespace = SVG_NAMESPACE;
}
/**
* Sets the namespace used to create elements to `'http://www.w3.org/1998/MathML/'` in global state.
*
* \@codeGenApi
* @return {?}
*/
function ɵɵnamespaceMathML() {
instructionState.lFrame.currentNamespace = MATH_ML_NAMESPACE;
}
/**
* Sets the namespace used to create elements to `null`, which forces element creation to use
* `createElement` rather than `createElementNS`.
*
* \@codeGenApi
* @return {?}
*/
function ɵɵnamespaceHTML() {
namespaceHTMLInternal();
}
/**
* Sets the namespace used to create elements to `null`, which forces element creation to use
* `createElement` rather than `createElementNS`.
* @return {?}
*/
function namespaceHTMLInternal() {
instructionState.lFrame.currentNamespace = null;
}
/**
* @return {?}
*/
function getNamespace() {
return instructionState.lFrame.currentNamespace;
}
/**
* @param {?} sanitizer
* @return {?}
*/
function setCurrentStyleSanitizer(sanitizer) {
instructionState.lFrame.currentSanitizer = sanitizer;
}
/**
* @return {?}
*/
function resetCurrentStyleSanitizer() {
setCurrentStyleSanitizer(null);
}
/**
* @return {?}
*/
function getCurrentStyleSanitizer() {
// TODO(misko): This should throw when there is no LView, but it turns out we can get here from
// `NodeStyleDebug` hence we return `null`. This should be fixed
/** @type {?} */
const lFrame = instructionState.lFrame;
return lFrame === null ? null : lFrame.currentSanitizer;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/hooks.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Adds all directive lifecycle hooks from the given `DirectiveDef` to the given `TView`.
*
* Must be run *only* on the first template pass.
*
* Sets up the pre-order hooks on the provided `tView`,
* see {\@link HookData} for details about the data structure.
*
* @param {?} directiveIndex The index of the directive in LView
* @param {?} directiveDef The definition containing the hooks to setup in tView
* @param {?} tView The current TView
* @return {?}
*/
function registerPreOrderHooks(directiveIndex, directiveDef, tView) {
ngDevMode && assertFirstCreatePass(tView);
const { onChanges, onInit, doCheck } = directiveDef;
if (onChanges) {
(tView.preOrderHooks || (tView.preOrderHooks = [])).push(directiveIndex, onChanges);
(tView.preOrderCheckHooks || (tView.preOrderCheckHooks = [])).push(directiveIndex, onChanges);
}
if (onInit) {
(tView.preOrderHooks || (tView.preOrderHooks = [])).push(-directiveIndex, onInit);
}
if (doCheck) {
(tView.preOrderHooks || (tView.preOrderHooks = [])).push(directiveIndex, doCheck);
(tView.preOrderCheckHooks || (tView.preOrderCheckHooks = [])).push(directiveIndex, doCheck);
}
}
/**
*
* Loops through the directives on the provided `tNode` and queues hooks to be
* run that are not initialization hooks.
*
* Should be executed during `elementEnd()` and similar to
* preserve hook execution order. Content, view, and destroy hooks for projected
* components and directives must be called *before* their hosts.
*
* Sets up the content, view, and destroy hooks on the provided `tView`,
* see {\@link HookData} for details about the data structure.
*
* NOTE: This does not set up `onChanges`, `onInit` or `doCheck`, those are set up
* separately at `elementStart`.
*
* @param {?} tView The current TView
* @param {?} tNode The TNode whose directives are to be searched for hooks to queue
* @return {?}
*/
function registerPostOrderHooks(tView, tNode) {
ngDevMode && assertFirstCreatePass(tView);
// It's necessary to loop through the directives at elementEnd() (rather than processing in
// directiveCreate) so we can preserve the current hook order. Content, view, and destroy
// hooks for projected components and directives must be called *before* their hosts.
for (let i = tNode.directiveStart, end = tNode.directiveEnd; i < end; i++) {
/** @type {?} */
const directiveDef = (/** @type {?} */ (tView.data[i]));
if (directiveDef.afterContentInit) {
(tView.contentHooks || (tView.contentHooks = [])).push(-i, directiveDef.afterContentInit);
}
if (directiveDef.afterContentChecked) {
(tView.contentHooks || (tView.contentHooks = [])).push(i, directiveDef.afterContentChecked);
(tView.contentCheckHooks || (tView.contentCheckHooks = []))
.push(i, directiveDef.afterContentChecked);
}
if (directiveDef.afterViewInit) {
(tView.viewHooks || (tView.viewHooks = [])).push(-i, directiveDef.afterViewInit);
}
if (directiveDef.afterViewChecked) {
(tView.viewHooks || (tView.viewHooks = [])).push(i, directiveDef.afterViewChecked);
(tView.viewCheckHooks || (tView.viewCheckHooks = [])).push(i, directiveDef.afterViewChecked);
}
if (directiveDef.onDestroy != null) {
(tView.destroyHooks || (tView.destroyHooks = [])).push(i, directiveDef.onDestroy);
}
}
}
/**
* Executing hooks requires complex logic as we need to deal with 2 constraints.
*
* 1. Init hooks (ngOnInit, ngAfterContentInit, ngAfterViewInit) must all be executed once and only
* once, across many change detection cycles. This must be true even if some hooks throw, or if
* some recursively trigger a change detection cycle.
* To solve that, it is required to track the state of the execution of these init hooks.
* This is done by storing and maintaining flags in the view: the {@link InitPhaseState},
* and the index within that phase. They can be seen as a cursor in the following structure:
* [[onInit1, onInit2], [afterContentInit1], [afterViewInit1, afterViewInit2, afterViewInit3]]
* They are are stored as flags in LView[FLAGS].
*
* 2. Pre-order hooks can be executed in batches, because of the select instruction.
* To be able to pause and resume their execution, we also need some state about the hook's array
* that is being processed:
* - the index of the next hook to be executed
* - the number of init hooks already found in the processed part of the array
* They are are stored as flags in LView[PREORDER_HOOK_FLAGS].
*/
/**
* Executes pre-order check hooks ( OnChanges, DoChanges) given a view where all the init hooks were
* executed once. This is a light version of executeInitAndCheckPreOrderHooks where we can skip read
* / write of the init-hooks related flags.
* @param {?} lView The LView where hooks are defined
* @param {?} hooks Hooks to be run
* @param {?=} nodeIndex 3 cases depending on the value:
* - undefined: all hooks from the array should be executed (post-order case)
* - null: execute hooks only from the saved index until the end of the array (pre-order case, when
* flushing the remaining hooks)
* - number: execute hooks only from the saved index until that node index exclusive (pre-order
* case, when executing select(number))
* @return {?}
*/
function executeCheckHooks(lView, hooks, nodeIndex) {
callHooks(lView, hooks, 3 /* InitPhaseCompleted */, nodeIndex);
}
/**
* Executes post-order init and check hooks (one of AfterContentInit, AfterContentChecked,
* AfterViewInit, AfterViewChecked) given a view where there are pending init hooks to be executed.
* @param {?} lView The LView where hooks are defined
* @param {?} hooks Hooks to be run
* @param {?} initPhase A phase for which hooks should be run
* @param {?=} nodeIndex 3 cases depending on the value:
* - undefined: all hooks from the array should be executed (post-order case)
* - null: execute hooks only from the saved index until the end of the array (pre-order case, when
* flushing the remaining hooks)
* - number: execute hooks only from the saved index until that node index exclusive (pre-order
* case, when executing select(number))
* @return {?}
*/
function executeInitAndCheckHooks(lView, hooks, initPhase, nodeIndex) {
ngDevMode &&
assertNotEqual(initPhase, 3 /* InitPhaseCompleted */, 'Init pre-order hooks should not be called more than once');
if ((lView[FLAGS] & 3 /* InitPhaseStateMask */) === initPhase) {
callHooks(lView, hooks, initPhase, nodeIndex);
}
}
/**
* @param {?} lView
* @param {?} initPhase
* @return {?}
*/
function incrementInitPhaseFlags(lView, initPhase) {
ngDevMode &&
assertNotEqual(initPhase, 3 /* InitPhaseCompleted */, 'Init hooks phase should not be incremented after all init hooks have been run.');
/** @type {?} */
let flags = lView[FLAGS];
if ((flags & 3 /* InitPhaseStateMask */) === initPhase) {
flags &= 2047 /* IndexWithinInitPhaseReset */;
flags += 1 /* InitPhaseStateIncrementer */;
lView[FLAGS] = flags;
}
}
/**
* Calls lifecycle hooks with their contexts, skipping init hooks if it's not
* the first LView pass
*
* @param {?} currentView The current view
* @param {?} arr The array in which the hooks are found
* @param {?} initPhase
* @param {?} currentNodeIndex 3 cases depending on the value:
* - undefined: all hooks from the array should be executed (post-order case)
* - null: execute hooks only from the saved index until the end of the array (pre-order case, when
* flushing the remaining hooks)
* - number: execute hooks only from the saved index until that node index exclusive (pre-order
* case, when executing select(number))
* @return {?}
*/
function callHooks(currentView, arr, initPhase, currentNodeIndex) {
ngDevMode &&
assertEqual(getCheckNoChangesMode(), false, 'Hooks should never be run in the check no changes mode.');
/** @type {?} */
const startIndex = currentNodeIndex !== undefined ?
(currentView[PREORDER_HOOK_FLAGS] & 65535 /* IndexOfTheNextPreOrderHookMaskMask */) :
0;
/** @type {?} */
const nodeIndexLimit = currentNodeIndex != null ? currentNodeIndex : -1;
/** @type {?} */
let lastNodeIndexFound = 0;
for (let i = startIndex; i < arr.length; i++) {
/** @type {?} */
const hook = (/** @type {?} */ (arr[i + 1]));
if (typeof hook === 'number') {
lastNodeIndexFound = (/** @type {?} */ (arr[i]));
if (currentNodeIndex != null && lastNodeIndexFound >= currentNodeIndex) {
break;
}
}
else {
/** @type {?} */
const isInitHook = arr[i] < 0;
if (isInitHook)
currentView[PREORDER_HOOK_FLAGS] += 65536 /* NumberOfInitHooksCalledIncrementer */;
if (lastNodeIndexFound < nodeIndexLimit || nodeIndexLimit == -1) {
callHook(currentView, initPhase, arr, i);
currentView[PREORDER_HOOK_FLAGS] =
(currentView[PREORDER_HOOK_FLAGS] & 4294901760 /* NumberOfInitHooksCalledMask */) + i +
2;
}
i++;
}
}
}
/**
* Execute one hook against the current `LView`.
*
* @param {?} currentView The current view
* @param {?} initPhase
* @param {?} arr The array in which the hooks are found
* @param {?} i The current index within the hook data array
* @return {?}
*/
function callHook(currentView, initPhase, arr, i) {
/** @type {?} */
const isInitHook = arr[i] < 0;
/** @type {?} */
const hook = (/** @type {?} */ (arr[i + 1]));
/** @type {?} */
const directiveIndex = isInitHook ? -arr[i] : (/** @type {?} */ (arr[i]));
/** @type {?} */
const directive = currentView[directiveIndex];
if (isInitHook) {
/** @type {?} */
const indexWithintInitPhase = currentView[FLAGS] >> 11 /* IndexWithinInitPhaseShift */;
// The init phase state must be always checked here as it may have been recursively
// updated
if (indexWithintInitPhase <
(currentView[PREORDER_HOOK_FLAGS] >> 16 /* NumberOfInitHooksCalledShift */) &&
(currentView[FLAGS] & 3 /* InitPhaseStateMask */) === initPhase) {
currentView[FLAGS] += 2048 /* IndexWithinInitPhaseIncrementer */;
hook.call(directive);
}
}
else {
hook.call(directive);
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/injector.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @type {?} */
const TNODE = 8;
/** @type {?} */
const PARENT_INJECTOR = 8;
/** @type {?} */
const INJECTOR_BLOOM_PARENT_SIZE = 9;
/**
* Represents a relative location of parent injector.
*
* The interfaces encodes number of parents `LView`s to traverse and index in the `LView`
* pointing to the parent injector.
* @record
*/
function RelativeInjectorLocation() { }
if (false) {}
/** @enum {number} */
const RelativeInjectorLocationFlags = {
InjectorIndexMask: 32767,
ViewOffsetShift: 16,
NO_PARENT: -1,
};
/** @type {?} */
const NO_PARENT_INJECTOR = (/** @type {?} */ (-1));
/**
* Each injector is saved in 9 contiguous slots in `LView` and 9 contiguous slots in
* `TView.data`. This allows us to store information about the current node's tokens (which
* can be shared in `TView`) as well as the tokens of its ancestor nodes (which cannot be
* shared, so they live in `LView`).
*
* Each of these slots (aside from the last slot) contains a bloom filter. This bloom filter
* determines whether a directive is available on the associated node or not. This prevents us
* from searching the directives array at this level unless it's probable the directive is in it.
*
* See: https://en.wikipedia.org/wiki/Bloom_filter for more about bloom filters.
*
* Because all injectors have been flattened into `LView` and `TViewData`, they cannot typed
* using interfaces as they were previously. The start index of each `LInjector` and `TInjector`
* will differ based on where it is flattened into the main array, so it's not possible to know
* the indices ahead of time and save their types here. The interfaces are still included here
* for documentation purposes.
*
* export interface LInjector extends Array<any> {
*
* // Cumulative bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)
* [0]: number;
*
* // Cumulative bloom for directive IDs 32-63
* [1]: number;
*
* // Cumulative bloom for directive IDs 64-95
* [2]: number;
*
* // Cumulative bloom for directive IDs 96-127
* [3]: number;
*
* // Cumulative bloom for directive IDs 128-159
* [4]: number;
*
* // Cumulative bloom for directive IDs 160 - 191
* [5]: number;
*
* // Cumulative bloom for directive IDs 192 - 223
* [6]: number;
*
* // Cumulative bloom for directive IDs 224 - 255
* [7]: number;
*
* // We need to store a reference to the injector's parent so DI can keep looking up
* // the injector tree until it finds the dependency it's looking for.
* [PARENT_INJECTOR]: number;
* }
*
* export interface TInjector extends Array<any> {
*
* // Shared node bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)
* [0]: number;
*
* // Shared node bloom for directive IDs 32-63
* [1]: number;
*
* // Shared node bloom for directive IDs 64-95
* [2]: number;
*
* // Shared node bloom for directive IDs 96-127
* [3]: number;
*
* // Shared node bloom for directive IDs 128-159
* [4]: number;
*
* // Shared node bloom for directive IDs 160 - 191
* [5]: number;
*
* // Shared node bloom for directive IDs 192 - 223
* [6]: number;
*
* // Shared node bloom for directive IDs 224 - 255
* [7]: number;
*
* // Necessary to find directive indices for a particular node.
* [TNODE]: TElementNode|TElementContainerNode|TContainerNode;
* }
*/
/**
* Factory for creating instances of injectors in the NodeInjector.
*
* This factory is complicated by the fact that it can resolve `multi` factories as well.
*
* NOTE: Some of the fields are optional which means that this class has two hidden classes.
* - One without `multi` support (most common)
* - One with `multi` values, (rare).
*
* Since VMs can cache up to 4 inline hidden classes this is OK.
*
* - Single factory: Only `resolving` and `factory` is defined.
* - `providers` factory: `componentProviders` is a number and `index = -1`.
* - `viewProviders` factory: `componentProviders` is a number and `index` points to `providers`.
*/
class NodeInjectorFactory {
/**
* @param {?} factory
* @param {?} isViewProvider
* @param {?} injectImplementation
*/
constructor(factory,
/**
* Set to `true` if the token is declared in `viewProviders` (or if it is component).
*/
isViewProvider, injectImplementation) {
this.factory = factory;
/**
* Marker set to true during factory invocation to see if we get into recursive loop.
* Recursive loop causes an error to be displayed.
*/
this.resolving = false;
this.canSeeViewProviders = isViewProvider;
this.injectImpl = injectImplementation;
}
}
if (false) {}
/**
* @param {?} obj
* @return {?}
*/
function isFactory(obj) {
return obj instanceof NodeInjectorFactory;
}
// Note: This hack is necessary so we don't erroneously get a circular dependency
// failure based on types.
/** @type {?} */
const unusedValueExportToPlacateAjd$3 = 1;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/node_assert.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} tNode
* @param {?} type
* @return {?}
*/
function assertNodeType(tNode, type) {
assertDefined(tNode, 'should be called with a TNode');
assertEqual(tNode.type, type, `should be a ${typeName(type)}`);
}
/**
* @param {?} tNode
* @param {...?} types
* @return {?}
*/
function assertNodeOfPossibleTypes(tNode, ...types) {
assertDefined(tNode, 'should be called with a TNode');
/** @type {?} */
const found = types.some((/**
* @param {?} type
* @return {?}
*/
type => tNode.type === type));
assertEqual(found, true, `Should be one of ${types.map(typeName).join(', ')} but got ${typeName(tNode.type)}`);
}
/**
* @param {?} type
* @return {?}
*/
function typeName(type) {
if (type == 1 /* Projection */)
return 'Projection';
if (type == 0 /* Container */)
return 'Container';
if (type == 5 /* IcuContainer */)
return 'IcuContainer';
if (type == 2 /* View */)
return 'View';
if (type == 3 /* Element */)
return 'Element';
if (type == 4 /* ElementContainer */)
return 'ElementContainer';
return '<unknown>';
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/util/attrs_utils.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Assigns all attribute values to the provided element via the inferred renderer.
*
* This function accepts two forms of attribute entries:
*
* default: (key, value):
* attrs = [key1, value1, key2, value2]
*
* namespaced: (NAMESPACE_MARKER, uri, name, value)
* attrs = [NAMESPACE_MARKER, uri, name, value, NAMESPACE_MARKER, uri, name, value]
*
* The `attrs` array can contain a mix of both the default and namespaced entries.
* The "default" values are set without a marker, but if the function comes across
* a marker value then it will attempt to set a namespaced value. If the marker is
* not of a namespaced value then the function will quit and return the index value
* where it stopped during the iteration of the attrs array.
*
* See [AttributeMarker] to understand what the namespace marker value is.
*
* Note that this instruction does not support assigning style and class values to
* an element. See `elementStart` and `elementHostAttrs` to learn how styling values
* are applied to an element.
* @param {?} renderer The renderer to be used
* @param {?} native The element that the attributes will be assigned to
* @param {?} attrs The attribute array of values that will be assigned to the element
* @return {?} the index value that was last accessed in the attributes array
*/
function setUpAttributes(renderer, native, attrs) {
/** @type {?} */
const isProc = isProceduralRenderer(renderer);
/** @type {?} */
let i = 0;
while (i < attrs.length) {
/** @type {?} */
const value = attrs[i];
if (typeof value === 'number') {
// only namespaces are supported. Other value types (such as style/class
// entries) are not supported in this function.
if (value !== 0 /* NamespaceURI */) {
break;
}
// we just landed on the marker value ... therefore
// we should skip to the next entry
i++;
/** @type {?} */
const namespaceURI = (/** @type {?} */ (attrs[i++]));
/** @type {?} */
const attrName = (/** @type {?} */ (attrs[i++]));
/** @type {?} */
const attrVal = (/** @type {?} */ (attrs[i++]));
ngDevMode && ngDevMode.rendererSetAttribute++;
isProc ?
((/** @type {?} */ (renderer))).setAttribute(native, attrName, attrVal, namespaceURI) :
native.setAttributeNS(namespaceURI, attrName, attrVal);
}
else {
// attrName is string;
/** @type {?} */
const attrName = (/** @type {?} */ (value));
/** @type {?} */
const attrVal = attrs[++i];
// Standard attributes
ngDevMode && ngDevMode.rendererSetAttribute++;
if (isAnimationProp(attrName)) {
if (isProc) {
((/** @type {?} */ (renderer))).setProperty(native, attrName, attrVal);
}
}
else {
isProc ?
((/** @type {?} */ (renderer))).setAttribute(native, attrName, (/** @type {?} */ (attrVal))) :
native.setAttribute(attrName, (/** @type {?} */ (attrVal)));
}
i++;
}
}
// another piece of code may iterate over the same attributes array. Therefore
// it may be helpful to return the exact spot where the attributes array exited
// whether by running into an unsupported marker or if all the static values were
// iterated over.
return i;
}
/**
* Test whether the given value is a marker that indicates that the following
* attribute values in a `TAttributes` array are only the names of attributes,
* and not name-value pairs.
* @param {?} marker The attribute marker to test.
* @return {?} true if the marker is a "name-only" marker (e.g. `Bindings`, `Template` or `I18n`).
*/
function isNameOnlyAttributeMarker(marker) {
return marker === 3 /* Bindings */ || marker === 4 /* Template */ ||
marker === 6 /* I18n */;
}
/**
* @param {?} name
* @return {?}
*/
function isAnimationProp(name) {
// Perf note: accessing charCodeAt to check for the first character of a string is faster as
// compared to accessing a character at index 0 (ex. name[0]). The main reason for this is that
// charCodeAt doesn't allocate memory to return a substring.
return name.charCodeAt(0) === 64 /* AT_SIGN */;
}
/**
* Merges `src` `TAttributes` into `dst` `TAttributes` removing any duplicates in the process.
*
* This merge function keeps the order of attrs same.
*
* @param {?} dst Location of where the merged `TAttributes` should end up.
* @param {?} src `TAttributes` which should be appended to `dst`
* @return {?}
*/
function mergeHostAttrs(dst, src) {
if (src === null || src.length === 0) {
// do nothing
}
else if (dst === null || dst.length === 0) {
// We have source, but dst is empty, just make a copy.
dst = src.slice();
}
else {
/** @type {?} */
let srcMarker = -1 /* ImplicitAttributes */;
for (let i = 0; i < src.length; i++) {
/** @type {?} */
const item = src[i];
if (typeof item === 'number') {
srcMarker = item;
}
else {
if (srcMarker === 0 /* NamespaceURI */) {
// Case where we need to consume `key1`, `key2`, `value` items.
}
else if (srcMarker === -1 /* ImplicitAttributes */ ||
srcMarker === 2 /* Styles */) {
// Case where we have to consume `key1` and `value` only.
mergeHostAttribute(dst, srcMarker, (/** @type {?} */ (item)), null, (/** @type {?} */ (src[++i])));
}
else {
// Case where we have to consume `key1` only.
mergeHostAttribute(dst, srcMarker, (/** @type {?} */ (item)), null, null);
}
}
}
}
return dst;
}
/**
* Append `key`/`value` to existing `TAttributes` taking region marker and duplicates into account.
*
* @param {?} dst `TAttributes` to append to.
* @param {?} marker Region where the `key`/`value` should be added.
* @param {?} key1 Key to add to `TAttributes`
* @param {?} key2 Key to add to `TAttributes` (in case of `AttributeMarker.NamespaceURI`)
* @param {?} value Value to add or to overwrite to `TAttributes` Only used if `marker` is not Class.
* @return {?}
*/
function mergeHostAttribute(dst, marker, key1, key2, value) {
/** @type {?} */
let i = 0;
// Assume that new markers will be inserted at the end.
/** @type {?} */
let markerInsertPosition = dst.length;
// scan until correct type.
if (marker === -1 /* ImplicitAttributes */) {
markerInsertPosition = -1;
}
else {
while (i < dst.length) {
/** @type {?} */
const dstValue = dst[i++];
if (typeof dstValue === 'number') {
if (dstValue === marker) {
markerInsertPosition = -1;
break;
}
else if (dstValue > marker) {
// We need to save this as we want the markers to be inserted in specific order.
markerInsertPosition = i - 1;
break;
}
}
}
}
// search until you find place of insertion
while (i < dst.length) {
/** @type {?} */
const item = dst[i];
if (typeof item === 'number') {
// since `i` started as the index after the marker, we did not find it if we are at the next
// marker
break;
}
else if (item === key1) {
// We already have same token
if (key2 === null) {
if (value !== null) {
dst[i + 1] = value;
}
return;
}
else if (key2 === dst[i + 1]) {
dst[i + 2] = (/** @type {?} */ (value));
return;
}
}
// Increment counter.
i++;
if (key2 !== null)
i++;
if (value !== null)
i++;
}
// insert at location.
if (markerInsertPosition !== -1) {
dst.splice(markerInsertPosition, 0, marker);
i = markerInsertPosition + 1;
}
dst.splice(i++, 0, key1);
if (key2 !== null) {
dst.splice(i++, 0, key2);
}
if (value !== null) {
dst.splice(i++, 0, value);
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/util/injector_utils.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/// Parent Injector Utils ///////////////////////////////////////////////////////////////
/**
* @param {?} parentLocation
* @return {?}
*/
function hasParentInjector(parentLocation) {
return parentLocation !== NO_PARENT_INJECTOR;
}
/**
* @param {?} parentLocation
* @return {?}
*/
function getParentInjectorIndex(parentLocation) {
return ((/** @type {?} */ ((/** @type {?} */ (parentLocation))))) & 32767 /* InjectorIndexMask */;
}
/**
* @param {?} parentLocation
* @return {?}
*/
function getParentInjectorViewOffset(parentLocation) {
return ((/** @type {?} */ ((/** @type {?} */ (parentLocation))))) >> 16 /* ViewOffsetShift */;
}
/**
* Unwraps a parent injector location number to find the view offset from the current injector,
* then walks up the declaration view tree until the view is found that contains the parent
* injector.
*
* @param {?} location The location of the parent injector, which contains the view offset
* @param {?} startView The LView instance from which to start walking up the view tree
* @return {?} The LView instance that contains the parent injector
*/
function getParentInjectorView(location, startView) {
/** @type {?} */
let viewOffset = getParentInjectorViewOffset(location);
/** @type {?} */
let parentView = startView;
// For most cases, the parent injector can be found on the host node (e.g. for component
// or container), but we must keep the loop here to support the rarer case of deeply nested
// <ng-template> tags or inline views, where the parent injector might live many views
// above the child injector.
while (viewOffset > 0) {
parentView = (/** @type {?} */ (parentView[DECLARATION_VIEW]));
viewOffset--;
}
return parentView;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/util/misc_utils.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Used for stringify render output in Ivy.
* Important! This function is very performance-sensitive and we should
* be extra careful not to introduce megamorphic reads in it.
* @param {?} value
* @return {?}
*/
function renderStringify(value) {
if (typeof value === 'string')
return value;
if (value == null)
return '';
return '' + value;
}
/**
* Used to stringify a value so that it can be displayed in an error message.
* Important! This function contains a megamorphic read and should only be
* used for error messages.
* @param {?} value
* @return {?}
*/
function stringifyForError(value) {
if (typeof value === 'function')
return value.name || value.toString();
if (typeof value === 'object' && value != null && typeof value.type === 'function') {
return value.type.name || value.type.toString();
}
return renderStringify(value);
}
const ɵ0$3 = /**
* @return {?}
*/
() => (typeof requestAnimationFrame !== 'undefined' &&
requestAnimationFrame || // browser only
setTimeout // everything else
)
.bind(_global);
/** @type {?} */
const defaultScheduler = ((ɵ0$3))();
/**
*
* \@codeGenApi
* @param {?} element
* @return {?}
*/
function ɵɵresolveWindow(element) {
return { name: 'window', target: element.ownerDocument.defaultView };
}
/**
*
* \@codeGenApi
* @param {?} element
* @return {?}
*/
function ɵɵresolveDocument(element) {
return { name: 'document', target: element.ownerDocument };
}
/**
*
* \@codeGenApi
* @param {?} element
* @return {?}
*/
function ɵɵresolveBody(element) {
return { name: 'body', target: element.ownerDocument.body };
}
/**
* The special delimiter we use to separate property names, prefixes, and suffixes
* in property binding metadata. See storeBindingMetadata().
*
* We intentionally use the Unicode "REPLACEMENT CHARACTER" (U+FFFD) as a delimiter
* because it is a very uncommon character that is unlikely to be part of a user's
* property names or interpolation strings. If it is in fact used in a property
* binding, DebugElement.properties will not return the correct value for that
* binding. However, there should be no runtime effect for real applications.
*
* This character is typically rendered as a question mark inside of a diamond.
* See https://en.wikipedia.org/wiki/Specials_(Unicode_block)
*
* @type {?}
*/
const INTERPOLATION_DELIMITER = `�`;
/**
* Unwrap a value which might be behind a closure (for forward declaration reasons).
* @template T
* @param {?} value
* @return {?}
*/
function maybeUnwrapFn(value) {
if (value instanceof Function) {
return value();
}
else {
return value;
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/di.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Defines if the call to `inject` should include `viewProviders` in its resolution.
*
* This is set to true when we try to instantiate a component. This value is reset in
* `getNodeInjectable` to a value which matches the declaration location of the token about to be
* instantiated. This is done so that if we are injecting a token which was declared outside of
* `viewProviders` we don't accidentally pull `viewProviders` in.
*
* Example:
*
* ```
* \@Injectable()
* class MyService {
* constructor(public value: String) {}
* }
*
* \@Component({
* providers: [
* MyService,
* {provide: String, value: 'providers' }
* ]
* viewProviders: [
* {provide: String, value: 'viewProviders'}
* ]
* })
* class MyComponent {
* constructor(myService: MyService, value: String) {
* // We expect that Component can see into `viewProviders`.
* expect(value).toEqual('viewProviders');
* // `MyService` was not declared in `viewProviders` hence it can't see it.
* expect(myService.value).toEqual('providers');
* }
* }
*
* ```
* @type {?}
*/
let includeViewProviders = true;
/**
* @param {?} v
* @return {?}
*/
function setIncludeViewProviders(v) {
/** @type {?} */
const oldValue = includeViewProviders;
includeViewProviders = v;
return oldValue;
}
/**
* The number of slots in each bloom filter (used by DI). The larger this number, the fewer
* directives that will share slots, and thus, the fewer false positives when checking for
* the existence of a directive.
* @type {?}
*/
const BLOOM_SIZE = 256;
/** @type {?} */
const BLOOM_MASK = BLOOM_SIZE - 1;
/**
* Counter used to generate unique IDs for directives.
* @type {?}
*/
let nextNgElementId = 0;
/**
* Registers this directive as present in its node's injector by flipping the directive's
* corresponding bit in the injector's bloom filter.
*
* @param {?} injectorIndex The index of the node injector where this token should be registered
* @param {?} tView The TView for the injector's bloom filters
* @param {?} type The directive token to register
* @return {?}
*/
function bloomAdd(injectorIndex, tView, type) {
ngDevMode && assertEqual(tView.firstCreatePass, true, 'expected firstCreatePass to be true');
/** @type {?} */
let id = typeof type !== 'string' ? ((/** @type {?} */ (type)))[NG_ELEMENT_ID] : type.charCodeAt(0) || 0;
// Set a unique ID on the directive type, so if something tries to inject the directive,
// we can easily retrieve the ID and hash it into the bloom bit that should be checked.
if (id == null) {
id = ((/** @type {?} */ (type)))[NG_ELEMENT_ID] = nextNgElementId++;
}
// We only have BLOOM_SIZE (256) slots in our bloom filter (8 buckets * 32 bits each),
// so all unique IDs must be modulo-ed into a number from 0 - 255 to fit into the filter.
/** @type {?} */
const bloomBit = id & BLOOM_MASK;
// Create a mask that targets the specific bit associated with the directive.
// JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
// to bit positions 0 - 31 in a 32 bit integer.
/** @type {?} */
const mask = 1 << bloomBit;
// Use the raw bloomBit number to determine which bloom filter bucket we should check
// e.g: bf0 = [0 - 31], bf1 = [32 - 63], bf2 = [64 - 95], bf3 = [96 - 127], etc
/** @type {?} */
const b7 = bloomBit & 0x80;
/** @type {?} */
const b6 = bloomBit & 0x40;
/** @type {?} */
const b5 = bloomBit & 0x20;
/** @type {?} */
const tData = (/** @type {?} */ (tView.data));
if (b7) {
b6 ? (b5 ? (tData[injectorIndex + 7] |= mask) : (tData[injectorIndex + 6] |= mask)) :
(b5 ? (tData[injectorIndex + 5] |= mask) : (tData[injectorIndex + 4] |= mask));
}
else {
b6 ? (b5 ? (tData[injectorIndex + 3] |= mask) : (tData[injectorIndex + 2] |= mask)) :
(b5 ? (tData[injectorIndex + 1] |= mask) : (tData[injectorIndex] |= mask));
}
}
/**
* Creates (or gets an existing) injector for a given element or container.
*
* @param {?} tNode for which an injector should be retrieved / created.
* @param {?} hostView View where the node is stored
* @return {?} Node injector
*/
function getOrCreateNodeInjectorForNode(tNode, hostView) {
/** @type {?} */
const existingInjectorIndex = getInjectorIndex(tNode, hostView);
if (existingInjectorIndex !== -1) {
return existingInjectorIndex;
}
/** @type {?} */
const tView = hostView[TVIEW];
if (tView.firstCreatePass) {
tNode.injectorIndex = hostView.length;
insertBloom(tView.data, tNode); // foundation for node bloom
insertBloom(hostView, null); // foundation for cumulative bloom
insertBloom(tView.blueprint, null);
}
/** @type {?} */
const parentLoc = getParentInjectorLocation(tNode, hostView);
/** @type {?} */
const injectorIndex = tNode.injectorIndex;
// If a parent injector can't be found, its location is set to -1.
// In that case, we don't need to set up a cumulative bloom
if (hasParentInjector(parentLoc)) {
/** @type {?} */
const parentIndex = getParentInjectorIndex(parentLoc);
/** @type {?} */
const parentLView = getParentInjectorView(parentLoc, hostView);
/** @type {?} */
const parentData = (/** @type {?} */ (parentLView[TVIEW].data));
// Creates a cumulative bloom filter that merges the parent's bloom filter
// and its own cumulative bloom (which contains tokens for all ancestors)
for (let i = 0; i < 8; i++) {
hostView[injectorIndex + i] = parentLView[parentIndex + i] | parentData[parentIndex + i];
}
}
hostView[injectorIndex + PARENT_INJECTOR] = parentLoc;
return injectorIndex;
}
/**
* @param {?} arr
* @param {?} footer
* @return {?}
*/
function insertBloom(arr, footer) {
arr.push(0, 0, 0, 0, 0, 0, 0, 0, footer);
}
/**
* @param {?} tNode
* @param {?} hostView
* @return {?}
*/
function getInjectorIndex(tNode, hostView) {
if (tNode.injectorIndex === -1 ||
// If the injector index is the same as its parent's injector index, then the index has been
// copied down from the parent node. No injector has been created yet on this node.
(tNode.parent && tNode.parent.injectorIndex === tNode.injectorIndex) ||
// After the first template pass, the injector index might exist but the parent values
// might not have been calculated yet for this instance
hostView[tNode.injectorIndex + PARENT_INJECTOR] == null) {
return -1;
}
else {
return tNode.injectorIndex;
}
}
/**
* Finds the index of the parent injector, with a view offset if applicable. Used to set the
* parent injector initially.
*
* Returns a combination of number of `ViewData` we have to go up and index in that `Viewdata`
* @param {?} tNode
* @param {?} view
* @return {?}
*/
function getParentInjectorLocation(tNode, view) {
if (tNode.parent && tNode.parent.injectorIndex !== -1) {
return (/** @type {?} */ (tNode.parent.injectorIndex)); // ViewOffset is 0
}
// For most cases, the parent injector index can be found on the host node (e.g. for component
// or container), so this loop will be skipped, but we must keep the loop here to support
// the rarer case of deeply nested <ng-template> tags or inline views.
/** @type {?} */
let hostTNode = view[T_HOST];
/** @type {?} */
let viewOffset = 1;
while (hostTNode && hostTNode.injectorIndex === -1) {
view = (/** @type {?} */ (view[DECLARATION_VIEW]));
hostTNode = view ? view[T_HOST] : null;
viewOffset++;
}
return hostTNode ?
hostTNode.injectorIndex | (viewOffset << 16 /* ViewOffsetShift */) :
(/** @type {?} */ (-1));
}
/**
* Makes a type or an injection token public to the DI system by adding it to an
* injector's bloom filter.
*
* @param {?} injectorIndex
* @param {?} tView
* @param {?} token The type or the injection token to be made public
* @return {?}
*/
function diPublicInInjector(injectorIndex, tView, token) {
bloomAdd(injectorIndex, tView, token);
}
/**
* Inject static attribute value into directive constructor.
*
* This method is used with `factory` functions which are generated as part of
* `defineDirective` or `defineComponent`. The method retrieves the static value
* of an attribute. (Dynamic attributes are not supported since they are not resolved
* at the time of injection and can change over time.)
*
* # Example
* Given:
* ```
* \@Component(...)
* class MyComponent {
* constructor(\@Attribute('title') title: string) { ... }
* }
* ```
* When instantiated with
* ```
* <my-component title="Hello"></my-component>
* ```
*
* Then factory method generated is:
* ```
* MyComponent.ɵcmp = defineComponent({
* factory: () => new MyComponent(injectAttribute('title'))
* ...
* })
* ```
*
* \@publicApi
* @param {?} tNode
* @param {?} attrNameToInject
* @return {?}
*/
function injectAttributeImpl(tNode, attrNameToInject) {
ngDevMode &&
assertNodeOfPossibleTypes(tNode, 0 /* Container */, 3 /* Element */, 4 /* ElementContainer */);
ngDevMode && assertDefined(tNode, 'expecting tNode');
if (attrNameToInject === 'class') {
return tNode.classes;
}
if (attrNameToInject === 'style') {
return tNode.styles;
}
/** @type {?} */
const attrs = tNode.attrs;
if (attrs) {
/** @type {?} */
const attrsLength = attrs.length;
/** @type {?} */
let i = 0;
while (i < attrsLength) {
/** @type {?} */
const value = attrs[i];
// If we hit a `Bindings` or `Template` marker then we are done.
if (isNameOnlyAttributeMarker(value))
break;
// Skip namespaced attributes
if (value === 0 /* NamespaceURI */) {
// we skip the next two values
// as namespaced attributes looks like
// [..., AttributeMarker.NamespaceURI, 'http://someuri.com/test', 'test:exist',
// 'existValue', ...]
i = i + 2;
}
else if (typeof value === 'number') {
// Skip to the first value of the marked attribute.
i++;
while (i < attrsLength && typeof attrs[i] === 'string') {
i++;
}
}
else if (value === attrNameToInject) {
return (/** @type {?} */ (attrs[i + 1]));
}
else {
i = i + 2;
}
}
}
return null;
}
/**
* Returns the value associated to the given token from the NodeInjectors => ModuleInjector.
*
* Look for the injector providing the token by walking up the node injector tree and then
* the module injector tree.
*
* This function patches `token` with `__NG_ELEMENT_ID__` which contains the id for the bloom
* filter. Negative values are reserved for special objects.
* - `-1` is reserved for injecting `Injector` (implemented by `NodeInjector`)
*
* @template T
* @param {?} tNode The Node where the search for the injector should start
* @param {?} lView The `LView` that contains the `tNode`
* @param {?} token The token to look for
* @param {?=} flags Injection flags
* @param {?=} notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
* @return {?} the value from the injector, `null` when not found, or `notFoundValue` if provided
*/
function getOrCreateInjectable(tNode, lView, token, flags = InjectFlags.Default, notFoundValue) {
if (tNode !== null) {
/** @type {?} */
const bloomHash = bloomHashBitOrFactory(token);
// If the ID stored here is a function, this is a special object like ElementRef or TemplateRef
// so just call the factory function to create it.
if (typeof bloomHash === 'function') {
enterDI(lView, tNode);
try {
/** @type {?} */
const value = bloomHash();
if (value == null && !(flags & InjectFlags.Optional)) {
throw new Error(`No provider for ${stringifyForError(token)}!`);
}
else {
return value;
}
}
finally {
leaveDI();
}
}
else if (typeof bloomHash == 'number') {
if (bloomHash === -1) {
// `-1` is a special value used to identify `Injector` types.
return (/** @type {?} */ (new NodeInjector(tNode, lView)));
}
// If the token has a bloom hash, then it is a token which could be in NodeInjector.
// A reference to the previous injector TView that was found while climbing the element
// injector tree. This is used to know if viewProviders can be accessed on the current
// injector.
/** @type {?} */
let previousTView = null;
/** @type {?} */
let injectorIndex = getInjectorIndex(tNode, lView);
/** @type {?} */
let parentLocation = NO_PARENT_INJECTOR;
/** @type {?} */
let hostTElementNode = flags & InjectFlags.Host ? lView[DECLARATION_COMPONENT_VIEW][T_HOST] : null;
// If we should skip this injector, or if there is no injector on this node, start by
// searching
// the parent injector.
if (injectorIndex === -1 || flags & InjectFlags.SkipSelf) {
parentLocation = injectorIndex === -1 ? getParentInjectorLocation(tNode, lView) :
lView[injectorIndex + PARENT_INJECTOR];
if (!shouldSearchParent(flags, false)) {
injectorIndex = -1;
}
else {
previousTView = lView[TVIEW];
injectorIndex = getParentInjectorIndex(parentLocation);
lView = getParentInjectorView(parentLocation, lView);
}
}
// Traverse up the injector tree until we find a potential match or until we know there
// *isn't* a match.
while (injectorIndex !== -1) {
parentLocation = lView[injectorIndex + PARENT_INJECTOR];
// Check the current injector. If it matches, see if it contains token.
/** @type {?} */
const tView = lView[TVIEW];
if (bloomHasToken(bloomHash, injectorIndex, tView.data)) {
// At this point, we have an injector which *may* contain the token, so we step through
// the providers and directives associated with the injector's corresponding node to get
// the instance.
/** @type {?} */
const instance = searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode);
if (instance !== NOT_FOUND) {
return instance;
}
}
if (shouldSearchParent(flags, lView[TVIEW].data[injectorIndex + TNODE] === hostTElementNode) &&
bloomHasToken(bloomHash, injectorIndex, lView)) {
// The def wasn't found anywhere on this node, so it was a false positive.
// Traverse up the tree and continue searching.
previousTView = tView;
injectorIndex = getParentInjectorIndex(parentLocation);
lView = getParentInjectorView(parentLocation, lView);
}
else {
// If we should not search parent OR If the ancestor bloom filter value does not have the
// bit corresponding to the directive we can give up on traversing up to find the specific
// injector.
injectorIndex = -1;
}
}
}
}
if (flags & InjectFlags.Optional && notFoundValue === undefined) {
// This must be set or the NullInjector will throw for optional deps
notFoundValue = null;
}
if ((flags & (InjectFlags.Self | InjectFlags.Host)) === 0) {
/** @type {?} */
const moduleInjector = lView[INJECTOR$1];
// switch to `injectInjectorOnly` implementation for module injector, since module injector
// should not have access to Component/Directive DI scope (that may happen through
// `directiveInject` implementation)
/** @type {?} */
const previousInjectImplementation = setInjectImplementation(undefined);
try {
if (moduleInjector) {
return moduleInjector.get(token, notFoundValue, flags & InjectFlags.Optional);
}
else {
return injectRootLimpMode(token, notFoundValue, flags & InjectFlags.Optional);
}
}
finally {
setInjectImplementation(previousInjectImplementation);
}
}
if (flags & InjectFlags.Optional) {
return notFoundValue;
}
else {
throw new Error(`NodeInjector: NOT_FOUND [${stringifyForError(token)}]`);
}
}
/** @type {?} */
const NOT_FOUND = {};
/**
* @template T
* @param {?} injectorIndex
* @param {?} lView
* @param {?} token
* @param {?} previousTView
* @param {?} flags
* @param {?} hostTElementNode
* @return {?}
*/
function searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode) {
/** @type {?} */
const currentTView = lView[TVIEW];
/** @type {?} */
const tNode = (/** @type {?} */ (currentTView.data[injectorIndex + TNODE]));
// First, we need to determine if view providers can be accessed by the starting element.
// There are two possibities
/** @type {?} */
const canAccessViewProviders = previousTView == null ?
// 1) This is the first invocation `previousTView == null` which means that we are at the
// `TNode` of where injector is starting to look. In such a case the only time we are allowed
// to look into the ViewProviders is if:
// - we are on a component
// - AND the injector set `includeViewProviders` to true (implying that the token can see
// ViewProviders because it is the Component or a Service which itself was declared in
// ViewProviders)
(isComponentHost(tNode) && includeViewProviders) :
// 2) `previousTView != null` which means that we are now walking across the parent nodes.
// In such a case we are only allowed to look into the ViewProviders if:
// - We just crossed from child View to Parent View `previousTView != currentTView`
// - AND the parent TNode is an Element.
// This means that we just came from the Component's View and therefore are allowed to see
// into the ViewProviders.
(previousTView != currentTView && (tNode.type === 3 /* Element */));
// This special case happens when there is a @host on the inject and when we are searching
// on the host element node.
/** @type {?} */
const isHostSpecialCase = (flags & InjectFlags.Host) && hostTElementNode === tNode;
/** @type {?} */
const injectableIdx = locateDirectiveOrProvider(tNode, currentTView, token, canAccessViewProviders, isHostSpecialCase);
if (injectableIdx !== null) {
return getNodeInjectable(lView, currentTView, injectableIdx, (/** @type {?} */ (tNode)));
}
else {
return NOT_FOUND;
}
}
/**
* Searches for the given token among the node's directives and providers.
*
* @template T
* @param {?} tNode TNode on which directives are present.
* @param {?} tView The tView we are currently processing
* @param {?} token Provider token or type of a directive to look for.
* @param {?} canAccessViewProviders Whether view providers should be considered.
* @param {?} isHostSpecialCase Whether the host special case applies.
* @return {?} Index of a found directive or provider, or null when none found.
*/
function locateDirectiveOrProvider(tNode, tView, token, canAccessViewProviders, isHostSpecialCase) {
/** @type {?} */
const nodeProviderIndexes = tNode.providerIndexes;
/** @type {?} */
const tInjectables = tView.data;
/** @type {?} */
const injectablesStart = nodeProviderIndexes & 65535 /* ProvidersStartIndexMask */;
/** @type {?} */
const directivesStart = tNode.directiveStart;
/** @type {?} */
const directiveEnd = tNode.directiveEnd;
/** @type {?} */
const cptViewProvidersCount = nodeProviderIndexes >> 16 /* CptViewProvidersCountShift */;
/** @type {?} */
const startingIndex = canAccessViewProviders ? injectablesStart : injectablesStart + cptViewProvidersCount;
// When the host special case applies, only the viewProviders and the component are visible
/** @type {?} */
const endIndex = isHostSpecialCase ? injectablesStart + cptViewProvidersCount : directiveEnd;
for (let i = startingIndex; i < endIndex; i++) {
/** @type {?} */
const providerTokenOrDef = (/** @type {?} */ (tInjectables[i]));
if (i < directivesStart && token === providerTokenOrDef ||
i >= directivesStart && ((/** @type {?} */ (providerTokenOrDef))).type === token) {
return i;
}
}
if (isHostSpecialCase) {
/** @type {?} */
const dirDef = (/** @type {?} */ (tInjectables[directivesStart]));
if (dirDef && isComponentDef(dirDef) && dirDef.type === token) {
return directivesStart;
}
}
return null;
}
/**
* Retrieve or instantiate the injectable from the `LView` at particular `index`.
*
* This function checks to see if the value has already been instantiated and if so returns the
* cached `injectable`. Otherwise if it detects that the value is still a factory it
* instantiates the `injectable` and caches the value.
* @param {?} lView
* @param {?} tView
* @param {?} index
* @param {?} tNode
* @return {?}
*/
function getNodeInjectable(lView, tView, index, tNode) {
/** @type {?} */
let value = lView[index];
/** @type {?} */
const tData = tView.data;
if (isFactory(value)) {
/** @type {?} */
const factory = value;
if (factory.resolving) {
throw new Error(`Circular dep for ${stringifyForError(tData[index])}`);
}
/** @type {?} */
const previousIncludeViewProviders = setIncludeViewProviders(factory.canSeeViewProviders);
factory.resolving = true;
/** @type {?} */
let previousInjectImplementation;
if (factory.injectImpl) {
previousInjectImplementation = setInjectImplementation(factory.injectImpl);
}
enterDI(lView, tNode);
try {
value = lView[index] = factory.factory(undefined, tData, lView, tNode);
// This code path is hit for both directives and providers.
// For perf reasons, we want to avoid searching for hooks on providers.
// It does no harm to try (the hooks just won't exist), but the extra
// checks are unnecessary and this is a hot path. So we check to see
// if the index of the dependency is in the directive range for this
// tNode. If it's not, we know it's a provider and skip hook registration.
if (tView.firstCreatePass && index >= tNode.directiveStart) {
ngDevMode && assertDirectiveDef(tData[index]);
registerPreOrderHooks(index, (/** @type {?} */ (tData[index])), tView);
}
}
finally {
if (factory.injectImpl)
setInjectImplementation(previousInjectImplementation);
setIncludeViewProviders(previousIncludeViewProviders);
factory.resolving = false;
leaveDI();
}
}
return value;
}
/**
* Returns the bit in an injector's bloom filter that should be used to determine whether or not
* the directive might be provided by the injector.
*
* When a directive is public, it is added to the bloom filter and given a unique ID that can be
* retrieved on the Type. When the directive isn't public or the token is not a directive `null`
* is returned as the node injector can not possibly provide that token.
*
* @param {?} token the injection token
* @return {?} the matching bit to check in the bloom filter or `null` if the token is not known.
* When the returned value is negative then it represents special values such as `Injector`.
*/
function bloomHashBitOrFactory(token) {
ngDevMode && assertDefined(token, 'token must be defined');
if (typeof token === 'string') {
return token.charCodeAt(0) || 0;
}
/** @type {?} */
const tokenId = ((/** @type {?} */ (token)))[NG_ELEMENT_ID];
// Negative token IDs are used for special objects such as `Injector`
return (typeof tokenId === 'number' && tokenId > 0) ? tokenId & BLOOM_MASK : tokenId;
}
/**
* @param {?} bloomHash
* @param {?} injectorIndex
* @param {?} injectorView
* @return {?}
*/
function bloomHasToken(bloomHash, injectorIndex, injectorView) {
// Create a mask that targets the specific bit associated with the directive we're looking for.
// JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
// to bit positions 0 - 31 in a 32 bit integer.
/** @type {?} */
const mask = 1 << bloomHash;
/** @type {?} */
const b7 = bloomHash & 0x80;
/** @type {?} */
const b6 = bloomHash & 0x40;
/** @type {?} */
const b5 = bloomHash & 0x20;
// Our bloom filter size is 256 bits, which is eight 32-bit bloom filter buckets:
// bf0 = [0 - 31], bf1 = [32 - 63], bf2 = [64 - 95], bf3 = [96 - 127], etc.
// Get the bloom filter value from the appropriate bucket based on the directive's bloomBit.
/** @type {?} */
let value;
if (b7) {
value = b6 ? (b5 ? injectorView[injectorIndex + 7] : injectorView[injectorIndex + 6]) :
(b5 ? injectorView[injectorIndex + 5] : injectorView[injectorIndex + 4]);
}
else {
value = b6 ? (b5 ? injectorView[injectorIndex + 3] : injectorView[injectorIndex + 2]) :
(b5 ? injectorView[injectorIndex + 1] : injectorView[injectorIndex]);
}
// If the bloom filter value has the bit corresponding to the directive's bloomBit flipped on,
// this injector is a potential match.
return !!(value & mask);
}
/**
* Returns true if flags prevent parent injector from being searched for tokens
* @param {?} flags
* @param {?} isFirstHostTNode
* @return {?}
*/
function shouldSearchParent(flags, isFirstHostTNode) {
return !(flags & InjectFlags.Self) && !(flags & InjectFlags.Host && isFirstHostTNode);
}
class NodeInjector {
/**
* @param {?} _tNode
* @param {?} _lView
*/
constructor(_tNode, _lView) {
this._tNode = _tNode;
this._lView = _lView;
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
get(token, notFoundValue) {
return getOrCreateInjectable(this._tNode, this._lView, token, undefined, notFoundValue);
}
}
if (false) {}
/**
* \@codeGenApi
* @template T
* @param {?} type
* @return {?}
*/
function ɵɵgetFactoryOf(type) {
/** @type {?} */
const typeAny = (/** @type {?} */ (type));
if (isForwardRef(type)) {
return (/** @type {?} */ (((/**
* @return {?}
*/
() => {
/** @type {?} */
const factory = ɵɵgetFactoryOf(resolveForwardRef(typeAny));
return factory ? factory() : null;
}))));
}
/** @type {?} */
let factory = getFactoryDef(typeAny);
if (factory === null) {
/** @type {?} */
const injectorDef = getInjectorDef(typeAny);
factory = injectorDef && injectorDef.factory;
}
return factory || null;
}
/**
* \@codeGenApi
* @template T
* @param {?} type
* @return {?}
*/
function ɵɵgetInheritedFactory(type) {
return noSideEffects((/**
* @return {?}
*/
() => {
/** @type {?} */
const ownConstructor = type.prototype.constructor;
/** @type {?} */
const ownFactory = ownConstructor[NG_FACTORY_DEF] || ɵɵgetFactoryOf(ownConstructor);
/** @type {?} */
const objectPrototype = Object.prototype;
/** @type {?} */
let parent = Object.getPrototypeOf(type.prototype).constructor;
// Go up the prototype until we hit `Object`.
while (parent && parent !== objectPrototype) {
/** @type {?} */
const factory = parent[NG_FACTORY_DEF] || ɵɵgetFactoryOf(parent);
// If we hit something that has a factory and the factory isn't the same as the type,
// we've found the inherited factory. Note the check that the factory isn't the type's
// own factory is redundant in most cases, but if the user has custom decorators on the
// class, this lookup will start one level down in the prototype chain, causing us to
// find the own factory first and potentially triggering an infinite loop downstream.
if (factory && factory !== ownFactory) {
return factory;
}
parent = Object.getPrototypeOf(parent);
}
// There is no factory defined. Either this was improper usage of inheritance
// (no Angular decorator on the superclass) or there is no constructor at all
// in the inheritance chain. Since the two cases cannot be distinguished, the
// latter has to be assumed.
return (/**
* @param {?} t
* @return {?}
*/
t => new t());
}));
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const ERROR_TYPE = 'ngType';
const ERROR_DEBUG_CONTEXT = 'ngDebugContext';
const ERROR_ORIGINAL_ERROR = 'ngOriginalError';
const ERROR_LOGGER = 'ngErrorLogger';
function wrappedError(message, originalError) {
const msg = `${message} caused by: ${originalError instanceof Error ? originalError.message : originalError}`;
const error = Error(msg);
error[ERROR_ORIGINAL_ERROR] = originalError;
return error;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/errors.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} error
* @return {?}
*/
function getType(error) {
return ((/** @type {?} */ (error)))[ERROR_TYPE];
}
/**
* @param {?} error
* @return {?}
*/
function getDebugContext(error) {
return ((/** @type {?} */ (error)))[ERROR_DEBUG_CONTEXT];
}
/**
* @param {?} error
* @return {?}
*/
function getOriginalError(error) {
return ((/** @type {?} */ (error)))[ERROR_ORIGINAL_ERROR];
}
/**
* @param {?} error
* @return {?}
*/
function getErrorLogger(error) {
return ((/** @type {?} */ (error)))[ERROR_LOGGER] || defaultErrorLogger;
}
/**
* @param {?} console
* @param {...?} values
* @return {?}
*/
function defaultErrorLogger(console, ...values) {
((/** @type {?} */ (console.error)))(...values);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/error_handler.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Provides a hook for centralized exception handling.
*
* The default implementation of `ErrorHandler` prints error messages to the `console`. To
* intercept error handling, write a custom exception handler that replaces this default as
* appropriate for your app.
*
* \@usageNotes
* ### Example
*
* ```
* class MyErrorHandler implements ErrorHandler {
* handleError(error) {
* // do something with the exception
* }
* }
*
* \@NgModule({
* providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
* })
* class MyModule {}
* ```
*
* \@publicApi
*/
class ErrorHandler {
constructor() {
/**
* \@internal
*/
this._console = console;
}
/**
* @param {?} error
* @return {?}
*/
handleError(error) {
/** @type {?} */
const originalError = this._findOriginalError(error);
/** @type {?} */
const context = this._findContext(error);
// Note: Browser consoles show the place from where console.error was called.
// We can use this to give users additional information about the error.
/** @type {?} */
const errorLogger = getErrorLogger(error);
errorLogger(this._console, `ERROR`, error);
if (originalError) {
errorLogger(this._console, `ORIGINAL ERROR`, originalError);
}
if (context) {
errorLogger(this._console, 'ERROR CONTEXT', context);
}
}
/**
* \@internal
* @param {?} error
* @return {?}
*/
_findContext(error) {
if (error) {
return getDebugContext(error) ? getDebugContext(error) :
this._findContext(getOriginalError(error));
}
return null;
}
/**
* \@internal
* @param {?} error
* @return {?}
*/
_findOriginalError(error) {
/** @type {?} */
let e = getOriginalError(error);
while (e && getOriginalError(e)) {
e = getOriginalError(e);
}
return e;
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/metadata/schema.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A schema definition associated with an NgModule.
*
* @see `\@NgModule`, `CUSTOM_ELEMENTS_SCHEMA`, `NO_ERRORS_SCHEMA`
*
* @param name The name of a defined schema.
*
* \@publicApi
* @record
*/
function SchemaMetadata() { }
if (false) {}
/**
* Defines a schema that allows an NgModule to contain the following:
* - Non-Angular elements named with dash case (`-`).
* - Element properties named with dash case (`-`).
* Dash case is the naming convention for custom elements.
*
* \@publicApi
* @type {?}
*/
const CUSTOM_ELEMENTS_SCHEMA = {
name: 'custom-elements'
};
/**
* Defines a schema that allows any property on any element.
*
* \@publicApi
* @type {?}
*/
const NO_ERRORS_SCHEMA = {
name: 'no-errors-schema'
};
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/sanitization/bypass.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @enum {string} */
const BypassType = {
Url: "URL",
Html: "HTML",
ResourceUrl: "ResourceURL",
Script: "Script",
Style: "Style",
};
/**
* Marker interface for a value that's safe to use in a particular context.
*
* \@publicApi
* @record
*/
function SafeValue() { }
/**
* Marker interface for a value that's safe to use as HTML.
*
* \@publicApi
* @record
*/
function SafeHtml() { }
/**
* Marker interface for a value that's safe to use as style (CSS).
*
* \@publicApi
* @record
*/
function SafeStyle() { }
/**
* Marker interface for a value that's safe to use as JavaScript.
*
* \@publicApi
* @record
*/
function SafeScript() { }
/**
* Marker interface for a value that's safe to use as a URL linking to a document.
*
* \@publicApi
* @record
*/
function SafeUrl() { }
/**
* Marker interface for a value that's safe to use as a URL to load executable code from.
*
* \@publicApi
* @record
*/
function SafeResourceUrl() { }
/**
* @abstract
*/
class SafeValueImpl {
/**
* @param {?} changingThisBreaksApplicationSecurity
*/
constructor(changingThisBreaksApplicationSecurity) {
this.changingThisBreaksApplicationSecurity = changingThisBreaksApplicationSecurity;
}
/**
* @return {?}
*/
toString() {
return `SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity}` +
` (see http://g.co/ng/security#xss)`;
}
}
if (false) {}
class SafeHtmlImpl extends SafeValueImpl {
/**
* @return {?}
*/
getTypeName() {
return "HTML" /* Html */;
}
}
class SafeStyleImpl extends SafeValueImpl {
/**
* @return {?}
*/
getTypeName() {
return "Style" /* Style */;
}
}
class SafeScriptImpl extends SafeValueImpl {
/**
* @return {?}
*/
getTypeName() {
return "Script" /* Script */;
}
}
class SafeUrlImpl extends SafeValueImpl {
/**
* @return {?}
*/
getTypeName() {
return "URL" /* Url */;
}
}
class SafeResourceUrlImpl extends SafeValueImpl {
/**
* @return {?}
*/
getTypeName() {
return "ResourceURL" /* ResourceUrl */;
}
}
/**
* @template T
* @param {?} value
* @return {?}
*/
function unwrapSafeValue(value) {
return value instanceof SafeValueImpl ? (/** @type {?} */ ((/** @type {?} */ (value.changingThisBreaksApplicationSecurity)))) :
(/** @type {?} */ ((/** @type {?} */ (value))));
}
/**
* @param {?} value
* @param {?} type
* @return {?}
*/
function allowSanitizationBypassAndThrow(value, type) {
/** @type {?} */
const actualType = getSanitizationBypassType(value);
if (actualType != null && actualType !== type) {
// Allow ResourceURLs in URL contexts, they are strictly more trusted.
if (actualType === "ResourceURL" /* ResourceUrl */ && type === "URL" /* Url */)
return true;
throw new Error(`Required a safe ${type}, got a ${actualType} (see http://g.co/ng/security#xss)`);
}
return actualType === type;
}
/**
* @param {?} value
* @return {?}
*/
function getSanitizationBypassType(value) {
return value instanceof SafeValueImpl && (/** @type {?} */ (value.getTypeName())) || null;
}
/**
* Mark `html` string as trusted.
*
* This function wraps the trusted string in `String` and brands it in a way which makes it
* recognizable to {\@link htmlSanitizer} to be trusted implicitly.
*
* @param {?} trustedHtml `html` string which needs to be implicitly trusted.
* @return {?} a `html` which has been branded to be implicitly trusted.
*/
function bypassSanitizationTrustHtml(trustedHtml) {
return new SafeHtmlImpl(trustedHtml);
}
/**
* Mark `style` string as trusted.
*
* This function wraps the trusted string in `String` and brands it in a way which makes it
* recognizable to {\@link styleSanitizer} to be trusted implicitly.
*
* @param {?} trustedStyle `style` string which needs to be implicitly trusted.
* @return {?} a `style` hich has been branded to be implicitly trusted.
*/
function bypassSanitizationTrustStyle(trustedStyle) {
return new SafeStyleImpl(trustedStyle);
}
/**
* Mark `script` string as trusted.
*
* This function wraps the trusted string in `String` and brands it in a way which makes it
* recognizable to {\@link scriptSanitizer} to be trusted implicitly.
*
* @param {?} trustedScript `script` string which needs to be implicitly trusted.
* @return {?} a `script` which has been branded to be implicitly trusted.
*/
function bypassSanitizationTrustScript(trustedScript) {
return new SafeScriptImpl(trustedScript);
}
/**
* Mark `url` string as trusted.
*
* This function wraps the trusted string in `String` and brands it in a way which makes it
* recognizable to {\@link urlSanitizer} to be trusted implicitly.
*
* @param {?} trustedUrl `url` string which needs to be implicitly trusted.
* @return {?} a `url` which has been branded to be implicitly trusted.
*/
function bypassSanitizationTrustUrl(trustedUrl) {
return new SafeUrlImpl(trustedUrl);
}
/**
* Mark `url` string as trusted.
*
* This function wraps the trusted string in `String` and brands it in a way which makes it
* recognizable to {\@link resourceUrlSanitizer} to be trusted implicitly.
*
* @param {?} trustedResourceUrl `url` string which needs to be implicitly trusted.
* @return {?} a `url` which has been branded to be implicitly trusted.
*/
function bypassSanitizationTrustResourceUrl(trustedResourceUrl) {
return new SafeResourceUrlImpl(trustedResourceUrl);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This file is used to control if the default rendering pipeline should be `ViewEngine` or `Ivy`.
*
* For more information on how to run and debug tests with either Ivy or View Engine (legacy),
* please see [BAZEL.md](./docs/BAZEL.md).
*/
let _devMode = true;
let _runModeLocked = false;
/**
* Returns whether Angular is in development mode. After called once,
* the value is locked and won't change any more.
*
* By default, this is true, unless a user calls `enableProdMode` before calling this.
*
* @publicApi
*/
function isDevMode() {
_runModeLocked = true;
return _devMode;
}
/**
* Disable Angular's development mode, which turns off assertions and other
* checks within the framework.
*
* One important assertion this disables verifies that a change detection pass
* does not result in additional changes to any bindings (also known as
* unidirectional data flow).
*
* @publicApi
*/
function enableProdMode() {
if (_runModeLocked) {
throw new Error('Cannot enable prod mode after platform setup.');
}
// The below check is there so when ngDevMode is set via terser
// `global['ngDevMode'] = false;` is also dropped.
if (typeof ngDevMode === undefined || !!ngDevMode) {
_global['ngDevMode'] = false;
}
_devMode = false;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/sanitization/inert_body.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This helper class is used to get hold of an inert tree of DOM elements containing dirty HTML
* that needs sanitizing.
* Depending upon browser support we must use one of three strategies for doing this.
* Support: Safari 10.x -> XHR strategy
* Support: Firefox -> DomParser strategy
* Default: InertDocument strategy
*/
class InertBodyHelper {
/**
* @param {?} defaultDoc
*/
constructor(defaultDoc) {
this.defaultDoc = defaultDoc;
this.inertDocument = this.defaultDoc.implementation.createHTMLDocument('sanitization-inert');
/** @type {?} */
let inertBodyElement = this.inertDocument.body;
if (inertBodyElement == null) {
// usually there should be only one body element in the document, but IE doesn't have any, so
// we need to create one.
/** @type {?} */
const inertHtml = this.inertDocument.createElement('html');
this.inertDocument.appendChild(inertHtml);
inertBodyElement = this.inertDocument.createElement('body');
inertHtml.appendChild(inertBodyElement);
}
inertBodyElement.innerHTML = '<svg><g onload="this.parentNode.remove()"></g></svg>';
if (inertBodyElement.querySelector && !inertBodyElement.querySelector('svg')) {
// We just hit the Safari 10.1 bug - which allows JS to run inside the SVG G element
// so use the XHR strategy.
this.getInertBodyElement = this.getInertBodyElement_XHR;
return;
}
inertBodyElement.innerHTML = '<svg><p><style><img src="</style><img src=x onerror=alert(1)//">';
if (inertBodyElement.querySelector && inertBodyElement.querySelector('svg img')) {
// We just hit the Firefox bug - which prevents the inner img JS from being sanitized
// so use the DOMParser strategy, if it is available.
// If the DOMParser is not available then we are not in Firefox (Server/WebWorker?) so we
// fall through to the default strategy below.
if (isDOMParserAvailable()) {
this.getInertBodyElement = this.getInertBodyElement_DOMParser;
return;
}
}
// None of the bugs were hit so it is safe for us to use the default InertDocument strategy
this.getInertBodyElement = this.getInertBodyElement_InertDocument;
}
/**
* Use XHR to create and fill an inert body element (on Safari 10.1)
* See
* https://github.com/cure53/DOMPurify/blob/a992d3a75031cb8bb032e5ea8399ba972bdf9a65/src/purify.js#L439-L449
* @private
* @param {?} html
* @return {?}
*/
getInertBodyElement_XHR(html) {
// We add these extra elements to ensure that the rest of the content is parsed as expected
// e.g. leading whitespace is maintained and tags like `<meta>` do not get hoisted to the
// `<head>` tag.
html = '<body><remove></remove>' + html + '</body>';
try {
html = encodeURI(html);
}
catch (_a) {
return null;
}
/** @type {?} */
const xhr = new XMLHttpRequest();
xhr.responseType = 'document';
xhr.open('GET', 'data:text/html;charset=utf-8,' + html, false);
xhr.send(undefined);
/** @type {?} */
const body = xhr.response.body;
body.removeChild((/** @type {?} */ (body.firstChild)));
return body;
}
/**
* Use DOMParser to create and fill an inert body element (on Firefox)
* See https://github.com/cure53/DOMPurify/releases/tag/0.6.7
*
* @private
* @param {?} html
* @return {?}
*/
getInertBodyElement_DOMParser(html) {
// We add these extra elements to ensure that the rest of the content is parsed as expected
// e.g. leading whitespace is maintained and tags like `<meta>` do not get hoisted to the
// `<head>` tag.
html = '<body><remove></remove>' + html + '</body>';
try {
/** @type {?} */
const body = (/** @type {?} */ (new ((/** @type {?} */ (window))).DOMParser().parseFromString(html, 'text/html').body));
body.removeChild((/** @type {?} */ (body.firstChild)));
return body;
}
catch (_a) {
return null;
}
}
/**
* Use an HTML5 `template` element, if supported, or an inert body element created via
* `createHtmlDocument` to create and fill an inert DOM element.
* This is the default sane strategy to use if the browser does not require one of the specialised
* strategies above.
* @private
* @param {?} html
* @return {?}
*/
getInertBodyElement_InertDocument(html) {
// Prefer using <template> element if supported.
/** @type {?} */
const templateEl = this.inertDocument.createElement('template');
if ('content' in templateEl) {
templateEl.innerHTML = html;
return templateEl;
}
// Note that previously we used to do something like `this.inertDocument.body.innerHTML = html`
// and we returned the inert `body` node. This was changed, because IE seems to treat setting
// `innerHTML` on an inserted element differently, compared to one that hasn't been inserted
// yet. In particular, IE appears to split some of the text into multiple text nodes rather
// than keeping them in a single one which ends up messing with Ivy's i18n parsing further
// down the line. This has been worked around by creating a new inert `body` and using it as
// the root node in which we insert the HTML.
/** @type {?} */
const inertBody = this.inertDocument.createElement('body');
inertBody.innerHTML = html;
// Support: IE 9-11 only
// strip custom-namespaced attributes on IE<=11
if (((/** @type {?} */ (this.defaultDoc))).documentMode) {
this.stripCustomNsAttrs(inertBody);
}
return inertBody;
}
/**
* When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1'
* attribute to declare ns1 namespace and prefixes the attribute with 'ns1' (e.g.
* 'ns1:xlink:foo').
*
* This is undesirable since we don't want to allow any of these custom attributes. This method
* strips them all.
* @private
* @param {?} el
* @return {?}
*/
stripCustomNsAttrs(el) {
/** @type {?} */
const elAttrs = el.attributes;
// loop backwards so that we can support removals.
for (let i = elAttrs.length - 1; 0 < i; i--) {
/** @type {?} */
const attrib = elAttrs.item(i);
/** @type {?} */
const attrName = (/** @type {?} */ (attrib)).name;
if (attrName === 'xmlns:ns1' || attrName.indexOf('ns1:') === 0) {
el.removeAttribute(attrName);
}
}
/** @type {?} */
let childNode = (/** @type {?} */ (el.firstChild));
while (childNode) {
if (childNode.nodeType === Node.ELEMENT_NODE)
this.stripCustomNsAttrs((/** @type {?} */ (childNode)));
childNode = childNode.nextSibling;
}
}
}
if (false) {}
/**
* We need to determine whether the DOMParser exists in the global context.
* The try-catch is because, on some browsers, trying to access this property
* on window can actually throw an error.
*
* @suppress {uselessCode}
* @return {?}
*/
function isDOMParserAvailable() {
try {
return !!((/** @type {?} */ (window))).DOMParser;
}
catch (_a) {
return false;
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/sanitization/url_sanitizer.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A pattern that recognizes a commonly useful subset of URLs that are safe.
*
* This regular expression matches a subset of URLs that will not cause script
* execution if used in URL context within a HTML document. Specifically, this
* regular expression matches if (comment from here on and regex copied from
* Soy's EscapingConventions):
* (1) Either an allowed protocol (http, https, mailto or ftp).
* (2) or no protocol. A protocol must be followed by a colon. The below
* allows that by allowing colons only after one of the characters [/?#].
* A colon after a hash (#) must be in the fragment.
* Otherwise, a colon after a (?) must be in a query.
* Otherwise, a colon after a single solidus (/) must be in a path.
* Otherwise, a colon after a double solidus (//) must be in the authority
* (before port).
*
* The pattern disallows &, used in HTML entity declarations before
* one of the characters in [/?#]. This disallows HTML entities used in the
* protocol name, which should never happen, e.g. "http" for "http".
* It also disallows HTML entities in the first path part of a relative path,
* e.g. "foo<bar/baz". Our existing escaping functions should not produce
* that. More importantly, it disallows masking of a colon,
* e.g. "javascript:...".
*
* This regular expression was taken from the Closure sanitization library.
* @type {?}
*/
const SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi;
/* A pattern that matches safe srcset values */
/** @type {?} */
const SAFE_SRCSET_PATTERN = /^(?:(?:https?|file):|[^&:/?#]*(?:[/?#]|$))/gi;
/**
* A pattern that matches safe data URLs. Only matches image, video and audio types.
* @type {?}
*/
const DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+\/]+=*$/i;
/**
* @param {?} url
* @return {?}
*/
function _sanitizeUrl(url) {
url = String(url);
if (url.match(SAFE_URL_PATTERN) || url.match(DATA_URL_PATTERN))
return url;
if (isDevMode()) {
console.warn(`WARNING: sanitizing unsafe URL value ${url} (see http://g.co/ng/security#xss)`);
}
return 'unsafe:' + url;
}
/**
* @param {?} srcset
* @return {?}
*/
function sanitizeSrcset(srcset) {
srcset = String(srcset);
return srcset.split(',').map((/**
* @param {?} srcset
* @return {?}
*/
(srcset) => _sanitizeUrl(srcset.trim()))).join(', ');
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/sanitization/html_sanitizer.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} tags
* @return {?}
*/
function tagSet(tags) {
/** @type {?} */
const res = {};
for (const t of tags.split(','))
res[t] = true;
return res;
}
/**
* @param {...?} sets
* @return {?}
*/
function merge(...sets) {
/** @type {?} */
const res = {};
for (const s of sets) {
for (const v in s) {
if (s.hasOwnProperty(v))
res[v] = true;
}
}
return res;
}
// Good source of info about elements and attributes
// http://dev.w3.org/html5/spec/Overview.html#semantics
// http://simon.html5.org/html-elements
// Safe Void Elements - HTML5
// http://dev.w3.org/html5/spec/Overview.html#void-elements
/** @type {?} */
const VOID_ELEMENTS = tagSet('area,br,col,hr,img,wbr');
// Elements that you can, intentionally, leave open (and which close themselves)
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
/** @type {?} */
const OPTIONAL_END_TAG_BLOCK_ELEMENTS = tagSet('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr');
/** @type {?} */
const OPTIONAL_END_TAG_INLINE_ELEMENTS = tagSet('rp,rt');
/** @type {?} */
const OPTIONAL_END_TAG_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, OPTIONAL_END_TAG_BLOCK_ELEMENTS);
// Safe Block Elements - HTML5
/** @type {?} */
const BLOCK_ELEMENTS = merge(OPTIONAL_END_TAG_BLOCK_ELEMENTS, tagSet('address,article,' +
'aside,blockquote,caption,center,del,details,dialog,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
'h6,header,hgroup,hr,ins,main,map,menu,nav,ol,pre,section,summary,table,ul'));
// Inline Elements - HTML5
/** @type {?} */
const INLINE_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, tagSet('a,abbr,acronym,audio,b,' +
'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,picture,q,ruby,rp,rt,s,' +
'samp,small,source,span,strike,strong,sub,sup,time,track,tt,u,var,video'));
/** @type {?} */
const VALID_ELEMENTS = merge(VOID_ELEMENTS, BLOCK_ELEMENTS, INLINE_ELEMENTS, OPTIONAL_END_TAG_ELEMENTS);
// Attributes that have href and hence need to be sanitized
/** @type {?} */
const URI_ATTRS = tagSet('background,cite,href,itemtype,longdesc,poster,src,xlink:href');
// Attributes that have special href set hence need to be sanitized
/** @type {?} */
const SRCSET_ATTRS = tagSet('srcset');
/** @type {?} */
const HTML_ATTRS = tagSet('abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,' +
'compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,' +
'ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,' +
'scope,scrolling,shape,size,sizes,span,srclang,start,summary,tabindex,target,title,translate,type,usemap,' +
'valign,value,vspace,width');
// Accessibility attributes as per WAI-ARIA 1.1 (W3C Working Draft 14 December 2018)
/** @type {?} */
const ARIA_ATTRS = tagSet('aria-activedescendant,aria-atomic,aria-autocomplete,aria-busy,aria-checked,aria-colcount,aria-colindex,' +
'aria-colspan,aria-controls,aria-current,aria-describedby,aria-details,aria-disabled,aria-dropeffect,' +
'aria-errormessage,aria-expanded,aria-flowto,aria-grabbed,aria-haspopup,aria-hidden,aria-invalid,' +
'aria-keyshortcuts,aria-label,aria-labelledby,aria-level,aria-live,aria-modal,aria-multiline,' +
'aria-multiselectable,aria-orientation,aria-owns,aria-placeholder,aria-posinset,aria-pressed,aria-readonly,' +
'aria-relevant,aria-required,aria-roledescription,aria-rowcount,aria-rowindex,aria-rowspan,aria-selected,' +
'aria-setsize,aria-sort,aria-valuemax,aria-valuemin,aria-valuenow,aria-valuetext');
// NB: This currently consciously doesn't support SVG. SVG sanitization has had several security
// issues in the past, so it seems safer to leave it out if possible. If support for binding SVG via
// innerHTML is required, SVG attributes should be added here.
// NB: Sanitization does not allow <form> elements or other active elements (<button> etc). Those
// can be sanitized, but they increase security surface area without a legitimate use case, so they
// are left out here.
/** @type {?} */
const VALID_ATTRS = merge(URI_ATTRS, SRCSET_ATTRS, HTML_ATTRS, ARIA_ATTRS);
// Elements whose content should not be traversed/preserved, if the elements themselves are invalid.
//
// Typically, `<invalid>Some content</invalid>` would traverse (and in this case preserve)
// `Some content`, but strip `invalid-element` opening/closing tags. For some elements, though, we
// don't want to preserve the content, if the elements themselves are going to be removed.
/** @type {?} */
const SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS = tagSet('script,style,template');
/**
* SanitizingHtmlSerializer serializes a DOM fragment, stripping out any unsafe elements and unsafe
* attributes.
*/
class SanitizingHtmlSerializer {
constructor() {
// Explicitly track if something was stripped, to avoid accidentally warning of sanitization just
// because characters were re-encoded.
this.sanitizedSomething = false;
this.buf = [];
}
/**
* @param {?} el
* @return {?}
*/
sanitizeChildren(el) {
// This cannot use a TreeWalker, as it has to run on Angular's various DOM adapters.
// However this code never accesses properties off of `document` before deleting its contents
// again, so it shouldn't be vulnerable to DOM clobbering.
/** @type {?} */
let current = (/** @type {?} */ (el.firstChild));
/** @type {?} */
let traverseContent = true;
while (current) {
if (current.nodeType === Node.ELEMENT_NODE) {
traverseContent = this.startElement((/** @type {?} */ (current)));
}
else if (current.nodeType === Node.TEXT_NODE) {
this.chars((/** @type {?} */ (current.nodeValue)));
}
else {
// Strip non-element, non-text nodes.
this.sanitizedSomething = true;
}
if (traverseContent && current.firstChild) {
current = (/** @type {?} */ (current.firstChild));
continue;
}
while (current) {
// Leaving the element. Walk up and to the right, closing tags as we go.
if (current.nodeType === Node.ELEMENT_NODE) {
this.endElement((/** @type {?} */ (current)));
}
/** @type {?} */
let next = this.checkClobberedElement(current, (/** @type {?} */ (current.nextSibling)));
if (next) {
current = next;
break;
}
current = this.checkClobberedElement(current, (/** @type {?} */ (current.parentNode)));
}
}
return this.buf.join('');
}
/**
* Sanitizes an opening element tag (if valid) and returns whether the element's contents should
* be traversed. Element content must always be traversed (even if the element itself is not
* valid/safe), unless the element is one of `SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS`.
*
* @private
* @param {?} element The element to sanitize.
* @return {?} True if the element's contents should be traversed.
*/
startElement(element) {
/** @type {?} */
const tagName = element.nodeName.toLowerCase();
if (!VALID_ELEMENTS.hasOwnProperty(tagName)) {
this.sanitizedSomething = true;
return !SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS.hasOwnProperty(tagName);
}
this.buf.push('<');
this.buf.push(tagName);
/** @type {?} */
const elAttrs = element.attributes;
for (let i = 0; i < elAttrs.length; i++) {
/** @type {?} */
const elAttr = elAttrs.item(i);
/** @type {?} */
const attrName = (/** @type {?} */ (elAttr)).name;
/** @type {?} */
const lower = attrName.toLowerCase();
if (!VALID_ATTRS.hasOwnProperty(lower)) {
this.sanitizedSomething = true;
continue;
}
/** @type {?} */
let value = (/** @type {?} */ (elAttr)).value;
// TODO(martinprobst): Special case image URIs for data:image/...
if (URI_ATTRS[lower])
value = _sanitizeUrl(value);
if (SRCSET_ATTRS[lower])
value = sanitizeSrcset(value);
this.buf.push(' ', attrName, '="', encodeEntities(value), '"');
}
this.buf.push('>');
return true;
}
/**
* @private
* @param {?} current
* @return {?}
*/
endElement(current) {
/** @type {?} */
const tagName = current.nodeName.toLowerCase();
if (VALID_ELEMENTS.hasOwnProperty(tagName) && !VOID_ELEMENTS.hasOwnProperty(tagName)) {
this.buf.push('</');
this.buf.push(tagName);
this.buf.push('>');
}
}
/**
* @private
* @param {?} chars
* @return {?}
*/
chars(chars) {
this.buf.push(encodeEntities(chars));
}
/**
* @param {?} node
* @param {?} nextNode
* @return {?}
*/
checkClobberedElement(node, nextNode) {
if (nextNode &&
(node.compareDocumentPosition(nextNode) &
Node.DOCUMENT_POSITION_CONTAINED_BY) === Node.DOCUMENT_POSITION_CONTAINED_BY) {
throw new Error(`Failed to sanitize html because the element is clobbered: ${((/** @type {?} */ (node))).outerHTML}`);
}
return nextNode;
}
}
if (false) {}
// Regular Expressions for parsing tags and attributes
/** @type {?} */
const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
// ! to ~ is the ASCII range.
/** @type {?} */
const NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g;
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param {?} value
* @return {?}
*/
function encodeEntities(value) {
return value.replace(/&/g, '&')
.replace(SURROGATE_PAIR_REGEXP, (/**
* @param {?} match
* @return {?}
*/
function (match) {
/** @type {?} */
const hi = match.charCodeAt(0);
/** @type {?} */
const low = match.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
}))
.replace(NON_ALPHANUMERIC_REGEXP, (/**
* @param {?} match
* @return {?}
*/
function (match) {
return '&#' + match.charCodeAt(0) + ';';
}))
.replace(/</g, '<')
.replace(/>/g, '>');
}
/** @type {?} */
let inertBodyHelper;
/**
* Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to
* the DOM in a browser environment.
* @param {?} defaultDoc
* @param {?} unsafeHtmlInput
* @return {?}
*/
function _sanitizeHtml(defaultDoc, unsafeHtmlInput) {
/** @type {?} */
let inertBodyElement = null;
try {
inertBodyHelper = inertBodyHelper || new InertBodyHelper(defaultDoc);
// Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).
/** @type {?} */
let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';
inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
// mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser
// trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.
/** @type {?} */
let mXSSAttempts = 5;
/** @type {?} */
let parsedHtml = unsafeHtml;
do {
if (mXSSAttempts === 0) {
throw new Error('Failed to sanitize html because the input is unstable');
}
mXSSAttempts--;
unsafeHtml = parsedHtml;
parsedHtml = (/** @type {?} */ (inertBodyElement)).innerHTML;
inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
} while (unsafeHtml !== parsedHtml);
/** @type {?} */
const sanitizer = new SanitizingHtmlSerializer();
/** @type {?} */
const safeHtml = sanitizer.sanitizeChildren((/** @type {?} */ (getTemplateContent((/** @type {?} */ (inertBodyElement))))) || inertBodyElement);
if (isDevMode() && sanitizer.sanitizedSomething) {
console.warn('WARNING: sanitizing HTML stripped some content, see http://g.co/ng/security#xss');
}
return safeHtml;
}
finally {
// In case anything goes wrong, clear out inertElement to reset the entire DOM structure.
if (inertBodyElement) {
/** @type {?} */
const parent = getTemplateContent(inertBodyElement) || inertBodyElement;
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
}
}
/**
* @param {?} el
* @return {?}
*/
function getTemplateContent(el) {
return 'content' in ((/** @type {?} */ (el))) && isTemplateElement(el) ?
el.content :
null;
}
/**
* @param {?} el
* @return {?}
*/
function isTemplateElement(el) {
return el.nodeType === Node.ELEMENT_NODE && el.nodeName === 'TEMPLATE';
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/sanitization/security.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @enum {number} */
const SecurityContext = {
NONE: 0,
HTML: 1,
STYLE: 2,
SCRIPT: 3,
URL: 4,
RESOURCE_URL: 5,
};
SecurityContext[SecurityContext.NONE] = 'NONE';
SecurityContext[SecurityContext.HTML] = 'HTML';
SecurityContext[SecurityContext.STYLE] = 'STYLE';
SecurityContext[SecurityContext.SCRIPT] = 'SCRIPT';
SecurityContext[SecurityContext.URL] = 'URL';
SecurityContext[SecurityContext.RESOURCE_URL] = 'RESOURCE_URL';
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/sanitization/style_sanitizer.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Regular expression for safe style values.
*
* Quotes (" and ') are allowed, but a check must be done elsewhere to ensure they're balanced.
*
* ',' allows multiple values to be assigned to the same property (e.g. background-attachment or
* font-family) and hence could allow multiple values to get injected, but that should pose no risk
* of XSS.
*
* The function expression checks only for XSS safety, not for CSS validity.
*
* This regular expression was taken from the Closure sanitization library, and augmented for
* transformation values.
* @type {?}
*/
const VALUES = '[-,."\'%_!# a-zA-Z0-9]+';
/** @type {?} */
const TRANSFORMATION_FNS = '(?:matrix|translate|scale|rotate|skew|perspective)(?:X|Y|Z|3d)?';
/** @type {?} */
const COLOR_FNS = '(?:rgb|hsl)a?';
/** @type {?} */
const GRADIENTS = '(?:repeating-)?(?:linear|radial)-gradient';
/** @type {?} */
const CSS3_FNS = '(?:attr|calc|var)';
/** @type {?} */
const FN_ARGS = '\\([-0-9.%, #a-zA-Z]+\\)';
/** @type {?} */
const SAFE_STYLE_VALUE = new RegExp(`^(${VALUES}|` +
`(?:${TRANSFORMATION_FNS}|${COLOR_FNS}|${GRADIENTS}|${CSS3_FNS})` +
`${FN_ARGS})$`, 'g');
/**
* Matches a `url(...)` value with an arbitrary argument as long as it does
* not contain parentheses.
*
* The URL value still needs to be sanitized separately.
*
* `url(...)` values are a very common use case, e.g. for `background-image`. With carefully crafted
* CSS style rules, it is possible to construct an information leak with `url` values in CSS, e.g.
* by observing whether scroll bars are displayed, or character ranges used by a font face
* definition.
*
* Angular only allows binding CSS values (as opposed to entire CSS rules), so it is unlikely that
* binding a URL value without further cooperation from the page will cause an information leak, and
* if so, it is just a leak, not a full blown XSS vulnerability.
*
* Given the common use case, low likelihood of attack vector, and low impact of an attack, this
* code is permissive and allows URLs that sanitize otherwise.
* @type {?}
*/
const URL_RE = /^url\(([^)]+)\)$/;
/**
* Checks that quotes (" and ') are properly balanced inside a string. Assumes
* that neither escape (\) nor any other character that could result in
* breaking out of a string parsing context are allowed;
* see http://www.w3.org/TR/css3-syntax/#string-token-diagram.
*
* This code was taken from the Closure sanitization library.
* @param {?} value
* @return {?}
*/
function hasBalancedQuotes(value) {
/** @type {?} */
let outsideSingle = true;
/** @type {?} */
let outsideDouble = true;
for (let i = 0; i < value.length; i++) {
/** @type {?} */
const c = value.charAt(i);
if (c === '\'' && outsideDouble) {
outsideSingle = !outsideSingle;
}
else if (c === '"' && outsideSingle) {
outsideDouble = !outsideDouble;
}
}
return outsideSingle && outsideDouble;
}
/**
* Sanitizes the given untrusted CSS style property value (i.e. not an entire object, just a single
* value) and returns a value that is safe to use in a browser environment.
* @param {?} value
* @return {?}
*/
function _sanitizeStyle(value) {
value = String(value).trim(); // Make sure it's actually a string.
if (!value)
return '';
// Single url(...) values are supported, but only for URLs that sanitize cleanly. See above for
// reasoning behind this.
/** @type {?} */
const urlMatch = value.match(URL_RE);
if ((urlMatch && _sanitizeUrl(urlMatch[1]) === urlMatch[1]) ||
value.match(SAFE_STYLE_VALUE) && hasBalancedQuotes(value)) {
return value; // Safe style values.
}
if (isDevMode()) {
console.warn(`WARNING: sanitizing unsafe style value ${value} (see http://g.co/ng/security#xss).`);
}
return 'unsafe';
}
/** @enum {number} */
const StyleSanitizeMode = {
/** Just check to see if the property is required to be sanitized or not */
ValidateProperty: 1,
/** Skip checking the property; just sanitize the value */
SanitizeOnly: 2,
/** Check the property and (if true) then sanitize the value */
ValidateAndSanitize: 3,
};
/**
* Used to intercept and sanitize style values before they are written to the renderer.
*
* This function is designed to be called in two modes. When a value is not provided
* then the function will return a boolean whether a property will be sanitized later.
* If a value is provided then the sanitized version of that will be returned.
* @record
*/
function StyleSanitizeFn() { }
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/sanitization/sanitization.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* An `html` sanitizer which converts untrusted `html` **string** into trusted string by removing
* dangerous content.
*
* This method parses the `html` and locates potentially dangerous content (such as urls and
* javascript) and removes it.
*
* It is possible to mark a string as trusted by calling {\@link bypassSanitizationTrustHtml}.
*
* \@publicApi
* @param {?} unsafeHtml untrusted `html`, typically from the user.
* @return {?} `html` string which is safe to display to user, because all of the dangerous javascript
* and urls have been removed.
*
*/
function ɵɵsanitizeHtml(unsafeHtml) {
/** @type {?} */
const sanitizer = getSanitizer();
if (sanitizer) {
return sanitizer.sanitize(SecurityContext.HTML, unsafeHtml) || '';
}
if (allowSanitizationBypassAndThrow(unsafeHtml, "HTML" /* Html */)) {
return unwrapSafeValue(unsafeHtml);
}
return _sanitizeHtml(getDocument(), renderStringify(unsafeHtml));
}
/**
* A `style` sanitizer which converts untrusted `style` **string** into trusted string by removing
* dangerous content.
*
* This method parses the `style` and locates potentially dangerous content (such as urls and
* javascript) and removes it.
*
* It is possible to mark a string as trusted by calling {\@link bypassSanitizationTrustStyle}.
*
* \@publicApi
* @param {?} unsafeStyle untrusted `style`, typically from the user.
* @return {?} `style` string which is safe to bind to the `style` properties, because all of the
* dangerous javascript and urls have been removed.
*
*/
function ɵɵsanitizeStyle(unsafeStyle) {
/** @type {?} */
const sanitizer = getSanitizer();
if (sanitizer) {
return sanitizer.sanitize(SecurityContext.STYLE, unsafeStyle) || '';
}
if (allowSanitizationBypassAndThrow(unsafeStyle, "Style" /* Style */)) {
return unwrapSafeValue(unsafeStyle);
}
return _sanitizeStyle(renderStringify(unsafeStyle));
}
/**
* A `url` sanitizer which converts untrusted `url` **string** into trusted string by removing
* dangerous
* content.
*
* This method parses the `url` and locates potentially dangerous content (such as javascript) and
* removes it.
*
* It is possible to mark a string as trusted by calling {\@link bypassSanitizationTrustUrl}.
*
* \@publicApi
* @param {?} unsafeUrl untrusted `url`, typically from the user.
* @return {?} `url` string which is safe to bind to the `src` properties such as `<img src>`, because
* all of the dangerous javascript has been removed.
*
*/
function ɵɵsanitizeUrl(unsafeUrl) {
/** @type {?} */
const sanitizer = getSanitizer();
if (sanitizer) {
return sanitizer.sanitize(SecurityContext.URL, unsafeUrl) || '';
}
if (allowSanitizationBypassAndThrow(unsafeUrl, "URL" /* Url */)) {
return unwrapSafeValue(unsafeUrl);
}
return _sanitizeUrl(renderStringify(unsafeUrl));
}
/**
* A `url` sanitizer which only lets trusted `url`s through.
*
* This passes only `url`s marked trusted by calling {\@link bypassSanitizationTrustResourceUrl}.
*
* \@publicApi
* @param {?} unsafeResourceUrl untrusted `url`, typically from the user.
* @return {?} `url` string which is safe to bind to the `src` properties such as `<img src>`, because
* only trusted `url`s have been allowed to pass.
*
*/
function ɵɵsanitizeResourceUrl(unsafeResourceUrl) {
/** @type {?} */
const sanitizer = getSanitizer();
if (sanitizer) {
return sanitizer.sanitize(SecurityContext.RESOURCE_URL, unsafeResourceUrl) || '';
}
if (allowSanitizationBypassAndThrow(unsafeResourceUrl, "ResourceURL" /* ResourceUrl */)) {
return unwrapSafeValue(unsafeResourceUrl);
}
throw new Error('unsafe value used in a resource URL context (see http://g.co/ng/security#xss)');
}
/**
* A `script` sanitizer which only lets trusted javascript through.
*
* This passes only `script`s marked trusted by calling {\@link
* bypassSanitizationTrustScript}.
*
* \@publicApi
* @param {?} unsafeScript untrusted `script`, typically from the user.
* @return {?} `url` string which is safe to bind to the `<script>` element such as `<img src>`,
* because only trusted `scripts` have been allowed to pass.
*
*/
function ɵɵsanitizeScript(unsafeScript) {
/** @type {?} */
const sanitizer = getSanitizer();
if (sanitizer) {
return sanitizer.sanitize(SecurityContext.SCRIPT, unsafeScript) || '';
}
if (allowSanitizationBypassAndThrow(unsafeScript, "Script" /* Script */)) {
return unwrapSafeValue(unsafeScript);
}
throw new Error('unsafe value used in a script context');
}
/**
* Detects which sanitizer to use for URL property, based on tag name and prop name.
*
* The rules are based on the RESOURCE_URL context config from
* `packages/compiler/src/schema/dom_security_schema.ts`.
* If tag and prop names don't match Resource URL schema, use URL sanitizer.
* @param {?} tag
* @param {?} prop
* @return {?}
*/
function getUrlSanitizer(tag, prop) {
if ((prop === 'src' &&
(tag === 'embed' || tag === 'frame' || tag === 'iframe' || tag === 'media' ||
tag === 'script')) ||
(prop === 'href' && (tag === 'base' || tag === 'link'))) {
return ɵɵsanitizeResourceUrl;
}
return ɵɵsanitizeUrl;
}
/**
* Sanitizes URL, selecting sanitizer function based on tag and property names.
*
* This function is used in case we can't define security context at compile time, when only prop
* name is available. This happens when we generate host bindings for Directives/Components. The
* host element is unknown at compile time, so we defer calculation of specific sanitizer to
* runtime.
*
* \@publicApi
* @param {?} unsafeUrl untrusted `url`, typically from the user.
* @param {?} tag target element tag name.
* @param {?} prop name of the property that contains the value.
* @return {?} `url` string which is safe to bind.
*
*/
function ɵɵsanitizeUrlOrResourceUrl(unsafeUrl, tag, prop) {
return getUrlSanitizer(tag, prop)(unsafeUrl);
}
/**
* The default style sanitizer will handle sanitization for style properties by
* sanitizing any CSS property that can include a `url` value (usually image-based properties)
*
* \@publicApi
* @type {?}
*/
const ɵɵdefaultStyleSanitizer = ((/** @type {?} */ ((/**
* @param {?} prop
* @param {?} value
* @param {?=} mode
* @return {?}
*/
function (prop, value, mode) {
if (value === undefined && mode === undefined) {
// This is a workaround for the fact that `StyleSanitizeFn` should not exist once PR#34480
// lands. For now the `StyleSanitizeFn` and should act like `(value: any) => string` as a
// work around.
return ɵɵsanitizeStyle(prop);
}
mode = mode || 3 /* ValidateAndSanitize */;
/** @type {?} */
let doSanitizeValue = true;
if (mode & 1 /* ValidateProperty */) {
doSanitizeValue = stylePropNeedsSanitization(prop);
}
if (mode & 2 /* SanitizeOnly */) {
return doSanitizeValue ? ɵɵsanitizeStyle(value) : unwrapSafeValue(value);
}
else {
return doSanitizeValue;
}
}))));
/**
* @param {?} prop
* @return {?}
*/
function stylePropNeedsSanitization(prop) {
return prop === 'background-image' || prop === 'backgroundImage' || prop === 'background' ||
prop === 'border-image' || prop === 'borderImage' || prop === 'border-image-source' ||
prop === 'borderImageSource' || prop === 'filter' || prop === 'list-style' ||
prop === 'listStyle' || prop === 'list-style-image' || prop === 'listStyleImage' ||
prop === 'clip-path' || prop === 'clipPath';
}
/**
* @param {?} name
* @return {?}
*/
function validateAgainstEventProperties(name) {
if (name.toLowerCase().startsWith('on')) {
/** @type {?} */
const msg = `Binding to event property '${name}' is disallowed for security reasons, ` +
`please use (${name.slice(2)})=...` +
`\nIf '${name}' is a directive input, make sure the directive is imported by the` +
` current module.`;
throw new Error(msg);
}
}
/**
* @param {?} name
* @return {?}
*/
function validateAgainstEventAttributes(name) {
if (name.toLowerCase().startsWith('on')) {
/** @type {?} */
const msg = `Binding to event attribute '${name}' is disallowed for security reasons, ` +
`please use (${name.slice(2)})=...`;
throw new Error(msg);
}
}
/**
* @return {?}
*/
function getSanitizer() {
/** @type {?} */
const lView = getLView();
return lView && lView[SANITIZER];
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const END_COMMENT = /-->/g;
const END_COMMENT_ESCAPED = '-\u200B-\u200B>';
/**
* Escape the content of the strings so that it can be safely inserted into a comment node.
*
* The issue is that HTML does not specify any way to escape comment end text inside the comment.
* `<!-- The way you close a comment is with "-->". -->`. Above the `"-->"` is meant to be text not
* an end to the comment. This can be created programmatically through DOM APIs.
*
* ```
* div.innerHTML = div.innerHTML
* ```
*
* One would expect that the above code would be safe to do, but it turns out that because comment
* text is not escaped, the comment may contain text which will prematurely close the comment
* opening up the application for XSS attack. (In SSR we programmatically create comment nodes which
* may contain such text and expect them to be safe.)
*
* This function escapes the comment text by looking for the closing char sequence `-->` and replace
* it with `-_-_>` where the `_` is a zero width space `\u200B`. The result is that if a comment
* contains `-->` text it will render normally but it will not cause the HTML parser to close the
* comment.
*
* @param value text to make safe for comment node by escaping the comment close character sequence
*/
function escapeCommentText(value) {
return value.replace(END_COMMENT, END_COMMENT_ESCAPED);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* THIS FILE CONTAINS CODE WHICH SHOULD BE TREE SHAKEN AND NEVER CALLED FROM PRODUCTION CODE!!!
*/
/**
* Creates an `Array` construction with a given name. This is useful when
* looking for memory consumption to see what time of array it is.
*
*
* @param name Name to give to the constructor
* @returns A subclass of `Array` if possible. This can only be done in
* environments which support `class` construct.
*/
function createNamedArrayType(name) {
// This should never be called in prod mode, so let's verify that is the case.
if (ngDevMode) {
try {
// We need to do it this way so that TypeScript does not down-level the below code.
const FunctionConstructor = createNamedArrayType.constructor;
return (new FunctionConstructor('Array', `return class ${name} extends Array{}`))(Array);
}
catch (e) {
// If it does not work just give up and fall back to regular Array.
return Array;
}
}
else {
throw new Error('Looks like we are in \'prod mode\', but we are creating a named Array type, which is wrong! Check your code');
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function normalizeDebugBindingName(name) {
// Attribute names with `$` (eg `x-y$`) are valid per spec, but unsupported by some browsers
name = camelCaseToDashCase(name.replace(/[$@]/g, '_'));
return `ng-reflect-${name}`;
}
const CAMEL_CASE_REGEXP = /([A-Z])/g;
function camelCaseToDashCase(input) {
return input.replace(CAMEL_CASE_REGEXP, (...m) => '-' + m[1].toLowerCase());
}
function normalizeDebugBindingValue(value) {
try {
// Limit the size of the value as otherwise the DOM just gets polluted.
return value != null ? value.toString().slice(0, 30) : value;
}
catch (e) {
return '[ERROR] Exception while trying to serialize the value';
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/context_discovery.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Returns the matching `LContext` data for a given DOM node, directive or component instance.
*
* This function will examine the provided DOM element, component, or directive instance\'s
* monkey-patched property to derive the `LContext` data. Once called then the monkey-patched
* value will be that of the newly created `LContext`.
*
* If the monkey-patched value is the `LView` instance then the context value for that
* target will be created and the monkey-patch reference will be updated. Therefore when this
* function is called it may mutate the provided element\'s, component\'s or any of the associated
* directive\'s monkey-patch values.
*
* If the monkey-patch value is not detected then the code will walk up the DOM until an element
* is found which contains a monkey-patch reference. When that occurs then the provided element
* will be updated with a new context (which is then returned). If the monkey-patch value is not
* detected for a component/directive instance then it will throw an error (all components and
* directives should be automatically monkey-patched by ivy).
*
* @param {?} target Component, Directive or DOM Node.
* @return {?}
*/
function getLContext(target) {
/** @type {?} */
let mpValue = readPatchedData(target);
if (mpValue) {
// only when it's an array is it considered an LView instance
// ... otherwise it's an already constructed LContext instance
if (Array.isArray(mpValue)) {
/** @type {?} */
const lView = (/** @type {?} */ (mpValue));
/** @type {?} */
let nodeIndex;
/** @type {?} */
let component = undefined;
/** @type {?} */
let directives = undefined;
if (isComponentInstance(target)) {
nodeIndex = findViaComponent(lView, target);
if (nodeIndex == -1) {
throw new Error('The provided component was not found in the application');
}
component = target;
}
else if (isDirectiveInstance(target)) {
nodeIndex = findViaDirective(lView, target);
if (nodeIndex == -1) {
throw new Error('The provided directive was not found in the application');
}
directives = getDirectivesAtNodeIndex(nodeIndex, lView, false);
}
else {
nodeIndex = findViaNativeElement(lView, (/** @type {?} */ (target)));
if (nodeIndex == -1) {
return null;
}
}
// the goal is not to fill the entire context full of data because the lookups
// are expensive. Instead, only the target data (the element, component, container, ICU
// expression or directive details) are filled into the context. If called multiple times
// with different target values then the missing target data will be filled in.
/** @type {?} */
const native = unwrapRNode(lView[nodeIndex]);
/** @type {?} */
const existingCtx = readPatchedData(native);
/** @type {?} */
const context = (existingCtx && !Array.isArray(existingCtx)) ?
existingCtx :
createLContext(lView, nodeIndex, native);
// only when the component has been discovered then update the monkey-patch
if (component && context.component === undefined) {
context.component = component;
attachPatchData(context.component, context);
}
// only when the directives have been discovered then update the monkey-patch
if (directives && context.directives === undefined) {
context.directives = directives;
for (let i = 0; i < directives.length; i++) {
attachPatchData(directives[i], context);
}
}
attachPatchData(context.native, context);
mpValue = context;
}
}
else {
/** @type {?} */
const rElement = (/** @type {?} */ (target));
ngDevMode && assertDomNode(rElement);
// if the context is not found then we need to traverse upwards up the DOM
// to find the nearest element that has already been monkey patched with data
/** @type {?} */
let parent = (/** @type {?} */ (rElement));
while (parent = parent.parentNode) {
/** @type {?} */
const parentContext = readPatchedData(parent);
if (parentContext) {
/** @type {?} */
let lView;
if (Array.isArray(parentContext)) {
lView = (/** @type {?} */ (parentContext));
}
else {
lView = parentContext.lView;
}
// the edge of the app was also reached here through another means
// (maybe because the DOM was changed manually).
if (!lView) {
return null;
}
/** @type {?} */
const index = findViaNativeElement(lView, rElement);
if (index >= 0) {
/** @type {?} */
const native = unwrapRNode(lView[index]);
/** @type {?} */
const context = createLContext(lView, index, native);
attachPatchData(native, context);
mpValue = context;
break;
}
}
}
}
return ((/** @type {?} */ (mpValue))) || null;
}
/**
* Creates an empty instance of a `LContext` context
* @param {?} lView
* @param {?} nodeIndex
* @param {?} native
* @return {?}
*/
function createLContext(lView, nodeIndex, native) {
return {
lView,
nodeIndex,
native,
component: undefined,
directives: undefined,
localRefs: undefined,
};
}
/**
* Takes a component instance and returns the view for that component.
*
* @param {?} componentInstance
* @return {?} The component's view
*/
function getComponentViewByInstance(componentInstance) {
/** @type {?} */
let lView = readPatchedData(componentInstance);
/** @type {?} */
let view;
if (Array.isArray(lView)) {
/** @type {?} */
const nodeIndex = findViaComponent(lView, componentInstance);
view = getComponentLViewByIndex(nodeIndex, lView);
/** @type {?} */
const context = createLContext(lView, nodeIndex, (/** @type {?} */ (view[HOST])));
context.component = componentInstance;
attachPatchData(componentInstance, context);
attachPatchData(context.native, context);
}
else {
/** @type {?} */
const context = (/** @type {?} */ ((/** @type {?} */ (lView))));
view = getComponentLViewByIndex(context.nodeIndex, context.lView);
}
return view;
}
/**
* Assigns the given data to the given target (which could be a component,
* directive or DOM node instance) using monkey-patching.
* @param {?} target
* @param {?} data
* @return {?}
*/
function attachPatchData(target, data) {
target[MONKEY_PATCH_KEY_NAME] = data;
}
/**
* @param {?} instance
* @return {?}
*/
function isComponentInstance(instance) {
return instance && instance.constructor && instance.constructor.ɵcmp;
}
/**
* @param {?} instance
* @return {?}
*/
function isDirectiveInstance(instance) {
return instance && instance.constructor && instance.constructor.ɵdir;
}
/**
* Locates the element within the given LView and returns the matching index
* @param {?} lView
* @param {?} target
* @return {?}
*/
function findViaNativeElement(lView, target) {
/** @type {?} */
let tNode = lView[TVIEW].firstChild;
while (tNode) {
/** @type {?} */
const native = (/** @type {?} */ (getNativeByTNodeOrNull(tNode, lView)));
if (native === target) {
return tNode.index;
}
tNode = traverseNextElement(tNode);
}
return -1;
}
/**
* Locates the next tNode (child, sibling or parent).
* @param {?} tNode
* @return {?}
*/
function traverseNextElement(tNode) {
if (tNode.child) {
return tNode.child;
}
else if (tNode.next) {
return tNode.next;
}
else {
// Let's take the following template: <div><span>text</span></div><component/>
// After checking the text node, we need to find the next parent that has a "next" TNode,
// in this case the parent `div`, so that we can find the component.
while (tNode.parent && !tNode.parent.next) {
tNode = tNode.parent;
}
return tNode.parent && tNode.parent.next;
}
}
/**
* Locates the component within the given LView and returns the matching index
* @param {?} lView
* @param {?} componentInstance
* @return {?}
*/
function findViaComponent(lView, componentInstance) {
/** @type {?} */
const componentIndices = lView[TVIEW].components;
if (componentIndices) {
for (let i = 0; i < componentIndices.length; i++) {
/** @type {?} */
const elementComponentIndex = componentIndices[i];
/** @type {?} */
const componentView = getComponentLViewByIndex(elementComponentIndex, lView);
if (componentView[CONTEXT] === componentInstance) {
return elementComponentIndex;
}
}
}
else {
/** @type {?} */
const rootComponentView = getComponentLViewByIndex(HEADER_OFFSET, lView);
/** @type {?} */
const rootComponent = rootComponentView[CONTEXT];
if (rootComponent === componentInstance) {
// we are dealing with the root element here therefore we know that the
// element is the very first element after the HEADER data in the lView
return HEADER_OFFSET;
}
}
return -1;
}
/**
* Locates the directive within the given LView and returns the matching index
* @param {?} lView
* @param {?} directiveInstance
* @return {?}
*/
function findViaDirective(lView, directiveInstance) {
// if a directive is monkey patched then it will (by default)
// have a reference to the LView of the current view. The
// element bound to the directive being search lives somewhere
// in the view data. We loop through the nodes and check their
// list of directives for the instance.
/** @type {?} */
let tNode = lView[TVIEW].firstChild;
while (tNode) {
/** @type {?} */
const directiveIndexStart = tNode.directiveStart;
/** @type {?} */
const directiveIndexEnd = tNode.directiveEnd;
for (let i = directiveIndexStart; i < directiveIndexEnd; i++) {
if (lView[i] === directiveInstance) {
return tNode.index;
}
}
tNode = traverseNextElement(tNode);
}
return -1;
}
/**
* Returns a list of directives extracted from the given view based on the
* provided list of directive index values.
*
* @param {?} nodeIndex The node index
* @param {?} lView The target view data
* @param {?} includeComponents Whether or not to include components in returned directives
* @return {?}
*/
function getDirectivesAtNodeIndex(nodeIndex, lView, includeComponents) {
/** @type {?} */
const tNode = (/** @type {?} */ (lView[TVIEW].data[nodeIndex]));
/** @type {?} */
let directiveStartIndex = tNode.directiveStart;
if (directiveStartIndex == 0)
return EMPTY_ARRAY;
/** @type {?} */
const directiveEndIndex = tNode.directiveEnd;
if (!includeComponents && tNode.flags & 2 /* isComponentHost */)
directiveStartIndex++;
return lView.slice(directiveStartIndex, directiveEndIndex);
}
/**
* @param {?} nodeIndex
* @param {?} lView
* @return {?}
*/
function getComponentAtNodeIndex(nodeIndex, lView) {
/** @type {?} */
const tNode = (/** @type {?} */ (lView[TVIEW].data[nodeIndex]));
/** @type {?} */
let directiveStartIndex = tNode.directiveStart;
return tNode.flags & 2 /* isComponentHost */ ? lView[directiveStartIndex] : null;
}
/**
* Returns a map of local references (local reference name => element or directive instance) that
* exist on a given element.
* @param {?} lView
* @param {?} nodeIndex
* @return {?}
*/
function discoverLocalRefs(lView, nodeIndex) {
/** @type {?} */
const tNode = (/** @type {?} */ (lView[TVIEW].data[nodeIndex]));
if (tNode && tNode.localNames) {
/** @type {?} */
const result = {};
/** @type {?} */
let localIndex = tNode.index + 1;
for (let i = 0; i < tNode.localNames.length; i += 2) {
result[tNode.localNames[i]] = lView[localIndex];
localIndex++;
}
return result;
}
return null;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/errors.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Called when directives inject each other (creating a circular dependency)
* @param {?} token
* @return {?}
*/
function throwCyclicDependencyError(token) {
throw new Error(`Cannot instantiate cyclic dependency! ${token}`);
}
/**
* Called when there are multiple component selectors that match a given node
* @param {?} tNode
* @return {?}
*/
function throwMultipleComponentError(tNode) {
throw new Error(`Multiple components match node with tagname ${tNode.tagName}`);
}
/**
* @return {?}
*/
function throwMixedMultiProviderError() {
throw new Error(`Cannot mix multi providers and regular providers`);
}
/**
* @param {?=} ngModuleType
* @param {?=} providers
* @param {?=} provider
* @return {?}
*/
function throwInvalidProviderError(ngModuleType, providers, provider) {
/** @type {?} */
let ngModuleDetail = '';
if (ngModuleType && providers) {
/** @type {?} */
const providerDetail = providers.map((/**
* @param {?} v
* @return {?}
*/
v => v == provider ? '?' + provider + '?' : '...'));
ngModuleDetail =
` - only instances of Provider and Type are allowed, got: [${providerDetail.join(', ')}]`;
}
throw new Error(`Invalid provider for the NgModule '${stringify(ngModuleType)}'` + ngModuleDetail);
}
/**
* Throws an ExpressionChangedAfterChecked error if checkNoChanges mode is on.
* @param {?} creationMode
* @param {?} oldValue
* @param {?} currValue
* @param {?=} propName
* @return {?}
*/
function throwErrorIfNoChangesMode(creationMode, oldValue, currValue, propName) {
/** @type {?} */
const field = propName ? ` for '${propName}'` : '';
/** @type {?} */
let msg = `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value${field}: '${oldValue}'. Current value: '${currValue}'.`;
if (creationMode) {
msg +=
` It seems like the view has been created after its parent and its children have been dirty checked.` +
` Has it been created in a change detection hook?`;
}
// TODO: include debug context, see `viewDebugError` function in
// `packages/core/src/view/errors.ts` for reference.
throw new Error(msg);
}
/**
* @param {?} lView
* @param {?} rootIndex
* @param {?} expressionIndex
* @param {?} meta
* @param {?} changedValue
* @return {?}
*/
function constructDetailsForInterpolation(lView, rootIndex, expressionIndex, meta, changedValue) {
const [propName, prefix, ...chunks] = meta.split(INTERPOLATION_DELIMITER);
/** @type {?} */
let oldValue = prefix;
/** @type {?} */
let newValue = prefix;
for (let i = 0; i < chunks.length; i++) {
/** @type {?} */
const slotIdx = rootIndex + i;
oldValue += `${lView[slotIdx]}${chunks[i]}`;
newValue += `${slotIdx === expressionIndex ? changedValue : lView[slotIdx]}${chunks[i]}`;
}
return { propName, oldValue, newValue };
}
/**
* Constructs an object that contains details for the ExpressionChangedAfterItHasBeenCheckedError:
* - property name (for property bindings or interpolations)
* - old and new values, enriched using information from metadata
*
* More information on the metadata storage format can be found in `storePropertyBindingMetadata`
* function description.
* @param {?} lView
* @param {?} bindingIndex
* @param {?} oldValue
* @param {?} newValue
* @return {?}
*/
function getExpressionChangedErrorDetails(lView, bindingIndex, oldValue, newValue) {
/** @type {?} */
const tData = lView[TVIEW].data;
/** @type {?} */
const metadata = tData[bindingIndex];
if (typeof metadata === 'string') {
// metadata for property interpolation
if (metadata.indexOf(INTERPOLATION_DELIMITER) > -1) {
return constructDetailsForInterpolation(lView, bindingIndex, bindingIndex, metadata, newValue);
}
// metadata for property binding
return { propName: metadata, oldValue, newValue };
}
// metadata is not available for this expression, check if this expression is a part of the
// property interpolation by going from the current binding index left and look for a string that
// contains INTERPOLATION_DELIMITER, the layout in tView.data for this case will look like this:
// [..., 'id�Prefix � and � suffix', null, null, null, ...]
if (metadata === null) {
/** @type {?} */
let idx = bindingIndex - 1;
while (typeof tData[idx] !== 'string' && tData[idx + 1] === null) {
idx--;
}
/** @type {?} */
const meta = tData[idx];
if (typeof meta === 'string') {
/** @type {?} */
const matches = meta.match(new RegExp(INTERPOLATION_DELIMITER, 'g'));
// first interpolation delimiter separates property name from interpolation parts (in case of
// property interpolations), so we subtract one from total number of found delimiters
if (matches && (matches.length - 1) > bindingIndex - idx) {
return constructDetailsForInterpolation(lView, idx, bindingIndex, meta, newValue);
}
}
}
return { propName: undefined, oldValue, newValue };
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/node.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @enum {number} */
const TNodeType = {
/**
* The TNode contains information about an {@link LContainer} for embedded views.
*/
Container: 0,
/**
* The TNode contains information about an `<ng-content>` projection
*/
Projection: 1,
/**
* The TNode contains information about an {@link LView}
*/
View: 2,
/**
* The TNode contains information about a DOM element aka {@link RNode}.
*/
Element: 3,
/**
* The TNode contains information about an `<ng-container>` element {@link RNode}.
*/
ElementContainer: 4,
/**
* The TNode contains information about an ICU comment used in `i18n`.
*/
IcuContainer: 5,
};
/** @enum {number} */
const TNodeFlags = {
/** Bit #1 - This bit is set if the node is a host for any directive (including a component) */
isDirectiveHost: 1,
/**
* Bit #2 - This bit is set if the node is a host for a component.
*
* Setting this bit implies that the `isDirectiveHost` bit is set as well.
* */
isComponentHost: 2,
/** Bit #3 - This bit is set if the node has been projected */
isProjected: 4,
/** Bit #4 - This bit is set if any directive on this node has content queries */
hasContentQuery: 8,
/** Bit #5 - This bit is set if the node has any "class" inputs */
hasClassInput: 16,
/** Bit #6 - This bit is set if the node has any "style" inputs */
hasStyleInput: 32,
/** Bit #7 This bit is set if the node has been detached by i18n */
isDetached: 64,
/**
* Bit #8 - This bit is set if the node has directives with host bindings.
*
* This flags allows us to guard host-binding logic and invoke it only on nodes
* that actually have directives with host bindings.
*/
hasHostBindings: 128,
};
/** @enum {number} */
const TNodeProviderIndexes = {
/** The index of the first provider on this node is encoded on the least significant bits */
ProvidersStartIndexMask: 65535,
/**
The count of view providers from the component on this node is encoded on the 16 most
significant bits
*/
CptViewProvidersCountShift: 16,
CptViewProvidersCountShifter: 65536,
};
/** @enum {number} */
const AttributeMarker = {
/**
* An implicit marker which indicates that the value in the array are of `attributeKey`,
* `attributeValue` format.
*
* NOTE: This is implicit as it is the type when no marker is present in array. We indicate that
* it should not be present at runtime by the negative number.
*/
ImplicitAttributes: -1,
/**
* Marker indicates that the following 3 values in the attributes array are:
* namespaceUri, attributeName, attributeValue
* in that order.
*/
NamespaceURI: 0,
/**
* Signals class declaration.
*
* Each value following `Classes` designates a class name to include on the element.
* ## Example:
*
* Given:
* ```
* <div class="foo bar baz">...<d/vi>
* ```
*
* the generated code is:
* ```
* var _c1 = [AttributeMarker.Classes, 'foo', 'bar', 'baz'];
* ```
*/
Classes: 1,
/**
* Signals style declaration.
*
* Each pair of values following `Styles` designates a style name and value to include on the
* element.
* ## Example:
*
* Given:
* ```
* <div style="width:100px; height:200px; color:red">...</div>
* ```
*
* the generated code is:
* ```
* var _c1 = [AttributeMarker.Styles, 'width', '100px', 'height'. '200px', 'color', 'red'];
* ```
*/
Styles: 2,
/**
* Signals that the following attribute names were extracted from input or output bindings.
*
* For example, given the following HTML:
*
* ```
* <div moo="car" [foo]="exp" (bar)="doSth()">
* ```
*
* the generated code is:
*
* ```
* var _c1 = ['moo', 'car', AttributeMarker.Bindings, 'foo', 'bar'];
* ```
*/
Bindings: 3,
/**
* Signals that the following attribute names were hoisted from an inline-template declaration.
*
* For example, given the following HTML:
*
* ```
* <div *ngFor="let value of values; trackBy:trackBy" dirA [dirB]="value">
* ```
*
* the generated code for the `template()` instruction would include:
*
* ```
* ['dirA', '', AttributeMarker.Bindings, 'dirB', AttributeMarker.Template, 'ngFor', 'ngForOf',
* 'ngForTrackBy', 'let-value']
* ```
*
* while the generated code for the `element()` instruction inside the template function would
* include:
*
* ```
* ['dirA', '', AttributeMarker.Bindings, 'dirB']
* ```
*/
Template: 4,
/**
* Signals that the following attribute is `ngProjectAs` and its value is a parsed `CssSelector`.
*
* For example, given the following HTML:
*
* ```
* <h1 attr="value" ngProjectAs="[title]">
* ```
*
* the generated code for the `element()` instruction would include:
*
* ```
* ['attr', 'value', AttributeMarker.ProjectAs, ['', 'title', '']]
* ```
*/
ProjectAs: 5,
/**
* Signals that the following attribute will be translated by runtime i18n
*
* For example, given the following HTML:
*
* ```
* <div moo="car" foo="value" i18n-foo [bar]="binding" i18n-bar>
* ```
*
* the generated code is:
*
* ```
* var _c1 = ['moo', 'car', AttributeMarker.I18n, 'foo', 'bar'];
*/
I18n: 6,
};
/**
* Binding data (flyweight) for a particular node that is shared between all templates
* of a specific type.
*
* If a property is:
* - PropertyAliases: that property's data was generated and this is it
* - Null: that property's data was already generated and nothing was found.
* - Undefined: that property's data has not yet been generated
*
* see: https://en.wikipedia.org/wiki/Flyweight_pattern for more on the Flyweight pattern
* @record
*/
function TNode() { }
if (false) {}
/**
* Static data for an element
* @record
*/
function TElementNode() { }
if (false) {}
/**
* Static data for a text node
* @record
*/
function TTextNode() { }
if (false) {}
/**
* Static data for an LContainer
* @record
*/
function TContainerNode() { }
if (false) {}
/**
* Static data for an <ng-container>
* @record
*/
function TElementContainerNode() { }
if (false) {}
/**
* Static data for an ICU expression
* @record
*/
function TIcuContainerNode() { }
if (false) {}
/**
* Static data for a view
* @record
*/
function TViewNode() { }
if (false) {}
/**
* Static data for an LProjectionNode
* @record
*/
function TProjectionNode() { }
if (false) {}
// Note: This hack is necessary so we don't erroneously get a circular dependency
// failure based on types.
/** @type {?} */
const unusedValueExportToPlacateAjd$4 = 1;
/**
* Returns `true` if the `TNode` has a directive which has `\@Input()` for `class` binding.
*
* ```
* <div my-dir [class]="exp"></div>
* ```
* and
* ```
* \@Directive({
* })
* class MyDirective {
* \@Input()
* class: string;
* }
* ```
*
* In the above case it is necessary to write the reconciled styling information into the
* directive's input.
*
* @param {?} tNode
* @return {?}
*/
function hasClassInput(tNode) {
return (tNode.flags & 16 /* hasClassInput */) !== 0;
}
/**
* Returns `true` if the `TNode` has a directive which has `\@Input()` for `style` binding.
*
* ```
* <div my-dir [style]="exp"></div>
* ```
* and
* ```
* \@Directive({
* })
* class MyDirective {
* \@Input()
* class: string;
* }
* ```
*
* In the above case it is necessary to write the reconciled styling information into the
* directive's input.
*
* @param {?} tNode
* @return {?}
*/
function hasStyleInput(tNode) {
return (tNode.flags & 32 /* hasStyleInput */) !== 0;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/projection.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @enum {number} */
const SelectorFlags = {
/** Indicates this is the beginning of a new negative selector */
NOT: 1,
/** Mode for matching attributes */
ATTRIBUTE: 2,
/** Mode for matching tag names */
ELEMENT: 4,
/** Mode for matching class names */
CLASS: 8,
};
// Note: This hack is necessary so we don't erroneously get a circular dependency
// failure based on types.
/** @type {?} */
const unusedValueExportToPlacateAjd$5 = 1;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/styling/class_differ.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Returns an index of `classToSearch` in `className` taking token boundaries into account.
*
* `classIndexOf('AB A', 'A', 0)` will be 3 (not 0 since `AB!==A`)
*
* @param {?} className A string containing classes (whitespace separated)
* @param {?} classToSearch A class name to locate
* @param {?} startingIndex Starting location of search
* @return {?} an index of the located class (or -1 if not found)
*/
function classIndexOf(className, classToSearch, startingIndex) {
ngDevMode && assertNotEqual(classToSearch, '', 'can not look for "" string.');
/** @type {?} */
let end = className.length;
while (true) {
/** @type {?} */
const foundIndex = className.indexOf(classToSearch, startingIndex);
if (foundIndex === -1)
return foundIndex;
if (foundIndex === 0 || className.charCodeAt(foundIndex - 1) <= 32 /* SPACE */) {
// Ensure that it has leading whitespace
/** @type {?} */
const length = classToSearch.length;
if (foundIndex + length === end ||
className.charCodeAt(foundIndex + length) <= 32 /* SPACE */) {
// Ensure that it has trailing whitespace
return foundIndex;
}
}
// False positive, keep searching from where we left off.
startingIndex = foundIndex + 1;
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/node_selector_matcher.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const unusedValueToPlacateAjd = unusedValueExportToPlacateAjd$4 + unusedValueExportToPlacateAjd$5;
/** @type {?} */
const NG_TEMPLATE_SELECTOR = 'ng-template';
/**
* Search the `TAttributes` to see if it contains `cssClassToMatch` (case insensitive)
*
* @param {?} attrs `TAttributes` to search through.
* @param {?} cssClassToMatch class to match (lowercase)
* @param {?} isProjectionMode Whether or not class matching should look into the attribute `class` in
* addition to the `AttributeMarker.Classes`.
* @return {?}
*/
function isCssClassMatching(attrs, cssClassToMatch, isProjectionMode) {
// TODO(misko): The fact that this function needs to know about `isProjectionMode` seems suspect.
// It is strange to me that sometimes the class information comes in form of `class` attribute
// and sometimes in form of `AttributeMarker.Classes`. Some investigation is needed to determine
// if that is the right behavior.
ngDevMode &&
assertEqual(cssClassToMatch, cssClassToMatch.toLowerCase(), 'Class name expected to be lowercase.');
/** @type {?} */
let i = 0;
while (i < attrs.length) {
/** @type {?} */
let item = attrs[i++];
if (isProjectionMode && item === 'class') {
item = (/** @type {?} */ (attrs[i]));
if (classIndexOf(item.toLowerCase(), cssClassToMatch, 0) !== -1) {
return true;
}
}
else if (item === 1 /* Classes */) {
// We found the classes section. Start searching for the class.
while (i < attrs.length && typeof (item = attrs[i++]) == 'string') {
// while we have strings
if (item.toLowerCase() === cssClassToMatch)
return true;
}
return false;
}
}
return false;
}
/**
* Checks whether the `tNode` represents an inline template (e.g. `*ngFor`).
*
* @param {?} tNode current TNode
* @return {?}
*/
function isInlineTemplate(tNode) {
return tNode.type === 0 /* Container */ && tNode.tagName !== NG_TEMPLATE_SELECTOR;
}
/**
* Function that checks whether a given tNode matches tag-based selector and has a valid type.
*
* Matching can be performed in 2 modes: projection mode (when we project nodes) and regular
* directive matching mode:
* - in the "directive matching" mode we do _not_ take TContainer's tagName into account if it is
* different from NG_TEMPLATE_SELECTOR (value different from NG_TEMPLATE_SELECTOR indicates that a
* tag name was extracted from * syntax so we would match the same directive twice);
* - in the "projection" mode, we use a tag name potentially extracted from the * syntax processing
* (applicable to TNodeType.Container only).
* @param {?} tNode
* @param {?} currentSelector
* @param {?} isProjectionMode
* @return {?}
*/
function hasTagAndTypeMatch(tNode, currentSelector, isProjectionMode) {
/** @type {?} */
const tagNameToCompare = tNode.type === 0 /* Container */ && !isProjectionMode ?
NG_TEMPLATE_SELECTOR :
tNode.tagName;
return currentSelector === tagNameToCompare;
}
/**
* A utility function to match an Ivy node static data against a simple CSS selector
*
* @param {?} tNode
* @param {?} selector The selector to try matching against the node.
* @param {?} isProjectionMode if `true` we are matching for content projection, otherwise we are doing
* directive matching.
* @return {?} true if node matches the selector.
*/
function isNodeMatchingSelector(tNode, selector, isProjectionMode) {
ngDevMode && assertDefined(selector[0], 'Selector should have a tag name');
/** @type {?} */
let mode = 4 /* ELEMENT */;
/** @type {?} */
const nodeAttrs = tNode.attrs || [];
// Find the index of first attribute that has no value, only a name.
/** @type {?} */
const nameOnlyMarkerIdx = getNameOnlyMarkerIndex(nodeAttrs);
// When processing ":not" selectors, we skip to the next ":not" if the
// current one doesn't match
/** @type {?} */
let skipToNextSelector = false;
for (let i = 0; i < selector.length; i++) {
/** @type {?} */
const current = selector[i];
if (typeof current === 'number') {
// If we finish processing a :not selector and it hasn't failed, return false
if (!skipToNextSelector && !isPositive(mode) && !isPositive(current)) {
return false;
}
// If we are skipping to the next :not() and this mode flag is positive,
// it's a part of the current :not() selector, and we should keep skipping
if (skipToNextSelector && isPositive(current))
continue;
skipToNextSelector = false;
mode = ((/** @type {?} */ (current))) | (mode & 1 /* NOT */);
continue;
}
if (skipToNextSelector)
continue;
if (mode & 4 /* ELEMENT */) {
mode = 2 /* ATTRIBUTE */ | mode & 1 /* NOT */;
if (current !== '' && !hasTagAndTypeMatch(tNode, current, isProjectionMode) ||
current === '' && selector.length === 1) {
if (isPositive(mode))
return false;
skipToNextSelector = true;
}
}
else {
/** @type {?} */
const selectorAttrValue = mode & 8 /* CLASS */ ? current : selector[++i];
// special case for matching against classes when a tNode has been instantiated with
// class and style values as separate attribute values (e.g. ['title', CLASS, 'foo'])
if ((mode & 8 /* CLASS */) && tNode.attrs !== null) {
if (!isCssClassMatching(tNode.attrs, (/** @type {?} */ (selectorAttrValue)), isProjectionMode)) {
if (isPositive(mode))
return false;
skipToNextSelector = true;
}
continue;
}
/** @type {?} */
const attrName = (mode & 8 /* CLASS */) ? 'class' : current;
/** @type {?} */
const attrIndexInNode = findAttrIndexInNode(attrName, nodeAttrs, isInlineTemplate(tNode), isProjectionMode);
if (attrIndexInNode === -1) {
if (isPositive(mode))
return false;
skipToNextSelector = true;
continue;
}
if (selectorAttrValue !== '') {
/** @type {?} */
let nodeAttrValue;
if (attrIndexInNode > nameOnlyMarkerIdx) {
nodeAttrValue = '';
}
else {
ngDevMode &&
assertNotEqual(nodeAttrs[attrIndexInNode], 0 /* NamespaceURI */, 'We do not match directives on namespaced attributes');
// we lowercase the attribute value to be able to match
// selectors without case-sensitivity
// (selectors are already in lowercase when generated)
nodeAttrValue = ((/** @type {?} */ (nodeAttrs[attrIndexInNode + 1]))).toLowerCase();
}
/** @type {?} */
const compareAgainstClassName = mode & 8 /* CLASS */ ? nodeAttrValue : null;
if (compareAgainstClassName &&
classIndexOf(compareAgainstClassName, (/** @type {?} */ (selectorAttrValue)), 0) !== -1 ||
mode & 2 /* ATTRIBUTE */ && selectorAttrValue !== nodeAttrValue) {
if (isPositive(mode))
return false;
skipToNextSelector = true;
}
}
}
}
return isPositive(mode) || skipToNextSelector;
}
/**
* @param {?} mode
* @return {?}
*/
function isPositive(mode) {
return (mode & 1 /* NOT */) === 0;
}
/**
* Examines the attribute's definition array for a node to find the index of the
* attribute that matches the given `name`.
*
* NOTE: This will not match namespaced attributes.
*
* Attribute matching depends upon `isInlineTemplate` and `isProjectionMode`.
* The following table summarizes which types of attributes we attempt to match:
*
* ===========================================================================================================
* Modes | Normal Attributes | Bindings Attributes | Template Attributes | I18n
* Attributes
* ===========================================================================================================
* Inline + Projection | YES | YES | NO | YES
* -----------------------------------------------------------------------------------------------------------
* Inline + Directive | NO | NO | YES | NO
* -----------------------------------------------------------------------------------------------------------
* Non-inline + Projection | YES | YES | NO | YES
* -----------------------------------------------------------------------------------------------------------
* Non-inline + Directive | YES | YES | NO | YES
* ===========================================================================================================
*
* @param {?} name the name of the attribute to find
* @param {?} attrs the attribute array to examine
* @param {?} isInlineTemplate true if the node being matched is an inline template (e.g. `*ngFor`)
* rather than a manually expanded template node (e.g `<ng-template>`).
* @param {?} isProjectionMode true if we are matching against content projection otherwise we are
* matching against directives.
* @return {?}
*/
function findAttrIndexInNode(name, attrs, isInlineTemplate, isProjectionMode) {
if (attrs === null)
return -1;
/** @type {?} */
let i = 0;
if (isProjectionMode || !isInlineTemplate) {
/** @type {?} */
let bindingsMode = false;
while (i < attrs.length) {
/** @type {?} */
const maybeAttrName = attrs[i];
if (maybeAttrName === name) {
return i;
}
else if (maybeAttrName === 3 /* Bindings */ || maybeAttrName === 6 /* I18n */) {
bindingsMode = true;
}
else if (maybeAttrName === 1 /* Classes */ || maybeAttrName === 2 /* Styles */) {
/** @type {?} */
let value = attrs[++i];
// We should skip classes here because we have a separate mechanism for
// matching classes in projection mode.
while (typeof value === 'string') {
value = attrs[++i];
}
continue;
}
else if (maybeAttrName === 4 /* Template */) {
// We do not care about Template attributes in this scenario.
break;
}
else if (maybeAttrName === 0 /* NamespaceURI */) {
// Skip the whole namespaced attribute and value. This is by design.
i += 4;
continue;
}
// In binding mode there are only names, rather than name-value pairs.
i += bindingsMode ? 1 : 2;
}
// We did not match the attribute
return -1;
}
else {
return matchTemplateAttribute(attrs, name);
}
}
/**
* @param {?} tNode
* @param {?} selector
* @param {?=} isProjectionMode
* @return {?}
*/
function isNodeMatchingSelectorList(tNode, selector, isProjectionMode = false) {
for (let i = 0; i < selector.length; i++) {
if (isNodeMatchingSelector(tNode, selector[i], isProjectionMode)) {
return true;
}
}
return false;
}
/**
* @param {?} tNode
* @return {?}
*/
function getProjectAsAttrValue(tNode) {
/** @type {?} */
const nodeAttrs = tNode.attrs;
if (nodeAttrs != null) {
/** @type {?} */
const ngProjectAsAttrIdx = nodeAttrs.indexOf(5 /* ProjectAs */);
// only check for ngProjectAs in attribute names, don't accidentally match attribute's value
// (attribute names are stored at even indexes)
if ((ngProjectAsAttrIdx & 1) === 0) {
return (/** @type {?} */ (nodeAttrs[ngProjectAsAttrIdx + 1]));
}
}
return null;
}
/**
* @param {?} nodeAttrs
* @return {?}
*/
function getNameOnlyMarkerIndex(nodeAttrs) {
for (let i = 0; i < nodeAttrs.length; i++) {
/** @type {?} */
const nodeAttr = nodeAttrs[i];
if (isNameOnlyAttributeMarker(nodeAttr)) {
return i;
}
}
return nodeAttrs.length;
}
/**
* @param {?} attrs
* @param {?} name
* @return {?}
*/
function matchTemplateAttribute(attrs, name) {
/** @type {?} */
let i = attrs.indexOf(4 /* Template */);
if (i > -1) {
i++;
while (i < attrs.length) {
/** @type {?} */
const attr = attrs[i];
// Return in case we checked all template attrs and are switching to the next section in the
// attrs array (that starts with a number that represents an attribute marker).
if (typeof attr === 'number')
return -1;
if (attr === name)
return i;
i++;
}
}
return -1;
}
/**
* Checks whether a selector is inside a CssSelectorList
* @param {?} selector Selector to be checked.
* @param {?} list List in which to look for the selector.
* @return {?}
*/
function isSelectorInSelectorList(selector, list) {
selectorListLoop: for (let i = 0; i < list.length; i++) {
/** @type {?} */
const currentSelectorInList = list[i];
if (selector.length !== currentSelectorInList.length) {
continue;
}
for (let j = 0; j < selector.length; j++) {
if (selector[j] !== currentSelectorInList[j]) {
continue selectorListLoop;
}
}
return true;
}
return false;
}
/**
* @param {?} isNegativeMode
* @param {?} chunk
* @return {?}
*/
function maybeWrapInNotSelector(isNegativeMode, chunk) {
return isNegativeMode ? ':not(' + chunk.trim() + ')' : chunk;
}
/**
* @param {?} selector
* @return {?}
*/
function stringifyCSSSelector(selector) {
/** @type {?} */
let result = (/** @type {?} */ (selector[0]));
/** @type {?} */
let i = 1;
/** @type {?} */
let mode = 2 /* ATTRIBUTE */;
/** @type {?} */
let currentChunk = '';
/** @type {?} */
let isNegativeMode = false;
while (i < selector.length) {
/** @type {?} */
let valueOrMarker = selector[i];
if (typeof valueOrMarker === 'string') {
if (mode & 2 /* ATTRIBUTE */) {
/** @type {?} */
const attrValue = (/** @type {?} */ (selector[++i]));
currentChunk +=
'[' + valueOrMarker + (attrValue.length > 0 ? '="' + attrValue + '"' : '') + ']';
}
else if (mode & 8 /* CLASS */) {
currentChunk += '.' + valueOrMarker;
}
else if (mode & 4 /* ELEMENT */) {
currentChunk += ' ' + valueOrMarker;
}
}
else {
//
// Append current chunk to the final result in case we come across SelectorFlag, which
// indicates that the previous section of a selector is over. We need to accumulate content
// between flags to make sure we wrap the chunk later in :not() selector if needed, e.g.
// ```
// ['', Flags.CLASS, '.classA', Flags.CLASS | Flags.NOT, '.classB', '.classC']
// ```
// should be transformed to `.classA :not(.classB .classC)`.
//
// Note: for negative selector part, we accumulate content between flags until we find the
// next negative flag. This is needed to support a case where `:not()` rule contains more than
// one chunk, e.g. the following selector:
// ```
// ['', Flags.ELEMENT | Flags.NOT, 'p', Flags.CLASS, 'foo', Flags.CLASS | Flags.NOT, 'bar']
// ```
// should be stringified to `:not(p.foo) :not(.bar)`
//
if (currentChunk !== '' && !isPositive(valueOrMarker)) {
result += maybeWrapInNotSelector(isNegativeMode, currentChunk);
currentChunk = '';
}
mode = valueOrMarker;
// According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative
// mode is maintained for remaining chunks of a selector.
isNegativeMode = isNegativeMode || !isPositive(mode);
}
i++;
}
if (currentChunk !== '') {
result += maybeWrapInNotSelector(isNegativeMode, currentChunk);
}
return result;
}
/**
* Generates string representation of CSS selector in parsed form.
*
* ComponentDef and DirectiveDef are generated with the selector in parsed form to avoid doing
* additional parsing at runtime (for example, for directive matching). However in some cases (for
* example, while bootstrapping a component), a string version of the selector is required to query
* for the host element on the page. This function takes the parsed form of a selector and returns
* its string representation.
*
* @param {?} selectorList selector in parsed form
* @return {?} string representation of a given selector
*/
function stringifyCSSSelectorList(selectorList) {
return selectorList.map(stringifyCSSSelector).join(',');
}
/**
* Extracts attributes and classes information from a given CSS selector.
*
* This function is used while creating a component dynamically. In this case, the host element
* (that is created dynamically) should contain attributes and classes specified in component's CSS
* selector.
*
* @param {?} selector CSS selector in parsed form (in a form of array)
* @return {?} object with `attrs` and `classes` fields that contain extracted information
*/
function extractAttrsAndClassesFromSelector(selector) {
/** @type {?} */
const attrs = [];
/** @type {?} */
const classes = [];
/** @type {?} */
let i = 1;
/** @type {?} */
let mode = 2 /* ATTRIBUTE */;
while (i < selector.length) {
/** @type {?} */
let valueOrMarker = selector[i];
if (typeof valueOrMarker === 'string') {
if (mode === 2 /* ATTRIBUTE */) {
if (valueOrMarker !== '') {
attrs.push(valueOrMarker, (/** @type {?} */ (selector[++i])));
}
}
else if (mode === 8 /* CLASS */) {
classes.push(valueOrMarker);
}
}
else {
// According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative
// mode is maintained for remaining chunks of a selector. Since attributes and classes are
// extracted only for "positive" part of the selector, we can stop here.
if (!isPositive(mode))
break;
mode = valueOrMarker;
}
i++;
}
return { attrs, classes };
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/tokens.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// WARNING: interface has both a type and a value, skipping emit
/**
* A special value which designates that a value has not changed.
* @type {?}
*/
const NO_CHANGE = (typeof ngDevMode === 'undefined' || ngDevMode) ? { __brand__: 'NO_CHANGE' } : ((/** @type {?} */ ({})));
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/util/view_traversal_utils.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Gets the parent LView of the passed LView, if the PARENT is an LContainer, will get the parent of
* that LContainer, which is an LView
* @param {?} lView the lView whose parent to get
* @return {?}
*/
function getLViewParent(lView) {
ngDevMode && assertLView(lView);
/** @type {?} */
const parent = lView[PARENT];
return isLContainer(parent) ? (/** @type {?} */ (parent[PARENT])) : parent;
}
/**
* Retrieve the root view from any component or `LView` by walking the parent `LView` until
* reaching the root `LView`.
*
* @param {?} componentOrLView any component or `LView`
* @return {?}
*/
function getRootView(componentOrLView) {
ngDevMode && assertDefined(componentOrLView, 'component');
/** @type {?} */
let lView = isLView(componentOrLView) ? componentOrLView : (/** @type {?} */ (readPatchedLView(componentOrLView)));
while (lView && !(lView[FLAGS] & 512 /* IsRoot */)) {
lView = (/** @type {?} */ (getLViewParent(lView)));
}
ngDevMode && assertLView(lView);
return lView;
}
/**
* Returns the `RootContext` instance that is associated with
* the application where the target is situated. It does this by walking the parent views until it
* gets to the root view, then getting the context off of that.
*
* @param {?} viewOrComponent the `LView` or component to get the root context for.
* @return {?}
*/
function getRootContext(viewOrComponent) {
/** @type {?} */
const rootView = getRootView(viewOrComponent);
ngDevMode &&
assertDefined(rootView[CONTEXT], 'RootView has no context. Perhaps it is disconnected?');
return (/** @type {?} */ (rootView[CONTEXT]));
}
/**
* Gets the first `LContainer` in the LView or `null` if none exists.
* @param {?} lView
* @return {?}
*/
function getFirstLContainer(lView) {
return getNearestLContainer(lView[CHILD_HEAD]);
}
/**
* Gets the next `LContainer` that is a sibling of the given container.
* @param {?} container
* @return {?}
*/
function getNextLContainer(container) {
return getNearestLContainer(container[NEXT]);
}
/**
* @param {?} viewOrContainer
* @return {?}
*/
function getNearestLContainer(viewOrContainer) {
while (viewOrContainer !== null && !isLContainer(viewOrContainer)) {
viewOrContainer = viewOrContainer[NEXT];
}
return viewOrContainer;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/advance.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Advances to an element for later binding instructions.
*
* Used in conjunction with instructions like {\@link property} to act on elements with specified
* indices, for example those created with {\@link element} or {\@link elementStart}.
*
* ```ts
* (rf: RenderFlags, ctx: any) => {
* if (rf & 1) {
* text(0, 'Hello');
* text(1, 'Goodbye')
* element(2, 'div');
* }
* if (rf & 2) {
* advance(2); // Advance twice to the <div>.
* property('title', 'test');
* }
* }
* ```
* \@codeGenApi
* @param {?} delta Number of elements to advance forwards by.
*
* @return {?}
*/
function ɵɵadvance(delta) {
ngDevMode && assertGreaterThan(delta, 0, 'Can only advance forward');
selectIndexInternal(getTView(), getLView(), getSelectedIndex() + delta, getCheckNoChangesMode());
}
/**
* Selects an element for later binding instructions.
* @deprecated No longer being generated, but still used in unit tests.
* \@codeGenApi
* @param {?} index
* @return {?}
*/
function ɵɵselect(index) {
// TODO(misko): Remove this function as it is no longer being used.
selectIndexInternal(getTView(), getLView(), index, getCheckNoChangesMode());
}
/**
* @param {?} tView
* @param {?} lView
* @param {?} index
* @param {?} checkNoChangesMode
* @return {?}
*/
function selectIndexInternal(tView, lView, index, checkNoChangesMode) {
ngDevMode && assertGreaterThan(index, -1, 'Invalid index');
ngDevMode && assertDataInRange(lView, index + HEADER_OFFSET);
// Flush the initial hooks for elements in the view that have been added up to this point.
// PERF WARNING: do NOT extract this to a separate function without running benchmarks
if (!checkNoChangesMode) {
/** @type {?} */
const hooksInitPhaseCompleted = (lView[FLAGS] & 3 /* InitPhaseStateMask */) === 3 /* InitPhaseCompleted */;
if (hooksInitPhaseCompleted) {
/** @type {?} */
const preOrderCheckHooks = tView.preOrderCheckHooks;
if (preOrderCheckHooks !== null) {
executeCheckHooks(lView, preOrderCheckHooks, index);
}
}
else {
/** @type {?} */
const preOrderHooks = tView.preOrderHooks;
if (preOrderHooks !== null) {
executeInitAndCheckHooks(lView, preOrderHooks, 0 /* OnInitHooksToBeRun */, index);
}
}
}
// We must set the selected index *after* running the hooks, because hooks may have side-effects
// that cause other template functions to run, thus updating the selected index, which is global
// state. If we run `setSelectedIndex` *before* we run the hooks, in some cases the selected index
// will be altered by the time we leave the `ɵɵadvance` instruction.
setSelectedIndex(index);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/i18n.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @enum {number} */
const I18nMutateOpCode = {
/**
* Stores shift amount for bits 17-3 that contain reference index.
*/
SHIFT_REF: 3,
/**
* Stores shift amount for bits 31-17 that contain parent index.
*/
SHIFT_PARENT: 17,
/**
* Mask for OpCode
*/
MASK_OPCODE: 7,
/**
* OpCode to select a node. (next OpCode will contain the operation.)
*/
Select: 0,
/**
* OpCode to append the current node to `PARENT`.
*/
AppendChild: 1,
/**
* OpCode to remove the `REF` node from `PARENT`.
*/
Remove: 3,
/**
* OpCode to set the attribute of a node.
*/
Attr: 4,
/**
* OpCode to simulate elementEnd()
*/
ElementEnd: 5,
/**
* OpCode to read the remove OpCodes for the nested ICU
*/
RemoveNestedIcu: 6,
};
/**
* Marks that the next string is for element.
*
* See `I18nMutateOpCodes` documentation.
* @type {?}
*/
const ELEMENT_MARKER = {
marker: 'element'
};
// WARNING: interface has both a type and a value, skipping emit
/**
* Marks that the next string is for comment.
*
* See `I18nMutateOpCodes` documentation.
* @type {?}
*/
const COMMENT_MARKER = {
marker: 'comment'
};
// WARNING: interface has both a type and a value, skipping emit
/**
* Array storing OpCode for dynamically creating `i18n` blocks.
*
* Example:
* ```ts
* <I18nCreateOpCode>[
* // For adding text nodes
* // ---------------------
* // Equivalent to:
* // const node = lView[index++] = document.createTextNode('abc');
* // lView[1].insertBefore(node, lView[2]);
* 'abc', 1 << SHIFT_PARENT | 2 << SHIFT_REF | InsertBefore,
*
* // Equivalent to:
* // const node = lView[index++] = document.createTextNode('xyz');
* // lView[1].appendChild(node);
* 'xyz', 1 << SHIFT_PARENT | AppendChild,
*
* // For adding element nodes
* // ---------------------
* // Equivalent to:
* // const node = lView[index++] = document.createElement('div');
* // lView[1].insertBefore(node, lView[2]);
* ELEMENT_MARKER, 'div', 1 << SHIFT_PARENT | 2 << SHIFT_REF | InsertBefore,
*
* // Equivalent to:
* // const node = lView[index++] = document.createElement('div');
* // lView[1].appendChild(node);
* ELEMENT_MARKER, 'div', 1 << SHIFT_PARENT | AppendChild,
*
* // For adding comment nodes
* // ---------------------
* // Equivalent to:
* // const node = lView[index++] = document.createComment('');
* // lView[1].insertBefore(node, lView[2]);
* COMMENT_MARKER, '', 1 << SHIFT_PARENT | 2 << SHIFT_REF | InsertBefore,
*
* // Equivalent to:
* // const node = lView[index++] = document.createComment('');
* // lView[1].appendChild(node);
* COMMENT_MARKER, '', 1 << SHIFT_PARENT | AppendChild,
*
* // For moving existing nodes to a different location
* // --------------------------------------------------
* // Equivalent to:
* // const node = lView[1];
* // lView[2].insertBefore(node, lView[3]);
* 1 << SHIFT_REF | Select, 2 << SHIFT_PARENT | 3 << SHIFT_REF | InsertBefore,
*
* // Equivalent to:
* // const node = lView[1];
* // lView[2].appendChild(node);
* 1 << SHIFT_REF | Select, 2 << SHIFT_PARENT | AppendChild,
*
* // For removing existing nodes
* // --------------------------------------------------
* // const node = lView[1];
* // removeChild(tView.data(1), node, lView);
* 1 << SHIFT_REF | Remove,
*
* // For writing attributes
* // --------------------------------------------------
* // const node = lView[1];
* // node.setAttribute('attr', 'value');
* 1 << SHIFT_REF | Select, 'attr', 'value'
* // NOTE: Select followed by two string (vs select followed by OpCode)
* ];
* ```
* NOTE:
* - `index` is initial location where the extra nodes should be stored in the EXPANDO section of
* `LVIewData`.
*
* See: `applyI18nCreateOpCodes`;
* @record
*/
function I18nMutateOpCodes() { }
/** @enum {number} */
const I18nUpdateOpCode = {
/**
* Stores shift amount for bits 17-2 that contain reference index.
*/
SHIFT_REF: 2,
/**
* Mask for OpCode
*/
MASK_OPCODE: 3,
/**
* OpCode to update a text node.
*/
Text: 0,
/**
* OpCode to update a attribute of a node.
*/
Attr: 1,
/**
* OpCode to switch the current ICU case.
*/
IcuSwitch: 2,
/**
* OpCode to update the current ICU case.
*/
IcuUpdate: 3,
};
/**
* Stores DOM operations which need to be applied to update DOM render tree due to changes in
* expressions.
*
* The basic idea is that `i18nExp` OpCodes capture expression changes and update a change
* mask bit. (Bit 1 for expression 1, bit 2 for expression 2 etc..., bit 32 for expression 32 and
* higher.) The OpCodes then compare its own change mask against the expression change mask to
* determine if the OpCodes should execute.
*
* These OpCodes can be used by both the i18n block as well as ICU sub-block.
*
* ## Example
*
* Assume
* ```ts
* if (rf & RenderFlags.Update) {
* i18nExp(ctx.exp1); // If changed set mask bit 1
* i18nExp(ctx.exp2); // If changed set mask bit 2
* i18nExp(ctx.exp3); // If changed set mask bit 3
* i18nExp(ctx.exp4); // If changed set mask bit 4
* i18nApply(0); // Apply all changes by executing the OpCodes.
* }
* ```
* We can assume that each call to `i18nExp` sets an internal `changeMask` bit depending on the
* index of `i18nExp`.
*
* ### OpCodes
* ```ts
* <I18nUpdateOpCodes>[
* // The following OpCodes represent: `<div i18n-title="pre{{exp1}}in{{exp2}}post">`
* // If `changeMask & 0b11`
* // has changed then execute update OpCodes.
* // has NOT changed then skip `7` values and start processing next OpCodes.
* 0b11, 7,
* // Concatenate `newValue = 'pre'+lView[bindIndex-4]+'in'+lView[bindIndex-3]+'post';`.
* 'pre', -4, 'in', -3, 'post',
* // Update attribute: `elementAttribute(1, 'title', sanitizerFn(newValue));`
* 1 << SHIFT_REF | Attr, 'title', sanitizerFn,
*
* // The following OpCodes represent: `<div i18n>Hello {{exp3}}!">`
* // If `changeMask & 0b100`
* // has changed then execute update OpCodes.
* // has NOT changed then skip `4` values and start processing next OpCodes.
* 0b100, 4,
* // Concatenate `newValue = 'Hello ' + lView[bindIndex -2] + '!';`.
* 'Hello ', -2, '!',
* // Update text: `lView[1].textContent = newValue;`
* 1 << SHIFT_REF | Text,
*
* // The following OpCodes represent: `<div i18n>{exp4, plural, ... }">`
* // If `changeMask & 0b1000`
* // has changed then execute update OpCodes.
* // has NOT changed then skip `4` values and start processing next OpCodes.
* 0b1000, 4,
* // Concatenate `newValue = lView[bindIndex -1];`.
* -1,
* // Switch ICU: `icuSwitchCase(lView[1], 0, newValue);`
* 0 << SHIFT_ICU | 1 << SHIFT_REF | IcuSwitch,
*
* // Note `changeMask & -1` is always true, so the IcuUpdate will always execute.
* -1, 1,
* // Update ICU: `icuUpdateCase(lView[1], 0);`
* 0 << SHIFT_ICU | 1 << SHIFT_REF | IcuUpdate,
*
* ];
* ```
*
* @record
*/
function I18nUpdateOpCodes() { }
/**
* Store information for the i18n translation block.
* @record
*/
function TI18n() { }
if (false) {}
/** @enum {number} */
const IcuType = {
select: 0,
plural: 1,
};
/**
* @record
*/
function TIcu() { }
if (false) {}
// Note: This hack is necessary so we don't erroneously get a circular dependency
// failure based on types.
/** @type {?} */
const unusedValueExportToPlacateAjd$6 = 1;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/styling.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Store the static values for the styling binding.
*
* The `TStylingStatic` is just `KeyValueArray` where key `""` (stored at location 0) contains the
* `TStylingKey` (stored at location 1). In other words this wraps the `TStylingKey` such that the
* `""` contains the wrapped value.
*
* When instructions are resolving styling they may need to look forward or backwards in the linked
* list to resolve the value. For this reason we have to make sure that he linked list also contains
* the static values. However the list only has space for one item per styling instruction. For this
* reason we store the static values here as part of the `TStylingKey`. This means that the
* resolution function when looking for a value needs to first look at the binding value, and than
* at `TStylingKey` (if it exists).
*
* Imagine we have:
*
* ```
* <div class="TEMPLATE" my-dir>
*
* \@Directive({
* host: {
* class: 'DIR',
* '[class.dynamic]': 'exp' // ɵɵclassProp('dynamic', ctx.exp);
* }
* })
* ```
*
* In the above case the linked list will contain one item:
*
* ```
* // assume binding location: 10 for `ɵɵclassProp('dynamic', ctx.exp);`
* tData[10] = <TStylingStatic>[
* '': 'dynamic', // This is the wrapped value of `TStylingKey`
* 'DIR': true, // This is the default static value of directive binding.
* ];
* tData[10 + 1] = 0; // We don't have prev/next.
*
* lView[10] = undefined; // assume `ctx.exp` is `undefined`
* lView[10 + 1] = undefined; // Just normalized `lView[10]`
* ```
*
* So when the function is resolving styling value, it first needs to look into the linked list
* (there is none) and than into the static `TStylingStatic` too see if there is a default value for
* `dynamic` (there is not). Therefore it is safe to remove it.
*
* If setting `true` case:
* ```
* lView[10] = true; // assume `ctx.exp` is `true`
* lView[10 + 1] = true; // Just normalized `lView[10]`
* ```
* So when the function is resolving styling value, it first needs to look into the linked list
* (there is none) and than into `TNode.residualClass` (TNode.residualStyle) which contains
* ```
* tNode.residualClass = [
* 'TEMPLATE': true,
* ];
* ```
*
* This means that it is safe to add class.
* @record
*/
function TStylingStatic() { }
/**
* This is a branded number which contains previous and next index.
*
* When we come across styling instructions we need to store the `TStylingKey` in the correct
* order so that we can re-concatenate the styling value in the desired priority.
*
* The insertion can happen either at the:
* - end of template as in the case of coming across additional styling instruction in the template
* - in front of the template in the case of coming across additional instruction in the
* `hostBindings`.
*
* We use `TStylingRange` to store the previous and next index into the `TData` where the template
* bindings can be found.
*
* - bit 0 is used to mark that the previous index has a duplicate for current value.
* - bit 1 is used to mark that the next index has a duplicate for the current value.
* - bits 2-16 are used to encode the next/tail of the template.
* - bits 17-32 are used to encode the previous/head of template.
*
* NODE: *duplicate* false implies that it is statically known that this binding will not collide
* with other bindings and therefore there is no need to check other bindings. For example the
* bindings in `<div [style.color]="exp" [style.width]="exp">` will never collide and will have
* their bits set accordingly. Previous duplicate means that we may need to check previous if the
* current binding is `null`. Next duplicate means that we may need to check next bindings if the
* current binding is not `null`.
*
* NOTE: `0` has special significance and represents `null` as in no additional pointer.
* @record
*/
function TStylingRange() { }
if (false) {}
/** @enum {number} */
const StylingRange = {
/// Number of bits to shift for the previous pointer
PREV_SHIFT: 17,
/// Previous pointer mask.
PREV_MASK: 4294836224,
/// Number of bits to shift for the next pointer
NEXT_SHIFT: 2,
/// Next pointer mask.
NEXT_MASK: 131068,
// Mask to remove nagative bit. (interpret number as positive)
UNSIGNED_MASK: 32767,
/**
* This bit is set if the previous bindings contains a binding which could possibly cause a
* duplicate. For example: `<div [style]="map" [style.width]="width">`, the `width` binding will
* have previous duplicate set. The implication is that if `width` binding becomes `null`, it is
* necessary to defer the value to `map.width`. (Because `width` overwrites `map.width`.)
*/
PREV_DUPLICATE: 2,
/**
* This bit is set to if the next binding contains a binding which could possibly cause a
* duplicate. For example: `<div [style]="map" [style.width]="width">`, the `map` binding will
* have next duplicate set. The implication is that if `map.width` binding becomes not `null`, it
* is necessary to defer the value to `width`. (Because `width` overwrites `map.width`.)
*/
NEXT_DUPLICATE: 1,
};
/**
* @param {?} prev
* @param {?} next
* @return {?}
*/
function toTStylingRange(prev, next) {
ngDevMode && assertNumberInRange(prev, 0, 32767 /* UNSIGNED_MASK */);
ngDevMode && assertNumberInRange(next, 0, 32767 /* UNSIGNED_MASK */);
return (/** @type {?} */ ((prev << 17 /* PREV_SHIFT */ | next << 2 /* NEXT_SHIFT */)));
}
/**
* @param {?} tStylingRange
* @return {?}
*/
function getTStylingRangePrev(tStylingRange) {
ngDevMode && assertNumber(tStylingRange, 'expected number');
return (((/** @type {?} */ ((/** @type {?} */ (tStylingRange))))) >> 17 /* PREV_SHIFT */) & 32767 /* UNSIGNED_MASK */;
}
/**
* @param {?} tStylingRange
* @return {?}
*/
function getTStylingRangePrevDuplicate(tStylingRange) {
ngDevMode && assertNumber(tStylingRange, 'expected number');
return (((/** @type {?} */ ((/** @type {?} */ (tStylingRange))))) & 2 /* PREV_DUPLICATE */) ==
2 /* PREV_DUPLICATE */;
}
/**
* @param {?} tStylingRange
* @param {?} previous
* @return {?}
*/
function setTStylingRangePrev(tStylingRange, previous) {
ngDevMode && assertNumber(tStylingRange, 'expected number');
ngDevMode && assertNumberInRange(previous, 0, 32767 /* UNSIGNED_MASK */);
return (/** @type {?} */ (((((/** @type {?} */ ((/** @type {?} */ (tStylingRange))))) & ~4294836224 /* PREV_MASK */) |
(previous << 17 /* PREV_SHIFT */))));
}
/**
* @param {?} tStylingRange
* @return {?}
*/
function setTStylingRangePrevDuplicate(tStylingRange) {
ngDevMode && assertNumber(tStylingRange, 'expected number');
return (/** @type {?} */ ((((/** @type {?} */ ((/** @type {?} */ (tStylingRange))))) | 2 /* PREV_DUPLICATE */)));
}
/**
* @param {?} tStylingRange
* @return {?}
*/
function getTStylingRangeNext(tStylingRange) {
ngDevMode && assertNumber(tStylingRange, 'expected number');
return (((/** @type {?} */ ((/** @type {?} */ (tStylingRange))))) & 131068 /* NEXT_MASK */) >> 2 /* NEXT_SHIFT */;
}
/**
* @param {?} tStylingRange
* @param {?} next
* @return {?}
*/
function setTStylingRangeNext(tStylingRange, next) {
ngDevMode && assertNumber(tStylingRange, 'expected number');
ngDevMode && assertNumberInRange(next, 0, 32767 /* UNSIGNED_MASK */);
return (/** @type {?} */ (((((/** @type {?} */ ((/** @type {?} */ (tStylingRange))))) & ~131068 /* NEXT_MASK */) | //
next << 2 /* NEXT_SHIFT */)));
}
/**
* @param {?} tStylingRange
* @return {?}
*/
function getTStylingRangeNextDuplicate(tStylingRange) {
ngDevMode && assertNumber(tStylingRange, 'expected number');
return (((/** @type {?} */ ((/** @type {?} */ (tStylingRange))))) & 1 /* NEXT_DUPLICATE */) ===
1 /* NEXT_DUPLICATE */;
}
/**
* @param {?} tStylingRange
* @return {?}
*/
function setTStylingRangeNextDuplicate(tStylingRange) {
ngDevMode && assertNumber(tStylingRange, 'expected number');
return (/** @type {?} */ ((((/** @type {?} */ ((/** @type {?} */ (tStylingRange))))) | 1 /* NEXT_DUPLICATE */)));
}
/**
* @param {?} tStylingRange
* @return {?}
*/
function getTStylingRangeTail(tStylingRange) {
ngDevMode && assertNumber(tStylingRange, 'expected number');
/** @type {?} */
const next = getTStylingRangeNext(tStylingRange);
return next === 0 ? getTStylingRangePrev(tStylingRange) : next;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/util/debug_utils.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
* @param {?} obj
* @param {?} debug
* @return {?}
*/
function attachDebugObject(obj, debug) {
Object.defineProperty(obj, 'debug', { value: debug, enumerable: false });
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/lview_debug.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const NG_DEV_MODE = ((typeof ngDevMode === 'undefined' || !!ngDevMode) && initNgDevMode());
/*
* This file contains conditionally attached classes which provide human readable (debug) level
* information for `LView`, `LContainer` and other internal data structures. These data structures
* are stored internally as array which makes it very difficult during debugging to reason about the
* current state of the system.
*
* Patching the array with extra property does change the array's hidden class' but it does not
* change the cost of access, therefore this patching should not have significant if any impact in
* `ngDevMode` mode. (see: https://jsperf.com/array-vs-monkey-patch-array)
*
* So instead of seeing:
* ```
* Array(30) [Object, 659, null, …]
* ```
*
* You get to see:
* ```
* LViewDebug {
* views: [...],
* flags: {attached: true, ...}
* nodes: [
* {html: '<div id="123">', ..., nodes: [
* {html: '<span>', ..., nodes: null}
* ]}
* ]
* }
* ```
*/
/** @type {?} */
let LVIEW_COMPONENT_CACHE;
/** @type {?} */
let LVIEW_EMBEDDED_CACHE;
/** @type {?} */
let LVIEW_ROOT;
/**
* @record
*/
function TViewDebug() { }
if (false) {}
/**
* This function clones a blueprint and creates LView.
*
* Simple slice will keep the same type, and we need it to be LView
* @param {?} tView
* @return {?}
*/
function cloneToLViewFromTViewBlueprint(tView) {
/** @type {?} */
const debugTView = (/** @type {?} */ (tView));
/** @type {?} */
const lView = getLViewToClone(debugTView.type, tView.template && tView.template.name);
return (/** @type {?} */ (lView.concat(tView.blueprint)));
}
/**
* @param {?} type
* @param {?} name
* @return {?}
*/
function getLViewToClone(type, name) {
switch (type) {
case 0 /* Root */:
if (LVIEW_ROOT === undefined)
LVIEW_ROOT = new (createNamedArrayType('LRootView'))();
return LVIEW_ROOT;
case 1 /* Component */:
if (LVIEW_COMPONENT_CACHE === undefined)
LVIEW_COMPONENT_CACHE = new Map();
/** @type {?} */
let componentArray = LVIEW_COMPONENT_CACHE.get(name);
if (componentArray === undefined) {
componentArray = new (createNamedArrayType('LComponentView' + nameSuffix(name)))();
LVIEW_COMPONENT_CACHE.set(name, componentArray);
}
return componentArray;
case 2 /* Embedded */:
if (LVIEW_EMBEDDED_CACHE === undefined)
LVIEW_EMBEDDED_CACHE = new Map();
/** @type {?} */
let embeddedArray = LVIEW_EMBEDDED_CACHE.get(name);
if (embeddedArray === undefined) {
embeddedArray = new (createNamedArrayType('LEmbeddedView' + nameSuffix(name)))();
LVIEW_EMBEDDED_CACHE.set(name, embeddedArray);
}
return embeddedArray;
}
throw new Error('unreachable code');
}
/**
* @param {?} text
* @return {?}
*/
function nameSuffix(text) {
if (text == null)
return '';
/** @type {?} */
const index = text.lastIndexOf('_Template');
return '_' + (index === -1 ? text : text.substr(0, index));
}
/**
* This class is a debug version of Object literal so that we can have constructor name show up
* in
* debug tools in ngDevMode.
* @type {?}
*/
const TViewConstructor = class TView {
/**
* @param {?} type
* @param {?} id
* @param {?} blueprint
* @param {?} template
* @param {?} queries
* @param {?} viewQuery
* @param {?} node
* @param {?} data
* @param {?} bindingStartIndex
* @param {?} expandoStartIndex
* @param {?} expandoInstructions
* @param {?} firstCreatePass
* @param {?} firstUpdatePass
* @param {?} staticViewQueries
* @param {?} staticContentQueries
* @param {?} preOrderHooks
* @param {?} preOrderCheckHooks
* @param {?} contentHooks
* @param {?} contentCheckHooks
* @param {?} viewHooks
* @param {?} viewCheckHooks
* @param {?} destroyHooks
* @param {?} cleanup
* @param {?} contentQueries
* @param {?} components
* @param {?} directiveRegistry
* @param {?} pipeRegistry
* @param {?} firstChild
* @param {?} schemas
* @param {?} consts
* @param {?} incompleteFirstPass
*/
constructor(type, //
id, //
blueprint, //
template, //
queries, //
viewQuery, //
node, //
data, //
bindingStartIndex, //
expandoStartIndex, //
expandoInstructions, //
firstCreatePass, //
firstUpdatePass, //
staticViewQueries, //
staticContentQueries, //
preOrderHooks, //
preOrderCheckHooks, //
contentHooks, //
contentCheckHooks, //
viewHooks, //
viewCheckHooks, //
destroyHooks, //
cleanup, //
contentQueries, //
components, //
directiveRegistry, //
pipeRegistry, //
firstChild, //
schemas, //
consts, //
incompleteFirstPass //
) {
this.type = type;
this.id = id;
this.blueprint = blueprint;
this.template = template;
this.queries = queries;
this.viewQuery = viewQuery;
this.node = node;
this.data = data;
this.bindingStartIndex = bindingStartIndex;
this.expandoStartIndex = expandoStartIndex;
this.expandoInstructions = expandoInstructions;
this.firstCreatePass = firstCreatePass;
this.firstUpdatePass = firstUpdatePass;
this.staticViewQueries = staticViewQueries;
this.staticContentQueries = staticContentQueries;
this.preOrderHooks = preOrderHooks;
this.preOrderCheckHooks = preOrderCheckHooks;
this.contentHooks = contentHooks;
this.contentCheckHooks = contentCheckHooks;
this.viewHooks = viewHooks;
this.viewCheckHooks = viewCheckHooks;
this.destroyHooks = destroyHooks;
this.cleanup = cleanup;
this.contentQueries = contentQueries;
this.components = components;
this.directiveRegistry = directiveRegistry;
this.pipeRegistry = pipeRegistry;
this.firstChild = firstChild;
this.schemas = schemas;
this.consts = consts;
this.incompleteFirstPass = incompleteFirstPass;
}
/**
* @return {?}
*/
get template_() {
/** @type {?} */
const buf = [];
processTNodeChildren(this.firstChild, buf);
return buf.join('');
}
};
class TNode$1 {
/**
* @param {?} tView_
* @param {?} type
* @param {?} index
* @param {?} injectorIndex
* @param {?} directiveStart
* @param {?} directiveEnd
* @param {?} directiveStylingLast
* @param {?} propertyBindings
* @param {?} flags
* @param {?} providerIndexes
* @param {?} tagName
* @param {?} attrs
* @param {?} mergedAttrs
* @param {?} localNames
* @param {?} initialInputs
* @param {?} inputs
* @param {?} outputs
* @param {?} tViews
* @param {?} next
* @param {?} projectionNext
* @param {?} child
* @param {?} parent
* @param {?} projection
* @param {?} styles
* @param {?} stylesWithoutHost
* @param {?} residualStyles
* @param {?} classes
* @param {?} classesWithoutHost
* @param {?} residualClasses
* @param {?} classBindings
* @param {?} styleBindings
*/
constructor(tView_, //
type, //
index, //
injectorIndex, //
directiveStart, //
directiveEnd, //
directiveStylingLast, //
propertyBindings, //
flags, //
providerIndexes, //
tagName, //
attrs, //
mergedAttrs, //
localNames, //
initialInputs, //
inputs, //
outputs, //
tViews, //
next, //
projectionNext, //
child, //
parent, //
projection, //
styles, //
stylesWithoutHost, //
residualStyles, //
classes, //
classesWithoutHost, //
residualClasses, //
classBindings, //
styleBindings) {
this.tView_ = tView_;
this.type = type;
this.index = index;
this.injectorIndex = injectorIndex;
this.directiveStart = directiveStart;
this.directiveEnd = directiveEnd;
this.directiveStylingLast = directiveStylingLast;
this.propertyBindings = propertyBindings;
this.flags = flags;
this.providerIndexes = providerIndexes;
this.tagName = tagName;
this.attrs = attrs;
this.mergedAttrs = mergedAttrs;
this.localNames = localNames;
this.initialInputs = initialInputs;
this.inputs = inputs;
this.outputs = outputs;
this.tViews = tViews;
this.next = next;
this.projectionNext = projectionNext;
this.child = child;
this.parent = parent;
this.projection = projection;
this.styles = styles;
this.stylesWithoutHost = stylesWithoutHost;
this.residualStyles = residualStyles;
this.classes = classes;
this.classesWithoutHost = classesWithoutHost;
this.residualClasses = residualClasses;
this.classBindings = classBindings;
this.styleBindings = styleBindings;
}
/**
* @return {?}
*/
get type_() {
switch (this.type) {
case 0 /* Container */:
return 'TNodeType.Container';
case 3 /* Element */:
return 'TNodeType.Element';
case 4 /* ElementContainer */:
return 'TNodeType.ElementContainer';
case 5 /* IcuContainer */:
return 'TNodeType.IcuContainer';
case 1 /* Projection */:
return 'TNodeType.Projection';
case 2 /* View */:
return 'TNodeType.View';
default:
return 'TNodeType.???';
}
}
/**
* @return {?}
*/
get flags_() {
/** @type {?} */
const flags = [];
if (this.flags & 16 /* hasClassInput */)
flags.push('TNodeFlags.hasClassInput');
if (this.flags & 8 /* hasContentQuery */)
flags.push('TNodeFlags.hasContentQuery');
if (this.flags & 32 /* hasStyleInput */)
flags.push('TNodeFlags.hasStyleInput');
if (this.flags & 128 /* hasHostBindings */)
flags.push('TNodeFlags.hasHostBindings');
if (this.flags & 2 /* isComponentHost */)
flags.push('TNodeFlags.isComponentHost');
if (this.flags & 1 /* isDirectiveHost */)
flags.push('TNodeFlags.isDirectiveHost');
if (this.flags & 64 /* isDetached */)
flags.push('TNodeFlags.isDetached');
if (this.flags & 4 /* isProjected */)
flags.push('TNodeFlags.isProjected');
return flags.join('|');
}
/**
* @return {?}
*/
get template_() {
/** @type {?} */
const buf = [];
buf.push('<', this.tagName || this.type_);
if (this.attrs) {
for (let i = 0; i < this.attrs.length;) {
/** @type {?} */
const attrName = this.attrs[i++];
if (typeof attrName == 'number') {
break;
}
/** @type {?} */
const attrValue = this.attrs[i++];
buf.push(' ', (/** @type {?} */ (attrName)), '="', (/** @type {?} */ (attrValue)), '"');
}
}
buf.push('>');
processTNodeChildren(this.child, buf);
buf.push('</', this.tagName || this.type_, '>');
return buf.join('');
}
/**
* @return {?}
*/
get styleBindings_() {
return toDebugStyleBinding(this, false);
}
/**
* @return {?}
*/
get classBindings_() {
return toDebugStyleBinding(this, true);
}
}
if (false) {}
/** @type {?} */
const TNodeDebug = TNode$1;
/**
* @record
*/
function DebugStyleBindings() { }
/**
* @record
*/
function DebugStyleBinding() { }
if (false) {}
/**
* @param {?} tNode
* @param {?} isClassBased
* @return {?}
*/
function toDebugStyleBinding(tNode, isClassBased) {
/** @type {?} */
const tData = tNode.tView_.data;
/** @type {?} */
const bindings = (/** @type {?} */ ([]));
/** @type {?} */
const range = isClassBased ? tNode.classBindings : tNode.styleBindings;
/** @type {?} */
const prev = getTStylingRangePrev(range);
/** @type {?} */
const next = getTStylingRangeNext(range);
/** @type {?} */
let isTemplate = next !== 0;
/** @type {?} */
let cursor = isTemplate ? next : prev;
while (cursor !== 0) {
/** @type {?} */
const itemKey = (/** @type {?} */ (tData[cursor]));
/** @type {?} */
const itemRange = (/** @type {?} */ (tData[cursor + 1]));
bindings.unshift({
key: itemKey,
index: cursor,
isTemplate: isTemplate,
prevDuplicate: getTStylingRangePrevDuplicate(itemRange),
nextDuplicate: getTStylingRangeNextDuplicate(itemRange),
nextIndex: getTStylingRangeNext(itemRange),
prevIndex: getTStylingRangePrev(itemRange),
});
if (cursor === prev)
isTemplate = false;
cursor = getTStylingRangePrev(itemRange);
}
bindings.push((isClassBased ? tNode.residualClasses : tNode.residualStyles) || null);
return bindings;
}
/**
* @param {?} tNode
* @param {?} buf
* @return {?}
*/
function processTNodeChildren(tNode, buf) {
while (tNode) {
buf.push(((/** @type {?} */ ((/** @type {?} */ (tNode))))).template_);
tNode = tNode.next;
}
}
/** @type {?} */
const TViewData = NG_DEV_MODE && createNamedArrayType('TViewData') || (/** @type {?} */ ((/** @type {?} */ (null))));
/** @type {?} */
let TVIEWDATA_EMPTY;
// can't initialize here or it will not be tree shaken, because
// `LView` constructor could have side-effects.
/**
* This function clones a blueprint and creates TData.
*
* Simple slice will keep the same type, and we need it to be TData
* @param {?} list
* @return {?}
*/
function cloneToTViewData(list) {
if (TVIEWDATA_EMPTY === undefined)
TVIEWDATA_EMPTY = new TViewData();
return (/** @type {?} */ (TVIEWDATA_EMPTY.concat(list)));
}
/** @type {?} */
const LViewBlueprint = NG_DEV_MODE && createNamedArrayType('LViewBlueprint') || (/** @type {?} */ ((/** @type {?} */ (null))));
/** @type {?} */
const MatchesArray = NG_DEV_MODE && createNamedArrayType('MatchesArray') || (/** @type {?} */ ((/** @type {?} */ (null))));
/** @type {?} */
const TViewComponents = NG_DEV_MODE && createNamedArrayType('TViewComponents') || (/** @type {?} */ ((/** @type {?} */ (null))));
/** @type {?} */
const TNodeLocalNames = NG_DEV_MODE && createNamedArrayType('TNodeLocalNames') || (/** @type {?} */ ((/** @type {?} */ (null))));
/** @type {?} */
const TNodeInitialInputs = NG_DEV_MODE && createNamedArrayType('TNodeInitialInputs') || (/** @type {?} */ ((/** @type {?} */ (null))));
/** @type {?} */
const TNodeInitialData = NG_DEV_MODE && createNamedArrayType('TNodeInitialData') || (/** @type {?} */ ((/** @type {?} */ (null))));
/** @type {?} */
const LCleanup = NG_DEV_MODE && createNamedArrayType('LCleanup') || (/** @type {?} */ ((/** @type {?} */ (null))));
/** @type {?} */
const TCleanup = NG_DEV_MODE && createNamedArrayType('TCleanup') || (/** @type {?} */ ((/** @type {?} */ (null))));
/**
* @param {?} lView
* @return {?}
*/
function attachLViewDebug(lView) {
attachDebugObject(lView, new LViewDebug(lView));
}
/**
* @param {?} lContainer
* @return {?}
*/
function attachLContainerDebug(lContainer) {
attachDebugObject(lContainer, new LContainerDebug(lContainer));
}
/**
* @param {?} obj
* @return {?}
*/
function toDebug(obj) {
if (obj) {
/** @type {?} */
const debug = ((/** @type {?} */ (obj))).debug;
assertDefined(debug, 'Object does not have a debug representation.');
return debug;
}
else {
return obj;
}
}
/**
* Use this method to unwrap a native element in `LView` and convert it into HTML for easier
* reading.
*
* @param {?} value possibly wrapped native DOM node.
* @param {?=} includeChildren If `true` then the serialized HTML form will include child elements
* (same
* as `outerHTML`). If `false` then the serialized HTML form will only contain the element
* itself
* (will not serialize child elements).
* @return {?}
*/
function toHtml(value, includeChildren = false) {
/** @type {?} */
const node = (/** @type {?} */ (unwrapRNode(value)));
if (node) {
/** @type {?} */
const isTextNode = node.nodeType === Node.TEXT_NODE;
/** @type {?} */
const outerHTML = (isTextNode ? node.textContent : node.outerHTML) || '';
if (includeChildren || isTextNode) {
return outerHTML;
}
else {
/** @type {?} */
const innerHTML = '>' + node.innerHTML + '<';
return (outerHTML.split(innerHTML)[0]) + '>';
}
}
else {
return null;
}
}
class LViewDebug {
/**
* @param {?} _raw_lView
*/
constructor(_raw_lView) {
this._raw_lView = _raw_lView;
}
/**
* Flags associated with the `LView` unpacked into a more readable state.
* @return {?}
*/
get flags() {
/** @type {?} */
const flags = this._raw_lView[FLAGS];
return {
__raw__flags__: flags,
initPhaseState: flags & 3 /* InitPhaseStateMask */,
creationMode: !!(flags & 4 /* CreationMode */),
firstViewPass: !!(flags & 8 /* FirstLViewPass */),
checkAlways: !!(flags & 16 /* CheckAlways */),
dirty: !!(flags & 64 /* Dirty */),
attached: !!(flags & 128 /* Attached */),
destroyed: !!(flags & 256 /* Destroyed */),
isRoot: !!(flags & 512 /* IsRoot */),
indexWithinInitPhase: flags >> 11 /* IndexWithinInitPhaseShift */,
};
}
/**
* @return {?}
*/
get parent() {
return toDebug(this._raw_lView[PARENT]);
}
/**
* @return {?}
*/
get host() {
return toHtml(this._raw_lView[HOST], true);
}
/**
* @return {?}
*/
get html() {
return (this.nodes || []).map((/**
* @param {?} node
* @return {?}
*/
node => toHtml(node.native, true))).join('');
}
/**
* @return {?}
*/
get context() {
return this._raw_lView[CONTEXT];
}
/**
* The tree of nodes associated with the current `LView`. The nodes have been normalized into
* a
* tree structure with relevant details pulled out for readability.
* @return {?}
*/
get nodes() {
/** @type {?} */
const lView = this._raw_lView;
/** @type {?} */
const tNode = lView[TVIEW].firstChild;
return toDebugNodes(tNode, lView);
}
/**
* @return {?}
*/
get tView() {
return this._raw_lView[TVIEW];
}
/**
* @return {?}
*/
get cleanup() {
return this._raw_lView[CLEANUP];
}
/**
* @return {?}
*/
get injector() {
return this._raw_lView[INJECTOR$1];
}
/**
* @return {?}
*/
get rendererFactory() {
return this._raw_lView[RENDERER_FACTORY];
}
/**
* @return {?}
*/
get renderer() {
return this._raw_lView[RENDERER];
}
/**
* @return {?}
*/
get sanitizer() {
return this._raw_lView[SANITIZER];
}
/**
* @return {?}
*/
get childHead() {
return toDebug(this._raw_lView[CHILD_HEAD]);
}
/**
* @return {?}
*/
get next() {
return toDebug(this._raw_lView[NEXT]);
}
/**
* @return {?}
*/
get childTail() {
return toDebug(this._raw_lView[CHILD_TAIL]);
}
/**
* @return {?}
*/
get declarationView() {
return toDebug(this._raw_lView[DECLARATION_VIEW]);
}
/**
* @return {?}
*/
get queries() {
return this._raw_lView[QUERIES];
}
/**
* @return {?}
*/
get tHost() {
return this._raw_lView[T_HOST];
}
/**
* Normalized view of child views (and containers) attached at this location.
* @return {?}
*/
get childViews() {
/** @type {?} */
const childViews = [];
/** @type {?} */
let child = this.childHead;
while (child) {
childViews.push(child);
child = child.next;
}
return childViews;
}
}
if (false) {}
/**
* @record
*/
function DebugNode() { }
if (false) {}
/**
* Turns a flat list of nodes into a tree by walking the associated `TNode` tree.
*
* @param {?} tNode
* @param {?} lView
* @return {?}
*/
function toDebugNodes(tNode, lView) {
if (tNode) {
/** @type {?} */
const debugNodes = [];
/** @type {?} */
let tNodeCursor = tNode;
while (tNodeCursor) {
debugNodes.push(buildDebugNode(tNodeCursor, lView, tNodeCursor.index));
tNodeCursor = tNodeCursor.next;
}
return debugNodes;
}
else {
return null;
}
}
/**
* @param {?} tNode
* @param {?} lView
* @param {?} nodeIndex
* @return {?}
*/
function buildDebugNode(tNode, lView, nodeIndex) {
/** @type {?} */
const rawValue = lView[nodeIndex];
/** @type {?} */
const native = unwrapRNode(rawValue);
/** @type {?} */
const componentLViewDebug = toDebug(readLViewValue(rawValue));
return {
html: toHtml(native),
native: (/** @type {?} */ (native)),
nodes: toDebugNodes(tNode.child, lView),
component: componentLViewDebug,
};
}
class LContainerDebug {
/**
* @param {?} _raw_lContainer
*/
constructor(_raw_lContainer) {
this._raw_lContainer = _raw_lContainer;
}
/**
* @return {?}
*/
get hasTransplantedViews() {
return this._raw_lContainer[HAS_TRANSPLANTED_VIEWS];
}
/**
* @return {?}
*/
get views() {
return this._raw_lContainer.slice(CONTAINER_HEADER_OFFSET)
.map((/** @type {?} */ (toDebug)));
}
/**
* @return {?}
*/
get parent() {
return toDebug(this._raw_lContainer[PARENT]);
}
/**
* @return {?}
*/
get movedViews() {
return this._raw_lContainer[MOVED_VIEWS];
}
/**
* @return {?}
*/
get host() {
return this._raw_lContainer[HOST];
}
/**
* @return {?}
*/
get native() {
return this._raw_lContainer[NATIVE];
}
/**
* @return {?}
*/
get next() {
return toDebug(this._raw_lContainer[NEXT]);
}
}
if (false) {}
/**
* Return an `LView` value if found.
*
* @param {?} value `LView` if any
* @return {?}
*/
function readLViewValue(value) {
while (Array.isArray(value)) {
// This check is not quite right, as it does not take into account `StylingContext`
// This is why it is in debug, not in util.ts
if (value.length >= HEADER_OFFSET - 1)
return (/** @type {?} */ (value));
value = value[HOST];
}
return null;
}
class I18NDebugItem {
/**
* @param {?} __raw_opCode
* @param {?} _lView
* @param {?} nodeIndex
* @param {?} type
*/
constructor(__raw_opCode, _lView, nodeIndex, type) {
this.__raw_opCode = __raw_opCode;
this._lView = _lView;
this.nodeIndex = nodeIndex;
this.type = type;
}
/**
* @return {?}
*/
get tNode() {
return getTNode(this._lView[TVIEW], this.nodeIndex);
}
}
if (false) {}
/**
* Turns a list of "Create" & "Update" OpCodes into a human-readable list of operations for
* debugging purposes.
* @param {?} mutateOpCodes mutation opCodes to read
* @param {?} updateOpCodes update opCodes to read
* @param {?} icus list of ICU expressions
* @param {?} lView The view the opCodes are acting on
* @return {?}
*/
function attachI18nOpCodesDebug(mutateOpCodes, updateOpCodes, icus, lView) {
attachDebugObject(mutateOpCodes, new I18nMutateOpCodesDebug(mutateOpCodes, lView));
attachDebugObject(updateOpCodes, new I18nUpdateOpCodesDebug(updateOpCodes, icus, lView));
if (icus) {
icus.forEach((/**
* @param {?} icu
* @return {?}
*/
icu => {
icu.create.forEach((/**
* @param {?} icuCase
* @return {?}
*/
icuCase => {
attachDebugObject(icuCase, new I18nMutateOpCodesDebug(icuCase, lView));
}));
icu.update.forEach((/**
* @param {?} icuCase
* @return {?}
*/
icuCase => {
attachDebugObject(icuCase, new I18nUpdateOpCodesDebug(icuCase, icus, lView));
}));
}));
}
}
class I18nMutateOpCodesDebug {
/**
* @param {?} __raw_opCodes
* @param {?} __lView
*/
constructor(__raw_opCodes, __lView) {
this.__raw_opCodes = __raw_opCodes;
this.__lView = __lView;
}
/**
* A list of operation information about how the OpCodes will act on the view.
* @return {?}
*/
get operations() {
const { __lView, __raw_opCodes } = this;
/** @type {?} */
const results = [];
for (let i = 0; i < __raw_opCodes.length; i++) {
/** @type {?} */
const opCode = __raw_opCodes[i];
/** @type {?} */
let result;
if (typeof opCode === 'string') {
result = {
__raw_opCode: opCode,
type: 'Create Text Node',
nodeIndex: __raw_opCodes[++i],
text: opCode,
};
}
if (typeof opCode === 'number') {
switch (opCode & 7 /* MASK_OPCODE */) {
case 1 /* AppendChild */:
/** @type {?} */
const destinationNodeIndex = opCode >>> 17 /* SHIFT_PARENT */;
result = new I18NDebugItem(opCode, __lView, destinationNodeIndex, 'AppendChild');
break;
case 0 /* Select */:
/** @type {?} */
const nodeIndex = opCode >>> 3 /* SHIFT_REF */;
result = new I18NDebugItem(opCode, __lView, nodeIndex, 'Select');
break;
case 5 /* ElementEnd */:
/** @type {?} */
let elementIndex = opCode >>> 3 /* SHIFT_REF */;
result = new I18NDebugItem(opCode, __lView, elementIndex, 'ElementEnd');
break;
case 4 /* Attr */:
elementIndex = opCode >>> 3 /* SHIFT_REF */;
result = new I18NDebugItem(opCode, __lView, elementIndex, 'Attr');
result['attrName'] = __raw_opCodes[++i];
result['attrValue'] = __raw_opCodes[++i];
break;
}
}
if (!result) {
switch (opCode) {
case COMMENT_MARKER:
result = {
__raw_opCode: opCode,
type: 'COMMENT_MARKER',
commentValue: __raw_opCodes[++i],
nodeIndex: __raw_opCodes[++i],
};
break;
case ELEMENT_MARKER:
result = {
__raw_opCode: opCode,
type: 'ELEMENT_MARKER',
};
break;
}
}
if (!result) {
result = {
__raw_opCode: opCode,
type: 'Unknown Op Code',
code: opCode,
};
}
results.push(result);
}
return results;
}
}
if (false) {}
class I18nUpdateOpCodesDebug {
/**
* @param {?} __raw_opCodes
* @param {?} icus
* @param {?} __lView
*/
constructor(__raw_opCodes, icus, __lView) {
this.__raw_opCodes = __raw_opCodes;
this.icus = icus;
this.__lView = __lView;
}
/**
* A list of operation information about how the OpCodes will act on the view.
* @return {?}
*/
get operations() {
const { __lView, __raw_opCodes, icus } = this;
/** @type {?} */
const results = [];
for (let i = 0; i < __raw_opCodes.length; i++) {
// bit code to check if we should apply the next update
/** @type {?} */
const checkBit = (/** @type {?} */ (__raw_opCodes[i]));
// Number of opCodes to skip until next set of update codes
/** @type {?} */
const skipCodes = (/** @type {?} */ (__raw_opCodes[++i]));
/** @type {?} */
let value = '';
for (let j = i + 1; j <= (i + skipCodes); j++) {
/** @type {?} */
const opCode = __raw_opCodes[j];
if (typeof opCode === 'string') {
value += opCode;
}
else if (typeof opCode == 'number') {
if (opCode < 0) {
// It's a binding index whose value is negative
// We cannot know the value of the binding so we only show the index
value += `�${-opCode - 1}�`;
}
else {
/** @type {?} */
const nodeIndex = opCode >>> 2 /* SHIFT_REF */;
/** @type {?} */
let tIcuIndex;
/** @type {?} */
let tIcu;
switch (opCode & 3 /* MASK_OPCODE */) {
case 1 /* Attr */:
/** @type {?} */
const attrName = (/** @type {?} */ (__raw_opCodes[++j]));
/** @type {?} */
const sanitizeFn = __raw_opCodes[++j];
results.push({
__raw_opCode: opCode,
checkBit,
type: 'Attr',
attrValue: value,
attrName,
sanitizeFn,
});
break;
case 0 /* Text */:
results.push({
__raw_opCode: opCode,
checkBit,
type: 'Text',
nodeIndex,
text: value,
});
break;
case 2 /* IcuSwitch */:
tIcuIndex = (/** @type {?} */ (__raw_opCodes[++j]));
tIcu = (/** @type {?} */ (icus))[tIcuIndex];
/** @type {?} */
let result = new I18NDebugItem(opCode, __lView, nodeIndex, 'IcuSwitch');
result['tIcuIndex'] = tIcuIndex;
result['checkBit'] = checkBit;
result['mainBinding'] = value;
result['tIcu'] = tIcu;
results.push(result);
break;
case 3 /* IcuUpdate */:
tIcuIndex = (/** @type {?} */ (__raw_opCodes[++j]));
tIcu = (/** @type {?} */ (icus))[tIcuIndex];
result = new I18NDebugItem(opCode, __lView, nodeIndex, 'IcuUpdate');
result['tIcuIndex'] = tIcuIndex;
result['checkBit'] = checkBit;
result['tIcu'] = tIcu;
results.push(result);
break;
}
}
}
}
i += skipCodes;
}
return results;
}
}
if (false) {}
/**
* @record
*/
function I18nOpCodesDebug() { }
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/shared.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
const ɵ0$4 = /**
* @return {?}
*/
() => Promise.resolve(null);
/**
* A permanent marker promise which signifies that the current CD tree is
* clean.
* @type {?}
*/
const _CLEAN_PROMISE = ((ɵ0$4))();
/**
* Process the `TView.expandoInstructions`. (Execute the `hostBindings`.)
*
* @param {?} tView `TView` containing the `expandoInstructions`
* @param {?} lView `LView` associated with the `TView`
* @return {?}
*/
function setHostBindingsByExecutingExpandoInstructions(tView, lView) {
ngDevMode && assertSame(tView, lView[TVIEW], '`LView` is not associated with the `TView`!');
try {
/** @type {?} */
const expandoInstructions = tView.expandoInstructions;
if (expandoInstructions !== null) {
/** @type {?} */
let bindingRootIndex = tView.expandoStartIndex;
/** @type {?} */
let currentDirectiveIndex = -1;
/** @type {?} */
let currentElementIndex = -1;
// TODO(misko): PERF It is possible to get here with `TView.expandoInstructions` containing no
// functions to execute. This is wasteful as there is no work to be done, but we still need
// to iterate over the instructions.
// In example of this is in this test: `host_binding_spec.ts`
// `fit('should not cause problems if detectChanges is called when a property updates', ...`
// In the above test we get here with expando [0, 0, 1] which requires a lot of processing but
// there is no function to execute.
for (let i = 0; i < expandoInstructions.length; i++) {
/** @type {?} */
const instruction = expandoInstructions[i];
if (typeof instruction === 'number') {
if (instruction <= 0) {
// Negative numbers mean that we are starting new EXPANDO block and need to update
// the current element and directive index.
// Important: In JS `-x` and `0-x` is not the same! If `x===0` then `-x` will produce
// `-0` which requires non standard math arithmetic and it can prevent VM optimizations.
// `0-0` will always produce `0` and will not cause a potential deoptimization in VM.
// TODO(misko): PERF This should be refactored to use `~instruction` as that does not
// suffer from `-0` and it is faster/more compact.
currentElementIndex = 0 - instruction;
setSelectedIndex(currentElementIndex);
// Injector block and providers are taken into account.
/** @type {?} */
const providerCount = ((/** @type {?} */ (expandoInstructions[++i])));
bindingRootIndex += INJECTOR_BLOOM_PARENT_SIZE + providerCount;
currentDirectiveIndex = bindingRootIndex;
}
else {
// This is either the injector size (so the binding root can skip over directives
// and get to the first set of host bindings on this node) or the host var count
// (to get to the next set of host bindings on this node).
bindingRootIndex += instruction;
}
}
else {
// If it's not a number, it's a host binding function that needs to be executed.
if (instruction !== null) {
setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex);
/** @type {?} */
const hostCtx = lView[currentDirectiveIndex];
instruction(2 /* Update */, hostCtx);
}
// TODO(misko): PERF Relying on incrementing the `currentDirectiveIndex` here is
// sub-optimal. The implications are that if we have a lot of directives but none of them
// have host bindings we nevertheless need to iterate over the expando instructions to
// update the counter. It would be much better if we could encode the
// `currentDirectiveIndex` into the `expandoInstruction` array so that we only need to
// iterate over those directives which actually have `hostBindings`.
currentDirectiveIndex++;
}
}
}
}
finally {
setSelectedIndex(-1);
}
}
/**
* Refreshes all content queries declared by directives in a given view
* @param {?} tView
* @param {?} lView
* @return {?}
*/
function refreshContentQueries(tView, lView) {
/** @type {?} */
const contentQueries = tView.contentQueries;
if (contentQueries !== null) {
for (let i = 0; i < contentQueries.length; i += 2) {
/** @type {?} */
const queryStartIdx = contentQueries[i];
/** @type {?} */
const directiveDefIdx = contentQueries[i + 1];
if (directiveDefIdx !== -1) {
/** @type {?} */
const directiveDef = (/** @type {?} */ (tView.data[directiveDefIdx]));
ngDevMode &&
assertDefined(directiveDef.contentQueries, 'contentQueries function should be defined');
setCurrentQueryIndex(queryStartIdx);
(/** @type {?} */ (directiveDef.contentQueries))(2 /* Update */, lView[directiveDefIdx], directiveDefIdx);
}
}
}
}
/**
* Refreshes child components in the current view (update mode).
* @param {?} hostLView
* @param {?} components
* @return {?}
*/
function refreshChildComponents(hostLView, components) {
for (let i = 0; i < components.length; i++) {
refreshComponent(hostLView, components[i]);
}
}
/**
* Renders child components in the current view (creation mode).
* @param {?} hostLView
* @param {?} components
* @return {?}
*/
function renderChildComponents(hostLView, components) {
for (let i = 0; i < components.length; i++) {
renderComponent(hostLView, components[i]);
}
}
/**
* Creates a native element from a tag name, using a renderer.
* @param {?} name the tag name
* @param {?} renderer A renderer to use
* @param {?} namespace
* @return {?} the element created
*/
function elementCreate(name, renderer, namespace) {
if (isProceduralRenderer(renderer)) {
return renderer.createElement(name, namespace);
}
else {
return namespace === null ? renderer.createElement(name) :
renderer.createElementNS(namespace, name);
}
}
/**
* @template T
* @param {?} parentLView
* @param {?} tView
* @param {?} context
* @param {?} flags
* @param {?} host
* @param {?} tHostNode
* @param {?=} rendererFactory
* @param {?=} renderer
* @param {?=} sanitizer
* @param {?=} injector
* @return {?}
*/
function createLView(parentLView, tView, context, flags, host, tHostNode, rendererFactory, renderer, sanitizer, injector) {
/** @type {?} */
const lView = ngDevMode ? cloneToLViewFromTViewBlueprint(tView) : (/** @type {?} */ (tView.blueprint.slice()));
lView[HOST] = host;
lView[FLAGS] = flags | 4 /* CreationMode */ | 128 /* Attached */ | 8 /* FirstLViewPass */;
resetPreOrderHookFlags(lView);
lView[PARENT] = lView[DECLARATION_VIEW] = parentLView;
lView[CONTEXT] = context;
lView[RENDERER_FACTORY] = (/** @type {?} */ ((rendererFactory || parentLView && parentLView[RENDERER_FACTORY])));
ngDevMode && assertDefined(lView[RENDERER_FACTORY], 'RendererFactory is required');
lView[RENDERER] = (/** @type {?} */ ((renderer || parentLView && parentLView[RENDERER])));
ngDevMode && assertDefined(lView[RENDERER], 'Renderer is required');
lView[SANITIZER] = sanitizer || parentLView && parentLView[SANITIZER] || (/** @type {?} */ (null));
lView[(/** @type {?} */ (INJECTOR$1))] = injector || parentLView && parentLView[INJECTOR$1] || null;
lView[T_HOST] = tHostNode;
ngDevMode &&
assertEqual(tView.type == 2 /* Embedded */ ? parentLView !== null : true, true, 'Embedded views must have parentLView');
lView[DECLARATION_COMPONENT_VIEW] =
tView.type == 2 /* Embedded */ ? (/** @type {?} */ (parentLView))[DECLARATION_COMPONENT_VIEW] : lView;
ngDevMode && attachLViewDebug(lView);
return lView;
}
/**
* @param {?} tView
* @param {?} tHostNode
* @param {?} index
* @param {?} type
* @param {?} name
* @param {?} attrs
* @return {?}
*/
function getOrCreateTNode(tView, tHostNode, index, type, name, attrs) {
// Keep this function short, so that the VM will inline it.
/** @type {?} */
const adjustedIndex = index + HEADER_OFFSET;
/** @type {?} */
const tNode = (/** @type {?} */ (tView.data[adjustedIndex])) ||
createTNodeAtIndex(tView, tHostNode, adjustedIndex, type, name, attrs);
setPreviousOrParentTNode(tNode, true);
return (/** @type {?} */ (tNode));
}
/**
* @param {?} tView
* @param {?} tHostNode
* @param {?} adjustedIndex
* @param {?} type
* @param {?} name
* @param {?} attrs
* @return {?}
*/
function createTNodeAtIndex(tView, tHostNode, adjustedIndex, type, name, attrs) {
/** @type {?} */
const previousOrParentTNode = getPreviousOrParentTNode();
/** @type {?} */
const isParent = getIsParent();
/** @type {?} */
const parent = isParent ? previousOrParentTNode : previousOrParentTNode && previousOrParentTNode.parent;
// Parents cannot cross component boundaries because components will be used in multiple places,
// so it's only set if the view is the same.
/** @type {?} */
const parentInSameView = parent && parent !== tHostNode;
/** @type {?} */
const tParentNode = parentInSameView ? (/** @type {?} */ (parent)) : null;
/** @type {?} */
const tNode = tView.data[adjustedIndex] =
createTNode(tView, tParentNode, type, adjustedIndex, name, attrs);
// Assign a pointer to the first child node of a given view. The first node is not always the one
// at index 0, in case of i18n, index 0 can be the instruction `i18nStart` and the first node has
// the index 1 or more, so we can't just check node index.
if (tView.firstChild === null) {
tView.firstChild = tNode;
}
if (previousOrParentTNode) {
if (isParent && previousOrParentTNode.child == null &&
(tNode.parent !== null || previousOrParentTNode.type === 2 /* View */)) {
// We are in the same view, which means we are adding content node to the parent view.
previousOrParentTNode.child = tNode;
}
else if (!isParent) {
previousOrParentTNode.next = tNode;
}
}
return tNode;
}
/**
* @param {?} tView
* @param {?} tParentNode
* @param {?} index
* @param {?} lView
* @return {?}
*/
function assignTViewNodeToLView(tView, tParentNode, index, lView) {
// View nodes are not stored in data because they can be added / removed at runtime (which
// would cause indices to change). Their TNodes are instead stored in tView.node.
/** @type {?} */
let tNode = tView.node;
if (tNode == null) {
ngDevMode && tParentNode &&
assertNodeOfPossibleTypes(tParentNode, 3 /* Element */, 0 /* Container */);
tView.node = tNode = (/** @type {?} */ (createTNode(tView, (/** @type {?} */ (tParentNode)), //
2 /* View */, index, null, null)));
}
lView[T_HOST] = (/** @type {?} */ (tNode));
}
/**
* When elements are created dynamically after a view blueprint is created (e.g. through
* i18nApply() or ComponentFactory.create), we need to adjust the blueprint for future
* template passes.
*
* @param {?} tView `TView` associated with `LView`
* @param {?} lView
* @param {?} numSlotsToAlloc The number of slots to alloc in the LView, should be >0
* @return {?}
*/
function allocExpando(tView, lView, numSlotsToAlloc) {
ngDevMode &&
assertGreaterThan(numSlotsToAlloc, 0, 'The number of slots to alloc should be greater than 0');
if (numSlotsToAlloc > 0) {
if (tView.firstCreatePass) {
for (let i = 0; i < numSlotsToAlloc; i++) {
tView.blueprint.push(null);
tView.data.push(null);
lView.push(null);
}
// We should only increment the expando start index if there aren't already directives
// and injectors saved in the "expando" section
if (!tView.expandoInstructions) {
tView.expandoStartIndex += numSlotsToAlloc;
}
else {
// Since we're adding the dynamic nodes into the expando section, we need to let the host
// bindings know that they should skip x slots
tView.expandoInstructions.push(numSlotsToAlloc);
}
}
}
}
//////////////////////////
//// Render
//////////////////////////
/**
* Processes a view in the creation mode. This includes a number of steps in a specific order:
* - creating view query functions (if any);
* - executing a template function in the creation mode;
* - updating static queries (if any);
* - creating child components defined in a given view.
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} context
* @return {?}
*/
function renderView(tView, lView, context) {
ngDevMode && assertEqual(isCreationMode(lView), true, 'Should be run in creation mode');
enterView(lView, lView[T_HOST]);
try {
/** @type {?} */
const viewQuery = tView.viewQuery;
if (viewQuery !== null) {
executeViewQueryFn(1 /* Create */, viewQuery, context);
}
// Execute a template associated with this view, if it exists. A template function might not be
// defined for the root component views.
/** @type {?} */
const templateFn = tView.template;
if (templateFn !== null) {
executeTemplate(tView, lView, templateFn, 1 /* Create */, context);
}
// This needs to be set before children are processed to support recursive components.
// This must be set to false immediately after the first creation run because in an
// ngFor loop, all the views will be created together before update mode runs and turns
// off firstCreatePass. If we don't set it here, instances will perform directive
// matching, etc again and again.
if (tView.firstCreatePass) {
tView.firstCreatePass = false;
}
// We resolve content queries specifically marked as `static` in creation mode. Dynamic
// content queries are resolved during change detection (i.e. update mode), after embedded
// views are refreshed (see block above).
if (tView.staticContentQueries) {
refreshContentQueries(tView, lView);
}
// We must materialize query results before child components are processed
// in case a child component has projected a container. The LContainer needs
// to exist so the embedded views are properly attached by the container.
if (tView.staticViewQueries) {
executeViewQueryFn(2 /* Update */, (/** @type {?} */ (tView.viewQuery)), context);
}
// Render child component views.
/** @type {?} */
const components = tView.components;
if (components !== null) {
renderChildComponents(lView, components);
}
}
catch (error) {
// If we didn't manage to get past the first template pass due to
// an error, mark the view as corrupted so we can try to recover.
if (tView.firstCreatePass) {
tView.incompleteFirstPass = true;
}
throw error;
}
finally {
lView[FLAGS] &= ~4 /* CreationMode */;
leaveView();
}
}
/**
* Processes a view in update mode. This includes a number of steps in a specific order:
* - executing a template function in update mode;
* - executing hooks;
* - refreshing queries;
* - setting host bindings;
* - refreshing child (embedded and component) views.
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} templateFn
* @param {?} context
* @return {?}
*/
function refreshView(tView, lView, templateFn, context) {
ngDevMode && assertEqual(isCreationMode(lView), false, 'Should be run in update mode');
/** @type {?} */
const flags = lView[FLAGS];
if ((flags & 256 /* Destroyed */) === 256 /* Destroyed */)
return;
enterView(lView, lView[T_HOST]);
/** @type {?} */
const checkNoChangesMode = getCheckNoChangesMode();
try {
resetPreOrderHookFlags(lView);
setBindingIndex(tView.bindingStartIndex);
if (templateFn !== null) {
executeTemplate(tView, lView, templateFn, 2 /* Update */, context);
}
/** @type {?} */
const hooksInitPhaseCompleted = (flags & 3 /* InitPhaseStateMask */) === 3 /* InitPhaseCompleted */;
// execute pre-order hooks (OnInit, OnChanges, DoCheck)
// PERF WARNING: do NOT extract this to a separate function without running benchmarks
if (!checkNoChangesMode) {
if (hooksInitPhaseCompleted) {
/** @type {?} */
const preOrderCheckHooks = tView.preOrderCheckHooks;
if (preOrderCheckHooks !== null) {
executeCheckHooks(lView, preOrderCheckHooks, null);
}
}
else {
/** @type {?} */
const preOrderHooks = tView.preOrderHooks;
if (preOrderHooks !== null) {
executeInitAndCheckHooks(lView, preOrderHooks, 0 /* OnInitHooksToBeRun */, null);
}
incrementInitPhaseFlags(lView, 0 /* OnInitHooksToBeRun */);
}
}
// First mark transplanted views that are declared in this lView as needing a refresh at their
// insertion points. This is needed to avoid the situation where the template is defined in this
// `LView` but its declaration appears after the insertion component.
markTransplantedViewsForRefresh(lView);
refreshEmbeddedViews(lView);
// Content query results must be refreshed before content hooks are called.
if (tView.contentQueries !== null) {
refreshContentQueries(tView, lView);
}
// execute content hooks (AfterContentInit, AfterContentChecked)
// PERF WARNING: do NOT extract this to a separate function without running benchmarks
if (!checkNoChangesMode) {
if (hooksInitPhaseCompleted) {
/** @type {?} */
const contentCheckHooks = tView.contentCheckHooks;
if (contentCheckHooks !== null) {
executeCheckHooks(lView, contentCheckHooks);
}
}
else {
/** @type {?} */
const contentHooks = tView.contentHooks;
if (contentHooks !== null) {
executeInitAndCheckHooks(lView, contentHooks, 1 /* AfterContentInitHooksToBeRun */);
}
incrementInitPhaseFlags(lView, 1 /* AfterContentInitHooksToBeRun */);
}
}
setHostBindingsByExecutingExpandoInstructions(tView, lView);
// Refresh child component views.
/** @type {?} */
const components = tView.components;
if (components !== null) {
refreshChildComponents(lView, components);
}
// View queries must execute after refreshing child components because a template in this view
// could be inserted in a child component. If the view query executes before child component
// refresh, the template might not yet be inserted.
/** @type {?} */
const viewQuery = tView.viewQuery;
if (viewQuery !== null) {
executeViewQueryFn(2 /* Update */, viewQuery, context);
}
// execute view hooks (AfterViewInit, AfterViewChecked)
// PERF WARNING: do NOT extract this to a separate function without running benchmarks
if (!checkNoChangesMode) {
if (hooksInitPhaseCompleted) {
/** @type {?} */
const viewCheckHooks = tView.viewCheckHooks;
if (viewCheckHooks !== null) {
executeCheckHooks(lView, viewCheckHooks);
}
}
else {
/** @type {?} */
const viewHooks = tView.viewHooks;
if (viewHooks !== null) {
executeInitAndCheckHooks(lView, viewHooks, 2 /* AfterViewInitHooksToBeRun */);
}
incrementInitPhaseFlags(lView, 2 /* AfterViewInitHooksToBeRun */);
}
}
if (tView.firstUpdatePass === true) {
// We need to make sure that we only flip the flag on successful `refreshView` only
// Don't do this in `finally` block.
// If we did this in `finally` block then an exception could block the execution of styling
// instructions which in turn would be unable to insert themselves into the styling linked
// list. The result of this would be that if the exception would not be throw on subsequent CD
// the styling would be unable to process it data and reflect to the DOM.
tView.firstUpdatePass = false;
}
// Do not reset the dirty state when running in check no changes mode. We don't want components
// to behave differently depending on whether check no changes is enabled or not. For example:
// Marking an OnPush component as dirty from within the `ngAfterViewInit` hook in order to
// refresh a `NgClass` binding should work. If we would reset the dirty state in the check
// no changes cycle, the component would be not be dirty for the next update pass. This would
// be different in production mode where the component dirty state is not reset.
if (!checkNoChangesMode) {
lView[FLAGS] &= ~(64 /* Dirty */ | 8 /* FirstLViewPass */);
}
if (lView[FLAGS] & 1024 /* RefreshTransplantedView */) {
lView[FLAGS] &= ~1024 /* RefreshTransplantedView */;
updateTransplantedViewCount((/** @type {?} */ (lView[PARENT])), -1);
}
}
finally {
leaveView();
}
}
/**
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} templateFn
* @param {?} context
* @return {?}
*/
function renderComponentOrTemplate(tView, lView, templateFn, context) {
/** @type {?} */
const rendererFactory = lView[RENDERER_FACTORY];
/** @type {?} */
const normalExecutionPath = !getCheckNoChangesMode();
/** @type {?} */
const creationModeIsActive = isCreationMode(lView);
try {
if (normalExecutionPath && !creationModeIsActive && rendererFactory.begin) {
rendererFactory.begin();
}
if (creationModeIsActive) {
renderView(tView, lView, context);
}
refreshView(tView, lView, templateFn, context);
}
finally {
if (normalExecutionPath && !creationModeIsActive && rendererFactory.end) {
rendererFactory.end();
}
}
}
/**
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} templateFn
* @param {?} rf
* @param {?} context
* @return {?}
*/
function executeTemplate(tView, lView, templateFn, rf, context) {
/** @type {?} */
const prevSelectedIndex = getSelectedIndex();
try {
setSelectedIndex(-1);
if (rf & 2 /* Update */ && lView.length > HEADER_OFFSET) {
// When we're updating, inherently select 0 so we don't
// have to generate that instruction for most update blocks.
selectIndexInternal(tView, lView, 0, getCheckNoChangesMode());
}
templateFn(rf, context);
}
finally {
setSelectedIndex(prevSelectedIndex);
}
}
//////////////////////////
//// Element
//////////////////////////
/**
* @param {?} tView
* @param {?} tNode
* @param {?} lView
* @return {?}
*/
function executeContentQueries(tView, tNode, lView) {
if (isContentQueryHost(tNode)) {
/** @type {?} */
const start = tNode.directiveStart;
/** @type {?} */
const end = tNode.directiveEnd;
for (let directiveIndex = start; directiveIndex < end; directiveIndex++) {
/** @type {?} */
const def = (/** @type {?} */ (tView.data[directiveIndex]));
if (def.contentQueries) {
def.contentQueries(1 /* Create */, lView[directiveIndex], directiveIndex);
}
}
}
}
/**
* Creates directive instances.
* @param {?} tView
* @param {?} lView
* @param {?} tNode
* @return {?}
*/
function createDirectivesInstances(tView, lView, tNode) {
if (!getBindingsEnabled())
return;
instantiateAllDirectives(tView, lView, tNode, getNativeByTNode(tNode, lView));
if ((tNode.flags & 128 /* hasHostBindings */) === 128 /* hasHostBindings */) {
invokeDirectivesHostBindings(tView, lView, tNode);
}
}
/**
* Takes a list of local names and indices and pushes the resolved local variable values
* to LView in the same order as they are loaded in the template with load().
* @param {?} viewData
* @param {?} tNode
* @param {?=} localRefExtractor
* @return {?}
*/
function saveResolvedLocalsInData(viewData, tNode, localRefExtractor = getNativeByTNode) {
/** @type {?} */
const localNames = tNode.localNames;
if (localNames !== null) {
/** @type {?} */
let localIndex = tNode.index + 1;
for (let i = 0; i < localNames.length; i += 2) {
/** @type {?} */
const index = (/** @type {?} */ (localNames[i + 1]));
/** @type {?} */
const value = index === -1 ?
localRefExtractor((/** @type {?} */ (tNode)), viewData) :
viewData[index];
viewData[localIndex++] = value;
}
}
}
/**
* Gets TView from a template function or creates a new TView
* if it doesn't already exist.
*
* @param {?} def ComponentDef
* @return {?} TView
*/
function getOrCreateTComponentView(def) {
/** @type {?} */
const tView = def.tView;
// Create a TView if there isn't one, or recreate it if the first create pass didn't
// complete successfuly since we can't know for sure whether it's in a usable shape.
if (tView === null || tView.incompleteFirstPass) {
return def.tView = createTView(1 /* Component */, -1, def.template, def.decls, def.vars, def.directiveDefs, def.pipeDefs, def.viewQuery, def.schemas, def.consts);
}
return tView;
}
/**
* Creates a TView instance
*
* @param {?} type
* @param {?} viewIndex The viewBlockId for inline views, or -1 if it's a component/dynamic
* @param {?} templateFn Template function
* @param {?} decls The number of nodes, local refs, and pipes in this template
* @param {?} vars
* @param {?} directives Registry of directives for this view
* @param {?} pipes Registry of pipes for this view
* @param {?} viewQuery View queries for this view
* @param {?} schemas Schemas for this view
* @param {?} consts Constants for this view
* @return {?}
*/
function createTView(type, viewIndex, templateFn, decls, vars, directives, pipes, viewQuery, schemas, consts) {
ngDevMode && ngDevMode.tView++;
/** @type {?} */
const bindingStartIndex = HEADER_OFFSET + decls;
// This length does not yet contain host bindings from child directives because at this point,
// we don't know which directives are active on this template. As soon as a directive is matched
// that has a host binding, we will update the blueprint with that def's hostVars count.
/** @type {?} */
const initialViewLength = bindingStartIndex + vars;
/** @type {?} */
const blueprint = createViewBlueprint(bindingStartIndex, initialViewLength);
return blueprint[(/** @type {?} */ (TVIEW))] = ngDevMode ?
new TViewConstructor(type, viewIndex, // id: number,
blueprint, // blueprint: LView,
templateFn, // template: ComponentTemplate<{}>|null,
null, // queries: TQueries|null
viewQuery, (/** @type {?} */ (null)), // node: TViewNode|TElementNode|null,
cloneToTViewData(blueprint).fill(null, bindingStartIndex), // data: TData,
bindingStartIndex, // bindingStartIndex: number,
initialViewLength, // expandoStartIndex: number,
null, // expandoInstructions: ExpandoInstructions|null,
true, // firstCreatePass: boolean,
true, // firstUpdatePass: boolean,
false, // staticViewQueries: boolean,
false, // staticContentQueries: boolean,
null, // preOrderHooks: HookData|null,
null, // preOrderCheckHooks: HookData|null,
null, // contentHooks: HookData|null,
null, // contentCheckHooks: HookData|null,
null, // viewHooks: HookData|null,
null, // viewCheckHooks: HookData|null,
null, // destroyHooks: DestroyHookData|null,
null, // cleanup: any[]|null,
null, // contentQueries: number[]|null,
null, // components: number[]|null,
typeof directives === 'function' ?
directives() :
directives, // directiveRegistry: DirectiveDefList|null,
typeof pipes === 'function' ? pipes() : pipes, // pipeRegistry: PipeDefList|null,
null, // firstChild: TNode|null,
schemas, // schemas: SchemaMetadata[]|null,
consts, // consts: TConstants|null
false // incompleteFirstPass: boolean
) :
{
type: type,
id: viewIndex,
blueprint: blueprint,
template: templateFn,
queries: null,
viewQuery: viewQuery,
node: (/** @type {?} */ (null)),
data: blueprint.slice().fill(null, bindingStartIndex),
bindingStartIndex: bindingStartIndex,
expandoStartIndex: initialViewLength,
expandoInstructions: null,
firstCreatePass: true,
firstUpdatePass: true,
staticViewQueries: false,
staticContentQueries: false,
preOrderHooks: null,
preOrderCheckHooks: null,
contentHooks: null,
contentCheckHooks: null,
viewHooks: null,
viewCheckHooks: null,
destroyHooks: null,
cleanup: null,
contentQueries: null,
components: null,
directiveRegistry: typeof directives === 'function' ? directives() : directives,
pipeRegistry: typeof pipes === 'function' ? pipes() : pipes,
firstChild: null,
schemas: schemas,
consts: consts,
incompleteFirstPass: false
};
}
/**
* @param {?} bindingStartIndex
* @param {?} initialViewLength
* @return {?}
*/
function createViewBlueprint(bindingStartIndex, initialViewLength) {
/** @type {?} */
const blueprint = ngDevMode ? new LViewBlueprint() : [];
for (let i = 0; i < initialViewLength; i++) {
blueprint.push(i < bindingStartIndex ? null : NO_CHANGE);
}
return (/** @type {?} */ (blueprint));
}
/**
* @param {?} text
* @param {?} token
* @return {?}
*/
function createError(text, token) {
return new Error(`Renderer: ${text} [${stringifyForError(token)}]`);
}
/**
* @param {?} rElement
* @param {?} elementOrSelector
* @return {?}
*/
function assertHostNodeExists(rElement, elementOrSelector) {
if (!rElement) {
if (typeof elementOrSelector === 'string') {
throw createError('Host node with selector not found:', elementOrSelector);
}
else {
throw createError('Host node is required:', elementOrSelector);
}
}
}
/**
* Locates the host native element, used for bootstrapping existing nodes into rendering pipeline.
*
* @param {?} renderer
* @param {?} elementOrSelector Render element or CSS selector to locate the element.
* @param {?} encapsulation View Encapsulation defined for component that requests host element.
* @return {?}
*/
function locateHostElement(renderer, elementOrSelector, encapsulation) {
if (isProceduralRenderer(renderer)) {
// When using native Shadow DOM, do not clear host element to allow native slot projection
/** @type {?} */
const preserveContent = encapsulation === ViewEncapsulation$1.ShadowDom;
return renderer.selectRootElement(elementOrSelector, preserveContent);
}
/** @type {?} */
let rElement = typeof elementOrSelector === 'string' ?
(/** @type {?} */ (renderer.querySelector(elementOrSelector))) :
elementOrSelector;
ngDevMode && assertHostNodeExists(rElement, elementOrSelector);
// Always clear host element's content when Renderer3 is in use. For procedural renderer case we
// make it depend on whether ShadowDom encapsulation is used (in which case the content should be
// preserved to allow native slot projection). ShadowDom encapsulation requires procedural
// renderer, and procedural renderer case is handled above.
rElement.textContent = '';
return rElement;
}
/**
* Saves context for this cleanup function in LView.cleanupInstances.
*
* On the first template pass, saves in TView:
* - Cleanup function
* - Index of context we just saved in LView.cleanupInstances
* @param {?} tView
* @param {?} lView
* @param {?} context
* @param {?} cleanupFn
* @return {?}
*/
function storeCleanupWithContext(tView, lView, context, cleanupFn) {
/** @type {?} */
const lCleanup = getLCleanup(lView);
lCleanup.push(context);
if (tView.firstCreatePass) {
getTViewCleanup(tView).push(cleanupFn, lCleanup.length - 1);
}
}
/**
* Saves the cleanup function itself in LView.cleanupInstances.
*
* This is necessary for functions that are wrapped with their contexts, like in renderer2
* listeners.
*
* On the first template pass, the index of the cleanup function is saved in TView.
* @param {?} tView
* @param {?} lView
* @param {?} cleanupFn
* @return {?}
*/
function storeCleanupFn(tView, lView, cleanupFn) {
getLCleanup(lView).push(cleanupFn);
if (tView.firstCreatePass) {
getTViewCleanup(tView).push((/** @type {?} */ (lView[CLEANUP])).length - 1, null);
}
}
/**
* Constructs a TNode object from the arguments.
*
* @param {?} tView `TView` to which this `TNode` belongs (used only in `ngDevMode`)
* @param {?} tParent
* @param {?} type The type of the node
* @param {?} adjustedIndex The index of the TNode in TView.data, adjusted for HEADER_OFFSET
* @param {?} tagName The tag name of the node
* @param {?} attrs The attributes defined on this node
* @return {?} the TNode object
*/
function createTNode(tView, tParent, type, adjustedIndex, tagName, attrs) {
ngDevMode && ngDevMode.tNode++;
/** @type {?} */
let injectorIndex = tParent ? tParent.injectorIndex : -1;
return ngDevMode ? new TNodeDebug(tView, // tView_: TView
type, // type: TNodeType
adjustedIndex, // index: number
injectorIndex, // injectorIndex: number
-1, // directiveStart: number
-1, // directiveEnd: number
-1, // directiveStylingLast: number
null, // propertyBindings: number[]|null
0, // flags: TNodeFlags
0, // providerIndexes: TNodeProviderIndexes
tagName, // tagName: string|null
attrs, // attrs: (string|AttributeMarker|(string|SelectorFlags)[])[]|null
null, // mergedAttrs
null, // localNames: (string|number)[]|null
undefined, // initialInputs: (string[]|null)[]|null|undefined
null, // inputs: PropertyAliases|null
null, // outputs: PropertyAliases|null
null, // tViews: ITView|ITView[]|null
null, // next: ITNode|null
null, // projectionNext: ITNode|null
null, // child: ITNode|null
tParent, // parent: TElementNode|TContainerNode|null
null, // projection: number|(ITNode|RNode[])[]|null
null, // styles: string|null
null, // stylesWithoutHost: string|null
undefined, // residualStyles: string|null
null, // classes: string|null
null, // classesWithoutHost: string|null
undefined, (/** @type {?} */ (0)), (/** @type {?} */ (0))) :
{
type: type,
index: adjustedIndex,
injectorIndex: injectorIndex,
directiveStart: -1,
directiveEnd: -1,
directiveStylingLast: -1,
propertyBindings: null,
flags: 0,
providerIndexes: 0,
tagName: tagName,
attrs: attrs,
mergedAttrs: null,
localNames: null,
initialInputs: undefined,
inputs: null,
outputs: null,
tViews: null,
next: null,
projectionNext: null,
child: null,
parent: tParent,
projection: null,
styles: null,
stylesWithoutHost: null,
residualStyles: undefined,
classes: null,
classesWithoutHost: null,
residualClasses: undefined,
classBindings: (/** @type {?} */ (0)),
styleBindings: (/** @type {?} */ (0)),
};
}
/**
* @param {?} inputAliasMap
* @param {?} directiveDefIdx
* @param {?} propStore
* @return {?}
*/
function generatePropertyAliases(inputAliasMap, directiveDefIdx, propStore) {
for (let publicName in inputAliasMap) {
if (inputAliasMap.hasOwnProperty(publicName)) {
propStore = propStore === null ? {} : propStore;
/** @type {?} */
const internalName = inputAliasMap[publicName];
if (propStore.hasOwnProperty(publicName)) {
propStore[publicName].push(directiveDefIdx, internalName);
}
else {
(propStore[publicName] = [directiveDefIdx, internalName]);
}
}
}
return propStore;
}
/**
* Initializes data structures required to work with directive outputs and outputs.
* Initialization is done for all directives matched on a given TNode.
* @param {?} tView
* @param {?} tNode
* @return {?}
*/
function initializeInputAndOutputAliases(tView, tNode) {
ngDevMode && assertFirstCreatePass(tView);
/** @type {?} */
const start = tNode.directiveStart;
/** @type {?} */
const end = tNode.directiveEnd;
/** @type {?} */
const defs = tView.data;
/** @type {?} */
const tNodeAttrs = tNode.attrs;
/** @type {?} */
const inputsFromAttrs = ngDevMode ? new TNodeInitialInputs() : [];
/** @type {?} */
let inputsStore = null;
/** @type {?} */
let outputsStore = null;
for (let i = start; i < end; i++) {
/** @type {?} */
const directiveDef = (/** @type {?} */ (defs[i]));
/** @type {?} */
const directiveInputs = directiveDef.inputs;
// Do not use unbound attributes as inputs to structural directives, since structural
// directive inputs can only be set using microsyntax (e.g. `<div *dir="exp">`).
// TODO(FW-1930): microsyntax expressions may also contain unbound/static attributes, which
// should be set for inline templates.
/** @type {?} */
const initialInputs = (tNodeAttrs !== null && !isInlineTemplate(tNode)) ?
generateInitialInputs(directiveInputs, tNodeAttrs) :
null;
inputsFromAttrs.push(initialInputs);
inputsStore = generatePropertyAliases(directiveInputs, i, inputsStore);
outputsStore = generatePropertyAliases(directiveDef.outputs, i, outputsStore);
}
if (inputsStore !== null) {
if (inputsStore.hasOwnProperty('class')) {
tNode.flags |= 16 /* hasClassInput */;
}
if (inputsStore.hasOwnProperty('style')) {
tNode.flags |= 32 /* hasStyleInput */;
}
}
tNode.initialInputs = inputsFromAttrs;
tNode.inputs = inputsStore;
tNode.outputs = outputsStore;
}
/**
* Mapping between attributes names that don't correspond to their element property names.
*
* Performance note: this function is written as a series of if checks (instead of, say, a property
* object lookup) for performance reasons - the series of `if` checks seems to be the fastest way of
* mapping property names. Do NOT change without benchmarking.
*
* Note: this mapping has to be kept in sync with the equally named mapping in the template
* type-checking machinery of ngtsc.
* @param {?} name
* @return {?}
*/
function mapPropName(name) {
if (name === 'class')
return 'className';
if (name === 'for')
return 'htmlFor';
if (name === 'formaction')
return 'formAction';
if (name === 'innerHtml')
return 'innerHTML';
if (name === 'readonly')
return 'readOnly';
if (name === 'tabindex')
return 'tabIndex';
return name;
}
/**
* @template T
* @param {?} tView
* @param {?} tNode
* @param {?} lView
* @param {?} propName
* @param {?} value
* @param {?} renderer
* @param {?} sanitizer
* @param {?} nativeOnly
* @return {?}
*/
function elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, nativeOnly) {
ngDevMode && assertNotSame(value, (/** @type {?} */ (NO_CHANGE)), 'Incoming value should never be NO_CHANGE.');
/** @type {?} */
const element = (/** @type {?} */ (getNativeByTNode(tNode, lView)));
/** @type {?} */
let inputData = tNode.inputs;
/** @type {?} */
let dataValue;
if (!nativeOnly && inputData != null && (dataValue = inputData[propName])) {
setInputsForProperty(tView, lView, dataValue, propName, value);
if (isComponentHost(tNode))
markDirtyIfOnPush(lView, tNode.index);
if (ngDevMode) {
setNgReflectProperties(lView, element, tNode.type, dataValue, value);
}
}
else if (tNode.type === 3 /* Element */) {
propName = mapPropName(propName);
if (ngDevMode) {
validateAgainstEventProperties(propName);
if (!validateProperty(tView, lView, element, propName, tNode)) {
// Return here since we only log warnings for unknown properties.
warnAboutUnknownProperty(propName, tNode);
return;
}
ngDevMode.rendererSetProperty++;
}
// It is assumed that the sanitizer is only added when the compiler determines that the
// property is risky, so sanitization can be done without further checks.
value = sanitizer != null ? ((/** @type {?} */ (sanitizer(value, tNode.tagName || '', propName)))) : value;
if (isProceduralRenderer(renderer)) {
renderer.setProperty((/** @type {?} */ (element)), propName, value);
}
else if (!isAnimationProp(propName)) {
((/** @type {?} */ (element))).setProperty ? ((/** @type {?} */ (element))).setProperty(propName, value) :
((/** @type {?} */ (element)))[propName] = value;
}
}
else if (tNode.type === 0 /* Container */) {
// If the node is a container and the property didn't
// match any of the inputs or schemas we should throw.
if (ngDevMode && !matchingSchemas(tView, lView, tNode.tagName)) {
warnAboutUnknownProperty(propName, tNode);
}
}
}
/**
* If node is an OnPush component, marks its LView dirty.
* @param {?} lView
* @param {?} viewIndex
* @return {?}
*/
function markDirtyIfOnPush(lView, viewIndex) {
ngDevMode && assertLView(lView);
/** @type {?} */
const childComponentLView = getComponentLViewByIndex(viewIndex, lView);
if (!(childComponentLView[FLAGS] & 16 /* CheckAlways */)) {
childComponentLView[FLAGS] |= 64 /* Dirty */;
}
}
/**
* @param {?} lView
* @param {?} element
* @param {?} type
* @param {?} attrName
* @param {?} value
* @return {?}
*/
function setNgReflectProperty(lView, element, type, attrName, value) {
/** @type {?} */
const renderer = lView[RENDERER];
attrName = normalizeDebugBindingName(attrName);
/** @type {?} */
const debugValue = normalizeDebugBindingValue(value);
if (type === 3 /* Element */) {
if (value == null) {
isProceduralRenderer(renderer) ? renderer.removeAttribute(((/** @type {?} */ (element))), attrName) :
((/** @type {?} */ (element))).removeAttribute(attrName);
}
else {
isProceduralRenderer(renderer) ?
renderer.setAttribute(((/** @type {?} */ (element))), attrName, debugValue) :
((/** @type {?} */ (element))).setAttribute(attrName, debugValue);
}
}
else {
/** @type {?} */
const textContent = escapeCommentText(`bindings=${JSON.stringify({ [attrName]: debugValue }, null, 2)}`);
if (isProceduralRenderer(renderer)) {
renderer.setValue(((/** @type {?} */ (element))), textContent);
}
else {
((/** @type {?} */ (element))).textContent = textContent;
}
}
}
/**
* @param {?} lView
* @param {?} element
* @param {?} type
* @param {?} dataValue
* @param {?} value
* @return {?}
*/
function setNgReflectProperties(lView, element, type, dataValue, value) {
if (type === 3 /* Element */ || type === 0 /* Container */) {
/**
* dataValue is an array containing runtime input or output names for the directives:
* i+0: directive instance index
* i+1: privateName
*
* e.g. [0, 'change', 'change-minified']
* we want to set the reflected property with the privateName: dataValue[i+1]
*/
for (let i = 0; i < dataValue.length; i += 2) {
setNgReflectProperty(lView, element, type, (/** @type {?} */ (dataValue[i + 1])), value);
}
}
}
/**
* @param {?} tView
* @param {?} lView
* @param {?} element
* @param {?} propName
* @param {?} tNode
* @return {?}
*/
function validateProperty(tView, lView, element, propName, tNode) {
// If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
// mode where this check happens at compile time. In JIT mode, `schemas` is always present and
// defined as an array (as an empty array in case `schemas` field is not defined) and we should
// execute the check below.
if (tView.schemas === null)
return true;
// The property is considered valid if the element matches the schema, it exists on the element
// or it is synthetic, and we are in a browser context (web worker nodes should be skipped).
if (matchingSchemas(tView, lView, tNode.tagName) || propName in element ||
isAnimationProp(propName)) {
return true;
}
// Note: `typeof Node` returns 'function' in most browsers, but on IE it is 'object' so we
// need to account for both here, while being careful for `typeof null` also returning 'object'.
return typeof Node === 'undefined' || Node === null || !(element instanceof Node);
}
/**
* @param {?} tView
* @param {?} lView
* @param {?} tagName
* @return {?}
*/
function matchingSchemas(tView, lView, tagName) {
/** @type {?} */
const schemas = tView.schemas;
if (schemas !== null) {
for (let i = 0; i < schemas.length; i++) {
/** @type {?} */
const schema = schemas[i];
if (schema === NO_ERRORS_SCHEMA ||
schema === CUSTOM_ELEMENTS_SCHEMA && tagName && tagName.indexOf('-') > -1) {
return true;
}
}
}
return false;
}
/**
* Logs a warning that a property is not supported on an element.
* @param {?} propName Name of the invalid property.
* @param {?} tNode Node on which we encountered the property.
* @return {?}
*/
function warnAboutUnknownProperty(propName, tNode) {
console.warn(`Can't bind to '${propName}' since it isn't a known property of '${tNode.tagName}'.`);
}
/**
* Instantiate a root component.
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} def
* @return {?}
*/
function instantiateRootComponent(tView, lView, def) {
/** @type {?} */
const rootTNode = getPreviousOrParentTNode();
if (tView.firstCreatePass) {
if (def.providersResolver)
def.providersResolver(def);
generateExpandoInstructionBlock(tView, rootTNode, 1);
baseResolveDirective(tView, lView, def);
}
/** @type {?} */
const directive = getNodeInjectable(lView, tView, lView.length - 1, (/** @type {?} */ (rootTNode)));
attachPatchData(directive, lView);
/** @type {?} */
const native = getNativeByTNode(rootTNode, lView);
if (native) {
attachPatchData(native, lView);
}
return directive;
}
/**
* Resolve the matched directives on a node.
* @param {?} tView
* @param {?} lView
* @param {?} tNode
* @param {?} localRefs
* @return {?}
*/
function resolveDirectives(tView, lView, tNode, localRefs) {
// Please make sure to have explicit type for `exportsMap`. Inferred type triggers bug in
// tsickle.
ngDevMode && assertFirstCreatePass(tView);
/** @type {?} */
let hasDirectives = false;
if (getBindingsEnabled()) {
/** @type {?} */
const directiveDefs = findDirectiveDefMatches(tView, lView, tNode);
/** @type {?} */
const exportsMap = localRefs === null ? null : { '': -1 };
if (directiveDefs !== null) {
/** @type {?} */
let totalDirectiveHostVars = 0;
hasDirectives = true;
initTNodeFlags(tNode, tView.data.length, directiveDefs.length);
// When the same token is provided by several directives on the same node, some rules apply in
// the viewEngine:
// - viewProviders have priority over providers
// - the last directive in NgModule.declarations has priority over the previous one
// So to match these rules, the order in which providers are added in the arrays is very
// important.
for (let i = 0; i < directiveDefs.length; i++) {
/** @type {?} */
const def = directiveDefs[i];
if (def.providersResolver)
def.providersResolver(def);
}
generateExpandoInstructionBlock(tView, tNode, directiveDefs.length);
/** @type {?} */
let preOrderHooksFound = false;
/** @type {?} */
let preOrderCheckHooksFound = false;
for (let i = 0; i < directiveDefs.length; i++) {
/** @type {?} */
const def = directiveDefs[i];
// Merge the attrs in the order of matches. This assumes that the first directive is the
// component itself, so that the component has the least priority.
tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, def.hostAttrs);
baseResolveDirective(tView, lView, def);
saveNameToExportMap((/** @type {?} */ (tView.data)).length - 1, def, exportsMap);
if (def.contentQueries !== null)
tNode.flags |= 8 /* hasContentQuery */;
if (def.hostBindings !== null || def.hostAttrs !== null || def.hostVars !== 0)
tNode.flags |= 128 /* hasHostBindings */;
// Only push a node index into the preOrderHooks array if this is the first
// pre-order hook found on this node.
if (!preOrderHooksFound && (def.onChanges || def.onInit || def.doCheck)) {
// We will push the actual hook function into this array later during dir instantiation.
// We cannot do it now because we must ensure hooks are registered in the same
// order that directives are created (i.e. injection order).
(tView.preOrderHooks || (tView.preOrderHooks = [])).push(tNode.index - HEADER_OFFSET);
preOrderHooksFound = true;
}
if (!preOrderCheckHooksFound && (def.onChanges || def.doCheck)) {
(tView.preOrderCheckHooks || (tView.preOrderCheckHooks = []))
.push(tNode.index - HEADER_OFFSET);
preOrderCheckHooksFound = true;
}
addHostBindingsToExpandoInstructions(tView, def);
totalDirectiveHostVars += def.hostVars;
}
initializeInputAndOutputAliases(tView, tNode);
growHostVarsSpace(tView, lView, totalDirectiveHostVars);
}
if (exportsMap)
cacheMatchingLocalNames(tNode, localRefs, exportsMap);
}
// Merge the template attrs last so that they have the highest priority.
tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, tNode.attrs);
return hasDirectives;
}
/**
* Add `hostBindings` to the `TView.expandoInstructions`.
*
* @param {?} tView `TView` to which the `hostBindings` should be added.
* @param {?} def `ComponentDef`/`DirectiveDef`, which contains the `hostVars`/`hostBindings` to add.
* @return {?}
*/
function addHostBindingsToExpandoInstructions(tView, def) {
ngDevMode && assertFirstCreatePass(tView);
/** @type {?} */
const expando = (/** @type {?} */ (tView.expandoInstructions));
// TODO(misko): PERF we are adding `hostBindings` even if there is nothing to add! This is
// suboptimal for performance. `def.hostBindings` may be null,
// but we still need to push null to the array as a placeholder
// to ensure the directive counter is incremented (so host
// binding functions always line up with the corrective directive).
// This is suboptimal for performance. See `currentDirectiveIndex`
// comment in `setHostBindingsByExecutingExpandoInstructions` for more
// details. expando.push(def.hostBindings);
expando.push(def.hostBindings);
/** @type {?} */
const hostVars = def.hostVars;
if (hostVars !== 0) {
expando.push(def.hostVars);
}
}
/**
* Grow the `LView`, blueprint and `TView.data` to accommodate the `hostBindings`.
*
* To support locality we don't know ahead of time how many `hostVars` of the containing directives
* we need to allocate. For this reason we allow growing these data structures as we discover more
* directives to accommodate them.
*
* @param {?} tView `TView` which needs to be grown.
* @param {?} lView `LView` which needs to be grown.
* @param {?} count Size by which we need to grow the data structures.
* @return {?}
*/
function growHostVarsSpace(tView, lView, count) {
ngDevMode && assertFirstCreatePass(tView);
ngDevMode && assertSame(tView, lView[TVIEW], '`LView` must be associated with `TView`!');
for (let i = 0; i < count; i++) {
lView.push(NO_CHANGE);
tView.blueprint.push(NO_CHANGE);
tView.data.push(null);
}
}
/**
* Instantiate all the directives that were previously resolved on the current node.
* @param {?} tView
* @param {?} lView
* @param {?} tNode
* @param {?} native
* @return {?}
*/
function instantiateAllDirectives(tView, lView, tNode, native) {
/** @type {?} */
const start = tNode.directiveStart;
/** @type {?} */
const end = tNode.directiveEnd;
if (!tView.firstCreatePass) {
getOrCreateNodeInjectorForNode(tNode, lView);
}
attachPatchData(native, lView);
/** @type {?} */
const initialInputs = tNode.initialInputs;
for (let i = start; i < end; i++) {
/** @type {?} */
const def = (/** @type {?} */ (tView.data[i]));
/** @type {?} */
const isComponent = isComponentDef(def);
if (isComponent) {
ngDevMode && assertNodeOfPossibleTypes(tNode, 3 /* Element */);
addComponentLogic(lView, (/** @type {?} */ (tNode)), (/** @type {?} */ (def)));
}
/** @type {?} */
const directive = getNodeInjectable(lView, tView, i, tNode);
attachPatchData(directive, lView);
if (initialInputs !== null) {
setInputsFromAttrs(lView, i - start, directive, def, tNode, (/** @type {?} */ (initialInputs)));
}
if (isComponent) {
/** @type {?} */
const componentView = getComponentLViewByIndex(tNode.index, lView);
componentView[CONTEXT] = directive;
}
}
}
/**
* @param {?} tView
* @param {?} lView
* @param {?} tNode
* @return {?}
*/
function invokeDirectivesHostBindings(tView, lView, tNode) {
/** @type {?} */
const start = tNode.directiveStart;
/** @type {?} */
const end = tNode.directiveEnd;
/** @type {?} */
const expando = (/** @type {?} */ (tView.expandoInstructions));
/** @type {?} */
const firstCreatePass = tView.firstCreatePass;
/** @type {?} */
const elementIndex = tNode.index - HEADER_OFFSET;
/** @type {?} */
const currentDirectiveIndex = getCurrentDirectiveIndex();
try {
setSelectedIndex(elementIndex);
for (let dirIndex = start; dirIndex < end; dirIndex++) {
/** @type {?} */
const def = (/** @type {?} */ (tView.data[dirIndex]));
/** @type {?} */
const directive = lView[dirIndex];
setCurrentDirectiveIndex(dirIndex);
if (def.hostBindings !== null || def.hostVars !== 0 || def.hostAttrs !== null) {
invokeHostBindingsInCreationMode(def, directive);
}
else if (firstCreatePass) {
expando.push(null);
}
}
}
finally {
setSelectedIndex(-1);
setCurrentDirectiveIndex(currentDirectiveIndex);
}
}
/**
* Invoke the host bindings in creation mode.
*
* @param {?} def `DirectiveDef` which may contain the `hostBindings` function.
* @param {?} directive Instance of directive.
* @return {?}
*/
function invokeHostBindingsInCreationMode(def, directive) {
if (def.hostBindings !== null) {
(/** @type {?} */ (def.hostBindings))(1 /* Create */, directive);
}
}
/**
* Generates a new block in TView.expandoInstructions for this node.
*
* Each expando block starts with the element index (turned negative so we can distinguish
* it from the hostVar count) and the directive count. See more in VIEW_DATA.md.
* @param {?} tView
* @param {?} tNode
* @param {?} directiveCount
* @return {?}
*/
function generateExpandoInstructionBlock(tView, tNode, directiveCount) {
ngDevMode &&
assertEqual(tView.firstCreatePass, true, 'Expando block should only be generated on first create pass.');
// Important: In JS `-x` and `0-x` is not the same! If `x===0` then `-x` will produce `-0` which
// requires non standard math arithmetic and it can prevent VM optimizations.
// `0-0` will always produce `0` and will not cause a potential deoptimization in VM.
/** @type {?} */
const elementIndex = HEADER_OFFSET - tNode.index;
/** @type {?} */
const providerStartIndex = tNode.providerIndexes & 65535 /* ProvidersStartIndexMask */;
/** @type {?} */
const providerCount = tView.data.length - providerStartIndex;
(tView.expandoInstructions || (tView.expandoInstructions = []))
.push(elementIndex, providerCount, directiveCount);
}
/**
* Matches the current node against all available selectors.
* If a component is matched (at most one), it is returned in first position in the array.
* @param {?} tView
* @param {?} viewData
* @param {?} tNode
* @return {?}
*/
function findDirectiveDefMatches(tView, viewData, tNode) {
ngDevMode && assertFirstCreatePass(tView);
ngDevMode &&
assertNodeOfPossibleTypes(tNode, 3 /* Element */, 4 /* ElementContainer */, 0 /* Container */);
/** @type {?} */
const registry = tView.directiveRegistry;
/** @type {?} */
let matches = null;
if (registry) {
for (let i = 0; i < registry.length; i++) {
/** @type {?} */
const def = (/** @type {?} */ (registry[i]));
if (isNodeMatchingSelectorList(tNode, (/** @type {?} */ (def.selectors)), /* isProjectionMode */ false)) {
matches || (matches = ngDevMode ? new MatchesArray() : []);
diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, viewData), tView, def.type);
if (isComponentDef(def)) {
if (tNode.flags & 2 /* isComponentHost */)
throwMultipleComponentError(tNode);
markAsComponentHost(tView, tNode);
// The component is always stored first with directives after.
matches.unshift(def);
}
else {
matches.push(def);
}
}
}
}
return matches;
}
/**
* Marks a given TNode as a component's host. This consists of:
* - setting appropriate TNode flags;
* - storing index of component's host element so it will be queued for view refresh during CD.
* @param {?} tView
* @param {?} hostTNode
* @return {?}
*/
function markAsComponentHost(tView, hostTNode) {
ngDevMode && assertFirstCreatePass(tView);
hostTNode.flags |= 2 /* isComponentHost */;
(tView.components || (tView.components = ngDevMode ? new TViewComponents() : []))
.push(hostTNode.index);
}
/**
* Caches local names and their matching directive indices for query and template lookups.
* @param {?} tNode
* @param {?} localRefs
* @param {?} exportsMap
* @return {?}
*/
function cacheMatchingLocalNames(tNode, localRefs, exportsMap) {
if (localRefs) {
/** @type {?} */
const localNames = tNode.localNames = ngDevMode ? new TNodeLocalNames() : [];
// Local names must be stored in tNode in the same order that localRefs are defined
// in the template to ensure the data is loaded in the same slots as their refs
// in the template (for template queries).
for (let i = 0; i < localRefs.length; i += 2) {
/** @type {?} */
const index = exportsMap[localRefs[i + 1]];
if (index == null)
throw new Error(`Export of name '${localRefs[i + 1]}' not found!`);
localNames.push(localRefs[i], index);
}
}
}
/**
* Builds up an export map as directives are created, so local refs can be quickly mapped
* to their directive instances.
* @param {?} index
* @param {?} def
* @param {?} exportsMap
* @return {?}
*/
function saveNameToExportMap(index, def, exportsMap) {
if (exportsMap) {
if (def.exportAs) {
for (let i = 0; i < def.exportAs.length; i++) {
exportsMap[def.exportAs[i]] = index;
}
}
if (isComponentDef(def))
exportsMap[''] = index;
}
}
/**
* Initializes the flags on the current node, setting all indices to the initial index,
* the directive count to 0, and adding the isComponent flag.
* @param {?} tNode
* @param {?} index the initial index
* @param {?} numberOfDirectives
* @return {?}
*/
function initTNodeFlags(tNode, index, numberOfDirectives) {
ngDevMode &&
assertNotEqual(numberOfDirectives, tNode.directiveEnd - tNode.directiveStart, 'Reached the max number of directives');
tNode.flags |= 1 /* isDirectiveHost */;
// When the first directive is created on a node, save the index
tNode.directiveStart = index;
tNode.directiveEnd = index + numberOfDirectives;
tNode.providerIndexes = index;
}
/**
* @template T
* @param {?} tView
* @param {?} viewData
* @param {?} def
* @return {?}
*/
function baseResolveDirective(tView, viewData, def) {
tView.data.push(def);
/** @type {?} */
const directiveFactory = def.factory || (((/** @type {?} */ (def))).factory = getFactoryDef(def.type, true));
/** @type {?} */
const nodeInjectorFactory = new NodeInjectorFactory(directiveFactory, isComponentDef(def), null);
tView.blueprint.push(nodeInjectorFactory);
viewData.push(nodeInjectorFactory);
}
/**
* @template T
* @param {?} lView
* @param {?} hostTNode
* @param {?} def
* @return {?}
*/
function addComponentLogic(lView, hostTNode, def) {
/** @type {?} */
const native = (/** @type {?} */ (getNativeByTNode(hostTNode, lView)));
/** @type {?} */
const tView = getOrCreateTComponentView(def);
// Only component views should be added to the view tree directly. Embedded views are
// accessed through their containers because they may be removed / re-added later.
/** @type {?} */
const rendererFactory = lView[RENDERER_FACTORY];
/** @type {?} */
const componentView = addToViewTree(lView, createLView(lView, tView, null, def.onPush ? 64 /* Dirty */ : 16 /* CheckAlways */, native, (/** @type {?} */ (hostTNode)), rendererFactory, rendererFactory.createRenderer(native, def)));
// Component view will always be created before any injected LContainers,
// so this is a regular element, wrap it with the component view
lView[hostTNode.index] = componentView;
}
/**
* @param {?} tNode
* @param {?} lView
* @param {?} name
* @param {?} value
* @param {?} sanitizer
* @param {?} namespace
* @return {?}
*/
function elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace) {
ngDevMode && assertNotSame(value, (/** @type {?} */ (NO_CHANGE)), 'Incoming value should never be NO_CHANGE.');
ngDevMode && validateAgainstEventAttributes(name);
/** @type {?} */
const element = (/** @type {?} */ (getNativeByTNode(tNode, lView)));
/** @type {?} */
const renderer = lView[RENDERER];
if (value == null) {
ngDevMode && ngDevMode.rendererRemoveAttribute++;
isProceduralRenderer(renderer) ? renderer.removeAttribute(element, name, namespace) :
element.removeAttribute(name);
}
else {
ngDevMode && ngDevMode.rendererSetAttribute++;
/** @type {?} */
const strValue = sanitizer == null ? renderStringify(value) : sanitizer(value, tNode.tagName || '', name);
if (isProceduralRenderer(renderer)) {
renderer.setAttribute(element, name, strValue, namespace);
}
else {
namespace ? element.setAttributeNS(namespace, name, strValue) :
element.setAttribute(name, strValue);
}
}
}
/**
* Sets initial input properties on directive instances from attribute data
*
* @template T
* @param {?} lView Current LView that is being processed.
* @param {?} directiveIndex Index of the directive in directives array
* @param {?} instance Instance of the directive on which to set the initial inputs
* @param {?} def The directive def that contains the list of inputs
* @param {?} tNode The static data for this node
* @param {?} initialInputData
* @return {?}
*/
function setInputsFromAttrs(lView, directiveIndex, instance, def, tNode, initialInputData) {
/** @type {?} */
const initialInputs = (/** @type {?} */ (initialInputData))[directiveIndex];
if (initialInputs !== null) {
/** @type {?} */
const setInput = def.setInput;
for (let i = 0; i < initialInputs.length;) {
/** @type {?} */
const publicName = initialInputs[i++];
/** @type {?} */
const privateName = initialInputs[i++];
/** @type {?} */
const value = initialInputs[i++];
if (setInput !== null) {
(/** @type {?} */ (def.setInput))(instance, value, publicName, privateName);
}
else {
((/** @type {?} */ (instance)))[privateName] = value;
}
if (ngDevMode) {
/** @type {?} */
const nativeElement = (/** @type {?} */ (getNativeByTNode(tNode, lView)));
setNgReflectProperty(lView, nativeElement, tNode.type, privateName, value);
}
}
}
}
/**
* Generates initialInputData for a node and stores it in the template's static storage
* so subsequent template invocations don't have to recalculate it.
*
* initialInputData is an array containing values that need to be set as input properties
* for directives on this node, but only once on creation. We need this array to support
* the case where you set an \@Input property of a directive using attribute-like syntax.
* e.g. if you have a `name` \@Input, you can set it once like this:
*
* <my-component name="Bess"></my-component>
*
* @param {?} inputs The list of inputs from the directive def
* @param {?} attrs The static attrs on this node
* @return {?}
*/
function generateInitialInputs(inputs, attrs) {
/** @type {?} */
let inputsToStore = null;
/** @type {?} */
let i = 0;
while (i < attrs.length) {
/** @type {?} */
const attrName = attrs[i];
if (attrName === 0 /* NamespaceURI */) {
// We do not allow inputs on namespaced attributes.
i += 4;
continue;
}
else if (attrName === 5 /* ProjectAs */) {
// Skip over the `ngProjectAs` value.
i += 2;
continue;
}
// If we hit any other attribute markers, we're done anyway. None of those are valid inputs.
if (typeof attrName === 'number')
break;
if (inputs.hasOwnProperty((/** @type {?} */ (attrName)))) {
if (inputsToStore === null)
inputsToStore = [];
inputsToStore.push((/** @type {?} */ (attrName)), inputs[(/** @type {?} */ (attrName))], (/** @type {?} */ (attrs[i + 1])));
}
i += 2;
}
return inputsToStore;
}
//////////////////////////
//// ViewContainer & View
//////////////////////////
// Not sure why I need to do `any` here but TS complains later.
/** @type {?} */
const LContainerArray = ((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode()) &&
createNamedArrayType('LContainer');
/**
* Creates a LContainer, either from a container instruction, or for a ViewContainerRef.
*
* @param {?} hostNative The host element for the LContainer
* @param {?} currentView The parent view of the LContainer
* @param {?} native The native comment element
* @param {?} tNode
* @return {?} LContainer
*/
function createLContainer(hostNative, currentView, native, tNode) {
ngDevMode && assertLView(currentView);
ngDevMode && !isProceduralRenderer(currentView[RENDERER]) && assertDomNode(native);
// https://jsperf.com/array-literal-vs-new-array-really
/** @type {?} */
const lContainer = new (ngDevMode ? LContainerArray : Array)(hostNative, // host native
true, // Boolean `true` in this position signifies that this is an `LContainer`
false, // has transplanted views
currentView, // parent
null, // next
0, // transplanted views to refresh count
tNode, // t_host
native, // native,
null, // view refs
null);
ngDevMode &&
assertEqual(lContainer.length, CONTAINER_HEADER_OFFSET, 'Should allocate correct number of slots for LContainer header.');
ngDevMode && attachLContainerDebug(lContainer);
return lContainer;
}
/**
* Goes over embedded views (ones created through ViewContainerRef APIs) and refreshes
* them by executing an associated template function.
* @param {?} lView
* @return {?}
*/
function refreshEmbeddedViews(lView) {
for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
/** @type {?} */
const embeddedLView = lContainer[i];
/** @type {?} */
const embeddedTView = embeddedLView[TVIEW];
ngDevMode && assertDefined(embeddedTView, 'TView must be allocated');
if (viewAttachedToChangeDetector(embeddedLView)) {
refreshView(embeddedTView, embeddedLView, embeddedTView.template, (/** @type {?} */ (embeddedLView[CONTEXT])));
}
}
}
}
/**
* Mark transplanted views as needing to be refreshed at their insertion points.
*
* @param {?} lView The `LView` that may have transplanted views.
* @return {?}
*/
function markTransplantedViewsForRefresh(lView) {
for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
if (!lContainer[HAS_TRANSPLANTED_VIEWS])
continue;
/** @type {?} */
const movedViews = (/** @type {?} */ (lContainer[MOVED_VIEWS]));
ngDevMode && assertDefined(movedViews, 'Transplanted View flags set but missing MOVED_VIEWS');
for (let i = 0; i < movedViews.length; i++) {
/** @type {?} */
const movedLView = (/** @type {?} */ (movedViews[i]));
/** @type {?} */
const insertionLContainer = (/** @type {?} */ (movedLView[PARENT]));
ngDevMode && assertLContainer(insertionLContainer);
// We don't want to increment the counter if the moved LView was already marked for
// refresh.
if ((movedLView[FLAGS] & 1024 /* RefreshTransplantedView */) === 0) {
updateTransplantedViewCount(insertionLContainer, 1);
}
// Note, it is possible that the `movedViews` is tracking views that are transplanted *and*
// those that aren't (declaration component === insertion component). In the latter case,
// it's fine to add the flag, as we will clear it immediately in
// `refreshEmbeddedViews` for the view currently being refreshed.
movedLView[FLAGS] |= 1024 /* RefreshTransplantedView */;
}
}
}
/////////////
/**
* Refreshes components by entering the component view and processing its bindings, queries, etc.
*
* @param {?} hostLView
* @param {?} componentHostIdx Element index in LView[] (adjusted for HEADER_OFFSET)
* @return {?}
*/
function refreshComponent(hostLView, componentHostIdx) {
ngDevMode && assertEqual(isCreationMode(hostLView), false, 'Should be run in update mode');
/** @type {?} */
const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
// Only attached components that are CheckAlways or OnPush and dirty should be refreshed
if (viewAttachedToChangeDetector(componentView)) {
/** @type {?} */
const tView = componentView[TVIEW];
if (componentView[FLAGS] & (16 /* CheckAlways */ | 64 /* Dirty */)) {
refreshView(tView, componentView, tView.template, componentView[CONTEXT]);
}
else if (componentView[TRANSPLANTED_VIEWS_TO_REFRESH] > 0) {
// Only attached components that are CheckAlways or OnPush and dirty should be refreshed
refreshContainsDirtyView(componentView);
}
}
}
/**
* Refreshes all transplanted views marked with `LViewFlags.RefreshTransplantedView` that are
* children or descendants of the given lView.
*
* @param {?} lView The lView which contains descendant transplanted views that need to be refreshed.
* @return {?}
*/
function refreshContainsDirtyView(lView) {
for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
/** @type {?} */
const embeddedLView = lContainer[i];
if (embeddedLView[FLAGS] & 1024 /* RefreshTransplantedView */) {
/** @type {?} */
const embeddedTView = embeddedLView[TVIEW];
ngDevMode && assertDefined(embeddedTView, 'TView must be allocated');
refreshView(embeddedTView, embeddedLView, embeddedTView.template, (/** @type {?} */ (embeddedLView[CONTEXT])));
}
else if (embeddedLView[TRANSPLANTED_VIEWS_TO_REFRESH] > 0) {
refreshContainsDirtyView(embeddedLView);
}
}
}
/** @type {?} */
const tView = lView[TVIEW];
// Refresh child component views.
/** @type {?} */
const components = tView.components;
if (components !== null) {
for (let i = 0; i < components.length; i++) {
/** @type {?} */
const componentView = getComponentLViewByIndex(components[i], lView);
// Only attached components that are CheckAlways or OnPush and dirty should be refreshed
if (viewAttachedToChangeDetector(componentView) &&
componentView[TRANSPLANTED_VIEWS_TO_REFRESH] > 0) {
refreshContainsDirtyView(componentView);
}
}
}
}
/**
* @param {?} hostLView
* @param {?} componentHostIdx
* @return {?}
*/
function renderComponent(hostLView, componentHostIdx) {
ngDevMode && assertEqual(isCreationMode(hostLView), true, 'Should be run in creation mode');
/** @type {?} */
const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
/** @type {?} */
const componentTView = componentView[TVIEW];
syncViewWithBlueprint(componentTView, componentView);
renderView(componentTView, componentView, componentView[CONTEXT]);
}
/**
* Syncs an LView instance with its blueprint if they have gotten out of sync.
*
* Typically, blueprints and their view instances should always be in sync, so the loop here
* will be skipped. However, consider this case of two components side-by-side:
*
* App template:
* ```
* <comp></comp>
* <comp></comp>
* ```
*
* The following will happen:
* 1. App template begins processing.
* 2. First <comp> is matched as a component and its LView is created.
* 3. Second <comp> is matched as a component and its LView is created.
* 4. App template completes processing, so it's time to check child templates.
* 5. First <comp> template is checked. It has a directive, so its def is pushed to blueprint.
* 6. Second <comp> template is checked. Its blueprint has been updated by the first
* <comp> template, but its LView was created before this update, so it is out of sync.
*
* Note that embedded views inside ngFor loops will never be out of sync because these views
* are processed as soon as they are created.
*
* @param {?} tView The `TView` that contains the blueprint for syncing
* @param {?} lView The view to sync
* @return {?}
*/
function syncViewWithBlueprint(tView, lView) {
for (let i = lView.length; i < tView.blueprint.length; i++) {
lView.push(tView.blueprint[i]);
}
}
/**
* Adds LView or LContainer to the end of the current view tree.
*
* This structure will be used to traverse through nested views to remove listeners
* and call onDestroy callbacks.
*
* @template T
* @param {?} lView The view where LView or LContainer should be added
* @param {?} lViewOrLContainer The LView or LContainer to add to the view tree
* @return {?} The state passed in
*/
function addToViewTree(lView, lViewOrLContainer) {
// TODO(benlesh/misko): This implementation is incorrect, because it always adds the LContainer
// to the end of the queue, which means if the developer retrieves the LContainers from RNodes out
// of order, the change detection will run out of order, as the act of retrieving the the
// LContainer from the RNode is what adds it to the queue.
if (lView[CHILD_HEAD]) {
(/** @type {?} */ (lView[CHILD_TAIL]))[NEXT] = lViewOrLContainer;
}
else {
lView[CHILD_HEAD] = lViewOrLContainer;
}
lView[CHILD_TAIL] = lViewOrLContainer;
return lViewOrLContainer;
}
///////////////////////////////
//// Change detection
///////////////////////////////
/**
* Marks current view and all ancestors dirty.
*
* Returns the root view because it is found as a byproduct of marking the view tree
* dirty, and can be used by methods that consume markViewDirty() to easily schedule
* change detection. Otherwise, such methods would need to traverse up the view tree
* an additional time to get the root view and schedule a tick on it.
*
* @param {?} lView The starting LView to mark dirty
* @return {?} the root LView
*/
function markViewDirty(lView) {
while (lView) {
lView[FLAGS] |= 64 /* Dirty */;
/** @type {?} */
const parent = getLViewParent(lView);
// Stop traversing up as soon as you find a root view that wasn't attached to any container
if (isRootView(lView) && !parent) {
return lView;
}
// continue otherwise
lView = (/** @type {?} */ (parent));
}
return null;
}
/**
* Used to schedule change detection on the whole application.
*
* Unlike `tick`, `scheduleTick` coalesces multiple calls into one change detection run.
* It is usually called indirectly by calling `markDirty` when the view needs to be
* re-rendered.
*
* Typically `scheduleTick` uses `requestAnimationFrame` to coalesce multiple
* `scheduleTick` requests. The scheduling function can be overridden in
* `renderComponent`'s `scheduler` option.
* @param {?} rootContext
* @param {?} flags
* @return {?}
*/
function scheduleTick(rootContext, flags) {
/** @type {?} */
const nothingScheduled = rootContext.flags === 0 /* Empty */;
rootContext.flags |= flags;
if (nothingScheduled && rootContext.clean == _CLEAN_PROMISE) {
/** @type {?} */
let res;
rootContext.clean = new Promise((/**
* @param {?} r
* @return {?}
*/
(r) => res = r));
rootContext.scheduler((/**
* @return {?}
*/
() => {
if (rootContext.flags & 1 /* DetectChanges */) {
rootContext.flags &= ~1 /* DetectChanges */;
tickRootContext(rootContext);
}
if (rootContext.flags & 2 /* FlushPlayers */) {
rootContext.flags &= ~2 /* FlushPlayers */;
/** @type {?} */
const playerHandler = rootContext.playerHandler;
if (playerHandler) {
playerHandler.flushPlayers();
}
}
rootContext.clean = _CLEAN_PROMISE;
(/** @type {?} */ (res))(null);
}));
}
}
/**
* @param {?} rootContext
* @return {?}
*/
function tickRootContext(rootContext) {
for (let i = 0; i < rootContext.components.length; i++) {
/** @type {?} */
const rootComponent = rootContext.components[i];
/** @type {?} */
const lView = (/** @type {?} */ (readPatchedLView(rootComponent)));
/** @type {?} */
const tView = lView[TVIEW];
renderComponentOrTemplate(tView, lView, tView.template, rootComponent);
}
}
/**
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} context
* @return {?}
*/
function detectChangesInternal(tView, lView, context) {
/** @type {?} */
const rendererFactory = lView[RENDERER_FACTORY];
if (rendererFactory.begin)
rendererFactory.begin();
try {
refreshView(tView, lView, tView.template, context);
}
catch (error) {
handleError(lView, error);
throw error;
}
finally {
if (rendererFactory.end)
rendererFactory.end();
}
}
/**
* Synchronously perform change detection on a root view and its components.
*
* @param {?} lView The view which the change detection should be performed on.
* @return {?}
*/
function detectChangesInRootView(lView) {
tickRootContext((/** @type {?} */ (lView[CONTEXT])));
}
/**
* @template T
* @param {?} tView
* @param {?} view
* @param {?} context
* @return {?}
*/
function checkNoChangesInternal(tView, view, context) {
setCheckNoChangesMode(true);
try {
detectChangesInternal(tView, view, context);
}
finally {
setCheckNoChangesMode(false);
}
}
/**
* Checks the change detector on a root view and its components, and throws if any changes are
* detected.
*
* This is used in development mode to verify that running change detection doesn't
* introduce other changes.
*
* @param {?} lView The view which the change detection should be checked on.
* @return {?}
*/
function checkNoChangesInRootView(lView) {
setCheckNoChangesMode(true);
try {
detectChangesInRootView(lView);
}
finally {
setCheckNoChangesMode(false);
}
}
/**
* @template T
* @param {?} flags
* @param {?} viewQueryFn
* @param {?} component
* @return {?}
*/
function executeViewQueryFn(flags, viewQueryFn, component) {
ngDevMode && assertDefined(viewQueryFn, 'View queries function to execute must be defined.');
setCurrentQueryIndex(0);
viewQueryFn(flags, component);
}
///////////////////////////////
//// Bindings & interpolations
///////////////////////////////
/**
* Stores meta-data for a property binding to be used by TestBed's `DebugElement.properties`.
*
* In order to support TestBed's `DebugElement.properties` we need to save, for each binding:
* - a bound property name;
* - a static parts of interpolated strings;
*
* A given property metadata is saved at the binding's index in the `TView.data` (in other words, a
* property binding metadata will be stored in `TView.data` at the same index as a bound value in
* `LView`). Metadata are represented as `INTERPOLATION_DELIMITER`-delimited string with the
* following format:
* - `propertyName` for bound properties;
* - `propertyName�prefix�interpolation_static_part1�..interpolation_static_partN�suffix` for
* interpolated properties.
*
* @param {?} tData `TData` where meta-data will be saved;
* @param {?} tNode `TNode` that is a target of the binding;
* @param {?} propertyName bound property name;
* @param {?} bindingIndex binding index in `LView`
* @param {...?} interpolationParts static interpolation parts (for property interpolations)
* @return {?}
*/
function storePropertyBindingMetadata(tData, tNode, propertyName, bindingIndex, ...interpolationParts) {
// Binding meta-data are stored only the first time a given property instruction is processed.
// Since we don't have a concept of the "first update pass" we need to check for presence of the
// binding meta-data to decide if one should be stored (or if was stored already).
if (tData[bindingIndex] === null) {
if (tNode.inputs == null || !tNode.inputs[propertyName]) {
/** @type {?} */
const propBindingIdxs = tNode.propertyBindings || (tNode.propertyBindings = []);
propBindingIdxs.push(bindingIndex);
/** @type {?} */
let bindingMetadata = propertyName;
if (interpolationParts.length > 0) {
bindingMetadata +=
INTERPOLATION_DELIMITER + interpolationParts.join(INTERPOLATION_DELIMITER);
}
tData[bindingIndex] = bindingMetadata;
}
}
}
/** @type {?} */
const CLEAN_PROMISE = _CLEAN_PROMISE;
/**
* @param {?} view
* @return {?}
*/
function getLCleanup(view) {
// top level variables should not be exported for performance reasons (PERF_NOTES.md)
return view[CLEANUP] || (view[CLEANUP] = ngDevMode ? new LCleanup() : []);
}
/**
* @param {?} tView
* @return {?}
*/
function getTViewCleanup(tView) {
return tView.cleanup || (tView.cleanup = ngDevMode ? new TCleanup() : []);
}
/**
* There are cases where the sub component's renderer needs to be included
* instead of the current renderer (see the componentSyntheticHost* instructions).
* @param {?} currentDef
* @param {?} tNode
* @param {?} lView
* @return {?}
*/
function loadComponentRenderer(currentDef, tNode, lView) {
// TODO(FW-2043): the `currentDef` is null when host bindings are invoked while creating root
// component (see packages/core/src/render3/component.ts). This is not consistent with the process
// of creating inner components, when current directive index is available in the state. In order
// to avoid relying on current def being `null` (thus special-casing root component creation), the
// process of creating root component should be unified with the process of creating inner
// components.
if (currentDef === null || isComponentDef(currentDef)) {
lView = (/** @type {?} */ (unwrapLView(lView[tNode.index])));
}
return lView[RENDERER];
}
/**
* Handles an error thrown in an LView.
* @param {?} lView
* @param {?} error
* @return {?}
*/
function handleError(lView, error) {
/** @type {?} */
const injector = lView[INJECTOR$1];
/** @type {?} */
const errorHandler = injector ? injector.get(ErrorHandler, null) : null;
errorHandler && errorHandler.handleError(error);
}
/**
* Set the inputs of directives at the current node to corresponding value.
*
* @param {?} tView The current TView
* @param {?} lView the `LView` which contains the directives.
* @param {?} inputs mapping between the public "input" name and privately-known,
* possibly minified, property names to write to.
* @param {?} publicName
* @param {?} value Value to set.
* @return {?}
*/
function setInputsForProperty(tView, lView, inputs, publicName, value) {
for (let i = 0; i < inputs.length;) {
/** @type {?} */
const index = (/** @type {?} */ (inputs[i++]));
/** @type {?} */
const privateName = (/** @type {?} */ (inputs[i++]));
/** @type {?} */
const instance = lView[index];
ngDevMode && assertDataInRange(lView, index);
/** @type {?} */
const def = (/** @type {?} */ (tView.data[index]));
if (def.setInput !== null) {
(/** @type {?} */ (def.setInput))(instance, value, publicName, privateName);
}
else {
instance[privateName] = value;
}
}
}
/**
* Updates a text binding at a given index in a given LView.
* @param {?} lView
* @param {?} index
* @param {?} value
* @return {?}
*/
function textBindingInternal(lView, index, value) {
ngDevMode && assertNotSame(value, (/** @type {?} */ (NO_CHANGE)), 'value should not be NO_CHANGE');
ngDevMode && assertDataInRange(lView, index + HEADER_OFFSET);
/** @type {?} */
const element = (/** @type {?} */ ((/** @type {?} */ (getNativeByIndex(index, lView)))));
ngDevMode && assertDefined(element, 'native element should exist');
ngDevMode && ngDevMode.rendererSetText++;
/** @type {?} */
const renderer = lView[RENDERER];
isProceduralRenderer(renderer) ? renderer.setValue(element, value) : element.textContent = value;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/node_manipulation.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const unusedValueToPlacateAjd$1 = unusedValueExportToPlacateAjd$1 + unusedValueExportToPlacateAjd$4 + unusedValueExportToPlacateAjd$5 + unusedValueExportToPlacateAjd$2 + unusedValueExportToPlacateAjd;
/**
* @param {?} tNode
* @param {?} embeddedView
* @return {?}
*/
function getLContainer(tNode, embeddedView) {
ngDevMode && assertLView(embeddedView);
/** @type {?} */
const container = (/** @type {?} */ (embeddedView[PARENT]));
if (tNode.index === -1) {
// This is a dynamically created view inside a dynamic container.
// The parent isn't an LContainer if the embedded view hasn't been attached yet.
return isLContainer(container) ? container : null;
}
else {
ngDevMode && assertLContainer(container);
// This is a inline view node (e.g. embeddedViewStart)
return container;
}
}
/**
* Retrieves render parent for a given view.
* Might be null if a view is not yet attached to any container.
* @param {?} tViewNode
* @param {?} view
* @return {?}
*/
function getContainerRenderParent(tViewNode, view) {
/** @type {?} */
const container = getLContainer(tViewNode, view);
return container ? nativeParentNode(view[RENDERER], container[NATIVE]) : null;
}
/** @enum {number} */
const WalkTNodeTreeAction = {
/** node create in the native environment. Run on initial creation. */
Create: 0,
/**
* node insert in the native environment.
* Run when existing node has been detached and needs to be re-attached.
*/
Insert: 1,
/** node detach from the native environment */
Detach: 2,
/** node destruction using the renderer's API */
Destroy: 3,
};
/**
* NOTE: for performance reasons, the possible actions are inlined within the function instead of
* being passed as an argument.
* @param {?} action
* @param {?} renderer
* @param {?} parent
* @param {?} lNodeToHandle
* @param {?=} beforeNode
* @return {?}
*/
function applyToElementOrContainer(action, renderer, parent, lNodeToHandle, beforeNode) {
// If this slot was allocated for a text node dynamically created by i18n, the text node itself
// won't be created until i18nApply() in the update block, so this node should be skipped.
// For more info, see "ICU expressions should work inside an ngTemplateOutlet inside an ngFor"
// in `i18n_spec.ts`.
if (lNodeToHandle != null) {
/** @type {?} */
let lContainer;
/** @type {?} */
let isComponent = false;
// We are expecting an RNode, but in the case of a component or LContainer the `RNode` is
// wrapped in an array which needs to be unwrapped. We need to know if it is a component and if
// it has LContainer so that we can process all of those cases appropriately.
if (isLContainer(lNodeToHandle)) {
lContainer = lNodeToHandle;
}
else if (isLView(lNodeToHandle)) {
isComponent = true;
ngDevMode && assertDefined(lNodeToHandle[HOST], 'HOST must be defined for a component LView');
lNodeToHandle = (/** @type {?} */ (lNodeToHandle[HOST]));
}
/** @type {?} */
const rNode = unwrapRNode(lNodeToHandle);
ngDevMode && !isProceduralRenderer(renderer) && assertDomNode(rNode);
if (action === 0 /* Create */ && parent !== null) {
if (beforeNode == null) {
nativeAppendChild(renderer, parent, rNode);
}
else {
nativeInsertBefore(renderer, parent, rNode, beforeNode || null);
}
}
else if (action === 1 /* Insert */ && parent !== null) {
nativeInsertBefore(renderer, parent, rNode, beforeNode || null);
}
else if (action === 2 /* Detach */) {
nativeRemoveNode(renderer, rNode, isComponent);
}
else if (action === 3 /* Destroy */) {
ngDevMode && ngDevMode.rendererDestroyNode++;
(/** @type {?} */ (((/** @type {?} */ (renderer))).destroyNode))(rNode);
}
if (lContainer != null) {
applyContainer(renderer, action, lContainer, parent, beforeNode);
}
}
}
/**
* @param {?} value
* @param {?} renderer
* @return {?}
*/
function createTextNode(value, renderer) {
ngDevMode && ngDevMode.rendererCreateTextNode++;
ngDevMode && ngDevMode.rendererSetText++;
return isProceduralRenderer(renderer) ? renderer.createText(value) :
renderer.createTextNode(value);
}
/**
* @param {?} tView
* @param {?} lView
* @param {?} insertMode
* @param {?} beforeNode
* @return {?}
*/
function addRemoveViewFromContainer(tView, lView, insertMode, beforeNode) {
/** @type {?} */
const renderParent = getContainerRenderParent((/** @type {?} */ (tView.node)), lView);
ngDevMode && assertNodeType((/** @type {?} */ (tView.node)), 2 /* View */);
if (renderParent) {
/** @type {?} */
const renderer = lView[RENDERER];
/** @type {?} */
const action = insertMode ? 1 /* Insert */ : 2 /* Detach */;
applyView(tView, lView, renderer, action, renderParent, beforeNode);
}
}
/**
* Detach a `LView` from the DOM by detaching its nodes.
*
* @param {?} tView The `TView' of the `LView` to be detached
* @param {?} lView the `LView` to be detached.
* @return {?}
*/
function renderDetachView(tView, lView) {
applyView(tView, lView, lView[RENDERER], 2 /* Detach */, null, null);
}
/**
* Traverses down and up the tree of views and containers to remove listeners and
* call onDestroy callbacks.
*
* Notes:
* - Because it's used for onDestroy calls, it needs to be bottom-up.
* - Must process containers instead of their views to avoid splicing
* when views are destroyed and re-added.
* - Using a while loop because it's faster than recursion
* - Destroy only called on movement to sibling or movement to parent (laterally or up)
*
* @param {?} rootView The view to destroy
* @return {?}
*/
function destroyViewTree(rootView) {
// If the view has no children, we can clean it up and return early.
/** @type {?} */
let lViewOrLContainer = rootView[CHILD_HEAD];
if (!lViewOrLContainer) {
return cleanUpView(rootView[TVIEW], rootView);
}
while (lViewOrLContainer) {
/** @type {?} */
let next = null;
if (isLView(lViewOrLContainer)) {
// If LView, traverse down to child.
next = lViewOrLContainer[CHILD_HEAD];
}
else {
ngDevMode && assertLContainer(lViewOrLContainer);
// If container, traverse down to its first LView.
/** @type {?} */
const firstView = lViewOrLContainer[CONTAINER_HEADER_OFFSET];
if (firstView)
next = firstView;
}
if (!next) {
// Only clean up view when moving to the side or up, as destroy hooks
// should be called in order from the bottom up.
while (lViewOrLContainer && !(/** @type {?} */ (lViewOrLContainer))[NEXT] && lViewOrLContainer !== rootView) {
isLView(lViewOrLContainer) && cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
lViewOrLContainer = getParentState(lViewOrLContainer, rootView);
}
if (lViewOrLContainer === null)
lViewOrLContainer = rootView;
isLView(lViewOrLContainer) && cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
next = lViewOrLContainer && (/** @type {?} */ (lViewOrLContainer))[NEXT];
}
lViewOrLContainer = next;
}
}
/**
* Inserts a view into a container.
*
* This adds the view to the container's array of active views in the correct
* position. It also adds the view's elements to the DOM if the container isn't a
* root node of another view (in that case, the view's elements will be added when
* the container's parent view is added later).
*
* @param {?} tView The `TView' of the `LView` to insert
* @param {?} lView The view to insert
* @param {?} lContainer The container into which the view should be inserted
* @param {?} index Which index in the container to insert the child view into
* @return {?}
*/
function insertView(tView, lView, lContainer, index) {
ngDevMode && assertLView(lView);
ngDevMode && assertLContainer(lContainer);
/** @type {?} */
const indexInContainer = CONTAINER_HEADER_OFFSET + index;
/** @type {?} */
const containerLength = lContainer.length;
if (index > 0) {
// This is a new view, we need to add it to the children.
lContainer[indexInContainer - 1][NEXT] = lView;
}
if (index < containerLength - CONTAINER_HEADER_OFFSET) {
lView[NEXT] = lContainer[indexInContainer];
addToArray(lContainer, CONTAINER_HEADER_OFFSET + index, lView);
}
else {
lContainer.push(lView);
lView[NEXT] = null;
}
lView[PARENT] = lContainer;
// track views where declaration and insertion points are different
/** @type {?} */
const declarationLContainer = lView[DECLARATION_LCONTAINER];
if (declarationLContainer !== null && lContainer !== declarationLContainer) {
trackMovedView(declarationLContainer, lView);
}
// notify query that a new view has been added
/** @type {?} */
const lQueries = lView[QUERIES];
if (lQueries !== null) {
lQueries.insertView(tView);
}
// Sets the attached flag
lView[FLAGS] |= 128 /* Attached */;
}
/**
* Track views created from the declaration container (TemplateRef) and inserted into a
* different LContainer.
* @param {?} declarationContainer
* @param {?} lView
* @return {?}
*/
function trackMovedView(declarationContainer, lView) {
ngDevMode && assertDefined(lView, 'LView required');
ngDevMode && assertLContainer(declarationContainer);
/** @type {?} */
const movedViews = declarationContainer[MOVED_VIEWS];
/** @type {?} */
const insertedLContainer = (/** @type {?} */ (lView[PARENT]));
ngDevMode && assertLContainer(insertedLContainer);
/** @type {?} */
const insertedComponentLView = (/** @type {?} */ (insertedLContainer[PARENT]))[DECLARATION_COMPONENT_VIEW];
ngDevMode && assertDefined(insertedComponentLView, 'Missing insertedComponentLView');
/** @type {?} */
const declaredComponentLView = lView[DECLARATION_COMPONENT_VIEW];
ngDevMode && assertDefined(declaredComponentLView, 'Missing declaredComponentLView');
if (declaredComponentLView !== insertedComponentLView) {
// At this point the declaration-component is not same as insertion-component; this means that
// this is a transplanted view. Mark the declared lView as having transplanted views so that
// those views can participate in CD.
declarationContainer[HAS_TRANSPLANTED_VIEWS] = true;
}
if (movedViews === null) {
declarationContainer[MOVED_VIEWS] = [lView];
}
else {
movedViews.push(lView);
}
}
/**
* @param {?} declarationContainer
* @param {?} lView
* @return {?}
*/
function detachMovedView(declarationContainer, lView) {
ngDevMode && assertLContainer(declarationContainer);
ngDevMode &&
assertDefined(declarationContainer[MOVED_VIEWS], 'A projected view should belong to a non-empty projected views collection');
/** @type {?} */
const movedViews = (/** @type {?} */ (declarationContainer[MOVED_VIEWS]));
/** @type {?} */
const declarationViewIndex = movedViews.indexOf(lView);
/** @type {?} */
const insertionLContainer = (/** @type {?} */ (lView[PARENT]));
ngDevMode && assertLContainer(insertionLContainer);
// If the view was marked for refresh but then detached before it was checked (where the flag
// would be cleared and the counter decremented), we need to decrement the view counter here
// instead.
if (lView[FLAGS] & 1024 /* RefreshTransplantedView */) {
updateTransplantedViewCount(insertionLContainer, -1);
}
movedViews.splice(declarationViewIndex, 1);
}
/**
* Detaches a view from a container.
*
* This method removes the view from the container's array of active views. It also
* removes the view's elements from the DOM.
*
* @param {?} lContainer The container from which to detach a view
* @param {?} removeIndex The index of the view to detach
* @return {?} Detached LView instance.
*/
function detachView(lContainer, removeIndex) {
if (lContainer.length <= CONTAINER_HEADER_OFFSET)
return;
/** @type {?} */
const indexInContainer = CONTAINER_HEADER_OFFSET + removeIndex;
/** @type {?} */
const viewToDetach = lContainer[indexInContainer];
if (viewToDetach) {
/** @type {?} */
const declarationLContainer = viewToDetach[DECLARATION_LCONTAINER];
if (declarationLContainer !== null && declarationLContainer !== lContainer) {
detachMovedView(declarationLContainer, viewToDetach);
}
if (removeIndex > 0) {
lContainer[indexInContainer - 1][NEXT] = (/** @type {?} */ (viewToDetach[NEXT]));
}
/** @type {?} */
const removedLView = removeFromArray(lContainer, CONTAINER_HEADER_OFFSET + removeIndex);
addRemoveViewFromContainer(viewToDetach[TVIEW], viewToDetach, false, null);
// notify query that a view has been removed
/** @type {?} */
const lQueries = removedLView[QUERIES];
if (lQueries !== null) {
lQueries.detachView(removedLView[TVIEW]);
}
viewToDetach[PARENT] = null;
viewToDetach[NEXT] = null;
// Unsets the attached flag
viewToDetach[FLAGS] &= ~128 /* Attached */;
}
return viewToDetach;
}
/**
* Removes a view from a container, i.e. detaches it and then destroys the underlying LView.
*
* @param {?} lContainer The container from which to remove a view
* @param {?} removeIndex The index of the view to remove
* @return {?}
*/
function removeView(lContainer, removeIndex) {
/** @type {?} */
const detachedView = detachView(lContainer, removeIndex);
detachedView && destroyLView(detachedView[TVIEW], detachedView);
}
/**
* A standalone function which destroys an LView,
* conducting clean up (e.g. removing listeners, calling onDestroys).
*
* @param {?} tView The `TView' of the `LView` to be destroyed
* @param {?} lView The view to be destroyed.
* @return {?}
*/
function destroyLView(tView, lView) {
if (!(lView[FLAGS] & 256 /* Destroyed */)) {
/** @type {?} */
const renderer = lView[RENDERER];
if (isProceduralRenderer(renderer) && renderer.destroyNode) {
applyView(tView, lView, renderer, 3 /* Destroy */, null, null);
}
destroyViewTree(lView);
}
}
/**
* Determines which LViewOrLContainer to jump to when traversing back up the
* tree in destroyViewTree.
*
* Normally, the view's parent LView should be checked, but in the case of
* embedded views, the container (which is the view node's parent, but not the
* LView's parent) needs to be checked for a possible next property.
*
* @param {?} lViewOrLContainer The LViewOrLContainer for which we need a parent state
* @param {?} rootView The rootView, so we don't propagate too far up the view tree
* @return {?} The correct parent LViewOrLContainer
*/
function getParentState(lViewOrLContainer, rootView) {
/** @type {?} */
let tNode;
if (isLView(lViewOrLContainer) && (tNode = lViewOrLContainer[T_HOST]) &&
tNode.type === 2 /* View */) {
// if it's an embedded view, the state needs to go up to the container, in case the
// container has a next
return getLContainer((/** @type {?} */ (tNode)), lViewOrLContainer);
}
else {
// otherwise, use parent view for containers or component views
return lViewOrLContainer[PARENT] === rootView ? null : lViewOrLContainer[PARENT];
}
}
/**
* Calls onDestroys hooks for all directives and pipes in a given view and then removes all
* listeners. Listeners are removed as the last step so events delivered in the onDestroys hooks
* can be propagated to \@Output listeners.
*
* @param {?} tView `TView` for the `LView` to clean up.
* @param {?} lView The LView to clean up
* @return {?}
*/
function cleanUpView(tView, lView) {
if (!(lView[FLAGS] & 256 /* Destroyed */)) {
// Usually the Attached flag is removed when the view is detached from its parent, however
// if it's a root view, the flag won't be unset hence why we're also removing on destroy.
lView[FLAGS] &= ~128 /* Attached */;
// Mark the LView as destroyed *before* executing the onDestroy hooks. An onDestroy hook
// runs arbitrary user code, which could include its own `viewRef.destroy()` (or similar). If
// We don't flag the view as destroyed before the hooks, this could lead to an infinite loop.
// This also aligns with the ViewEngine behavior. It also means that the onDestroy hook is
// really more of an "afterDestroy" hook if you think about it.
lView[FLAGS] |= 256 /* Destroyed */;
executeOnDestroys(tView, lView);
removeListeners(tView, lView);
/** @type {?} */
const hostTNode = lView[T_HOST];
// For component views only, the local renderer is destroyed as clean up time.
if (hostTNode && hostTNode.type === 3 /* Element */ &&
isProceduralRenderer(lView[RENDERER])) {
ngDevMode && ngDevMode.rendererDestroy++;
((/** @type {?} */ (lView[RENDERER]))).destroy();
}
/** @type {?} */
const declarationContainer = lView[DECLARATION_LCONTAINER];
// we are dealing with an embedded view that is still inserted into a container
if (declarationContainer !== null && isLContainer(lView[PARENT])) {
// and this is a projected view
if (declarationContainer !== lView[PARENT]) {
detachMovedView(declarationContainer, lView);
}
// For embedded views still attached to a container: remove query result from this view.
/** @type {?} */
const lQueries = lView[QUERIES];
if (lQueries !== null) {
lQueries.detachView(tView);
}
}
}
}
/**
* Removes listeners and unsubscribes from output subscriptions
* @param {?} tView
* @param {?} lView
* @return {?}
*/
function removeListeners(tView, lView) {
/** @type {?} */
const tCleanup = tView.cleanup;
if (tCleanup !== null) {
/** @type {?} */
const lCleanup = (/** @type {?} */ (lView[CLEANUP]));
for (let i = 0; i < tCleanup.length - 1; i += 2) {
if (typeof tCleanup[i] === 'string') {
// This is a native DOM listener
/** @type {?} */
const idxOrTargetGetter = tCleanup[i + 1];
/** @type {?} */
const target = typeof idxOrTargetGetter === 'function' ?
idxOrTargetGetter(lView) :
unwrapRNode(lView[idxOrTargetGetter]);
/** @type {?} */
const listener = lCleanup[tCleanup[i + 2]];
/** @type {?} */
const useCaptureOrSubIdx = tCleanup[i + 3];
if (typeof useCaptureOrSubIdx === 'boolean') {
// native DOM listener registered with Renderer3
target.removeEventListener(tCleanup[i], listener, useCaptureOrSubIdx);
}
else {
if (useCaptureOrSubIdx >= 0) {
// unregister
lCleanup[useCaptureOrSubIdx]();
}
else {
// Subscription
lCleanup[-useCaptureOrSubIdx].unsubscribe();
}
}
i += 2;
}
else {
// This is a cleanup function that is grouped with the index of its context
/** @type {?} */
const context = lCleanup[tCleanup[i + 1]];
tCleanup[i].call(context);
}
}
lView[CLEANUP] = null;
}
}
/**
* Calls onDestroy hooks for this view
* @param {?} tView
* @param {?} lView
* @return {?}
*/
function executeOnDestroys(tView, lView) {
/** @type {?} */
let destroyHooks;
if (tView != null && (destroyHooks = tView.destroyHooks) != null) {
for (let i = 0; i < destroyHooks.length; i += 2) {
/** @type {?} */
const context = lView[(/** @type {?} */ (destroyHooks[i]))];
// Only call the destroy hook if the context has been requested.
if (!(context instanceof NodeInjectorFactory)) {
/** @type {?} */
const toCall = (/** @type {?} */ (destroyHooks[i + 1]));
if (Array.isArray(toCall)) {
for (let j = 0; j < toCall.length; j += 2) {
((/** @type {?} */ (toCall[j + 1]))).call(context[(/** @type {?} */ (toCall[j]))]);
}
}
else {
toCall.call(context);
}
}
}
}
}
/**
* Returns a native element if a node can be inserted into the given parent.
*
* There are two reasons why we may not be able to insert a element immediately.
* - Projection: When creating a child content element of a component, we have to skip the
* insertion because the content of a component will be projected.
* `<component><content>delayed due to projection</content></component>`
* - Parent container is disconnected: This can happen when we are inserting a view into
* parent container, which itself is disconnected. For example the parent container is part
* of a View which has not be inserted or is made for projection but has not been inserted
* into destination.
* @param {?} tView
* @param {?} tNode
* @param {?} currentView
* @return {?}
*/
function getRenderParent(tView, tNode, currentView) {
// Skip over element and ICU containers as those are represented by a comment node and
// can't be used as a render parent.
/** @type {?} */
let parentTNode = tNode.parent;
while (parentTNode != null &&
(parentTNode.type === 4 /* ElementContainer */ ||
parentTNode.type === 5 /* IcuContainer */)) {
tNode = parentTNode;
parentTNode = tNode.parent;
}
// If the parent tNode is null, then we are inserting across views: either into an embedded view
// or a component view.
if (parentTNode == null) {
/** @type {?} */
const hostTNode = (/** @type {?} */ (currentView[T_HOST]));
if (hostTNode.type === 2 /* View */) {
// We are inserting a root element of an embedded view We might delay insertion of children
// for a given view if it is disconnected. This might happen for 2 main reasons:
// - view is not inserted into any container(view was created but not inserted yet)
// - view is inserted into a container but the container itself is not inserted into the DOM
// (container might be part of projection or child of a view that is not inserted yet).
// In other words we can insert children of a given view if this view was inserted into a
// container and the container itself has its render parent determined.
return getContainerRenderParent((/** @type {?} */ (hostTNode)), currentView);
}
else {
// We are inserting a root element of the component view into the component host element and
// it should always be eager.
ngDevMode && assertNodeOfPossibleTypes(hostTNode, 3 /* Element */);
return currentView[HOST];
}
}
else {
/** @type {?} */
const isIcuCase = tNode && tNode.type === 5 /* IcuContainer */;
// If the parent of this node is an ICU container, then it is represented by comment node and we
// need to use it as an anchor. If it is projected then it's direct parent node is the renderer.
if (isIcuCase && tNode.flags & 4 /* isProjected */) {
return (/** @type {?} */ (getNativeByTNode(tNode, currentView).parentNode));
}
ngDevMode && assertNodeType(parentTNode, 3 /* Element */);
if (parentTNode.flags & 2 /* isComponentHost */) {
/** @type {?} */
const tData = tView.data;
/** @type {?} */
const tNode = (/** @type {?} */ (tData[parentTNode.index]));
/** @type {?} */
const encapsulation = ((/** @type {?} */ (tData[tNode.directiveStart]))).encapsulation;
// We've got a parent which is an element in the current view. We just need to verify if the
// parent element is not a component. Component's content nodes are not inserted immediately
// because they will be projected, and so doing insert at this point would be wasteful.
// Since the projection would then move it to its final destination. Note that we can't
// make this assumption when using the Shadow DOM, because the native projection placeholders
// (<content> or <slot>) have to be in place as elements are being inserted.
if (encapsulation !== ViewEncapsulation$1.ShadowDom &&
encapsulation !== ViewEncapsulation$1.Native) {
return null;
}
}
return (/** @type {?} */ (getNativeByTNode(parentTNode, currentView)));
}
}
/**
* Inserts a native node before another native node for a given parent using {\@link Renderer3}.
* This is a utility function that can be used when native nodes were determined - it abstracts an
* actual renderer being used.
* @param {?} renderer
* @param {?} parent
* @param {?} child
* @param {?} beforeNode
* @return {?}
*/
function nativeInsertBefore(renderer, parent, child, beforeNode) {
ngDevMode && ngDevMode.rendererInsertBefore++;
if (isProceduralRenderer(renderer)) {
renderer.insertBefore(parent, child, beforeNode);
}
else {
parent.insertBefore(child, beforeNode, true);
}
}
/**
* @param {?} renderer
* @param {?} parent
* @param {?} child
* @return {?}
*/
function nativeAppendChild(renderer, parent, child) {
ngDevMode && ngDevMode.rendererAppendChild++;
ngDevMode && assertDefined(parent, 'parent node must be defined');
if (isProceduralRenderer(renderer)) {
renderer.appendChild(parent, child);
}
else {
parent.appendChild(child);
}
}
/**
* @param {?} renderer
* @param {?} parent
* @param {?} child
* @param {?} beforeNode
* @return {?}
*/
function nativeAppendOrInsertBefore(renderer, parent, child, beforeNode) {
if (beforeNode !== null) {
nativeInsertBefore(renderer, parent, child, beforeNode);
}
else {
nativeAppendChild(renderer, parent, child);
}
}
/**
* Removes a node from the DOM given its native parent.
* @param {?} renderer
* @param {?} parent
* @param {?} child
* @param {?=} isHostElement
* @return {?}
*/
function nativeRemoveChild(renderer, parent, child, isHostElement) {
if (isProceduralRenderer(renderer)) {
renderer.removeChild(parent, child, isHostElement);
}
else {
parent.removeChild(child);
}
}
/**
* Returns a native parent of a given native node.
* @param {?} renderer
* @param {?} node
* @return {?}
*/
function nativeParentNode(renderer, node) {
return (/** @type {?} */ ((isProceduralRenderer(renderer) ? renderer.parentNode(node) : node.parentNode)));
}
/**
* Returns a native sibling of a given native node.
* @param {?} renderer
* @param {?} node
* @return {?}
*/
function nativeNextSibling(renderer, node) {
return isProceduralRenderer(renderer) ? renderer.nextSibling(node) : node.nextSibling;
}
/**
* Finds a native "anchor" node for cases where we can't append a native child directly
* (`appendChild`) and need to use a reference (anchor) node for the `insertBefore` operation.
* @param {?} parentTNode
* @param {?} lView
* @return {?}
*/
function getNativeAnchorNode(parentTNode, lView) {
if (parentTNode.type === 2 /* View */) {
/** @type {?} */
const lContainer = getLContainer((/** @type {?} */ (parentTNode)), lView);
if (lContainer === null)
return null;
/** @type {?} */
const index = lContainer.indexOf(lView, CONTAINER_HEADER_OFFSET) - CONTAINER_HEADER_OFFSET;
return getBeforeNodeForView(index, lContainer);
}
else if (parentTNode.type === 4 /* ElementContainer */ ||
parentTNode.type === 5 /* IcuContainer */) {
return getNativeByTNode(parentTNode, lView);
}
return null;
}
/**
* Appends the `child` native node (or a collection of nodes) to the `parent`.
*
* The element insertion might be delayed {\@link canInsertNativeNode}.
*
* @param {?} tView The `TView' to be appended
* @param {?} lView The current LView
* @param {?} childEl The native child (or children) that should be appended
* @param {?} childTNode The TNode of the child element
* @return {?} Whether or not the child was appended
*/
function appendChild(tView, lView, childEl, childTNode) {
/** @type {?} */
const renderParent = getRenderParent(tView, childTNode, lView);
if (renderParent != null) {
/** @type {?} */
const renderer = lView[RENDERER];
/** @type {?} */
const parentTNode = childTNode.parent || (/** @type {?} */ (lView[T_HOST]));
/** @type {?} */
const anchorNode = getNativeAnchorNode(parentTNode, lView);
if (Array.isArray(childEl)) {
for (let i = 0; i < childEl.length; i++) {
nativeAppendOrInsertBefore(renderer, renderParent, childEl[i], anchorNode);
}
}
else {
nativeAppendOrInsertBefore(renderer, renderParent, childEl, anchorNode);
}
}
}
/**
* Returns the first native node for a given LView, starting from the provided TNode.
*
* Native nodes are returned in the order in which those appear in the native tree (DOM).
* @param {?} lView
* @param {?} tNode
* @return {?}
*/
function getFirstNativeNode(lView, tNode) {
if (tNode !== null) {
ngDevMode &&
assertNodeOfPossibleTypes(tNode, 3 /* Element */, 0 /* Container */, 4 /* ElementContainer */, 5 /* IcuContainer */, 1 /* Projection */);
/** @type {?} */
const tNodeType = tNode.type;
if (tNodeType === 3 /* Element */) {
return getNativeByTNode(tNode, lView);
}
else if (tNodeType === 0 /* Container */) {
return getBeforeNodeForView(-1, lView[tNode.index]);
}
else if (tNodeType === 4 /* ElementContainer */ || tNodeType === 5 /* IcuContainer */) {
/** @type {?} */
const elIcuContainerChild = tNode.child;
if (elIcuContainerChild !== null) {
return getFirstNativeNode(lView, elIcuContainerChild);
}
else {
/** @type {?} */
const rNodeOrLContainer = lView[tNode.index];
if (isLContainer(rNodeOrLContainer)) {
return getBeforeNodeForView(-1, rNodeOrLContainer);
}
else {
return unwrapRNode(rNodeOrLContainer);
}
}
}
else {
/** @type {?} */
const componentView = lView[DECLARATION_COMPONENT_VIEW];
/** @type {?} */
const componentHost = (/** @type {?} */ (componentView[T_HOST]));
/** @type {?} */
const parentView = getLViewParent(componentView);
/** @type {?} */
const firstProjectedTNode = ((/** @type {?} */ (componentHost.projection)))[(/** @type {?} */ (tNode.projection))];
if (firstProjectedTNode != null) {
return getFirstNativeNode((/** @type {?} */ (parentView)), firstProjectedTNode);
}
else {
return getFirstNativeNode(lView, tNode.next);
}
}
}
return null;
}
/**
* @param {?} viewIndexInContainer
* @param {?} lContainer
* @return {?}
*/
function getBeforeNodeForView(viewIndexInContainer, lContainer) {
/** @type {?} */
const nextViewIndex = CONTAINER_HEADER_OFFSET + viewIndexInContainer + 1;
if (nextViewIndex < lContainer.length) {
/** @type {?} */
const lView = (/** @type {?} */ (lContainer[nextViewIndex]));
/** @type {?} */
const firstTNodeOfView = lView[TVIEW].firstChild;
if (firstTNodeOfView !== null) {
return getFirstNativeNode(lView, firstTNodeOfView);
}
}
return lContainer[NATIVE];
}
/**
* Removes a native node itself using a given renderer. To remove the node we are looking up its
* parent from the native tree as not all platforms / browsers support the equivalent of
* node.remove().
*
* @param {?} renderer A renderer to be used
* @param {?} rNode The native node that should be removed
* @param {?=} isHostElement A flag indicating if a node to be removed is a host of a component.
* @return {?}
*/
function nativeRemoveNode(renderer, rNode, isHostElement) {
/** @type {?} */
const nativeParent = nativeParentNode(renderer, rNode);
if (nativeParent) {
nativeRemoveChild(renderer, nativeParent, rNode, isHostElement);
}
}
/**
* Performs the operation of `action` on the node. Typically this involves inserting or removing
* nodes on the LView or projection boundary.
* @param {?} renderer
* @param {?} action
* @param {?} tNode
* @param {?} lView
* @param {?} renderParent
* @param {?} beforeNode
* @param {?} isProjection
* @return {?}
*/
function applyNodes(renderer, action, tNode, lView, renderParent, beforeNode, isProjection) {
while (tNode != null) {
ngDevMode && assertTNodeForLView(tNode, lView);
ngDevMode &&
assertNodeOfPossibleTypes(tNode, 0 /* Container */, 3 /* Element */, 4 /* ElementContainer */, 1 /* Projection */, 1 /* Projection */, 5 /* IcuContainer */);
/** @type {?} */
const rawSlotValue = lView[tNode.index];
/** @type {?} */
const tNodeType = tNode.type;
if (isProjection) {
if (action === 0 /* Create */) {
rawSlotValue && attachPatchData(unwrapRNode(rawSlotValue), lView);
tNode.flags |= 4 /* isProjected */;
}
}
if ((tNode.flags & 64 /* isDetached */) !== 64 /* isDetached */) {
if (tNodeType === 4 /* ElementContainer */ || tNodeType === 5 /* IcuContainer */) {
applyNodes(renderer, action, tNode.child, lView, renderParent, beforeNode, false);
applyToElementOrContainer(action, renderer, renderParent, rawSlotValue, beforeNode);
}
else if (tNodeType === 1 /* Projection */) {
applyProjectionRecursive(renderer, action, lView, (/** @type {?} */ (tNode)), renderParent, beforeNode);
}
else {
ngDevMode && assertNodeOfPossibleTypes(tNode, 3 /* Element */, 0 /* Container */);
applyToElementOrContainer(action, renderer, renderParent, rawSlotValue, beforeNode);
}
}
tNode = isProjection ? tNode.projectionNext : tNode.next;
}
}
/**
* `applyView` performs operation on the view as specified in `action` (insert, detach, destroy)
*
* Inserting a view without projection or containers at top level is simple. Just iterate over the
* root nodes of the View, and for each node perform the `action`.
*
* Things get more complicated with containers and projections. That is because coming across:
* - Container: implies that we have to insert/remove/destroy the views of that container as well
* which in turn can have their own Containers at the View roots.
* - Projection: implies that we have to insert/remove/destroy the nodes of the projection. The
* complication is that the nodes we are projecting can themselves have Containers
* or other Projections.
*
* As you can see this is a very recursive problem. Yes recursion is not most efficient but the
* code is complicated enough that trying to implemented with recursion becomes unmaintainable.
*
* @param {?} tView The `TView' which needs to be inserted, detached, destroyed
* @param {?} lView The LView which needs to be inserted, detached, destroyed.
* @param {?} renderer Renderer to use
* @param {?} action action to perform (insert, detach, destroy)
* @param {?} renderParent parent DOM element for insertion/removal.
* @param {?} beforeNode Before which node the insertions should happen.
* @return {?}
*/
function applyView(tView, lView, renderer, action, renderParent, beforeNode) {
ngDevMode && assertNodeType((/** @type {?} */ (tView.node)), 2 /* View */);
/** @type {?} */
const viewRootTNode = (/** @type {?} */ (tView.node)).child;
applyNodes(renderer, action, viewRootTNode, lView, renderParent, beforeNode, false);
}
/**
* `applyProjection` performs operation on the projection.
*
* Inserting a projection requires us to locate the projected nodes from the parent component. The
* complication is that those nodes themselves could be re-projected from their parent component.
*
* @param {?} tView The `TView` of `LView` which needs to be inserted, detached, destroyed
* @param {?} lView The `LView` which needs to be inserted, detached, destroyed.
* @param {?} tProjectionNode node to project
* @return {?}
*/
function applyProjection(tView, lView, tProjectionNode) {
/** @type {?} */
const renderer = lView[RENDERER];
/** @type {?} */
const renderParent = getRenderParent(tView, tProjectionNode, lView);
/** @type {?} */
const parentTNode = tProjectionNode.parent || (/** @type {?} */ (lView[T_HOST]));
/** @type {?} */
let beforeNode = getNativeAnchorNode(parentTNode, lView);
applyProjectionRecursive(renderer, 0 /* Create */, lView, tProjectionNode, renderParent, beforeNode);
}
/**
* `applyProjectionRecursive` performs operation on the projection specified by `action` (insert,
* detach, destroy)
*
* Inserting a projection requires us to locate the projected nodes from the parent component. The
* complication is that those nodes themselves could be re-projected from their parent component.
*
* @param {?} renderer Render to use
* @param {?} action action to perform (insert, detach, destroy)
* @param {?} lView The LView which needs to be inserted, detached, destroyed.
* @param {?} tProjectionNode node to project
* @param {?} renderParent parent DOM element for insertion/removal.
* @param {?} beforeNode Before which node the insertions should happen.
* @return {?}
*/
function applyProjectionRecursive(renderer, action, lView, tProjectionNode, renderParent, beforeNode) {
/** @type {?} */
const componentLView = lView[DECLARATION_COMPONENT_VIEW];
/** @type {?} */
const componentNode = (/** @type {?} */ (componentLView[T_HOST]));
ngDevMode &&
assertEqual(typeof tProjectionNode.projection, 'number', 'expecting projection index');
/** @type {?} */
const nodeToProjectOrRNodes = (/** @type {?} */ ((/** @type {?} */ (componentNode.projection))[tProjectionNode.projection]));
if (Array.isArray(nodeToProjectOrRNodes)) {
// This should not exist, it is a bit of a hack. When we bootstrap a top level node and we
// need to support passing projectable nodes, so we cheat and put them in the TNode
// of the Host TView. (Yes we put instance info at the T Level). We can get away with it
// because we know that that TView is not shared and therefore it will not be a problem.
// This should be refactored and cleaned up.
for (let i = 0; i < nodeToProjectOrRNodes.length; i++) {
/** @type {?} */
const rNode = nodeToProjectOrRNodes[i];
applyToElementOrContainer(action, renderer, renderParent, rNode, beforeNode);
}
}
else {
/** @type {?} */
let nodeToProject = nodeToProjectOrRNodes;
/** @type {?} */
const projectedComponentLView = (/** @type {?} */ (componentLView[PARENT]));
applyNodes(renderer, action, nodeToProject, projectedComponentLView, renderParent, beforeNode, true);
}
}
/**
* `applyContainer` performs an operation on the container and its views as specified by
* `action` (insert, detach, destroy)
*
* Inserting a Container is complicated by the fact that the container may have Views which
* themselves have containers or projections.
*
* @param {?} renderer Renderer to use
* @param {?} action action to perform (insert, detach, destroy)
* @param {?} lContainer The LContainer which needs to be inserted, detached, destroyed.
* @param {?} renderParent parent DOM element for insertion/removal.
* @param {?} beforeNode Before which node the insertions should happen.
* @return {?}
*/
function applyContainer(renderer, action, lContainer, renderParent, beforeNode) {
ngDevMode && assertLContainer(lContainer);
/** @type {?} */
const anchor = lContainer[NATIVE];
// LContainer has its own before node.
/** @type {?} */
const native = unwrapRNode(lContainer);
// An LContainer can be created dynamically on any node by injecting ViewContainerRef.
// Asking for a ViewContainerRef on an element will result in a creation of a separate anchor node
// (comment in the DOM) that will be different from the LContainer's host node. In this particular
// case we need to execute action on 2 nodes:
// - container's host node (this is done in the executeActionOnElementOrContainer)
// - container's host node (this is done here)
if (anchor !== native) {
// This is very strange to me (Misko). I would expect that the native is same as anchor. I don't
// see a reason why they should be different, but they are.
//
// If they are we need to process the second anchor as well.
applyToElementOrContainer(action, renderer, renderParent, anchor, beforeNode);
}
for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
/** @type {?} */
const lView = (/** @type {?} */ (lContainer[i]));
applyView(lView[TVIEW], lView, renderer, action, renderParent, anchor);
}
}
/**
* Writes class/style to element.
*
* @param {?} renderer Renderer to use.
* @param {?} isClassBased `true` if it should be written to `class` (`false` to write to `style`)
* @param {?} rNode The Node to write to.
* @param {?} prop Property to write to. This would be the class/style name.
* @param {?} value Value to write. If `null`/`undefined`/`false` this is considered a remove (set/add
* otherwise).
* @return {?}
*/
function applyStyling(renderer, isClassBased, rNode, prop, value) {
/** @type {?} */
const isProcedural = isProceduralRenderer(renderer);
if (isClassBased) {
// We actually want JS true/false here because any truthy value should add the class
if (!value) {
ngDevMode && ngDevMode.rendererRemoveClass++;
if (isProcedural) {
((/** @type {?} */ (renderer))).removeClass(rNode, prop);
}
else {
((/** @type {?} */ (rNode))).classList.remove(prop);
}
}
else {
ngDevMode && ngDevMode.rendererAddClass++;
if (isProcedural) {
((/** @type {?} */ (renderer))).addClass(rNode, prop);
}
else {
ngDevMode && assertDefined(((/** @type {?} */ (rNode))).classList, 'HTMLElement expected');
((/** @type {?} */ (rNode))).classList.add(prop);
}
}
}
else {
// TODO(misko): Can't import RendererStyleFlags2.DashCase as it causes imports to be resolved in
// different order which causes failures. Using direct constant as workaround for now.
/** @type {?} */
const flags = prop.indexOf('-') == -1 ? undefined : 2 /* RendererStyleFlags2.DashCase */;
if (value == null /** || value === undefined */) {
ngDevMode && ngDevMode.rendererRemoveStyle++;
if (isProcedural) {
((/** @type {?} */ (renderer))).removeStyle(rNode, prop, flags);
}
else {
((/** @type {?} */ (rNode))).style.removeProperty(prop);
}
}
else {
ngDevMode && ngDevMode.rendererSetStyle++;
if (isProcedural) {
((/** @type {?} */ (renderer))).setStyle(rNode, prop, value, flags);
}
else {
ngDevMode && assertDefined(((/** @type {?} */ (rNode))).style, 'HTMLElement expected');
((/** @type {?} */ (rNode))).style.setProperty(prop, value);
}
}
}
}
/**
* Write `cssText` to `RElement`.
*
* This function does direct write without any reconciliation. Used for writing initial values, so
* that static styling values do not pull in the style parser.
*
* @param {?} renderer Renderer to use
* @param {?} element The element which needs to be updated.
* @param {?} newValue The new class list to write.
* @return {?}
*/
function writeDirectStyle(renderer, element, newValue) {
ngDevMode && assertString(newValue, '\'newValue\' should be a string');
if (isProceduralRenderer(renderer)) {
renderer.setAttribute(element, 'style', newValue);
}
else {
((/** @type {?} */ (element))).style.cssText = newValue;
}
ngDevMode && ngDevMode.rendererSetStyle++;
}
/**
* Write `className` to `RElement`.
*
* This function does direct write without any reconciliation. Used for writing initial values, so
* that static styling values do not pull in the style parser.
*
* @param {?} renderer Renderer to use
* @param {?} element The element which needs to be updated.
* @param {?} newValue The new class list to write.
* @return {?}
*/
function writeDirectClass(renderer, element, newValue) {
ngDevMode && assertString(newValue, '\'newValue\' should be a string');
if (isProceduralRenderer(renderer)) {
if (newValue === '') {
// There are tests in `google3` which expect `element.getAttribute('class')` to be `null`.
renderer.removeAttribute(element, 'class');
}
else {
renderer.setAttribute(element, 'class', newValue);
}
}
else {
element.className = newValue;
}
ngDevMode && ngDevMode.rendererSetClassName++;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/node_util.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* If `startTNode.parent` exists and has an injector, returns TNode for that injector.
* Otherwise, unwraps a parent injector location number to find the view offset from the current
* injector, then walks up the declaration view tree until the TNode of the parent injector is
* found.
*
* @param {?} location The location of the parent injector, which contains the view offset
* @param {?} startView The LView instance from which to start walking up the view tree
* @param {?} startTNode The TNode instance of the starting element
* @return {?} The TNode of the parent injector
*/
function getParentInjectorTNode(location, startView, startTNode) {
// If there is an injector on the parent TNode, retrieve the TNode for that injector.
if (startTNode.parent && startTNode.parent.injectorIndex !== -1) {
// view offset is 0
/** @type {?} */
const injectorIndex = startTNode.parent.injectorIndex;
/** @type {?} */
let tNode = startTNode.parent;
// If tNode.injectorIndex === tNode.parent.injectorIndex, then the index belongs to a parent
// injector.
while (tNode.parent != null && injectorIndex == tNode.parent.injectorIndex) {
tNode = tNode.parent;
}
return tNode;
}
/** @type {?} */
let viewOffset = getParentInjectorViewOffset(location);
// view offset is 1
/** @type {?} */
let parentView = startView;
/** @type {?} */
let parentTNode = (/** @type {?} */ (startView[T_HOST]));
// view offset is superior to 1
while (viewOffset > 1) {
parentView = (/** @type {?} */ (parentView[DECLARATION_VIEW]));
parentTNode = (/** @type {?} */ (parentView[T_HOST]));
viewOffset--;
}
return parentTNode;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/view_ref.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @record
*/
function viewEngine_ChangeDetectorRef_interface() { }
/**
* @template T
*/
class ViewRef {
/**
* @param {?} _lView
* @param {?=} _cdRefInjectingView
*/
constructor(_lView, _cdRefInjectingView) {
this._lView = _lView;
this._cdRefInjectingView = _cdRefInjectingView;
this._appRef = null;
this._viewContainerRef = null;
}
/**
* @return {?}
*/
get rootNodes() {
/** @type {?} */
const lView = this._lView;
if (lView[HOST] == null) {
/** @type {?} */
const hostTView = (/** @type {?} */ (lView[T_HOST]));
return collectNativeNodes(lView[TVIEW], lView, hostTView.child, []);
}
return [];
}
/**
* @return {?}
*/
get context() {
return (/** @type {?} */ (this._lView[CONTEXT]));
}
/**
* @return {?}
*/
get destroyed() {
return (this._lView[FLAGS] & 256 /* Destroyed */) === 256 /* Destroyed */;
}
/**
* @return {?}
*/
destroy() {
if (this._appRef) {
this._appRef.detachView(this);
}
else if (this._viewContainerRef) {
/** @type {?} */
const index = this._viewContainerRef.indexOf(this);
if (index > -1) {
this._viewContainerRef.detach(index);
}
this._viewContainerRef = null;
}
destroyLView(this._lView[TVIEW], this._lView);
}
/**
* @param {?} callback
* @return {?}
*/
onDestroy(callback) {
storeCleanupFn(this._lView[TVIEW], this._lView, callback);
}
/**
* Marks a view and all of its ancestors dirty.
*
* It also triggers change detection by calling `scheduleTick` internally, which coalesces
* multiple `markForCheck` calls to into one change detection run.
*
* This can be used to ensure an {\@link ChangeDetectionStrategy#OnPush OnPush} component is
* checked when it needs to be re-rendered but the two normal triggers haven't marked it
* dirty (i.e. inputs haven't changed and events haven't fired in the view).
*
* <!-- TODO: Add a link to a chapter on OnPush components -->
*
* \@usageNotes
* ### Example
*
* ```typescript
* \@Component({
* selector: 'my-app',
* template: `Number of ticks: {{numberOfTicks}}`
* changeDetection: ChangeDetectionStrategy.OnPush,
* })
* class AppComponent {
* numberOfTicks = 0;
*
* constructor(private ref: ChangeDetectorRef) {
* setInterval(() => {
* this.numberOfTicks++;
* // the following is required, otherwise the view will not be updated
* this.ref.markForCheck();
* }, 1000);
* }
* }
* ```
* @return {?}
*/
markForCheck() {
markViewDirty(this._cdRefInjectingView || this._lView);
}
/**
* Detaches the view from the change detection tree.
*
* Detached views will not be checked during change detection runs until they are
* re-attached, even if they are dirty. `detach` can be used in combination with
* {\@link ChangeDetectorRef#detectChanges detectChanges} to implement local change
* detection checks.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
* <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
*
* \@usageNotes
* ### Example
*
* The following example defines a component with a large list of readonly data.
* Imagine the data changes constantly, many times per second. For performance reasons,
* we want to check and update the list every five seconds. We can do that by detaching
* the component's change detector and doing a local check every five seconds.
*
* ```typescript
* class DataProvider {
* // in a real application the returned data will be different every time
* get data() {
* return [1,2,3,4,5];
* }
* }
*
* \@Component({
* selector: 'giant-list',
* template: `
* <li *ngFor="let d of dataProvider.data">Data {{d}}</li>
* `,
* })
* class GiantList {
* constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {
* ref.detach();
* setInterval(() => {
* this.ref.detectChanges();
* }, 5000);
* }
* }
* /
* selector: 'app',
* providers: [DataProvider],
* template: `
* <giant-list><giant-list>
* `,
* })
* class App {
* }
* ```
* @return {?}
*/
detach() {
this._lView[FLAGS] &= ~128 /* Attached */;
}
/**
* Re-attaches a view to the change detection tree.
*
* This can be used to re-attach views that were previously detached from the tree
* using {\@link ChangeDetectorRef#detach detach}. Views are attached to the tree by default.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
*
* \@usageNotes
* ### Example
*
* The following example creates a component displaying `live` data. The component will detach
* its change detector from the main change detector tree when the component's live property
* is set to false.
*
* ```typescript
* class DataProvider {
* data = 1;
*
* constructor() {
* setInterval(() => {
* this.data = this.data * 2;
* }, 500);
* }
* }
*
* \@Component({
* selector: 'live-data',
* inputs: ['live'],
* template: 'Data: {{dataProvider.data}}'
* })
* class LiveData {
* constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {}
*
* set live(value) {
* if (value) {
* this.ref.reattach();
* } else {
* this.ref.detach();
* }
* }
* }
* /
* selector: 'my-app',
* providers: [DataProvider],
* template: `
* Live Update: <input type="checkbox" [(ngModel)]="live">
* <live-data [live]="live"><live-data>
* `,
* })
* class AppComponent {
* live = true;
* }
* ```
* @return {?}
*/
reattach() {
this._lView[FLAGS] |= 128 /* Attached */;
}
/**
* Checks the view and its children.
*
* This can also be used in combination with {\@link ChangeDetectorRef#detach detach} to implement
* local change detection checks.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
* <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
*
* \@usageNotes
* ### Example
*
* The following example defines a component with a large list of readonly data.
* Imagine, the data changes constantly, many times per second. For performance reasons,
* we want to check and update the list every five seconds.
*
* We can do that by detaching the component's change detector and doing a local change detection
* check every five seconds.
*
* See {\@link ChangeDetectorRef#detach detach} for more information.
* @return {?}
*/
detectChanges() {
detectChangesInternal(this._lView[TVIEW], this._lView, this.context);
}
/**
* Checks the change detector and its children, and throws if any changes are detected.
*
* This is used in development mode to verify that running change detection doesn't
* introduce other changes.
* @return {?}
*/
checkNoChanges() {
checkNoChangesInternal(this._lView[TVIEW], this._lView, this.context);
}
/**
* @param {?} vcRef
* @return {?}
*/
attachToViewContainerRef(vcRef) {
if (this._appRef) {
throw new Error('This view is already attached directly to the ApplicationRef!');
}
this._viewContainerRef = vcRef;
}
/**
* @return {?}
*/
detachFromAppRef() {
this._appRef = null;
renderDetachView(this._lView[TVIEW], this._lView);
}
/**
* @param {?} appRef
* @return {?}
*/
attachToAppRef(appRef) {
if (this._viewContainerRef) {
throw new Error('This view is already attached to a ViewContainer!');
}
this._appRef = appRef;
}
}
if (false) {}
/**
* \@internal
* @template T
*/
class RootViewRef extends ViewRef {
/**
* @param {?} _view
*/
constructor(_view) {
super(_view);
this._view = _view;
}
/**
* @return {?}
*/
detectChanges() {
detectChangesInRootView(this._view);
}
/**
* @return {?}
*/
checkNoChanges() {
checkNoChangesInRootView(this._view);
}
/**
* @return {?}
*/
get context() {
return (/** @type {?} */ (null));
}
}
if (false) {}
/**
* @param {?} tView
* @param {?} lView
* @param {?} tNode
* @param {?} result
* @param {?=} isProjection
* @return {?}
*/
function collectNativeNodes(tView, lView, tNode, result, isProjection = false) {
while (tNode !== null) {
ngDevMode &&
assertNodeOfPossibleTypes(tNode, 3 /* Element */, 0 /* Container */, 1 /* Projection */, 4 /* ElementContainer */, 5 /* IcuContainer */);
/** @type {?} */
const lNode = lView[tNode.index];
if (lNode !== null) {
result.push(unwrapRNode(lNode));
}
// A given lNode can represent either a native node or a LContainer (when it is a host of a
// ViewContainerRef). When we find a LContainer we need to descend into it to collect root nodes
// from the views in this container.
if (isLContainer(lNode)) {
for (let i = CONTAINER_HEADER_OFFSET; i < lNode.length; i++) {
/** @type {?} */
const lViewInAContainer = lNode[i];
/** @type {?} */
const lViewFirstChildTNode = lViewInAContainer[TVIEW].firstChild;
if (lViewFirstChildTNode !== null) {
collectNativeNodes(lViewInAContainer[TVIEW], lViewInAContainer, lViewFirstChildTNode, result);
}
}
}
/** @type {?} */
const tNodeType = tNode.type;
if (tNodeType === 4 /* ElementContainer */ || tNodeType === 5 /* IcuContainer */) {
collectNativeNodes(tView, lView, tNode.child, result);
}
else if (tNodeType === 1 /* Projection */) {
/** @type {?} */
const componentView = lView[DECLARATION_COMPONENT_VIEW];
/** @type {?} */
const componentHost = (/** @type {?} */ (componentView[T_HOST]));
/** @type {?} */
const slotIdx = (/** @type {?} */ (tNode.projection));
ngDevMode &&
assertDefined(componentHost.projection, 'Components with projection nodes (<ng-content>) must have projection slots defined.');
/** @type {?} */
const nodesInSlot = (/** @type {?} */ (componentHost.projection))[slotIdx];
if (Array.isArray(nodesInSlot)) {
result.push(...nodesInSlot);
}
else {
/** @type {?} */
const parentView = (/** @type {?} */ (getLViewParent(componentView)));
ngDevMode &&
assertDefined(parentView, 'Component views should always have a parent view (component\'s host view)');
collectNativeNodes(parentView[TVIEW], parentView, nodesInSlot, result, true);
}
}
tNode = isProjection ? tNode.projectionNext : tNode.next;
}
return result;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/view_engine_compatibility.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Creates an ElementRef from the most recent node.
*
* @param {?} ElementRefToken
* @return {?} The ElementRef instance to use
*/
function injectElementRef(ElementRefToken) {
return createElementRef(ElementRefToken, getPreviousOrParentTNode(), getLView());
}
/** @type {?} */
let R3ElementRef;
/**
* Creates an ElementRef given a node.
*
* @param {?} ElementRefToken The ElementRef type
* @param {?} tNode The node for which you'd like an ElementRef
* @param {?} view The view to which the node belongs
* @return {?} The ElementRef instance to use
*/
function createElementRef(ElementRefToken, tNode, view) {
if (!R3ElementRef) {
R3ElementRef = class ElementRef extends ElementRefToken {
};
}
return new R3ElementRef((/** @type {?} */ (getNativeByTNode(tNode, view))));
}
/** @type {?} */
let R3TemplateRef;
/**
* Creates a TemplateRef given a node.
*
* @template T
* @param {?} TemplateRefToken
* @param {?} ElementRefToken
* @return {?} The TemplateRef instance to use
*/
function injectTemplateRef(TemplateRefToken, ElementRefToken) {
return createTemplateRef(TemplateRefToken, ElementRefToken, getPreviousOrParentTNode(), getLView());
}
/**
* Creates a TemplateRef and stores it on the injector.
*
* @template T
* @param {?} TemplateRefToken The TemplateRef type
* @param {?} ElementRefToken The ElementRef type
* @param {?} hostTNode The node on which a TemplateRef is requested
* @param {?} hostView The view to which the node belongs
* @return {?} The TemplateRef instance or null if we can't create a TemplateRef on a given node type
*/
function createTemplateRef(TemplateRefToken, ElementRefToken, hostTNode, hostView) {
if (!R3TemplateRef) {
R3TemplateRef = class TemplateRef extends TemplateRefToken {
/**
* @param {?} _declarationView
* @param {?} _declarationTContainer
* @param {?} elementRef
*/
constructor(_declarationView, _declarationTContainer, elementRef) {
super();
this._declarationView = _declarationView;
this._declarationTContainer = _declarationTContainer;
this.elementRef = elementRef;
}
/**
* @param {?} context
* @return {?}
*/
createEmbeddedView(context) {
/** @type {?} */
const embeddedTView = (/** @type {?} */ (this._declarationTContainer.tViews));
/** @type {?} */
const embeddedLView = createLView(this._declarationView, embeddedTView, context, 16 /* CheckAlways */, null, embeddedTView.node);
/** @type {?} */
const declarationLContainer = this._declarationView[this._declarationTContainer.index];
ngDevMode && assertLContainer(declarationLContainer);
embeddedLView[DECLARATION_LCONTAINER] = declarationLContainer;
/** @type {?} */
const declarationViewLQueries = this._declarationView[QUERIES];
if (declarationViewLQueries !== null) {
embeddedLView[QUERIES] = declarationViewLQueries.createEmbeddedView(embeddedTView);
}
renderView(embeddedTView, embeddedLView, context);
return new ViewRef(embeddedLView);
}
};
}
if (hostTNode.type === 0 /* Container */) {
ngDevMode && assertDefined(hostTNode.tViews, 'TView must be allocated');
return new R3TemplateRef(hostView, (/** @type {?} */ (hostTNode)), createElementRef(ElementRefToken, hostTNode, hostView));
}
else {
return null;
}
}
/** @type {?} */
let R3ViewContainerRef;
/**
* Creates a ViewContainerRef and stores it on the injector. Or, if the ViewContainerRef
* already exists, retrieves the existing ViewContainerRef.
*
* @param {?} ViewContainerRefToken
* @param {?} ElementRefToken
* @return {?} The ViewContainerRef instance to use
*/
function injectViewContainerRef(ViewContainerRefToken, ElementRefToken) {
/** @type {?} */
const previousTNode = (/** @type {?} */ (getPreviousOrParentTNode()));
return createContainerRef(ViewContainerRefToken, ElementRefToken, previousTNode, getLView());
}
/**
* Creates a ViewContainerRef and stores it on the injector.
*
* @param {?} ViewContainerRefToken The ViewContainerRef type
* @param {?} ElementRefToken The ElementRef type
* @param {?} hostTNode The node that is requesting a ViewContainerRef
* @param {?} hostView The view to which the node belongs
* @return {?} The ViewContainerRef instance to use
*/
function createContainerRef(ViewContainerRefToken, ElementRefToken, hostTNode, hostView) {
if (!R3ViewContainerRef) {
R3ViewContainerRef = class ViewContainerRef extends ViewContainerRefToken {
/**
* @param {?} _lContainer
* @param {?} _hostTNode
* @param {?} _hostView
*/
constructor(_lContainer, _hostTNode, _hostView) {
super();
this._lContainer = _lContainer;
this._hostTNode = _hostTNode;
this._hostView = _hostView;
}
/**
* @return {?}
*/
get element() {
return createElementRef(ElementRefToken, this._hostTNode, this._hostView);
}
/**
* @return {?}
*/
get injector() {
return new NodeInjector(this._hostTNode, this._hostView);
}
/**
* @deprecated No replacement
* @return {?}
*/
get parentInjector() {
/** @type {?} */
const parentLocation = getParentInjectorLocation(this._hostTNode, this._hostView);
/** @type {?} */
const parentView = getParentInjectorView(parentLocation, this._hostView);
/** @type {?} */
const parentTNode = getParentInjectorTNode(parentLocation, this._hostView, this._hostTNode);
return !hasParentInjector(parentLocation) || parentTNode == null ?
new NodeInjector(null, this._hostView) :
new NodeInjector(parentTNode, parentView);
}
/**
* @return {?}
*/
clear() {
while (this.length > 0) {
this.remove(this.length - 1);
}
}
/**
* @param {?} index
* @return {?}
*/
get(index) {
return this._lContainer[VIEW_REFS] !== null && (/** @type {?} */ (this._lContainer[VIEW_REFS]))[index] || null;
}
/**
* @return {?}
*/
get length() {
return this._lContainer.length - CONTAINER_HEADER_OFFSET;
}
/**
* @template C
* @param {?} templateRef
* @param {?=} context
* @param {?=} index
* @return {?}
*/
createEmbeddedView(templateRef, context, index) {
/** @type {?} */
const viewRef = templateRef.createEmbeddedView(context || (/** @type {?} */ ({})));
this.insert(viewRef, index);
return viewRef;
}
/**
* @template C
* @param {?} componentFactory
* @param {?=} index
* @param {?=} injector
* @param {?=} projectableNodes
* @param {?=} ngModuleRef
* @return {?}
*/
createComponent(componentFactory, index, injector, projectableNodes, ngModuleRef) {
/** @type {?} */
const contextInjector = injector || this.parentInjector;
if (!ngModuleRef && ((/** @type {?} */ (componentFactory))).ngModule == null && contextInjector) {
// DO NOT REFACTOR. The code here used to have a `value || undefined` expression
// which seems to cause internal google apps to fail. This is documented in the
// following internal bug issue: go/b/142967802
/** @type {?} */
const result = contextInjector.get(NgModuleRef, null);
if (result) {
ngModuleRef = result;
}
}
/** @type {?} */
const componentRef = componentFactory.create(contextInjector, projectableNodes, undefined, ngModuleRef);
this.insert(componentRef.hostView, index);
return componentRef;
}
/**
* @param {?} viewRef
* @param {?=} index
* @return {?}
*/
insert(viewRef, index) {
/** @type {?} */
const lView = (/** @type {?} */ (((/** @type {?} */ (viewRef)))._lView));
/** @type {?} */
const tView = lView[TVIEW];
if (viewRef.destroyed) {
throw new Error('Cannot insert a destroyed View in a ViewContainer!');
}
this.allocateContainerIfNeeded();
if (viewAttachedToContainer(lView)) {
// If view is already attached, detach it first so we clean up references appropriately.
/** @type {?} */
const prevIdx = this.indexOf(viewRef);
// A view might be attached either to this or a different container. The `prevIdx` for
// those cases will be:
// equal to -1 for views attached to this ViewContainerRef
// >= 0 for views attached to a different ViewContainerRef
if (prevIdx !== -1) {
this.detach(prevIdx);
}
else {
/** @type {?} */
const prevLContainer = (/** @type {?} */ (lView[PARENT]));
ngDevMode &&
assertEqual(isLContainer(prevLContainer), true, 'An attached view should have its PARENT point to a container.');
// We need to re-create a R3ViewContainerRef instance since those are not stored on
// LView (nor anywhere else).
/** @type {?} */
const prevVCRef = new R3ViewContainerRef(prevLContainer, (/** @type {?} */ (prevLContainer[T_HOST])), prevLContainer[PARENT]);
prevVCRef.detach(prevVCRef.indexOf(viewRef));
}
}
/** @type {?} */
const adjustedIdx = this._adjustIndex(index);
insertView(tView, lView, this._lContainer, adjustedIdx);
/** @type {?} */
const beforeNode = getBeforeNodeForView(adjustedIdx, this._lContainer);
addRemoveViewFromContainer(tView, lView, true, beforeNode);
((/** @type {?} */ (viewRef))).attachToViewContainerRef(this);
addToArray((/** @type {?} */ (this._lContainer[VIEW_REFS])), adjustedIdx, viewRef);
return viewRef;
}
/**
* @param {?} viewRef
* @param {?} newIndex
* @return {?}
*/
move(viewRef, newIndex) {
if (viewRef.destroyed) {
throw new Error('Cannot move a destroyed View in a ViewContainer!');
}
return this.insert(viewRef, newIndex);
}
/**
* @param {?} viewRef
* @return {?}
*/
indexOf(viewRef) {
/** @type {?} */
const viewRefsArr = this._lContainer[VIEW_REFS];
return viewRefsArr !== null ? viewRefsArr.indexOf(viewRef) : -1;
}
/**
* @param {?=} index
* @return {?}
*/
remove(index) {
this.allocateContainerIfNeeded();
/** @type {?} */
const adjustedIdx = this._adjustIndex(index, -1);
removeView(this._lContainer, adjustedIdx);
removeFromArray((/** @type {?} */ (this._lContainer[VIEW_REFS])), adjustedIdx);
}
/**
* @param {?=} index
* @return {?}
*/
detach(index) {
this.allocateContainerIfNeeded();
/** @type {?} */
const adjustedIdx = this._adjustIndex(index, -1);
/** @type {?} */
const view = detachView(this._lContainer, adjustedIdx);
/** @type {?} */
const wasDetached = view && removeFromArray((/** @type {?} */ (this._lContainer[VIEW_REFS])), adjustedIdx) != null;
return wasDetached ? new ViewRef((/** @type {?} */ (view))) : null;
}
/**
* @private
* @param {?=} index
* @param {?=} shift
* @return {?}
*/
_adjustIndex(index, shift = 0) {
if (index == null) {
return this.length + shift;
}
if (ngDevMode) {
assertGreaterThan(index, -1, `ViewRef index must be positive, got ${index}`);
// +1 because it's legal to insert at the end.
assertLessThan(index, this.length + 1 + shift, 'index');
}
return index;
}
/**
* @private
* @return {?}
*/
allocateContainerIfNeeded() {
if (this._lContainer[VIEW_REFS] === null) {
this._lContainer[VIEW_REFS] = [];
}
}
};
}
ngDevMode &&
assertNodeOfPossibleTypes(hostTNode, 0 /* Container */, 3 /* Element */, 4 /* ElementContainer */);
/** @type {?} */
let lContainer;
/** @type {?} */
const slotValue = hostView[hostTNode.index];
if (isLContainer(slotValue)) {
// If the host is a container, we don't need to create a new LContainer
lContainer = slotValue;
}
else {
/** @type {?} */
let commentNode;
// If the host is an element container, the native host element is guaranteed to be a
// comment and we can reuse that comment as anchor element for the new LContainer.
// The comment node in question is already part of the DOM structure so we don't need to append
// it again.
if (hostTNode.type === 4 /* ElementContainer */) {
commentNode = (/** @type {?} */ (unwrapRNode(slotValue)));
}
else {
ngDevMode && ngDevMode.rendererCreateComment++;
commentNode = hostView[RENDERER].createComment(ngDevMode ? 'container' : '');
// A `ViewContainerRef` can be injected by the root (topmost / bootstrapped) component. In
// this case we can't use TView / TNode data structures to insert container's marker node
// (both a parent of a comment node and the comment node itself are not part of any view). In
// this specific case we use low-level DOM manipulation to insert container's marker (comment)
// node.
if (isRootView(hostView)) {
/** @type {?} */
const renderer = hostView[RENDERER];
/** @type {?} */
const hostNative = (/** @type {?} */ (getNativeByTNode(hostTNode, hostView)));
/** @type {?} */
const parentOfHostNative = nativeParentNode(renderer, hostNative);
nativeInsertBefore(renderer, (/** @type {?} */ (parentOfHostNative)), commentNode, nativeNextSibling(renderer, hostNative));
}
else {
appendChild(hostView[TVIEW], hostView, commentNode, hostTNode);
}
}
hostView[hostTNode.index] = lContainer =
createLContainer(slotValue, hostView, commentNode, hostTNode);
addToViewTree(hostView, lContainer);
}
return new R3ViewContainerRef(lContainer, hostTNode, hostView);
}
/**
* Returns a ChangeDetectorRef (a.k.a. a ViewRef)
* @param {?=} isPipe
* @return {?}
*/
function injectChangeDetectorRef(isPipe = false) {
return createViewRef(getPreviousOrParentTNode(), getLView(), isPipe);
}
/**
* Creates a ViewRef and stores it on the injector as ChangeDetectorRef (public alias).
*
* @param {?} tNode The node that is requesting a ChangeDetectorRef
* @param {?} lView The view to which the node belongs
* @param {?} isPipe Whether the view is being injected into a pipe.
* @return {?} The ChangeDetectorRef to use
*/
function createViewRef(tNode, lView, isPipe) {
// `isComponentView` will be true for Component and Directives (but not for Pipes).
// See https://github.com/angular/angular/pull/33072 for proper fix
/** @type {?} */
const isComponentView = !isPipe && isComponentHost(tNode);
if (isComponentView) {
// The LView represents the location where the component is declared.
// Instead we want the LView for the component View and so we need to look it up.
/** @type {?} */
const componentView = getComponentLViewByIndex(tNode.index, lView);
return new ViewRef(componentView, componentView);
}
else if (tNode.type === 3 /* Element */ || tNode.type === 0 /* Container */ ||
tNode.type === 4 /* ElementContainer */ || tNode.type === 5 /* IcuContainer */) {
// The LView represents the location where the injection is requested from.
// We need to locate the containing LView (in case where the `lView` is an embedded view)
/** @type {?} */
const hostComponentView = lView[DECLARATION_COMPONENT_VIEW];
return new ViewRef(hostComponentView, lView);
}
return (/** @type {?} */ (null));
}
/**
* Returns a Renderer2 (or throws when application was bootstrapped with Renderer3)
* @param {?} view
* @return {?}
*/
function getOrCreateRenderer2(view) {
/** @type {?} */
const renderer = view[RENDERER];
if (isProceduralRenderer(renderer)) {
return (/** @type {?} */ (renderer));
}
else {
throw new Error('Cannot inject Renderer2 when the application uses Renderer3!');
}
}
/**
* Injects a Renderer2 for the current component.
* @return {?}
*/
function injectRenderer2() {
// We need the Renderer to be based on the component that it's being injected into, however since
// DI happens before we've entered its view, `getLView` will return the parent view instead.
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tNode = getPreviousOrParentTNode();
/** @type {?} */
const nodeAtIndex = getComponentLViewByIndex(tNode.index, lView);
return getOrCreateRenderer2(isLView(nodeAtIndex) ? nodeAtIndex : lView);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/change_detection/change_detector_ref.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Base class for Angular Views, provides change detection functionality.
* A change-detection tree collects all views that are to be checked for changes.
* Use the methods to add and remove views from the tree, initiate change-detection,
* and explicitly mark views as _dirty_, meaning that they have changed and need to be rerendered.
*
* \@usageNotes
*
* The following examples demonstrate how to modify default change-detection behavior
* to perform explicit detection when needed.
*
* ### Use `markForCheck()` with `CheckOnce` strategy
*
* The following example sets the `OnPush` change-detection strategy for a component
* (`CheckOnce`, rather than the default `CheckAlways`), then forces a second check
* after an interval. See [live demo](http://plnkr.co/edit/GC512b?p=preview).
*
* <code-example path="core/ts/change_detect/change-detection.ts"
* region="mark-for-check"></code-example>
*
* ### Detach change detector to limit how often check occurs
*
* The following example defines a component with a large list of read-only data
* that is expected to change constantly, many times per second.
* To improve performance, we want to check and update the list
* less often than the changes actually occur. To do that, we detach
* the component's change detector and perform an explicit local check every five seconds.
*
* <code-example path="core/ts/change_detect/change-detection.ts" region="detach"></code-example>
*
*
* ### Reattaching a detached component
*
* The following example creates a component displaying live data.
* The component detaches its change detector from the main change detector tree
* when the `live` property is set to false, and reattaches it when the property
* becomes true.
*
* <code-example path="core/ts/change_detect/change-detection.ts" region="reattach"></code-example>
*
* \@publicApi
* @abstract
*/
class ChangeDetectorRef {
}
/**
* \@internal
* @nocollapse
*/
ChangeDetectorRef.__NG_ELEMENT_ID__ = (/**
* @return {?}
*/
() => SWITCH_CHANGE_DETECTOR_REF_FACTORY());
if (false) {}
/** @type {?} */
const SWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__ = injectChangeDetectorRef;
/** @type {?} */
const SWITCH_CHANGE_DETECTOR_REF_FACTORY__PRE_R3__ = (/**
* @param {...?} args
* @return {?}
*/
(...args) => { });
const ɵ0$5 = SWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__;
/** @type {?} */
const SWITCH_CHANGE_DETECTOR_REF_FACTORY = SWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__;
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @description
*
* Represents a type that a Component or other object is instances of.
*
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by
* the `MyCustomComponent` constructor function.
*
* @publicApi
*/
const Type = Function;
function isType(v) {
return typeof v === 'function';
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Attention: These regex has to hold even if the code is minified!
*/
const DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/;
const INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/;
const INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/;
const INHERITED_CLASS_WITH_DELEGATE_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(\)\s*{\s*super\(\.\.\.arguments\)/;
/**
* Determine whether a stringified type is a class which delegates its constructor
* to its parent.
*
* This is not trivial since compiled code can actually contain a constructor function
* even if the original source code did not. For instance, when the child class contains
* an initialized instance property.
*/
function isDelegateCtor(typeStr) {
return DELEGATE_CTOR.test(typeStr) || INHERITED_CLASS_WITH_DELEGATE_CTOR.test(typeStr) ||
(INHERITED_CLASS.test(typeStr) && !INHERITED_CLASS_WITH_CTOR.test(typeStr));
}
class ReflectionCapabilities {
constructor(reflect) {
this._reflect = reflect || _global['Reflect'];
}
isReflectionEnabled() {
return true;
}
factory(t) {
return (...args) => new t(...args);
}
/** @internal */
_zipTypesAndAnnotations(paramTypes, paramAnnotations) {
let result;
if (typeof paramTypes === 'undefined') {
result = newArray(paramAnnotations.length);
}
else {
result = newArray(paramTypes.length);
}
for (let i = 0; i < result.length; i++) {
// TS outputs Object for parameters without types, while Traceur omits
// the annotations. For now we preserve the Traceur behavior to aid
// migration, but this can be revisited.
if (typeof paramTypes === 'undefined') {
result[i] = [];
}
else if (paramTypes[i] && paramTypes[i] != Object) {
result[i] = [paramTypes[i]];
}
else {
result[i] = [];
}
if (paramAnnotations && paramAnnotations[i] != null) {
result[i] = result[i].concat(paramAnnotations[i]);
}
}
return result;
}
_ownParameters(type, parentCtor) {
const typeStr = type.toString();
// If we have no decorators, we only have function.length as metadata.
// In that case, to detect whether a child class declared an own constructor or not,
// we need to look inside of that constructor to check whether it is
// just calling the parent.
// This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439
// that sets 'design:paramtypes' to []
// if a class inherits from another class but has no ctor declared itself.
if (isDelegateCtor(typeStr)) {
return null;
}
// Prefer the direct API.
if (type.parameters && type.parameters !== parentCtor.parameters) {
return type.parameters;
}
// API of tsickle for lowering decorators to properties on the class.
const tsickleCtorParams = type.ctorParameters;
if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {
// Newer tsickle uses a function closure
// Retain the non-function case for compatibility with older tsickle
const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;
const paramTypes = ctorParameters.map((ctorParam) => ctorParam && ctorParam.type);
const paramAnnotations = ctorParameters.map((ctorParam) => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));
return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
}
// API for metadata created by invoking the decorators.
const paramAnnotations = type.hasOwnProperty(PARAMETERS) && type[PARAMETERS];
const paramTypes = this._reflect && this._reflect.getOwnMetadata &&
this._reflect.getOwnMetadata('design:paramtypes', type);
if (paramTypes || paramAnnotations) {
return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
}
// If a class has no decorators, at least create metadata
// based on function.length.
// Note: We know that this is a real constructor as we checked
// the content of the constructor above.
return newArray(type.length);
}
parameters(type) {
// Note: only report metadata if we have at least one class decorator
// to stay in sync with the static reflector.
if (!isType(type)) {
return [];
}
const parentCtor = getParentCtor(type);
let parameters = this._ownParameters(type, parentCtor);
if (!parameters && parentCtor !== Object) {
parameters = this.parameters(parentCtor);
}
return parameters || [];
}
_ownAnnotations(typeOrFunc, parentCtor) {
// Prefer the direct API.
if (typeOrFunc.annotations && typeOrFunc.annotations !== parentCtor.annotations) {
let annotations = typeOrFunc.annotations;
if (typeof annotations === 'function' && annotations.annotations) {
annotations = annotations.annotations;
}
return annotations;
}
// API of tsickle for lowering decorators to properties on the class.
if (typeOrFunc.decorators && typeOrFunc.decorators !== parentCtor.decorators) {
return convertTsickleDecoratorIntoMetadata(typeOrFunc.decorators);
}
// API for metadata created by invoking the decorators.
if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {
return typeOrFunc[ANNOTATIONS];
}
return null;
}
annotations(typeOrFunc) {
if (!isType(typeOrFunc)) {
return [];
}
const parentCtor = getParentCtor(typeOrFunc);
const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];
const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];
return parentAnnotations.concat(ownAnnotations);
}
_ownPropMetadata(typeOrFunc, parentCtor) {
// Prefer the direct API.
if (typeOrFunc.propMetadata &&
typeOrFunc.propMetadata !== parentCtor.propMetadata) {
let propMetadata = typeOrFunc.propMetadata;
if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
propMetadata = propMetadata.propMetadata;
}
return propMetadata;
}
// API of tsickle for lowering decorators to properties on the class.
if (typeOrFunc.propDecorators &&
typeOrFunc.propDecorators !== parentCtor.propDecorators) {
const propDecorators = typeOrFunc.propDecorators;
const propMetadata = {};
Object.keys(propDecorators).forEach(prop => {
propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);
});
return propMetadata;
}
// API for metadata created by invoking the decorators.
if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {
return typeOrFunc[PROP_METADATA];
}
return null;
}
propMetadata(typeOrFunc) {
if (!isType(typeOrFunc)) {
return {};
}
const parentCtor = getParentCtor(typeOrFunc);
const propMetadata = {};
if (parentCtor !== Object) {
const parentPropMetadata = this.propMetadata(parentCtor);
Object.keys(parentPropMetadata).forEach((propName) => {
propMetadata[propName] = parentPropMetadata[propName];
});
}
const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);
if (ownPropMetadata) {
Object.keys(ownPropMetadata).forEach((propName) => {
const decorators = [];
if (propMetadata.hasOwnProperty(propName)) {
decorators.push(...propMetadata[propName]);
}
decorators.push(...ownPropMetadata[propName]);
propMetadata[propName] = decorators;
});
}
return propMetadata;
}
ownPropMetadata(typeOrFunc) {
if (!isType(typeOrFunc)) {
return {};
}
return this._ownPropMetadata(typeOrFunc, getParentCtor(typeOrFunc)) || {};
}
hasLifecycleHook(type, lcProperty) {
return type instanceof Type && lcProperty in type.prototype;
}
guards(type) {
return {};
}
getter(name) {
return new Function('o', 'return o.' + name + ';');
}
setter(name) {
return new Function('o', 'v', 'return o.' + name + ' = v;');
}
method(name) {
const functionBody = `if (!o.${name}) throw new Error('"${name}" is undefined');
return o.${name}.apply(o, args);`;
return new Function('o', 'args', functionBody);
}
// There is not a concept of import uri in Js, but this is useful in developing Dart applications.
importUri(type) {
// StaticSymbol
if (typeof type === 'object' && type['filePath']) {
return type['filePath'];
}
// Runtime type
return `./${stringify(type)}`;
}
resourceUri(type) {
return `./${stringify(type)}`;
}
resolveIdentifier(name, moduleUrl, members, runtime) {
return runtime;
}
resolveEnum(enumIdentifier, name) {
return enumIdentifier[name];
}
}
function convertTsickleDecoratorIntoMetadata(decoratorInvocations) {
if (!decoratorInvocations) {
return [];
}
return decoratorInvocations.map(decoratorInvocation => {
const decoratorType = decoratorInvocation.type;
const annotationCls = decoratorType.annotationCls;
const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
return new annotationCls(...annotationArgs);
});
}
function getParentCtor(ctor) {
const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;
const parentCtor = parentProto ? parentProto.constructor : null;
// Note: We always use `Object` as the null value
// to simplify checking later on.
return parentCtor || Object;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/jit/util.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
let _reflect = null;
/**
* @return {?}
*/
function getReflect() {
return (_reflect = _reflect || new ReflectionCapabilities());
}
/**
* @param {?} type
* @return {?}
*/
function reflectDependencies(type) {
return convertDependencies(getReflect().parameters(type));
}
/**
* @param {?} deps
* @return {?}
*/
function convertDependencies(deps) {
/** @type {?} */
const compiler = getCompilerFacade();
return deps.map((/**
* @param {?} dep
* @return {?}
*/
dep => reflectDependency(compiler, dep)));
}
/**
* @param {?} compiler
* @param {?} dep
* @return {?}
*/
function reflectDependency(compiler, dep) {
/** @type {?} */
const meta = {
token: null,
host: false,
optional: false,
resolved: compiler.R3ResolvedDependencyType.Token,
self: false,
skipSelf: false,
};
/**
* @param {?} token
* @return {?}
*/
function setTokenAndResolvedType(token) {
meta.resolved = compiler.R3ResolvedDependencyType.Token;
meta.token = token;
}
if (Array.isArray(dep) && dep.length > 0) {
for (let j = 0; j < dep.length; j++) {
/** @type {?} */
const param = dep[j];
if (param === undefined) {
// param may be undefined if type of dep is not set by ngtsc
continue;
}
/** @type {?} */
const proto = Object.getPrototypeOf(param);
if (param instanceof Optional || proto.ngMetadataName === 'Optional') {
meta.optional = true;
}
else if (param instanceof SkipSelf || proto.ngMetadataName === 'SkipSelf') {
meta.skipSelf = true;
}
else if (param instanceof Self || proto.ngMetadataName === 'Self') {
meta.self = true;
}
else if (param instanceof Host || proto.ngMetadataName === 'Host') {
meta.host = true;
}
else if (param instanceof Inject) {
meta.token = param.token;
}
else if (param instanceof Attribute) {
if (param.attributeName === undefined) {
throw new Error(`Attribute name must be defined.`);
}
meta.token = param.attributeName;
meta.resolved = compiler.R3ResolvedDependencyType.Attribute;
}
else if (param === ChangeDetectorRef) {
meta.token = param;
meta.resolved = compiler.R3ResolvedDependencyType.ChangeDetectorRef;
}
else {
setTokenAndResolvedType(param);
}
}
}
else if (dep === undefined || (Array.isArray(dep) && dep.length === 0)) {
meta.token = undefined;
meta.resolved = R3ResolvedDependencyType.Invalid;
}
else {
setTokenAndResolvedType(dep);
}
return meta;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/jit/injectable.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Compile an Angular injectable according to its `Injectable` metadata, and patch the resulting
* injectable def (`ɵprov`) onto the injectable type.
* @param {?} type
* @param {?=} srcMeta
* @return {?}
*/
function compileInjectable(type, srcMeta) {
/** @type {?} */
let ngInjectableDef = null;
/** @type {?} */
let ngFactoryDef = null;
// if NG_PROV_DEF is already defined on this class then don't overwrite it
if (!type.hasOwnProperty(NG_PROV_DEF)) {
Object.defineProperty(type, NG_PROV_DEF, {
get: (/**
* @return {?}
*/
() => {
if (ngInjectableDef === null) {
ngInjectableDef = getCompilerFacade().compileInjectable(angularCoreDiEnv, `ng:///${type.name}/ɵprov.js`, getInjectableMetadata(type, srcMeta));
}
return ngInjectableDef;
}),
});
// On IE10 properties defined via `defineProperty` won't be inherited by child classes,
// which will break inheriting the injectable definition from a grandparent through an
// undecorated parent class. We work around it by defining a method which should be used
// as a fallback. This should only be a problem in JIT mode, because in AOT TypeScript
// seems to have a workaround for static properties. When inheriting from an undecorated
// parent is no longer supported in v10, this can safely be removed.
if (!type.hasOwnProperty(NG_PROV_DEF_FALLBACK)) {
((/** @type {?} */ (type)))[NG_PROV_DEF_FALLBACK] = (/**
* @return {?}
*/
() => ((/** @type {?} */ (type)))[NG_PROV_DEF]);
}
}
// if NG_FACTORY_DEF is already defined on this class then don't overwrite it
if (!type.hasOwnProperty(NG_FACTORY_DEF)) {
Object.defineProperty(type, NG_FACTORY_DEF, {
get: (/**
* @return {?}
*/
() => {
if (ngFactoryDef === null) {
/** @type {?} */
const metadata = getInjectableMetadata(type, srcMeta);
/** @type {?} */
const compiler = getCompilerFacade();
ngFactoryDef = compiler.compileFactory(angularCoreDiEnv, `ng:///${type.name}/ɵfac.js`, {
name: metadata.name,
type: metadata.type,
typeArgumentCount: metadata.typeArgumentCount,
deps: reflectDependencies(type),
injectFn: 'inject',
target: compiler.R3FactoryTarget.Injectable
});
}
return ngFactoryDef;
}),
// Leave this configurable so that the factories from directives or pipes can take precedence.
configurable: true
});
}
}
const ɵ0$6 = getClosureSafeProperty;
/** @type {?} */
const USE_VALUE$1 = getClosureSafeProperty({ provide: String, useValue: ɵ0$6 });
/**
* @param {?} meta
* @return {?}
*/
function isUseClassProvider(meta) {
return ((/** @type {?} */ (meta))).useClass !== undefined;
}
/**
* @param {?} meta
* @return {?}
*/
function isUseValueProvider(meta) {
return USE_VALUE$1 in meta;
}
/**
* @param {?} meta
* @return {?}
*/
function isUseFactoryProvider(meta) {
return ((/** @type {?} */ (meta))).useFactory !== undefined;
}
/**
* @param {?} meta
* @return {?}
*/
function isUseExistingProvider(meta) {
return ((/** @type {?} */ (meta))).useExisting !== undefined;
}
/**
* @param {?} type
* @param {?=} srcMeta
* @return {?}
*/
function getInjectableMetadata(type, srcMeta) {
// Allow the compilation of a class with a `@Injectable()` decorator without parameters
/** @type {?} */
const meta = srcMeta || { providedIn: null };
/** @type {?} */
const compilerMeta = {
name: type.name,
type: type,
typeArgumentCount: 0,
providedIn: meta.providedIn,
userDeps: undefined,
};
if ((isUseClassProvider(meta) || isUseFactoryProvider(meta)) && meta.deps !== undefined) {
compilerMeta.userDeps = convertDependencies(meta.deps);
}
if (isUseClassProvider(meta)) {
// The user explicitly specified useClass, and may or may not have provided deps.
compilerMeta.useClass = resolveForwardRef(meta.useClass);
}
else if (isUseValueProvider(meta)) {
// The user explicitly specified useValue.
compilerMeta.useValue = resolveForwardRef(meta.useValue);
}
else if (isUseFactoryProvider(meta)) {
// The user explicitly specified useFactory.
compilerMeta.useFactory = meta.useFactory;
}
else if (isUseExistingProvider(meta)) {
// The user explicitly specified useExisting.
compilerMeta.useExisting = resolveForwardRef(meta.useExisting);
}
return compilerMeta;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/util.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
const ɵ0$7 = getClosureSafeProperty;
/** @type {?} */
const USE_VALUE$2 = getClosureSafeProperty({ provide: String, useValue: ɵ0$7 });
/** @type {?} */
const EMPTY_ARRAY$1 = [];
/**
* @param {?} type
* @param {?=} provider
* @return {?}
*/
function convertInjectableProviderToFactory(type, provider) {
if (!provider) {
/** @type {?} */
const reflectionCapabilities = new ReflectionCapabilities();
/** @type {?} */
const deps = reflectionCapabilities.parameters(type);
// TODO - convert to flags.
return (/**
* @return {?}
*/
() => new type(...injectArgs((/** @type {?} */ (deps)))));
}
if (USE_VALUE$2 in provider) {
/** @type {?} */
const valueProvider = ((/** @type {?} */ (provider)));
return (/**
* @return {?}
*/
() => valueProvider.useValue);
}
else if (((/** @type {?} */ (provider))).useExisting) {
/** @type {?} */
const existingProvider = ((/** @type {?} */ (provider)));
return (/**
* @return {?}
*/
() => ɵɵinject(resolveForwardRef(existingProvider.useExisting)));
}
else if (((/** @type {?} */ (provider))).useFactory) {
/** @type {?} */
const factoryProvider = ((/** @type {?} */ (provider)));
return (/**
* @return {?}
*/
() => factoryProvider.useFactory(...injectArgs(factoryProvider.deps || EMPTY_ARRAY$1)));
}
else if (((/** @type {?} */ (provider))).useClass) {
/** @type {?} */
const classProvider = ((/** @type {?} */ (provider)));
/** @type {?} */
let deps = ((/** @type {?} */ (provider))).deps;
if (!deps) {
/** @type {?} */
const reflectionCapabilities = new ReflectionCapabilities();
deps = reflectionCapabilities.parameters(type);
}
return (/**
* @return {?}
*/
() => new (resolveForwardRef(classProvider.useClass))(...injectArgs(deps)));
}
else {
/** @type {?} */
let deps = ((/** @type {?} */ (provider))).deps;
if (!deps) {
/** @type {?} */
const reflectionCapabilities = new ReflectionCapabilities();
deps = reflectionCapabilities.parameters(type);
}
return (/**
* @return {?}
*/
() => new type(...injectArgs((/** @type {?} */ (deps)))));
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/injectable.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Type of the Injectable decorator / constructor function.
*
* \@publicApi
* @record
*/
function InjectableDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ0$8 = /**
* @param {?} type
* @param {?} meta
* @return {?}
*/
(type, meta) => SWITCH_COMPILE_INJECTABLE((/** @type {?} */ (type)), meta);
/**
* Injectable decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Injectable = makeDecorator('Injectable', undefined, undefined, undefined, (ɵ0$8));
/**
* Supports \@Injectable() in JIT mode for Render2.
* @param {?} injectableType
* @param {?=} options
* @return {?}
*/
function render2CompileInjectable(injectableType, options) {
if (options && options.providedIn !== undefined && !getInjectableDef(injectableType)) {
((/** @type {?} */ (injectableType))).ɵprov = ɵɵdefineInjectable({
token: injectableType,
providedIn: options.providedIn,
factory: convertInjectableProviderToFactory(injectableType, options),
});
}
}
/** @type {?} */
const SWITCH_COMPILE_INJECTABLE__POST_R3__ = compileInjectable;
/** @type {?} */
const SWITCH_COMPILE_INJECTABLE__PRE_R3__ = render2CompileInjectable;
/** @type {?} */
const SWITCH_COMPILE_INJECTABLE = SWITCH_COMPILE_INJECTABLE__POST_R3__;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/scope.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* An internal token whose presence in an injector indicates that the injector should treat itself
* as a root scoped injector when processing requests for unknown tokens which may indicate
* they are provided in the root scope.
* @type {?}
*/
const INJECTOR_SCOPE = new InjectionToken('Set Injector scope.');
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/r3_injector.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Marker which indicates that a value has not yet been created from the factory function.
* @type {?}
*/
const NOT_YET = {};
/**
* Marker which indicates that the factory function for a token is in the process of being called.
*
* If the injector is asked to inject a token with its value set to CIRCULAR, that indicates
* injection of a dependency has recursively attempted to inject the original token, and there is
* a circular dependency among the providers.
* @type {?}
*/
const CIRCULAR = {};
/** @type {?} */
const EMPTY_ARRAY$2 = (/** @type {?} */ ([]));
/**
* A lazily initialized NullInjector.
* @type {?}
*/
let NULL_INJECTOR = undefined;
/**
* @return {?}
*/
function getNullInjector() {
if (NULL_INJECTOR === undefined) {
NULL_INJECTOR = new NullInjector();
}
return NULL_INJECTOR;
}
/**
* An entry in the injector which tracks information about the given token, including a possible
* current value.
* @record
* @template T
*/
function Record() { }
if (false) {}
/**
* Create a new `Injector` which is configured using a `defType` of `InjectorType<any>`s.
*
* \@publicApi
* @param {?} defType
* @param {?=} parent
* @param {?=} additionalProviders
* @param {?=} name
* @return {?}
*/
function createInjector(defType, parent = null, additionalProviders = null, name) {
/** @type {?} */
const injector = createInjectorWithoutInjectorInstances(defType, parent, additionalProviders, name);
injector._resolveInjectorDefTypes();
return injector;
}
/**
* Creates a new injector without eagerly resolving its injector types. Can be used in places
* where resolving the injector types immediately can lead to an infinite loop. The injector types
* should be resolved at a later point by calling `_resolveInjectorDefTypes`.
* @param {?} defType
* @param {?=} parent
* @param {?=} additionalProviders
* @param {?=} name
* @return {?}
*/
function createInjectorWithoutInjectorInstances(defType, parent = null, additionalProviders = null, name) {
return new R3Injector(defType, additionalProviders, parent || getNullInjector(), name);
}
class R3Injector {
/**
* @param {?} def
* @param {?} additionalProviders
* @param {?} parent
* @param {?=} source
*/
constructor(def, additionalProviders, parent, source = null) {
this.parent = parent;
/**
* Map of tokens to records which contain the instances of those tokens.
* - `null` value implies that we don't have the record. Used by tree-shakable injectors
* to prevent further searches.
*/
this.records = new Map();
/**
* The transitive set of `InjectorType`s which define this injector.
*/
this.injectorDefTypes = new Set();
/**
* Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.
*/
this.onDestroy = new Set();
this._destroyed = false;
/** @type {?} */
const dedupStack = [];
// Start off by creating Records for every provider declared in every InjectorType
// included transitively in additional providers then do the same for `def`. This order is
// important because `def` may include providers that override ones in additionalProviders.
additionalProviders &&
deepForEach(additionalProviders, (/**
* @param {?} provider
* @return {?}
*/
provider => this.processProvider(provider, def, additionalProviders)));
deepForEach([def], (/**
* @param {?} injectorDef
* @return {?}
*/
injectorDef => this.processInjectorType(injectorDef, [], dedupStack)));
// Make sure the INJECTOR token provides this injector.
this.records.set(INJECTOR, makeRecord(undefined, this));
// Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide
// any injectable scoped to APP_ROOT_SCOPE.
/** @type {?} */
const record = this.records.get(INJECTOR_SCOPE);
this.scope = record != null ? record.value : null;
// Source name, used for debugging
this.source = source || (typeof def === 'object' ? null : stringify(def));
}
/**
* Flag indicating that this injector was previously destroyed.
* @return {?}
*/
get destroyed() {
return this._destroyed;
}
/**
* Destroy the injector and release references to every instance or provider associated with it.
*
* Also calls the `OnDestroy` lifecycle hooks of every instance that was created for which a
* hook was found.
* @return {?}
*/
destroy() {
this.assertNotDestroyed();
// Set destroyed = true first, in case lifecycle hooks re-enter destroy().
this._destroyed = true;
try {
// Call all the lifecycle hooks.
this.onDestroy.forEach((/**
* @param {?} service
* @return {?}
*/
service => service.ngOnDestroy()));
}
finally {
// Release all references.
this.records.clear();
this.onDestroy.clear();
this.injectorDefTypes.clear();
}
}
/**
* @template T
* @param {?} token
* @param {?=} notFoundValue
* @param {?=} flags
* @return {?}
*/
get(token, notFoundValue = THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
this.assertNotDestroyed();
// Set the injection context.
/** @type {?} */
const previousInjector = setCurrentInjector(this);
try {
// Check for the SkipSelf flag.
if (!(flags & InjectFlags.SkipSelf)) {
// SkipSelf isn't set, check if the record belongs to this injector.
/** @type {?} */
let record = this.records.get(token);
if (record === undefined) {
// No record, but maybe the token is scoped to this injector. Look for an injectable
// def with a scope matching this injector.
/** @type {?} */
const def = couldBeInjectableType(token) && getInjectableDef(token);
if (def && this.injectableDefInScope(def)) {
// Found an injectable def and it's scoped to this injector. Pretend as if it was here
// all along.
record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);
}
else {
record = null;
}
this.records.set(token, record);
}
// If a record was found, get the instance for it and return it.
if (record != null /* NOT null || undefined */) {
return this.hydrate(token, record);
}
}
// Select the next injector based on the Self flag - if self is set, the next injector is
// the NullInjector, otherwise it's the parent.
/** @type {?} */
const nextInjector = !(flags & InjectFlags.Self) ? this.parent : getNullInjector();
// Set the notFoundValue based on the Optional flag - if optional is set and notFoundValue
// is undefined, the value is null, otherwise it's the notFoundValue.
notFoundValue = (flags & InjectFlags.Optional) && notFoundValue === THROW_IF_NOT_FOUND ?
null :
notFoundValue;
return nextInjector.get(token, notFoundValue);
}
catch (e) {
if (e.name === 'NullInjectorError') {
/** @type {?} */
const path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || [];
path.unshift(stringify(token));
if (previousInjector) {
// We still have a parent injector, keep throwing
throw e;
}
else {
// Format & throw the final error message when we don't have any previous injector
return catchInjectorError(e, token, 'R3InjectorError', this.source);
}
}
else {
throw e;
}
}
finally {
// Lastly, clean up the state by restoring the previous injector.
setCurrentInjector(previousInjector);
}
}
/**
* \@internal
* @return {?}
*/
_resolveInjectorDefTypes() {
this.injectorDefTypes.forEach((/**
* @param {?} defType
* @return {?}
*/
defType => this.get(defType)));
}
/**
* @return {?}
*/
toString() {
/** @type {?} */
const tokens = (/** @type {?} */ ([]));
/** @type {?} */
const records = this.records;
records.forEach((/**
* @param {?} v
* @param {?} token
* @return {?}
*/
(v, token) => tokens.push(stringify(token))));
return `R3Injector[${tokens.join(', ')}]`;
}
/**
* @private
* @return {?}
*/
assertNotDestroyed() {
if (this._destroyed) {
throw new Error('Injector has already been destroyed.');
}
}
/**
* Add an `InjectorType` or `InjectorTypeWithProviders` and all of its transitive providers
* to this injector.
*
* If an `InjectorTypeWithProviders` that declares providers besides the type is specified,
* the function will return "true" to indicate that the providers of the type definition need
* to be processed. This allows us to process providers of injector types after all imports of
* an injector definition are processed. (following View Engine semantics: see FW-1349)
* @private
* @param {?} defOrWrappedDef
* @param {?} parents
* @param {?} dedupStack
* @return {?}
*/
processInjectorType(defOrWrappedDef, parents, dedupStack) {
defOrWrappedDef = resolveForwardRef(defOrWrappedDef);
if (!defOrWrappedDef)
return false;
// Either the defOrWrappedDef is an InjectorType (with injector def) or an
// InjectorDefTypeWithProviders (aka ModuleWithProviders). Detecting either is a megamorphic
// read, so care is taken to only do the read once.
// First attempt to read the injector def (`ɵinj`).
/** @type {?} */
let def = getInjectorDef(defOrWrappedDef);
// If that's not present, then attempt to read ngModule from the InjectorDefTypeWithProviders.
/** @type {?} */
const ngModule = (def == null) && ((/** @type {?} */ (defOrWrappedDef))).ngModule || undefined;
// Determine the InjectorType. In the case where `defOrWrappedDef` is an `InjectorType`,
// then this is easy. In the case of an InjectorDefTypeWithProviders, then the definition type
// is the `ngModule`.
/** @type {?} */
const defType = (ngModule === undefined) ? ((/** @type {?} */ (defOrWrappedDef))) : ngModule;
// Check for circular dependencies.
if (ngDevMode && parents.indexOf(defType) !== -1) {
/** @type {?} */
const defName = stringify(defType);
throw new Error(`Circular dependency in DI detected for type ${defName}. Dependency path: ${parents.map((/**
* @param {?} defType
* @return {?}
*/
defType => stringify(defType))).join(' > ')} > ${defName}.`);
}
// Check for multiple imports of the same module
/** @type {?} */
const isDuplicate = dedupStack.indexOf(defType) !== -1;
// Finally, if defOrWrappedType was an `InjectorDefTypeWithProviders`, then the actual
// `InjectorDef` is on its `ngModule`.
if (ngModule !== undefined) {
def = getInjectorDef(ngModule);
}
// If no definition was found, it might be from exports. Remove it.
if (def == null) {
return false;
}
// Add providers in the same way that @NgModule resolution did:
// First, include providers from any imports.
if (def.imports != null && !isDuplicate) {
// Before processing defType's imports, add it to the set of parents. This way, if it ends
// up deeply importing itself, this can be detected.
ngDevMode && parents.push(defType);
// Add it to the set of dedups. This way we can detect multiple imports of the same module
dedupStack.push(defType);
/** @type {?} */
let importTypesWithProviders;
try {
deepForEach(def.imports, (/**
* @param {?} imported
* @return {?}
*/
imported => {
if (this.processInjectorType(imported, parents, dedupStack)) {
if (importTypesWithProviders === undefined)
importTypesWithProviders = [];
// If the processed import is an injector type with providers, we store it in the
// list of import types with providers, so that we can process those afterwards.
importTypesWithProviders.push(imported);
}
}));
}
finally {
// Remove it from the parents set when finished.
ngDevMode && parents.pop();
}
// Imports which are declared with providers (TypeWithProviders) need to be processed
// after all imported modules are processed. This is similar to how View Engine
// processes/merges module imports in the metadata resolver. See: FW-1349.
if (importTypesWithProviders !== undefined) {
for (let i = 0; i < importTypesWithProviders.length; i++) {
const { ngModule, providers } = importTypesWithProviders[i];
deepForEach((/** @type {?} */ (providers)), (/**
* @param {?} provider
* @return {?}
*/
provider => this.processProvider(provider, ngModule, providers || EMPTY_ARRAY$2)));
}
}
}
// Track the InjectorType and add a provider for it. It's important that this is done after the
// def's imports.
this.injectorDefTypes.add(defType);
this.records.set(defType, makeRecord(def.factory, NOT_YET));
// Next, include providers listed on the definition itself.
/** @type {?} */
const defProviders = def.providers;
if (defProviders != null && !isDuplicate) {
/** @type {?} */
const injectorType = (/** @type {?} */ (defOrWrappedDef));
deepForEach(defProviders, (/**
* @param {?} provider
* @return {?}
*/
provider => this.processProvider(provider, injectorType, defProviders)));
}
return (ngModule !== undefined &&
((/** @type {?} */ (defOrWrappedDef))).providers !== undefined);
}
/**
* Process a `SingleProvider` and add it.
* @private
* @param {?} provider
* @param {?} ngModuleType
* @param {?} providers
* @return {?}
*/
processProvider(provider, ngModuleType, providers) {
// Determine the token from the provider. Either it's its own token, or has a {provide: ...}
// property.
provider = resolveForwardRef(provider);
/** @type {?} */
let token = isTypeProvider(provider) ? provider : resolveForwardRef(provider && provider.provide);
// Construct a `Record` for the provider.
/** @type {?} */
const record = providerToRecord(provider, ngModuleType, providers);
if (!isTypeProvider(provider) && provider.multi === true) {
// If the provider indicates that it's a multi-provider, process it specially.
// First check whether it's been defined already.
/** @type {?} */
let multiRecord = this.records.get(token);
if (multiRecord) {
// It has. Throw a nice error if
if (multiRecord.multi === undefined) {
throwMixedMultiProviderError();
}
}
else {
multiRecord = makeRecord(undefined, NOT_YET, true);
multiRecord.factory = (/**
* @return {?}
*/
() => injectArgs((/** @type {?} */ ((/** @type {?} */ (multiRecord)).multi))));
this.records.set(token, multiRecord);
}
token = provider;
(/** @type {?} */ (multiRecord.multi)).push(provider);
}
else {
/** @type {?} */
const existing = this.records.get(token);
if (existing && existing.multi !== undefined) {
throwMixedMultiProviderError();
}
}
this.records.set(token, record);
}
/**
* @private
* @template T
* @param {?} token
* @param {?} record
* @return {?}
*/
hydrate(token, record) {
if (record.value === CIRCULAR) {
throwCyclicDependencyError(stringify(token));
}
else if (record.value === NOT_YET) {
record.value = CIRCULAR;
record.value = (/** @type {?} */ (record.factory))();
}
if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) {
this.onDestroy.add(record.value);
}
return (/** @type {?} */ (record.value));
}
/**
* @private
* @param {?} def
* @return {?}
*/
injectableDefInScope(def) {
if (!def.providedIn) {
return false;
}
else if (typeof def.providedIn === 'string') {
return def.providedIn === 'any' || (def.providedIn === this.scope);
}
else {
return this.injectorDefTypes.has(def.providedIn);
}
}
}
if (false) {}
/**
* @param {?} token
* @return {?}
*/
function injectableDefOrInjectorDefFactory(token) {
// Most tokens will have an injectable def directly on them, which specifies a factory directly.
/** @type {?} */
const injectableDef = getInjectableDef(token);
/** @type {?} */
const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token);
if (factory !== null) {
return factory;
}
// If the token is an NgModule, it's also injectable but the factory is on its injector def
// (`ɵinj`)
/** @type {?} */
const injectorDef = getInjectorDef(token);
if (injectorDef !== null) {
return injectorDef.factory;
}
// InjectionTokens should have an injectable def (ɵprov) and thus should be handled above.
// If it's missing that, it's an error.
if (token instanceof InjectionToken) {
throw new Error(`Token ${stringify(token)} is missing a ɵprov definition.`);
}
// Undecorated types can sometimes be created if they have no constructor arguments.
if (token instanceof Function) {
return getUndecoratedInjectableFactory(token);
}
// There was no way to resolve a factory for this token.
throw new Error('unreachable');
}
/**
* @param {?} token
* @return {?}
*/
function getUndecoratedInjectableFactory(token) {
// If the token has parameters then it has dependencies that we cannot resolve implicitly.
/** @type {?} */
const paramLength = token.length;
if (paramLength > 0) {
/** @type {?} */
const args = newArray(paramLength, '?');
throw new Error(`Can't resolve all parameters for ${stringify(token)}: (${args.join(', ')}).`);
}
// The constructor function appears to have no parameters.
// This might be because it inherits from a super-class. In which case, use an injectable
// def from an ancestor if there is one.
// Otherwise this really is a simple class with no dependencies, so return a factory that
// just instantiates the zero-arg constructor.
/** @type {?} */
const inheritedInjectableDef = getInheritedInjectableDef(token);
if (inheritedInjectableDef !== null) {
return (/**
* @return {?}
*/
() => inheritedInjectableDef.factory((/** @type {?} */ (token))));
}
else {
return (/**
* @return {?}
*/
() => new ((/** @type {?} */ (token)))());
}
}
/**
* @param {?} provider
* @param {?} ngModuleType
* @param {?} providers
* @return {?}
*/
function providerToRecord(provider, ngModuleType, providers) {
if (isValueProvider(provider)) {
return makeRecord(undefined, provider.useValue);
}
else {
/** @type {?} */
const factory = providerToFactory(provider, ngModuleType, providers);
return makeRecord(factory, NOT_YET);
}
}
/**
* Converts a `SingleProvider` into a factory function.
*
* @param {?} provider provider to convert to factory
* @param {?=} ngModuleType
* @param {?=} providers
* @return {?}
*/
function providerToFactory(provider, ngModuleType, providers) {
/** @type {?} */
let factory = undefined;
if (isTypeProvider(provider)) {
/** @type {?} */
const unwrappedProvider = resolveForwardRef(provider);
return getFactoryDef(unwrappedProvider) || injectableDefOrInjectorDefFactory(unwrappedProvider);
}
else {
if (isValueProvider(provider)) {
factory = (/**
* @return {?}
*/
() => resolveForwardRef(provider.useValue));
}
else if (isFactoryProvider(provider)) {
factory = (/**
* @return {?}
*/
() => provider.useFactory(...injectArgs(provider.deps || [])));
}
else if (isExistingProvider(provider)) {
factory = (/**
* @return {?}
*/
() => ɵɵinject(resolveForwardRef(provider.useExisting)));
}
else {
/** @type {?} */
const classRef = resolveForwardRef(provider &&
(((/** @type {?} */ (provider))).useClass || provider.provide));
if (!classRef) {
throwInvalidProviderError(ngModuleType, providers, provider);
}
if (hasDeps(provider)) {
factory = (/**
* @return {?}
*/
() => new (classRef)(...injectArgs(provider.deps)));
}
else {
return getFactoryDef(classRef) || injectableDefOrInjectorDefFactory(classRef);
}
}
}
return factory;
}
/**
* @template T
* @param {?} factory
* @param {?} value
* @param {?=} multi
* @return {?}
*/
function makeRecord(factory, value, multi = false) {
return {
factory: factory,
value: value,
multi: multi ? [] : undefined,
};
}
/**
* @param {?} value
* @return {?}
*/
function isValueProvider(value) {
return value !== null && typeof value == 'object' && USE_VALUE in value;
}
/**
* @param {?} value
* @return {?}
*/
function isExistingProvider(value) {
return !!(value && ((/** @type {?} */ (value))).useExisting);
}
/**
* @param {?} value
* @return {?}
*/
function isFactoryProvider(value) {
return !!(value && ((/** @type {?} */ (value))).useFactory);
}
/**
* @param {?} value
* @return {?}
*/
function isTypeProvider(value) {
return typeof value === 'function';
}
/**
* @param {?} value
* @return {?}
*/
function isClassProvider(value) {
return !!((/** @type {?} */ (value))).useClass;
}
/**
* @param {?} value
* @return {?}
*/
function hasDeps(value) {
return !!((/** @type {?} */ (value))).deps;
}
/**
* @param {?} value
* @return {?}
*/
function hasOnDestroy(value) {
return value !== null && typeof value === 'object' &&
typeof ((/** @type {?} */ (value))).ngOnDestroy === 'function';
}
/**
* @param {?} value
* @return {?}
*/
function couldBeInjectableType(value) {
return (typeof value === 'function') ||
(typeof value === 'object' && value instanceof InjectionToken);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/injector.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} providers
* @param {?} parent
* @param {?} name
* @return {?}
*/
function INJECTOR_IMPL__PRE_R3__(providers, parent, name) {
return new StaticInjector(providers, parent, name);
}
/**
* @param {?} providers
* @param {?} parent
* @param {?} name
* @return {?}
*/
function INJECTOR_IMPL__POST_R3__(providers, parent, name) {
return createInjector({ name: name }, parent, providers, name);
}
/** @type {?} */
const INJECTOR_IMPL = INJECTOR_IMPL__POST_R3__;
/**
* Concrete injectors implement this interface. Injectors are configured
* with [providers](guide/glossary#provider) that associate
* dependencies of various types with [injection tokens](guide/glossary#di-token).
*
* @see ["DI Providers"](guide/dependency-injection-providers).
* @see `StaticProvider`
*
* \@usageNotes
*
* The following example creates a service injector instance.
*
* {\@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
*
* ### Usage example
*
* {\@example core/di/ts/injector_spec.ts region='Injector'}
*
* `Injector` returns itself when given `Injector` as a token:
*
* {\@example core/di/ts/injector_spec.ts region='injectInjector'}
*
* \@publicApi
* @abstract
*/
class Injector {
/**
* @param {?} options
* @param {?=} parent
* @return {?}
*/
static create(options, parent) {
if (Array.isArray(options)) {
return INJECTOR_IMPL(options, parent, '');
}
else {
return INJECTOR_IMPL(options.providers, options.parent, options.name || '');
}
}
}
Injector.THROW_IF_NOT_FOUND = THROW_IF_NOT_FOUND;
Injector.NULL = new NullInjector();
/** @nocollapse */
Injector.ɵprov = ɵɵdefineInjectable({
token: Injector,
providedIn: (/** @type {?} */ ('any')),
factory: (/**
* @return {?}
*/
() => ɵɵinject(INJECTOR)),
});
/**
* \@internal
* @nocollapse
*/
Injector.__NG_ELEMENT_ID__ = -1;
if (false) {}
/** @type {?} */
const IDENT = (/**
* @template T
* @param {?} value
* @return {?}
*/
function (value) {
return value;
});
const ɵ0$9 = IDENT;
/** @type {?} */
const EMPTY = (/** @type {?} */ ([]));
/** @type {?} */
const CIRCULAR$1 = IDENT;
/** @type {?} */
const MULTI_PROVIDER_FN = (/**
* @return {?}
*/
function () {
return Array.prototype.slice.call(arguments);
});
const ɵ1$1 = MULTI_PROVIDER_FN;
/** @enum {number} */
const OptionFlags = {
Optional: 1,
CheckSelf: 2,
CheckParent: 4,
Default: 6,
};
/** @type {?} */
const NO_NEW_LINE$1 = 'ɵ';
class StaticInjector {
/**
* @param {?} providers
* @param {?=} parent
* @param {?=} source
*/
constructor(providers, parent = Injector.NULL, source = null) {
this.parent = parent;
this.source = source;
/** @type {?} */
const records = this._records = new Map();
records.set(Injector, (/** @type {?} */ ({ token: Injector, fn: IDENT, deps: EMPTY, value: this, useNew: false })));
records.set(INJECTOR, (/** @type {?} */ ({ token: INJECTOR, fn: IDENT, deps: EMPTY, value: this, useNew: false })));
this.scope = recursivelyProcessProviders(records, providers);
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @param {?=} flags
* @return {?}
*/
get(token, notFoundValue, flags = InjectFlags.Default) {
/** @type {?} */
const records = this._records;
/** @type {?} */
let record = records.get(token);
if (record === undefined) {
// This means we have never seen this record, see if it is tree shakable provider.
/** @type {?} */
const injectableDef = getInjectableDef(token);
if (injectableDef) {
/** @type {?} */
const providedIn = injectableDef && injectableDef.providedIn;
if (providedIn === 'any' || providedIn != null && providedIn === this.scope) {
records.set(token, record = resolveProvider({ provide: token, useFactory: injectableDef.factory, deps: EMPTY }));
}
}
if (record === undefined) {
// Set record to null to make sure that we don't go through expensive lookup above again.
records.set(token, null);
}
}
/** @type {?} */
let lastInjector = setCurrentInjector(this);
try {
return tryResolveToken(token, record, records, this.parent, notFoundValue, flags);
}
catch (e) {
return catchInjectorError(e, token, 'StaticInjectorError', this.source);
}
finally {
setCurrentInjector(lastInjector);
}
}
/**
* @return {?}
*/
toString() {
/** @type {?} */
const tokens = (/** @type {?} */ ([]));
/** @type {?} */
const records = this._records;
records.forEach((/**
* @param {?} v
* @param {?} token
* @return {?}
*/
(v, token) => tokens.push(stringify(token))));
return `StaticInjector[${tokens.join(', ')}]`;
}
}
if (false) {}
/**
* @record
*/
function Record$1() { }
if (false) {}
/**
* @record
*/
function DependencyRecord() { }
if (false) {}
/**
* @param {?} provider
* @return {?}
*/
function resolveProvider(provider) {
/** @type {?} */
const deps = computeDeps(provider);
/** @type {?} */
let fn = IDENT;
/** @type {?} */
let value = EMPTY;
/** @type {?} */
let useNew = false;
/** @type {?} */
let provide = resolveForwardRef(provider.provide);
if (USE_VALUE in provider) {
// We need to use USE_VALUE in provider since provider.useValue could be defined as undefined.
value = ((/** @type {?} */ (provider))).useValue;
}
else if (((/** @type {?} */ (provider))).useFactory) {
fn = ((/** @type {?} */ (provider))).useFactory;
}
else if (((/** @type {?} */ (provider))).useExisting) {
// Just use IDENT
}
else if (((/** @type {?} */ (provider))).useClass) {
useNew = true;
fn = resolveForwardRef(((/** @type {?} */ (provider))).useClass);
}
else if (typeof provide == 'function') {
useNew = true;
fn = provide;
}
else {
throw staticError('StaticProvider does not have [useValue|useFactory|useExisting|useClass] or [provide] is not newable', provider);
}
return { deps, fn, useNew, value };
}
/**
* @param {?} token
* @return {?}
*/
function multiProviderMixError(token) {
return staticError('Cannot mix multi providers and regular providers', token);
}
/**
* @param {?} records
* @param {?} provider
* @return {?}
*/
function recursivelyProcessProviders(records, provider) {
/** @type {?} */
let scope = null;
if (provider) {
provider = resolveForwardRef(provider);
if (Array.isArray(provider)) {
// if we have an array recurse into the array
for (let i = 0; i < provider.length; i++) {
scope = recursivelyProcessProviders(records, provider[i]) || scope;
}
}
else if (typeof provider === 'function') {
// Functions were supported in ReflectiveInjector, but are not here. For safety give useful
// error messages
throw staticError('Function/Class not supported', provider);
}
else if (provider && typeof provider === 'object' && provider.provide) {
// At this point we have what looks like a provider: {provide: ?, ....}
/** @type {?} */
let token = resolveForwardRef(provider.provide);
/** @type {?} */
const resolvedProvider = resolveProvider(provider);
if (provider.multi === true) {
// This is a multi provider.
/** @type {?} */
let multiProvider = records.get(token);
if (multiProvider) {
if (multiProvider.fn !== MULTI_PROVIDER_FN) {
throw multiProviderMixError(token);
}
}
else {
// Create a placeholder factory which will look up the constituents of the multi provider.
records.set(token, multiProvider = (/** @type {?} */ ({
token: provider.provide,
deps: [],
useNew: false,
fn: MULTI_PROVIDER_FN,
value: EMPTY
})));
}
// Treat the provider as the token.
token = provider;
multiProvider.deps.push({ token, options: 6 /* Default */ });
}
/** @type {?} */
const record = records.get(token);
if (record && record.fn == MULTI_PROVIDER_FN) {
throw multiProviderMixError(token);
}
if (token === INJECTOR_SCOPE) {
scope = resolvedProvider.value;
}
records.set(token, resolvedProvider);
}
else {
throw staticError('Unexpected provider', provider);
}
}
return scope;
}
/**
* @param {?} token
* @param {?} record
* @param {?} records
* @param {?} parent
* @param {?} notFoundValue
* @param {?} flags
* @return {?}
*/
function tryResolveToken(token, record, records, parent, notFoundValue, flags) {
try {
return resolveToken(token, record, records, parent, notFoundValue, flags);
}
catch (e) {
// ensure that 'e' is of type Error.
if (!(e instanceof Error)) {
e = new Error(e);
}
/** @type {?} */
const path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || [];
path.unshift(token);
if (record && record.value == CIRCULAR$1) {
// Reset the Circular flag.
record.value = EMPTY;
}
throw e;
}
}
/**
* @param {?} token
* @param {?} record
* @param {?} records
* @param {?} parent
* @param {?} notFoundValue
* @param {?} flags
* @return {?}
*/
function resolveToken(token, record, records, parent, notFoundValue, flags) {
/** @type {?} */
let value;
if (record && !(flags & InjectFlags.SkipSelf)) {
// If we don't have a record, this implies that we don't own the provider hence don't know how
// to resolve it.
value = record.value;
if (value == CIRCULAR$1) {
throw Error(NO_NEW_LINE$1 + 'Circular dependency');
}
else if (value === EMPTY) {
record.value = CIRCULAR$1;
/** @type {?} */
let obj = undefined;
/** @type {?} */
let useNew = record.useNew;
/** @type {?} */
let fn = record.fn;
/** @type {?} */
let depRecords = record.deps;
/** @type {?} */
let deps = EMPTY;
if (depRecords.length) {
deps = [];
for (let i = 0; i < depRecords.length; i++) {
/** @type {?} */
const depRecord = depRecords[i];
/** @type {?} */
const options = depRecord.options;
/** @type {?} */
const childRecord = options & 2 /* CheckSelf */ ? records.get(depRecord.token) : undefined;
deps.push(tryResolveToken(
// Current Token to resolve
depRecord.token,
// A record which describes how to resolve the token.
// If undefined, this means we don't have such a record
childRecord,
// Other records we know about.
records,
// If we don't know how to resolve dependency and we should not check parent for it,
// than pass in Null injector.
!childRecord && !(options & 4 /* CheckParent */) ? Injector.NULL : parent, options & 1 /* Optional */ ? null : Injector.THROW_IF_NOT_FOUND, InjectFlags.Default));
}
}
record.value = value = useNew ? new ((/** @type {?} */ (fn)))(...deps) : fn.apply(obj, deps);
}
}
else if (!(flags & InjectFlags.Self)) {
value = parent.get(token, notFoundValue, InjectFlags.Default);
}
else if (!(flags & InjectFlags.Optional)) {
value = Injector.NULL.get(token, notFoundValue);
}
else {
value = Injector.NULL.get(token, typeof notFoundValue !== 'undefined' ? notFoundValue : null);
}
return value;
}
/**
* @param {?} provider
* @return {?}
*/
function computeDeps(provider) {
/** @type {?} */
let deps = EMPTY;
/** @type {?} */
const providerDeps = ((/** @type {?} */ (provider))).deps;
if (providerDeps && providerDeps.length) {
deps = [];
for (let i = 0; i < providerDeps.length; i++) {
/** @type {?} */
let options = 6 /* Default */;
/** @type {?} */
let token = resolveForwardRef(providerDeps[i]);
if (Array.isArray(token)) {
for (let j = 0, annotations = token; j < annotations.length; j++) {
/** @type {?} */
const annotation = annotations[j];
if (annotation instanceof Optional || annotation == Optional) {
options = options | 1 /* Optional */;
}
else if (annotation instanceof SkipSelf || annotation == SkipSelf) {
options = options & ~2 /* CheckSelf */;
}
else if (annotation instanceof Self || annotation == Self) {
options = options & ~4 /* CheckParent */;
}
else if (annotation instanceof Inject) {
token = ((/** @type {?} */ (annotation))).token;
}
else {
token = resolveForwardRef(annotation);
}
}
}
deps.push({ token, options });
}
}
else if (((/** @type {?} */ (provider))).useExisting) {
/** @type {?} */
const token = resolveForwardRef(((/** @type {?} */ (provider))).useExisting);
deps = [{ token, options: 6 /* Default */ }];
}
else if (!providerDeps && !(USE_VALUE in provider)) {
// useValue & useExisting are the only ones which are exempt from deps all others need it.
throw staticError('\'deps\' required', provider);
}
return deps;
}
/**
* @param {?} text
* @param {?} obj
* @return {?}
*/
function staticError(text, obj) {
return new Error(formatError(text, obj, 'StaticInjectorError'));
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/reflective_errors.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} keys
* @return {?}
*/
function findFirstClosedCycle(keys) {
/** @type {?} */
const res = [];
for (let i = 0; i < keys.length; ++i) {
if (res.indexOf(keys[i]) > -1) {
res.push(keys[i]);
return res;
}
res.push(keys[i]);
}
return res;
}
/**
* @param {?} keys
* @return {?}
*/
function constructResolvingPath(keys) {
if (keys.length > 1) {
/** @type {?} */
const reversed = findFirstClosedCycle(keys.slice().reverse());
/** @type {?} */
const tokenStrs = reversed.map((/**
* @param {?} k
* @return {?}
*/
k => stringify(k.token)));
return ' (' + tokenStrs.join(' -> ') + ')';
}
return '';
}
/**
* @record
*/
function InjectionError() { }
if (false) {}
/**
* @param {?} injector
* @param {?} key
* @param {?} constructResolvingMessage
* @param {?=} originalError
* @return {?}
*/
function injectionError(injector, key, constructResolvingMessage, originalError) {
/** @type {?} */
const keys = [key];
/** @type {?} */
const errMsg = constructResolvingMessage(keys);
/** @type {?} */
const error = (/** @type {?} */ ((originalError ? wrappedError(errMsg, originalError) : Error(errMsg))));
error.addKey = addKey;
error.keys = keys;
error.injectors = [injector];
error.constructResolvingMessage = constructResolvingMessage;
((/** @type {?} */ (error)))[ERROR_ORIGINAL_ERROR] = originalError;
return error;
}
/**
* @this {?}
* @param {?} injector
* @param {?} key
* @return {?}
*/
function addKey(injector, key) {
this.injectors.push(injector);
this.keys.push(key);
// Note: This updated message won't be reflected in the `.stack` property
this.message = this.constructResolvingMessage(this.keys);
}
/**
* Thrown when trying to retrieve a dependency by key from {\@link Injector}, but the
* {\@link Injector} does not have a {\@link Provider} for the given key.
*
* \@usageNotes
* ### Example
*
* ```typescript
* class A {
* constructor(b:B) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
* @param {?} injector
* @param {?} key
* @return {?}
*/
function noProviderError(injector, key) {
return injectionError(injector, key, (/**
* @param {?} keys
* @return {?}
*/
function (keys) {
/** @type {?} */
const first = stringify(keys[0].token);
return `No provider for ${first}!${constructResolvingPath(keys)}`;
}));
}
/**
* Thrown when dependencies form a cycle.
*
* \@usageNotes
* ### Example
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* {provide: "one", useFactory: (two) => "two", deps: [[new Inject("two")]]},
* {provide: "two", useFactory: (one) => "one", deps: [[new Inject("one")]]}
* ]);
*
* expect(() => injector.get("one")).toThrowError();
* ```
*
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
* @param {?} injector
* @param {?} key
* @return {?}
*/
function cyclicDependencyError(injector, key) {
return injectionError(injector, key, (/**
* @param {?} keys
* @return {?}
*/
function (keys) {
return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`;
}));
}
/**
* Thrown when a constructing type returns with an Error.
*
* The `InstantiationError` class contains the original error plus the dependency graph which caused
* this object to be instantiated.
*
* \@usageNotes
* ### Example
*
* ```typescript
* class A {
* constructor() {
* throw new Error('message');
* }
* }
*
* var injector = Injector.resolveAndCreate([A]);
* try {
* injector.get(A);
* } catch (e) {
* expect(e instanceof InstantiationError).toBe(true);
* expect(e.originalException.message).toEqual("message");
* expect(e.originalStack).toBeDefined();
* }
* ```
* @param {?} injector
* @param {?} originalException
* @param {?} originalStack
* @param {?} key
* @return {?}
*/
function instantiationError(injector, originalException, originalStack, key) {
return injectionError(injector, key, (/**
* @param {?} keys
* @return {?}
*/
function (keys) {
/** @type {?} */
const first = stringify(keys[0].token);
return `${originalException.message}: Error during instantiation of ${first}!${constructResolvingPath(keys)}.`;
}), originalException);
}
/**
* Thrown when an object other then {\@link Provider} (or `Type`) is passed to {\@link Injector}
* creation.
*
* \@usageNotes
* ### Example
*
* ```typescript
* expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
* ```
* @param {?} provider
* @return {?}
*/
function invalidProviderError(provider) {
return Error(`Invalid provider - only instances of Provider and Type are allowed, got: ${provider}`);
}
/**
* Thrown when the class has no annotation information.
*
* Lack of annotation information prevents the {\@link Injector} from determining which dependencies
* need to be injected into the constructor.
*
* \@usageNotes
* ### Example
*
* ```typescript
* class A {
* constructor(b) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*
* This error is also thrown when the class not marked with {\@link Injectable} has parameter types.
*
* ```typescript
* class B {}
*
* class A {
* constructor(b:B) {} // no information about the parameter types of A is available at runtime.
* }
*
* expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
* ```
*
* @param {?} typeOrFunc
* @param {?} params
* @return {?}
*/
function noAnnotationError(typeOrFunc, params) {
/** @type {?} */
const signature = [];
for (let i = 0, ii = params.length; i < ii; i++) {
/** @type {?} */
const parameter = params[i];
if (!parameter || parameter.length == 0) {
signature.push('?');
}
else {
signature.push(parameter.map(stringify).join(' '));
}
}
return Error('Cannot resolve all parameters for \'' + stringify(typeOrFunc) + '\'(' +
signature.join(', ') + '). ' +
'Make sure that all the parameters are decorated with Inject or have valid type annotations and that \'' +
stringify(typeOrFunc) + '\' is decorated with Injectable.');
}
/**
* Thrown when getting an object by index.
*
* \@usageNotes
* ### Example
*
* ```typescript
* class A {}
*
* var injector = Injector.resolveAndCreate([A]);
*
* expect(() => injector.getAt(100)).toThrowError();
* ```
*
* @param {?} index
* @return {?}
*/
function outOfBoundsError(index) {
return Error(`Index ${index} is out-of-bounds.`);
}
// TODO: add a working example after alpha38 is released
/**
* Thrown when a multi provider and a regular provider are bound to the same token.
*
* \@usageNotes
* ### Example
*
* ```typescript
* expect(() => Injector.resolveAndCreate([
* { provide: "Strings", useValue: "string1", multi: true},
* { provide: "Strings", useValue: "string2", multi: false}
* ])).toThrowError();
* ```
* @param {?} provider1
* @param {?} provider2
* @return {?}
*/
function mixingMultiProvidersWithRegularProvidersError(provider1, provider2) {
return Error(`Cannot mix multi providers and regular providers, got: ${provider1} ${provider2}`);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/reflective_key.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A unique object used for retrieving items from the {\@link ReflectiveInjector}.
*
* Keys have:
* - a system-wide unique `id`.
* - a `token`.
*
* `Key` is used internally by {\@link ReflectiveInjector} because its system-wide unique `id` allows
* the
* injector to store created objects in a more efficient way.
*
* `Key` should not be created directly. {\@link ReflectiveInjector} creates keys automatically when
* resolving
* providers.
*
* @deprecated No replacement
* \@publicApi
*/
class ReflectiveKey {
/**
* Private
* @param {?} token
* @param {?} id
*/
constructor(token, id) {
this.token = token;
this.id = id;
if (!token) {
throw new Error('Token must be defined!');
}
this.displayName = stringify(this.token);
}
/**
* Retrieves a `Key` for a token.
* @param {?} token
* @return {?}
*/
static get(token) {
return _globalKeyRegistry.get(resolveForwardRef(token));
}
/**
* @return {?} the number of keys registered in the system.
*/
static get numberOfKeys() {
return _globalKeyRegistry.numberOfKeys;
}
}
if (false) {}
class KeyRegistry {
constructor() {
this._allKeys = new Map();
}
/**
* @param {?} token
* @return {?}
*/
get(token) {
if (token instanceof ReflectiveKey)
return token;
if (this._allKeys.has(token)) {
return (/** @type {?} */ (this._allKeys.get(token)));
}
/** @type {?} */
const newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys);
this._allKeys.set(token, newKey);
return newKey;
}
/**
* @return {?}
*/
get numberOfKeys() {
return this._allKeys.size;
}
}
if (false) {}
/** @type {?} */
const _globalKeyRegistry = new KeyRegistry();
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Provides access to reflection data about symbols. Used internally by Angular
* to power dependency injection and compilation.
*/
class Reflector {
constructor(reflectionCapabilities) {
this.reflectionCapabilities = reflectionCapabilities;
}
updateCapabilities(caps) {
this.reflectionCapabilities = caps;
}
factory(type) {
return this.reflectionCapabilities.factory(type);
}
parameters(typeOrFunc) {
return this.reflectionCapabilities.parameters(typeOrFunc);
}
annotations(typeOrFunc) {
return this.reflectionCapabilities.annotations(typeOrFunc);
}
propMetadata(typeOrFunc) {
return this.reflectionCapabilities.propMetadata(typeOrFunc);
}
hasLifecycleHook(type, lcProperty) {
return this.reflectionCapabilities.hasLifecycleHook(type, lcProperty);
}
getter(name) {
return this.reflectionCapabilities.getter(name);
}
setter(name) {
return this.reflectionCapabilities.setter(name);
}
method(name) {
return this.reflectionCapabilities.method(name);
}
importUri(type) {
return this.reflectionCapabilities.importUri(type);
}
resourceUri(type) {
return this.reflectionCapabilities.resourceUri(type);
}
resolveIdentifier(name, moduleUrl, members, runtime) {
return this.reflectionCapabilities.resolveIdentifier(name, moduleUrl, members, runtime);
}
resolveEnum(identifier, name) {
return this.reflectionCapabilities.resolveEnum(identifier, name);
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* The {@link Reflector} used internally in Angular to access metadata
* about symbols.
*/
const reflector = new Reflector(new ReflectionCapabilities());
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/reflective_provider.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @record
*/
function NormalizedProvider() { }
/**
* `Dependency` is used by the framework to extend DI.
* This is internal to Angular and should not be used directly.
*/
class ReflectiveDependency {
/**
* @param {?} key
* @param {?} optional
* @param {?} visibility
*/
constructor(key, optional, visibility) {
this.key = key;
this.optional = optional;
this.visibility = visibility;
}
/**
* @param {?} key
* @return {?}
*/
static fromKey(key) {
return new ReflectiveDependency(key, false, null);
}
}
if (false) {}
/** @type {?} */
const _EMPTY_LIST = [];
/**
* An internal resolved representation of a `Provider` used by the `Injector`.
*
* \@usageNotes
* This is usually created automatically by `Injector.resolveAndCreate`.
*
* It can be created manually, as follows:
*
* ### Example
*
* ```typescript
* var resolvedProviders = Injector.resolve([{ provide: 'message', useValue: 'Hello' }]);
* var injector = Injector.fromResolvedProviders(resolvedProviders);
*
* expect(injector.get('message')).toEqual('Hello');
* ```
*
* \@publicApi
* @record
*/
function ResolvedReflectiveProvider() { }
if (false) {}
class ResolvedReflectiveProvider_ {
/**
* @param {?} key
* @param {?} resolvedFactories
* @param {?} multiProvider
*/
constructor(key, resolvedFactories, multiProvider) {
this.key = key;
this.resolvedFactories = resolvedFactories;
this.multiProvider = multiProvider;
this.resolvedFactory = this.resolvedFactories[0];
}
}
if (false) {}
/**
* An internal resolved representation of a factory function created by resolving `Provider`.
* \@publicApi
*/
class ResolvedReflectiveFactory {
/**
* @param {?} factory
* @param {?} dependencies
*/
constructor(factory, dependencies) {
this.factory = factory;
this.dependencies = dependencies;
}
}
if (false) {}
/**
* Resolve a single provider.
* @param {?} provider
* @return {?}
*/
function resolveReflectiveFactory(provider) {
/** @type {?} */
let factoryFn;
/** @type {?} */
let resolvedDeps;
if (provider.useClass) {
/** @type {?} */
const useClass = resolveForwardRef(provider.useClass);
factoryFn = reflector.factory(useClass);
resolvedDeps = _dependenciesFor(useClass);
}
else if (provider.useExisting) {
factoryFn = (/**
* @param {?} aliasInstance
* @return {?}
*/
(aliasInstance) => aliasInstance);
resolvedDeps = [ReflectiveDependency.fromKey(ReflectiveKey.get(provider.useExisting))];
}
else if (provider.useFactory) {
factoryFn = provider.useFactory;
resolvedDeps = constructDependencies(provider.useFactory, provider.deps);
}
else {
factoryFn = (/**
* @return {?}
*/
() => provider.useValue);
resolvedDeps = _EMPTY_LIST;
}
return new ResolvedReflectiveFactory(factoryFn, resolvedDeps);
}
/**
* Converts the `Provider` into `ResolvedProvider`.
*
* `Injector` internally only uses `ResolvedProvider`, `Provider` contains convenience provider
* syntax.
* @param {?} provider
* @return {?}
*/
function resolveReflectiveProvider(provider) {
return new ResolvedReflectiveProvider_(ReflectiveKey.get(provider.provide), [resolveReflectiveFactory(provider)], provider.multi || false);
}
/**
* Resolve a list of Providers.
* @param {?} providers
* @return {?}
*/
function resolveReflectiveProviders(providers) {
/** @type {?} */
const normalized = _normalizeProviders(providers, []);
/** @type {?} */
const resolved = normalized.map(resolveReflectiveProvider);
/** @type {?} */
const resolvedProviderMap = mergeResolvedReflectiveProviders(resolved, new Map());
return Array.from(resolvedProviderMap.values());
}
/**
* Merges a list of ResolvedProviders into a list where each key is contained exactly once and
* multi providers have been merged.
* @param {?} providers
* @param {?} normalizedProvidersMap
* @return {?}
*/
function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) {
for (let i = 0; i < providers.length; i++) {
/** @type {?} */
const provider = providers[i];
/** @type {?} */
const existing = normalizedProvidersMap.get(provider.key.id);
if (existing) {
if (provider.multiProvider !== existing.multiProvider) {
throw mixingMultiProvidersWithRegularProvidersError(existing, provider);
}
if (provider.multiProvider) {
for (let j = 0; j < provider.resolvedFactories.length; j++) {
existing.resolvedFactories.push(provider.resolvedFactories[j]);
}
}
else {
normalizedProvidersMap.set(provider.key.id, provider);
}
}
else {
/** @type {?} */
let resolvedProvider;
if (provider.multiProvider) {
resolvedProvider = new ResolvedReflectiveProvider_(provider.key, provider.resolvedFactories.slice(), provider.multiProvider);
}
else {
resolvedProvider = provider;
}
normalizedProvidersMap.set(provider.key.id, resolvedProvider);
}
}
return normalizedProvidersMap;
}
/**
* @param {?} providers
* @param {?} res
* @return {?}
*/
function _normalizeProviders(providers, res) {
providers.forEach((/**
* @param {?} b
* @return {?}
*/
b => {
if (b instanceof Type) {
res.push((/** @type {?} */ ({ provide: b, useClass: b })));
}
else if (b && typeof b == 'object' && ((/** @type {?} */ (b))).provide !== undefined) {
res.push((/** @type {?} */ (b)));
}
else if (Array.isArray(b)) {
_normalizeProviders(b, res);
}
else {
throw invalidProviderError(b);
}
}));
return res;
}
/**
* @param {?} typeOrFunc
* @param {?=} dependencies
* @return {?}
*/
function constructDependencies(typeOrFunc, dependencies) {
if (!dependencies) {
return _dependenciesFor(typeOrFunc);
}
else {
/** @type {?} */
const params = dependencies.map((/**
* @param {?} t
* @return {?}
*/
t => [t]));
return dependencies.map((/**
* @param {?} t
* @return {?}
*/
t => _extractToken(typeOrFunc, t, params)));
}
}
/**
* @param {?} typeOrFunc
* @return {?}
*/
function _dependenciesFor(typeOrFunc) {
/** @type {?} */
const params = reflector.parameters(typeOrFunc);
if (!params)
return [];
if (params.some((/**
* @param {?} p
* @return {?}
*/
p => p == null))) {
throw noAnnotationError(typeOrFunc, params);
}
return params.map((/**
* @param {?} p
* @return {?}
*/
p => _extractToken(typeOrFunc, p, params)));
}
/**
* @param {?} typeOrFunc
* @param {?} metadata
* @param {?} params
* @return {?}
*/
function _extractToken(typeOrFunc, metadata, params) {
/** @type {?} */
let token = null;
/** @type {?} */
let optional = false;
if (!Array.isArray(metadata)) {
if (metadata instanceof Inject) {
return _createDependency(metadata.token, optional, null);
}
else {
return _createDependency(metadata, optional, null);
}
}
/** @type {?} */
let visibility = null;
for (let i = 0; i < metadata.length; ++i) {
/** @type {?} */
const paramMetadata = metadata[i];
if (paramMetadata instanceof Type) {
token = paramMetadata;
}
else if (paramMetadata instanceof Inject) {
token = paramMetadata.token;
}
else if (paramMetadata instanceof Optional) {
optional = true;
}
else if (paramMetadata instanceof Self || paramMetadata instanceof SkipSelf) {
visibility = paramMetadata;
}
else if (paramMetadata instanceof InjectionToken) {
token = paramMetadata;
}
}
token = resolveForwardRef(token);
if (token != null) {
return _createDependency(token, optional, visibility);
}
else {
throw noAnnotationError(typeOrFunc, params);
}
}
/**
* @param {?} token
* @param {?} optional
* @param {?} visibility
* @return {?}
*/
function _createDependency(token, optional, visibility) {
return new ReflectiveDependency(ReflectiveKey.get(token), optional, visibility);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/reflective_injector.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// Threshold for the dynamic version
/** @type {?} */
const UNDEFINED = {};
/**
* A ReflectiveDependency injection container used for instantiating objects and resolving
* dependencies.
*
* An `Injector` is a replacement for a `new` operator, which can automatically resolve the
* constructor dependencies.
*
* In typical use, application code asks for the dependencies in the constructor and they are
* resolved by the `Injector`.
*
* \@usageNotes
* ### Example
*
* The following example creates an `Injector` configured to create `Engine` and `Car`.
*
* ```typescript
* \@Injectable()
* class Engine {
* }
*
* \@Injectable()
* class Car {
* constructor(public engine:Engine) {}
* }
*
* var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
* var car = injector.get(Car);
* expect(car instanceof Car).toBe(true);
* expect(car.engine instanceof Engine).toBe(true);
* ```
*
* Notice, we don't use the `new` operator because we explicitly want to have the `Injector`
* resolve all of the object's dependencies automatically.
*
* @deprecated from v5 - slow and brings in a lot of code, Use `Injector.create` instead.
* \@publicApi
* @abstract
*/
class ReflectiveInjector {
/**
* Turns an array of provider definitions into an array of resolved providers.
*
* A resolution is a process of flattening multiple nested arrays and converting individual
* providers into an array of `ResolvedReflectiveProvider`s.
*
* \@usageNotes
* ### Example
*
* ```typescript
* \@Injectable()
* class Engine {
* }
* /
* class Car {
* constructor(public engine:Engine) {}
* }
*
* var providers = ReflectiveInjector.resolve([Car, [[Engine]]]);
*
* expect(providers.length).toEqual(2);
*
* expect(providers[0] instanceof ResolvedReflectiveProvider).toBe(true);
* expect(providers[0].key.displayName).toBe("Car");
* expect(providers[0].dependencies.length).toEqual(1);
* expect(providers[0].factory).toBeDefined();
*
* expect(providers[1].key.displayName).toBe("Engine");
* });
* ```
*
* @param {?} providers
* @return {?}
*/
static resolve(providers) {
return resolveReflectiveProviders(providers);
}
/**
* Resolves an array of providers and creates an injector from those providers.
*
* The passed-in providers can be an array of `Type`, `Provider`,
* or a recursive array of more providers.
*
* \@usageNotes
* ### Example
*
* ```typescript
* \@Injectable()
* class Engine {
* }
* /
* class Car {
* constructor(public engine:Engine) {}
* }
*
* var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
* expect(injector.get(Car) instanceof Car).toBe(true);
* ```
* @param {?} providers
* @param {?=} parent
* @return {?}
*/
static resolveAndCreate(providers, parent) {
/** @type {?} */
const ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
return ReflectiveInjector.fromResolvedProviders(ResolvedReflectiveProviders, parent);
}
/**
* Creates an injector from previously resolved providers.
*
* This API is the recommended way to construct injectors in performance-sensitive parts.
*
* \@usageNotes
* ### Example
*
* ```typescript
* \@Injectable()
* class Engine {
* }
* /
* class Car {
* constructor(public engine:Engine) {}
* }
*
* var providers = ReflectiveInjector.resolve([Car, Engine]);
* var injector = ReflectiveInjector.fromResolvedProviders(providers);
* expect(injector.get(Car) instanceof Car).toBe(true);
* ```
* @param {?} providers
* @param {?=} parent
* @return {?}
*/
static fromResolvedProviders(providers, parent) {
return new ReflectiveInjector_(providers, parent);
}
}
if (false) {}
class ReflectiveInjector_ {
/**
* Private
* @param {?} _providers
* @param {?=} _parent
*/
constructor(_providers, _parent) {
/**
* \@internal
*/
this._constructionCounter = 0;
this._providers = _providers;
this.parent = _parent || null;
/** @type {?} */
const len = _providers.length;
this.keyIds = [];
this.objs = [];
for (let i = 0; i < len; i++) {
this.keyIds[i] = _providers[i].key.id;
this.objs[i] = UNDEFINED;
}
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
get(token, notFoundValue = THROW_IF_NOT_FOUND) {
return this._getByKey(ReflectiveKey.get(token), null, notFoundValue);
}
/**
* @param {?} providers
* @return {?}
*/
resolveAndCreateChild(providers) {
/** @type {?} */
const ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
return this.createChildFromResolved(ResolvedReflectiveProviders);
}
/**
* @param {?} providers
* @return {?}
*/
createChildFromResolved(providers) {
/** @type {?} */
const inj = new ReflectiveInjector_(providers);
((/** @type {?} */ (inj))).parent = this;
return inj;
}
/**
* @param {?} provider
* @return {?}
*/
resolveAndInstantiate(provider) {
return this.instantiateResolved(ReflectiveInjector.resolve([provider])[0]);
}
/**
* @param {?} provider
* @return {?}
*/
instantiateResolved(provider) {
return this._instantiateProvider(provider);
}
/**
* @param {?} index
* @return {?}
*/
getProviderAtIndex(index) {
if (index < 0 || index >= this._providers.length) {
throw outOfBoundsError(index);
}
return this._providers[index];
}
/**
* \@internal
* @param {?} provider
* @return {?}
*/
_new(provider) {
if (this._constructionCounter++ > this._getMaxNumberOfObjects()) {
throw cyclicDependencyError(this, provider.key);
}
return this._instantiateProvider(provider);
}
/**
* @private
* @return {?}
*/
_getMaxNumberOfObjects() {
return this.objs.length;
}
/**
* @private
* @param {?} provider
* @return {?}
*/
_instantiateProvider(provider) {
if (provider.multiProvider) {
/** @type {?} */
const res = [];
for (let i = 0; i < provider.resolvedFactories.length; ++i) {
res[i] = this._instantiate(provider, provider.resolvedFactories[i]);
}
return res;
}
else {
return this._instantiate(provider, provider.resolvedFactories[0]);
}
}
/**
* @private
* @param {?} provider
* @param {?} ResolvedReflectiveFactory
* @return {?}
*/
_instantiate(provider, ResolvedReflectiveFactory) {
/** @type {?} */
const factory = ResolvedReflectiveFactory.factory;
/** @type {?} */
let deps;
try {
deps =
ResolvedReflectiveFactory.dependencies.map((/**
* @param {?} dep
* @return {?}
*/
dep => this._getByReflectiveDependency(dep)));
}
catch (e) {
if (e.addKey) {
e.addKey(this, provider.key);
}
throw e;
}
/** @type {?} */
let obj;
try {
obj = factory(...deps);
}
catch (e) {
throw instantiationError(this, e, e.stack, provider.key);
}
return obj;
}
/**
* @private
* @param {?} dep
* @return {?}
*/
_getByReflectiveDependency(dep) {
return this._getByKey(dep.key, dep.visibility, dep.optional ? null : THROW_IF_NOT_FOUND);
}
/**
* @private
* @param {?} key
* @param {?} visibility
* @param {?} notFoundValue
* @return {?}
*/
_getByKey(key, visibility, notFoundValue) {
if (key === ReflectiveInjector_.INJECTOR_KEY) {
return this;
}
if (visibility instanceof Self) {
return this._getByKeySelf(key, notFoundValue);
}
else {
return this._getByKeyDefault(key, notFoundValue, visibility);
}
}
/**
* @private
* @param {?} keyId
* @return {?}
*/
_getObjByKeyId(keyId) {
for (let i = 0; i < this.keyIds.length; i++) {
if (this.keyIds[i] === keyId) {
if (this.objs[i] === UNDEFINED) {
this.objs[i] = this._new(this._providers[i]);
}
return this.objs[i];
}
}
return UNDEFINED;
}
/**
* \@internal
* @param {?} key
* @param {?} notFoundValue
* @return {?}
*/
_throwOrNull(key, notFoundValue) {
if (notFoundValue !== THROW_IF_NOT_FOUND) {
return notFoundValue;
}
else {
throw noProviderError(this, key);
}
}
/**
* \@internal
* @param {?} key
* @param {?} notFoundValue
* @return {?}
*/
_getByKeySelf(key, notFoundValue) {
/** @type {?} */
const obj = this._getObjByKeyId(key.id);
return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, notFoundValue);
}
/**
* \@internal
* @param {?} key
* @param {?} notFoundValue
* @param {?} visibility
* @return {?}
*/
_getByKeyDefault(key, notFoundValue, visibility) {
/** @type {?} */
let inj;
if (visibility instanceof SkipSelf) {
inj = this.parent;
}
else {
inj = this;
}
while (inj instanceof ReflectiveInjector_) {
/** @type {?} */
const inj_ = (/** @type {?} */ (inj));
/** @type {?} */
const obj = inj_._getObjByKeyId(key.id);
if (obj !== UNDEFINED)
return obj;
inj = inj_.parent;
}
if (inj !== null) {
return inj.get(key.token, notFoundValue);
}
else {
return this._throwOrNull(key, notFoundValue);
}
}
/**
* @return {?}
*/
get displayName() {
/** @type {?} */
const providers = _mapProviders(this, (/**
* @param {?} b
* @return {?}
*/
(b) => ' "' + b.key.displayName + '" '))
.join(', ');
return `ReflectiveInjector(providers: [${providers}])`;
}
/**
* @return {?}
*/
toString() {
return this.displayName;
}
}
ReflectiveInjector_.INJECTOR_KEY = ReflectiveKey.get(Injector);
if (false) {}
/**
* @param {?} injector
* @param {?} fn
* @return {?}
*/
function _mapProviders(injector, fn) {
/** @type {?} */
const res = [];
for (let i = 0; i < injector._providers.length; ++i) {
res[i] = fn(injector.getProviderAtIndex(i));
}
return res;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/di.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/metadata/di.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A DI token that you can use to create a virtual [provider](guide/glossary#provider)
* that will populate the `entryComponents` field of components and NgModules
* based on its `useValue` property value.
* All components that are referenced in the `useValue` value (either directly
* or in a nested array or map) are added to the `entryComponents` property.
*
* \@usageNotes
*
* The following example shows how the router can populate the `entryComponents`
* field of an NgModule based on a router configuration that refers
* to components.
*
* ```typescript
* // helper function inside the router
* function provideRoutes(routes) {
* return [
* {provide: ROUTES, useValue: routes},
* {provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: routes, multi: true}
* ];
* }
*
* // user code
* let routes = [
* {path: '/root', component: RootComp},
* {path: '/teams', component: TeamsComp}
* ];
*
* \@NgModule({
* providers: [provideRoutes(routes)]
* })
* class ModuleWithRoutes {}
* ```
*
* \@publicApi
* @deprecated Since 9.0.0. With Ivy, this property is no longer necessary.
* @type {?}
*/
const ANALYZE_FOR_ENTRY_COMPONENTS = new InjectionToken('AnalyzeForEntryComponents');
/**
* Type of the `Attribute` decorator / constructor function.
*
* \@publicApi
* @record
*/
function AttributeDecorator$1() { }
/**
* Type of the Attribute metadata.
*
* \@publicApi
* @record
*/
function Attribute$1() { }
if (false) {}
// WARNING: interface has both a type and a value, skipping emit
/**
* Base class for query metadata.
*
* @see `ContentChildren`.
* @see `ContentChild`.
* @see `ViewChildren`.
* @see `ViewChild`.
*
* \@publicApi
* @abstract
*/
class Query {
}
/**
* Type of the ContentChildren decorator / constructor function.
*
* @see `ContentChildren`.
* \@publicApi
* @record
*/
function ContentChildrenDecorator() { }
const ɵ0$a = /**
* @param {?=} selector
* @param {?=} data
* @return {?}
*/
(selector, data = {}) => (Object.assign({ selector, first: false, isViewQuery: false, descendants: false }, data));
/**
* ContentChildren decorator and metadata.
*
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const ContentChildren = makePropDecorator('ContentChildren', (ɵ0$a), Query);
/**
* Type of the ContentChild decorator / constructor function.
*
* \@publicApi
* @record
*/
function ContentChildDecorator() { }
const ɵ1$2 = /**
* @param {?=} selector
* @param {?=} data
* @return {?}
*/
(selector, data = {}) => (Object.assign({ selector, first: true, isViewQuery: false, descendants: true }, data));
/**
* ContentChild decorator and metadata.
*
*
* \@Annotation
*
* \@publicApi
* @type {?}
*/
const ContentChild = makePropDecorator('ContentChild', (ɵ1$2), Query);
/**
* Type of the ViewChildren decorator / constructor function.
*
* @see `ViewChildren`.
*
* \@publicApi
* @record
*/
function ViewChildrenDecorator() { }
const ɵ2 = /**
* @param {?=} selector
* @param {?=} data
* @return {?}
*/
(selector, data = {}) => (Object.assign({ selector, first: false, isViewQuery: true, descendants: true }, data));
/**
* ViewChildren decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const ViewChildren = makePropDecorator('ViewChildren', (ɵ2), Query);
/**
* Type of the ViewChild decorator / constructor function.
*
* @see `ViewChild`.
* \@publicApi
* @record
*/
function ViewChildDecorator() { }
const ɵ3 = /**
* @param {?} selector
* @param {?} data
* @return {?}
*/
(selector, data) => (Object.assign({ selector, first: true, isViewQuery: true, descendants: true }, data));
/**
* ViewChild decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const ViewChild = makePropDecorator('ViewChild', (ɵ3), Query);
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/metadata/resource_loading.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Used to resolve resource URLs on `\@Component` when used with JIT compilation.
*
* Example:
* ```
* \@Component({
* selector: 'my-comp',
* templateUrl: 'my-comp.html', // This requires asynchronous resolution
* })
* class MyComponent{
* }
*
* // Calling `renderComponent` will fail because `renderComponent` is a synchronous process
* // and `MyComponent`'s `\@Component.templateUrl` needs to be resolved asynchronously.
*
* // Calling `resolveComponentResources()` will resolve `\@Component.templateUrl` into
* // `\@Component.template`, which allows `renderComponent` to proceed in a synchronous manner.
*
* // Use browser's `fetch()` function as the default resource resolution strategy.
* resolveComponentResources(fetch).then(() => {
* // After resolution all URLs have been converted into `template` strings.
* renderComponent(MyComponent);
* });
*
* ```
*
* NOTE: In AOT the resolution happens during compilation, and so there should be no need
* to call this method outside JIT mode.
*
* @param {?} resourceResolver a function which is responsible for returning a `Promise` to the
* contents of the resolved URL. Browser's `fetch()` method is a good default implementation.
* @return {?}
*/
function resolveComponentResources(resourceResolver) {
// Store all promises which are fetching the resources.
/** @type {?} */
const componentResolved = [];
// Cache so that we don't fetch the same resource more than once.
/** @type {?} */
const urlMap = new Map();
/**
* @param {?} url
* @return {?}
*/
function cachedResourceResolve(url) {
/** @type {?} */
let promise = urlMap.get(url);
if (!promise) {
/** @type {?} */
const resp = resourceResolver(url);
urlMap.set(url, promise = resp.then(unwrapResponse));
}
return promise;
}
componentResourceResolutionQueue.forEach((/**
* @param {?} component
* @param {?} type
* @return {?}
*/
(component, type) => {
/** @type {?} */
const promises = [];
if (component.templateUrl) {
promises.push(cachedResourceResolve(component.templateUrl).then((/**
* @param {?} template
* @return {?}
*/
(template) => {
component.template = template;
})));
}
/** @type {?} */
const styleUrls = component.styleUrls;
/** @type {?} */
const styles = component.styles || (component.styles = []);
/** @type {?} */
const styleOffset = component.styles.length;
styleUrls && styleUrls.forEach((/**
* @param {?} styleUrl
* @param {?} index
* @return {?}
*/
(styleUrl, index) => {
styles.push(''); // pre-allocate array.
promises.push(cachedResourceResolve(styleUrl).then((/**
* @param {?} style
* @return {?}
*/
(style) => {
styles[styleOffset + index] = style;
styleUrls.splice(styleUrls.indexOf(styleUrl), 1);
if (styleUrls.length == 0) {
component.styleUrls = undefined;
}
})));
}));
/** @type {?} */
const fullyResolved = Promise.all(promises).then((/**
* @return {?}
*/
() => componentDefResolved(type)));
componentResolved.push(fullyResolved);
}));
clearResolutionOfComponentResourcesQueue();
return Promise.all(componentResolved).then((/**
* @return {?}
*/
() => undefined));
}
/** @type {?} */
let componentResourceResolutionQueue = new Map();
// Track when existing ɵcmp for a Type is waiting on resources.
/** @type {?} */
const componentDefPendingResolution = new Set();
/**
* @param {?} type
* @param {?} metadata
* @return {?}
*/
function maybeQueueResolutionOfComponentResources(type, metadata) {
if (componentNeedsResolution(metadata)) {
componentResourceResolutionQueue.set(type, metadata);
componentDefPendingResolution.add(type);
}
}
/**
* @param {?} type
* @return {?}
*/
function isComponentDefPendingResolution(type) {
return componentDefPendingResolution.has(type);
}
/**
* @param {?} component
* @return {?}
*/
function componentNeedsResolution(component) {
return !!((component.templateUrl && !component.hasOwnProperty('template')) ||
component.styleUrls && component.styleUrls.length);
}
/**
* @return {?}
*/
function clearResolutionOfComponentResourcesQueue() {
/** @type {?} */
const old = componentResourceResolutionQueue;
componentResourceResolutionQueue = new Map();
return old;
}
/**
* @param {?} queue
* @return {?}
*/
function restoreComponentResolutionQueue(queue) {
componentDefPendingResolution.clear();
queue.forEach((/**
* @param {?} _
* @param {?} type
* @return {?}
*/
(_, type) => componentDefPendingResolution.add(type)));
componentResourceResolutionQueue = queue;
}
/**
* @return {?}
*/
function isComponentResourceResolutionQueueEmpty() {
return componentResourceResolutionQueue.size === 0;
}
/**
* @param {?} response
* @return {?}
*/
function unwrapResponse(response) {
return typeof response == 'string' ? response : response.text();
}
/**
* @param {?} type
* @return {?}
*/
function componentDefResolved(type) {
componentDefPendingResolution.delete(type);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/styling/static_styling.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Compute the static styling (class/style) from `TAttributes`.
*
* This function should be called during `firstCreatePass` only.
*
* @param {?} tNode The `TNode` into which the styling information should be loaded.
* @param {?} attrs `TAttributes` containing the styling information.
* @param {?} writeToHost Where should the resulting static styles be written?
* - `false` Write to `TNode.stylesWithoutHost` / `TNode.classesWithoutHost`
* - `true` Write to `TNode.styles` / `TNode.classes`
* @return {?}
*/
function computeStaticStyling(tNode, attrs, writeToHost) {
ngDevMode &&
assertFirstCreatePass(getTView(), 'Expecting to be called in first template pass only');
/** @type {?} */
let styles = writeToHost ? tNode.styles : null;
/** @type {?} */
let classes = writeToHost ? tNode.classes : null;
/** @type {?} */
let mode = 0;
if (attrs !== null) {
for (let i = 0; i < attrs.length; i++) {
/** @type {?} */
const value = attrs[i];
if (typeof value === 'number') {
mode = value;
}
else if (mode == 1 /* Classes */) {
classes = concatStringsWithSpace(classes, (/** @type {?} */ (value)));
}
else if (mode == 2 /* Styles */) {
/** @type {?} */
const style = (/** @type {?} */ (value));
/** @type {?} */
const styleValue = (/** @type {?} */ (attrs[++i]));
styles = concatStringsWithSpace(styles, style + ': ' + styleValue + ';');
}
}
}
writeToHost ? tNode.styles = styles : tNode.stylesWithoutHost = styles;
writeToHost ? tNode.classes = classes : tNode.classesWithoutHost = classes;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
let _symbolIterator = null;
function getSymbolIterator() {
if (!_symbolIterator) {
const Symbol = _global['Symbol'];
if (Symbol && Symbol.iterator) {
_symbolIterator = Symbol.iterator;
}
else {
// es6-shim specific logic
const keys = Object.getOwnPropertyNames(Map.prototype);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (key !== 'entries' && key !== 'size' &&
Map.prototype[key] === Map.prototype['entries']) {
_symbolIterator = key;
}
}
}
}
return _symbolIterator;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function isIterable(obj) {
return obj !== null && typeof obj === 'object' && obj[getSymbolIterator()] !== undefined;
}
function isListLikeIterable(obj) {
if (!isJsObject(obj))
return false;
return Array.isArray(obj) ||
(!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v]
getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop
}
function areIterablesEqual(a, b, comparator) {
const iterator1 = a[getSymbolIterator()]();
const iterator2 = b[getSymbolIterator()]();
while (true) {
const item1 = iterator1.next();
const item2 = iterator2.next();
if (item1.done && item2.done)
return true;
if (item1.done || item2.done)
return false;
if (!comparator(item1.value, item2.value))
return false;
}
}
function iterateListLike(obj, fn) {
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
fn(obj[i]);
}
}
else {
const iterator = obj[getSymbolIterator()]();
let item;
while (!((item = iterator.next()).done)) {
fn(item.value);
}
}
}
function isJsObject(o) {
return o !== null && (typeof o === 'function' || typeof o === 'object');
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// JS has NaN !== NaN
function looseIdentical(a, b) {
return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b);
}
function devModeEqual(a, b) {
const isListLikeIterableA = isListLikeIterable(a);
const isListLikeIterableB = isListLikeIterable(b);
if (isListLikeIterableA && isListLikeIterableB) {
return areIterablesEqual(a, b, devModeEqual);
}
else {
const isAObject = a && (typeof a === 'object' || typeof a === 'function');
const isBObject = b && (typeof b === 'object' || typeof b === 'function');
if (!isListLikeIterableA && isAObject && !isListLikeIterableB && isBObject) {
return true;
}
else {
return looseIdentical(a, b);
}
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/change_detection/change_detection_util.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function devModeEqual$1(a, b) {
/** @type {?} */
const isListLikeIterableA = isListLikeIterable$1(a);
/** @type {?} */
const isListLikeIterableB = isListLikeIterable$1(b);
if (isListLikeIterableA && isListLikeIterableB) {
return areIterablesEqual$1(a, b, devModeEqual$1);
}
else {
/** @type {?} */
const isAObject = a && (typeof a === 'object' || typeof a === 'function');
/** @type {?} */
const isBObject = b && (typeof b === 'object' || typeof b === 'function');
if (!isListLikeIterableA && isAObject && !isListLikeIterableB && isBObject) {
return true;
}
else {
return looseIdentical(a, b);
}
}
}
/**
* Indicates that the result of a {\@link Pipe} transformation has changed even though the
* reference has not changed.
*
* Wrapped values are unwrapped automatically during the change detection, and the unwrapped value
* is stored.
*
* Example:
*
* ```
* if (this._latestValue === this._latestReturnedValue) {
* return this._latestReturnedValue;
* } else {
* this._latestReturnedValue = this._latestValue;
* return WrappedValue.wrap(this._latestValue); // this will force update
* }
* ```
*
* \@publicApi
*/
class WrappedValue {
/**
* @param {?} value
*/
constructor(value) {
this.wrapped = value;
}
/**
* Creates a wrapped value.
* @param {?} value
* @return {?}
*/
static wrap(value) {
return new WrappedValue(value);
}
/**
* Returns the underlying value of a wrapped value.
* Returns the given `value` when it is not wrapped.
*
* @param {?} value
* @return {?}
*/
static unwrap(value) {
return WrappedValue.isWrapped(value) ? value.wrapped : value;
}
/**
* Returns true if `value` is a wrapped value.
* @param {?} value
* @return {?}
*/
static isWrapped(value) {
return value instanceof WrappedValue;
}
}
if (false) {}
/**
* @param {?} obj
* @return {?}
*/
function isListLikeIterable$1(obj) {
if (!isJsObject$1(obj))
return false;
return Array.isArray(obj) ||
(!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v]
getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop
}
/**
* @param {?} a
* @param {?} b
* @param {?} comparator
* @return {?}
*/
function areIterablesEqual$1(a, b, comparator) {
/** @type {?} */
const iterator1 = a[getSymbolIterator()]();
/** @type {?} */
const iterator2 = b[getSymbolIterator()]();
while (true) {
/** @type {?} */
const item1 = iterator1.next();
/** @type {?} */
const item2 = iterator2.next();
if (item1.done && item2.done)
return true;
if (item1.done || item2.done)
return false;
if (!comparator(item1.value, item2.value))
return false;
}
}
/**
* @param {?} obj
* @param {?} fn
* @return {?}
*/
function iterateListLike$1(obj, fn) {
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
fn(obj[i]);
}
}
else {
/** @type {?} */
const iterator = obj[getSymbolIterator()]();
/** @type {?} */
let item;
while (!((item = iterator.next()).done)) {
fn(item.value);
}
}
}
/**
* @param {?} o
* @return {?}
*/
function isJsObject$1(o) {
return o !== null && (typeof o === 'function' || typeof o === 'object');
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/bindings.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// TODO(misko): consider inlining
/**
* Updates binding and returns the value.
* @param {?} lView
* @param {?} bindingIndex
* @param {?} value
* @return {?}
*/
function updateBinding(lView, bindingIndex, value) {
return lView[bindingIndex] = value;
}
/**
* Gets the current binding value.
* @param {?} lView
* @param {?} bindingIndex
* @return {?}
*/
function getBinding(lView, bindingIndex) {
ngDevMode && assertDataInRange(lView, bindingIndex);
ngDevMode &&
assertNotSame(lView[bindingIndex], NO_CHANGE, 'Stored value should never be NO_CHANGE.');
return lView[bindingIndex];
}
/**
* Updates binding if changed, then returns whether it was updated.
*
* This function also checks the `CheckNoChangesMode` and throws if changes are made.
* Some changes (Objects/iterables) during `CheckNoChangesMode` are exempt to comply with VE
* behavior.
*
* @param {?} lView current `LView`
* @param {?} bindingIndex The binding in the `LView` to check
* @param {?} value New value to check against `lView[bindingIndex]`
* @return {?} `true` if the bindings has changed. (Throws if binding has changed during
* `CheckNoChangesMode`)
*/
function bindingUpdated(lView, bindingIndex, value) {
ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
ngDevMode &&
assertLessThan(bindingIndex, lView.length, `Slot should have been initialized to NO_CHANGE`);
/** @type {?} */
const oldValue = lView[bindingIndex];
if (Object.is(oldValue, value)) {
return false;
}
else {
if (ngDevMode && getCheckNoChangesMode()) {
// View engine didn't report undefined values as changed on the first checkNoChanges pass
// (before the change detection was run).
/** @type {?} */
const oldValueToCompare = oldValue !== NO_CHANGE ? oldValue : undefined;
if (!devModeEqual$1(oldValueToCompare, value)) {
/** @type {?} */
const details = getExpressionChangedErrorDetails(lView, bindingIndex, oldValueToCompare, value);
throwErrorIfNoChangesMode(oldValue === NO_CHANGE, details.oldValue, details.newValue, details.propName);
}
// There was a change, but the `devModeEqual` decided that the change is exempt from an error.
// For this reason we exit as if no change. The early exit is needed to prevent the changed
// value to be written into `LView` (If we would write the new value that we would not see it
// as change on next CD.)
return false;
}
lView[bindingIndex] = value;
return true;
}
}
/**
* Updates 2 bindings if changed, then returns whether either was updated.
* @param {?} lView
* @param {?} bindingIndex
* @param {?} exp1
* @param {?} exp2
* @return {?}
*/
function bindingUpdated2(lView, bindingIndex, exp1, exp2) {
/** @type {?} */
const different = bindingUpdated(lView, bindingIndex, exp1);
return bindingUpdated(lView, bindingIndex + 1, exp2) || different;
}
/**
* Updates 3 bindings if changed, then returns whether any was updated.
* @param {?} lView
* @param {?} bindingIndex
* @param {?} exp1
* @param {?} exp2
* @param {?} exp3
* @return {?}
*/
function bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3) {
/** @type {?} */
const different = bindingUpdated2(lView, bindingIndex, exp1, exp2);
return bindingUpdated(lView, bindingIndex + 2, exp3) || different;
}
/**
* Updates 4 bindings if changed, then returns whether any was updated.
* @param {?} lView
* @param {?} bindingIndex
* @param {?} exp1
* @param {?} exp2
* @param {?} exp3
* @param {?} exp4
* @return {?}
*/
function bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4) {
/** @type {?} */
const different = bindingUpdated2(lView, bindingIndex, exp1, exp2);
return bindingUpdated2(lView, bindingIndex + 2, exp3, exp4) || different;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/attribute.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Updates the value of or removes a bound attribute on an Element.
*
* Used in the case of `[attr.title]="value"`
*
* \@codeGenApi
* @param {?} name name The name of the attribute.
* @param {?} value value The attribute is removed when value is `null` or `undefined`.
* Otherwise the attribute value is set to the stringified value.
* @param {?=} sanitizer An optional function used to sanitize the value.
* @param {?=} namespace Optional namespace to use when setting the attribute.
*
* @return {?}
*/
function ɵɵattribute(name, value, sanitizer, namespace) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const bindingIndex = nextBindingIndex();
if (bindingUpdated(lView, bindingIndex, value)) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace);
ngDevMode && storePropertyBindingMetadata(tView.data, tNode, 'attr.' + name, bindingIndex);
}
return ɵɵattribute;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/interpolation.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Create interpolation bindings with a variable number of expressions.
*
* If there are 1 to 8 expressions `interpolation1()` to `interpolation8()` should be used instead.
* Those are faster because there is no need to create an array of expressions and iterate over it.
*
* `values`:
* - has static text at even indexes,
* - has evaluated expressions at odd indexes.
*
* Returns the concatenated string when any of the arguments changes, `NO_CHANGE` otherwise.
* @param {?} lView
* @param {?} values
* @return {?}
*/
function interpolationV(lView, values) {
ngDevMode && assertLessThan(2, values.length, 'should have at least 3 values');
ngDevMode && assertEqual(values.length % 2, 1, 'should have an odd number of values');
/** @type {?} */
let isBindingUpdated = false;
/** @type {?} */
let bindingIndex = getBindingIndex();
for (let i = 1; i < values.length; i += 2) {
// Check if bindings (odd indexes) have changed
isBindingUpdated = bindingUpdated(lView, bindingIndex++, values[i]) || isBindingUpdated;
}
setBindingIndex(bindingIndex);
if (!isBindingUpdated) {
return NO_CHANGE;
}
// Build the updated content
/** @type {?} */
let content = values[0];
for (let i = 1; i < values.length; i += 2) {
content += renderStringify(values[i]) + values[i + 1];
}
return content;
}
/**
* Creates an interpolation binding with 1 expression.
*
* @param {?} lView
* @param {?} prefix static value used for concatenation only.
* @param {?} v0 value checked for change.
* @param {?} suffix static value used for concatenation only.
* @return {?}
*/
function interpolation1(lView, prefix, v0, suffix) {
/** @type {?} */
const different = bindingUpdated(lView, nextBindingIndex(), v0);
return different ? prefix + renderStringify(v0) + suffix : NO_CHANGE;
}
/**
* Creates an interpolation binding with 2 expressions.
* @param {?} lView
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} suffix
* @return {?}
*/
function interpolation2(lView, prefix, v0, i0, v1, suffix) {
/** @type {?} */
const bindingIndex = getBindingIndex();
/** @type {?} */
const different = bindingUpdated2(lView, bindingIndex, v0, v1);
incrementBindingIndex(2);
return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + suffix : NO_CHANGE;
}
/**
* Creates an interpolation binding with 3 expressions.
* @param {?} lView
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} suffix
* @return {?}
*/
function interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix) {
/** @type {?} */
const bindingIndex = getBindingIndex();
/** @type {?} */
const different = bindingUpdated3(lView, bindingIndex, v0, v1, v2);
incrementBindingIndex(3);
return different ?
prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + suffix :
NO_CHANGE;
}
/**
* Create an interpolation binding with 4 expressions.
* @param {?} lView
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} i2
* @param {?} v3
* @param {?} suffix
* @return {?}
*/
function interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
/** @type {?} */
const bindingIndex = getBindingIndex();
/** @type {?} */
const different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
incrementBindingIndex(4);
return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 +
renderStringify(v2) + i2 + renderStringify(v3) + suffix :
NO_CHANGE;
}
/**
* Creates an interpolation binding with 5 expressions.
* @param {?} lView
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} i2
* @param {?} v3
* @param {?} i3
* @param {?} v4
* @param {?} suffix
* @return {?}
*/
function interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
/** @type {?} */
const bindingIndex = getBindingIndex();
/** @type {?} */
let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
different = bindingUpdated(lView, bindingIndex + 4, v4) || different;
incrementBindingIndex(5);
return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 +
renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + suffix :
NO_CHANGE;
}
/**
* Creates an interpolation binding with 6 expressions.
* @param {?} lView
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} i2
* @param {?} v3
* @param {?} i3
* @param {?} v4
* @param {?} i4
* @param {?} v5
* @param {?} suffix
* @return {?}
*/
function interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
/** @type {?} */
const bindingIndex = getBindingIndex();
/** @type {?} */
let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
different = bindingUpdated2(lView, bindingIndex + 4, v4, v5) || different;
incrementBindingIndex(6);
return different ?
prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 +
renderStringify(v3) + i3 + renderStringify(v4) + i4 + renderStringify(v5) + suffix :
NO_CHANGE;
}
/**
* Creates an interpolation binding with 7 expressions.
* @param {?} lView
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} i2
* @param {?} v3
* @param {?} i3
* @param {?} v4
* @param {?} i4
* @param {?} v5
* @param {?} i5
* @param {?} v6
* @param {?} suffix
* @return {?}
*/
function interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
/** @type {?} */
const bindingIndex = getBindingIndex();
/** @type {?} */
let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
different = bindingUpdated3(lView, bindingIndex + 4, v4, v5, v6) || different;
incrementBindingIndex(7);
return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 +
renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + i4 +
renderStringify(v5) + i5 + renderStringify(v6) + suffix :
NO_CHANGE;
}
/**
* Creates an interpolation binding with 8 expressions.
* @param {?} lView
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} i2
* @param {?} v3
* @param {?} i3
* @param {?} v4
* @param {?} i4
* @param {?} v5
* @param {?} i5
* @param {?} v6
* @param {?} i6
* @param {?} v7
* @param {?} suffix
* @return {?}
*/
function interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
/** @type {?} */
const bindingIndex = getBindingIndex();
/** @type {?} */
let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
different = bindingUpdated4(lView, bindingIndex + 4, v4, v5, v6, v7) || different;
incrementBindingIndex(8);
return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 +
renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + i4 +
renderStringify(v5) + i5 + renderStringify(v6) + i6 + renderStringify(v7) + suffix :
NO_CHANGE;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/attribute_interpolation.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
*
* Update an interpolated attribute on an element with single bound value surrounded by text.
*
* Used when the value passed to a property has 1 interpolated value in it:
*
* ```html
* <div attr.title="prefix{{v0}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate1('title', 'prefix', v0, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} attrName The name of the attribute to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @param {?=} namespace
* @return {?} itself, so that it may be chained.
*/
function ɵɵattributeInterpolate1(attrName, prefix, v0, suffix, sanitizer, namespace) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 1, prefix, suffix);
}
return ɵɵattributeInterpolate1;
}
/**
*
* Update an interpolated attribute on an element with 2 bound values surrounded by text.
*
* Used when the value passed to a property has 2 interpolated values in it:
*
* ```html
* <div attr.title="prefix{{v0}}-{{v1}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} attrName The name of the attribute to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @param {?=} namespace
* @return {?} itself, so that it may be chained.
*/
function ɵɵattributeInterpolate2(attrName, prefix, v0, i0, v1, suffix, sanitizer, namespace) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 2, prefix, i0, suffix);
}
return ɵɵattributeInterpolate2;
}
/**
*
* Update an interpolated attribute on an element with 3 bound values surrounded by text.
*
* Used when the value passed to a property has 3 interpolated values in it:
*
* ```html
* <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate3(
* 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} attrName The name of the attribute to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @param {?=} namespace
* @return {?} itself, so that it may be chained.
*/
function ɵɵattributeInterpolate3(attrName, prefix, v0, i0, v1, i1, v2, suffix, sanitizer, namespace) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 3, prefix, i0, i1, suffix);
}
return ɵɵattributeInterpolate3;
}
/**
*
* Update an interpolated attribute on an element with 4 bound values surrounded by text.
*
* Used when the value passed to a property has 4 interpolated values in it:
*
* ```html
* <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate4(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} attrName The name of the attribute to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @param {?=} namespace
* @return {?} itself, so that it may be chained.
*/
function ɵɵattributeInterpolate4(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, sanitizer, namespace) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix);
}
return ɵɵattributeInterpolate4;
}
/**
*
* Update an interpolated attribute on an element with 5 bound values surrounded by text.
*
* Used when the value passed to a property has 5 interpolated values in it:
*
* ```html
* <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate5(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} attrName The name of the attribute to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @param {?=} namespace
* @return {?} itself, so that it may be chained.
*/
function ɵɵattributeInterpolate5(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, sanitizer, namespace) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix);
}
return ɵɵattributeInterpolate5;
}
/**
*
* Update an interpolated attribute on an element with 6 bound values surrounded by text.
*
* Used when the value passed to a property has 6 interpolated values in it:
*
* ```html
* <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate6(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} attrName The name of the attribute to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @param {?=} namespace
* @return {?} itself, so that it may be chained.
*/
function ɵɵattributeInterpolate6(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, sanitizer, namespace) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix);
}
return ɵɵattributeInterpolate6;
}
/**
*
* Update an interpolated attribute on an element with 7 bound values surrounded by text.
*
* Used when the value passed to a property has 7 interpolated values in it:
*
* ```html
* <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate7(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} attrName The name of the attribute to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} i5 Static value used for concatenation only.
* @param {?} v6 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @param {?=} namespace
* @return {?} itself, so that it may be chained.
*/
function ɵɵattributeInterpolate7(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, sanitizer, namespace) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix);
}
return ɵɵattributeInterpolate7;
}
/**
*
* Update an interpolated attribute on an element with 8 bound values surrounded by text.
*
* Used when the value passed to a property has 8 interpolated values in it:
*
* ```html
* <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate8(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} attrName The name of the attribute to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} i5 Static value used for concatenation only.
* @param {?} v6 Value checked for change.
* @param {?} i6 Static value used for concatenation only.
* @param {?} v7 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @param {?=} namespace
* @return {?} itself, so that it may be chained.
*/
function ɵɵattributeInterpolate8(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, sanitizer, namespace) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix);
}
return ɵɵattributeInterpolate8;
}
/**
* Update an interpolated attribute on an element with 9 or more bound values surrounded by text.
*
* Used when the number of interpolated values exceeds 8.
*
* ```html
* <div
* title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolateV(
* 'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
* 'suffix']);
* ```
*
* \@codeGenApi
* @param {?} attrName The name of the attribute to update.
* @param {?} values The collection of values and the strings in-between those values, beginning with
* a string prefix and ending with a string suffix.
* (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
* @param {?=} sanitizer An optional sanitizer function
* @param {?=} namespace
* @return {?} itself, so that it may be chained.
*/
function ɵɵattributeInterpolateV(attrName, values, sanitizer, namespace) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolated = interpolationV(lView, values);
if (interpolated !== NO_CHANGE) {
/** @type {?} */
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolated, sanitizer, namespace);
if (ngDevMode) {
/** @type {?} */
const interpolationInBetween = [values[0]];
for (let i = 2; i < values.length; i += 2) {
interpolationInBetween.push(values[i]);
}
storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween);
}
}
return ɵɵattributeInterpolateV;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/change_detection.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Synchronously perform change detection on a component (and possibly its sub-components).
*
* This function triggers change detection in a synchronous way on a component.
*
* @param {?} component The component which the change detection should be performed on.
* @return {?}
*/
function detectChanges(component) {
/** @type {?} */
const view = getComponentViewByInstance(component);
detectChangesInternal(view[TVIEW], view, component);
}
/**
* Marks the component as dirty (needing change detection). Marking a component dirty will
* schedule a change detection on it at some point in the future.
*
* Marking an already dirty component as dirty won't do anything. Only one outstanding change
* detection can be scheduled per component tree.
*
* @param {?} component Component to mark as dirty.
* @return {?}
*/
function markDirty(component) {
ngDevMode && assertDefined(component, 'component');
/** @type {?} */
const rootView = (/** @type {?} */ (markViewDirty(getComponentViewByInstance(component))));
ngDevMode && assertDefined(rootView[CONTEXT], 'rootContext should be defined');
scheduleTick((/** @type {?} */ (rootView[CONTEXT])), 1 /* DetectChanges */);
}
/**
* Used to perform change detection on the whole application.
*
* This is equivalent to `detectChanges`, but invoked on root component. Additionally, `tick`
* executes lifecycle hooks and conditionally checks components based on their
* `ChangeDetectionStrategy` and dirtiness.
*
* The preferred way to trigger change detection is to call `markDirty`. `markDirty` internally
* schedules `tick` using a scheduler in order to coalesce multiple `markDirty` calls into a
* single change detection run. By default, the scheduler is `requestAnimationFrame`, but can
* be changed when calling `renderComponent` and providing the `scheduler` option.
* @template T
* @param {?} component
* @return {?}
*/
function tick(component) {
/** @type {?} */
const rootView = getRootView(component);
/** @type {?} */
const rootContext = (/** @type {?} */ (rootView[CONTEXT]));
tickRootContext(rootContext);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/template.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} index
* @param {?} tView
* @param {?} lView
* @param {?} templateFn
* @param {?} decls
* @param {?} vars
* @param {?=} tagName
* @param {?=} attrsIndex
* @param {?=} localRefsIndex
* @return {?}
*/
function templateFirstCreatePass(index, tView, lView, templateFn, decls, vars, tagName, attrsIndex, localRefsIndex) {
ngDevMode && assertFirstCreatePass(tView);
ngDevMode && ngDevMode.firstCreatePass++;
/** @type {?} */
const tViewConsts = tView.consts;
// TODO(pk): refactor getOrCreateTNode to have the "create" only version
/** @type {?} */
const tNode = getOrCreateTNode(tView, lView[T_HOST], index, 0 /* Container */, tagName || null, getConstant(tViewConsts, attrsIndex));
resolveDirectives(tView, lView, tNode, getConstant(tViewConsts, localRefsIndex));
registerPostOrderHooks(tView, tNode);
/** @type {?} */
const embeddedTView = tNode.tViews = createTView(2 /* Embedded */, -1, templateFn, decls, vars, tView.directiveRegistry, tView.pipeRegistry, null, tView.schemas, tViewConsts);
/** @type {?} */
const embeddedTViewNode = (/** @type {?} */ (createTNode(tView, null, 2 /* View */, -1, null, null)));
embeddedTViewNode.injectorIndex = tNode.injectorIndex;
embeddedTView.node = embeddedTViewNode;
if (tView.queries !== null) {
tView.queries.template(tView, tNode);
embeddedTView.queries = tView.queries.embeddedTView(tNode);
}
return tNode;
}
/**
* Creates an LContainer for an ng-template (dynamically-inserted view), e.g.
*
* <ng-template #foo>
* <div></div>
* </ng-template>
*
* \@codeGenApi
* @param {?} index The index of the container in the data array
* @param {?} templateFn Inline template
* @param {?} decls The number of nodes, local refs, and pipes for this template
* @param {?} vars The number of bindings for this template
* @param {?=} tagName The name of the container element, if applicable
* @param {?=} attrsIndex Index of template attributes in the `consts` array.
* @param {?=} localRefsIndex
* @param {?=} localRefExtractor A function which extracts local-refs values from the template.
* Defaults to the current element associated with the local-ref.
*
* @return {?}
*/
function ɵɵtemplate(index, templateFn, decls, vars, tagName, attrsIndex, localRefsIndex, localRefExtractor) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
/** @type {?} */
const adjustedIndex = index + HEADER_OFFSET;
/** @type {?} */
const tNode = tView.firstCreatePass ?
templateFirstCreatePass(index, tView, lView, templateFn, decls, vars, tagName, attrsIndex, localRefsIndex) :
(/** @type {?} */ (tView.data[adjustedIndex]));
setPreviousOrParentTNode(tNode, false);
/** @type {?} */
const comment = lView[RENDERER].createComment(ngDevMode ? 'container' : '');
appendChild(tView, lView, comment, tNode);
attachPatchData(comment, lView);
addToViewTree(lView, lView[adjustedIndex] = createLContainer(comment, lView, comment, tNode));
if (isDirectiveHost(tNode)) {
createDirectivesInstances(tView, lView, tNode);
}
if (localRefsIndex != null) {
saveResolvedLocalsInData(lView, tNode, localRefExtractor);
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/storage.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Store a value in the `data` at a given `index`.
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} index
* @param {?} value
* @return {?}
*/
function store(tView, lView, index, value) {
// We don't store any static data for local variables, so the first time
// we see the template, we should store as null to avoid a sparse array
/** @type {?} */
const adjustedIndex = index + HEADER_OFFSET;
if (adjustedIndex >= tView.data.length) {
tView.data[adjustedIndex] = null;
tView.blueprint[adjustedIndex] = null;
}
lView[adjustedIndex] = value;
}
/**
* Retrieves a local reference from the current contextViewData.
*
* If the reference to retrieve is in a parent view, this instruction is used in conjunction
* with a nextContext() call, which walks up the tree and updates the contextViewData instance.
*
* \@codeGenApi
* @template T
* @param {?} index The index of the local ref in contextViewData.
*
* @return {?}
*/
function ɵɵreference(index) {
/** @type {?} */
const contextLView = getContextLView();
return load(contextLView, index);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/di.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @template T
* @param {?} token
* @param {?=} flags
* @return {?}
*/
function ɵɵdirectiveInject(token, flags = InjectFlags.Default) {
/** @type {?} */
const lView = getLView();
// Fall back to inject() if view hasn't been created. This situation can happen in tests
// if inject utilities are used before bootstrapping.
if (lView == null)
return ɵɵinject(token, flags);
/** @type {?} */
const tNode = getPreviousOrParentTNode();
return getOrCreateInjectable((/** @type {?} */ (tNode)), lView, resolveForwardRef(token), flags);
}
/**
* Facade for the attribute injection from DI.
*
* \@codeGenApi
* @param {?} attrNameToInject
* @return {?}
*/
function ɵɵinjectAttribute(attrNameToInject) {
return injectAttributeImpl(getPreviousOrParentTNode(), attrNameToInject);
}
/**
* Throws an error indicating that a factory function could not be generated by the compiler for a
* particular class.
*
* This instruction allows the actual error message to be optimized away when ngDevMode is turned
* off, saving bytes of generated code while still providing a good experience in dev mode.
*
* The name of the class is not mentioned here, but will be in the generated factory function name
* and thus in the stack trace.
*
* \@codeGenApi
* @return {?}
*/
function ɵɵinvalidFactory() {
/** @type {?} */
const msg = ngDevMode ? `This constructor was not compatible with Dependency Injection.` : 'invalid';
throw new Error(msg);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/property.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Update a property on a selected element.
*
* Operates on the element selected by index via the {\@link select} instruction.
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled
*
* \@codeGenApi
* @template T
* @param {?} propName Name of property. Because it is going to DOM, this is not subject to
* renaming as part of minification.
* @param {?} value New value to write.
* @param {?=} sanitizer An optional function used to sanitize the value.
* @return {?} This function returns itself so that it may be chained
* (e.g. `property('name', ctx.name)('title', ctx.title)`)
*
*/
function ɵɵproperty(propName, value, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const bindingIndex = nextBindingIndex();
if (bindingUpdated(lView, bindingIndex, value)) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, false);
ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
}
return ɵɵproperty;
}
/**
* Given `<div style="..." my-dir>` and `MyDir` with `\@Input('style')` we need to write to
* directive input.
* @param {?} tView
* @param {?} tNode
* @param {?} lView
* @param {?} value
* @param {?} isClassBased
* @return {?}
*/
function setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased) {
/** @type {?} */
const inputs = (/** @type {?} */ (tNode.inputs));
/** @type {?} */
const property = isClassBased ? 'class' : 'style';
// We support both 'class' and `className` hence the fallback.
setInputsForProperty(tView, lView, inputs[property], property, value);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/element.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} index
* @param {?} tView
* @param {?} lView
* @param {?} native
* @param {?} name
* @param {?=} attrsIndex
* @param {?=} localRefsIndex
* @return {?}
*/
function elementStartFirstCreatePass(index, tView, lView, native, name, attrsIndex, localRefsIndex) {
ngDevMode && assertFirstCreatePass(tView);
ngDevMode && ngDevMode.firstCreatePass++;
/** @type {?} */
const tViewConsts = tView.consts;
/** @type {?} */
const attrs = getConstant(tViewConsts, attrsIndex);
/** @type {?} */
const tNode = getOrCreateTNode(tView, lView[T_HOST], index, 3 /* Element */, name, attrs);
/** @type {?} */
const hasDirectives = resolveDirectives(tView, lView, tNode, getConstant(tViewConsts, localRefsIndex));
ngDevMode && warnAboutUnknownElement(tView, lView, native, tNode, hasDirectives);
if (tNode.attrs !== null) {
computeStaticStyling(tNode, tNode.attrs, false);
}
if (tNode.mergedAttrs !== null) {
computeStaticStyling(tNode, tNode.mergedAttrs, true);
}
if (tView.queries !== null) {
tView.queries.elementStart(tView, tNode);
}
return tNode;
}
/**
* Create DOM element. The instruction must later be followed by `elementEnd()` call.
*
* \@codeGenApi
* @param {?} index Index of the element in the LView array
* @param {?} name Name of the DOM Node
* @param {?=} attrsIndex Index of the element's attributes in the `consts` array.
* @param {?=} localRefsIndex Index of the element's local references in the `consts` array.
*
* Attributes and localRefs are passed as an array of strings where elements with an even index
* hold an attribute name and elements with an odd index hold an attribute value, ex.:
* ['id', 'warning5', 'class', 'alert']
*
* @return {?}
*/
function ɵɵelementStart(index, name, attrsIndex, localRefsIndex) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
/** @type {?} */
const adjustedIndex = HEADER_OFFSET + index;
ngDevMode &&
assertEqual(getBindingIndex(), tView.bindingStartIndex, 'elements should be created before any bindings');
ngDevMode && ngDevMode.rendererCreateElement++;
ngDevMode && assertDataInRange(lView, adjustedIndex);
/** @type {?} */
const renderer = lView[RENDERER];
/** @type {?} */
const native = lView[adjustedIndex] = elementCreate(name, renderer, getNamespace());
/** @type {?} */
const tNode = tView.firstCreatePass ?
elementStartFirstCreatePass(index, tView, lView, native, name, attrsIndex, localRefsIndex) :
(/** @type {?} */ (tView.data[adjustedIndex]));
setPreviousOrParentTNode(tNode, true);
/** @type {?} */
const mergedAttrs = tNode.mergedAttrs;
if (mergedAttrs !== null) {
setUpAttributes(renderer, native, mergedAttrs);
}
/** @type {?} */
const classes = tNode.classes;
if (classes !== null) {
writeDirectClass(renderer, native, classes);
}
/** @type {?} */
const styles = tNode.styles;
if (styles !== null) {
writeDirectStyle(renderer, native, styles);
}
appendChild(tView, lView, native, tNode);
// any immediate children of a component or template container must be pre-emptively
// monkey-patched with the component view data so that the element can be inspected
// later on using any element discovery utility methods (see `element_discovery.ts`)
if (getElementDepthCount() === 0) {
attachPatchData(native, lView);
}
increaseElementDepthCount();
if (isDirectiveHost(tNode)) {
createDirectivesInstances(tView, lView, tNode);
executeContentQueries(tView, tNode, lView);
}
if (localRefsIndex !== null) {
saveResolvedLocalsInData(lView, tNode);
}
}
/**
* Mark the end of the element.
*
* \@codeGenApi
* @return {?}
*/
function ɵɵelementEnd() {
/** @type {?} */
let previousOrParentTNode = getPreviousOrParentTNode();
ngDevMode && assertDefined(previousOrParentTNode, 'No parent node to close.');
if (getIsParent()) {
setIsNotParent();
}
else {
ngDevMode && assertHasParent(getPreviousOrParentTNode());
previousOrParentTNode = (/** @type {?} */ (previousOrParentTNode.parent));
setPreviousOrParentTNode(previousOrParentTNode, false);
}
/** @type {?} */
const tNode = previousOrParentTNode;
ngDevMode && assertNodeType(tNode, 3 /* Element */);
decreaseElementDepthCount();
/** @type {?} */
const tView = getTView();
if (tView.firstCreatePass) {
registerPostOrderHooks(tView, previousOrParentTNode);
if (isContentQueryHost(previousOrParentTNode)) {
(/** @type {?} */ (tView.queries)).elementEnd(previousOrParentTNode);
}
}
if (tNode.classesWithoutHost != null && hasClassInput(tNode)) {
setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.classesWithoutHost, true);
}
if (tNode.stylesWithoutHost != null && hasStyleInput(tNode)) {
setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.stylesWithoutHost, false);
}
}
/**
* Creates an empty element using {\@link elementStart} and {\@link elementEnd}
*
* \@codeGenApi
* @param {?} index Index of the element in the data array
* @param {?} name Name of the DOM Node
* @param {?=} attrsIndex Index of the element's attributes in the `consts` array.
* @param {?=} localRefsIndex Index of the element's local references in the `consts` array.
*
* @return {?}
*/
function ɵɵelement(index, name, attrsIndex, localRefsIndex) {
ɵɵelementStart(index, name, attrsIndex, localRefsIndex);
ɵɵelementEnd();
}
/**
* @param {?} tView
* @param {?} lView
* @param {?} element
* @param {?} tNode
* @param {?} hasDirectives
* @return {?}
*/
function warnAboutUnknownElement(tView, lView, element, tNode, hasDirectives) {
/** @type {?} */
const schemas = tView.schemas;
// If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
// mode where this check happens at compile time. In JIT mode, `schemas` is always present and
// defined as an array (as an empty array in case `schemas` field is not defined) and we should
// execute the check below.
if (schemas === null)
return;
/** @type {?} */
const tagName = tNode.tagName;
// If the element matches any directive, it's considered as valid.
if (!hasDirectives && tagName !== null) {
// The element is unknown if it's an instance of HTMLUnknownElement or it isn't registered
// as a custom element. Note that unknown elements with a dash in their name won't be instances
// of HTMLUnknownElement in browsers that support web components.
/** @type {?} */
const isUnknown =
// Note that we can't check for `typeof HTMLUnknownElement === 'function'`,
// because while most browsers return 'function', IE returns 'object'.
(typeof HTMLUnknownElement !== 'undefined' && HTMLUnknownElement &&
element instanceof HTMLUnknownElement) ||
(typeof customElements !== 'undefined' && tagName.indexOf('-') > -1 &&
!customElements.get(tagName));
if (isUnknown && !matchingSchemas(tView, lView, tagName)) {
/** @type {?} */
let warning = `'${tagName}' is not a known element:\n`;
warning += `1. If '${tagName}' is an Angular component, then verify that it is part of this module.\n`;
if (tagName && tagName.indexOf('-') > -1) {
warning += `2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`;
}
else {
warning +=
`2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
}
console.warn(warning);
}
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/element_container.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} index
* @param {?} tView
* @param {?} lView
* @param {?=} attrsIndex
* @param {?=} localRefsIndex
* @return {?}
*/
function elementContainerStartFirstCreatePass(index, tView, lView, attrsIndex, localRefsIndex) {
ngDevMode && ngDevMode.firstCreatePass++;
/** @type {?} */
const tViewConsts = tView.consts;
/** @type {?} */
const attrs = getConstant(tViewConsts, attrsIndex);
/** @type {?} */
const tNode = getOrCreateTNode(tView, lView[T_HOST], index, 4 /* ElementContainer */, 'ng-container', attrs);
// While ng-container doesn't necessarily support styling, we use the style context to identify
// and execute directives on the ng-container.
if (attrs !== null) {
computeStaticStyling(tNode, attrs, true);
}
/** @type {?} */
const localRefs = getConstant(tViewConsts, localRefsIndex);
resolveDirectives(tView, lView, tNode, localRefs);
if (tView.queries !== null) {
tView.queries.elementStart(tView, tNode);
}
return tNode;
}
/**
* Creates a logical container for other nodes (<ng-container>) backed by a comment node in the DOM.
* The instruction must later be followed by `elementContainerEnd()` call.
*
* \@codeGenApi
* @param {?} index Index of the element in the LView array
* @param {?=} attrsIndex Index of the container attributes in the `consts` array.
* @param {?=} localRefsIndex Index of the container's local references in the `consts` array.
*
* Even if this instruction accepts a set of attributes no actual attribute values are propagated to
* the DOM (as a comment node can't have attributes). Attributes are here only for directive
* matching purposes and setting initial inputs of directives.
*
* @return {?}
*/
function ɵɵelementContainerStart(index, attrsIndex, localRefsIndex) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
/** @type {?} */
const adjustedIndex = index + HEADER_OFFSET;
ngDevMode && assertDataInRange(lView, adjustedIndex);
ngDevMode &&
assertEqual(getBindingIndex(), tView.bindingStartIndex, 'element containers should be created before any bindings');
/** @type {?} */
const tNode = tView.firstCreatePass ?
elementContainerStartFirstCreatePass(index, tView, lView, attrsIndex, localRefsIndex) :
(/** @type {?} */ (tView.data[adjustedIndex]));
setPreviousOrParentTNode(tNode, true);
ngDevMode && ngDevMode.rendererCreateComment++;
/** @type {?} */
const native = lView[adjustedIndex] =
lView[RENDERER].createComment(ngDevMode ? 'ng-container' : '');
appendChild(tView, lView, native, tNode);
attachPatchData(native, lView);
if (isDirectiveHost(tNode)) {
createDirectivesInstances(tView, lView, tNode);
executeContentQueries(tView, tNode, lView);
}
if (localRefsIndex != null) {
saveResolvedLocalsInData(lView, tNode);
}
}
/**
* Mark the end of the <ng-container>.
*
* \@codeGenApi
* @return {?}
*/
function ɵɵelementContainerEnd() {
/** @type {?} */
let previousOrParentTNode = getPreviousOrParentTNode();
/** @type {?} */
const tView = getTView();
if (getIsParent()) {
setIsNotParent();
}
else {
ngDevMode && assertHasParent(previousOrParentTNode);
previousOrParentTNode = (/** @type {?} */ (previousOrParentTNode.parent));
setPreviousOrParentTNode(previousOrParentTNode, false);
}
ngDevMode && assertNodeType(previousOrParentTNode, 4 /* ElementContainer */);
if (tView.firstCreatePass) {
registerPostOrderHooks(tView, previousOrParentTNode);
if (isContentQueryHost(previousOrParentTNode)) {
(/** @type {?} */ (tView.queries)).elementEnd(previousOrParentTNode);
}
}
}
/**
* Creates an empty logical container using {\@link elementContainerStart}
* and {\@link elementContainerEnd}
*
* \@codeGenApi
* @param {?} index Index of the element in the LView array
* @param {?=} attrsIndex Index of the container attributes in the `consts` array.
* @param {?=} localRefsIndex Index of the container's local references in the `consts` array.
*
* @return {?}
*/
function ɵɵelementContainer(index, attrsIndex, localRefsIndex) {
ɵɵelementContainerStart(index, attrsIndex, localRefsIndex);
ɵɵelementContainerEnd();
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/get_current_view.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Returns the current OpaqueViewState instance.
*
* Used in conjunction with the restoreView() instruction to save a snapshot
* of the current view and restore it when listeners are invoked. This allows
* walking the declaration view tree in listeners to get vars from parent views.
*
* \@codeGenApi
* @return {?}
*/
function ɵɵgetCurrentView() {
return (/** @type {?} */ ((/** @type {?} */ (getLView()))));
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Determine if the argument is shaped like a Promise
*/
function isPromise(obj) {
// allow any Promise/A+ compliant thenable.
// It's up to the caller to ensure that obj.then conforms to the spec
return !!obj && typeof obj.then === 'function';
}
/**
* Determine if the argument is an Observable
*/
function isObservable(obj) {
// TODO: use isObservable once we update pass rxjs 6.1
// https://github.com/ReactiveX/rxjs/blob/master/CHANGELOG.md#610-2018-05-03
return !!obj && typeof obj.subscribe === 'function';
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/listener.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Adds an event listener to the current node.
*
* If an output exists on one of the node's directives, it also subscribes to the output
* and saves the subscription for later cleanup.
*
* \@codeGenApi
* @param {?} eventName Name of the event
* @param {?} listenerFn The function to be called when event emits
* @param {?=} useCapture Whether or not to use capture in event listener
* @param {?=} eventTargetResolver Function that returns global target information in case this listener
* should be attached to a global object like window, document or body
*
* @return {?}
*/
function ɵɵlistener(eventName, listenerFn, useCapture = false, eventTargetResolver) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getPreviousOrParentTNode();
listenerInternal(tView, lView, lView[RENDERER], tNode, eventName, listenerFn, useCapture, eventTargetResolver);
return ɵɵlistener;
}
/**
* Registers a synthetic host listener (e.g. `(\@foo.start)`) on a component or directive.
*
* This instruction is for compatibility purposes and is designed to ensure that a
* synthetic host listener (e.g. `\@HostListener('\@foo.start')`) properly gets rendered
* in the component's renderer. Normally all host listeners are evaluated with the
* parent component's renderer, but, in the case of animation \@triggers, they need
* to be evaluated with the sub component's renderer (because that's where the
* animation triggers are defined).
*
* Do not use this instruction as a replacement for `listener`. This instruction
* only exists to ensure compatibility with the ViewEngine's host binding behavior.
*
* \@codeGenApi
* @param {?} eventName Name of the event
* @param {?} listenerFn The function to be called when event emits
* @param {?=} useCapture Whether or not to use capture in event listener
* @param {?=} eventTargetResolver Function that returns global target information in case this listener
* should be attached to a global object like window, document or body
*
* @return {?}
*/
function ɵɵcomponentHostSyntheticListener(eventName, listenerFn, useCapture = false, eventTargetResolver) {
/** @type {?} */
const tNode = getPreviousOrParentTNode();
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
/** @type {?} */
const currentDef = getCurrentDirectiveDef(tView.data);
/** @type {?} */
const renderer = loadComponentRenderer(currentDef, tNode, lView);
listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn, useCapture, eventTargetResolver);
return ɵɵcomponentHostSyntheticListener;
}
/**
* A utility function that checks if a given element has already an event handler registered for an
* event with a specified name. The TView.cleanup data structure is used to find out which events
* are registered for a given element.
* @param {?} tView
* @param {?} lView
* @param {?} eventName
* @param {?} tNodeIdx
* @return {?}
*/
function findExistingListener(tView, lView, eventName, tNodeIdx) {
/** @type {?} */
const tCleanup = tView.cleanup;
if (tCleanup != null) {
for (let i = 0; i < tCleanup.length - 1; i += 2) {
/** @type {?} */
const cleanupEventName = tCleanup[i];
if (cleanupEventName === eventName && tCleanup[i + 1] === tNodeIdx) {
// We have found a matching event name on the same node but it might not have been
// registered yet, so we must explicitly verify entries in the LView cleanup data
// structures.
/** @type {?} */
const lCleanup = (/** @type {?} */ (lView[CLEANUP]));
/** @type {?} */
const listenerIdxInLCleanup = tCleanup[i + 2];
return lCleanup.length > listenerIdxInLCleanup ? lCleanup[listenerIdxInLCleanup] : null;
}
// TView.cleanup can have a mix of 4-elements entries (for event handler cleanups) or
// 2-element entries (for directive and queries destroy hooks). As such we can encounter
// blocks of 4 or 2 items in the tView.cleanup and this is why we iterate over 2 elements
// first and jump another 2 elements if we detect listeners cleanup (4 elements). Also check
// documentation of TView.cleanup for more details of this data structure layout.
if (typeof cleanupEventName === 'string') {
i += 2;
}
}
}
return null;
}
/**
* @param {?} tView
* @param {?} lView
* @param {?} renderer
* @param {?} tNode
* @param {?} eventName
* @param {?} listenerFn
* @param {?=} useCapture
* @param {?=} eventTargetResolver
* @return {?}
*/
function listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn, useCapture = false, eventTargetResolver) {
/** @type {?} */
const isTNodeDirectiveHost = isDirectiveHost(tNode);
/** @type {?} */
const firstCreatePass = tView.firstCreatePass;
/** @type {?} */
const tCleanup = firstCreatePass && (tView.cleanup || (tView.cleanup = []));
// When the ɵɵlistener instruction was generated and is executed we know that there is either a
// native listener or a directive output on this element. As such we we know that we will have to
// register a listener and store its cleanup function on LView.
/** @type {?} */
const lCleanup = getLCleanup(lView);
ngDevMode &&
assertNodeOfPossibleTypes(tNode, 3 /* Element */, 0 /* Container */, 4 /* ElementContainer */);
/** @type {?} */
let processOutputs = true;
// add native event listener - applicable to elements only
if (tNode.type === 3 /* Element */) {
/** @type {?} */
const native = (/** @type {?} */ (getNativeByTNode(tNode, lView)));
/** @type {?} */
const resolved = eventTargetResolver ? eventTargetResolver(native) : (/** @type {?} */ (EMPTY_OBJ));
/** @type {?} */
const target = resolved.target || native;
/** @type {?} */
const lCleanupIndex = lCleanup.length;
/** @type {?} */
const idxOrTargetGetter = eventTargetResolver ?
(/**
* @param {?} _lView
* @return {?}
*/
(_lView) => eventTargetResolver(unwrapRNode(_lView[tNode.index])).target) :
tNode.index;
// In order to match current behavior, native DOM event listeners must be added for all
// events (including outputs).
if (isProceduralRenderer(renderer)) {
// There might be cases where multiple directives on the same element try to register an event
// handler function for the same event. In this situation we want to avoid registration of
// several native listeners as each registration would be intercepted by NgZone and
// trigger change detection. This would mean that a single user action would result in several
// change detections being invoked. To avoid this situation we want to have only one call to
// native handler registration (for the same element and same type of event).
//
// In order to have just one native event handler in presence of multiple handler functions,
// we just register a first handler function as a native event listener and then chain
// (coalesce) other handler functions on top of the first native handler function.
/** @type {?} */
let existingListener = null;
// Please note that the coalescing described here doesn't happen for events specifying an
// alternative target (ex. (document:click)) - this is to keep backward compatibility with the
// view engine.
// Also, we don't have to search for existing listeners is there are no directives
// matching on a given node as we can't register multiple event handlers for the same event in
// a template (this would mean having duplicate attributes).
if (!eventTargetResolver && isTNodeDirectiveHost) {
existingListener = findExistingListener(tView, lView, eventName, tNode.index);
}
if (existingListener !== null) {
// Attach a new listener to coalesced listeners list, maintaining the order in which
// listeners are registered. For performance reasons, we keep a reference to the last
// listener in that list (in `__ngLastListenerFn__` field), so we can avoid going through
// the entire set each time we need to add a new listener.
/** @type {?} */
const lastListenerFn = ((/** @type {?} */ (existingListener))).__ngLastListenerFn__ || existingListener;
lastListenerFn.__ngNextListenerFn__ = listenerFn;
((/** @type {?} */ (existingListener))).__ngLastListenerFn__ = listenerFn;
processOutputs = false;
}
else {
// The first argument of `listen` function in Procedural Renderer is:
// - either a target name (as a string) in case of global target (window, document, body)
// - or element reference (in all other cases)
listenerFn = wrapListener(tNode, lView, listenerFn, false /** preventDefault */);
/** @type {?} */
const cleanupFn = renderer.listen(resolved.name || target, eventName, listenerFn);
ngDevMode && ngDevMode.rendererAddEventListener++;
lCleanup.push(listenerFn, cleanupFn);
tCleanup && tCleanup.push(eventName, idxOrTargetGetter, lCleanupIndex, lCleanupIndex + 1);
}
}
else {
listenerFn = wrapListener(tNode, lView, listenerFn, true /** preventDefault */);
target.addEventListener(eventName, listenerFn, useCapture);
ngDevMode && ngDevMode.rendererAddEventListener++;
lCleanup.push(listenerFn);
tCleanup && tCleanup.push(eventName, idxOrTargetGetter, lCleanupIndex, useCapture);
}
}
// subscribe to directive outputs
/** @type {?} */
const outputs = tNode.outputs;
/** @type {?} */
let props;
if (processOutputs && outputs !== null && (props = outputs[eventName])) {
/** @type {?} */
const propsLength = props.length;
if (propsLength) {
for (let i = 0; i < propsLength; i += 2) {
/** @type {?} */
const index = (/** @type {?} */ (props[i]));
ngDevMode && assertDataInRange(lView, index);
/** @type {?} */
const minifiedName = props[i + 1];
/** @type {?} */
const directiveInstance = lView[index];
/** @type {?} */
const output = directiveInstance[minifiedName];
if (ngDevMode && !isObservable(output)) {
throw new Error(`@Output ${minifiedName} not initialized in '${directiveInstance.constructor.name}'.`);
}
/** @type {?} */
const subscription = output.subscribe(listenerFn);
/** @type {?} */
const idx = lCleanup.length;
lCleanup.push(listenerFn, subscription);
tCleanup && tCleanup.push(eventName, tNode.index, idx, -(idx + 1));
}
}
}
}
/**
* @param {?} lView
* @param {?} listenerFn
* @param {?} e
* @return {?}
*/
function executeListenerWithErrorHandling(lView, listenerFn, e) {
try {
// Only explicitly returning false from a listener should preventDefault
return listenerFn(e) !== false;
}
catch (error) {
handleError(lView, error);
return false;
}
}
/**
* Wraps an event listener with a function that marks ancestors dirty and prevents default behavior,
* if applicable.
*
* @param {?} tNode The TNode associated with this listener
* @param {?} lView The LView that contains this listener
* @param {?} listenerFn The listener function to call
* @param {?} wrapWithPreventDefault Whether or not to prevent default behavior
* (the procedural renderer does this already, so in those cases, we should skip)
* @return {?}
*/
function wrapListener(tNode, lView, listenerFn, wrapWithPreventDefault) {
// Note: we are performing most of the work in the listener function itself
// to optimize listener registration.
return (/**
* @param {?} e
* @return {?}
*/
function wrapListenerIn_markDirtyAndPreventDefault(e) {
// Ivy uses `Function` as a special token that allows us to unwrap the function
// so that it can be invoked programmatically by `DebugNode.triggerEventHandler`.
if (e === Function) {
return listenerFn;
}
// In order to be backwards compatible with View Engine, events on component host nodes
// must also mark the component view itself dirty (i.e. the view that it owns).
/** @type {?} */
const startView = tNode.flags & 2 /* isComponentHost */ ?
getComponentLViewByIndex(tNode.index, lView) :
lView;
// See interfaces/view.ts for more on LViewFlags.ManualOnPush
if ((lView[FLAGS] & 32 /* ManualOnPush */) === 0) {
markViewDirty(startView);
}
/** @type {?} */
let result = executeListenerWithErrorHandling(lView, listenerFn, e);
// A just-invoked listener function might have coalesced listeners so we need to check for
// their presence and invoke as needed.
/** @type {?} */
let nextListenerFn = ((/** @type {?} */ (wrapListenerIn_markDirtyAndPreventDefault))).__ngNextListenerFn__;
while (nextListenerFn) {
// We should prevent default if any of the listeners explicitly return false
result = executeListenerWithErrorHandling(lView, nextListenerFn, e) && result;
nextListenerFn = ((/** @type {?} */ (nextListenerFn))).__ngNextListenerFn__;
}
if (wrapWithPreventDefault && result === false) {
e.preventDefault();
// Necessary for legacy browsers that don't support preventDefault (e.g. IE)
e.returnValue = false;
}
return result;
});
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/namespace.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/next_context.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Retrieves a context at the level specified and saves it as the global, contextViewData.
* Will get the next level up if level is not specified.
*
* This is used to save contexts of parent views so they can be bound in embedded views, or
* in conjunction with reference() to bind a ref from a parent view.
*
* \@codeGenApi
* @template T
* @param {?=} level The relative level of the view from which to grab context compared to contextVewData
* @return {?} context
*
*/
function ɵɵnextContext(level = 1) {
return nextContextImpl(level);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/projection.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Checks a given node against matching projection slots and returns the
* determined slot index. Returns "null" if no slot matched the given node.
*
* This function takes into account the parsed ngProjectAs selector from the
* node's attributes. If present, it will check whether the ngProjectAs selector
* matches any of the projection slot selectors.
* @param {?} tNode
* @param {?} projectionSlots
* @return {?}
*/
function matchingProjectionSlotIndex(tNode, projectionSlots) {
/** @type {?} */
let wildcardNgContentIndex = null;
/** @type {?} */
const ngProjectAsAttrVal = getProjectAsAttrValue(tNode);
for (let i = 0; i < projectionSlots.length; i++) {
/** @type {?} */
const slotValue = projectionSlots[i];
// The last wildcard projection slot should match all nodes which aren't matching
// any selector. This is necessary to be backwards compatible with view engine.
if (slotValue === '*') {
wildcardNgContentIndex = i;
continue;
}
// If we ran into an `ngProjectAs` attribute, we should match its parsed selector
// to the list of selectors, otherwise we fall back to matching against the node.
if (ngProjectAsAttrVal === null ?
isNodeMatchingSelectorList(tNode, slotValue, /* isProjectionMode */ true) :
isSelectorInSelectorList(ngProjectAsAttrVal, slotValue)) {
return i; // first matching selector "captures" a given node
}
}
return wildcardNgContentIndex;
}
/**
* Instruction to distribute projectable nodes among <ng-content> occurrences in a given template.
* It takes all the selectors from the entire component's template and decides where
* each projected node belongs (it re-distributes nodes among "buckets" where each "bucket" is
* backed by a selector).
*
* This function requires CSS selectors to be provided in 2 forms: parsed (by a compiler) and text,
* un-parsed form.
*
* The parsed form is needed for efficient matching of a node against a given CSS selector.
* The un-parsed, textual form is needed for support of the ngProjectAs attribute.
*
* Having a CSS selector in 2 different formats is not ideal, but alternatives have even more
* drawbacks:
* - having only a textual form would require runtime parsing of CSS selectors;
* - we can't have only a parsed as we can't re-construct textual form from it (as entered by a
* template author).
*
* \@codeGenApi
* @param {?=} projectionSlots
* @return {?}
*/
function ɵɵprojectionDef(projectionSlots) {
/** @type {?} */
const componentNode = (/** @type {?} */ (getLView()[DECLARATION_COMPONENT_VIEW][T_HOST]));
if (!componentNode.projection) {
// If no explicit projection slots are defined, fall back to a single
// projection slot with the wildcard selector.
/** @type {?} */
const numProjectionSlots = projectionSlots ? projectionSlots.length : 1;
/** @type {?} */
const projectionHeads = componentNode.projection =
newArray(numProjectionSlots, (/** @type {?} */ ((/** @type {?} */ (null)))));
/** @type {?} */
const tails = projectionHeads.slice();
/** @type {?} */
let componentChild = componentNode.child;
while (componentChild !== null) {
/** @type {?} */
const slotIndex = projectionSlots ? matchingProjectionSlotIndex(componentChild, projectionSlots) : 0;
if (slotIndex !== null) {
if (tails[slotIndex]) {
(/** @type {?} */ (tails[slotIndex])).projectionNext = componentChild;
}
else {
projectionHeads[slotIndex] = componentChild;
}
tails[slotIndex] = componentChild;
}
componentChild = componentChild.next;
}
}
}
/** @type {?} */
let delayProjection = false;
/**
* @param {?} value
* @return {?}
*/
function setDelayProjection(value) {
delayProjection = value;
}
/**
* Inserts previously re-distributed projected nodes. This instruction must be preceded by a call
* to the projectionDef instruction.
*
* \@codeGenApi
* @param {?} nodeIndex
* @param {?=} selectorIndex
* @param {?=} attrs
* @return {?}
*/
function ɵɵprojection(nodeIndex, selectorIndex = 0, attrs) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tProjectionNode = getOrCreateTNode(tView, lView[T_HOST], nodeIndex, 1 /* Projection */, null, attrs || null);
// We can't use viewData[HOST_NODE] because projection nodes can be nested in embedded views.
if (tProjectionNode.projection === null)
tProjectionNode.projection = selectorIndex;
// `<ng-content>` has no content
setIsNotParent();
// We might need to delay the projection of nodes if they are in the middle of an i18n block
if (!delayProjection) {
// re-distribution of projectable nodes is stored on a component's view level
applyProjection(tView, lView, tProjectionNode);
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/property_interpolation.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
*
* Update an interpolated property on an element with a lone bound value
*
* Used when the value passed to a property has 1 interpolated value in it, an no additional text
* surrounds that interpolated value:
*
* ```html
* <div title="{{v0}}"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵpropertyInterpolate('title', v0);
* ```
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled.
*
* \@codeGenApi
* @param {?} propName The name of the property to update
* @param {?} v0 Value checked for change.
* @param {?=} sanitizer An optional sanitizer function
* @return {?} itself, so that it may be chained.
*/
function ɵɵpropertyInterpolate(propName, v0, sanitizer) {
ɵɵpropertyInterpolate1(propName, '', v0, '', sanitizer);
return ɵɵpropertyInterpolate;
}
/**
*
* Update an interpolated property on an element with single bound value surrounded by text.
*
* Used when the value passed to a property has 1 interpolated value in it:
*
* ```html
* <div title="prefix{{v0}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵpropertyInterpolate1('title', 'prefix', v0, 'suffix');
* ```
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled.
*
* \@codeGenApi
* @param {?} propName The name of the property to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @return {?} itself, so that it may be chained.
*/
function ɵɵpropertyInterpolate1(propName, prefix, v0, suffix, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
ngDevMode &&
storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 1, prefix, suffix);
}
return ɵɵpropertyInterpolate1;
}
/**
*
* Update an interpolated property on an element with 2 bound values surrounded by text.
*
* Used when the value passed to a property has 2 interpolated values in it:
*
* ```html
* <div title="prefix{{v0}}-{{v1}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵpropertyInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
* ```
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled.
*
* \@codeGenApi
* @param {?} propName The name of the property to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @return {?} itself, so that it may be chained.
*/
function ɵɵpropertyInterpolate2(propName, prefix, v0, i0, v1, suffix, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
ngDevMode &&
storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 2, prefix, i0, suffix);
}
return ɵɵpropertyInterpolate2;
}
/**
*
* Update an interpolated property on an element with 3 bound values surrounded by text.
*
* Used when the value passed to a property has 3 interpolated values in it:
*
* ```html
* <div title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵpropertyInterpolate3(
* 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
* ```
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled.
*
* \@codeGenApi
* @param {?} propName The name of the property to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @return {?} itself, so that it may be chained.
*/
function ɵɵpropertyInterpolate3(propName, prefix, v0, i0, v1, i1, v2, suffix, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
ngDevMode &&
storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 3, prefix, i0, i1, suffix);
}
return ɵɵpropertyInterpolate3;
}
/**
*
* Update an interpolated property on an element with 4 bound values surrounded by text.
*
* Used when the value passed to a property has 4 interpolated values in it:
*
* ```html
* <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵpropertyInterpolate4(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
* ```
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled.
*
* \@codeGenApi
* @param {?} propName The name of the property to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @return {?} itself, so that it may be chained.
*/
function ɵɵpropertyInterpolate4(propName, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
ngDevMode &&
storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix);
}
return ɵɵpropertyInterpolate4;
}
/**
*
* Update an interpolated property on an element with 5 bound values surrounded by text.
*
* Used when the value passed to a property has 5 interpolated values in it:
*
* ```html
* <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵpropertyInterpolate5(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
* ```
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled.
*
* \@codeGenApi
* @param {?} propName The name of the property to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @return {?} itself, so that it may be chained.
*/
function ɵɵpropertyInterpolate5(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
ngDevMode &&
storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix);
}
return ɵɵpropertyInterpolate5;
}
/**
*
* Update an interpolated property on an element with 6 bound values surrounded by text.
*
* Used when the value passed to a property has 6 interpolated values in it:
*
* ```html
* <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵpropertyInterpolate6(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
* ```
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled.
*
* \@codeGenApi
* @param {?} propName The name of the property to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @return {?} itself, so that it may be chained.
*/
function ɵɵpropertyInterpolate6(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
ngDevMode &&
storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix);
}
return ɵɵpropertyInterpolate6;
}
/**
*
* Update an interpolated property on an element with 7 bound values surrounded by text.
*
* Used when the value passed to a property has 7 interpolated values in it:
*
* ```html
* <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵpropertyInterpolate7(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
* ```
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled.
*
* \@codeGenApi
* @param {?} propName The name of the property to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} i5 Static value used for concatenation only.
* @param {?} v6 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @return {?} itself, so that it may be chained.
*/
function ɵɵpropertyInterpolate7(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
ngDevMode &&
storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix);
}
return ɵɵpropertyInterpolate7;
}
/**
*
* Update an interpolated property on an element with 8 bound values surrounded by text.
*
* Used when the value passed to a property has 8 interpolated values in it:
*
* ```html
* <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵpropertyInterpolate8(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
* ```
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled.
*
* \@codeGenApi
* @param {?} propName The name of the property to update
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} i5 Static value used for concatenation only.
* @param {?} v6 Value checked for change.
* @param {?} i6 Static value used for concatenation only.
* @param {?} v7 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} sanitizer An optional sanitizer function
* @return {?} itself, so that it may be chained.
*/
function ɵɵpropertyInterpolate8(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
ngDevMode &&
storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix);
}
return ɵɵpropertyInterpolate8;
}
/**
* Update an interpolated property on an element with 9 or more bound values surrounded by text.
*
* Used when the number of interpolated values exceeds 8.
*
* ```html
* <div
* title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵpropertyInterpolateV(
* 'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
* 'suffix']);
* ```
*
* If the property name also exists as an input property on one of the element's directives,
* the component property will be set instead of the element property. This check must
* be conducted at runtime so child components that add new `\@Inputs` don't have to be re-compiled.
*
* \@codeGenApi
* @param {?} propName The name of the property to update.
* @param {?} values The collection of values and the strings inbetween those values, beginning with a
* string prefix and ending with a string suffix.
* (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
* @param {?=} sanitizer An optional sanitizer function
* @return {?} itself, so that it may be chained.
*/
function ɵɵpropertyInterpolateV(propName, values, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolationV(lView, values);
if (interpolatedValue !== NO_CHANGE) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
if (ngDevMode) {
/** @type {?} */
const interpolationInBetween = [values[0]];
for (let i = 2; i < values.length; i += 2) {
interpolationInBetween.push(values[i]);
}
storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween);
}
}
return ɵɵpropertyInterpolateV;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This file contains reuseable "empty" symbols that can be used as default return values
* in different parts of the rendering code. Because the same symbols are returned, this
* allows for identity checks against these values to be consistently used by the framework
* code.
*/
const EMPTY_OBJ$1 = {};
const EMPTY_ARRAY$3 = [];
// freezing the values prevents any code from accidentally inserting new values in
if ((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode()) {
// These property accesses can be ignored because ngDevMode will be set to false
// when optimizing code and the whole if statement will be dropped.
// tslint:disable-next-line:no-toplevel-property-access
Object.freeze(EMPTY_OBJ$1);
// tslint:disable-next-line:no-toplevel-property-access
Object.freeze(EMPTY_ARRAY$3);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/styling/style_binding_list.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* NOTE: The word `styling` is used interchangeably as style or class styling.
*
* This file contains code to link styling instructions together so that they can be replayed in
* priority order. The file exists because Ivy styling instruction execution order does not match
* that of the priority order. The purpose of this code is to create a linked list so that the
* instructions can be traversed in priority order when computing the styles.
*
* Assume we are dealing with the following code:
* ```
* \@Component({
* template: `
* <my-cmp [style]=" {color: '#001'} "
* [style.color]=" #002 "
* dir-style-color-1
* dir-style-color-2> `
* })
* class ExampleComponent {
* static ngComp = ... {
* ...
* // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
* ɵɵstyleMap({color: '#001'});
* ɵɵstyleProp('color', '#002');
* ...
* }
* }
*
* \@Directive({
* selector: `[dir-style-color-1]',
* })
* class Style1Directive {
* \@HostBinding('style') style = {color: '#005'};
* \@HostBinding('style.color') color = '#006';
*
* static ngDir = ... {
* ...
* // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
* ɵɵstyleMap({color: '#005'});
* ɵɵstyleProp('color', '#006');
* ...
* }
* }
*
* \@Directive({
* selector: `[dir-style-color-2]',
* })
* class Style2Directive {
* \@HostBinding('style') style = {color: '#007'};
* \@HostBinding('style.color') color = '#008';
*
* static ngDir = ... {
* ...
* // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
* ɵɵstyleMap({color: '#007'});
* ɵɵstyleProp('color', '#008');
* ...
* }
* }
*
* \@Directive({
* selector: `my-cmp',
* })
* class MyComponent {
* \@HostBinding('style') style = {color: '#003'};
* \@HostBinding('style.color') color = '#004';
*
* static ngComp = ... {
* ...
* // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
* ɵɵstyleMap({color: '#003'});
* ɵɵstyleProp('color', '#004');
* ...
* }
* }
* ```
*
* The Order of instruction execution is:
*
* NOTE: the comment binding location is for illustrative purposes only.
*
* ```
* // Template: (ExampleComponent)
* ɵɵstyleMap({color: '#001'}); // Binding index: 10
* ɵɵstyleProp('color', '#002'); // Binding index: 12
* // MyComponent
* ɵɵstyleMap({color: '#003'}); // Binding index: 20
* ɵɵstyleProp('color', '#004'); // Binding index: 22
* // Style1Directive
* ɵɵstyleMap({color: '#005'}); // Binding index: 24
* ɵɵstyleProp('color', '#006'); // Binding index: 26
* // Style2Directive
* ɵɵstyleMap({color: '#007'}); // Binding index: 28
* ɵɵstyleProp('color', '#008'); // Binding index: 30
* ```
*
* The correct priority order of concatenation is:
*
* ```
* // MyComponent
* ɵɵstyleMap({color: '#003'}); // Binding index: 20
* ɵɵstyleProp('color', '#004'); // Binding index: 22
* // Style1Directive
* ɵɵstyleMap({color: '#005'}); // Binding index: 24
* ɵɵstyleProp('color', '#006'); // Binding index: 26
* // Style2Directive
* ɵɵstyleMap({color: '#007'}); // Binding index: 28
* ɵɵstyleProp('color', '#008'); // Binding index: 30
* // Template: (ExampleComponent)
* ɵɵstyleMap({color: '#001'}); // Binding index: 10
* ɵɵstyleProp('color', '#002'); // Binding index: 12
* ```
*
* What color should be rendered?
*
* Once the items are correctly sorted in the list, the answer is simply the last item in the
* concatenation list which is `#002`.
*
* To do so we keep a linked list of all of the bindings which pertain to this element.
* Notice that the bindings are inserted in the order of execution, but the `TView.data` allows
* us to traverse them in the order of priority.
*
* |Idx|`TView.data`|`LView` | Notes
* |---|------------|-----------------|--------------
* |...| | |
* |10 |`null` |`{color: '#001'}`| `ɵɵstyleMap('color', {color: '#001'})`
* |11 |`30 | 12` | ... |
* |12 |`color` |`'#002'` | `ɵɵstyleProp('color', '#002')`
* |13 |`10 | 0` | ... |
* |...| | |
* |20 |`null` |`{color: '#003'}`| `ɵɵstyleMap('color', {color: '#003'})`
* |21 |`0 | 22` | ... |
* |22 |`color` |`'#004'` | `ɵɵstyleProp('color', '#004')`
* |23 |`20 | 24` | ... |
* |24 |`null` |`{color: '#005'}`| `ɵɵstyleMap('color', {color: '#005'})`
* |25 |`22 | 26` | ... |
* |26 |`color` |`'#006'` | `ɵɵstyleProp('color', '#006')`
* |27 |`24 | 28` | ... |
* |28 |`null` |`{color: '#007'}`| `ɵɵstyleMap('color', {color: '#007'})`
* |29 |`26 | 30` | ... |
* |30 |`color` |`'#008'` | `ɵɵstyleProp('color', '#008')`
* |31 |`28 | 10` | ... |
*
* The above data structure allows us to re-concatenate the styling no matter which data binding
* changes.
*
* NOTE: in addition to keeping track of next/previous index the `TView.data` also stores prev/next
* duplicate bit. The duplicate bit if true says there either is a binding with the same name or
* there is a map (which may contain the name). This information is useful in knowing if other
* styles with higher priority need to be searched for overwrites.
*
* NOTE: See `should support example in 'tnode_linked_list.ts' documentation` in
* `tnode_linked_list_spec.ts` for working example.
* @type {?}
*/
let __unused_const_as_closure_does_not_like_standalone_comment_blocks__;
/**
* Insert new `tStyleValue` at `TData` and link existing style bindings such that we maintain linked
* list of styles and compute the duplicate flag.
*
* Note: this function is executed during `firstUpdatePass` only to populate the `TView.data`.
*
* The function works by keeping track of `tStylingRange` which contains two pointers pointing to
* the head/tail of the template portion of the styles.
* - if `isHost === false` (we are template) then insertion is at tail of `TStylingRange`
* - if `isHost === true` (we are host binding) then insertion is at head of `TStylingRange`
*
* @param {?} tData The `TData` to insert into.
* @param {?} tNode `TNode` associated with the styling element.
* @param {?} tStylingKeyWithStatic
* @param {?} index location of where `tStyleValue` should be stored (and linked into list.)
* @param {?} isHostBinding `true` if the insertion is for a `hostBinding`. (insertion is in front of
* template.)
* @param {?} isClassBinding True if the associated `tStylingKey` as a `class` styling.
* `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
* @return {?}
*/
function insertTStylingBinding(tData, tNode, tStylingKeyWithStatic, index, isHostBinding, isClassBinding) {
ngDevMode && assertFirstUpdatePass(getTView());
/** @type {?} */
let tBindings = isClassBinding ? tNode.classBindings : tNode.styleBindings;
/** @type {?} */
let tmplHead = getTStylingRangePrev(tBindings);
/** @type {?} */
let tmplTail = getTStylingRangeNext(tBindings);
tData[index] = tStylingKeyWithStatic;
/** @type {?} */
let isKeyDuplicateOfStatic = false;
/** @type {?} */
let tStylingKey;
if (Array.isArray(tStylingKeyWithStatic)) {
// We are case when the `TStylingKey` contains static fields as well.
/** @type {?} */
const staticKeyValueArray = (/** @type {?} */ (tStylingKeyWithStatic));
tStylingKey = staticKeyValueArray[1]; // unwrap.
// We need to check if our key is present in the static so that we can mark it as duplicate.
if (tStylingKey === null ||
keyValueArrayIndexOf(staticKeyValueArray, (/** @type {?} */ (tStylingKey))) > 0) {
// tStylingKey is present in the statics, need to mark it as duplicate.
isKeyDuplicateOfStatic = true;
}
}
else {
tStylingKey = tStylingKeyWithStatic;
}
if (isHostBinding) {
// We are inserting host bindings
// If we don't have template bindings then `tail` is 0.
/** @type {?} */
const hasTemplateBindings = tmplTail !== 0;
// This is important to know because that means that the `head` can't point to the first
// template bindings (there are none.) Instead the head points to the tail of the template.
if (hasTemplateBindings) {
// template head's "prev" will point to last host binding or to 0 if no host bindings yet
/** @type {?} */
const previousNode = getTStylingRangePrev((/** @type {?} */ (tData[tmplHead + 1])));
tData[index + 1] = toTStylingRange(previousNode, tmplHead);
// if a host binding has already been registered, we need to update the next of that host
// binding to point to this one
if (previousNode !== 0) {
// We need to update the template-tail value to point to us.
tData[previousNode + 1] =
setTStylingRangeNext((/** @type {?} */ (tData[previousNode + 1])), index);
}
// The "previous" of the template binding head should point to this host binding
tData[tmplHead + 1] = setTStylingRangePrev((/** @type {?} */ (tData[tmplHead + 1])), index);
}
else {
tData[index + 1] = toTStylingRange(tmplHead, 0);
// if a host binding has already been registered, we need to update the next of that host
// binding to point to this one
if (tmplHead !== 0) {
// We need to update the template-tail value to point to us.
tData[tmplHead + 1] = setTStylingRangeNext((/** @type {?} */ (tData[tmplHead + 1])), index);
}
// if we don't have template, the head points to template-tail, and needs to be advanced.
tmplHead = index;
}
}
else {
// We are inserting in template section.
// We need to set this binding's "previous" to the current template tail
tData[index + 1] = toTStylingRange(tmplTail, 0);
ngDevMode &&
assertEqual(tmplHead !== 0 && tmplTail === 0, false, 'Adding template bindings after hostBindings is not allowed.');
if (tmplHead === 0) {
tmplHead = index;
}
else {
// We need to update the previous value "next" to point to this binding
tData[tmplTail + 1] = setTStylingRangeNext((/** @type {?} */ (tData[tmplTail + 1])), index);
}
tmplTail = index;
}
// Now we need to update / compute the duplicates.
// Starting with our location search towards head (least priority)
if (isKeyDuplicateOfStatic) {
tData[index + 1] = setTStylingRangePrevDuplicate((/** @type {?} */ (tData[index + 1])));
}
markDuplicates(tData, tStylingKey, index, true, isClassBinding);
markDuplicates(tData, tStylingKey, index, false, isClassBinding);
markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding);
tBindings = toTStylingRange(tmplHead, tmplTail);
if (isClassBinding) {
tNode.classBindings = tBindings;
}
else {
tNode.styleBindings = tBindings;
}
}
/**
* Look into the residual styling to see if the current `tStylingKey` is duplicate of residual.
*
* @param {?} tNode `TNode` where the residual is stored.
* @param {?} tStylingKey `TStylingKey` to store.
* @param {?} tData `TData` associated with the current `LView`.
* @param {?} index location of where `tStyleValue` should be stored (and linked into list.)
* @param {?} isClassBinding True if the associated `tStylingKey` as a `class` styling.
* `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
* @return {?}
*/
function markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding) {
/** @type {?} */
const residual = isClassBinding ? tNode.residualClasses : tNode.residualStyles;
if (residual != null /* or undefined */ && typeof tStylingKey == 'string' &&
keyValueArrayIndexOf(residual, tStylingKey) >= 0) {
// We have duplicate in the residual so mark ourselves as duplicate.
tData[index + 1] = setTStylingRangeNextDuplicate((/** @type {?} */ (tData[index + 1])));
}
}
/**
* Marks `TStyleValue`s as duplicates if another style binding in the list has the same
* `TStyleValue`.
*
* NOTE: this function is intended to be called twice once with `isPrevDir` set to `true` and once
* with it set to `false` to search both the previous as well as next items in the list.
*
* No duplicate case
* ```
* [style.color]
* [style.width.px] <<- index
* [style.height.px]
* ```
*
* In the above case adding `[style.width.px]` to the existing `[style.color]` produces no
* duplicates because `width` is not found in any other part of the linked list.
*
* Duplicate case
* ```
* [style.color]
* [style.width.em]
* [style.width.px] <<- index
* ```
* In the above case adding `[style.width.px]` will produce a duplicate with `[style.width.em]`
* because `width` is found in the chain.
*
* Map case 1
* ```
* [style.width.px]
* [style.color]
* [style] <<- index
* ```
* In the above case adding `[style]` will produce a duplicate with any other bindings because
* `[style]` is a Map and as such is fully dynamic and could produce `color` or `width`.
*
* Map case 2
* ```
* [style]
* [style.width.px]
* [style.color] <<- index
* ```
* In the above case adding `[style.color]` will produce a duplicate because there is already a
* `[style]` binding which is a Map and as such is fully dynamic and could produce `color` or
* `width`.
*
* NOTE: Once `[style]` (Map) is added into the system all things are mapped as duplicates.
* NOTE: We use `style` as example, but same logic is applied to `class`es as well.
*
* @param {?} tData `TData` where the linked list is stored.
* @param {?} tStylingKey `TStylingKeyPrimitive` which contains the value to compare to other keys in
* the linked list.
* @param {?} index Starting location in the linked list to search from
* @param {?} isPrevDir Direction.
* - `true` for previous (lower priority);
* - `false` for next (higher priority).
* @param {?} isClassBinding
* @return {?}
*/
function markDuplicates(tData, tStylingKey, index, isPrevDir, isClassBinding) {
/** @type {?} */
const tStylingAtIndex = (/** @type {?} */ (tData[index + 1]));
/** @type {?} */
const isMap = tStylingKey === null;
/** @type {?} */
let cursor = isPrevDir ? getTStylingRangePrev(tStylingAtIndex) : getTStylingRangeNext(tStylingAtIndex);
/** @type {?} */
let foundDuplicate = false;
// We keep iterating as long as we have a cursor
// AND either:
// - we found what we are looking for, OR
// - we are a map in which case we have to continue searching even after we find what we were
// looking for since we are a wild card and everything needs to be flipped to duplicate.
while (cursor !== 0 && (foundDuplicate === false || isMap)) {
ngDevMode && assertDataInRange(tData, cursor);
/** @type {?} */
const tStylingValueAtCursor = (/** @type {?} */ (tData[cursor]));
/** @type {?} */
const tStyleRangeAtCursor = (/** @type {?} */ (tData[cursor + 1]));
if (isStylingMatch(tStylingValueAtCursor, tStylingKey)) {
foundDuplicate = true;
tData[cursor + 1] = isPrevDir ? setTStylingRangeNextDuplicate(tStyleRangeAtCursor) :
setTStylingRangePrevDuplicate(tStyleRangeAtCursor);
}
cursor = isPrevDir ? getTStylingRangePrev(tStyleRangeAtCursor) :
getTStylingRangeNext(tStyleRangeAtCursor);
}
if (foundDuplicate) {
// if we found a duplicate, than mark ourselves.
tData[index + 1] = isPrevDir ? setTStylingRangePrevDuplicate(tStylingAtIndex) :
setTStylingRangeNextDuplicate(tStylingAtIndex);
}
}
/**
* Determines if two `TStylingKey`s are a match.
*
* When computing weather a binding contains a duplicate, we need to compare if the instruction
* `TStylingKey` has a match.
*
* Here are examples of `TStylingKey`s which match given `tStylingKeyCursor` is:
* - `color`
* - `color` // Match another color
* - `null` // That means that `tStylingKey` is a `classMap`/`styleMap` instruction
* - `['', 'color', 'other', true]` // wrapped `color` so match
* - `['', null, 'other', true]` // wrapped `null` so match
* - `['', 'width', 'color', 'value']` // wrapped static value contains a match on `'color'`
* - `null` // `tStylingKeyCursor` always match as it is `classMap`/`styleMap` instruction
*
* @param {?} tStylingKeyCursor
* @param {?} tStylingKey
* @return {?}
*/
function isStylingMatch(tStylingKeyCursor, tStylingKey) {
ngDevMode &&
assertNotEqual(Array.isArray(tStylingKey), true, 'Expected that \'tStylingKey\' has been unwrapped');
if (tStylingKeyCursor === null || // If the cursor is `null` it means that we have map at that
// location so we must assume that we have a match.
tStylingKey == null || // If `tStylingKey` is `null` then it is a map therefor assume that it
// contains a match.
(Array.isArray(tStylingKeyCursor) ? tStylingKeyCursor[1] : tStylingKeyCursor) ===
tStylingKey // If the keys match explicitly than we are a match.
) {
return true;
}
else if (Array.isArray(tStylingKeyCursor) && typeof tStylingKey === 'string') {
// if we did not find a match, but `tStylingKeyCursor` is `KeyValueArray` that means cursor has
// statics and we need to check those as well.
return keyValueArrayIndexOf(tStylingKeyCursor, tStylingKey) >=
0; // see if we are matching the key
}
return false;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/styling/styling_parser.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Stores the locations of key/value indexes while parsing styling.
*
* In case of `cssText` parsing the indexes are like so:
* ```
* "key1: value1; key2: value2; key3: value3"
* ^ ^ ^ ^ ^
* | | | | +-- textEnd
* | | | +---------------- valueEnd
* | | +---------------------- value
* | +------------------------ keyEnd
* +---------------------------- key
* ```
*
* In case of `className` parsing the indexes are like so:
* ```
* "key1 key2 key3"
* ^ ^ ^
* | | +-- textEnd
* | +------------------------ keyEnd
* +---------------------------- key
* ```
* NOTE: `value` and `valueEnd` are used only for styles, not classes.
* @record
*/
function ParserState() { }
if (false) {}
// Global state of the parser. (This makes parser non-reentrant, but that is not an issue)
/** @type {?} */
const parserState = {
textEnd: 0,
key: 0,
keyEnd: 0,
value: 0,
valueEnd: 0,
};
/**
* Retrieves the last parsed `key` of style.
* @param {?} text the text to substring the key from.
* @return {?}
*/
function getLastParsedKey(text) {
return text.substring(parserState.key, parserState.keyEnd);
}
/**
* Retrieves the last parsed `value` of style.
* @param {?} text the text to substring the key from.
* @return {?}
*/
function getLastParsedValue(text) {
return text.substring(parserState.value, parserState.valueEnd);
}
/**
* Initializes `className` string for parsing and parses the first token.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
* const key = getLastParsedKey();
* ...
* }
* ```
* @param {?} text `className` to parse
* @return {?} index where the next invocation of `parseClassNameNext` should resume.
*/
function parseClassName(text) {
resetParserState(text);
return parseClassNameNext(text, consumeWhitespace(text, 0, parserState.textEnd));
}
/**
* Parses next `className` token.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
* const key = getLastParsedKey();
* ...
* }
* ```
*
* @param {?} text `className` to parse
* @param {?} index where the parsing should resume.
* @return {?} index where the next invocation of `parseClassNameNext` should resume.
*/
function parseClassNameNext(text, index) {
/** @type {?} */
const end = parserState.textEnd;
if (end === index) {
return -1;
}
index = parserState.keyEnd = consumeClassToken(text, parserState.key = index, end);
return consumeWhitespace(text, index, end);
}
/**
* Initializes `cssText` string for parsing and parses the first key/values.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
* const key = getLastParsedKey();
* const value = getLastParsedValue();
* ...
* }
* ```
* @param {?} text `cssText` to parse
* @return {?} index where the next invocation of `parseStyleNext` should resume.
*/
function parseStyle(text) {
resetParserState(text);
return parseStyleNext(text, consumeWhitespace(text, 0, parserState.textEnd));
}
/**
* Parses the next `cssText` key/values.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
* const key = getLastParsedKey();
* const value = getLastParsedValue();
* ...
* }
*
* @param {?} text `cssText` to parse
* @param {?} startIndex
* @return {?} index where the next invocation of `parseStyleNext` should resume.
*/
function parseStyleNext(text, startIndex) {
/** @type {?} */
const end = parserState.textEnd;
/** @type {?} */
let index = parserState.key = consumeWhitespace(text, startIndex, end);
if (end === index) {
// we reached an end so just quit
return -1;
}
index = parserState.keyEnd = consumeStyleKey(text, index, end);
index = consumeSeparator(text, index, end, 58 /* COLON */);
index = parserState.value = consumeWhitespace(text, index, end);
index = parserState.valueEnd = consumeStyleValue(text, index, end);
return consumeSeparator(text, index, end, 59 /* SEMI_COLON */);
}
/**
* Reset the global state of the styling parser.
* @param {?} text The styling text to parse.
* @return {?}
*/
function resetParserState(text) {
parserState.key = 0;
parserState.keyEnd = 0;
parserState.value = 0;
parserState.valueEnd = 0;
parserState.textEnd = text.length;
}
/**
* Returns index of next non-whitespace character.
*
* @param {?} text Text to scan
* @param {?} startIndex Starting index of character where the scan should start.
* @param {?} endIndex Ending index of character where the scan should end.
* @return {?} Index of next non-whitespace character (May be the same as `start` if no whitespace at
* that location.)
*/
function consumeWhitespace(text, startIndex, endIndex) {
while (startIndex < endIndex && text.charCodeAt(startIndex) <= 32 /* SPACE */) {
startIndex++;
}
return startIndex;
}
/**
* Returns index of last char in class token.
*
* @param {?} text Text to scan
* @param {?} startIndex Starting index of character where the scan should start.
* @param {?} endIndex Ending index of character where the scan should end.
* @return {?} Index after last char in class token.
*/
function consumeClassToken(text, startIndex, endIndex) {
while (startIndex < endIndex && text.charCodeAt(startIndex) > 32 /* SPACE */) {
startIndex++;
}
return startIndex;
}
/**
* Consumes all of the characters belonging to style key and token.
*
* @param {?} text Text to scan
* @param {?} startIndex Starting index of character where the scan should start.
* @param {?} endIndex Ending index of character where the scan should end.
* @return {?} Index after last style key character.
*/
function consumeStyleKey(text, startIndex, endIndex) {
/** @type {?} */
let ch;
while (startIndex < endIndex &&
((ch = text.charCodeAt(startIndex)) === 45 /* DASH */ || ch === 95 /* UNDERSCORE */ ||
((ch & -33 /* UPPER_CASE */) >= 65 /* A */ && (ch & -33 /* UPPER_CASE */) <= 90 /* Z */))) {
startIndex++;
}
return startIndex;
}
/**
* Consumes all whitespace and the separator `:` after the style key.
*
* @param {?} text Text to scan
* @param {?} startIndex Starting index of character where the scan should start.
* @param {?} endIndex Ending index of character where the scan should end.
* @param {?} separator
* @return {?} Index after separator and surrounding whitespace.
*/
function consumeSeparator(text, startIndex, endIndex, separator) {
startIndex = consumeWhitespace(text, startIndex, endIndex);
if (startIndex < endIndex) {
if (ngDevMode && text.charCodeAt(startIndex) !== separator) {
malformedStyleError(text, String.fromCharCode(separator), startIndex);
}
startIndex++;
}
return startIndex;
}
/**
* Consumes style value honoring `url()` and `""` text.
*
* @param {?} text Text to scan
* @param {?} startIndex Starting index of character where the scan should start.
* @param {?} endIndex Ending index of character where the scan should end.
* @return {?} Index after last style value character.
*/
function consumeStyleValue(text, startIndex, endIndex) {
/** @type {?} */
let ch1 = -1;
// 1st previous character
/** @type {?} */
let ch2 = -1;
// 2nd previous character
/** @type {?} */
let ch3 = -1;
// 3rd previous character
/** @type {?} */
let i = startIndex;
/** @type {?} */
let lastChIndex = i;
while (i < endIndex) {
/** @type {?} */
const ch = text.charCodeAt(i++);
if (ch === 59 /* SEMI_COLON */) {
return lastChIndex;
}
else if (ch === 34 /* DOUBLE_QUOTE */ || ch === 39 /* SINGLE_QUOTE */) {
lastChIndex = i = consumeQuotedText(text, ch, i, endIndex);
}
else if (startIndex ===
i - 4 && // We have seen only 4 characters so far "URL(" (Ignore "foo_URL()")
ch3 === 85 /* U */ &&
ch2 === 82 /* R */ && ch1 === 76 /* L */ && ch === 40 /* OPEN_PAREN */) {
lastChIndex = i = consumeQuotedText(text, 41 /* CLOSE_PAREN */, i, endIndex);
}
else if (ch > 32 /* SPACE */) {
// if we have a non-whitespace character then capture its location
lastChIndex = i;
}
ch3 = ch2;
ch2 = ch1;
ch1 = ch & -33 /* UPPER_CASE */;
}
return lastChIndex;
}
/**
* Consumes all of the quoted characters.
*
* @param {?} text Text to scan
* @param {?} quoteCharCode CharCode of either `"` or `'` quote or `)` for `url(...)`.
* @param {?} startIndex Starting index of character where the scan should start.
* @param {?} endIndex Ending index of character where the scan should end.
* @return {?} Index after quoted characters.
*/
function consumeQuotedText(text, quoteCharCode, startIndex, endIndex) {
/** @type {?} */
let ch1 = -1;
// 1st previous character
/** @type {?} */
let index = startIndex;
while (index < endIndex) {
/** @type {?} */
const ch = text.charCodeAt(index++);
if (ch == quoteCharCode && ch1 !== 92 /* BACK_SLASH */) {
return index;
}
if (ch == 92 /* BACK_SLASH */ && ch1 === 92 /* BACK_SLASH */) {
// two back slashes cancel each other out. For example `"\\"` should properly end the
// quotation. (It should not assume that the last `"` is escaped.)
ch1 = 0;
}
else {
ch1 = ch;
}
}
throw ngDevMode ? malformedStyleError(text, String.fromCharCode(quoteCharCode), endIndex) :
new Error();
}
/**
* @param {?} text
* @param {?} expecting
* @param {?} index
* @return {?}
*/
function malformedStyleError(text, expecting, index) {
ngDevMode && assertEqual(typeof text === 'string', true, 'String expected here');
throw throwError(`Malformed style at location ${index} in string '` + text.substring(0, index) + '[>>' +
text.substring(index, index + 1) + '<<]' + text.substr(index + 1) +
`'. Expecting '${expecting}'.`);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/styling.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Sets the current style sanitizer function which will then be used
* within all follow-up prop and map-based style binding instructions
* for the given element.
*
* Note that once styling has been applied to the element (i.e. once
* `advance(n)` is executed or the hostBindings/template function exits)
* then the active `sanitizerFn` will be set to `null`. This means that
* once styling is applied to another element then a another call to
* `styleSanitizer` will need to be made.
*
* \@codeGenApi
* @param {?} sanitizer
* @return {?}
*/
function ɵɵstyleSanitizer(sanitizer) {
setCurrentStyleSanitizer(sanitizer);
}
/**
* Update a style binding on an element with the provided value.
*
* If the style value is falsy then it will be removed from the element
* (or assigned a different value depending if there are any styles placed
* on the element with `styleMap` or any static styles that are
* present from when the element was created with `styling`).
*
* Note that the styling element is updated as part of `stylingApply`.
*
* \@codeGenApi
* @param {?} prop A valid CSS property.
* @param {?} value New value to write (`null` or an empty string to remove).
* @param {?=} suffix Optional suffix. Used with scalar values to add unit such as `px`.
* Note that when a suffix is provided then the underlying sanitizer will
* be ignored.
*
* Note that this will apply the provided style value to the host element if this function is called
* within a host binding function.
*
* @return {?}
*/
function ɵɵstyleProp(prop, value, suffix) {
checkStylingProperty(prop, value, suffix, false);
return ɵɵstyleProp;
}
/**
* Update a class binding on an element with the provided value.
*
* This instruction is meant to handle the `[class.foo]="exp"` case and,
* therefore, the class binding itself must already be allocated using
* `styling` within the creation block.
*
* \@codeGenApi
* @param {?} className
* @param {?} value A true/false value which will turn the class on or off.
*
* Note that this will apply the provided class value to the host element if this function
* is called within a host binding function.
*
* @return {?}
*/
function ɵɵclassProp(className, value) {
checkStylingProperty(className, value, null, true);
return ɵɵclassProp;
}
/**
* Update style bindings using an object literal on an element.
*
* This instruction is meant to apply styling via the `[style]="exp"` template bindings.
* When styles are applied to the element they will then be updated with respect to
* any styles/classes set via `styleProp`. If any styles are set to falsy
* then they will be removed from the element.
*
* Note that the styling instruction will not be applied until `stylingApply` is called.
*
* \@codeGenApi
* @param {?} styles A key/value style map of the styles that will be applied to the given element.
* Any missing styles (that have already been applied to the element beforehand) will be
* removed (unset) from the element's styling.
*
* Note that this will apply the provided styleMap value to the host element if this function
* is called within a host binding.
*
* @return {?}
*/
function ɵɵstyleMap(styles) {
checkStylingMap(styleKeyValueArraySet, styleStringParser, styles, false);
}
/**
* Parse text as style and add values to KeyValueArray.
*
* This code is pulled out to a separate function so that it can be tree shaken away if it is not
* needed. It is only referenced from `ɵɵstyleMap`.
*
* @param {?} keyValueArray KeyValueArray to add parsed values to.
* @param {?} text text to parse.
* @return {?}
*/
function styleStringParser(keyValueArray, text) {
for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i)) {
styleKeyValueArraySet(keyValueArray, getLastParsedKey(text), getLastParsedValue(text));
}
}
/**
* Update class bindings using an object literal or class-string on an element.
*
* This instruction is meant to apply styling via the `[class]="exp"` template bindings.
* When classes are applied to the element they will then be updated with
* respect to any styles/classes set via `classProp`. If any
* classes are set to falsy then they will be removed from the element.
*
* Note that the styling instruction will not be applied until `stylingApply` is called.
* Note that this will the provided classMap value to the host element if this function is called
* within a host binding.
*
* \@codeGenApi
* @param {?} classes A key/value map or string of CSS classes that will be added to the
* given element. Any missing classes (that have already been applied to the element
* beforehand) will be removed (unset) from the element's list of CSS classes.
*
* @return {?}
*/
function ɵɵclassMap(classes) {
checkStylingMap(keyValueArraySet, classStringParser, classes, true);
}
/**
* Parse text as class and add values to KeyValueArray.
*
* This code is pulled out to a separate function so that it can be tree shaken away if it is not
* needed. It is only referenced from `ɵɵclassMap`.
*
* @param {?} keyValueArray KeyValueArray to add parsed values to.
* @param {?} text text to parse.
* @return {?}
*/
function classStringParser(keyValueArray, text) {
for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
keyValueArraySet(keyValueArray, getLastParsedKey(text), true);
}
}
/**
* Common code between `ɵɵclassProp` and `ɵɵstyleProp`.
*
* @param {?} prop property name.
* @param {?} value binding value.
* @param {?} suffixOrSanitizer suffix or sanitization function
* @param {?} isClassBased `true` if `class` change (`false` if `style`)
* @return {?}
*/
function checkStylingProperty(prop, value, suffixOrSanitizer, isClassBased) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
// Styling instructions use 2 slots per binding.
// 1. one for the value / TStylingKey
// 2. one for the intermittent-value / TStylingRange
/** @type {?} */
const bindingIndex = incrementBindingIndex(2);
if (tView.firstUpdatePass) {
stylingFirstUpdatePass(tView, prop, bindingIndex, isClassBased);
}
if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) {
// This is a work around. Once PR#34480 lands the sanitizer is passed explicitly and this line
// can be removed.
/** @type {?} */
let styleSanitizer;
if (suffixOrSanitizer == null) {
if (styleSanitizer = getCurrentStyleSanitizer()) {
suffixOrSanitizer = (/** @type {?} */ (styleSanitizer));
}
}
/** @type {?} */
const tNode = (/** @type {?} */ (tView.data[getSelectedIndex() + HEADER_OFFSET]));
updateStyling(tView, tNode, lView, lView[RENDERER], prop, lView[bindingIndex + 1] = normalizeAndApplySuffixOrSanitizer(value, suffixOrSanitizer), isClassBased, bindingIndex);
}
}
/**
* Common code between `ɵɵclassMap` and `ɵɵstyleMap`.
*
* @param {?} keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a
* function so that
* `style` can pass in version which does sanitization. This is done for tree shaking
* purposes.
* @param {?} stringParser Parser used to parse `value` if `string`. (Passed in as `style` and `class`
* have different parsers.)
* @param {?} value bound value from application
* @param {?} isClassBased `true` if `class` change (`false` if `style`)
* @return {?}
*/
function checkStylingMap(keyValueArraySet, stringParser, value, isClassBased) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const bindingIndex = incrementBindingIndex(2);
if (tView.firstUpdatePass) {
stylingFirstUpdatePass(tView, null, bindingIndex, isClassBased);
}
/** @type {?} */
const lView = getLView();
if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) {
// `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the
// if so as not to read unnecessarily.
/** @type {?} */
const tNode = (/** @type {?} */ (tView.data[getSelectedIndex() + HEADER_OFFSET]));
if (hasStylingInputShadow(tNode, isClassBased) && !isInHostBindings(tView, bindingIndex)) {
if (ngDevMode) {
// verify that if we are shadowing then `TData` is appropriately marked so that we skip
// processing this binding in styling resolution.
/** @type {?} */
const tStylingKey = tView.data[bindingIndex];
assertEqual(Array.isArray(tStylingKey) ? tStylingKey[1] : tStylingKey, false, 'Styling linked list shadow input should be marked as \'false\'');
}
// VE does not concatenate the static portion like we are doing here.
// Instead VE just ignores the static completely if dynamic binding is present.
// Because of locality we have already set the static portion because we don't know if there
// is a dynamic portion until later. If we would ignore the static portion it would look like
// the binding has removed it. This would confuse `[ngStyle]`/`[ngClass]` to do the wrong
// thing as it would think that the static portion was removed. For this reason we
// concatenate it so that `[ngStyle]`/`[ngClass]` can continue to work on changed.
/** @type {?} */
let staticPrefix = isClassBased ? tNode.classesWithoutHost : tNode.stylesWithoutHost;
ngDevMode && isClassBased === false && staticPrefix !== null &&
assertEqual(staticPrefix.endsWith(';'), true, 'Expecting static portion to end with \';\'');
if (staticPrefix !== null) {
// We want to make sure that falsy values of `value` become empty strings.
value = concatStringsWithSpace(staticPrefix, value ? value : '');
}
// Given `<div [style] my-dir>` such that `my-dir` has `@Input('style')`.
// This takes over the `[style]` binding. (Same for `[class]`)
setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased);
}
else {
updateStylingMap(tView, tNode, lView, lView[RENDERER], lView[bindingIndex + 1], lView[bindingIndex + 1] = toStylingKeyValueArray(keyValueArraySet, stringParser, value), isClassBased, bindingIndex);
}
}
}
/**
* Determines when the binding is in `hostBindings` section
*
* @param {?} tView Current `TView`
* @param {?} bindingIndex index of binding which we would like if it is in `hostBindings`
* @return {?}
*/
function isInHostBindings(tView, bindingIndex) {
// All host bindings are placed after the expando section.
return bindingIndex >= tView.expandoStartIndex;
}
/**
* Collects the necessary information to insert the binding into a linked list of style bindings
* using `insertTStylingBinding`.
*
* @param {?} tView `TView` where the binding linked list will be stored.
* @param {?} tStylingKey Property/key of the binding.
* @param {?} bindingIndex Index of binding associated with the `prop`
* @param {?} isClassBased `true` if `class` change (`false` if `style`)
* @return {?}
*/
function stylingFirstUpdatePass(tView, tStylingKey, bindingIndex, isClassBased) {
ngDevMode && assertFirstUpdatePass(tView);
/** @type {?} */
const tData = tView.data;
if (tData[bindingIndex + 1] === null) {
// The above check is necessary because we don't clear first update pass until first successful
// (no exception) template execution. This prevents the styling instruction from double adding
// itself to the list.
// `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the
// if so as not to read unnecessarily.
/** @type {?} */
const tNode = (/** @type {?} */ (tData[getSelectedIndex() + HEADER_OFFSET]));
/** @type {?} */
const isHostBindings = isInHostBindings(tView, bindingIndex);
if (hasStylingInputShadow(tNode, isClassBased) && tStylingKey === null && !isHostBindings) {
// `tStylingKey === null` implies that we are either `[style]` or `[class]` binding.
// If there is a directive which uses `@Input('style')` or `@Input('class')` than
// we need to neutralize this binding since that directive is shadowing it.
// We turn this into a noop by setting the key to `false`
tStylingKey = false;
}
tStylingKey = wrapInStaticStylingKey(tData, tNode, tStylingKey, isClassBased);
insertTStylingBinding(tData, tNode, tStylingKey, bindingIndex, isHostBindings, isClassBased);
}
}
/**
* Adds static styling information to the binding if applicable.
*
* The linked list of styles not only stores the list and keys, but also stores static styling
* information on some of the keys. This function determines if the key should contain the styling
* information and computes it.
*
* See `TStylingStatic` for more details.
*
* @param {?} tData `TData` where the linked list is stored.
* @param {?} tNode `TNode` for which the styling is being computed.
* @param {?} stylingKey `TStylingKeyPrimitive` which may need to be wrapped into `TStylingKey`
* @param {?} isClassBased `true` if `class` (`false` if `style`)
* @return {?}
*/
function wrapInStaticStylingKey(tData, tNode, stylingKey, isClassBased) {
/** @type {?} */
const hostDirectiveDef = getCurrentDirectiveDef(tData);
/** @type {?} */
let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
if (hostDirectiveDef === null) {
// We are in template node.
// If template node already had styling instruction then it has already collected the static
// styling and there is no need to collect them again. We know that we are the first styling
// instruction because the `TNode.*Bindings` points to 0 (nothing has been inserted yet).
/** @type {?} */
const isFirstStylingInstructionInTemplate = (/** @type {?} */ ((/** @type {?} */ ((isClassBased ? tNode.classBindings : tNode.styleBindings))))) === 0;
if (isFirstStylingInstructionInTemplate) {
// It would be nice to be able to get the statics from `mergeAttrs`, however, at this point
// they are already merged and it would not be possible to figure which property belongs where
// in the priority.
stylingKey = collectStylingFromDirectives(null, tData, tNode, stylingKey, isClassBased);
stylingKey = collectStylingFromTAttrs(stylingKey, tNode.attrs, isClassBased);
// We know that if we have styling binding in template we can't have residual.
residual = null;
}
}
else {
// We are in host binding node and there was no binding instruction in template node.
// This means that we need to compute the residual.
/** @type {?} */
const directiveStylingLast = tNode.directiveStylingLast;
/** @type {?} */
const isFirstStylingInstructionInHostBinding = directiveStylingLast === -1 || tData[directiveStylingLast] !== hostDirectiveDef;
if (isFirstStylingInstructionInHostBinding) {
stylingKey =
collectStylingFromDirectives(hostDirectiveDef, tData, tNode, stylingKey, isClassBased);
if (residual === null) {
// - If `null` than either:
// - Template styling instruction already ran and it has consumed the static
// styling into its `TStylingKey` and so there is no need to update residual. Instead
// we need to update the `TStylingKey` associated with the first template node
// instruction. OR
// - Some other styling instruction ran and determined that there are no residuals
/** @type {?} */
let templateStylingKey = getTemplateHeadTStylingKey(tData, tNode, isClassBased);
if (templateStylingKey !== undefined && Array.isArray(templateStylingKey)) {
// Only recompute if `templateStylingKey` had static values. (If no static value found
// then there is nothing to do since this operation can only produce less static keys, not
// more.)
templateStylingKey = collectStylingFromDirectives(null, tData, tNode, templateStylingKey[1] /* unwrap previous statics */, isClassBased);
templateStylingKey =
collectStylingFromTAttrs(templateStylingKey, tNode.attrs, isClassBased);
setTemplateHeadTStylingKey(tData, tNode, isClassBased, templateStylingKey);
}
}
else {
// We only need to recompute residual if it is not `null`.
// - If existing residual (implies there was no template styling). This means that some of
// the statics may have moved from the residual to the `stylingKey` and so we have to
// recompute.
// - If `undefined` this is the first time we are running.
residual = collectResidual(tData, tNode, isClassBased);
}
}
}
if (residual !== undefined) {
isClassBased ? (tNode.residualClasses = residual) : (tNode.residualStyles = residual);
}
return stylingKey;
}
/**
* Retrieve the `TStylingKey` for the template styling instruction.
*
* This is needed since `hostBinding` styling instructions are inserted after the template
* instruction. While the template instruction needs to update the residual in `TNode` the
* `hostBinding` instructions need to update the `TStylingKey` of the template instruction because
* the template instruction is downstream from the `hostBindings` instructions.
*
* @param {?} tData `TData` where the linked list is stored.
* @param {?} tNode `TNode` for which the styling is being computed.
* @param {?} isClassBased `true` if `class` (`false` if `style`)
* @return {?} `TStylingKey` if found or `undefined` if not found.
*/
function getTemplateHeadTStylingKey(tData, tNode, isClassBased) {
/** @type {?} */
const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
if (getTStylingRangeNext(bindings) === 0) {
// There does not seem to be a styling instruction in the `template`.
return undefined;
}
return (/** @type {?} */ (tData[getTStylingRangePrev(bindings)]));
}
/**
* Update the `TStylingKey` of the first template instruction in `TNode`.
*
* Logically `hostBindings` styling instructions are of lower priority than that of the template.
* However, they execute after the template styling instructions. This means that they get inserted
* in front of the template styling instructions.
*
* If we have a template styling instruction and a new `hostBindings` styling instruction is
* executed it means that it may need to steal static fields from the template instruction. This
* method allows us to update the first template instruction `TStylingKey` with a new value.
*
* Assume:
* ```
* <div my-dir style="color: red" [style.color]="tmplExp"></div>
*
* \@Directive({
* host: {
* 'style': 'width: 100px',
* '[style.color]': 'dirExp',
* }
* })
* class MyDir {}
* ```
*
* when `[style.color]="tmplExp"` executes it creates this data structure.
* ```
* ['', 'color', 'color', 'red', 'width', '100px'],
* ```
*
* The reason for this is that the template instruction does not know if there are styling
* instructions and must assume that there are none and must collect all of the static styling.
* (both
* `color' and 'width`)
*
* When `'[style.color]': 'dirExp',` executes we need to insert a new data into the linked list.
* ```
* ['', 'color', 'width', '100px'], // newly inserted
* ['', 'color', 'color', 'red', 'width', '100px'], // this is wrong
* ```
*
* Notice that the template statics is now wrong as it incorrectly contains `width` so we need to
* update it like so:
* ```
* ['', 'color', 'width', '100px'],
* ['', 'color', 'color', 'red'], // UPDATE
* ```
*
* @param {?} tData `TData` where the linked list is stored.
* @param {?} tNode `TNode` for which the styling is being computed.
* @param {?} isClassBased `true` if `class` (`false` if `style`)
* @param {?} tStylingKey New `TStylingKey` which is replacing the old one.
* @return {?}
*/
function setTemplateHeadTStylingKey(tData, tNode, isClassBased, tStylingKey) {
/** @type {?} */
const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
ngDevMode &&
assertNotEqual(getTStylingRangeNext(bindings), 0, 'Expecting to have at least one template styling binding.');
tData[getTStylingRangePrev(bindings)] = tStylingKey;
}
/**
* Collect all static values after the current `TNode.directiveStylingLast` index.
*
* Collect the remaining styling information which has not yet been collected by an existing
* styling instruction.
*
* @param {?} tData `TData` where the `DirectiveDefs` are stored.
* @param {?} tNode `TNode` which contains the directive range.
* @param {?} isClassBased `true` if `class` (`false` if `style`)
* @return {?}
*/
function collectResidual(tData, tNode, isClassBased) {
/** @type {?} */
let residual = undefined;
/** @type {?} */
const directiveEnd = tNode.directiveEnd;
ngDevMode &&
assertNotEqual(tNode.directiveStylingLast, -1, 'By the time this function gets called at least one hostBindings-node styling instruction must have executed.');
// We add `1 + tNode.directiveStart` because we need to skip the current directive (as we are
// collecting things after the last `hostBindings` directive which had a styling instruction.)
for (let i = 1 + tNode.directiveStylingLast; i < directiveEnd; i++) {
/** @type {?} */
const attrs = ((/** @type {?} */ (tData[i]))).hostAttrs;
residual = (/** @type {?} */ (collectStylingFromTAttrs(residual, attrs, isClassBased)));
}
return (/** @type {?} */ (collectStylingFromTAttrs(residual, tNode.attrs, isClassBased)));
}
/**
* Collect the static styling information with lower priority than `hostDirectiveDef`.
*
* (This is opposite of residual styling.)
*
* @param {?} hostDirectiveDef `DirectiveDef` for which we want to collect lower priority static
* styling. (Or `null` if template styling)
* @param {?} tData `TData` where the linked list is stored.
* @param {?} tNode `TNode` for which the styling is being computed.
* @param {?} stylingKey Existing `TStylingKey` to update or wrap.
* @param {?} isClassBased `true` if `class` (`false` if `style`)
* @return {?}
*/
function collectStylingFromDirectives(hostDirectiveDef, tData, tNode, stylingKey, isClassBased) {
// We need to loop because there can be directives which have `hostAttrs` but don't have
// `hostBindings` so this loop catches up to the current directive..
/** @type {?} */
let currentDirective = null;
/** @type {?} */
const directiveEnd = tNode.directiveEnd;
/** @type {?} */
let directiveStylingLast = tNode.directiveStylingLast;
if (directiveStylingLast === -1) {
directiveStylingLast = tNode.directiveStart;
}
else {
directiveStylingLast++;
}
while (directiveStylingLast < directiveEnd) {
currentDirective = (/** @type {?} */ (tData[directiveStylingLast]));
ngDevMode && assertDefined(currentDirective, 'expected to be defined');
stylingKey = collectStylingFromTAttrs(stylingKey, currentDirective.hostAttrs, isClassBased);
if (currentDirective === hostDirectiveDef)
break;
directiveStylingLast++;
}
if (hostDirectiveDef !== null) {
// we only advance the styling cursor if we are collecting data from host bindings.
// Template executes before host bindings and so if we would update the index,
// host bindings would not get their statics.
tNode.directiveStylingLast = directiveStylingLast;
}
return stylingKey;
}
/**
* Convert `TAttrs` into `TStylingStatic`.
*
* @param {?} stylingKey existing `TStylingKey` to update or wrap.
* @param {?} attrs `TAttributes` to process.
* @param {?} isClassBased `true` if `class` (`false` if `style`)
* @return {?}
*/
function collectStylingFromTAttrs(stylingKey, attrs, isClassBased) {
/** @type {?} */
const desiredMarker = isClassBased ? 1 /* Classes */ : 2 /* Styles */;
/** @type {?} */
let currentMarker = -1 /* ImplicitAttributes */;
if (attrs !== null) {
for (let i = 0; i < attrs.length; i++) {
/** @type {?} */
const item = (/** @type {?} */ (attrs[i]));
if (typeof item === 'number') {
currentMarker = item;
}
else {
if (currentMarker === desiredMarker) {
if (!Array.isArray(stylingKey)) {
stylingKey = stylingKey === undefined ? [] : (/** @type {?} */ (['', stylingKey]));
}
keyValueArraySet((/** @type {?} */ (stylingKey)), item, isClassBased ? true : attrs[++i]);
}
}
}
}
return stylingKey === undefined ? null : stylingKey;
}
/**
* Convert user input to `KeyValueArray`.
*
* This function takes user input which could be `string`, Object literal, or iterable and converts
* it into a consistent representation. The output of this is `KeyValueArray` (which is an array
* where
* even indexes contain keys and odd indexes contain values for those keys).
*
* The advantage of converting to `KeyValueArray` is that we can perform diff in an input
* independent
* way.
* (ie we can compare `foo bar` to `['bar', 'baz'] and determine a set of changes which need to be
* applied)
*
* The fact that `KeyValueArray` is sorted is very important because it allows us to compute the
* difference in linear fashion without the need to allocate any additional data.
*
* For example if we kept this as a `Map` we would have to iterate over previous `Map` to determine
* which values need to be deleted, over the new `Map` to determine additions, and we would have to
* keep additional `Map` to keep track of duplicates or items which have not yet been visited.
*
* @param {?} keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a
* function so that
* `style` can pass in version which does sanitization. This is done for tree shaking
* purposes.
* @param {?} stringParser The parser is passed in so that it will be tree shakable. See
* `styleStringParser` and `classStringParser`
* @param {?} value The value to parse/convert to `KeyValueArray`
* @return {?}
*/
function toStylingKeyValueArray(keyValueArraySet, stringParser, value) {
if (value == null /*|| value === undefined */ || value === '')
return (/** @type {?} */ (EMPTY_ARRAY$3));
/** @type {?} */
const styleKeyValueArray = (/** @type {?} */ ([]));
/** @type {?} */
const unwrappedValue = (/** @type {?} */ (unwrapSafeValue(value)));
if (Array.isArray(unwrappedValue)) {
for (let i = 0; i < unwrappedValue.length; i++) {
keyValueArraySet(styleKeyValueArray, unwrappedValue[i], true);
}
}
else if (typeof unwrappedValue === 'object') {
for (const key in unwrappedValue) {
if (unwrappedValue.hasOwnProperty(key)) {
keyValueArraySet(styleKeyValueArray, key, unwrappedValue[key]);
}
}
}
else if (typeof unwrappedValue === 'string') {
stringParser(styleKeyValueArray, unwrappedValue);
}
else {
ngDevMode &&
throwError('Unsupported styling type ' + typeof unwrappedValue + ': ' + unwrappedValue);
}
return styleKeyValueArray;
}
/**
* Set a `value` for a `key` taking style sanitization into account.
*
* See: `keyValueArraySet` for details
*
* @param {?} keyValueArray KeyValueArray to add to.
* @param {?} key Style key to add. (This key will be checked if it needs sanitization)
* @param {?} value The value to set (If key needs sanitization it will be sanitized)
* @return {?}
*/
function styleKeyValueArraySet(keyValueArray, key, value) {
if (stylePropNeedsSanitization(key)) {
value = ɵɵsanitizeStyle(value);
}
keyValueArraySet(keyValueArray, key, value);
}
/**
* Update map based styling.
*
* Map based styling could be anything which contains more than one binding. For example `string`,
* or object literal. Dealing with all of these types would complicate the logic so
* instead this function expects that the complex input is first converted into normalized
* `KeyValueArray`. The advantage of normalization is that we get the values sorted, which makes it
* very cheap to compute deltas between the previous and current value.
*
* @param {?} tView Associated `TView.data` contains the linked list of binding priorities.
* @param {?} tNode `TNode` where the binding is located.
* @param {?} lView `LView` contains the values associated with other styling binding at this `TNode`.
* @param {?} renderer Renderer to use if any updates.
* @param {?} oldKeyValueArray Previous value represented as `KeyValueArray`
* @param {?} newKeyValueArray Current value represented as `KeyValueArray`
* @param {?} isClassBased `true` if `class` (`false` if `style`)
* @param {?} bindingIndex Binding index of the binding.
* @return {?}
*/
function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {
if ((/** @type {?} */ (oldKeyValueArray)) === NO_CHANGE) {
// On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.
oldKeyValueArray = (/** @type {?} */ (EMPTY_ARRAY$3));
}
/** @type {?} */
let oldIndex = 0;
/** @type {?} */
let newIndex = 0;
/** @type {?} */
let oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;
/** @type {?} */
let newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;
while (oldKey !== null || newKey !== null) {
ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');
ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');
/** @type {?} */
const oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;
/** @type {?} */
const newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;
/** @type {?} */
let setKey = null;
/** @type {?} */
let setValue = undefined;
if (oldKey === newKey) {
// UPDATE: Keys are equal => new value is overwriting old value.
oldIndex += 2;
newIndex += 2;
if (oldValue !== newValue) {
setKey = newKey;
setValue = newValue;
}
}
else if (newKey === null || oldKey !== null && oldKey < (/** @type {?} */ (newKey))) {
// DELETE: oldKey key is missing or we did not find the oldKey in the newValue
// (because the keyValueArray is sorted and `newKey` is found later alphabetically).
// `"background" < "color"` so we need to delete `"background"` because it is not found in the
// new array.
oldIndex += 2;
setKey = oldKey;
}
else {
// CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.
// `"color" > "background"` so we need to add `color` because it is in new array but not in
// old array.
ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');
newIndex += 2;
setKey = newKey;
setValue = newValue;
}
if (setKey !== null) {
updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);
}
oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;
newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;
}
}
/**
* Update a simple (property name) styling.
*
* This function takes `prop` and updates the DOM to that value. The function takes the binding
* value as well as binding priority into consideration to determine which value should be written
* to DOM. (For example it may be determined that there is a higher priority overwrite which blocks
* the DOM write, or if the value goes to `undefined` a lower priority overwrite may be consulted.)
*
* @param {?} tView Associated `TView.data` contains the linked list of binding priorities.
* @param {?} tNode `TNode` where the binding is located.
* @param {?} lView `LView` contains the values associated with other styling binding at this `TNode`.
* @param {?} renderer Renderer to use if any updates.
* @param {?} prop Either style property name or a class name.
* @param {?} value Either style value for `prop` or `true`/`false` if `prop` is class.
* @param {?} isClassBased `true` if `class` (`false` if `style`)
* @param {?} bindingIndex Binding index of the binding.
* @return {?}
*/
function updateStyling(tView, tNode, lView, renderer, prop, value, isClassBased, bindingIndex) {
if (tNode.type !== 3 /* Element */) {
// It is possible to have styling on non-elements (such as ng-container).
// This is rare, but it does happen. In such a case, just ignore the binding.
return;
}
/** @type {?} */
const tData = tView.data;
/** @type {?} */
const tRange = (/** @type {?} */ (tData[bindingIndex + 1]));
/** @type {?} */
const higherPriorityValue = getTStylingRangeNextDuplicate(tRange) ?
findStylingValue(tData, tNode, lView, prop, getTStylingRangeNext(tRange), isClassBased) :
undefined;
if (!isStylingValuePresent(higherPriorityValue)) {
// We don't have a next duplicate, or we did not find a duplicate value.
if (!isStylingValuePresent(value)) {
// We should delete current value or restore to lower priority value.
if (getTStylingRangePrevDuplicate(tRange)) {
// We have a possible prev duplicate, let's retrieve it.
value = findStylingValue(tData, null, lView, prop, bindingIndex, isClassBased);
}
}
/** @type {?} */
const rNode = (/** @type {?} */ (getNativeByIndex(getSelectedIndex(), lView)));
applyStyling(renderer, isClassBased, rNode, prop, value);
}
}
/**
* Search for styling value with higher priority which is overwriting current value, or a
* value of lower priority to which we should fall back if the value is `undefined`.
*
* When value is being applied at a location, related values need to be consulted.
* - If there is a higher priority binding, we should be using that one instead.
* For example `<div [style]="{color:exp1}" [style.color]="exp2">` change to `exp1`
* requires that we check `exp2` to see if it is set to value other than `undefined`.
* - If there is a lower priority binding and we are changing to `undefined`
* For example `<div [style]="{color:exp1}" [style.color]="exp2">` change to `exp2` to
* `undefined` requires that we check `exp1` (and static values) and use that as new value.
*
* NOTE: The styling stores two values.
* 1. The raw value which came from the application is stored at `index + 0` location. (This value
* is used for dirty checking).
* 2. The normalized value (converted to `KeyValueArray` if map and sanitized) is stored at `index +
* 1`.
* The advantage of storing the sanitized value is that once the value is written we don't need
* to worry about sanitizing it later or keeping track of the sanitizer.
*
* @param {?} tData `TData` used for traversing the priority.
* @param {?} tNode `TNode` to use for resolving static styling. Also controls search direction.
* - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
* If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
* - `null` search prev and go all the way to end. Return last value where
* `isStylingValuePresent(value)` is true.
* @param {?} lView `LView` used for retrieving the actual values.
* @param {?} prop Property which we are interested in.
* @param {?} index Starting index in the linked list of styling bindings where the search should start.
* @param {?} isClassBased `true` if `class` (`false` if `style`)
* @return {?}
*/
function findStylingValue(tData, tNode, lView, prop, index, isClassBased) {
// `TNode` to use for resolving static styling. Also controls search direction.
// - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
// If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
// - `null` search prev and go all the way to end. Return last value where
// `isStylingValuePresent(value)` is true.
/** @type {?} */
const isPrevDirection = tNode === null;
/** @type {?} */
let value = undefined;
while (index > 0) {
/** @type {?} */
const rawKey = (/** @type {?} */ (tData[index]));
/** @type {?} */
const containsStatics = Array.isArray(rawKey);
// Unwrap the key if we contain static values.
/** @type {?} */
const key = containsStatics ? ((/** @type {?} */ (rawKey)))[1] : rawKey;
/** @type {?} */
const isStylingMap = key === null;
/** @type {?} */
let valueAtLViewIndex = lView[index + 1];
if (valueAtLViewIndex === NO_CHANGE) {
// In firstUpdatePass the styling instructions create a linked list of styling.
// On subsequent passes it is possible for a styling instruction to try to read a binding
// which
// has not yet executed. In that case we will find `NO_CHANGE` and we should assume that
// we have `undefined` (or empty array in case of styling-map instruction) instead. This
// allows the resolution to apply the value (which may later be overwritten when the
// binding actually executes.)
valueAtLViewIndex = isStylingMap ? EMPTY_ARRAY$3 : undefined;
}
/** @type {?} */
let currentValue = isStylingMap ? keyValueArrayGet(valueAtLViewIndex, prop) :
key === prop ? valueAtLViewIndex : undefined;
if (containsStatics && !isStylingValuePresent(currentValue)) {
currentValue = keyValueArrayGet((/** @type {?} */ (rawKey)), prop);
}
if (isStylingValuePresent(currentValue)) {
value = currentValue;
if (isPrevDirection) {
return value;
}
}
/** @type {?} */
const tRange = (/** @type {?} */ (tData[index + 1]));
index = isPrevDirection ? getTStylingRangePrev(tRange) : getTStylingRangeNext(tRange);
}
if (tNode !== null) {
// in case where we are going in next direction AND we did not find anything, we need to
// consult residual styling
/** @type {?} */
let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
if (residual != null /** OR residual !=== undefined */) {
value = keyValueArrayGet((/** @type {?} */ (residual)), prop);
}
}
return value;
}
/**
* Determines if the binding value should be used (or if the value is 'undefined' and hence priority
* resolution should be used.)
*
* @param {?} value Binding style value.
* @return {?}
*/
function isStylingValuePresent(value) {
// Currently only `undefined` value is considered non-binding. That is `undefined` says I don't
// have an opinion as to what this binding should be and you should consult other bindings by
// priority to determine the valid value.
// This is extracted into a single function so that we have a single place to control this.
return value !== undefined;
}
/**
* Sanitizes or adds suffix to the value.
*
* If value is `null`/`undefined` no suffix is added
* @param {?} value
* @param {?} suffixOrSanitizer
* @return {?}
*/
function normalizeAndApplySuffixOrSanitizer(value, suffixOrSanitizer) {
if (value == null /** || value === undefined */) {
// do nothing
}
else if (typeof suffixOrSanitizer === 'function') {
// sanitize the value.
value = suffixOrSanitizer(value);
}
else if (typeof suffixOrSanitizer === 'string') {
value = value + suffixOrSanitizer;
}
else if (typeof value === 'object') {
value = stringify(unwrapSafeValue(value));
}
return value;
}
/**
* Tests if the `TNode` has input shadow.
*
* An input shadow is when a directive steals (shadows) the input by using `\@Input('style')` or
* `\@Input('class')` as input.
*
* @param {?} tNode `TNode` which we would like to see if it has shadow.
* @param {?} isClassBased `true` if `class` (`false` if `style`)
* @return {?}
*/
function hasStylingInputShadow(tNode, isClassBased) {
return (tNode.flags & (isClassBased ? 16 /* hasClassInput */ : 32 /* hasStyleInput */)) !== 0;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/text.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Create static text node
*
* \@codeGenApi
* @param {?} index Index of the node in the data array
* @param {?=} value Static string value to write.
*
* @return {?}
*/
function ɵɵtext(index, value = '') {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
/** @type {?} */
const adjustedIndex = index + HEADER_OFFSET;
ngDevMode &&
assertEqual(getBindingIndex(), tView.bindingStartIndex, 'text nodes should be created before any bindings');
ngDevMode && assertDataInRange(lView, adjustedIndex);
/** @type {?} */
const tNode = tView.firstCreatePass ?
getOrCreateTNode(tView, lView[T_HOST], index, 3 /* Element */, null, null) :
(/** @type {?} */ (tView.data[adjustedIndex]));
/** @type {?} */
const textNative = lView[adjustedIndex] = createTextNode(value, lView[RENDERER]);
appendChild(tView, lView, textNative, tNode);
// Text nodes are self closing.
setPreviousOrParentTNode(tNode, false);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/text_interpolation.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
*
* Update text content with a lone bound value
*
* Used when a text node has 1 interpolated value in it, an no additional text
* surrounds that interpolated value:
*
* ```html
* <div>{{v0}}</div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵtextInterpolate(v0);
* ```
* @see textInterpolateV
* \@codeGenApi
* @param {?} v0
* @return {?} itself, so that it may be chained.
*/
function ɵɵtextInterpolate(v0) {
ɵɵtextInterpolate1('', v0, '');
return ɵɵtextInterpolate;
}
/**
*
* Update text content with single bound value surrounded by other text.
*
* Used when a text node has 1 interpolated value in it:
*
* ```html
* <div>prefix{{v0}}suffix</div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵtextInterpolate1('prefix', v0, 'suffix');
* ```
* @see textInterpolateV
* \@codeGenApi
* @param {?} prefix
* @param {?} v0
* @param {?} suffix
* @return {?} itself, so that it may be chained.
*/
function ɵɵtextInterpolate1(prefix, v0, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolated = interpolation1(lView, prefix, v0, suffix);
if (interpolated !== NO_CHANGE) {
textBindingInternal(lView, getSelectedIndex(), (/** @type {?} */ (interpolated)));
}
return ɵɵtextInterpolate1;
}
/**
*
* Update text content with 2 bound values surrounded by other text.
*
* Used when a text node has 2 interpolated values in it:
*
* ```html
* <div>prefix{{v0}}-{{v1}}suffix</div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵtextInterpolate2('prefix', v0, '-', v1, 'suffix');
* ```
* @see textInterpolateV
* \@codeGenApi
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} suffix
* @return {?} itself, so that it may be chained.
*/
function ɵɵtextInterpolate2(prefix, v0, i0, v1, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolated = interpolation2(lView, prefix, v0, i0, v1, suffix);
if (interpolated !== NO_CHANGE) {
textBindingInternal(lView, getSelectedIndex(), (/** @type {?} */ (interpolated)));
}
return ɵɵtextInterpolate2;
}
/**
*
* Update text content with 3 bound values surrounded by other text.
*
* Used when a text node has 3 interpolated values in it:
*
* ```html
* <div>prefix{{v0}}-{{v1}}-{{v2}}suffix</div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵtextInterpolate3(
* 'prefix', v0, '-', v1, '-', v2, 'suffix');
* ```
* @see textInterpolateV
* \@codeGenApi
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} suffix
* @return {?} itself, so that it may be chained.
*/
function ɵɵtextInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolated = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
if (interpolated !== NO_CHANGE) {
textBindingInternal(lView, getSelectedIndex(), (/** @type {?} */ (interpolated)));
}
return ɵɵtextInterpolate3;
}
/**
*
* Update text content with 4 bound values surrounded by other text.
*
* Used when a text node has 4 interpolated values in it:
*
* ```html
* <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix</div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵtextInterpolate4(
* 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
* ```
* @see ɵɵtextInterpolateV
* \@codeGenApi
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} i2
* @param {?} v3
* @param {?} suffix
* @return {?} itself, so that it may be chained.
*/
function ɵɵtextInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolated = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
if (interpolated !== NO_CHANGE) {
textBindingInternal(lView, getSelectedIndex(), (/** @type {?} */ (interpolated)));
}
return ɵɵtextInterpolate4;
}
/**
*
* Update text content with 5 bound values surrounded by other text.
*
* Used when a text node has 5 interpolated values in it:
*
* ```html
* <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix</div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵtextInterpolate5(
* 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
* ```
* @see textInterpolateV
* \@codeGenApi
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} i2
* @param {?} v3
* @param {?} i3
* @param {?} v4
* @param {?} suffix
* @return {?} itself, so that it may be chained.
*/
function ɵɵtextInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolated = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
if (interpolated !== NO_CHANGE) {
textBindingInternal(lView, getSelectedIndex(), (/** @type {?} */ (interpolated)));
}
return ɵɵtextInterpolate5;
}
/**
*
* Update text content with 6 bound values surrounded by other text.
*
* Used when a text node has 6 interpolated values in it:
*
* ```html
* <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix</div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵtextInterpolate6(
* 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
* ```
*
* @see textInterpolateV
* \@codeGenApi
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} i2
* @param {?} v3
* @param {?} i3
* @param {?} v4
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change. \@returns itself, so that it may be chained.
* @param {?} suffix
* @return {?}
*/
function ɵɵtextInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolated = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
if (interpolated !== NO_CHANGE) {
textBindingInternal(lView, getSelectedIndex(), (/** @type {?} */ (interpolated)));
}
return ɵɵtextInterpolate6;
}
/**
*
* Update text content with 7 bound values surrounded by other text.
*
* Used when a text node has 7 interpolated values in it:
*
* ```html
* <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix</div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵtextInterpolate7(
* 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
* ```
* @see textInterpolateV
* \@codeGenApi
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} i2
* @param {?} v3
* @param {?} i3
* @param {?} v4
* @param {?} i4
* @param {?} v5
* @param {?} i5
* @param {?} v6
* @param {?} suffix
* @return {?} itself, so that it may be chained.
*/
function ɵɵtextInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolated = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
if (interpolated !== NO_CHANGE) {
textBindingInternal(lView, getSelectedIndex(), (/** @type {?} */ (interpolated)));
}
return ɵɵtextInterpolate7;
}
/**
*
* Update text content with 8 bound values surrounded by other text.
*
* Used when a text node has 8 interpolated values in it:
*
* ```html
* <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix</div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵtextInterpolate8(
* 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
* ```
* @see textInterpolateV
* \@codeGenApi
* @param {?} prefix
* @param {?} v0
* @param {?} i0
* @param {?} v1
* @param {?} i1
* @param {?} v2
* @param {?} i2
* @param {?} v3
* @param {?} i3
* @param {?} v4
* @param {?} i4
* @param {?} v5
* @param {?} i5
* @param {?} v6
* @param {?} i6
* @param {?} v7
* @param {?} suffix
* @return {?} itself, so that it may be chained.
*/
function ɵɵtextInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolated = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
if (interpolated !== NO_CHANGE) {
textBindingInternal(lView, getSelectedIndex(), (/** @type {?} */ (interpolated)));
}
return ɵɵtextInterpolate8;
}
/**
* Update text content with 9 or more bound values other surrounded by text.
*
* Used when the number of interpolated values exceeds 8.
*
* ```html
* <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix</div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵtextInterpolateV(
* ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
* 'suffix']);
* ```
* .
* \@codeGenApi
* @param {?} values The collection of values and the strings in between those values, beginning with
* a string prefix and ending with a string suffix.
* (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
*
* @return {?} itself, so that it may be chained.
*/
function ɵɵtextInterpolateV(values) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolated = interpolationV(lView, values);
if (interpolated !== NO_CHANGE) {
textBindingInternal(lView, getSelectedIndex(), (/** @type {?} */ (interpolated)));
}
return ɵɵtextInterpolateV;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/class_map_interpolation.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
*
* Update an interpolated class on an element with single bound value surrounded by text.
*
* Used when the value passed to a property has 1 interpolated value in it:
*
* ```html
* <div class="prefix{{v0}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵclassMapInterpolate1('prefix', v0, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵclassMapInterpolate1(prefix, v0, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
*
* Update an interpolated class on an element with 2 bound values surrounded by text.
*
* Used when the value passed to a property has 2 interpolated values in it:
*
* ```html
* <div class="prefix{{v0}}-{{v1}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵclassMapInterpolate2('prefix', v0, '-', v1, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵclassMapInterpolate2(prefix, v0, i0, v1, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
*
* Update an interpolated class on an element with 3 bound values surrounded by text.
*
* Used when the value passed to a property has 3 interpolated values in it:
*
* ```html
* <div class="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵclassMapInterpolate3(
* 'prefix', v0, '-', v1, '-', v2, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵclassMapInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
*
* Update an interpolated class on an element with 4 bound values surrounded by text.
*
* Used when the value passed to a property has 4 interpolated values in it:
*
* ```html
* <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵclassMapInterpolate4(
* 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵclassMapInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
*
* Update an interpolated class on an element with 5 bound values surrounded by text.
*
* Used when the value passed to a property has 5 interpolated values in it:
*
* ```html
* <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵclassMapInterpolate5(
* 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵclassMapInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
*
* Update an interpolated class on an element with 6 bound values surrounded by text.
*
* Used when the value passed to a property has 6 interpolated values in it:
*
* ```html
* <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵclassMapInterpolate6(
* 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵclassMapInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
*
* Update an interpolated class on an element with 7 bound values surrounded by text.
*
* Used when the value passed to a property has 7 interpolated values in it:
*
* ```html
* <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵclassMapInterpolate7(
* 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} i5 Static value used for concatenation only.
* @param {?} v6 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵclassMapInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
*
* Update an interpolated class on an element with 8 bound values surrounded by text.
*
* Used when the value passed to a property has 8 interpolated values in it:
*
* ```html
* <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵclassMapInterpolate8(
* 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} i5 Static value used for concatenation only.
* @param {?} v6 Value checked for change.
* @param {?} i6 Static value used for concatenation only.
* @param {?} v7 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵclassMapInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
* Update an interpolated class on an element with 9 or more bound values surrounded by text.
*
* Used when the number of interpolated values exceeds 8.
*
* ```html
* <div
* class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵclassMapInterpolateV(
* ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
* 'suffix']);
* ```
* .
* \@codeGenApi
* @param {?} values The collection of values and the strings in-between those values, beginning with
* a string prefix and ending with a string suffix.
* (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
* @return {?}
*/
function ɵɵclassMapInterpolateV(values) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolationV(lView, values);
checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/style_map_interpolation.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
*
* Update an interpolated style on an element with single bound value surrounded by text.
*
* Used when the value passed to a property has 1 interpolated value in it:
*
* ```html
* <div style="key: {{v0}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate1('key: ', v0, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵstyleMapInterpolate1(prefix, v0, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style on an element with 2 bound values surrounded by text.
*
* Used when the value passed to a property has 2 interpolated values in it:
*
* ```html
* <div style="key: {{v0}}; key1: {{v1}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate2('key: ', v0, '; key1: ', v1, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵstyleMapInterpolate2(prefix, v0, i0, v1, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style on an element with 3 bound values surrounded by text.
*
* Used when the value passed to a property has 3 interpolated values in it:
*
* ```html
* <div style="key: {{v0}}; key2: {{v1}}; key2: {{v2}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate3(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵstyleMapInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style on an element with 4 bound values surrounded by text.
*
* Used when the value passed to a property has 4 interpolated values in it:
*
* ```html
* <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate4(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵstyleMapInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style on an element with 5 bound values surrounded by text.
*
* Used when the value passed to a property has 5 interpolated values in it:
*
* ```html
* <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate5(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵstyleMapInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style on an element with 6 bound values surrounded by text.
*
* Used when the value passed to a property has 6 interpolated values in it:
*
* ```html
* <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}};
* key5: {{v5}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate6(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
* 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵstyleMapInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style on an element with 7 bound values surrounded by text.
*
* Used when the value passed to a property has 7 interpolated values in it:
*
* ```html
* <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
* key6: {{v6}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate7(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
* '; key6: ', v6, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} i5 Static value used for concatenation only.
* @param {?} v6 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵstyleMapInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style on an element with 8 bound values surrounded by text.
*
* Used when the value passed to a property has 8 interpolated values in it:
*
* ```html
* <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
* key6: {{v6}}; key7: {{v7}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate8(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
* '; key6: ', v6, '; key7: ', v7, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} i5 Static value used for concatenation only.
* @param {?} v6 Value checked for change.
* @param {?} i6 Static value used for concatenation only.
* @param {?} v7 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @return {?}
*/
function ɵɵstyleMapInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
ɵɵstyleMap(interpolatedValue);
}
/**
* Update an interpolated style on an element with 9 or more bound values surrounded by text.
*
* Used when the number of interpolated values exceeds 8.
*
* ```html
* <div
* class="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
* key6: {{v6}}; key7: {{v7}}; key8: {{v8}}; key9: {{v9}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolateV(
* ['key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
* '; key6: ', v6, '; key7: ', v7, '; key8: ', v8, '; key9: ', v9, 'suffix']);
* ```
* .
* \@codeGenApi
* @param {?} values The collection of values and the strings in-between those values, beginning with
* a string prefix and ending with a string suffix.
* (e.g. `['prefix', value0, '; key2: ', value1, '; key2: ', value2, ..., value99, 'suffix']`)
* @return {?}
*/
function ɵɵstyleMapInterpolateV(values) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolationV(lView, values);
ɵɵstyleMap(interpolatedValue);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/style_prop_interpolation.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
*
* Update an interpolated style property on an element with single bound value surrounded by text.
*
* Used when the value passed to a property has 1 interpolated value in it:
*
* ```html
* <div style.color="prefix{{v0}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate1(0, 'prefix', v0, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prop
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @return {?} itself, so that it may be chained.
*/
function ɵɵstylePropInterpolate1(prop, prefix, v0, suffix, valueSuffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate1;
}
/**
*
* Update an interpolated style property on an element with 2 bound values surrounded by text.
*
* Used when the value passed to a property has 2 interpolated values in it:
*
* ```html
* <div style.color="prefix{{v0}}-{{v1}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate2(0, 'prefix', v0, '-', v1, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prop
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @return {?} itself, so that it may be chained.
*/
function ɵɵstylePropInterpolate2(prop, prefix, v0, i0, v1, suffix, valueSuffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate2;
}
/**
*
* Update an interpolated style property on an element with 3 bound values surrounded by text.
*
* Used when the value passed to a property has 3 interpolated values in it:
*
* ```html
* <div style.color="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate3(0, 'prefix', v0, '-', v1, '-', v2, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prop
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @return {?} itself, so that it may be chained.
*/
function ɵɵstylePropInterpolate3(prop, prefix, v0, i0, v1, i1, v2, suffix, valueSuffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate3;
}
/**
*
* Update an interpolated style property on an element with 4 bound values surrounded by text.
*
* Used when the value passed to a property has 4 interpolated values in it:
*
* ```html
* <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate4(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prop
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @return {?} itself, so that it may be chained.
*/
function ɵɵstylePropInterpolate4(prop, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, valueSuffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate4;
}
/**
*
* Update an interpolated style property on an element with 5 bound values surrounded by text.
*
* Used when the value passed to a property has 5 interpolated values in it:
*
* ```html
* <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate5(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prop
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @return {?} itself, so that it may be chained.
*/
function ɵɵstylePropInterpolate5(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, valueSuffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate5;
}
/**
*
* Update an interpolated style property on an element with 6 bound values surrounded by text.
*
* Used when the value passed to a property has 6 interpolated values in it:
*
* ```html
* <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate6(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prop
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @return {?} itself, so that it may be chained.
*/
function ɵɵstylePropInterpolate6(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, valueSuffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate6;
}
/**
*
* Update an interpolated style property on an element with 7 bound values surrounded by text.
*
* Used when the value passed to a property has 7 interpolated values in it:
*
* ```html
* <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate7(
* 0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prop
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} i5 Static value used for concatenation only.
* @param {?} v6 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @return {?} itself, so that it may be chained.
*/
function ɵɵstylePropInterpolate7(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, valueSuffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate7;
}
/**
*
* Update an interpolated style property on an element with 8 bound values surrounded by text.
*
* Used when the value passed to a property has 8 interpolated values in it:
*
* ```html
* <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate8(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6,
* '-', v7, 'suffix');
* ```
*
* \@codeGenApi
* @param {?} prop
* @param {?} prefix Static value used for concatenation only.
* @param {?} v0 Value checked for change.
* @param {?} i0 Static value used for concatenation only.
* @param {?} v1 Value checked for change.
* @param {?} i1 Static value used for concatenation only.
* @param {?} v2 Value checked for change.
* @param {?} i2 Static value used for concatenation only.
* @param {?} v3 Value checked for change.
* @param {?} i3 Static value used for concatenation only.
* @param {?} v4 Value checked for change.
* @param {?} i4 Static value used for concatenation only.
* @param {?} v5 Value checked for change.
* @param {?} i5 Static value used for concatenation only.
* @param {?} v6 Value checked for change.
* @param {?} i6 Static value used for concatenation only.
* @param {?} v7 Value checked for change.
* @param {?} suffix Static value used for concatenation only.
* @param {?=} valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @return {?} itself, so that it may be chained.
*/
function ɵɵstylePropInterpolate8(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, valueSuffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate8;
}
/**
* Update an interpolated style property on an element with 9 or more bound values surrounded by
* text.
*
* Used when the number of interpolated values exceeds 8.
*
* ```html
* <div
* style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix">
* </div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolateV(
* 0, ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
* 'suffix']);
* ```
*
* \@codeGenApi
* @param {?} prop
* @param {?} values The collection of values and the strings in-between those values, beginning with
* a string prefix and ending with a string suffix.
* (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
* @param {?=} valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @return {?} itself, so that it may be chained.
*/
function ɵɵstylePropInterpolateV(prop, values, valueSuffix) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const interpolatedValue = interpolationV(lView, values);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolateV;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/host_property.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Update a property on a host element. Only applies to native node properties, not inputs.
*
* Operates on the element selected by index via the {\@link select} instruction.
*
* \@codeGenApi
* @template T
* @param {?} propName Name of property. Because it is going to DOM, this is not subject to
* renaming as part of minification.
* @param {?} value New value to write.
* @param {?=} sanitizer An optional function used to sanitize the value.
* @return {?} This function returns itself so that it may be chained
* (e.g. `property('name', ctx.name)('title', ctx.title)`)
*
*/
function ɵɵhostProperty(propName, value, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const bindingIndex = nextBindingIndex();
if (bindingUpdated(lView, bindingIndex, value)) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, true);
ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
}
return ɵɵhostProperty;
}
/**
* Updates a synthetic host binding (e.g. `[\@foo]`) on a component or directive.
*
* This instruction is for compatibility purposes and is designed to ensure that a
* synthetic host binding (e.g. `\@HostBinding('\@foo')`) properly gets rendered in
* the component's renderer. Normally all host bindings are evaluated with the parent
* component's renderer, but, in the case of animation \@triggers, they need to be
* evaluated with the sub component's renderer (because that's where the animation
* triggers are defined).
*
* Do not use this instruction as a replacement for `elementProperty`. This instruction
* only exists to ensure compatibility with the ViewEngine's host binding behavior.
*
* \@codeGenApi
* @template T
* @param {?} propName Name of property. Because it is going to DOM, this is not subject to
* renaming as part of minification.
* @param {?} value New value to write.
* @param {?=} sanitizer An optional function used to sanitize the value.
*
* @return {?}
*/
function ɵɵupdateSyntheticHostBinding(propName, value, sanitizer) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const bindingIndex = nextBindingIndex();
if (bindingUpdated(lView, bindingIndex, value)) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const tNode = getSelectedTNode();
/** @type {?} */
const currentDef = getCurrentDirectiveDef(tView.data);
/** @type {?} */
const renderer = loadComponentRenderer(currentDef, tNode, lView);
elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, true);
ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
}
return ɵɵupdateSyntheticHostBinding;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/instructions/all.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/util/discovery_utils.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Retrieves the component instance associated with a given DOM element.
*
* \@usageNotes
* Given the following DOM structure:
* ```html
* <my-app>
* <div>
* <child-comp></child-comp>
* </div>
* </my-app>
* ```
* Calling `getComponent` on `<child-comp>` will return the instance of `ChildComponent`
* associated with this DOM element.
*
* Calling the function on `<my-app>` will return the `MyApp` instance.
*
*
* \@publicApi
* \@globalApi ng
* @template T
* @param {?} element DOM element from which the component should be retrieved.
* @return {?} Component instance associated with the element or `null` if there
* is no component associated with it.
*
*/
function getComponent(element) {
assertDomElement(element);
/** @type {?} */
const context = loadLContext(element, false);
if (context === null)
return null;
if (context.component === undefined) {
context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView);
}
return (/** @type {?} */ (context.component));
}
/**
* If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded
* view that the element is part of. Otherwise retrieves the instance of the component whose view
* owns the element (in this case, the result is the same as calling `getOwningComponent`).
*
* \@publicApi
* \@globalApi ng
* @template T
* @param {?} element Element for which to get the surrounding component instance.
* @return {?} Instance of the component that is around the element or null if the element isn't
* inside any component.
*
*/
function getContext(element) {
assertDomElement(element);
/** @type {?} */
const context = loadLContext(element, false);
return context === null ? null : (/** @type {?} */ (context.lView[CONTEXT]));
}
/**
* Retrieves the component instance whose view contains the DOM element.
*
* For example, if `<child-comp>` is used in the template of `<app-comp>`
* (i.e. a `ViewChild` of `<app-comp>`), calling `getOwningComponent` on `<child-comp>`
* would return `<app-comp>`.
*
* \@publicApi
* \@globalApi ng
* @template T
* @param {?} elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @return {?} Component instance whose view owns the DOM element or null if the element is not
* part of a component view.
*
*/
function getOwningComponent(elementOrDir) {
/** @type {?} */
const context = loadLContext(elementOrDir, false);
if (context === null)
return null;
/** @type {?} */
let lView = context.lView;
/** @type {?} */
let parent;
ngDevMode && assertLView(lView);
while (lView[HOST] === null && (parent = (/** @type {?} */ (getLViewParent(lView))))) {
// As long as lView[HOST] is null we know we are part of sub-template such as `*ngIf`
lView = parent;
}
return lView[FLAGS] & 512 /* IsRoot */ ? null : (/** @type {?} */ (lView[CONTEXT]));
}
/**
* Retrieves all root components associated with a DOM element, directive or component instance.
* Root components are those which have been bootstrapped by Angular.
*
* \@publicApi
* \@globalApi ng
* @param {?} elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @return {?} Root components associated with the target object.
*
*/
function getRootComponents(elementOrDir) {
return [...getRootContext(elementOrDir).components];
}
/**
* Retrieves an `Injector` associated with an element, component or directive instance.
*
* \@publicApi
* \@globalApi ng
* @param {?} elementOrDir DOM element, component or directive instance for which to
* retrieve the injector.
* @return {?} Injector associated with the element, component or directive instance.
*
*/
function getInjector(elementOrDir) {
/** @type {?} */
const context = loadLContext(elementOrDir, false);
if (context === null)
return Injector.NULL;
/** @type {?} */
const tNode = (/** @type {?} */ (context.lView[TVIEW].data[context.nodeIndex]));
return new NodeInjector(tNode, context.lView);
}
/**
* Retrieve a set of injection tokens at a given DOM node.
*
* @param {?} element Element for which the injection tokens should be retrieved.
* @return {?}
*/
function getInjectionTokens(element) {
/** @type {?} */
const context = loadLContext(element, false);
if (context === null)
return [];
/** @type {?} */
const lView = context.lView;
/** @type {?} */
const tView = lView[TVIEW];
/** @type {?} */
const tNode = (/** @type {?} */ (tView.data[context.nodeIndex]));
/** @type {?} */
const providerTokens = [];
/** @type {?} */
const startIndex = tNode.providerIndexes & 65535 /* ProvidersStartIndexMask */;
/** @type {?} */
const endIndex = tNode.directiveEnd;
for (let i = startIndex; i < endIndex; i++) {
/** @type {?} */
let value = tView.data[i];
if (isDirectiveDefHack(value)) {
// The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
// design flaw. We should always store same type so that we can be monomorphic. The issue
// is that for Components/Directives we store the def instead the type. The correct behavior
// is that we should always be storing injectable type in this location.
value = value.type;
}
providerTokens.push(value);
}
return providerTokens;
}
/**
* Retrieves directive instances associated with a given DOM element. Does not include
* component instances.
*
* \@usageNotes
* Given the following DOM structure:
* ```
* <my-app>
* <button my-button></button>
* <my-comp></my-comp>
* </my-app>
* ```
* Calling `getDirectives` on `<button>` will return an array with an instance of the `MyButton`
* directive that is associated with the DOM element.
*
* Calling `getDirectives` on `<my-comp>` will return an empty array.
*
* \@publicApi
* \@globalApi ng
* @param {?} element DOM element for which to get the directives.
* @return {?} Array of directives associated with the element.
*
*/
function getDirectives(element) {
/** @type {?} */
const context = (/** @type {?} */ (loadLContext(element)));
if (context.directives === undefined) {
context.directives = getDirectivesAtNodeIndex(context.nodeIndex, context.lView, false);
}
// The `directives` in this case are a named array called `LComponentView`. Clone the
// result so we don't expose an internal data structure in the user's console.
return context.directives === null ? [] : [...context.directives];
}
/**
* @param {?} target
* @param {?=} throwOnNotFound
* @return {?}
*/
function loadLContext(target, throwOnNotFound = true) {
/** @type {?} */
const context = getLContext(target);
if (!context && throwOnNotFound) {
throw new Error(ngDevMode ? `Unable to find context associated with ${stringifyForError(target)}` :
'Invalid ng target');
}
return context;
}
/**
* Retrieve map of local references.
*
* The references are retrieved as a map of local reference name to element or directive instance.
*
* @param {?} target DOM element, component or directive instance for which to retrieve
* the local references.
* @return {?}
*/
function getLocalRefs(target) {
/** @type {?} */
const context = loadLContext(target, false);
if (context === null)
return {};
if (context.localRefs === undefined) {
context.localRefs = discoverLocalRefs(context.lView, context.nodeIndex);
}
return context.localRefs || {};
}
/**
* Retrieves the host element of a component or directive instance.
* The host element is the DOM element that matched the selector of the directive.
*
* \@publicApi
* \@globalApi ng
* @param {?} componentOrDirective Component or directive instance for which the host
* element should be retrieved.
* @return {?} Host element of the target.
*
*/
function getHostElement(componentOrDirective) {
return (/** @type {?} */ ((/** @type {?} */ ((/** @type {?} */ (getLContext(componentOrDirective))).native))));
}
/**
* Retrieves the rendered text for a given component.
*
* This function retrieves the host element of a component and
* and then returns the `textContent` for that element. This implies
* that the text returned will include re-projected content of
* the component as well.
*
* @param {?} component The component to return the content text for.
* @return {?}
*/
function getRenderedText(component) {
/** @type {?} */
const hostElement = getHostElement(component);
return hostElement.textContent || '';
}
/**
* @param {?} node
* @return {?}
*/
function loadLContextFromNode(node) {
if (!(node instanceof Node))
throw new Error('Expecting instance of DOM Element');
return (/** @type {?} */ (loadLContext(node)));
}
/**
* Event listener configuration returned from `getListeners`.
* \@publicApi
* @record
*/
function Listener() { }
if (false) {}
/**
* Retrieves a list of event listeners associated with a DOM element. The list does include host
* listeners, but it does not include event listeners defined outside of the Angular context
* (e.g. through `addEventListener`).
*
* \@usageNotes
* Given the following DOM structure:
* ```
* <my-app>
* <div (click)="doSomething()"></div>
* </my-app>
*
* ```
* Calling `getListeners` on `<div>` will return an object that looks as follows:
* ```
* {
* name: 'click',
* element: <div>,
* callback: () => doSomething(),
* useCapture: false
* }
* ```
*
* \@publicApi
* \@globalApi ng
* @param {?} element Element for which the DOM listeners should be retrieved.
* @return {?} Array of event listeners on the DOM element.
*
*/
function getListeners(element) {
assertDomElement(element);
/** @type {?} */
const lContext = loadLContext(element, false);
if (lContext === null)
return [];
/** @type {?} */
const lView = lContext.lView;
/** @type {?} */
const tView = lView[TVIEW];
/** @type {?} */
const lCleanup = lView[CLEANUP];
/** @type {?} */
const tCleanup = tView.cleanup;
/** @type {?} */
const listeners = [];
if (tCleanup && lCleanup) {
for (let i = 0; i < tCleanup.length;) {
/** @type {?} */
const firstParam = tCleanup[i++];
/** @type {?} */
const secondParam = tCleanup[i++];
if (typeof firstParam === 'string') {
/** @type {?} */
const name = firstParam;
/** @type {?} */
const listenerElement = (/** @type {?} */ ((/** @type {?} */ (unwrapRNode(lView[secondParam])))));
/** @type {?} */
const callback = lCleanup[tCleanup[i++]];
/** @type {?} */
const useCaptureOrIndx = tCleanup[i++];
// if useCaptureOrIndx is boolean then report it as is.
// if useCaptureOrIndx is positive number then it in unsubscribe method
// if useCaptureOrIndx is negative number then it is a Subscription
/** @type {?} */
const type = (typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0) ? 'dom' : 'output';
/** @type {?} */
const useCapture = typeof useCaptureOrIndx === 'boolean' ? useCaptureOrIndx : false;
if (element == listenerElement) {
listeners.push({ element, name, callback, useCapture, type });
}
}
}
}
listeners.sort(sortListeners);
return listeners;
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function sortListeners(a, b) {
if (a.name == b.name)
return 0;
return a.name < b.name ? -1 : 1;
}
/**
* This function should not exist because it is megamorphic and only mostly correct.
*
* See call site for more info.
* @param {?} obj
* @return {?}
*/
function isDirectiveDefHack(obj) {
return obj.type !== undefined && obj.template !== undefined && obj.declaredInputs !== undefined;
}
/**
* Returns the attached `DebugNode` instance for an element in the DOM.
*
* @param {?} element DOM element which is owned by an existing component's view.
* @return {?}
*/
function getDebugNode(element) {
/** @type {?} */
let debugNode = null;
/** @type {?} */
const lContext = loadLContextFromNode(element);
/** @type {?} */
const lView = lContext.lView;
/** @type {?} */
const nodeIndex = lContext.nodeIndex;
if (nodeIndex !== -1) {
/** @type {?} */
const valueInLView = lView[nodeIndex];
// this means that value in the lView is a component with its own
// data. In this situation the TNode is not accessed at the same spot.
/** @type {?} */
const tNode = isLView(valueInLView) ? ((/** @type {?} */ (valueInLView[T_HOST]))) :
getTNode(lView[TVIEW], nodeIndex - HEADER_OFFSET);
debugNode = buildDebugNode(tNode, lView, nodeIndex);
}
return debugNode;
}
/**
* Retrieve the component `LView` from component/element.
*
* NOTE: `LView` is a private and should not be leaked outside.
* Don't export this method to `ng.*` on window.
*
* @param {?} target DOM element or component instance for which to retrieve the LView.
* @return {?}
*/
function getComponentLView(target) {
/** @type {?} */
const lContext = loadLContext(target);
/** @type {?} */
const nodeIndx = lContext.nodeIndex;
/** @type {?} */
const lView = lContext.lView;
/** @type {?} */
const componentLView = lView[nodeIndx];
ngDevMode && assertLView(componentLView);
return componentLView;
}
/**
* Asserts that a value is a DOM Element.
* @param {?} value
* @return {?}
*/
function assertDomElement(value) {
if (typeof Element !== 'undefined' && !(value instanceof Element)) {
throw new Error('Expecting instance of DOM Element');
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/util/change_detection_utils.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Marks a component for check (in case of OnPush components) and synchronously
* performs change detection on the application this component belongs to.
*
* \@publicApi
* \@globalApi ng
* @param {?} component Component to {\@link ChangeDetectorRef#markForCheck mark for check}.
*
* @return {?}
*/
function applyChanges(component) {
markDirty(component);
getRootComponents(component).forEach((/**
* @param {?} rootComponent
* @return {?}
*/
rootComponent => detectChanges(rootComponent)));
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/util/global_utils.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* This value reflects the property on the window where the dev
* tools are patched (window.ng).
*
* @type {?}
*/
const GLOBAL_PUBLISH_EXPANDO_KEY = 'ng';
/** @type {?} */
let _published = false;
/**
* Publishes a collection of default debug tools onto`window.ng`.
*
* These functions are available globally when Angular is in development
* mode and are automatically stripped away from prod mode is on.
* @return {?}
*/
function publishDefaultGlobalUtils() {
if (!_published) {
_published = true;
publishGlobalUtil('getComponent', getComponent);
publishGlobalUtil('getContext', getContext);
publishGlobalUtil('getListeners', getListeners);
publishGlobalUtil('getOwningComponent', getOwningComponent);
publishGlobalUtil('getHostElement', getHostElement);
publishGlobalUtil('getInjector', getInjector);
publishGlobalUtil('getRootComponents', getRootComponents);
publishGlobalUtil('getDirectives', getDirectives);
publishGlobalUtil('applyChanges', applyChanges);
}
}
/**
* Publishes the given function to `window.ng` so that it can be
* used from the browser console when an application is not in production.
* @param {?} name
* @param {?} fn
* @return {?}
*/
function publishGlobalUtil(name, fn) {
if (typeof COMPILED === 'undefined' || !COMPILED) {
// Note: we can't export `ng` when using closure enhanced optimization as:
// - closure declares globals itself for minified names, which sometimes clobber our `ng` global
// - we can't declare a closure extern as the namespace `ng` is already used within Google
// for typings for AngularJS (via `goog.provide('ng....')`).
/** @type {?} */
const w = (/** @type {?} */ ((/** @type {?} */ (_global))));
ngDevMode && assertDefined(fn, 'function not defined');
if (w) {
/** @type {?} */
let container = w[GLOBAL_PUBLISH_EXPANDO_KEY];
if (!container) {
container = w[GLOBAL_PUBLISH_EXPANDO_KEY] = {};
}
container[name] = fn;
}
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/component.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Options that control how the component should be bootstrapped.
* @record
*/
function CreateComponentOptions() { }
if (false) {}
// TODO: A hack to not pull in the NullInjector from @angular/core.
const ɵ0$b = /**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
(token, notFoundValue) => {
throw new Error('NullInjector: Not found: ' + stringifyForError(token));
};
/** @type {?} */
const NULL_INJECTOR$1 = {
get: (ɵ0$b)
};
/**
* Bootstraps a Component into an existing host element and returns an instance
* of the component.
*
* Use this function to bootstrap a component into the DOM tree. Each invocation
* of this function will create a separate tree of components, injectors and
* change detection cycles and lifetimes. To dynamically insert a new component
* into an existing tree such that it shares the same injection, change detection
* and object lifetime, use {\@link ViewContainer#createComponent}.
*
* @template T
* @param {?} componentType Component to bootstrap
* @param {?=} opts
* @return {?}
*/
function renderComponent$1(componentType /* Type as workaround for: Microsoft/TypeScript/issues/4881 */, opts = {}) {
ngDevMode && publishDefaultGlobalUtils();
ngDevMode && assertComponentType(componentType);
/** @type {?} */
const rendererFactory = opts.rendererFactory || domRendererFactory3;
/** @type {?} */
const sanitizer = opts.sanitizer || null;
/** @type {?} */
const componentDef = (/** @type {?} */ (getComponentDef(componentType)));
if (componentDef.type != componentType)
((/** @type {?} */ (componentDef))).type = componentType;
// The first index of the first selector is the tag name.
/** @type {?} */
const componentTag = (/** @type {?} */ ((/** @type {?} */ ((/** @type {?} */ (componentDef.selectors))[0]))[0]));
/** @type {?} */
const hostRenderer = rendererFactory.createRenderer(null, null);
/** @type {?} */
const hostRNode = locateHostElement(hostRenderer, opts.host || componentTag, componentDef.encapsulation);
/** @type {?} */
const rootFlags = componentDef.onPush ? 64 /* Dirty */ | 512 /* IsRoot */ :
16 /* CheckAlways */ | 512 /* IsRoot */;
/** @type {?} */
const rootContext = createRootContext(opts.scheduler, opts.playerHandler);
/** @type {?} */
const renderer = rendererFactory.createRenderer(hostRNode, componentDef);
/** @type {?} */
const rootTView = createTView(0 /* Root */, -1, null, 1, 0, null, null, null, null, null);
/** @type {?} */
const rootView = createLView(null, rootTView, rootContext, rootFlags, null, null, rendererFactory, renderer, undefined, opts.injector || null);
enterView(rootView, null);
/** @type {?} */
let component;
try {
if (rendererFactory.begin)
rendererFactory.begin();
/** @type {?} */
const componentView = createRootComponentView(hostRNode, componentDef, rootView, rendererFactory, renderer, sanitizer);
component = createRootComponent(componentView, componentDef, rootView, rootContext, opts.hostFeatures || null);
// create mode pass
renderView(rootTView, rootView, null);
// update mode pass
refreshView(rootTView, rootView, null, null);
}
finally {
leaveView();
if (rendererFactory.end)
rendererFactory.end();
}
return component;
}
/**
* Creates the root component view and the root component node.
*
* @param {?} rNode Render host element.
* @param {?} def ComponentDef
* @param {?} rootView The parent view where the host node is stored
* @param {?} rendererFactory
* @param {?} hostRenderer The current renderer
* @param {?=} sanitizer The sanitizer, if provided
*
* @return {?} Component view created
*/
function createRootComponentView(rNode, def, rootView, rendererFactory, hostRenderer, sanitizer) {
/** @type {?} */
const tView = rootView[TVIEW];
ngDevMode && assertDataInRange(rootView, 0 + HEADER_OFFSET);
rootView[0 + HEADER_OFFSET] = rNode;
/** @type {?} */
const tNode = getOrCreateTNode(tView, null, 0, 3 /* Element */, null, null);
/** @type {?} */
const mergedAttrs = tNode.mergedAttrs = def.hostAttrs;
if (mergedAttrs !== null) {
computeStaticStyling(tNode, mergedAttrs, true);
if (rNode !== null) {
setUpAttributes(hostRenderer, rNode, mergedAttrs);
if (tNode.classes !== null) {
writeDirectClass(hostRenderer, rNode, tNode.classes);
}
if (tNode.styles !== null) {
writeDirectStyle(hostRenderer, rNode, tNode.styles);
}
}
}
/** @type {?} */
const viewRenderer = rendererFactory.createRenderer(rNode, def);
/** @type {?} */
const componentView = createLView(rootView, getOrCreateTComponentView(def), null, def.onPush ? 64 /* Dirty */ : 16 /* CheckAlways */, rootView[HEADER_OFFSET], tNode, rendererFactory, viewRenderer, sanitizer);
if (tView.firstCreatePass) {
diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, rootView), tView, def.type);
markAsComponentHost(tView, tNode);
initTNodeFlags(tNode, rootView.length, 1);
}
addToViewTree(rootView, componentView);
// Store component view at node index, with node as the HOST
return rootView[HEADER_OFFSET] = componentView;
}
/**
* Creates a root component and sets it up with features and host bindings. Shared by
* renderComponent() and ViewContainerRef.createComponent().
* @template T
* @param {?} componentView
* @param {?} componentDef
* @param {?} rootLView
* @param {?} rootContext
* @param {?} hostFeatures
* @return {?}
*/
function createRootComponent(componentView, componentDef, rootLView, rootContext, hostFeatures) {
/** @type {?} */
const tView = rootLView[TVIEW];
// Create directive instance with factory() and store at next index in viewData
/** @type {?} */
const component = instantiateRootComponent(tView, rootLView, componentDef);
rootContext.components.push(component);
componentView[CONTEXT] = component;
hostFeatures && hostFeatures.forEach((/**
* @param {?} feature
* @return {?}
*/
(feature) => feature(component, componentDef)));
// We want to generate an empty QueryList for root content queries for backwards
// compatibility with ViewEngine.
if (componentDef.contentQueries) {
componentDef.contentQueries(1 /* Create */, component, rootLView.length - 1);
}
/** @type {?} */
const rootTNode = getPreviousOrParentTNode();
if (tView.firstCreatePass &&
(componentDef.hostBindings !== null || componentDef.hostAttrs !== null)) {
/** @type {?} */
const elementIndex = rootTNode.index - HEADER_OFFSET;
setSelectedIndex(elementIndex);
/** @type {?} */
const rootTView = rootLView[TVIEW];
addHostBindingsToExpandoInstructions(rootTView, componentDef);
growHostVarsSpace(rootTView, rootLView, componentDef.hostVars);
invokeHostBindingsInCreationMode(componentDef, component);
}
return component;
}
/**
* @param {?=} scheduler
* @param {?=} playerHandler
* @return {?}
*/
function createRootContext(scheduler, playerHandler) {
return {
components: [],
scheduler: scheduler || defaultScheduler,
clean: CLEAN_PROMISE,
playerHandler: playerHandler || null,
flags: 0 /* Empty */
};
}
/**
* Used to enable lifecycle hooks on the root component.
*
* Include this feature when calling `renderComponent` if the root component
* you are rendering has lifecycle hooks defined. Otherwise, the hooks won't
* be called properly.
*
* Example:
*
* ```
* renderComponent(AppComponent, {hostFeatures: [LifecycleHooksFeature]});
* ```
* @param {?} component
* @param {?} def
* @return {?}
*/
function LifecycleHooksFeature(component, def) {
/** @type {?} */
const rootTView = (/** @type {?} */ (readPatchedLView(component)))[TVIEW];
/** @type {?} */
const dirIndex = rootTView.data.length - 1;
// TODO(misko): replace `as TNode` with createTNode call. (needs refactoring to lose dep on
// LNode).
registerPostOrderHooks(rootTView, (/** @type {?} */ ({ directiveStart: dirIndex, directiveEnd: dirIndex + 1 })));
}
/**
* Wait on component until it is rendered.
*
* This function returns a `Promise` which is resolved when the component's
* change detection is executed. This is determined by finding the scheduler
* associated with the `component`'s render tree and waiting until the scheduler
* flushes. If nothing is scheduled, the function returns a resolved promise.
*
* Example:
* ```
* await whenRendered(myComponent);
* ```
*
* @param {?} component Component to wait upon
* @return {?} Promise which resolves when the component is rendered.
*/
function whenRendered(component) {
return getRootContext(component).clean;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/features/inherit_definition_feature.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} type
* @return {?}
*/
function getSuperType(type) {
return Object.getPrototypeOf(type.prototype).constructor;
}
/**
* Merges the definition from a super class to a sub class.
* \@codeGenApi
* @param {?} definition The definition that is a SubClass of another directive of component
*
* @return {?}
*/
function ɵɵInheritDefinitionFeature(definition) {
/** @type {?} */
let superType = getSuperType(definition.type);
/** @type {?} */
let shouldInheritFields = true;
/** @type {?} */
const inheritanceChain = [definition];
while (superType) {
/** @type {?} */
let superDef = undefined;
if (isComponentDef(definition)) {
// Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
superDef = superType.ɵcmp || superType.ɵdir;
}
else {
if (superType.ɵcmp) {
throw new Error('Directives cannot inherit Components');
}
// Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
superDef = superType.ɵdir;
}
if (superDef) {
if (shouldInheritFields) {
inheritanceChain.push(superDef);
// Some fields in the definition may be empty, if there were no values to put in them that
// would've justified object creation. Unwrap them if necessary.
/** @type {?} */
const writeableDef = (/** @type {?} */ (definition));
writeableDef.inputs = maybeUnwrapEmpty(definition.inputs);
writeableDef.declaredInputs = maybeUnwrapEmpty(definition.declaredInputs);
writeableDef.outputs = maybeUnwrapEmpty(definition.outputs);
// Merge hostBindings
/** @type {?} */
const superHostBindings = superDef.hostBindings;
superHostBindings && inheritHostBindings(definition, superHostBindings);
// Merge queries
/** @type {?} */
const superViewQuery = superDef.viewQuery;
/** @type {?} */
const superContentQueries = superDef.contentQueries;
superViewQuery && inheritViewQuery(definition, superViewQuery);
superContentQueries && inheritContentQueries(definition, superContentQueries);
// Merge inputs and outputs
fillProperties(definition.inputs, superDef.inputs);
fillProperties(definition.declaredInputs, superDef.declaredInputs);
fillProperties(definition.outputs, superDef.outputs);
// Merge animations metadata.
// If `superDef` is a Component, the `data` field is present (defaults to an empty object).
if (isComponentDef(superDef) && superDef.data.animation) {
// If super def is a Component, the `definition` is also a Component, since Directives can
// not inherit Components (we throw an error above and cannot reach this code).
/** @type {?} */
const defData = ((/** @type {?} */ (definition))).data;
defData.animation = (defData.animation || []).concat(superDef.data.animation);
}
// Inherit hooks
// Assume super class inheritance feature has already run.
writeableDef.afterContentChecked =
writeableDef.afterContentChecked || superDef.afterContentChecked;
writeableDef.afterContentInit = definition.afterContentInit || superDef.afterContentInit;
writeableDef.afterViewChecked = definition.afterViewChecked || superDef.afterViewChecked;
writeableDef.afterViewInit = definition.afterViewInit || superDef.afterViewInit;
writeableDef.doCheck = definition.doCheck || superDef.doCheck;
writeableDef.onDestroy = definition.onDestroy || superDef.onDestroy;
writeableDef.onInit = definition.onInit || superDef.onInit;
}
// Run parent features
/** @type {?} */
const features = superDef.features;
if (features) {
for (let i = 0; i < features.length; i++) {
/** @type {?} */
const feature = features[i];
if (feature && feature.ngInherit) {
((/** @type {?} */ (feature)))(definition);
}
// If `InheritDefinitionFeature` is a part of the current `superDef`, it means that this
// def already has all the necessary information inherited from its super class(es), so we
// can stop merging fields from super classes. However we need to iterate through the
// prototype chain to look for classes that might contain other "features" (like
// NgOnChanges), which we should invoke for the original `definition`. We set the
// `shouldInheritFields` flag to indicate that, essentially skipping fields inheritance
// logic and only invoking functions from the "features" list.
if (feature === ɵɵInheritDefinitionFeature) {
shouldInheritFields = false;
}
}
}
}
superType = Object.getPrototypeOf(superType);
}
mergeHostAttrsAcrossInheritance(inheritanceChain);
}
/**
* Merge the `hostAttrs` and `hostVars` from the inherited parent to the base class.
*
* @param {?} inheritanceChain A list of `WritableDefs` starting at the top most type and listing
* sub-types in order. For each type take the `hostAttrs` and `hostVars` and merge it with the child
* type.
* @return {?}
*/
function mergeHostAttrsAcrossInheritance(inheritanceChain) {
/** @type {?} */
let hostVars = 0;
/** @type {?} */
let hostAttrs = null;
// We process the inheritance order from the base to the leaves here.
for (let i = inheritanceChain.length - 1; i >= 0; i--) {
/** @type {?} */
const def = inheritanceChain[i];
// For each `hostVars`, we need to add the superclass amount.
def.hostVars = (hostVars += def.hostVars);
// for each `hostAttrs` we need to merge it with superclass.
def.hostAttrs =
mergeHostAttrs(def.hostAttrs, hostAttrs = mergeHostAttrs(hostAttrs, def.hostAttrs));
}
}
/**
* @param {?} value
* @return {?}
*/
function maybeUnwrapEmpty(value) {
if (value === EMPTY_OBJ) {
return {};
}
else if (value === EMPTY_ARRAY) {
return [];
}
else {
return value;
}
}
/**
* @param {?} definition
* @param {?} superViewQuery
* @return {?}
*/
function inheritViewQuery(definition, superViewQuery) {
/** @type {?} */
const prevViewQuery = definition.viewQuery;
if (prevViewQuery) {
definition.viewQuery = (/**
* @param {?} rf
* @param {?} ctx
* @return {?}
*/
(rf, ctx) => {
superViewQuery(rf, ctx);
prevViewQuery(rf, ctx);
});
}
else {
definition.viewQuery = superViewQuery;
}
}
/**
* @param {?} definition
* @param {?} superContentQueries
* @return {?}
*/
function inheritContentQueries(definition, superContentQueries) {
/** @type {?} */
const prevContentQueries = definition.contentQueries;
if (prevContentQueries) {
definition.contentQueries = (/**
* @param {?} rf
* @param {?} ctx
* @param {?} directiveIndex
* @return {?}
*/
(rf, ctx, directiveIndex) => {
superContentQueries(rf, ctx, directiveIndex);
prevContentQueries(rf, ctx, directiveIndex);
});
}
else {
definition.contentQueries = superContentQueries;
}
}
/**
* @param {?} definition
* @param {?} superHostBindings
* @return {?}
*/
function inheritHostBindings(definition, superHostBindings) {
/** @type {?} */
const prevHostBindings = definition.hostBindings;
if (prevHostBindings) {
definition.hostBindings = (/**
* @param {?} rf
* @param {?} ctx
* @return {?}
*/
(rf, ctx) => {
superHostBindings(rf, ctx);
prevHostBindings(rf, ctx);
});
}
else {
definition.hostBindings = superHostBindings;
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/features/copy_definition_feature.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Fields which exist on either directive or component definitions, and need to be copied from
* parent to child classes by the `ɵɵCopyDefinitionFeature`.
* @type {?}
*/
const COPY_DIRECTIVE_FIELDS = [
// The child class should use the providers of its parent.
'providersResolver',
];
/**
* Fields which exist only on component definitions, and need to be copied from parent to child
* classes by the `ɵɵCopyDefinitionFeature`.
*
* The type here allows any field of `ComponentDef` which is not also a property of `DirectiveDef`,
* since those should go in `COPY_DIRECTIVE_FIELDS` above.
* @type {?}
*/
const COPY_COMPONENT_FIELDS = [
// The child class should use the template function of its parent, including all template
// semantics.
'template',
'decls',
'consts',
'vars',
'onPush',
'ngContentSelectors',
// The child class should use the CSS styles of its parent, including all styling semantics.
'styles',
'encapsulation',
// The child class should be checked by the runtime in the same way as its parent.
'schemas',
];
/**
* Copies the fields not handled by the `ɵɵInheritDefinitionFeature` from the supertype of a
* definition.
*
* This exists primarily to support ngcc migration of an existing View Engine pattern, where an
* entire decorator is inherited from a parent to a child class. When ngcc detects this case, it
* generates a skeleton definition on the child class, and applies this feature.
*
* The `ɵɵCopyDefinitionFeature` then copies any needed fields from the parent class' definition,
* including things like the component template function.
*
* \@codeGenApi
* @param {?} definition The definition of a child class which inherits from a parent class with its
* own definition.
*
* @return {?}
*/
function ɵɵCopyDefinitionFeature(definition) {
/** @type {?} */
let superType = (/** @type {?} */ (getSuperType(definition.type)));
/** @type {?} */
let superDef = undefined;
if (isComponentDef(definition)) {
// Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
superDef = (/** @type {?} */ (superType.ɵcmp));
}
else {
// Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
superDef = (/** @type {?} */ (superType.ɵdir));
}
// Needed because `definition` fields are readonly.
/** @type {?} */
const defAny = ((/** @type {?} */ (definition)));
// Copy over any fields that apply to either directives or components.
for (const field of COPY_DIRECTIVE_FIELDS) {
defAny[field] = superDef[field];
}
if (isComponentDef(superDef)) {
// Copy over any component-specific fields.
for (const field of COPY_COMPONENT_FIELDS) {
defAny[field] = superDef[field];
}
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Represents a basic change from a previous to a new value for a single
* property on a directive instance. Passed as a value in a
* {@link SimpleChanges} object to the `ngOnChanges` hook.
*
* @see `OnChanges`
*
* @publicApi
*/
class SimpleChange {
constructor(previousValue, currentValue, firstChange) {
this.previousValue = previousValue;
this.currentValue = currentValue;
this.firstChange = firstChange;
}
/**
* Check whether the new value is the first value assigned.
*/
isFirstChange() {
return this.firstChange;
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/features/ng_onchanges_feature.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const PRIVATE_PREFIX = '__ngOnChanges_';
/**
* The NgOnChangesFeature decorates a component with support for the ngOnChanges
* lifecycle hook, so it should be included in any component that implements
* that hook.
*
* If the component or directive uses inheritance, the NgOnChangesFeature MUST
* be included as a feature AFTER {\@link InheritDefinitionFeature}, otherwise
* inherited properties will not be propagated to the ngOnChanges lifecycle
* hook.
*
* Example usage:
*
* ```
* static ɵcmp = defineComponent({
* ...
* inputs: {name: 'publicName'},
* features: [NgOnChangesFeature]
* });
* ```
*
* \@codeGenApi
* @template T
* @param {?} definition
* @return {?}
*/
function ɵɵNgOnChangesFeature(definition) {
if (definition.type.prototype.ngOnChanges) {
definition.setInput = ngOnChangesSetInput;
((/** @type {?} */ (definition))).onChanges = wrapOnChanges();
}
}
// This option ensures that the ngOnChanges lifecycle hook will be inherited
// from superclasses (in InheritDefinitionFeature).
/** @nocollapse */
// tslint:disable-next-line:no-toplevel-property-access
((/** @type {?} */ (ɵɵNgOnChangesFeature))).ngInherit = true;
/**
* @return {?}
*/
function wrapOnChanges() {
return (/**
* @this {?}
* @return {?}
*/
function wrapOnChangesHook_inPreviousChangesStorage() {
/** @type {?} */
const simpleChangesStore = getSimpleChangesStore(this);
/** @type {?} */
const current = simpleChangesStore && simpleChangesStore.current;
if (current) {
/** @type {?} */
const previous = (/** @type {?} */ (simpleChangesStore)).previous;
if (previous === EMPTY_OBJ) {
(/** @type {?} */ (simpleChangesStore)).previous = current;
}
else {
// New changes are copied to the previous store, so that we don't lose history for inputs
// which were not changed this time
for (let key in current) {
previous[key] = current[key];
}
}
(/** @type {?} */ (simpleChangesStore)).current = null;
this.ngOnChanges(current);
}
});
}
/**
* @template T
* @this {?}
* @param {?} instance
* @param {?} value
* @param {?} publicName
* @param {?} privateName
* @return {?}
*/
function ngOnChangesSetInput(instance, value, publicName, privateName) {
/** @type {?} */
const simpleChangesStore = getSimpleChangesStore(instance) ||
setSimpleChangesStore(instance, { previous: EMPTY_OBJ, current: null });
/** @type {?} */
const current = simpleChangesStore.current || (simpleChangesStore.current = {});
/** @type {?} */
const previous = simpleChangesStore.previous;
/** @type {?} */
const declaredName = ((/** @type {?} */ (this.declaredInputs)))[publicName];
/** @type {?} */
const previousChange = previous[declaredName];
current[declaredName] = new SimpleChange(previousChange && previousChange.currentValue, value, previous === EMPTY_OBJ);
((/** @type {?} */ (instance)))[privateName] = value;
}
/** @type {?} */
const SIMPLE_CHANGES_STORE = '__ngSimpleChanges__';
/**
* @param {?} instance
* @return {?}
*/
function getSimpleChangesStore(instance) {
return instance[SIMPLE_CHANGES_STORE] || null;
}
/**
* @param {?} instance
* @param {?} store
* @return {?}
*/
function setSimpleChangesStore(instance, store) {
return instance[SIMPLE_CHANGES_STORE] = store;
}
/**
* @record
*/
function NgSimpleChangesStore() { }
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/di_setup.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Resolves the providers which are defined in the DirectiveDef.
*
* When inserting the tokens and the factories in their respective arrays, we can assume that
* this method is called first for the component (if any), and then for other directives on the same
* node.
* As a consequence,the providers are always processed in that order:
* 1) The view providers of the component
* 2) The providers of the component
* 3) The providers of the other directives
* This matches the structure of the injectables arrays of a view (for each node).
* So the tokens and the factories can be pushed at the end of the arrays, except
* in one case for multi providers.
*
* @template T
* @param {?} def the directive definition
* @param {?} providers
* @param {?} viewProviders
* @return {?}
*/
function providersResolver(def, providers, viewProviders) {
/** @type {?} */
const tView = getTView();
if (tView.firstCreatePass) {
/** @type {?} */
const isComponent = isComponentDef(def);
// The list of view providers is processed first, and the flags are updated
resolveProvider$1(viewProviders, tView.data, tView.blueprint, isComponent, true);
// Then, the list of providers is processed, and the flags are updated
resolveProvider$1(providers, tView.data, tView.blueprint, isComponent, false);
}
}
/**
* Resolves a provider and publishes it to the DI system.
* @param {?} provider
* @param {?} tInjectables
* @param {?} lInjectablesBlueprint
* @param {?} isComponent
* @param {?} isViewProvider
* @return {?}
*/
function resolveProvider$1(provider, tInjectables, lInjectablesBlueprint, isComponent, isViewProvider) {
provider = resolveForwardRef(provider);
if (Array.isArray(provider)) {
// Recursively call `resolveProvider`
// Recursion is OK in this case because this code will not be in hot-path once we implement
// cloning of the initial state.
for (let i = 0; i < provider.length; i++) {
resolveProvider$1(provider[i], tInjectables, lInjectablesBlueprint, isComponent, isViewProvider);
}
}
else {
/** @type {?} */
const tView = getTView();
/** @type {?} */
const lView = getLView();
/** @type {?} */
let token = isTypeProvider(provider) ? provider : resolveForwardRef(provider.provide);
/** @type {?} */
let providerFactory = providerToFactory(provider);
/** @type {?} */
const tNode = getPreviousOrParentTNode();
/** @type {?} */
const beginIndex = tNode.providerIndexes & 65535 /* ProvidersStartIndexMask */;
/** @type {?} */
const endIndex = tNode.directiveStart;
/** @type {?} */
const cptViewProvidersCount = tNode.providerIndexes >> 16 /* CptViewProvidersCountShift */;
if (isTypeProvider(provider) || !provider.multi) {
// Single provider case: the factory is created and pushed immediately
/** @type {?} */
const factory = new NodeInjectorFactory(providerFactory, isViewProvider, ɵɵdirectiveInject);
/** @type {?} */
const existingFactoryIndex = indexOf(token, tInjectables, isViewProvider ? beginIndex : beginIndex + cptViewProvidersCount, endIndex);
if (existingFactoryIndex === -1) {
diPublicInInjector(getOrCreateNodeInjectorForNode((/** @type {?} */ (tNode)), lView), tView, token);
registerDestroyHooksIfSupported(tView, provider, tInjectables.length);
tInjectables.push(token);
tNode.directiveStart++;
tNode.directiveEnd++;
if (isViewProvider) {
tNode.providerIndexes += 65536 /* CptViewProvidersCountShifter */;
}
lInjectablesBlueprint.push(factory);
lView.push(factory);
}
else {
lInjectablesBlueprint[existingFactoryIndex] = factory;
lView[existingFactoryIndex] = factory;
}
}
else {
// Multi provider case:
// We create a multi factory which is going to aggregate all the values.
// Since the output of such a factory depends on content or view injection,
// we create two of them, which are linked together.
//
// The first one (for view providers) is always in the first block of the injectables array,
// and the second one (for providers) is always in the second block.
// This is important because view providers have higher priority. When a multi token
// is being looked up, the view providers should be found first.
// Note that it is not possible to have a multi factory in the third block (directive block).
//
// The algorithm to process multi providers is as follows:
// 1) If the multi provider comes from the `viewProviders` of the component:
// a) If the special view providers factory doesn't exist, it is created and pushed.
// b) Else, the multi provider is added to the existing multi factory.
// 2) If the multi provider comes from the `providers` of the component or of another
// directive:
// a) If the multi factory doesn't exist, it is created and provider pushed into it.
// It is also linked to the multi factory for view providers, if it exists.
// b) Else, the multi provider is added to the existing multi factory.
/** @type {?} */
const existingProvidersFactoryIndex = indexOf(token, tInjectables, beginIndex + cptViewProvidersCount, endIndex);
/** @type {?} */
const existingViewProvidersFactoryIndex = indexOf(token, tInjectables, beginIndex, beginIndex + cptViewProvidersCount);
/** @type {?} */
const doesProvidersFactoryExist = existingProvidersFactoryIndex >= 0 &&
lInjectablesBlueprint[existingProvidersFactoryIndex];
/** @type {?} */
const doesViewProvidersFactoryExist = existingViewProvidersFactoryIndex >= 0 &&
lInjectablesBlueprint[existingViewProvidersFactoryIndex];
if (isViewProvider && !doesViewProvidersFactoryExist ||
!isViewProvider && !doesProvidersFactoryExist) {
// Cases 1.a and 2.a
diPublicInInjector(getOrCreateNodeInjectorForNode((/** @type {?} */ (tNode)), lView), tView, token);
/** @type {?} */
const factory = multiFactory(isViewProvider ? multiViewProvidersFactoryResolver : multiProvidersFactoryResolver, lInjectablesBlueprint.length, isViewProvider, isComponent, providerFactory);
if (!isViewProvider && doesViewProvidersFactoryExist) {
lInjectablesBlueprint[existingViewProvidersFactoryIndex].providerFactory = factory;
}
registerDestroyHooksIfSupported(tView, provider, tInjectables.length, 0);
tInjectables.push(token);
tNode.directiveStart++;
tNode.directiveEnd++;
if (isViewProvider) {
tNode.providerIndexes += 65536 /* CptViewProvidersCountShifter */;
}
lInjectablesBlueprint.push(factory);
lView.push(factory);
}
else {
// Cases 1.b and 2.b
/** @type {?} */
const indexInFactory = multiFactoryAdd((/** @type {?} */ (lInjectablesBlueprint))[isViewProvider ? existingViewProvidersFactoryIndex :
existingProvidersFactoryIndex], providerFactory, !isViewProvider && isComponent);
registerDestroyHooksIfSupported(tView, provider, existingProvidersFactoryIndex > -1 ? existingProvidersFactoryIndex :
existingViewProvidersFactoryIndex, indexInFactory);
}
if (!isViewProvider && isComponent && doesViewProvidersFactoryExist) {
(/** @type {?} */ (lInjectablesBlueprint[existingViewProvidersFactoryIndex].componentProviders))++;
}
}
}
}
/**
* Registers the `ngOnDestroy` hook of a provider, if the provider supports destroy hooks.
* @param {?} tView `TView` in which to register the hook.
* @param {?} provider Provider whose hook should be registered.
* @param {?} contextIndex Index under which to find the context for the hook when it's being invoked.
* @param {?=} indexInFactory Only required for `multi` providers. Index of the provider in the multi
* provider factory.
* @return {?}
*/
function registerDestroyHooksIfSupported(tView, provider, contextIndex, indexInFactory) {
/** @type {?} */
const providerIsTypeProvider = isTypeProvider(provider);
if (providerIsTypeProvider || isClassProvider(provider)) {
/** @type {?} */
const prototype = (((/** @type {?} */ (provider))).useClass || provider).prototype;
/** @type {?} */
const ngOnDestroy = prototype.ngOnDestroy;
if (ngOnDestroy) {
/** @type {?} */
const hooks = tView.destroyHooks || (tView.destroyHooks = []);
if (!providerIsTypeProvider && (((/** @type {?} */ (provider)))).multi) {
ngDevMode &&
assertDefined(indexInFactory, 'indexInFactory when registering multi factory destroy hook');
/** @type {?} */
const existingCallbacksIndex = hooks.indexOf(contextIndex);
if (existingCallbacksIndex === -1) {
hooks.push(contextIndex, [indexInFactory, ngOnDestroy]);
}
else {
((/** @type {?} */ (hooks[existingCallbacksIndex + 1]))).push((/** @type {?} */ (indexInFactory)), ngOnDestroy);
}
}
else {
hooks.push(contextIndex, ngOnDestroy);
}
}
}
}
/**
* Add a factory in a multi factory.
* @param {?} multiFactory
* @param {?} factory
* @param {?} isComponentProvider
* @return {?} Index at which the factory was inserted.
*/
function multiFactoryAdd(multiFactory, factory, isComponentProvider) {
if (isComponentProvider) {
(/** @type {?} */ (multiFactory.componentProviders))++;
}
return (/** @type {?} */ (multiFactory.multi)).push(factory) - 1;
}
/**
* Returns the index of item in the array, but only in the begin to end range.
* @param {?} item
* @param {?} arr
* @param {?} begin
* @param {?} end
* @return {?}
*/
function indexOf(item, arr, begin, end) {
for (let i = begin; i < end; i++) {
if (arr[i] === item)
return i;
}
return -1;
}
/**
* Use this with `multi` `providers`.
* @this {?}
* @param {?} _
* @param {?} tData
* @param {?} lData
* @param {?} tNode
* @return {?}
*/
function multiProvidersFactoryResolver(_, tData, lData, tNode) {
return multiResolve((/** @type {?} */ (this.multi)), []);
}
/**
* Use this with `multi` `viewProviders`.
*
* This factory knows how to concatenate itself with the existing `multi` `providers`.
* @this {?}
* @param {?} _
* @param {?} tData
* @param {?} lView
* @param {?} tNode
* @return {?}
*/
function multiViewProvidersFactoryResolver(_, tData, lView, tNode) {
/** @type {?} */
const factories = (/** @type {?} */ (this.multi));
/** @type {?} */
let result;
if (this.providerFactory) {
/** @type {?} */
const componentCount = (/** @type {?} */ (this.providerFactory.componentProviders));
/** @type {?} */
const multiProviders = getNodeInjectable(lView, lView[TVIEW], (/** @type {?} */ ((/** @type {?} */ (this.providerFactory)).index)), tNode);
// Copy the section of the array which contains `multi` `providers` from the component
result = multiProviders.slice(0, componentCount);
// Insert the `viewProvider` instances.
multiResolve(factories, result);
// Copy the section of the array which contains `multi` `providers` from other directives
for (let i = componentCount; i < multiProviders.length; i++) {
result.push(multiProviders[i]);
}
}
else {
result = [];
// Insert the `viewProvider` instances.
multiResolve(factories, result);
}
return result;
}
/**
* Maps an array of factories into an array of values.
* @param {?} factories
* @param {?} result
* @return {?}
*/
function multiResolve(factories, result) {
for (let i = 0; i < factories.length; i++) {
/** @type {?} */
const factory = (/** @type {?} */ ((/** @type {?} */ (factories[i]))));
result.push(factory());
}
return result;
}
/**
* Creates a multi factory.
* @param {?} factoryFn
* @param {?} index
* @param {?} isViewProvider
* @param {?} isComponent
* @param {?} f
* @return {?}
*/
function multiFactory(factoryFn, index, isViewProvider, isComponent, f) {
/** @type {?} */
const factory = new NodeInjectorFactory(factoryFn, isViewProvider, ɵɵdirectiveInject);
factory.multi = [];
factory.index = index;
factory.componentProviders = 0;
multiFactoryAdd(factory, f, isComponent && !isViewProvider);
return factory;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/features/providers_feature.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* This feature resolves the providers of a directive (or component),
* and publish them into the DI system, making it visible to others for injection.
*
* For example:
* ```ts
* class ComponentWithProviders {
* constructor(private greeter: GreeterDE) {}
*
* static ɵcmp = defineComponent({
* type: ComponentWithProviders,
* selectors: [['component-with-providers']],
* factory: () => new ComponentWithProviders(directiveInject(GreeterDE as any)),
* decls: 1,
* vars: 1,
* template: function(fs: RenderFlags, ctx: ComponentWithProviders) {
* if (fs & RenderFlags.Create) {
* ɵɵtext(0);
* }
* if (fs & RenderFlags.Update) {
* ɵɵtextInterpolate(ctx.greeter.greet());
* }
* },
* features: [ProvidersFeature([GreeterDE])]
* });
* }
* ```
*
* \@codeGenApi
* @template T
* @param {?} providers
* @param {?=} viewProviders
* @return {?}
*/
function ɵɵProvidersFeature(providers, viewProviders = []) {
return (/**
* @param {?} definition
* @return {?}
*/
(definition) => {
definition.providersResolver =
(/**
* @param {?} def
* @param {?=} processProvidersFn
* @return {?}
*/
(def, processProvidersFn) => {
return providersResolver(def, //
processProvidersFn ? processProvidersFn(providers) : providers, //
viewProviders);
});
});
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/component_factory.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Represents a component created by a `ComponentFactory`.
* Provides access to the component instance and related objects,
* and provides the means of destroying the instance.
*
* \@publicApi
* @abstract
* @template C
*/
class ComponentRef {
}
if (false) {}
/**
* Base class for a factory that can create a component dynamically.
* Instantiate a factory for a given type of component with `resolveComponentFactory()`.
* Use the resulting `ComponentFactory.create()` method to create a component of that type.
*
* @see [Dynamic Components](guide/dynamic-component-loader)
*
* \@publicApi
* @abstract
* @template C
*/
class ComponentFactory {
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/component_factory_resolver.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} component
* @return {?}
*/
function noComponentFactoryError(component) {
/** @type {?} */
const error = Error(`No component factory found for ${stringify(component)}. Did you add it to @NgModule.entryComponents?`);
((/** @type {?} */ (error)))[ERROR_COMPONENT] = component;
return error;
}
/** @type {?} */
const ERROR_COMPONENT = 'ngComponent';
/**
* @param {?} error
* @return {?}
*/
function getComponent$1(error) {
return ((/** @type {?} */ (error)))[ERROR_COMPONENT];
}
class _NullComponentFactoryResolver {
/**
* @template T
* @param {?} component
* @return {?}
*/
resolveComponentFactory(component) {
throw noComponentFactoryError(component);
}
}
/**
* A simple registry that maps `Components` to generated `ComponentFactory` classes
* that can be used to create instances of components.
* Use to obtain the factory for a given component type,
* then use the factory's `create()` method to create a component of that type.
*
* @see [Dynamic Components](guide/dynamic-component-loader)
* \@publicApi
* @abstract
*/
class ComponentFactoryResolver {
}
ComponentFactoryResolver.NULL = new _NullComponentFactoryResolver();
if (false) {}
class CodegenComponentFactoryResolver {
/**
* @param {?} factories
* @param {?} _parent
* @param {?} _ngModule
*/
constructor(factories, _parent, _ngModule) {
this._parent = _parent;
this._ngModule = _ngModule;
this._factories = new Map();
for (let i = 0; i < factories.length; i++) {
/** @type {?} */
const factory = factories[i];
this._factories.set(factory.componentType, factory);
}
}
/**
* @template T
* @param {?} component
* @return {?}
*/
resolveComponentFactory(component) {
/** @type {?} */
let factory = this._factories.get(component);
if (!factory && this._parent) {
factory = this._parent.resolveComponentFactory(component);
}
if (!factory) {
throw noComponentFactoryError(component);
}
return new ComponentFactoryBoundToModule(factory, this._ngModule);
}
}
if (false) {}
/**
* @template C
*/
class ComponentFactoryBoundToModule extends ComponentFactory {
/**
* @param {?} factory
* @param {?} ngModule
*/
constructor(factory, ngModule) {
super();
this.factory = factory;
this.ngModule = ngModule;
this.selector = factory.selector;
this.componentType = factory.componentType;
this.ngContentSelectors = factory.ngContentSelectors;
this.inputs = factory.inputs;
this.outputs = factory.outputs;
}
/**
* @param {?} injector
* @param {?=} projectableNodes
* @param {?=} rootSelectorOrNode
* @param {?=} ngModule
* @return {?}
*/
create(injector, projectableNodes, rootSelectorOrNode, ngModule) {
return this.factory.create(injector, projectableNodes, rootSelectorOrNode, ngModule || this.ngModule);
}
}
if (false) {}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function noop(...args) {
// Do nothing.
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/element_ref.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A wrapper around a native element inside of a View.
*
* An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM
* element.
*
* \@security Permitting direct access to the DOM can make your application more vulnerable to
* XSS attacks. Carefully review any use of `ElementRef` in your code. For more detail, see the
* [Security Guide](http://g.co/ng/security).
*
* \@publicApi
* @template T
*/
// Note: We don't expose things like `Injector`, `ViewContainer`, ... here,
// i.e. users have to ask for what they need. With that, we can build better analysis tools
// and could do better codegen in the future.
class ElementRef {
/**
* @param {?} nativeElement
*/
constructor(nativeElement) {
this.nativeElement = nativeElement;
}
}
/**
* \@internal
* @nocollapse
*/
ElementRef.__NG_ELEMENT_ID__ = (/**
* @return {?}
*/
() => SWITCH_ELEMENT_REF_FACTORY(ElementRef));
if (false) {}
/** @type {?} */
const SWITCH_ELEMENT_REF_FACTORY__POST_R3__ = injectElementRef;
/** @type {?} */
const SWITCH_ELEMENT_REF_FACTORY__PRE_R3__ = noop;
/** @type {?} */
const SWITCH_ELEMENT_REF_FACTORY = SWITCH_ELEMENT_REF_FACTORY__POST_R3__;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render/api.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const Renderer2Interceptor = new InjectionToken('Renderer2Interceptor');
/**
* Used by `RendererFactory2` to associate custom rendering data and styles
* with a rendering implementation.
* \@publicApi
* @record
*/
function RendererType2() { }
if (false) {}
/**
* Creates and initializes a custom renderer that implements the `Renderer2` base class.
*
* \@publicApi
* @abstract
*/
class RendererFactory2 {
}
if (false) {}
/** @enum {number} */
const RendererStyleFlags2 = {
// TODO(misko): This needs to be refactored into a separate file so that it can be imported from
// `node_manipulation.ts` Currently doing the import cause resolution order to change and fails
// the tests. The work around is to have hard coded value in `node_manipulation.ts` for now.
/**
* Marks a style as important.
*/
Important: 1,
/**
* Marks a style as using dash case naming (this-is-dash-case).
*/
DashCase: 2,
};
RendererStyleFlags2[RendererStyleFlags2.Important] = 'Important';
RendererStyleFlags2[RendererStyleFlags2.DashCase] = 'DashCase';
/**
* Extend this base class to implement custom rendering. By default, Angular
* renders a template into DOM. You can use custom rendering to intercept
* rendering calls, or to render to something other than DOM.
*
* Create your custom renderer using `RendererFactory2`.
*
* Use a custom renderer to bypass Angular's templating and
* make custom UI changes that can't be expressed declaratively.
* For example if you need to set a property or an attribute whose name is
* not statically known, use the `setProperty()` or
* `setAttribute()` method.
*
* \@publicApi
* @abstract
*/
class Renderer2 {
}
/**
* \@internal
* @nocollapse
*/
Renderer2.__NG_ELEMENT_ID__ = (/**
* @return {?}
*/
() => SWITCH_RENDERER2_FACTORY());
if (false) {}
/** @type {?} */
const SWITCH_RENDERER2_FACTORY__POST_R3__ = injectRenderer2;
/** @type {?} */
const SWITCH_RENDERER2_FACTORY__PRE_R3__ = noop;
/** @type {?} */
const SWITCH_RENDERER2_FACTORY = SWITCH_RENDERER2_FACTORY__POST_R3__;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/sanitization/sanitizer.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Sanitizer is used by the views to sanitize potentially dangerous values.
*
* \@publicApi
* @abstract
*/
class Sanitizer {
}
/** @nocollapse */
Sanitizer.ɵprov = ɵɵdefineInjectable({
token: Sanitizer,
providedIn: 'root',
factory: (/**
* @return {?}
*/
() => null),
});
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/version.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@description Represents the version of Angular
*
* \@publicApi
*/
class Version {
/**
* @param {?} full
*/
constructor(full) {
this.full = full;
this.major = full.split('.')[0];
this.minor = full.split('.')[1];
this.patch = full.split('.').slice(2).join('.');
}
}
if (false) {}
/**
* \@publicApi
* @type {?}
*/
const VERSION = new Version('9.1.13');
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/change_detection/differs/default_iterable_differ.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class DefaultIterableDifferFactory {
constructor() { }
/**
* @param {?} obj
* @return {?}
*/
supports(obj) {
return isListLikeIterable$1(obj);
}
/**
* @template V
* @param {?=} trackByFn
* @return {?}
*/
create(trackByFn) {
return new DefaultIterableDiffer(trackByFn);
}
}
/** @type {?} */
const trackByIdentity = (/**
* @param {?} index
* @param {?} item
* @return {?}
*/
(index, item) => item);
const ɵ0$c = trackByIdentity;
/**
* @deprecated v4.0.0 - Should not be part of public API.
* \@publicApi
* @template V
*/
class DefaultIterableDiffer {
/**
* @param {?=} trackByFn
*/
constructor(trackByFn) {
this.length = 0;
// Keeps track of the used records at any point in time (during & across `_check()` calls)
this._linkedRecords = null;
// Keeps track of the removed records at any point in time during `_check()` calls.
this._unlinkedRecords = null;
this._previousItHead = null;
this._itHead = null;
this._itTail = null;
this._additionsHead = null;
this._additionsTail = null;
this._movesHead = null;
this._movesTail = null;
this._removalsHead = null;
this._removalsTail = null;
// Keeps track of records where custom track by is the same, but item identity has changed
this._identityChangesHead = null;
this._identityChangesTail = null;
this._trackByFn = trackByFn || trackByIdentity;
}
/**
* @param {?} fn
* @return {?}
*/
forEachItem(fn) {
/** @type {?} */
let record;
for (record = this._itHead; record !== null; record = record._next) {
fn(record);
}
}
/**
* @param {?} fn
* @return {?}
*/
forEachOperation(fn) {
/** @type {?} */
let nextIt = this._itHead;
/** @type {?} */
let nextRemove = this._removalsHead;
/** @type {?} */
let addRemoveOffset = 0;
/** @type {?} */
let moveOffsets = null;
while (nextIt || nextRemove) {
// Figure out which is the next record to process
// Order: remove, add, move
/** @type {?} */
const record = !nextRemove ||
nextIt &&
(/** @type {?} */ (nextIt.currentIndex)) <
getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets) ?
(/** @type {?} */ (nextIt)) :
nextRemove;
/** @type {?} */
const adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets);
/** @type {?} */
const currentIndex = record.currentIndex;
// consume the item, and adjust the addRemoveOffset and update moveDistance if necessary
if (record === nextRemove) {
addRemoveOffset--;
nextRemove = nextRemove._nextRemoved;
}
else {
nextIt = (/** @type {?} */ (nextIt))._next;
if (record.previousIndex == null) {
addRemoveOffset++;
}
else {
// INVARIANT: currentIndex < previousIndex
if (!moveOffsets)
moveOffsets = [];
/** @type {?} */
const localMovePreviousIndex = adjPreviousIndex - addRemoveOffset;
/** @type {?} */
const localCurrentIndex = (/** @type {?} */ (currentIndex)) - addRemoveOffset;
if (localMovePreviousIndex != localCurrentIndex) {
for (let i = 0; i < localMovePreviousIndex; i++) {
/** @type {?} */
const offset = i < moveOffsets.length ? moveOffsets[i] : (moveOffsets[i] = 0);
/** @type {?} */
const index = offset + i;
if (localCurrentIndex <= index && index < localMovePreviousIndex) {
moveOffsets[i] = offset + 1;
}
}
/** @type {?} */
const previousIndex = record.previousIndex;
moveOffsets[previousIndex] = localCurrentIndex - localMovePreviousIndex;
}
}
}
if (adjPreviousIndex !== currentIndex) {
fn(record, adjPreviousIndex, currentIndex);
}
}
}
/**
* @param {?} fn
* @return {?}
*/
forEachPreviousItem(fn) {
/** @type {?} */
let record;
for (record = this._previousItHead; record !== null; record = record._nextPrevious) {
fn(record);
}
}
/**
* @param {?} fn
* @return {?}
*/
forEachAddedItem(fn) {
/** @type {?} */
let record;
for (record = this._additionsHead; record !== null; record = record._nextAdded) {
fn(record);
}
}
/**
* @param {?} fn
* @return {?}
*/
forEachMovedItem(fn) {
/** @type {?} */
let record;
for (record = this._movesHead; record !== null; record = record._nextMoved) {
fn(record);
}
}
/**
* @param {?} fn
* @return {?}
*/
forEachRemovedItem(fn) {
/** @type {?} */
let record;
for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
fn(record);
}
}
/**
* @param {?} fn
* @return {?}
*/
forEachIdentityChange(fn) {
/** @type {?} */
let record;
for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) {
fn(record);
}
}
/**
* @param {?} collection
* @return {?}
*/
diff(collection) {
if (collection == null)
collection = [];
if (!isListLikeIterable$1(collection)) {
throw new Error(`Error trying to diff '${stringify(collection)}'. Only arrays and iterables are allowed`);
}
if (this.check(collection)) {
return this;
}
else {
return null;
}
}
/**
* @return {?}
*/
onDestroy() { }
/**
* @param {?} collection
* @return {?}
*/
check(collection) {
this._reset();
/** @type {?} */
let record = this._itHead;
/** @type {?} */
let mayBeDirty = false;
/** @type {?} */
let index;
/** @type {?} */
let item;
/** @type {?} */
let itemTrackBy;
if (Array.isArray(collection)) {
((/** @type {?} */ (this))).length = collection.length;
for (let index = 0; index < this.length; index++) {
item = collection[index];
itemTrackBy = this._trackByFn(index, item);
if (record === null || !looseIdentical(record.trackById, itemTrackBy)) {
record = this._mismatch(record, item, itemTrackBy, index);
mayBeDirty = true;
}
else {
if (mayBeDirty) {
// TODO(misko): can we limit this to duplicates only?
record = this._verifyReinsertion(record, item, itemTrackBy, index);
}
if (!looseIdentical(record.item, item))
this._addIdentityChange(record, item);
}
record = record._next;
}
}
else {
index = 0;
iterateListLike$1(collection, (/**
* @param {?} item
* @return {?}
*/
(item) => {
itemTrackBy = this._trackByFn(index, item);
if (record === null || !looseIdentical(record.trackById, itemTrackBy)) {
record = this._mismatch(record, item, itemTrackBy, index);
mayBeDirty = true;
}
else {
if (mayBeDirty) {
// TODO(misko): can we limit this to duplicates only?
record = this._verifyReinsertion(record, item, itemTrackBy, index);
}
if (!looseIdentical(record.item, item))
this._addIdentityChange(record, item);
}
record = record._next;
index++;
}));
((/** @type {?} */ (this))).length = index;
}
this._truncate(record);
((/** @type {?} */ (this))).collection = collection;
return this.isDirty;
}
/* CollectionChanges is considered dirty if it has any additions, moves, removals, or identity
* changes.
*/
/**
* @return {?}
*/
get isDirty() {
return this._additionsHead !== null || this._movesHead !== null ||
this._removalsHead !== null || this._identityChangesHead !== null;
}
/**
* Reset the state of the change objects to show no changes. This means set previousKey to
* currentKey, and clear all of the queues (additions, moves, removals).
* Set the previousIndexes of moved and added items to their currentIndexes
* Reset the list of additions, moves and removals
*
* \@internal
* @return {?}
*/
_reset() {
if (this.isDirty) {
/** @type {?} */
let record;
/** @type {?} */
let nextRecord;
for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {
record._nextPrevious = record._next;
}
for (record = this._additionsHead; record !== null; record = record._nextAdded) {
record.previousIndex = record.currentIndex;
}
this._additionsHead = this._additionsTail = null;
for (record = this._movesHead; record !== null; record = nextRecord) {
record.previousIndex = record.currentIndex;
nextRecord = record._nextMoved;
}
this._movesHead = this._movesTail = null;
this._removalsHead = this._removalsTail = null;
this._identityChangesHead = this._identityChangesTail = null;
// TODO(vicb): when assert gets supported
// assert(!this.isDirty);
}
}
/**
* This is the core function which handles differences between collections.
*
* - `record` is the record which we saw at this position last time. If null then it is a new
* item.
* - `item` is the current item in the collection
* - `index` is the position of the item in the collection
*
* \@internal
* @param {?} record
* @param {?} item
* @param {?} itemTrackBy
* @param {?} index
* @return {?}
*/
_mismatch(record, item, itemTrackBy, index) {
// The previous record after which we will append the current one.
/** @type {?} */
let previousRecord;
if (record === null) {
previousRecord = this._itTail;
}
else {
previousRecord = record._prev;
// Remove the record from the collection since we know it does not match the item.
this._remove(record);
}
// Attempt to see if we have seen the item before.
record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index);
if (record !== null) {
// We have seen this before, we need to move it forward in the collection.
// But first we need to check if identity changed, so we can update in view if necessary
if (!looseIdentical(record.item, item))
this._addIdentityChange(record, item);
this._moveAfter(record, previousRecord, index);
}
else {
// Never seen it, check evicted list.
record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
if (record !== null) {
// It is an item which we have evicted earlier: reinsert it back into the list.
// But first we need to check if identity changed, so we can update in view if necessary
if (!looseIdentical(record.item, item))
this._addIdentityChange(record, item);
this._reinsertAfter(record, previousRecord, index);
}
else {
// It is a new item: add it.
record =
this._addAfter(new IterableChangeRecord_(item, itemTrackBy), previousRecord, index);
}
}
return record;
}
/**
* This check is only needed if an array contains duplicates. (Short circuit of nothing dirty)
*
* Use case: `[a, a]` => `[b, a, a]`
*
* If we did not have this check then the insertion of `b` would:
* 1) evict first `a`
* 2) insert `b` at `0` index.
* 3) leave `a` at index `1` as is. <-- this is wrong!
* 3) reinsert `a` at index 2. <-- this is wrong!
*
* The correct behavior is:
* 1) evict first `a`
* 2) insert `b` at `0` index.
* 3) reinsert `a` at index 1.
* 3) move `a` at from `1` to `2`.
*
*
* Double check that we have not evicted a duplicate item. We need to check if the item type may
* have already been removed:
* The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted
* at the end. Which will show up as the two 'a's switching position. This is incorrect, since a
* better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a'
* at the end.
*
* \@internal
* @param {?} record
* @param {?} item
* @param {?} itemTrackBy
* @param {?} index
* @return {?}
*/
_verifyReinsertion(record, item, itemTrackBy, index) {
/** @type {?} */
let reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
if (reinsertRecord !== null) {
record = this._reinsertAfter(reinsertRecord, (/** @type {?} */ (record._prev)), index);
}
else if (record.currentIndex != index) {
record.currentIndex = index;
this._addToMoves(record, index);
}
return record;
}
/**
* Get rid of any excess {\@link IterableChangeRecord_}s from the previous collection
*
* - `record` The first excess {\@link IterableChangeRecord_}.
*
* \@internal
* @param {?} record
* @return {?}
*/
_truncate(record) {
// Anything after that needs to be removed;
while (record !== null) {
/** @type {?} */
const nextRecord = record._next;
this._addToRemovals(this._unlink(record));
record = nextRecord;
}
if (this._unlinkedRecords !== null) {
this._unlinkedRecords.clear();
}
if (this._additionsTail !== null) {
this._additionsTail._nextAdded = null;
}
if (this._movesTail !== null) {
this._movesTail._nextMoved = null;
}
if (this._itTail !== null) {
this._itTail._next = null;
}
if (this._removalsTail !== null) {
this._removalsTail._nextRemoved = null;
}
if (this._identityChangesTail !== null) {
this._identityChangesTail._nextIdentityChange = null;
}
}
/**
* \@internal
* @param {?} record
* @param {?} prevRecord
* @param {?} index
* @return {?}
*/
_reinsertAfter(record, prevRecord, index) {
if (this._unlinkedRecords !== null) {
this._unlinkedRecords.remove(record);
}
/** @type {?} */
const prev = record._prevRemoved;
/** @type {?} */
const next = record._nextRemoved;
if (prev === null) {
this._removalsHead = next;
}
else {
prev._nextRemoved = next;
}
if (next === null) {
this._removalsTail = prev;
}
else {
next._prevRemoved = prev;
}
this._insertAfter(record, prevRecord, index);
this._addToMoves(record, index);
return record;
}
/**
* \@internal
* @param {?} record
* @param {?} prevRecord
* @param {?} index
* @return {?}
*/
_moveAfter(record, prevRecord, index) {
this._unlink(record);
this._insertAfter(record, prevRecord, index);
this._addToMoves(record, index);
return record;
}
/**
* \@internal
* @param {?} record
* @param {?} prevRecord
* @param {?} index
* @return {?}
*/
_addAfter(record, prevRecord, index) {
this._insertAfter(record, prevRecord, index);
if (this._additionsTail === null) {
// TODO(vicb):
// assert(this._additionsHead === null);
this._additionsTail = this._additionsHead = record;
}
else {
// TODO(vicb):
// assert(_additionsTail._nextAdded === null);
// assert(record._nextAdded === null);
this._additionsTail = this._additionsTail._nextAdded = record;
}
return record;
}
/**
* \@internal
* @param {?} record
* @param {?} prevRecord
* @param {?} index
* @return {?}
*/
_insertAfter(record, prevRecord, index) {
// TODO(vicb):
// assert(record != prevRecord);
// assert(record._next === null);
// assert(record._prev === null);
// TODO(vicb):
// assert(record != prevRecord);
// assert(record._next === null);
// assert(record._prev === null);
/** @type {?} */
const next = prevRecord === null ? this._itHead : prevRecord._next;
// TODO(vicb):
// assert(next != record);
// assert(prevRecord != record);
record._next = next;
record._prev = prevRecord;
if (next === null) {
this._itTail = record;
}
else {
next._prev = record;
}
if (prevRecord === null) {
this._itHead = record;
}
else {
prevRecord._next = record;
}
if (this._linkedRecords === null) {
this._linkedRecords = new _DuplicateMap();
}
this._linkedRecords.put(record);
record.currentIndex = index;
return record;
}
/**
* \@internal
* @param {?} record
* @return {?}
*/
_remove(record) {
return this._addToRemovals(this._unlink(record));
}
/**
* \@internal
* @param {?} record
* @return {?}
*/
_unlink(record) {
if (this._linkedRecords !== null) {
this._linkedRecords.remove(record);
}
/** @type {?} */
const prev = record._prev;
/** @type {?} */
const next = record._next;
// TODO(vicb):
// assert((record._prev = null) === null);
// assert((record._next = null) === null);
if (prev === null) {
this._itHead = next;
}
else {
prev._next = next;
}
if (next === null) {
this._itTail = prev;
}
else {
next._prev = prev;
}
return record;
}
/**
* \@internal
* @param {?} record
* @param {?} toIndex
* @return {?}
*/
_addToMoves(record, toIndex) {
// TODO(vicb):
// assert(record._nextMoved === null);
if (record.previousIndex === toIndex) {
return record;
}
if (this._movesTail === null) {
// TODO(vicb):
// assert(_movesHead === null);
this._movesTail = this._movesHead = record;
}
else {
// TODO(vicb):
// assert(_movesTail._nextMoved === null);
this._movesTail = this._movesTail._nextMoved = record;
}
return record;
}
/**
* @private
* @param {?} record
* @return {?}
*/
_addToRemovals(record) {
if (this._unlinkedRecords === null) {
this._unlinkedRecords = new _DuplicateMap();
}
this._unlinkedRecords.put(record);
record.currentIndex = null;
record._nextRemoved = null;
if (this._removalsTail === null) {
// TODO(vicb):
// assert(_removalsHead === null);
this._removalsTail = this._removalsHead = record;
record._prevRemoved = null;
}
else {
// TODO(vicb):
// assert(_removalsTail._nextRemoved === null);
// assert(record._nextRemoved === null);
record._prevRemoved = this._removalsTail;
this._removalsTail = this._removalsTail._nextRemoved = record;
}
return record;
}
/**
* \@internal
* @param {?} record
* @param {?} item
* @return {?}
*/
_addIdentityChange(record, item) {
record.item = item;
if (this._identityChangesTail === null) {
this._identityChangesTail = this._identityChangesHead = record;
}
else {
this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record;
}
return record;
}
}
if (false) {}
/**
* @template V
*/
class IterableChangeRecord_ {
/**
* @param {?} item
* @param {?} trackById
*/
constructor(item, trackById) {
this.item = item;
this.trackById = trackById;
this.currentIndex = null;
this.previousIndex = null;
/**
* \@internal
*/
this._nextPrevious = null;
/**
* \@internal
*/
this._prev = null;
/**
* \@internal
*/
this._next = null;
/**
* \@internal
*/
this._prevDup = null;
/**
* \@internal
*/
this._nextDup = null;
/**
* \@internal
*/
this._prevRemoved = null;
/**
* \@internal
*/
this._nextRemoved = null;
/**
* \@internal
*/
this._nextAdded = null;
/**
* \@internal
*/
this._nextMoved = null;
/**
* \@internal
*/
this._nextIdentityChange = null;
}
}
if (false) {}
// A linked list of CollectionChangeRecords with the same IterableChangeRecord_.item
/**
* @template V
*/
class _DuplicateItemRecordList {
constructor() {
/**
* \@internal
*/
this._head = null;
/**
* \@internal
*/
this._tail = null;
}
/**
* Append the record to the list of duplicates.
*
* Note: by design all records in the list of duplicates hold the same value in record.item.
* @param {?} record
* @return {?}
*/
add(record) {
if (this._head === null) {
this._head = this._tail = record;
record._nextDup = null;
record._prevDup = null;
}
else {
// TODO(vicb):
// assert(record.item == _head.item ||
// record.item is num && record.item.isNaN && _head.item is num && _head.item.isNaN);
(/** @type {?} */ (this._tail))._nextDup = record;
record._prevDup = this._tail;
record._nextDup = null;
this._tail = record;
}
}
// Returns a IterableChangeRecord_ having IterableChangeRecord_.trackById == trackById and
// IterableChangeRecord_.currentIndex >= atOrAfterIndex
/**
* @param {?} trackById
* @param {?} atOrAfterIndex
* @return {?}
*/
get(trackById, atOrAfterIndex) {
/** @type {?} */
let record;
for (record = this._head; record !== null; record = record._nextDup) {
if ((atOrAfterIndex === null || atOrAfterIndex <= (/** @type {?} */ (record.currentIndex))) &&
looseIdentical(record.trackById, trackById)) {
return record;
}
}
return null;
}
/**
* Remove one {\@link IterableChangeRecord_} from the list of duplicates.
*
* Returns whether the list of duplicates is empty.
* @param {?} record
* @return {?}
*/
remove(record) {
// TODO(vicb):
// assert(() {
// // verify that the record being removed is in the list.
// for (IterableChangeRecord_ cursor = _head; cursor != null; cursor = cursor._nextDup) {
// if (identical(cursor, record)) return true;
// }
// return false;
//});
// TODO(vicb):
// assert(() {
// // verify that the record being removed is in the list.
// for (IterableChangeRecord_ cursor = _head; cursor != null; cursor = cursor._nextDup) {
// if (identical(cursor, record)) return true;
// }
// return false;
//});
/** @type {?} */
const prev = record._prevDup;
/** @type {?} */
const next = record._nextDup;
if (prev === null) {
this._head = next;
}
else {
prev._nextDup = next;
}
if (next === null) {
this._tail = prev;
}
else {
next._prevDup = prev;
}
return this._head === null;
}
}
if (false) {}
/**
* @template V
*/
class _DuplicateMap {
constructor() {
this.map = new Map();
}
/**
* @param {?} record
* @return {?}
*/
put(record) {
/** @type {?} */
const key = record.trackById;
/** @type {?} */
let duplicates = this.map.get(key);
if (!duplicates) {
duplicates = new _DuplicateItemRecordList();
this.map.set(key, duplicates);
}
duplicates.add(record);
}
/**
* Retrieve the `value` using key. Because the IterableChangeRecord_ value may be one which we
* have already iterated over, we use the `atOrAfterIndex` to pretend it is not there.
*
* Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we
* have any more `a`s needs to return the second `a`.
* @param {?} trackById
* @param {?} atOrAfterIndex
* @return {?}
*/
get(trackById, atOrAfterIndex) {
/** @type {?} */
const key = trackById;
/** @type {?} */
const recordList = this.map.get(key);
return recordList ? recordList.get(trackById, atOrAfterIndex) : null;
}
/**
* Removes a {\@link IterableChangeRecord_} from the list of duplicates.
*
* The list of duplicates also is removed from the map if it gets empty.
* @param {?} record
* @return {?}
*/
remove(record) {
/** @type {?} */
const key = record.trackById;
/** @type {?} */
const recordList = (/** @type {?} */ (this.map.get(key)));
// Remove the list of duplicates when it gets empty
if (recordList.remove(record)) {
this.map.delete(key);
}
return record;
}
/**
* @return {?}
*/
get isEmpty() {
return this.map.size === 0;
}
/**
* @return {?}
*/
clear() {
this.map.clear();
}
}
if (false) {}
/**
* @param {?} item
* @param {?} addRemoveOffset
* @param {?} moveOffsets
* @return {?}
*/
function getPreviousIndex(item, addRemoveOffset, moveOffsets) {
/** @type {?} */
const previousIndex = item.previousIndex;
if (previousIndex === null)
return previousIndex;
/** @type {?} */
let moveOffset = 0;
if (moveOffsets && previousIndex < moveOffsets.length) {
moveOffset = moveOffsets[previousIndex];
}
return previousIndex + addRemoveOffset + moveOffset;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/change_detection/differs/default_keyvalue_differ.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @template K, V
*/
class DefaultKeyValueDifferFactory {
constructor() { }
/**
* @param {?} obj
* @return {?}
*/
supports(obj) {
return obj instanceof Map || isJsObject$1(obj);
}
/**
* @template K, V
* @return {?}
*/
create() {
return new DefaultKeyValueDiffer();
}
}
/**
* @template K, V
*/
class DefaultKeyValueDiffer {
constructor() {
this._records = new Map();
this._mapHead = null;
// _appendAfter is used in the check loop
this._appendAfter = null;
this._previousMapHead = null;
this._changesHead = null;
this._changesTail = null;
this._additionsHead = null;
this._additionsTail = null;
this._removalsHead = null;
this._removalsTail = null;
}
/**
* @return {?}
*/
get isDirty() {
return this._additionsHead !== null || this._changesHead !== null ||
this._removalsHead !== null;
}
/**
* @param {?} fn
* @return {?}
*/
forEachItem(fn) {
/** @type {?} */
let record;
for (record = this._mapHead; record !== null; record = record._next) {
fn(record);
}
}
/**
* @param {?} fn
* @return {?}
*/
forEachPreviousItem(fn) {
/** @type {?} */
let record;
for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
fn(record);
}
}
/**
* @param {?} fn
* @return {?}
*/
forEachChangedItem(fn) {
/** @type {?} */
let record;
for (record = this._changesHead; record !== null; record = record._nextChanged) {
fn(record);
}
}
/**
* @param {?} fn
* @return {?}
*/
forEachAddedItem(fn) {
/** @type {?} */
let record;
for (record = this._additionsHead; record !== null; record = record._nextAdded) {
fn(record);
}
}
/**
* @param {?} fn
* @return {?}
*/
forEachRemovedItem(fn) {
/** @type {?} */
let record;
for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
fn(record);
}
}
/**
* @param {?=} map
* @return {?}
*/
diff(map) {
if (!map) {
map = new Map();
}
else if (!(map instanceof Map || isJsObject$1(map))) {
throw new Error(`Error trying to diff '${stringify(map)}'. Only maps and objects are allowed`);
}
return this.check(map) ? this : null;
}
/**
* @return {?}
*/
onDestroy() { }
/**
* Check the current state of the map vs the previous.
* The algorithm is optimised for when the keys do no change.
* @param {?} map
* @return {?}
*/
check(map) {
this._reset();
/** @type {?} */
let insertBefore = this._mapHead;
this._appendAfter = null;
this._forEach(map, (/**
* @param {?} value
* @param {?} key
* @return {?}
*/
(value, key) => {
if (insertBefore && insertBefore.key === key) {
this._maybeAddToChanges(insertBefore, value);
this._appendAfter = insertBefore;
insertBefore = insertBefore._next;
}
else {
/** @type {?} */
const record = this._getOrCreateRecordForKey(key, value);
insertBefore = this._insertBeforeOrAppend(insertBefore, record);
}
}));
// Items remaining at the end of the list have been deleted
if (insertBefore) {
if (insertBefore._prev) {
insertBefore._prev._next = null;
}
this._removalsHead = insertBefore;
for (let record = insertBefore; record !== null; record = record._nextRemoved) {
if (record === this._mapHead) {
this._mapHead = null;
}
this._records.delete(record.key);
record._nextRemoved = record._next;
record.previousValue = record.currentValue;
record.currentValue = null;
record._prev = null;
record._next = null;
}
}
// Make sure tails have no next records from previous runs
if (this._changesTail)
this._changesTail._nextChanged = null;
if (this._additionsTail)
this._additionsTail._nextAdded = null;
return this.isDirty;
}
/**
* Inserts a record before `before` or append at the end of the list when `before` is null.
*
* Notes:
* - This method appends at `this._appendAfter`,
* - This method updates `this._appendAfter`,
* - The return value is the new value for the insertion pointer.
* @private
* @param {?} before
* @param {?} record
* @return {?}
*/
_insertBeforeOrAppend(before, record) {
if (before) {
/** @type {?} */
const prev = before._prev;
record._next = before;
record._prev = prev;
before._prev = record;
if (prev) {
prev._next = record;
}
if (before === this._mapHead) {
this._mapHead = record;
}
this._appendAfter = before;
return before;
}
if (this._appendAfter) {
this._appendAfter._next = record;
record._prev = this._appendAfter;
}
else {
this._mapHead = record;
}
this._appendAfter = record;
return null;
}
/**
* @private
* @param {?} key
* @param {?} value
* @return {?}
*/
_getOrCreateRecordForKey(key, value) {
if (this._records.has(key)) {
/** @type {?} */
const record = (/** @type {?} */ (this._records.get(key)));
this._maybeAddToChanges(record, value);
/** @type {?} */
const prev = record._prev;
/** @type {?} */
const next = record._next;
if (prev) {
prev._next = next;
}
if (next) {
next._prev = prev;
}
record._next = null;
record._prev = null;
return record;
}
/** @type {?} */
const record = new KeyValueChangeRecord_(key);
this._records.set(key, record);
record.currentValue = value;
this._addToAdditions(record);
return record;
}
/**
* \@internal
* @return {?}
*/
_reset() {
if (this.isDirty) {
/** @type {?} */
let record;
// let `_previousMapHead` contain the state of the map before the changes
this._previousMapHead = this._mapHead;
for (record = this._previousMapHead; record !== null; record = record._next) {
record._nextPrevious = record._next;
}
// Update `record.previousValue` with the value of the item before the changes
// We need to update all changed items (that's those which have been added and changed)
for (record = this._changesHead; record !== null; record = record._nextChanged) {
record.previousValue = record.currentValue;
}
for (record = this._additionsHead; record != null; record = record._nextAdded) {
record.previousValue = record.currentValue;
}
this._changesHead = this._changesTail = null;
this._additionsHead = this._additionsTail = null;
this._removalsHead = null;
}
}
// Add the record or a given key to the list of changes only when the value has actually changed
/**
* @private
* @param {?} record
* @param {?} newValue
* @return {?}
*/
_maybeAddToChanges(record, newValue) {
if (!looseIdentical(newValue, record.currentValue)) {
record.previousValue = record.currentValue;
record.currentValue = newValue;
this._addToChanges(record);
}
}
/**
* @private
* @param {?} record
* @return {?}
*/
_addToAdditions(record) {
if (this._additionsHead === null) {
this._additionsHead = this._additionsTail = record;
}
else {
(/** @type {?} */ (this._additionsTail))._nextAdded = record;
this._additionsTail = record;
}
}
/**
* @private
* @param {?} record
* @return {?}
*/
_addToChanges(record) {
if (this._changesHead === null) {
this._changesHead = this._changesTail = record;
}
else {
(/** @type {?} */ (this._changesTail))._nextChanged = record;
this._changesTail = record;
}
}
/**
* \@internal
* @private
* @template K, V
* @param {?} obj
* @param {?} fn
* @return {?}
*/
_forEach(obj, fn) {
if (obj instanceof Map) {
obj.forEach(fn);
}
else {
Object.keys(obj).forEach((/**
* @param {?} k
* @return {?}
*/
k => fn(obj[k], k)));
}
}
}
if (false) {}
/**
* @template K, V
*/
class KeyValueChangeRecord_ {
/**
* @param {?} key
*/
constructor(key) {
this.key = key;
this.previousValue = null;
this.currentValue = null;
/**
* \@internal
*/
this._nextPrevious = null;
/**
* \@internal
*/
this._next = null;
/**
* \@internal
*/
this._prev = null;
/**
* \@internal
*/
this._nextAdded = null;
/**
* \@internal
*/
this._nextRemoved = null;
/**
* \@internal
*/
this._nextChanged = null;
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/change_detection/differs/iterable_differs.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A strategy for tracking changes over time to an iterable. Used by {\@link NgForOf} to
* respond to changes in an iterable by effecting equivalent changes in the DOM.
*
* \@publicApi
* @record
* @template V
*/
function IterableDiffer() { }
if (false) {}
/**
* An object describing the changes in the `Iterable` collection since last time
* `IterableDiffer#diff()` was invoked.
*
* \@publicApi
* @record
* @template V
*/
function IterableChanges() { }
if (false) {}
/**
* Record representing the item change information.
*
* \@publicApi
* @record
* @template V
*/
function IterableChangeRecord() { }
if (false) {}
/**
* @deprecated v4.0.0 - Use IterableChangeRecord instead.
* \@publicApi
* @record
* @template V
*/
function CollectionChangeRecord() { }
/**
* An optional function passed into the `NgForOf` directive that defines how to track
* changes for items in an iterable.
* The function takes the iteration index and item ID.
* When supplied, Angular tracks changes by the return value of the function.
*
* \@publicApi
* @record
* @template T
*/
function TrackByFunction() { }
/**
* Provides a factory for {\@link IterableDiffer}.
*
* \@publicApi
* @record
*/
function IterableDifferFactory() { }
if (false) {}
/**
* A repository of different iterable diffing strategies used by NgFor, NgClass, and others.
*
* \@publicApi
*/
class IterableDiffers {
/**
* @param {?} factories
*/
constructor(factories) {
this.factories = factories;
}
/**
* @param {?} factories
* @param {?=} parent
* @return {?}
*/
static create(factories, parent) {
if (parent != null) {
/** @type {?} */
const copied = parent.factories.slice();
factories = factories.concat(copied);
}
return new IterableDiffers(factories);
}
/**
* Takes an array of {\@link IterableDifferFactory} and returns a provider used to extend the
* inherited {\@link IterableDiffers} instance with the provided factories and return a new
* {\@link IterableDiffers} instance.
*
* \@usageNotes
* ### Example
*
* The following example shows how to extend an existing list of factories,
* which will only be applied to the injector for this component and its children.
* This step is all that's required to make a new {\@link IterableDiffer} available.
*
* ```
* \@Component({
* viewProviders: [
* IterableDiffers.extend([new ImmutableListDiffer()])
* ]
* })
* ```
* @param {?} factories
* @return {?}
*/
static extend(factories) {
return {
provide: IterableDiffers,
useFactory: (/**
* @param {?} parent
* @return {?}
*/
(parent) => {
if (!parent) {
// Typically would occur when calling IterableDiffers.extend inside of dependencies passed
// to
// bootstrap(), which would override default pipes instead of extending them.
throw new Error('Cannot extend IterableDiffers without a parent injector');
}
return IterableDiffers.create(factories, parent);
}),
// Dependency technically isn't optional, but we can provide a better error message this way.
deps: [[IterableDiffers, new SkipSelf(), new Optional()]]
};
}
/**
* @param {?} iterable
* @return {?}
*/
find(iterable) {
/** @type {?} */
const factory = this.factories.find((/**
* @param {?} f
* @return {?}
*/
f => f.supports(iterable)));
if (factory != null) {
return factory;
}
else {
throw new Error(`Cannot find a differ supporting object '${iterable}' of type '${getTypeNameForDebugging(iterable)}'`);
}
}
}
/** @nocollapse */
IterableDiffers.ɵprov = ɵɵdefineInjectable({
token: IterableDiffers,
providedIn: 'root',
factory: (/**
* @return {?}
*/
() => new IterableDiffers([new DefaultIterableDifferFactory()]))
});
if (false) {}
/**
* @param {?} type
* @return {?}
*/
function getTypeNameForDebugging(type) {
return type['name'] || typeof type;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/change_detection/differs/keyvalue_differs.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A differ that tracks changes made to an object over time.
*
* \@publicApi
* @record
* @template K, V
*/
function KeyValueDiffer() { }
if (false) {}
/**
* An object describing the changes in the `Map` or `{[k:string]: string}` since last time
* `KeyValueDiffer#diff()` was invoked.
*
* \@publicApi
* @record
* @template K, V
*/
function KeyValueChanges() { }
if (false) {}
/**
* Record representing the item change information.
*
* \@publicApi
* @record
* @template K, V
*/
function KeyValueChangeRecord() { }
if (false) {}
/**
* Provides a factory for {\@link KeyValueDiffer}.
*
* \@publicApi
* @record
*/
function KeyValueDifferFactory() { }
if (false) {}
/**
* A repository of different Map diffing strategies used by NgClass, NgStyle, and others.
*
* \@publicApi
*/
class KeyValueDiffers {
/**
* @param {?} factories
*/
constructor(factories) {
this.factories = factories;
}
/**
* @template S
* @param {?} factories
* @param {?=} parent
* @return {?}
*/
static create(factories, parent) {
if (parent) {
/** @type {?} */
const copied = parent.factories.slice();
factories = factories.concat(copied);
}
return new KeyValueDiffers(factories);
}
/**
* Takes an array of {\@link KeyValueDifferFactory} and returns a provider used to extend the
* inherited {\@link KeyValueDiffers} instance with the provided factories and return a new
* {\@link KeyValueDiffers} instance.
*
* \@usageNotes
* ### Example
*
* The following example shows how to extend an existing list of factories,
* which will only be applied to the injector for this component and its children.
* This step is all that's required to make a new {\@link KeyValueDiffer} available.
*
* ```
* \@Component({
* viewProviders: [
* KeyValueDiffers.extend([new ImmutableMapDiffer()])
* ]
* })
* ```
* @template S
* @param {?} factories
* @return {?}
*/
static extend(factories) {
return {
provide: KeyValueDiffers,
useFactory: (/**
* @param {?} parent
* @return {?}
*/
(parent) => {
if (!parent) {
// Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed
// to bootstrap(), which would override default pipes instead of extending them.
throw new Error('Cannot extend KeyValueDiffers without a parent injector');
}
return KeyValueDiffers.create(factories, parent);
}),
// Dependency technically isn't optional, but we can provide a better error message this way.
deps: [[KeyValueDiffers, new SkipSelf(), new Optional()]]
};
}
/**
* @param {?} kv
* @return {?}
*/
find(kv) {
/** @type {?} */
const factory = this.factories.find((/**
* @param {?} f
* @return {?}
*/
f => f.supports(kv)));
if (factory) {
return factory;
}
throw new Error(`Cannot find a differ supporting object '${kv}'`);
}
}
/** @nocollapse */
KeyValueDiffers.ɵprov = ɵɵdefineInjectable({
token: KeyValueDiffers,
providedIn: 'root',
factory: (/**
* @return {?}
*/
() => new KeyValueDiffers([new DefaultKeyValueDifferFactory()]))
});
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/change_detection/change_detection.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Structural diffing for `Object`s and `Map`s.
* @type {?}
*/
const keyValDiff = [new DefaultKeyValueDifferFactory()];
/**
* Structural diffing for `Iterable` types such as `Array`s.
* @type {?}
*/
const iterableDiff = [new DefaultIterableDifferFactory()];
/** @type {?} */
const defaultIterableDiffers = new IterableDiffers(iterableDiff);
/** @type {?} */
const defaultKeyValueDiffers = new KeyValueDiffers(keyValDiff);
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/template_ref.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Represents an embedded template that can be used to instantiate embedded views.
* To instantiate embedded views based on a template, use the `ViewContainerRef`
* method `createEmbeddedView()`.
*
* Access a `TemplateRef` instance by placing a directive on an `<ng-template>`
* element (or directive prefixed with `*`). The `TemplateRef` for the embedded view
* is injected into the constructor of the directive,
* using the `TemplateRef` token.
*
* You can also use a `Query` to find a `TemplateRef` associated with
* a component or a directive.
*
* @see `ViewContainerRef`
* @see [Navigate the Component Tree with DI](guide/dependency-injection-navtree)
*
* \@publicApi
* @abstract
* @template C
*/
class TemplateRef {
}
/**
* \@internal
* @nocollapse
*/
TemplateRef.__NG_ELEMENT_ID__ = (/**
* @return {?}
*/
() => SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef));
if (false) {}
/** @type {?} */
const SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ = injectTemplateRef;
/** @type {?} */
const SWITCH_TEMPLATE_REF_FACTORY__PRE_R3__ = noop;
/** @type {?} */
const SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__POST_R3__;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/view_container_ref.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Represents a container where one or more views can be attached to a component.
*
* Can contain *host views* (created by instantiating a
* component with the `createComponent()` method), and *embedded views*
* (created by instantiating a `TemplateRef` with the `createEmbeddedView()` method).
*
* A view container instance can contain other view containers,
* creating a [view hierarchy](guide/glossary#view-tree).
*
* @see `ComponentRef`
* @see `EmbeddedViewRef`
*
* \@publicApi
* @abstract
*/
class ViewContainerRef {
}
/**
* \@internal
* @nocollapse
*/
ViewContainerRef.__NG_ELEMENT_ID__ = (/**
* @return {?}
*/
() => SWITCH_VIEW_CONTAINER_REF_FACTORY(ViewContainerRef, ElementRef));
if (false) {}
/** @type {?} */
const SWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__ = injectViewContainerRef;
/** @type {?} */
const SWITCH_VIEW_CONTAINER_REF_FACTORY__PRE_R3__ = noop;
/** @type {?} */
const SWITCH_VIEW_CONTAINER_REF_FACTORY = SWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/errors.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} context
* @param {?} oldValue
* @param {?} currValue
* @param {?} isFirstCheck
* @return {?}
*/
function expressionChangedAfterItHasBeenCheckedError(context, oldValue, currValue, isFirstCheck) {
/** @type {?} */
let msg = `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '${oldValue}'. Current value: '${currValue}'.`;
if (isFirstCheck) {
msg +=
` It seems like the view has been created after its parent and its children have been dirty checked.` +
` Has it been created in a change detection hook ?`;
}
return viewDebugError(msg, context);
}
/**
* @param {?} err
* @param {?} context
* @return {?}
*/
function viewWrappedDebugError(err, context) {
if (!(err instanceof Error)) {
// errors that are not Error instances don't have a stack,
// so it is ok to wrap them into a new Error object...
err = new Error(err.toString());
}
_addDebugContext(err, context);
return err;
}
/**
* @param {?} msg
* @param {?} context
* @return {?}
*/
function viewDebugError(msg, context) {
/** @type {?} */
const err = new Error(msg);
_addDebugContext(err, context);
return err;
}
/**
* @param {?} err
* @param {?} context
* @return {?}
*/
function _addDebugContext(err, context) {
((/** @type {?} */ (err)))[ERROR_DEBUG_CONTEXT] = context;
((/** @type {?} */ (err)))[ERROR_LOGGER] = context.logError.bind(context);
}
/**
* @param {?} err
* @return {?}
*/
function isViewDebugError(err) {
return !!getDebugContext(err);
}
/**
* @param {?} action
* @return {?}
*/
function viewDestroyedError(action) {
return new Error(`ViewDestroyedError: Attempt to use a destroyed view: ${action}`);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/types.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Factory for ViewDefinitions/NgModuleDefinitions.
* We use a function so we can reexeute it in case an error happens and use the given logger
* function to log the error from the definition of the node, which is shown in all browser
* logs.
* @record
* @template D
*/
function DefinitionFactory() { }
/**
* Function to call console.error at the right source location. This is an indirection
* via another function as browser will log the location that actually called
* `console.error`.
* @record
*/
function NodeLogger() { }
/**
* @record
* @template DF
*/
function Definition() { }
if (false) {}
/**
* @record
*/
function NgModuleDefinition() { }
if (false) {}
/**
* @record
*/
function NgModuleDefinitionFactory() { }
/**
* @record
*/
function ViewDefinition() { }
if (false) {}
/**
* @record
*/
function ViewDefinitionFactory() { }
/**
* @record
*/
function ViewUpdateFn() { }
/**
* @record
*/
function NodeCheckFn() { }
/** @enum {number} */
const ArgumentType = {
Inline: 0,
Dynamic: 1,
};
/**
* @record
*/
function ViewHandleEventFn() { }
/** @enum {number} */
const ViewFlags = {
None: 0,
OnPush: 2,
};
/**
* A node definition in the view.
*
* Note: We use one type for all nodes so that loops that loop over all nodes
* of a ViewDefinition stay monomorphic!
* @record
*/
function NodeDef() { }
if (false) {}
/** @enum {number} */
const NodeFlags = {
None: 0,
TypeElement: 1,
TypeText: 2,
ProjectedTemplate: 4,
CatRenderNode: 3,
TypeNgContent: 8,
TypePipe: 16,
TypePureArray: 32,
TypePureObject: 64,
TypePurePipe: 128,
CatPureExpression: 224,
TypeValueProvider: 256,
TypeClassProvider: 512,
TypeFactoryProvider: 1024,
TypeUseExistingProvider: 2048,
LazyProvider: 4096,
PrivateProvider: 8192,
TypeDirective: 16384,
Component: 32768,
CatProviderNoDirective: 3840,
CatProvider: 20224,
OnInit: 65536,
OnDestroy: 131072,
DoCheck: 262144,
OnChanges: 524288,
AfterContentInit: 1048576,
AfterContentChecked: 2097152,
AfterViewInit: 4194304,
AfterViewChecked: 8388608,
EmbeddedViews: 16777216,
ComponentView: 33554432,
TypeContentQuery: 67108864,
TypeViewQuery: 134217728,
StaticQuery: 268435456,
DynamicQuery: 536870912,
TypeNgModule: 1073741824,
CatQuery: 201326592,
// mutually exclusive values...
Types: 201347067,
};
/**
* @record
*/
function BindingDef() { }
if (false) {}
/** @enum {number} */
const BindingFlags = {
TypeElementAttribute: 1,
TypeElementClass: 2,
TypeElementStyle: 4,
TypeProperty: 8,
SyntheticProperty: 16,
SyntheticHostProperty: 32,
CatSyntheticProperty: 48,
// mutually exclusive values...
Types: 15,
};
/**
* @record
*/
function OutputDef() { }
if (false) {}
/** @enum {number} */
const OutputType = {
ElementOutput: 0,
DirectiveOutput: 1,
};
/** @enum {number} */
const QueryValueType = {
ElementRef: 0,
RenderElement: 1,
TemplateRef: 2,
ViewContainerRef: 3,
Provider: 4,
};
/**
* @record
*/
function ElementDef() { }
if (false) {}
/**
* @record
*/
function ElementHandleEventFn() { }
/**
* @record
*/
function ProviderDef() { }
if (false) {}
/**
* @record
*/
function NgModuleProviderDef() { }
if (false) {}
/**
* @record
*/
function DepDef() { }
if (false) {}
/** @enum {number} */
const DepFlags = {
None: 0,
SkipSelf: 1,
Optional: 2,
Self: 4,
Value: 8,
};
/**
* @record
*/
function TextDef() { }
if (false) {}
/**
* @record
*/
function QueryDef() { }
if (false) {}
/**
* @record
*/
function QueryBindingDef() { }
if (false) {}
/** @enum {number} */
const QueryBindingType = {
First: 0,
All: 1,
};
/**
* @record
*/
function NgContentDef() { }
if (false) {}
/**
* @record
*/
function NgModuleData() { }
if (false) {}
/**
* View instance data.
* Attention: Adding fields to this is performance sensitive!
* @record
*/
function ViewData() { }
if (false) {}
/** @enum {number} */
const ViewState = {
BeforeFirstCheck: 1,
FirstCheck: 2,
Attached: 4,
ChecksEnabled: 8,
IsProjectedView: 16,
CheckProjectedView: 32,
CheckProjectedViews: 64,
Destroyed: 128,
// InitState Uses 3 bits
InitState_Mask: 1792,
InitState_BeforeInit: 0,
InitState_CallingOnInit: 256,
InitState_CallingAfterContentInit: 512,
InitState_CallingAfterViewInit: 768,
InitState_AfterInit: 1024,
CatDetectChanges: 12,
CatInit: 13,
};
// Called before each cycle of a view's check to detect whether this is in the
// initState for which we need to call ngOnInit, ngAfterContentInit or ngAfterViewInit
// lifecycle methods. Returns true if this check cycle should call lifecycle
// methods.
/**
* @param {?} view
* @param {?} priorInitState
* @param {?} newInitState
* @return {?}
*/
function shiftInitState(view, priorInitState, newInitState) {
// Only update the InitState if we are currently in the prior state.
// For example, only move into CallingInit if we are in BeforeInit. Only
// move into CallingContentInit if we are in CallingInit. Normally this will
// always be true because of how checkCycle is called in checkAndUpdateView.
// However, if checkAndUpdateView is called recursively or if an exception is
// thrown while checkAndUpdateView is running, checkAndUpdateView starts over
// from the beginning. This ensures the state is monotonically increasing,
// terminating in the AfterInit state, which ensures the Init methods are called
// at least once and only once.
/** @type {?} */
const state = view.state;
/** @type {?} */
const initState = state & 1792 /* InitState_Mask */;
if (initState === priorInitState) {
view.state = (state & ~1792 /* InitState_Mask */) | newInitState;
view.initIndex = -1;
return true;
}
return initState === newInitState;
}
// Returns true if the lifecycle init method should be called for the node with
// the given init index.
/**
* @param {?} view
* @param {?} initState
* @param {?} index
* @return {?}
*/
function shouldCallLifecycleInitHook(view, initState, index) {
if ((view.state & 1792 /* InitState_Mask */) === initState && view.initIndex <= index) {
view.initIndex = index + 1;
return true;
}
return false;
}
/**
* @record
*/
function DisposableFn() { }
/**
* Node instance data.
*
* We have a separate type per NodeType to save memory
* (TextData | ElementData | ProviderData | PureExpressionData | QueryList<any>)
*
* To keep our code monomorphic,
* we prohibit using `NodeData` directly but enforce the use of accessors (`asElementData`, ...).
* This way, no usage site can get a `NodeData` from view.nodes and then use it for different
* purposes.
*/
class NodeData {
}
if (false) {}
/**
* Data for an instantiated NodeType.Text.
*
* Attention: Adding fields to this is performance sensitive!
* @record
*/
function TextData() { }
if (false) {}
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
* @param {?} view
* @param {?} index
* @return {?}
*/
function asTextData(view, index) {
return (/** @type {?} */ (view.nodes[index]));
}
/**
* Data for an instantiated NodeType.Element.
*
* Attention: Adding fields to this is performance sensitive!
* @record
*/
function ElementData() { }
if (false) {}
/**
* @record
*/
function ViewContainerData() { }
if (false) {}
/**
* @record
*/
function TemplateData() { }
if (false) {}
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
* @param {?} view
* @param {?} index
* @return {?}
*/
function asElementData(view, index) {
return (/** @type {?} */ (view.nodes[index]));
}
/**
* Data for an instantiated NodeType.Provider.
*
* Attention: Adding fields to this is performance sensitive!
* @record
*/
function ProviderData() { }
if (false) {}
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
* @param {?} view
* @param {?} index
* @return {?}
*/
function asProviderData(view, index) {
return (/** @type {?} */ (view.nodes[index]));
}
/**
* Data for an instantiated NodeType.PureExpression.
*
* Attention: Adding fields to this is performance sensitive!
* @record
*/
function PureExpressionData() { }
if (false) {}
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
* @param {?} view
* @param {?} index
* @return {?}
*/
function asPureExpressionData(view, index) {
return (/** @type {?} */ (view.nodes[index]));
}
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
* @param {?} view
* @param {?} index
* @return {?}
*/
function asQueryList(view, index) {
return (/** @type {?} */ (view.nodes[index]));
}
/**
* @record
*/
function RootData() { }
if (false) {}
/**
* @abstract
*/
class DebugContext {
}
if (false) {}
/** @enum {number} */
const CheckType = {
CheckAndUpdate: 0,
CheckNoChanges: 1,
};
/**
* @record
*/
function ProviderOverride() { }
if (false) {}
// WARNING: interface has both a type and a value, skipping emit
/**
* This object is used to prevent cycles in the source files and to have a place where
* debug mode can hook it. It is lazily filled when `isDevMode` is known.
* @type {?}
*/
const Services = {
setCurrentNode: (/** @type {?} */ (undefined)),
createRootView: (/** @type {?} */ (undefined)),
createEmbeddedView: (/** @type {?} */ (undefined)),
createComponentView: (/** @type {?} */ (undefined)),
createNgModuleRef: (/** @type {?} */ (undefined)),
overrideProvider: (/** @type {?} */ (undefined)),
overrideComponentView: (/** @type {?} */ (undefined)),
clearOverrides: (/** @type {?} */ (undefined)),
checkAndUpdateView: (/** @type {?} */ (undefined)),
checkNoChangesView: (/** @type {?} */ (undefined)),
destroyView: (/** @type {?} */ (undefined)),
resolveDep: (/** @type {?} */ (undefined)),
createDebugContext: (/** @type {?} */ (undefined)),
handleEvent: (/** @type {?} */ (undefined)),
updateDirectives: (/** @type {?} */ (undefined)),
updateRenderer: (/** @type {?} */ (undefined)),
dirtyParentQueries: (/** @type {?} */ (undefined)),
};
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/util.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const NOOP = (/**
* @return {?}
*/
() => { });
/** @type {?} */
const _tokenKeyCache = new Map();
/**
* @param {?} token
* @return {?}
*/
function tokenKey(token) {
/** @type {?} */
let key = _tokenKeyCache.get(token);
if (!key) {
key = stringify(token) + '_' + _tokenKeyCache.size;
_tokenKeyCache.set(token, key);
}
return key;
}
/**
* @param {?} view
* @param {?} nodeIdx
* @param {?} bindingIdx
* @param {?} value
* @return {?}
*/
function unwrapValue(view, nodeIdx, bindingIdx, value) {
if (WrappedValue.isWrapped(value)) {
value = WrappedValue.unwrap(value);
/** @type {?} */
const globalBindingIdx = view.def.nodes[nodeIdx].bindingIndex + bindingIdx;
/** @type {?} */
const oldValue = WrappedValue.unwrap(view.oldValues[globalBindingIdx]);
view.oldValues[globalBindingIdx] = new WrappedValue(oldValue);
}
return value;
}
/** @type {?} */
const UNDEFINED_RENDERER_TYPE_ID = '$$undefined';
/** @type {?} */
const EMPTY_RENDERER_TYPE_ID = '$$empty';
// Attention: this function is called as top level function.
// Putting any logic in here will destroy closure tree shaking!
/**
* @param {?} values
* @return {?}
*/
function createRendererType2(values) {
return {
id: UNDEFINED_RENDERER_TYPE_ID,
styles: values.styles,
encapsulation: values.encapsulation,
data: values.data
};
}
/** @type {?} */
let _renderCompCount$1 = 0;
/**
* @param {?=} type
* @return {?}
*/
function resolveRendererType2(type) {
if (type && type.id === UNDEFINED_RENDERER_TYPE_ID) {
// first time we see this RendererType2. Initialize it...
/** @type {?} */
const isFilled = ((type.encapsulation != null && type.encapsulation !== ViewEncapsulation$1.None) ||
type.styles.length || Object.keys(type.data).length);
if (isFilled) {
type.id = `c${_renderCompCount$1++}`;
}
else {
type.id = EMPTY_RENDERER_TYPE_ID;
}
}
if (type && type.id === EMPTY_RENDERER_TYPE_ID) {
type = null;
}
return type || null;
}
/**
* @param {?} view
* @param {?} def
* @param {?} bindingIdx
* @param {?} value
* @return {?}
*/
function checkBinding(view, def, bindingIdx, value) {
/** @type {?} */
const oldValues = view.oldValues;
if ((view.state & 2 /* FirstCheck */) ||
!looseIdentical(oldValues[def.bindingIndex + bindingIdx], value)) {
return true;
}
return false;
}
/**
* @param {?} view
* @param {?} def
* @param {?} bindingIdx
* @param {?} value
* @return {?}
*/
function checkAndUpdateBinding(view, def, bindingIdx, value) {
if (checkBinding(view, def, bindingIdx, value)) {
view.oldValues[def.bindingIndex + bindingIdx] = value;
return true;
}
return false;
}
/**
* @param {?} view
* @param {?} def
* @param {?} bindingIdx
* @param {?} value
* @return {?}
*/
function checkBindingNoChanges(view, def, bindingIdx, value) {
/** @type {?} */
const oldValue = view.oldValues[def.bindingIndex + bindingIdx];
if ((view.state & 1 /* BeforeFirstCheck */) || !devModeEqual$1(oldValue, value)) {
/** @type {?} */
const bindingName = def.bindings[bindingIdx].name;
throw expressionChangedAfterItHasBeenCheckedError(Services.createDebugContext(view, def.nodeIndex), `${bindingName}: ${oldValue}`, `${bindingName}: ${value}`, (view.state & 1 /* BeforeFirstCheck */) !== 0);
}
}
/**
* @param {?} view
* @return {?}
*/
function markParentViewsForCheck(view) {
/** @type {?} */
let currView = view;
while (currView) {
if (currView.def.flags & 2 /* OnPush */) {
currView.state |= 8 /* ChecksEnabled */;
}
currView = currView.viewContainerParent || currView.parent;
}
}
/**
* @param {?} view
* @param {?} endView
* @return {?}
*/
function markParentViewsForCheckProjectedViews(view, endView) {
/** @type {?} */
let currView = view;
while (currView && currView !== endView) {
currView.state |= 64 /* CheckProjectedViews */;
currView = currView.viewContainerParent || currView.parent;
}
}
/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} eventName
* @param {?} event
* @return {?}
*/
function dispatchEvent(view, nodeIndex, eventName, event) {
try {
/** @type {?} */
const nodeDef = view.def.nodes[nodeIndex];
/** @type {?} */
const startView = nodeDef.flags & 33554432 /* ComponentView */ ?
asElementData(view, nodeIndex).componentView :
view;
markParentViewsForCheck(startView);
return Services.handleEvent(view, nodeIndex, eventName, event);
}
catch (e) {
// Attention: Don't rethrow, as it would cancel Observable subscriptions!
view.root.errorHandler.handleError(e);
}
}
/**
* @param {?} view
* @return {?}
*/
function declaredViewContainer(view) {
if (view.parent) {
/** @type {?} */
const parentView = view.parent;
return asElementData(parentView, (/** @type {?} */ (view.parentNodeDef)).nodeIndex);
}
return null;
}
/**
* for component views, this is the host element.
* for embedded views, this is the index of the parent node
* that contains the view container.
* @param {?} view
* @return {?}
*/
function viewParentEl(view) {
/** @type {?} */
const parentView = view.parent;
if (parentView) {
return (/** @type {?} */ (view.parentNodeDef)).parent;
}
else {
return null;
}
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function renderNode(view, def) {
switch (def.flags & 201347067 /* Types */) {
case 1 /* TypeElement */:
return asElementData(view, def.nodeIndex).renderElement;
case 2 /* TypeText */:
return asTextData(view, def.nodeIndex).renderText;
}
}
/**
* @param {?} target
* @param {?} name
* @return {?}
*/
function elementEventFullName(target, name) {
return target ? `${target}:${name}` : name;
}
/**
* @param {?} view
* @return {?}
*/
function isComponentView(view) {
return !!view.parent && !!((/** @type {?} */ (view.parentNodeDef)).flags & 32768 /* Component */);
}
/**
* @param {?} view
* @return {?}
*/
function isEmbeddedView(view) {
return !!view.parent && !((/** @type {?} */ (view.parentNodeDef)).flags & 32768 /* Component */);
}
/**
* @param {?} queryId
* @return {?}
*/
function filterQueryId(queryId) {
return 1 << (queryId % 32);
}
/**
* @param {?} matchedQueriesDsl
* @return {?}
*/
function splitMatchedQueriesDsl(matchedQueriesDsl) {
/** @type {?} */
const matchedQueries = {};
/** @type {?} */
let matchedQueryIds = 0;
/** @type {?} */
const references = {};
if (matchedQueriesDsl) {
matchedQueriesDsl.forEach((/**
* @param {?} __0
* @return {?}
*/
([queryId, valueType]) => {
if (typeof queryId === 'number') {
matchedQueries[queryId] = valueType;
matchedQueryIds |= filterQueryId(queryId);
}
else {
references[queryId] = valueType;
}
}));
}
return { matchedQueries, references, matchedQueryIds };
}
/**
* @param {?} deps
* @param {?=} sourceName
* @return {?}
*/
function splitDepsDsl(deps, sourceName) {
return deps.map((/**
* @param {?} value
* @return {?}
*/
value => {
/** @type {?} */
let token;
/** @type {?} */
let flags;
if (Array.isArray(value)) {
[flags, token] = value;
}
else {
flags = 0 /* None */;
token = value;
}
if (token && (typeof token === 'function' || typeof token === 'object') && sourceName) {
Object.defineProperty(token, SOURCE, { value: sourceName, configurable: true });
}
return { flags, token, tokenKey: tokenKey(token) };
}));
}
/**
* @param {?} view
* @param {?} renderHost
* @param {?} def
* @return {?}
*/
function getParentRenderElement(view, renderHost, def) {
/** @type {?} */
let renderParent = def.renderParent;
if (renderParent) {
if ((renderParent.flags & 1 /* TypeElement */) === 0 ||
(renderParent.flags & 33554432 /* ComponentView */) === 0 ||
((/** @type {?} */ (renderParent.element)).componentRendererType &&
(/** @type {?} */ ((/** @type {?} */ (renderParent.element)).componentRendererType)).encapsulation === ViewEncapsulation$1.Native)) {
// only children of non components, or children of components with native encapsulation should
// be attached.
return asElementData(view, (/** @type {?} */ (def.renderParent)).nodeIndex).renderElement;
}
}
else {
return renderHost;
}
}
/** @type {?} */
const DEFINITION_CACHE = new WeakMap();
/**
* @template D
* @param {?} factory
* @return {?}
*/
function resolveDefinition(factory) {
/** @type {?} */
let value = (/** @type {?} */ ((/** @type {?} */ (DEFINITION_CACHE.get(factory)))));
if (!value) {
value = factory((/**
* @return {?}
*/
() => NOOP));
value.factory = factory;
DEFINITION_CACHE.set(factory, value);
}
return value;
}
/**
* @param {?} view
* @return {?}
*/
function rootRenderNodes(view) {
/** @type {?} */
const renderNodes = [];
visitRootRenderNodes(view, 0 /* Collect */, undefined, undefined, renderNodes);
return renderNodes;
}
/** @enum {number} */
const RenderNodeAction = {
Collect: 0,
AppendChild: 1,
InsertBefore: 2,
RemoveChild: 3,
};
/**
* @param {?} view
* @param {?} action
* @param {?} parentNode
* @param {?} nextSibling
* @param {?=} target
* @return {?}
*/
function visitRootRenderNodes(view, action, parentNode, nextSibling, target) {
// We need to re-compute the parent node in case the nodes have been moved around manually
if (action === 3 /* RemoveChild */) {
parentNode = view.renderer.parentNode(renderNode(view, (/** @type {?} */ (view.def.lastRenderRootNode))));
}
visitSiblingRenderNodes(view, action, 0, view.def.nodes.length - 1, parentNode, nextSibling, target);
}
/**
* @param {?} view
* @param {?} action
* @param {?} startIndex
* @param {?} endIndex
* @param {?} parentNode
* @param {?} nextSibling
* @param {?=} target
* @return {?}
*/
function visitSiblingRenderNodes(view, action, startIndex, endIndex, parentNode, nextSibling, target) {
for (let i = startIndex; i <= endIndex; i++) {
/** @type {?} */
const nodeDef = view.def.nodes[i];
if (nodeDef.flags & (1 /* TypeElement */ | 2 /* TypeText */ | 8 /* TypeNgContent */)) {
visitRenderNode(view, nodeDef, action, parentNode, nextSibling, target);
}
// jump to next sibling
i += nodeDef.childCount;
}
}
/**
* @param {?} view
* @param {?} ngContentIndex
* @param {?} action
* @param {?} parentNode
* @param {?} nextSibling
* @param {?=} target
* @return {?}
*/
function visitProjectedRenderNodes(view, ngContentIndex, action, parentNode, nextSibling, target) {
/** @type {?} */
let compView = view;
while (compView && !isComponentView(compView)) {
compView = compView.parent;
}
/** @type {?} */
const hostView = (/** @type {?} */ (compView)).parent;
/** @type {?} */
const hostElDef = viewParentEl((/** @type {?} */ (compView)));
/** @type {?} */
const startIndex = (/** @type {?} */ (hostElDef)).nodeIndex + 1;
/** @type {?} */
const endIndex = (/** @type {?} */ (hostElDef)).nodeIndex + (/** @type {?} */ (hostElDef)).childCount;
for (let i = startIndex; i <= endIndex; i++) {
/** @type {?} */
const nodeDef = (/** @type {?} */ (hostView)).def.nodes[i];
if (nodeDef.ngContentIndex === ngContentIndex) {
visitRenderNode((/** @type {?} */ (hostView)), nodeDef, action, parentNode, nextSibling, target);
}
// jump to next sibling
i += nodeDef.childCount;
}
if (!(/** @type {?} */ (hostView)).parent) {
// a root view
/** @type {?} */
const projectedNodes = view.root.projectableNodes[ngContentIndex];
if (projectedNodes) {
for (let i = 0; i < projectedNodes.length; i++) {
execRenderNodeAction(view, projectedNodes[i], action, parentNode, nextSibling, target);
}
}
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} action
* @param {?} parentNode
* @param {?} nextSibling
* @param {?=} target
* @return {?}
*/
function visitRenderNode(view, nodeDef, action, parentNode, nextSibling, target) {
if (nodeDef.flags & 8 /* TypeNgContent */) {
visitProjectedRenderNodes(view, (/** @type {?} */ (nodeDef.ngContent)).index, action, parentNode, nextSibling, target);
}
else {
/** @type {?} */
const rn = renderNode(view, nodeDef);
if (action === 3 /* RemoveChild */ && (nodeDef.flags & 33554432 /* ComponentView */) &&
(nodeDef.bindingFlags & 48 /* CatSyntheticProperty */)) {
// Note: we might need to do both actions.
if (nodeDef.bindingFlags & (16 /* SyntheticProperty */)) {
execRenderNodeAction(view, rn, action, parentNode, nextSibling, target);
}
if (nodeDef.bindingFlags & (32 /* SyntheticHostProperty */)) {
/** @type {?} */
const compView = asElementData(view, nodeDef.nodeIndex).componentView;
execRenderNodeAction(compView, rn, action, parentNode, nextSibling, target);
}
}
else {
execRenderNodeAction(view, rn, action, parentNode, nextSibling, target);
}
if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
/** @type {?} */
const embeddedViews = (/** @type {?} */ (asElementData(view, nodeDef.nodeIndex).viewContainer))._embeddedViews;
for (let k = 0; k < embeddedViews.length; k++) {
visitRootRenderNodes(embeddedViews[k], action, parentNode, nextSibling, target);
}
}
if (nodeDef.flags & 1 /* TypeElement */ && !(/** @type {?} */ (nodeDef.element)).name) {
visitSiblingRenderNodes(view, action, nodeDef.nodeIndex + 1, nodeDef.nodeIndex + nodeDef.childCount, parentNode, nextSibling, target);
}
}
}
/**
* @param {?} view
* @param {?} renderNode
* @param {?} action
* @param {?} parentNode
* @param {?} nextSibling
* @param {?=} target
* @return {?}
*/
function execRenderNodeAction(view, renderNode, action, parentNode, nextSibling, target) {
/** @type {?} */
const renderer = view.renderer;
switch (action) {
case 1 /* AppendChild */:
renderer.appendChild(parentNode, renderNode);
break;
case 2 /* InsertBefore */:
renderer.insertBefore(parentNode, renderNode, nextSibling);
break;
case 3 /* RemoveChild */:
renderer.removeChild(parentNode, renderNode);
break;
case 0 /* Collect */:
(/** @type {?} */ (target)).push(renderNode);
break;
}
}
/** @type {?} */
const NS_PREFIX_RE = /^:([^:]+):(.+)$/;
/**
* @param {?} name
* @return {?}
*/
function splitNamespace(name) {
if (name[0] === ':') {
/** @type {?} */
const match = (/** @type {?} */ (name.match(NS_PREFIX_RE)));
return [match[1], match[2]];
}
return ['', name];
}
/**
* @param {?} bindings
* @return {?}
*/
function calcBindingFlags(bindings) {
/** @type {?} */
let flags = 0;
for (let i = 0; i < bindings.length; i++) {
flags |= bindings[i].flags;
}
return flags;
}
/**
* @param {?} valueCount
* @param {?} constAndInterp
* @return {?}
*/
function interpolate(valueCount, constAndInterp) {
/** @type {?} */
let result = '';
for (let i = 0; i < valueCount * 2; i = i + 2) {
result = result + constAndInterp[i] + _toStringWithNull(constAndInterp[i + 1]);
}
return result + constAndInterp[valueCount * 2];
}
/**
* @param {?} valueCount
* @param {?} c0
* @param {?} a1
* @param {?} c1
* @param {?=} a2
* @param {?=} c2
* @param {?=} a3
* @param {?=} c3
* @param {?=} a4
* @param {?=} c4
* @param {?=} a5
* @param {?=} c5
* @param {?=} a6
* @param {?=} c6
* @param {?=} a7
* @param {?=} c7
* @param {?=} a8
* @param {?=} c8
* @param {?=} a9
* @param {?=} c9
* @return {?}
*/
function inlineInterpolate(valueCount, c0, a1, c1, a2, c2, a3, c3, a4, c4, a5, c5, a6, c6, a7, c7, a8, c8, a9, c9) {
switch (valueCount) {
case 1:
return c0 + _toStringWithNull(a1) + c1;
case 2:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2;
case 3:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3;
case 4:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4;
case 5:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5;
case 6:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) + c6;
case 7:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) +
c6 + _toStringWithNull(a7) + c7;
case 8:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) +
c6 + _toStringWithNull(a7) + c7 + _toStringWithNull(a8) + c8;
case 9:
return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) +
c6 + _toStringWithNull(a7) + c7 + _toStringWithNull(a8) + c8 + _toStringWithNull(a9) + c9;
default:
throw new Error(`Does not support more than 9 expressions`);
}
}
/**
* @param {?} v
* @return {?}
*/
function _toStringWithNull(v) {
return v != null ? v.toString() : '';
}
/** @type {?} */
const EMPTY_ARRAY$4 = [];
/** @type {?} */
const EMPTY_MAP = {};
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/ng_module.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const UNDEFINED_VALUE = {};
/** @type {?} */
const InjectorRefTokenKey = tokenKey(Injector);
/** @type {?} */
const INJECTORRefTokenKey = tokenKey(INJECTOR);
/** @type {?} */
const NgModuleRefTokenKey = tokenKey(NgModuleRef);
/**
* @param {?} flags
* @param {?} token
* @param {?} value
* @param {?} deps
* @return {?}
*/
function moduleProvideDef(flags, token, value, deps) {
// Need to resolve forwardRefs as e.g. for `useValue` we
// lowered the expression and then stopped evaluating it,
// i.e. also didn't unwrap it.
value = resolveForwardRef(value);
/** @type {?} */
const depDefs = splitDepsDsl(deps, stringify(token));
return {
// will bet set by the module definition
index: -1,
deps: depDefs,
flags,
token,
value
};
}
/**
* @param {?} providers
* @return {?}
*/
function moduleDef(providers) {
/** @type {?} */
const providersByKey = {};
/** @type {?} */
const modules = [];
/** @type {?} */
let scope = null;
for (let i = 0; i < providers.length; i++) {
/** @type {?} */
const provider = providers[i];
if (provider.token === INJECTOR_SCOPE) {
scope = provider.value;
}
if (provider.flags & 1073741824 /* TypeNgModule */) {
modules.push(provider.token);
}
provider.index = i;
providersByKey[tokenKey(provider.token)] = provider;
}
return {
// Will be filled later...
factory: null,
providersByKey,
providers,
modules,
scope: scope,
};
}
/**
* @param {?} data
* @return {?}
*/
function initNgModule(data) {
/** @type {?} */
const def = data._def;
/** @type {?} */
const providers = data._providers = newArray(def.providers.length);
for (let i = 0; i < def.providers.length; i++) {
/** @type {?} */
const provDef = def.providers[i];
if (!(provDef.flags & 4096 /* LazyProvider */)) {
// Make sure the provider has not been already initialized outside this loop.
if (providers[i] === undefined) {
providers[i] = _createProviderInstance(data, provDef);
}
}
}
}
/**
* @param {?} data
* @param {?} depDef
* @param {?=} notFoundValue
* @return {?}
*/
function resolveNgModuleDep(data, depDef, notFoundValue = Injector.THROW_IF_NOT_FOUND) {
/** @type {?} */
const former = setCurrentInjector(data);
try {
if (depDef.flags & 8 /* Value */) {
return depDef.token;
}
if (depDef.flags & 2 /* Optional */) {
notFoundValue = null;
}
if (depDef.flags & 1 /* SkipSelf */) {
return data._parent.get(depDef.token, notFoundValue);
}
/** @type {?} */
const tokenKey = depDef.tokenKey;
switch (tokenKey) {
case InjectorRefTokenKey:
case INJECTORRefTokenKey:
case NgModuleRefTokenKey:
return data;
}
/** @type {?} */
const providerDef = data._def.providersByKey[tokenKey];
/** @type {?} */
let injectableDef;
if (providerDef) {
/** @type {?} */
let providerInstance = data._providers[providerDef.index];
if (providerInstance === undefined) {
providerInstance = data._providers[providerDef.index] =
_createProviderInstance(data, providerDef);
}
return providerInstance === UNDEFINED_VALUE ? undefined : providerInstance;
}
else if ((injectableDef = getInjectableDef(depDef.token)) && targetsModule(data, injectableDef)) {
/** @type {?} */
const index = data._providers.length;
data._def.providers[index] = data._def.providersByKey[depDef.tokenKey] = {
flags: 1024 /* TypeFactoryProvider */ | 4096 /* LazyProvider */,
value: injectableDef.factory,
deps: [],
index,
token: depDef.token,
};
data._providers[index] = UNDEFINED_VALUE;
return (data._providers[index] =
_createProviderInstance(data, data._def.providersByKey[depDef.tokenKey]));
}
else if (depDef.flags & 4 /* Self */) {
return notFoundValue;
}
return data._parent.get(depDef.token, notFoundValue);
}
finally {
setCurrentInjector(former);
}
}
/**
* @param {?} ngModule
* @param {?} scope
* @return {?}
*/
function moduleTransitivelyPresent(ngModule, scope) {
return ngModule._def.modules.indexOf(scope) > -1;
}
/**
* @param {?} ngModule
* @param {?} def
* @return {?}
*/
function targetsModule(ngModule, def) {
/** @type {?} */
const providedIn = def.providedIn;
return providedIn != null &&
(providedIn === 'any' || providedIn === ngModule._def.scope ||
moduleTransitivelyPresent(ngModule, providedIn));
}
/**
* @param {?} ngModule
* @param {?} providerDef
* @return {?}
*/
function _createProviderInstance(ngModule, providerDef) {
/** @type {?} */
let injectable;
switch (providerDef.flags & 201347067 /* Types */) {
case 512 /* TypeClassProvider */:
injectable = _createClass(ngModule, providerDef.value, providerDef.deps);
break;
case 1024 /* TypeFactoryProvider */:
injectable = _callFactory(ngModule, providerDef.value, providerDef.deps);
break;
case 2048 /* TypeUseExistingProvider */:
injectable = resolveNgModuleDep(ngModule, providerDef.deps[0]);
break;
case 256 /* TypeValueProvider */:
injectable = providerDef.value;
break;
}
// The read of `ngOnDestroy` here is slightly expensive as it's megamorphic, so it should be
// avoided if possible. The sequence of checks here determines whether ngOnDestroy needs to be
// checked. It might not if the `injectable` isn't an object or if NodeFlags.OnDestroy is already
// set (ngOnDestroy was detected statically).
if (injectable !== UNDEFINED_VALUE && injectable !== null && typeof injectable === 'object' &&
!(providerDef.flags & 131072 /* OnDestroy */) && typeof injectable.ngOnDestroy === 'function') {
providerDef.flags |= 131072 /* OnDestroy */;
}
return injectable === undefined ? UNDEFINED_VALUE : injectable;
}
/**
* @param {?} ngModule
* @param {?} ctor
* @param {?} deps
* @return {?}
*/
function _createClass(ngModule, ctor, deps) {
/** @type {?} */
const len = deps.length;
switch (len) {
case 0:
return new ctor();
case 1:
return new ctor(resolveNgModuleDep(ngModule, deps[0]));
case 2:
return new ctor(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]));
case 3:
return new ctor(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]), resolveNgModuleDep(ngModule, deps[2]));
default:
/** @type {?} */
const depValues = [];
for (let i = 0; i < len; i++) {
depValues[i] = resolveNgModuleDep(ngModule, deps[i]);
}
return new ctor(...depValues);
}
}
/**
* @param {?} ngModule
* @param {?} factory
* @param {?} deps
* @return {?}
*/
function _callFactory(ngModule, factory, deps) {
/** @type {?} */
const len = deps.length;
switch (len) {
case 0:
return factory();
case 1:
return factory(resolveNgModuleDep(ngModule, deps[0]));
case 2:
return factory(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]));
case 3:
return factory(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]), resolveNgModuleDep(ngModule, deps[2]));
default:
/** @type {?} */
const depValues = [];
for (let i = 0; i < len; i++) {
depValues[i] = resolveNgModuleDep(ngModule, deps[i]);
}
return factory(...depValues);
}
}
/**
* @param {?} ngModule
* @param {?} lifecycles
* @return {?}
*/
function callNgModuleLifecycle(ngModule, lifecycles) {
/** @type {?} */
const def = ngModule._def;
/** @type {?} */
const destroyed = new Set();
for (let i = 0; i < def.providers.length; i++) {
/** @type {?} */
const provDef = def.providers[i];
if (provDef.flags & 131072 /* OnDestroy */) {
/** @type {?} */
const instance = ngModule._providers[i];
if (instance && instance !== UNDEFINED_VALUE) {
/** @type {?} */
const onDestroy = instance.ngOnDestroy;
if (typeof onDestroy === 'function' && !destroyed.has(instance)) {
onDestroy.apply(instance);
destroyed.add(instance);
}
}
}
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/view_attach.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} parentView
* @param {?} elementData
* @param {?} viewIndex
* @param {?} view
* @return {?}
*/
function attachEmbeddedView(parentView, elementData, viewIndex, view) {
/** @type {?} */
let embeddedViews = (/** @type {?} */ (elementData.viewContainer))._embeddedViews;
if (viewIndex === null || viewIndex === undefined) {
viewIndex = embeddedViews.length;
}
view.viewContainerParent = parentView;
addToArray(embeddedViews, (/** @type {?} */ (viewIndex)), view);
attachProjectedView(elementData, view);
Services.dirtyParentQueries(view);
/** @type {?} */
const prevView = (/** @type {?} */ (viewIndex)) > 0 ? embeddedViews[(/** @type {?} */ (viewIndex)) - 1] : null;
renderAttachEmbeddedView(elementData, prevView, view);
}
/**
* @param {?} vcElementData
* @param {?} view
* @return {?}
*/
function attachProjectedView(vcElementData, view) {
/** @type {?} */
const dvcElementData = declaredViewContainer(view);
if (!dvcElementData || dvcElementData === vcElementData ||
view.state & 16 /* IsProjectedView */) {
return;
}
// Note: For performance reasons, we
// - add a view to template._projectedViews only 1x throughout its lifetime,
// and remove it not until the view is destroyed.
// (hard, as when a parent view is attached/detached we would need to attach/detach all
// nested projected views as well, even across component boundaries).
// - don't track the insertion order of views in the projected views array
// (hard, as when the views of the same template are inserted different view containers)
view.state |= 16 /* IsProjectedView */;
/** @type {?} */
let projectedViews = dvcElementData.template._projectedViews;
if (!projectedViews) {
projectedViews = dvcElementData.template._projectedViews = [];
}
projectedViews.push(view);
// Note: we are changing the NodeDef here as we cannot calculate
// the fact whether a template is used for projection during compilation.
markNodeAsProjectedTemplate((/** @type {?} */ (view.parent)).def, (/** @type {?} */ (view.parentNodeDef)));
}
/**
* @param {?} viewDef
* @param {?} nodeDef
* @return {?}
*/
function markNodeAsProjectedTemplate(viewDef, nodeDef) {
if (nodeDef.flags & 4 /* ProjectedTemplate */) {
return;
}
viewDef.nodeFlags |= 4 /* ProjectedTemplate */;
nodeDef.flags |= 4 /* ProjectedTemplate */;
/** @type {?} */
let parentNodeDef = nodeDef.parent;
while (parentNodeDef) {
parentNodeDef.childFlags |= 4 /* ProjectedTemplate */;
parentNodeDef = parentNodeDef.parent;
}
}
/**
* @param {?} elementData
* @param {?=} viewIndex
* @return {?}
*/
function detachEmbeddedView(elementData, viewIndex) {
/** @type {?} */
const embeddedViews = (/** @type {?} */ (elementData.viewContainer))._embeddedViews;
if (viewIndex == null || viewIndex >= embeddedViews.length) {
viewIndex = embeddedViews.length - 1;
}
if (viewIndex < 0) {
return null;
}
/** @type {?} */
const view = embeddedViews[viewIndex];
view.viewContainerParent = null;
removeFromArray(embeddedViews, viewIndex);
// See attachProjectedView for why we don't update projectedViews here.
Services.dirtyParentQueries(view);
renderDetachView$1(view);
return view;
}
/**
* @param {?} view
* @return {?}
*/
function detachProjectedView(view) {
if (!(view.state & 16 /* IsProjectedView */)) {
return;
}
/** @type {?} */
const dvcElementData = declaredViewContainer(view);
if (dvcElementData) {
/** @type {?} */
const projectedViews = dvcElementData.template._projectedViews;
if (projectedViews) {
removeFromArray(projectedViews, projectedViews.indexOf(view));
Services.dirtyParentQueries(view);
}
}
}
/**
* @param {?} elementData
* @param {?} oldViewIndex
* @param {?} newViewIndex
* @return {?}
*/
function moveEmbeddedView(elementData, oldViewIndex, newViewIndex) {
/** @type {?} */
const embeddedViews = (/** @type {?} */ (elementData.viewContainer))._embeddedViews;
/** @type {?} */
const view = embeddedViews[oldViewIndex];
removeFromArray(embeddedViews, oldViewIndex);
if (newViewIndex == null) {
newViewIndex = embeddedViews.length;
}
addToArray(embeddedViews, newViewIndex, view);
// Note: Don't need to change projectedViews as the order in there
// as always invalid...
Services.dirtyParentQueries(view);
renderDetachView$1(view);
/** @type {?} */
const prevView = newViewIndex > 0 ? embeddedViews[newViewIndex - 1] : null;
renderAttachEmbeddedView(elementData, prevView, view);
return view;
}
/**
* @param {?} elementData
* @param {?} prevView
* @param {?} view
* @return {?}
*/
function renderAttachEmbeddedView(elementData, prevView, view) {
/** @type {?} */
const prevRenderNode = prevView ? renderNode(prevView, (/** @type {?} */ (prevView.def.lastRenderRootNode))) : elementData.renderElement;
/** @type {?} */
const parentNode = view.renderer.parentNode(prevRenderNode);
/** @type {?} */
const nextSibling = view.renderer.nextSibling(prevRenderNode);
// Note: We can't check if `nextSibling` is present, as on WebWorkers it will always be!
// However, browsers automatically do `appendChild` when there is no `nextSibling`.
visitRootRenderNodes(view, 2 /* InsertBefore */, parentNode, nextSibling, undefined);
}
/**
* @param {?} view
* @return {?}
*/
function renderDetachView$1(view) {
visitRootRenderNodes(view, 3 /* RemoveChild */, null, null, undefined);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/refs.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const EMPTY_CONTEXT = {};
// Attention: this function is called as top level function.
// Putting any logic in here will destroy closure tree shaking!
/**
* @param {?} selector
* @param {?} componentType
* @param {?} viewDefFactory
* @param {?} inputs
* @param {?} outputs
* @param {?} ngContentSelectors
* @return {?}
*/
function createComponentFactory(selector, componentType, viewDefFactory, inputs, outputs, ngContentSelectors) {
return new ComponentFactory_(selector, componentType, viewDefFactory, inputs, outputs, ngContentSelectors);
}
/**
* @param {?} componentFactory
* @return {?}
*/
function getComponentViewDefinitionFactory(componentFactory) {
return ((/** @type {?} */ (componentFactory))).viewDefFactory;
}
class ComponentFactory_ extends ComponentFactory {
/**
* @param {?} selector
* @param {?} componentType
* @param {?} viewDefFactory
* @param {?} _inputs
* @param {?} _outputs
* @param {?} ngContentSelectors
*/
constructor(selector, componentType, viewDefFactory, _inputs, _outputs, ngContentSelectors) {
// Attention: this ctor is called as top level function.
// Putting any logic in here will destroy closure tree shaking!
super();
this.selector = selector;
this.componentType = componentType;
this._inputs = _inputs;
this._outputs = _outputs;
this.ngContentSelectors = ngContentSelectors;
this.viewDefFactory = viewDefFactory;
}
/**
* @return {?}
*/
get inputs() {
/** @type {?} */
const inputsArr = [];
/** @type {?} */
const inputs = (/** @type {?} */ (this._inputs));
for (let propName in inputs) {
/** @type {?} */
const templateName = inputs[propName];
inputsArr.push({ propName, templateName });
}
return inputsArr;
}
/**
* @return {?}
*/
get outputs() {
/** @type {?} */
const outputsArr = [];
for (let propName in this._outputs) {
/** @type {?} */
const templateName = this._outputs[propName];
outputsArr.push({ propName, templateName });
}
return outputsArr;
}
/**
* Creates a new component.
* @param {?} injector
* @param {?=} projectableNodes
* @param {?=} rootSelectorOrNode
* @param {?=} ngModule
* @return {?}
*/
create(injector, projectableNodes, rootSelectorOrNode, ngModule) {
if (!ngModule) {
throw new Error('ngModule should be provided');
}
/** @type {?} */
const viewDef = resolveDefinition(this.viewDefFactory);
/** @type {?} */
const componentNodeIndex = (/** @type {?} */ ((/** @type {?} */ (viewDef.nodes[0].element)).componentProvider)).nodeIndex;
/** @type {?} */
const view = Services.createRootView(injector, projectableNodes || [], rootSelectorOrNode, viewDef, ngModule, EMPTY_CONTEXT);
/** @type {?} */
const component = asProviderData(view, componentNodeIndex).instance;
if (rootSelectorOrNode) {
view.renderer.setAttribute(asElementData(view, 0).renderElement, 'ng-version', VERSION.full);
}
return new ComponentRef_(view, new ViewRef_(view), component);
}
}
if (false) {}
class ComponentRef_ extends ComponentRef {
/**
* @param {?} _view
* @param {?} _viewRef
* @param {?} _component
*/
constructor(_view, _viewRef, _component) {
super();
this._view = _view;
this._viewRef = _viewRef;
this._component = _component;
this._elDef = this._view.def.nodes[0];
this.hostView = _viewRef;
this.changeDetectorRef = _viewRef;
this.instance = _component;
}
/**
* @return {?}
*/
get location() {
return new ElementRef(asElementData(this._view, this._elDef.nodeIndex).renderElement);
}
/**
* @return {?}
*/
get injector() {
return new Injector_(this._view, this._elDef);
}
/**
* @return {?}
*/
get componentType() {
return (/** @type {?} */ (this._component.constructor));
}
/**
* @return {?}
*/
destroy() {
this._viewRef.destroy();
}
/**
* @param {?} callback
* @return {?}
*/
onDestroy(callback) {
this._viewRef.onDestroy(callback);
}
}
if (false) {}
/**
* @param {?} view
* @param {?} elDef
* @param {?} elData
* @return {?}
*/
function createViewContainerData(view, elDef, elData) {
return new ViewContainerRef_(view, elDef, elData);
}
class ViewContainerRef_ {
/**
* @param {?} _view
* @param {?} _elDef
* @param {?} _data
*/
constructor(_view, _elDef, _data) {
this._view = _view;
this._elDef = _elDef;
this._data = _data;
/**
* \@internal
*/
this._embeddedViews = [];
}
/**
* @return {?}
*/
get element() {
return new ElementRef(this._data.renderElement);
}
/**
* @return {?}
*/
get injector() {
return new Injector_(this._view, this._elDef);
}
/**
* @deprecated No replacement
* @return {?}
*/
get parentInjector() {
/** @type {?} */
let view = this._view;
/** @type {?} */
let elDef = this._elDef.parent;
while (!elDef && view) {
elDef = viewParentEl(view);
view = (/** @type {?} */ (view.parent));
}
return view ? new Injector_(view, elDef) : new Injector_(this._view, null);
}
/**
* @return {?}
*/
clear() {
/** @type {?} */
const len = this._embeddedViews.length;
for (let i = len - 1; i >= 0; i--) {
/** @type {?} */
const view = (/** @type {?} */ (detachEmbeddedView(this._data, i)));
Services.destroyView(view);
}
}
/**
* @param {?} index
* @return {?}
*/
get(index) {
/** @type {?} */
const view = this._embeddedViews[index];
if (view) {
/** @type {?} */
const ref = new ViewRef_(view);
ref.attachToViewContainerRef(this);
return ref;
}
return null;
}
/**
* @return {?}
*/
get length() {
return this._embeddedViews.length;
}
/**
* @template C
* @param {?} templateRef
* @param {?=} context
* @param {?=} index
* @return {?}
*/
createEmbeddedView(templateRef, context, index) {
/** @type {?} */
const viewRef = templateRef.createEmbeddedView(context || (/** @type {?} */ ({})));
this.insert(viewRef, index);
return viewRef;
}
/**
* @template C
* @param {?} componentFactory
* @param {?=} index
* @param {?=} injector
* @param {?=} projectableNodes
* @param {?=} ngModuleRef
* @return {?}
*/
createComponent(componentFactory, index, injector, projectableNodes, ngModuleRef) {
/** @type {?} */
const contextInjector = injector || this.parentInjector;
if (!ngModuleRef && !(componentFactory instanceof ComponentFactoryBoundToModule)) {
ngModuleRef = contextInjector.get(NgModuleRef);
}
/** @type {?} */
const componentRef = componentFactory.create(contextInjector, projectableNodes, undefined, ngModuleRef);
this.insert(componentRef.hostView, index);
return componentRef;
}
/**
* @param {?} viewRef
* @param {?=} index
* @return {?}
*/
insert(viewRef, index) {
if (viewRef.destroyed) {
throw new Error('Cannot insert a destroyed View in a ViewContainer!');
}
/** @type {?} */
const viewRef_ = (/** @type {?} */ (viewRef));
/** @type {?} */
const viewData = viewRef_._view;
attachEmbeddedView(this._view, this._data, index, viewData);
viewRef_.attachToViewContainerRef(this);
return viewRef;
}
/**
* @param {?} viewRef
* @param {?} currentIndex
* @return {?}
*/
move(viewRef, currentIndex) {
if (viewRef.destroyed) {
throw new Error('Cannot move a destroyed View in a ViewContainer!');
}
/** @type {?} */
const previousIndex = this._embeddedViews.indexOf(viewRef._view);
moveEmbeddedView(this._data, previousIndex, currentIndex);
return viewRef;
}
/**
* @param {?} viewRef
* @return {?}
*/
indexOf(viewRef) {
return this._embeddedViews.indexOf(((/** @type {?} */ (viewRef)))._view);
}
/**
* @param {?=} index
* @return {?}
*/
remove(index) {
/** @type {?} */
const viewData = detachEmbeddedView(this._data, index);
if (viewData) {
Services.destroyView(viewData);
}
}
/**
* @param {?=} index
* @return {?}
*/
detach(index) {
/** @type {?} */
const view = detachEmbeddedView(this._data, index);
return view ? new ViewRef_(view) : null;
}
}
if (false) {}
/**
* @param {?} view
* @return {?}
*/
function createChangeDetectorRef(view) {
return new ViewRef_(view);
}
class ViewRef_ {
/**
* @param {?} _view
*/
constructor(_view) {
this._view = _view;
this._viewContainerRef = null;
this._appRef = null;
}
/**
* @return {?}
*/
get rootNodes() {
return rootRenderNodes(this._view);
}
/**
* @return {?}
*/
get context() {
return this._view.context;
}
/**
* @return {?}
*/
get destroyed() {
return (this._view.state & 128 /* Destroyed */) !== 0;
}
/**
* @return {?}
*/
markForCheck() {
markParentViewsForCheck(this._view);
}
/**
* @return {?}
*/
detach() {
this._view.state &= ~4 /* Attached */;
}
/**
* @return {?}
*/
detectChanges() {
/** @type {?} */
const fs = this._view.root.rendererFactory;
if (fs.begin) {
fs.begin();
}
try {
Services.checkAndUpdateView(this._view);
}
finally {
if (fs.end) {
fs.end();
}
}
}
/**
* @return {?}
*/
checkNoChanges() {
Services.checkNoChangesView(this._view);
}
/**
* @return {?}
*/
reattach() {
this._view.state |= 4 /* Attached */;
}
/**
* @param {?} callback
* @return {?}
*/
onDestroy(callback) {
if (!this._view.disposables) {
this._view.disposables = [];
}
this._view.disposables.push((/** @type {?} */ (callback)));
}
/**
* @return {?}
*/
destroy() {
if (this._appRef) {
this._appRef.detachView(this);
}
else if (this._viewContainerRef) {
this._viewContainerRef.detach(this._viewContainerRef.indexOf(this));
}
Services.destroyView(this._view);
}
/**
* @return {?}
*/
detachFromAppRef() {
this._appRef = null;
renderDetachView$1(this._view);
Services.dirtyParentQueries(this._view);
}
/**
* @param {?} appRef
* @return {?}
*/
attachToAppRef(appRef) {
if (this._viewContainerRef) {
throw new Error('This view is already attached to a ViewContainer!');
}
this._appRef = appRef;
}
/**
* @param {?} vcRef
* @return {?}
*/
attachToViewContainerRef(vcRef) {
if (this._appRef) {
throw new Error('This view is already attached directly to the ApplicationRef!');
}
this._viewContainerRef = vcRef;
}
}
if (false) {}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function createTemplateData(view, def) {
return new TemplateRef_(view, def);
}
class TemplateRef_ extends TemplateRef {
/**
* @param {?} _parentView
* @param {?} _def
*/
constructor(_parentView, _def) {
super();
this._parentView = _parentView;
this._def = _def;
}
/**
* @param {?} context
* @return {?}
*/
createEmbeddedView(context) {
return new ViewRef_(Services.createEmbeddedView(this._parentView, this._def, (/** @type {?} */ ((/** @type {?} */ (this._def.element)).template)), context));
}
/**
* @return {?}
*/
get elementRef() {
return new ElementRef(asElementData(this._parentView, this._def.nodeIndex).renderElement);
}
}
if (false) {}
/**
* @param {?} view
* @param {?} elDef
* @return {?}
*/
function createInjector$1(view, elDef) {
return new Injector_(view, elDef);
}
class Injector_ {
/**
* @param {?} view
* @param {?} elDef
*/
constructor(view, elDef) {
this.view = view;
this.elDef = elDef;
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND) {
/** @type {?} */
const allowPrivateServices = this.elDef ? (this.elDef.flags & 33554432 /* ComponentView */) !== 0 : false;
return Services.resolveDep(this.view, this.elDef, allowPrivateServices, { flags: 0 /* None */, token, tokenKey: tokenKey(token) }, notFoundValue);
}
}
if (false) {}
/**
* @param {?} view
* @param {?} index
* @return {?}
*/
function nodeValue(view, index) {
/** @type {?} */
const def = view.def.nodes[index];
if (def.flags & 1 /* TypeElement */) {
/** @type {?} */
const elData = asElementData(view, def.nodeIndex);
return (/** @type {?} */ (def.element)).template ? elData.template : elData.renderElement;
}
else if (def.flags & 2 /* TypeText */) {
return asTextData(view, def.nodeIndex).renderText;
}
else if (def.flags & (20224 /* CatProvider */ | 16 /* TypePipe */)) {
return asProviderData(view, def.nodeIndex).instance;
}
throw new Error(`Illegal state: read nodeValue for node index ${index}`);
}
/**
* @param {?} moduleType
* @param {?} parent
* @param {?} bootstrapComponents
* @param {?} def
* @return {?}
*/
function createNgModuleRef(moduleType, parent, bootstrapComponents, def) {
return new NgModuleRef_(moduleType, parent, bootstrapComponents, def);
}
class NgModuleRef_ {
/**
* @param {?} _moduleType
* @param {?} _parent
* @param {?} _bootstrapComponents
* @param {?} _def
*/
constructor(_moduleType, _parent, _bootstrapComponents, _def) {
this._moduleType = _moduleType;
this._parent = _parent;
this._bootstrapComponents = _bootstrapComponents;
this._def = _def;
this._destroyListeners = [];
this._destroyed = false;
this.injector = this;
initNgModule(this);
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @param {?=} injectFlags
* @return {?}
*/
get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND, injectFlags = InjectFlags.Default) {
/** @type {?} */
let flags = 0 /* None */;
if (injectFlags & InjectFlags.SkipSelf) {
flags |= 1 /* SkipSelf */;
}
else if (injectFlags & InjectFlags.Self) {
flags |= 4 /* Self */;
}
return resolveNgModuleDep(this, { token: token, tokenKey: tokenKey(token), flags: flags }, notFoundValue);
}
/**
* @return {?}
*/
get instance() {
return this.get(this._moduleType);
}
/**
* @return {?}
*/
get componentFactoryResolver() {
return this.get(ComponentFactoryResolver);
}
/**
* @return {?}
*/
destroy() {
if (this._destroyed) {
throw new Error(`The ng module ${stringify(this.instance.constructor)} has already been destroyed.`);
}
this._destroyed = true;
callNgModuleLifecycle(this, 131072 /* OnDestroy */);
this._destroyListeners.forEach((/**
* @param {?} listener
* @return {?}
*/
(listener) => listener()));
}
/**
* @param {?} callback
* @return {?}
*/
onDestroy(callback) {
this._destroyListeners.push(callback);
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/provider.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const Renderer2TokenKey = tokenKey(Renderer2);
/** @type {?} */
const ElementRefTokenKey = tokenKey(ElementRef);
/** @type {?} */
const ViewContainerRefTokenKey = tokenKey(ViewContainerRef);
/** @type {?} */
const TemplateRefTokenKey = tokenKey(TemplateRef);
/** @type {?} */
const ChangeDetectorRefTokenKey = tokenKey(ChangeDetectorRef);
/** @type {?} */
const InjectorRefTokenKey$1 = tokenKey(Injector);
/** @type {?} */
const INJECTORRefTokenKey$1 = tokenKey(INJECTOR);
/**
* @param {?} checkIndex
* @param {?} flags
* @param {?} matchedQueries
* @param {?} childCount
* @param {?} ctor
* @param {?} deps
* @param {?=} props
* @param {?=} outputs
* @return {?}
*/
function directiveDef(checkIndex, flags, matchedQueries, childCount, ctor, deps, props, outputs) {
/** @type {?} */
const bindings = [];
if (props) {
for (let prop in props) {
const [bindingIndex, nonMinifiedName] = props[prop];
bindings[bindingIndex] = {
flags: 8 /* TypeProperty */,
name: prop,
nonMinifiedName,
ns: null,
securityContext: null,
suffix: null
};
}
}
/** @type {?} */
const outputDefs = [];
if (outputs) {
for (let propName in outputs) {
outputDefs.push({ type: 1 /* DirectiveOutput */, propName, target: null, eventName: outputs[propName] });
}
}
flags |= 16384 /* TypeDirective */;
return _def(checkIndex, flags, matchedQueries, childCount, ctor, ctor, deps, bindings, outputDefs);
}
/**
* @param {?} flags
* @param {?} ctor
* @param {?} deps
* @return {?}
*/
function pipeDef(flags, ctor, deps) {
flags |= 16 /* TypePipe */;
return _def(-1, flags, null, 0, ctor, ctor, deps);
}
/**
* @param {?} flags
* @param {?} matchedQueries
* @param {?} token
* @param {?} value
* @param {?} deps
* @return {?}
*/
function providerDef(flags, matchedQueries, token, value, deps) {
return _def(-1, flags, matchedQueries, 0, token, value, deps);
}
/**
* @param {?} checkIndex
* @param {?} flags
* @param {?} matchedQueriesDsl
* @param {?} childCount
* @param {?} token
* @param {?} value
* @param {?} deps
* @param {?=} bindings
* @param {?=} outputs
* @return {?}
*/
function _def(checkIndex, flags, matchedQueriesDsl, childCount, token, value, deps, bindings, outputs) {
const { matchedQueries, references, matchedQueryIds } = splitMatchedQueriesDsl(matchedQueriesDsl);
if (!outputs) {
outputs = [];
}
if (!bindings) {
bindings = [];
}
// Need to resolve forwardRefs as e.g. for `useValue` we
// lowered the expression and then stopped evaluating it,
// i.e. also didn't unwrap it.
value = resolveForwardRef(value);
/** @type {?} */
const depDefs = splitDepsDsl(deps, stringify(token));
return {
// will bet set by the view definition
nodeIndex: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
checkIndex,
flags,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
matchedQueries,
matchedQueryIds,
references,
ngContentIndex: -1,
childCount,
bindings,
bindingFlags: calcBindingFlags(bindings),
outputs,
element: null,
provider: { token, value, deps: depDefs },
text: null,
query: null,
ngContent: null
};
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function createProviderInstance(view, def) {
return _createProviderInstance$1(view, def);
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function createPipeInstance(view, def) {
// deps are looked up from component.
/** @type {?} */
let compView = view;
while (compView.parent && !isComponentView(compView)) {
compView = compView.parent;
}
// pipes can see the private services of the component
/** @type {?} */
const allowPrivateServices = true;
// pipes are always eager and classes!
return createClass((/** @type {?} */ (compView.parent)), (/** @type {?} */ (viewParentEl(compView))), allowPrivateServices, (/** @type {?} */ (def.provider)).value, (/** @type {?} */ (def.provider)).deps);
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function createDirectiveInstance(view, def) {
// components can see other private services, other directives can't.
/** @type {?} */
const allowPrivateServices = (def.flags & 32768 /* Component */) > 0;
// directives are always eager and classes!
/** @type {?} */
const instance = createClass(view, (/** @type {?} */ (def.parent)), allowPrivateServices, (/** @type {?} */ (def.provider)).value, (/** @type {?} */ (def.provider)).deps);
if (def.outputs.length) {
for (let i = 0; i < def.outputs.length; i++) {
/** @type {?} */
const output = def.outputs[i];
/** @type {?} */
const outputObservable = instance[(/** @type {?} */ (output.propName))];
if (isObservable(outputObservable)) {
/** @type {?} */
const subscription = outputObservable.subscribe(eventHandlerClosure(view, (/** @type {?} */ (def.parent)).nodeIndex, output.eventName));
(/** @type {?} */ (view.disposables))[def.outputIndex + i] = subscription.unsubscribe.bind(subscription);
}
else {
throw new Error(`@Output ${output.propName} not initialized in '${instance.constructor.name}'.`);
}
}
}
return instance;
}
/**
* @param {?} view
* @param {?} index
* @param {?} eventName
* @return {?}
*/
function eventHandlerClosure(view, index, eventName) {
return (/**
* @param {?} event
* @return {?}
*/
(event) => dispatchEvent(view, index, eventName, event));
}
/**
* @param {?} view
* @param {?} def
* @param {?} v0
* @param {?} v1
* @param {?} v2
* @param {?} v3
* @param {?} v4
* @param {?} v5
* @param {?} v6
* @param {?} v7
* @param {?} v8
* @param {?} v9
* @return {?}
*/
function checkAndUpdateDirectiveInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
/** @type {?} */
const providerData = asProviderData(view, def.nodeIndex);
/** @type {?} */
const directive = providerData.instance;
/** @type {?} */
let changed = false;
/** @type {?} */
let changes = (/** @type {?} */ (undefined));
/** @type {?} */
const bindLen = def.bindings.length;
if (bindLen > 0 && checkBinding(view, def, 0, v0)) {
changed = true;
changes = updateProp(view, providerData, def, 0, v0, changes);
}
if (bindLen > 1 && checkBinding(view, def, 1, v1)) {
changed = true;
changes = updateProp(view, providerData, def, 1, v1, changes);
}
if (bindLen > 2 && checkBinding(view, def, 2, v2)) {
changed = true;
changes = updateProp(view, providerData, def, 2, v2, changes);
}
if (bindLen > 3 && checkBinding(view, def, 3, v3)) {
changed = true;
changes = updateProp(view, providerData, def, 3, v3, changes);
}
if (bindLen > 4 && checkBinding(view, def, 4, v4)) {
changed = true;
changes = updateProp(view, providerData, def, 4, v4, changes);
}
if (bindLen > 5 && checkBinding(view, def, 5, v5)) {
changed = true;
changes = updateProp(view, providerData, def, 5, v5, changes);
}
if (bindLen > 6 && checkBinding(view, def, 6, v6)) {
changed = true;
changes = updateProp(view, providerData, def, 6, v6, changes);
}
if (bindLen > 7 && checkBinding(view, def, 7, v7)) {
changed = true;
changes = updateProp(view, providerData, def, 7, v7, changes);
}
if (bindLen > 8 && checkBinding(view, def, 8, v8)) {
changed = true;
changes = updateProp(view, providerData, def, 8, v8, changes);
}
if (bindLen > 9 && checkBinding(view, def, 9, v9)) {
changed = true;
changes = updateProp(view, providerData, def, 9, v9, changes);
}
if (changes) {
directive.ngOnChanges(changes);
}
if ((def.flags & 65536 /* OnInit */) &&
shouldCallLifecycleInitHook(view, 256 /* InitState_CallingOnInit */, def.nodeIndex)) {
directive.ngOnInit();
}
if (def.flags & 262144 /* DoCheck */) {
directive.ngDoCheck();
}
return changed;
}
/**
* @param {?} view
* @param {?} def
* @param {?} values
* @return {?}
*/
function checkAndUpdateDirectiveDynamic(view, def, values) {
/** @type {?} */
const providerData = asProviderData(view, def.nodeIndex);
/** @type {?} */
const directive = providerData.instance;
/** @type {?} */
let changed = false;
/** @type {?} */
let changes = (/** @type {?} */ (undefined));
for (let i = 0; i < values.length; i++) {
if (checkBinding(view, def, i, values[i])) {
changed = true;
changes = updateProp(view, providerData, def, i, values[i], changes);
}
}
if (changes) {
directive.ngOnChanges(changes);
}
if ((def.flags & 65536 /* OnInit */) &&
shouldCallLifecycleInitHook(view, 256 /* InitState_CallingOnInit */, def.nodeIndex)) {
directive.ngOnInit();
}
if (def.flags & 262144 /* DoCheck */) {
directive.ngDoCheck();
}
return changed;
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function _createProviderInstance$1(view, def) {
// private services can see other private services
/** @type {?} */
const allowPrivateServices = (def.flags & 8192 /* PrivateProvider */) > 0;
/** @type {?} */
const providerDef = def.provider;
switch (def.flags & 201347067 /* Types */) {
case 512 /* TypeClassProvider */:
return createClass(view, (/** @type {?} */ (def.parent)), allowPrivateServices, (/** @type {?} */ (providerDef)).value, (/** @type {?} */ (providerDef)).deps);
case 1024 /* TypeFactoryProvider */:
return callFactory(view, (/** @type {?} */ (def.parent)), allowPrivateServices, (/** @type {?} */ (providerDef)).value, (/** @type {?} */ (providerDef)).deps);
case 2048 /* TypeUseExistingProvider */:
return resolveDep(view, (/** @type {?} */ (def.parent)), allowPrivateServices, (/** @type {?} */ (providerDef)).deps[0]);
case 256 /* TypeValueProvider */:
return (/** @type {?} */ (providerDef)).value;
}
}
/**
* @param {?} view
* @param {?} elDef
* @param {?} allowPrivateServices
* @param {?} ctor
* @param {?} deps
* @return {?}
*/
function createClass(view, elDef, allowPrivateServices, ctor, deps) {
/** @type {?} */
const len = deps.length;
switch (len) {
case 0:
return new ctor();
case 1:
return new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]));
case 2:
return new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]));
case 3:
return new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]), resolveDep(view, elDef, allowPrivateServices, deps[2]));
default:
/** @type {?} */
const depValues = [];
for (let i = 0; i < len; i++) {
depValues.push(resolveDep(view, elDef, allowPrivateServices, deps[i]));
}
return new ctor(...depValues);
}
}
/**
* @param {?} view
* @param {?} elDef
* @param {?} allowPrivateServices
* @param {?} factory
* @param {?} deps
* @return {?}
*/
function callFactory(view, elDef, allowPrivateServices, factory, deps) {
/** @type {?} */
const len = deps.length;
switch (len) {
case 0:
return factory();
case 1:
return factory(resolveDep(view, elDef, allowPrivateServices, deps[0]));
case 2:
return factory(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]));
case 3:
return factory(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]), resolveDep(view, elDef, allowPrivateServices, deps[2]));
default:
/** @type {?} */
const depValues = [];
for (let i = 0; i < len; i++) {
depValues.push(resolveDep(view, elDef, allowPrivateServices, deps[i]));
}
return factory(...depValues);
}
}
// This default value is when checking the hierarchy for a token.
//
// It means both:
// - the token is not provided by the current injector,
// - only the element injectors should be checked (ie do not check module injectors
//
// mod1
// /
// el1 mod2
// \ /
// el2
//
// When requesting el2.injector.get(token), we should check in the following order and return the
// first found value:
// - el2.injector.get(token, default)
// - el1.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) -> do not check the module
// - mod2.injector.get(token, default)
/** @type {?} */
const NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR = {};
/**
* @param {?} view
* @param {?} elDef
* @param {?} allowPrivateServices
* @param {?} depDef
* @param {?=} notFoundValue
* @return {?}
*/
function resolveDep(view, elDef, allowPrivateServices, depDef, notFoundValue = Injector.THROW_IF_NOT_FOUND) {
if (depDef.flags & 8 /* Value */) {
return depDef.token;
}
/** @type {?} */
const startView = view;
if (depDef.flags & 2 /* Optional */) {
notFoundValue = null;
}
/** @type {?} */
const tokenKey = depDef.tokenKey;
if (tokenKey === ChangeDetectorRefTokenKey) {
// directives on the same element as a component should be able to control the change detector
// of that component as well.
allowPrivateServices = !!(elDef && (/** @type {?} */ (elDef.element)).componentView);
}
if (elDef && (depDef.flags & 1 /* SkipSelf */)) {
allowPrivateServices = false;
elDef = (/** @type {?} */ (elDef.parent));
}
/** @type {?} */
let searchView = view;
while (searchView) {
if (elDef) {
switch (tokenKey) {
case Renderer2TokenKey: {
/** @type {?} */
const compView = findCompView(searchView, elDef, allowPrivateServices);
return compView.renderer;
}
case ElementRefTokenKey:
return new ElementRef(asElementData(searchView, elDef.nodeIndex).renderElement);
case ViewContainerRefTokenKey:
return asElementData(searchView, elDef.nodeIndex).viewContainer;
case TemplateRefTokenKey: {
if ((/** @type {?} */ (elDef.element)).template) {
return asElementData(searchView, elDef.nodeIndex).template;
}
break;
}
case ChangeDetectorRefTokenKey: {
/** @type {?} */
let cdView = findCompView(searchView, elDef, allowPrivateServices);
return createChangeDetectorRef(cdView);
}
case InjectorRefTokenKey$1:
case INJECTORRefTokenKey$1:
return createInjector$1(searchView, elDef);
default:
/** @type {?} */
const providerDef = (/** @type {?} */ ((allowPrivateServices ? (/** @type {?} */ (elDef.element)).allProviders :
(/** @type {?} */ (elDef.element)).publicProviders)))[tokenKey];
if (providerDef) {
/** @type {?} */
let providerData = asProviderData(searchView, providerDef.nodeIndex);
if (!providerData) {
providerData = { instance: _createProviderInstance$1(searchView, providerDef) };
searchView.nodes[providerDef.nodeIndex] = (/** @type {?} */ (providerData));
}
return providerData.instance;
}
}
}
allowPrivateServices = isComponentView(searchView);
elDef = (/** @type {?} */ (viewParentEl(searchView)));
searchView = (/** @type {?} */ (searchView.parent));
if (depDef.flags & 4 /* Self */) {
searchView = null;
}
}
/** @type {?} */
const value = startView.root.injector.get(depDef.token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR);
if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR ||
notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
// Return the value from the root element injector when
// - it provides it
// (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
// - the module injector should not be checked
// (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
return value;
}
return startView.root.ngModule.injector.get(depDef.token, notFoundValue);
}
/**
* @param {?} view
* @param {?} elDef
* @param {?} allowPrivateServices
* @return {?}
*/
function findCompView(view, elDef, allowPrivateServices) {
/** @type {?} */
let compView;
if (allowPrivateServices) {
compView = asElementData(view, elDef.nodeIndex).componentView;
}
else {
compView = view;
while (compView.parent && !isComponentView(compView)) {
compView = compView.parent;
}
}
return compView;
}
/**
* @param {?} view
* @param {?} providerData
* @param {?} def
* @param {?} bindingIdx
* @param {?} value
* @param {?} changes
* @return {?}
*/
function updateProp(view, providerData, def, bindingIdx, value, changes) {
if (def.flags & 32768 /* Component */) {
/** @type {?} */
const compView = asElementData(view, (/** @type {?} */ (def.parent)).nodeIndex).componentView;
if (compView.def.flags & 2 /* OnPush */) {
compView.state |= 8 /* ChecksEnabled */;
}
}
/** @type {?} */
const binding = def.bindings[bindingIdx];
/** @type {?} */
const propName = (/** @type {?} */ (binding.name));
// Note: This is still safe with Closure Compiler as
// the user passed in the property name as an object has to `providerDef`,
// so Closure Compiler will have renamed the property correctly already.
providerData.instance[propName] = value;
if (def.flags & 524288 /* OnChanges */) {
changes = changes || {};
/** @type {?} */
const oldValue = WrappedValue.unwrap(view.oldValues[def.bindingIndex + bindingIdx]);
/** @type {?} */
const binding = def.bindings[bindingIdx];
changes[(/** @type {?} */ (binding.nonMinifiedName))] =
new SimpleChange(oldValue, value, (view.state & 2 /* FirstCheck */) !== 0);
}
view.oldValues[def.bindingIndex + bindingIdx] = value;
return changes;
}
// This function calls the ngAfterContentCheck, ngAfterContentInit,
// ngAfterViewCheck, and ngAfterViewInit lifecycle hooks (depending on the node
// flags in lifecycle). Unlike ngDoCheck, ngOnChanges and ngOnInit, which are
// called during a pre-order traversal of the view tree (that is calling the
// parent hooks before the child hooks) these events are sent in using a
// post-order traversal of the tree (children before parents). This changes the
// meaning of initIndex in the view state. For ngOnInit, initIndex tracks the
// expected nodeIndex which a ngOnInit should be called. When sending
// ngAfterContentInit and ngAfterViewInit it is the expected count of
// ngAfterContentInit or ngAfterViewInit methods that have been called. This
// ensure that despite being called recursively or after picking up after an
// exception, the ngAfterContentInit or ngAfterViewInit will be called on the
// correct nodes. Consider for example, the following (where E is an element
// and D is a directive)
// Tree: pre-order index post-order index
// E1 0 6
// E2 1 1
// D3 2 0
// E4 3 5
// E5 4 4
// E6 5 2
// E7 6 3
// As can be seen, the post-order index has an unclear relationship to the
// pre-order index (postOrderIndex === preOrderIndex - parentCount +
// childCount). Since number of calls to ngAfterContentInit and ngAfterViewInit
// are stable (will be the same for the same view regardless of exceptions or
// recursion) we just need to count them which will roughly correspond to the
// post-order index (it skips elements and directives that do not have
// lifecycle hooks).
//
// For example, if an exception is raised in the E6.onAfterViewInit() the
// initIndex is left at 3 (by shouldCallLifecycleInitHook() which set it to
// initIndex + 1). When checkAndUpdateView() is called again D3, E2 and E6 will
// not have their ngAfterViewInit() called but, starting with E7, the rest of
// the view will begin getting ngAfterViewInit() called until a check and
// pass is complete.
//
// This algorthim also handles recursion. Consider if E4's ngAfterViewInit()
// indirectly calls E1's ChangeDetectorRef.detectChanges(). The expected
// initIndex is set to 6, the recusive checkAndUpdateView() starts walk again.
// D3, E2, E6, E7, E5 and E4 are skipped, ngAfterViewInit() is called on E1.
// When the recursion returns the initIndex will be 7 so E1 is skipped as it
// has already been called in the recursively called checkAnUpdateView().
/**
* @param {?} view
* @param {?} lifecycles
* @return {?}
*/
function callLifecycleHooksChildrenFirst(view, lifecycles) {
if (!(view.def.nodeFlags & lifecycles)) {
return;
}
/** @type {?} */
const nodes = view.def.nodes;
/** @type {?} */
let initIndex = 0;
for (let i = 0; i < nodes.length; i++) {
/** @type {?} */
const nodeDef = nodes[i];
/** @type {?} */
let parent = nodeDef.parent;
if (!parent && nodeDef.flags & lifecycles) {
// matching root node (e.g. a pipe)
callProviderLifecycles(view, i, nodeDef.flags & lifecycles, initIndex++);
}
if ((nodeDef.childFlags & lifecycles) === 0) {
// no child matches one of the lifecycles
i += nodeDef.childCount;
}
while (parent && (parent.flags & 1 /* TypeElement */) &&
i === parent.nodeIndex + parent.childCount) {
// last child of an element
if (parent.directChildFlags & lifecycles) {
initIndex = callElementProvidersLifecycles(view, parent, lifecycles, initIndex);
}
parent = parent.parent;
}
}
}
/**
* @param {?} view
* @param {?} elDef
* @param {?} lifecycles
* @param {?} initIndex
* @return {?}
*/
function callElementProvidersLifecycles(view, elDef, lifecycles, initIndex) {
for (let i = elDef.nodeIndex + 1; i <= elDef.nodeIndex + elDef.childCount; i++) {
/** @type {?} */
const nodeDef = view.def.nodes[i];
if (nodeDef.flags & lifecycles) {
callProviderLifecycles(view, i, nodeDef.flags & lifecycles, initIndex++);
}
// only visit direct children
i += nodeDef.childCount;
}
return initIndex;
}
/**
* @param {?} view
* @param {?} index
* @param {?} lifecycles
* @param {?} initIndex
* @return {?}
*/
function callProviderLifecycles(view, index, lifecycles, initIndex) {
/** @type {?} */
const providerData = asProviderData(view, index);
if (!providerData) {
return;
}
/** @type {?} */
const provider = providerData.instance;
if (!provider) {
return;
}
Services.setCurrentNode(view, index);
if (lifecycles & 1048576 /* AfterContentInit */ &&
shouldCallLifecycleInitHook(view, 512 /* InitState_CallingAfterContentInit */, initIndex)) {
provider.ngAfterContentInit();
}
if (lifecycles & 2097152 /* AfterContentChecked */) {
provider.ngAfterContentChecked();
}
if (lifecycles & 4194304 /* AfterViewInit */ &&
shouldCallLifecycleInitHook(view, 768 /* InitState_CallingAfterViewInit */, initIndex)) {
provider.ngAfterViewInit();
}
if (lifecycles & 8388608 /* AfterViewChecked */) {
provider.ngAfterViewChecked();
}
if (lifecycles & 131072 /* OnDestroy */) {
provider.ngOnDestroy();
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/component_ref.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class ComponentFactoryResolver$1 extends ComponentFactoryResolver {
/**
* @param {?=} ngModule The NgModuleRef to which all resolved factories are bound.
*/
constructor(ngModule) {
super();
this.ngModule = ngModule;
}
/**
* @template T
* @param {?} component
* @return {?}
*/
resolveComponentFactory(component) {
ngDevMode && assertComponentType(component);
/** @type {?} */
const componentDef = (/** @type {?} */ (getComponentDef(component)));
return new ComponentFactory$1(componentDef, this.ngModule);
}
}
if (false) {}
/**
* @param {?} map
* @return {?}
*/
function toRefArray(map) {
/** @type {?} */
const array = [];
for (let nonMinified in map) {
if (map.hasOwnProperty(nonMinified)) {
/** @type {?} */
const minified = map[nonMinified];
array.push({ propName: minified, templateName: nonMinified });
}
}
return array;
}
/**
* @param {?} elementName
* @return {?}
*/
function getNamespace$1(elementName) {
/** @type {?} */
const name = elementName.toLowerCase();
return name === 'svg' ? SVG_NAMESPACE : (name === 'math' ? MATH_ML_NAMESPACE : null);
}
/**
* A change detection scheduler token for {\@link RootContext}. This token is the default value used
* for the default `RootContext` found in the {\@link ROOT_CONTEXT} token.
* @type {?}
*/
const SCHEDULER = new InjectionToken('SCHEDULER_TOKEN', {
providedIn: 'root',
factory: (/**
* @return {?}
*/
() => defaultScheduler),
});
/**
* @param {?} rootViewInjector
* @param {?} moduleInjector
* @return {?}
*/
function createChainedInjector(rootViewInjector, moduleInjector) {
return {
get: (/**
* @template T
* @param {?} token
* @param {?=} notFoundValue
* @param {?=} flags
* @return {?}
*/
(token, notFoundValue, flags) => {
/** @type {?} */
const value = rootViewInjector.get(token, (/** @type {?} */ (NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)), flags);
if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR ||
notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
// Return the value from the root element injector when
// - it provides it
// (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
// - the module injector should not be checked
// (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
return value;
}
return moduleInjector.get(token, notFoundValue, flags);
})
};
}
/**
* Render3 implementation of {\@link viewEngine_ComponentFactory}.
* @template T
*/
class ComponentFactory$1 extends ComponentFactory {
/**
* @param {?} componentDef The component definition.
* @param {?=} ngModule The NgModuleRef to which the factory is bound.
*/
constructor(componentDef, ngModule) {
super();
this.componentDef = componentDef;
this.ngModule = ngModule;
this.componentType = componentDef.type;
this.selector = stringifyCSSSelectorList(componentDef.selectors);
this.ngContentSelectors =
componentDef.ngContentSelectors ? componentDef.ngContentSelectors : [];
this.isBoundToModule = !!ngModule;
}
/**
* @return {?}
*/
get inputs() {
return toRefArray(this.componentDef.inputs);
}
/**
* @return {?}
*/
get outputs() {
return toRefArray(this.componentDef.outputs);
}
/**
* @param {?} injector
* @param {?=} projectableNodes
* @param {?=} rootSelectorOrNode
* @param {?=} ngModule
* @return {?}
*/
create(injector, projectableNodes, rootSelectorOrNode, ngModule) {
ngModule = ngModule || this.ngModule;
/** @type {?} */
const rootViewInjector = ngModule ? createChainedInjector(injector, ngModule.injector) : injector;
/** @type {?} */
const rendererFactory = (/** @type {?} */ (rootViewInjector.get(RendererFactory2, domRendererFactory3)));
/** @type {?} */
const sanitizer = rootViewInjector.get(Sanitizer, null);
/** @type {?} */
const hostRenderer = rendererFactory.createRenderer(null, this.componentDef);
// Determine a tag name used for creating host elements when this component is created
// dynamically. Default to 'div' if this component did not specify any tag name in its selector.
/** @type {?} */
const elementName = (/** @type {?} */ (this.componentDef.selectors[0][0])) || 'div';
/** @type {?} */
const hostRNode = rootSelectorOrNode ?
locateHostElement(hostRenderer, rootSelectorOrNode, this.componentDef.encapsulation) :
elementCreate(elementName, rendererFactory.createRenderer(null, this.componentDef), getNamespace$1(elementName));
/** @type {?} */
const rootFlags = this.componentDef.onPush ? 64 /* Dirty */ | 512 /* IsRoot */ :
16 /* CheckAlways */ | 512 /* IsRoot */;
// Check whether this Component needs to be isolated from other components, i.e. whether it
// should be placed into its own (empty) root context or existing root context should be used.
// Note: this is internal-only convention and might change in the future, so it should not be
// relied upon externally.
/** @type {?} */
const isIsolated = typeof rootSelectorOrNode === 'string' &&
/^#root-ng-internal-isolated-\d+/.test(rootSelectorOrNode);
/** @type {?} */
const rootContext = createRootContext();
// Create the root view. Uses empty TView and ContentTemplate.
/** @type {?} */
const rootTView = createTView(0 /* Root */, -1, null, 1, 0, null, null, null, null, null);
/** @type {?} */
const rootLView = createLView(null, rootTView, rootContext, rootFlags, null, null, rendererFactory, hostRenderer, sanitizer, rootViewInjector);
// rootView is the parent when bootstrapping
// TODO(misko): it looks like we are entering view here but we don't really need to as
// `renderView` does that. However as the code is written it is needed because
// `createRootComponentView` and `createRootComponent` both read global state. Fixing those
// issues would allow us to drop this.
enterView(rootLView, null);
/** @type {?} */
let component;
/** @type {?} */
let tElementNode;
try {
/** @type {?} */
const componentView = createRootComponentView(hostRNode, this.componentDef, rootLView, rendererFactory, hostRenderer);
if (hostRNode) {
if (rootSelectorOrNode) {
setUpAttributes(hostRenderer, hostRNode, ['ng-version', VERSION.full]);
}
else {
// If host element is created as a part of this function call (i.e. `rootSelectorOrNode`
// is not defined), also apply attributes and classes extracted from component selector.
// Extract attributes and classes from the first selector only to match VE behavior.
const { attrs, classes } = extractAttrsAndClassesFromSelector(this.componentDef.selectors[0]);
if (attrs) {
setUpAttributes(hostRenderer, hostRNode, attrs);
}
if (classes && classes.length > 0) {
writeDirectClass(hostRenderer, hostRNode, classes.join(' '));
}
}
}
tElementNode = (/** @type {?} */ (getTNode(rootTView, 0)));
if (projectableNodes !== undefined) {
/** @type {?} */
const projection = tElementNode.projection = [];
for (let i = 0; i < this.ngContentSelectors.length; i++) {
/** @type {?} */
const nodesforSlot = projectableNodes[i];
// Projectable nodes can be passed as array of arrays or an array of iterables (ngUpgrade
// case). Here we do normalize passed data structure to be an array of arrays to avoid
// complex checks down the line.
// We also normalize the length of the passed in projectable nodes (to match the number of
// <ng-container> slots defined by a component).
projection.push(nodesforSlot != null ? Array.from(nodesforSlot) : null);
}
}
// TODO: should LifecycleHooksFeature and other host features be generated by the compiler and
// executed here?
// Angular 5 reference: https://stackblitz.com/edit/lifecycle-hooks-vcref
component = createRootComponent(componentView, this.componentDef, rootLView, rootContext, [LifecycleHooksFeature]);
renderView(rootTView, rootLView, null);
}
finally {
leaveView();
}
/** @type {?} */
const componentRef = new ComponentRef$1(this.componentType, component, createElementRef(ElementRef, tElementNode, rootLView), rootLView, tElementNode);
if (!rootSelectorOrNode || isIsolated) {
// The host element of the internal or isolated root view is attached to the component's host
// view node.
ngDevMode && assertNodeOfPossibleTypes(rootTView.node, 2 /* View */);
(/** @type {?} */ (rootTView.node)).child = tElementNode;
}
return componentRef;
}
}
if (false) {}
/** @type {?} */
const componentFactoryResolver = new ComponentFactoryResolver$1();
/**
* Creates a ComponentFactoryResolver and stores it on the injector. Or, if the
* ComponentFactoryResolver
* already exists, retrieves the existing ComponentFactoryResolver.
*
* @return {?} The ComponentFactoryResolver instance to use
*/
function injectComponentFactoryResolver() {
return componentFactoryResolver;
}
/**
* Represents an instance of a Component created via a {\@link ComponentFactory}.
*
* `ComponentRef` provides access to the Component Instance as well other objects related to this
* Component Instance and allows you to destroy the Component Instance via the {\@link #destroy}
* method.
*
* @template T
*/
class ComponentRef$1 extends ComponentRef {
/**
* @param {?} componentType
* @param {?} instance
* @param {?} location
* @param {?} _rootLView
* @param {?} _tNode
*/
constructor(componentType, instance, location, _rootLView, _tNode) {
super();
this.location = location;
this._rootLView = _rootLView;
this._tNode = _tNode;
this.destroyCbs = [];
this.instance = instance;
this.hostView = this.changeDetectorRef = new RootViewRef(_rootLView);
assignTViewNodeToLView(_rootLView[TVIEW], null, -1, _rootLView);
this.componentType = componentType;
}
/**
* @return {?}
*/
get injector() {
return new NodeInjector(this._tNode, this._rootLView);
}
/**
* @return {?}
*/
destroy() {
if (this.destroyCbs) {
this.destroyCbs.forEach((/**
* @param {?} fn
* @return {?}
*/
fn => fn()));
this.destroyCbs = null;
!this.hostView.destroyed && this.hostView.destroy();
}
}
/**
* @param {?} callback
* @return {?}
*/
onDestroy(callback) {
if (this.destroyCbs) {
this.destroyCbs.push(callback);
}
}
}
if (false) {}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* NOTE: changes to the `ngI18nClosureMode` name must be synced with `compiler-cli/src/tooling.ts`.
*/
if (typeof ngI18nClosureMode === 'undefined') {
// These property accesses can be ignored because ngI18nClosureMode will be set to false
// when optimizing code and the whole if statement will be dropped.
// Make sure to refer to ngI18nClosureMode as ['ngI18nClosureMode'] for closure.
// NOTE: we need to have it in IIFE so that the tree-shaker is happy.
(function () {
// tslint:disable-next-line:no-toplevel-property-access
_global['ngI18nClosureMode'] =
// TODO(FW-1250): validate that this actually, you know, works.
// tslint:disable-next-line:no-toplevel-property-access
typeof goog !== 'undefined' && typeof goog.getMsg === 'function';
})();
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/i18n/locale_en.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
/** @type {?} */
const u = undefined;
/**
* @param {?} n
* @return {?}
*/
function plural(n) {
/** @type {?} */
let i = Math.floor(Math.abs(n));
/** @type {?} */
let v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0)
return 1;
return 5;
}
var localeEn = [
'en',
[['a', 'p'], ['AM', 'PM'], u],
[['AM', 'PM'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
[
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
]
],
u,
[['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']],
0,
[6, 0],
['M/d/yy', 'MMM d, y', 'MMMM d, y', 'EEEE, MMMM d, y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1}, {0}', u, '{1} \'at\' {0}', u],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'],
'USD',
'$',
'US Dollar',
{},
'ltr',
plural
];
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/i18n/locale_data_api.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* This const is used to store the locale data registered with `registerLocaleData`
* @type {?}
*/
let LOCALE_DATA = {};
/**
* Register locale data to be used internally by Angular. See the
* ["I18n guide"](guide/i18n#i18n-pipes) to know how to import additional locale data.
*
* The signature `registerLocaleData(data: any, extraData?: any)` is deprecated since v5.1
* @param {?} data
* @param {?=} localeId
* @param {?=} extraData
* @return {?}
*/
function registerLocaleData(data, localeId, extraData) {
if (typeof localeId !== 'string') {
extraData = localeId;
localeId = data[LocaleDataIndex.LocaleId];
}
localeId = localeId.toLowerCase().replace(/_/g, '-');
LOCALE_DATA[localeId] = data;
if (extraData) {
LOCALE_DATA[localeId][LocaleDataIndex.ExtraData] = extraData;
}
}
/**
* Finds the locale data for a given locale.
*
* @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
* @param {?} locale The locale code.
* @return {?} The locale data.
*/
function findLocaleData(locale) {
/** @type {?} */
const normalizedLocale = normalizeLocale(locale);
/** @type {?} */
let match = getLocaleData(normalizedLocale);
if (match) {
return match;
}
// let's try to find a parent locale
/** @type {?} */
const parentLocale = normalizedLocale.split('-')[0];
match = getLocaleData(parentLocale);
if (match) {
return match;
}
if (parentLocale === 'en') {
return localeEn;
}
throw new Error(`Missing locale data for the locale "${locale}".`);
}
/**
* Retrieves the default currency code for the given locale.
*
* The default is defined as the first currency which is still in use.
*
* @param {?} locale The code of the locale whose currency code we want.
* @return {?} The code of the default currency for the given locale.
*
*/
function getLocaleCurrencyCode(locale) {
/** @type {?} */
const data = findLocaleData(locale);
return data[LocaleDataIndex.CurrencyCode] || null;
}
/**
* Retrieves the plural function used by ICU expressions to determine the plural case to use
* for a given locale.
* @see `NgPlural` / [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
* @param {?} locale A locale code for the locale format rules to use.
* @return {?} The plural function for the locale.
*/
function getLocalePluralCase(locale) {
/** @type {?} */
const data = findLocaleData(locale);
return data[LocaleDataIndex.PluralCase];
}
/**
* Helper function to get the given `normalizedLocale` from `LOCALE_DATA`
* or from the global `ng.common.locale`.
* @param {?} normalizedLocale
* @return {?}
*/
function getLocaleData(normalizedLocale) {
if (!(normalizedLocale in LOCALE_DATA)) {
LOCALE_DATA[normalizedLocale] = _global.ng && _global.ng.common && _global.ng.common.locales &&
_global.ng.common.locales[normalizedLocale];
}
return LOCALE_DATA[normalizedLocale];
}
/**
* Helper function to remove all the locale data from `LOCALE_DATA`.
* @return {?}
*/
function unregisterAllLocaleData() {
LOCALE_DATA = {};
}
/** @enum {number} */
const LocaleDataIndex = {
LocaleId: 0,
DayPeriodsFormat: 1,
DayPeriodsStandalone: 2,
DaysFormat: 3,
DaysStandalone: 4,
MonthsFormat: 5,
MonthsStandalone: 6,
Eras: 7,
FirstDayOfWeek: 8,
WeekendRange: 9,
DateFormat: 10,
TimeFormat: 11,
DateTimeFormat: 12,
NumberSymbols: 13,
NumberFormats: 14,
CurrencyCode: 15,
CurrencySymbol: 16,
CurrencyName: 17,
Currencies: 18,
Directionality: 19,
PluralCase: 20,
ExtraData: 21,
};
LocaleDataIndex[LocaleDataIndex.LocaleId] = 'LocaleId';
LocaleDataIndex[LocaleDataIndex.DayPeriodsFormat] = 'DayPeriodsFormat';
LocaleDataIndex[LocaleDataIndex.DayPeriodsStandalone] = 'DayPeriodsStandalone';
LocaleDataIndex[LocaleDataIndex.DaysFormat] = 'DaysFormat';
LocaleDataIndex[LocaleDataIndex.DaysStandalone] = 'DaysStandalone';
LocaleDataIndex[LocaleDataIndex.MonthsFormat] = 'MonthsFormat';
LocaleDataIndex[LocaleDataIndex.MonthsStandalone] = 'MonthsStandalone';
LocaleDataIndex[LocaleDataIndex.Eras] = 'Eras';
LocaleDataIndex[LocaleDataIndex.FirstDayOfWeek] = 'FirstDayOfWeek';
LocaleDataIndex[LocaleDataIndex.WeekendRange] = 'WeekendRange';
LocaleDataIndex[LocaleDataIndex.DateFormat] = 'DateFormat';
LocaleDataIndex[LocaleDataIndex.TimeFormat] = 'TimeFormat';
LocaleDataIndex[LocaleDataIndex.DateTimeFormat] = 'DateTimeFormat';
LocaleDataIndex[LocaleDataIndex.NumberSymbols] = 'NumberSymbols';
LocaleDataIndex[LocaleDataIndex.NumberFormats] = 'NumberFormats';
LocaleDataIndex[LocaleDataIndex.CurrencyCode] = 'CurrencyCode';
LocaleDataIndex[LocaleDataIndex.CurrencySymbol] = 'CurrencySymbol';
LocaleDataIndex[LocaleDataIndex.CurrencyName] = 'CurrencyName';
LocaleDataIndex[LocaleDataIndex.Currencies] = 'Currencies';
LocaleDataIndex[LocaleDataIndex.Directionality] = 'Directionality';
LocaleDataIndex[LocaleDataIndex.PluralCase] = 'PluralCase';
LocaleDataIndex[LocaleDataIndex.ExtraData] = 'ExtraData';
/** @enum {number} */
const ExtraLocaleDataIndex = {
ExtraDayPeriodFormats: 0,
ExtraDayPeriodStandalone: 1,
ExtraDayPeriodsRules: 2,
};
/** @enum {number} */
const CurrencyIndex = {
Symbol: 0,
SymbolNarrow: 1,
NbOfDigits: 2,
};
/**
* Returns the canonical form of a locale name - lowercase with `_` replaced with `-`.
* @param {?} locale
* @return {?}
*/
function normalizeLocale(locale) {
return locale.toLowerCase().replace(/_/g, '-');
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/i18n/localization.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const pluralMapping = ['zero', 'one', 'two', 'few', 'many'];
/**
* Returns the plural case based on the locale
* @param {?} value
* @param {?} locale
* @return {?}
*/
function getPluralCase(value, locale) {
/** @type {?} */
const plural = getLocalePluralCase(locale)(parseInt(value, 10));
/** @type {?} */
const result = pluralMapping[plural];
return (result !== undefined) ? result : 'other';
}
/**
* The locale id that the application is using by default (for translations and ICU expressions).
* @type {?}
*/
const DEFAULT_LOCALE_ID = 'en-US';
/**
* USD currency code that the application uses by default for CurrencyPipe when no
* DEFAULT_CURRENCY_CODE is provided.
* @type {?}
*/
const USD_CURRENCY_CODE = 'USD';
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/i18n.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const MARKER = `�`;
/** @type {?} */
const ICU_BLOCK_REGEXP = /^\s*(�\d+:?\d*�)\s*,\s*(select|plural)\s*,/;
/** @type {?} */
const SUBTEMPLATE_REGEXP = /�\/?\*(\d+:\d+)�/gi;
/** @type {?} */
const PH_REGEXP = /�(\/?[#*!]\d+):?\d*�/gi;
/** @type {?} */
const BINDING_REGEXP = /�(\d+):?\d*�/gi;
/** @type {?} */
const ICU_REGEXP = /({\s*�\d+:?\d*�\s*,\s*\S{6}\s*,[\s\S]*})/gi;
/** @enum {string} */
const TagType = {
ELEMENT: "#",
TEMPLATE: "*",
PROJECTION: "!",
};
// i18nPostprocess consts
/** @type {?} */
const ROOT_TEMPLATE_ID = 0;
/** @type {?} */
const PP_MULTI_VALUE_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]/;
/** @type {?} */
const PP_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]|(�\/?\*\d+:\d+�)/g;
/** @type {?} */
const PP_ICU_VARS_REGEXP = /({\s*)(VAR_(PLURAL|SELECT)(_\d+)?)(\s*,)/g;
/** @type {?} */
const PP_ICU_PLACEHOLDERS_REGEXP = /{([A-Z0-9_]+)}/g;
/** @type {?} */
const PP_ICUS_REGEXP = /�I18N_EXP_(ICU(_\d+)?)�/g;
/** @type {?} */
const PP_CLOSE_TEMPLATE_REGEXP = /\/\*/;
/** @type {?} */
const PP_TEMPLATE_ID_REGEXP = /\d+\:(\d+)/;
/**
* @record
*/
function IcuExpression() { }
if (false) {}
/**
* @record
*/
function IcuCase() { }
if (false) {}
/**
* Breaks pattern into strings and top level {...} blocks.
* Can be used to break a message into text and ICU expressions, or to break an ICU expression into
* keys and cases.
* Original code from closure library, modified for Angular.
*
* @param {?} pattern (sub)Pattern to be broken.
*
* @return {?}
*/
function extractParts(pattern) {
if (!pattern) {
return [];
}
/** @type {?} */
let prevPos = 0;
/** @type {?} */
const braceStack = [];
/** @type {?} */
const results = [];
/** @type {?} */
const braces = /[{}]/g;
// lastIndex doesn't get set to 0 so we have to.
braces.lastIndex = 0;
/** @type {?} */
let match;
while (match = braces.exec(pattern)) {
/** @type {?} */
const pos = match.index;
if (match[0] == '}') {
braceStack.pop();
if (braceStack.length == 0) {
// End of the block.
/** @type {?} */
const block = pattern.substring(prevPos, pos);
if (ICU_BLOCK_REGEXP.test(block)) {
results.push(parseICUBlock(block));
}
else {
results.push(block);
}
prevPos = pos + 1;
}
}
else {
if (braceStack.length == 0) {
/** @type {?} */
const substring = pattern.substring(prevPos, pos);
results.push(substring);
prevPos = pos + 1;
}
braceStack.push('{');
}
}
/** @type {?} */
const substring = pattern.substring(prevPos);
results.push(substring);
return results;
}
/**
* Parses text containing an ICU expression and produces a JSON object for it.
* Original code from closure library, modified for Angular.
*
* @param {?} pattern Text containing an ICU expression that needs to be parsed.
*
* @return {?}
*/
function parseICUBlock(pattern) {
/** @type {?} */
const cases = [];
/** @type {?} */
const values = [];
/** @type {?} */
let icuType = 1 /* plural */;
/** @type {?} */
let mainBinding = 0;
pattern = pattern.replace(ICU_BLOCK_REGEXP, (/**
* @param {?} str
* @param {?} binding
* @param {?} type
* @return {?}
*/
function (str, binding, type) {
if (type === 'select') {
icuType = 0 /* select */;
}
else {
icuType = 1 /* plural */;
}
mainBinding = parseInt(binding.substr(1), 10);
return '';
}));
/** @type {?} */
const parts = (/** @type {?} */ (extractParts(pattern)));
// Looking for (key block)+ sequence. One of the keys has to be "other".
for (let pos = 0; pos < parts.length;) {
/** @type {?} */
let key = parts[pos++].trim();
if (icuType === 1 /* plural */) {
// Key can be "=x", we just want "x"
key = key.replace(/\s*(?:=)?(\w+)\s*/, '$1');
}
if (key.length) {
cases.push(key);
}
/** @type {?} */
const blocks = (/** @type {?} */ (extractParts(parts[pos++])));
if (cases.length > values.length) {
values.push(blocks);
}
}
// TODO(ocombe): support ICU expressions in attributes, see #21615
return { type: icuType, mainBinding: mainBinding, cases, values };
}
/**
* Removes everything inside the sub-templates of a message.
* @param {?} message
* @return {?}
*/
function removeInnerTemplateTranslation(message) {
/** @type {?} */
let match;
/** @type {?} */
let res = '';
/** @type {?} */
let index = 0;
/** @type {?} */
let inTemplate = false;
/** @type {?} */
let tagMatched;
while ((match = SUBTEMPLATE_REGEXP.exec(message)) !== null) {
if (!inTemplate) {
res += message.substring(index, match.index + match[0].length);
tagMatched = match[1];
inTemplate = true;
}
else {
if (match[0] === `${MARKER}/*${tagMatched}${MARKER}`) {
index = match.index;
inTemplate = false;
}
}
}
ngDevMode &&
assertEqual(inTemplate, false, `Tag mismatch: unable to find the end of the sub-template in the translation "${message}"`);
res += message.substr(index);
return res;
}
/**
* Extracts a part of a message and removes the rest.
*
* This method is used for extracting a part of the message associated with a template. A translated
* message can span multiple templates.
*
* Example:
* ```
* <div i18n>Translate <span *ngIf>me</span>!</div>
* ```
*
* @param {?} message The message to crop
* @param {?=} subTemplateIndex Index of the sub-template to extract. If undefined it returns the
* external template and removes all sub-templates.
* @return {?}
*/
function getTranslationForTemplate(message, subTemplateIndex) {
if (isRootTemplateMessage(subTemplateIndex)) {
// We want the root template message, ignore all sub-templates
return removeInnerTemplateTranslation(message);
}
else {
// We want a specific sub-template
/** @type {?} */
const start = message.indexOf(`:${subTemplateIndex}${MARKER}`) + 2 + subTemplateIndex.toString().length;
/** @type {?} */
const end = message.search(new RegExp(`${MARKER}\\/\\*\\d+:${subTemplateIndex}${MARKER}`));
return removeInnerTemplateTranslation(message.substring(start, end));
}
}
/**
* Generate the OpCodes to update the bindings of a string.
*
* @param {?} str The string containing the bindings.
* @param {?} destinationNode Index of the destination node which will receive the binding.
* @param {?=} attrName Name of the attribute, if the string belongs to an attribute.
* @param {?=} sanitizeFn Sanitization function used to sanitize the string after update, if necessary.
* @return {?}
*/
function generateBindingUpdateOpCodes(str, destinationNode, attrName, sanitizeFn = null) {
/** @type {?} */
const updateOpCodes = [null, null];
// Alloc space for mask and size
/** @type {?} */
const textParts = str.split(BINDING_REGEXP);
/** @type {?} */
let mask = 0;
for (let j = 0; j < textParts.length; j++) {
/** @type {?} */
const textValue = textParts[j];
if (j & 1) {
// Odd indexes are bindings
/** @type {?} */
const bindingIndex = parseInt(textValue, 10);
updateOpCodes.push(-1 - bindingIndex);
mask = mask | toMaskBit(bindingIndex);
}
else if (textValue !== '') {
// Even indexes are text
updateOpCodes.push(textValue);
}
}
updateOpCodes.push(destinationNode << 2 /* SHIFT_REF */ |
(attrName ? 1 /* Attr */ : 0 /* Text */));
if (attrName) {
updateOpCodes.push(attrName, sanitizeFn);
}
updateOpCodes[0] = mask;
updateOpCodes[1] = updateOpCodes.length - 2;
return updateOpCodes;
}
/**
* @param {?} icuExpression
* @param {?=} mask
* @return {?}
*/
function getBindingMask(icuExpression, mask = 0) {
mask = mask | toMaskBit(icuExpression.mainBinding);
/** @type {?} */
let match;
for (let i = 0; i < icuExpression.values.length; i++) {
/** @type {?} */
const valueArr = icuExpression.values[i];
for (let j = 0; j < valueArr.length; j++) {
/** @type {?} */
const value = valueArr[j];
if (typeof value === 'string') {
while (match = BINDING_REGEXP.exec(value)) {
mask = mask | toMaskBit(parseInt(match[1], 10));
}
}
else {
mask = getBindingMask((/** @type {?} */ (value)), mask);
}
}
}
return mask;
}
/** @type {?} */
const i18nIndexStack = [];
/** @type {?} */
let i18nIndexStackPointer = -1;
/**
* Convert binding index to mask bit.
*
* Each index represents a single bit on the bit-mask. Because bit-mask only has 32 bits, we make
* the 32nd bit share all masks for all bindings higher than 32. Since it is extremely rare to have
* more than 32 bindings this will be hit very rarely. The downside of hitting this corner case is
* that we will execute binding code more often than necessary. (penalty of performance)
* @param {?} bindingIndex
* @return {?}
*/
function toMaskBit(bindingIndex) {
return 1 << Math.min(bindingIndex, 31);
}
/** @type {?} */
const parentIndexStack = [];
/**
* Marks a block of text as translatable.
*
* The instructions `i18nStart` and `i18nEnd` mark the translation block in the template.
* The translation `message` is the value which is locale specific. The translation string may
* contain placeholders which associate inner elements and sub-templates within the translation.
*
* The translation `message` placeholders are:
* - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be
* interpolated into. The placeholder `index` points to the expression binding index. An optional
* `block` that matches the sub-template in which it was declared.
* - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*: Marks the beginning
* and end of DOM element that were embedded in the original translation block. The placeholder
* `index` points to the element index in the template instructions set. An optional `block` that
* matches the sub-template in which it was declared.
* - `�!{index}(:{block})�`/`�/!{index}(:{block})�`: *Projection Placeholder*: Marks the
* beginning and end of <ng-content> that was embedded in the original translation block.
* The placeholder `index` points to the element index in the template instructions set.
* An optional `block` that matches the sub-template in which it was declared.
* - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be
* split up and translated separately in each angular template function. The `index` points to the
* `template` instruction index. A `block` that matches the sub-template in which it was declared.
*
* \@codeGenApi
* @param {?} index A unique index of the translation in the static block.
* @param {?} message The translation message.
* @param {?=} subTemplateIndex Optional sub-template index in the `message`.
*
* @return {?}
*/
function ɵɵi18nStart(index, message, subTemplateIndex) {
/** @type {?} */
const tView = getTView();
ngDevMode && assertDefined(tView, `tView should be defined`);
i18nIndexStack[++i18nIndexStackPointer] = index;
// We need to delay projections until `i18nEnd`
setDelayProjection(true);
if (tView.firstCreatePass && tView.data[index + HEADER_OFFSET] === null) {
i18nStartFirstPass(getLView(), tView, index, message, subTemplateIndex);
}
}
// Count for the number of vars that will be allocated for each i18n block.
// It is global because this is used in multiple functions that include loops and recursive calls.
// This is reset to 0 when `i18nStartFirstPass` is called.
/** @type {?} */
let i18nVarsCount;
/**
* @param {?} startIndex
* @return {?}
*/
function allocNodeIndex(startIndex) {
return startIndex + i18nVarsCount++;
}
/**
* See `i18nStart` above.
* @param {?} lView
* @param {?} tView
* @param {?} index
* @param {?} message
* @param {?=} subTemplateIndex
* @return {?}
*/
function i18nStartFirstPass(lView, tView, index, message, subTemplateIndex) {
/** @type {?} */
const startIndex = tView.blueprint.length - HEADER_OFFSET;
i18nVarsCount = 0;
/** @type {?} */
const previousOrParentTNode = getPreviousOrParentTNode();
/** @type {?} */
const parentTNode = getIsParent() ? previousOrParentTNode : previousOrParentTNode && previousOrParentTNode.parent;
/** @type {?} */
let parentIndex = parentTNode && parentTNode !== lView[T_HOST] ? parentTNode.index - HEADER_OFFSET : index;
/** @type {?} */
let parentIndexPointer = 0;
parentIndexStack[parentIndexPointer] = parentIndex;
/** @type {?} */
const createOpCodes = [];
// If the previous node wasn't the direct parent then we have a translation without top level
// element and we need to keep a reference of the previous element if there is one. We should also
// keep track whether an element was a parent node or not, so that the logic that consumes
// the generated `I18nMutateOpCode`s can leverage this information to properly set TNode state
// (whether it's a parent or sibling).
if (index > 0 && previousOrParentTNode !== parentTNode) {
/** @type {?} */
let previousTNodeIndex = previousOrParentTNode.index - HEADER_OFFSET;
// If current TNode is a sibling node, encode it using a negative index. This information is
// required when the `Select` action is processed (see the `readCreateOpCodes` function).
if (!getIsParent()) {
previousTNodeIndex = ~previousTNodeIndex;
}
// Create an OpCode to select the previous TNode
createOpCodes.push(previousTNodeIndex << 3 /* SHIFT_REF */ | 0 /* Select */);
}
/** @type {?} */
const updateOpCodes = [];
/** @type {?} */
const icuExpressions = [];
if (message === '' && isRootTemplateMessage(subTemplateIndex)) {
// If top level translation is an empty string, do not invoke additional processing
// and just create op codes for empty text node instead.
createOpCodes.push(message, allocNodeIndex(startIndex), parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
}
else {
/** @type {?} */
const templateTranslation = getTranslationForTemplate(message, subTemplateIndex);
/** @type {?} */
const msgParts = replaceNgsp(templateTranslation).split(PH_REGEXP);
for (let i = 0; i < msgParts.length; i++) {
/** @type {?} */
let value = msgParts[i];
if (i & 1) {
// Odd indexes are placeholders (elements and sub-templates)
if (value.charAt(0) === '/') {
// It is a closing tag
if (value.charAt(1) === "#" /* ELEMENT */) {
/** @type {?} */
const phIndex = parseInt(value.substr(2), 10);
parentIndex = parentIndexStack[--parentIndexPointer];
createOpCodes.push(phIndex << 3 /* SHIFT_REF */ | 5 /* ElementEnd */);
}
}
else {
/** @type {?} */
const phIndex = parseInt(value.substr(1), 10);
/** @type {?} */
const isElement = value.charAt(0) === "#" /* ELEMENT */;
// The value represents a placeholder that we move to the designated index.
// Note: positive indicies indicate that a TNode with a given index should also be marked
// as parent while executing `Select` instruction.
createOpCodes.push((isElement ? phIndex : ~phIndex) << 3 /* SHIFT_REF */ |
0 /* Select */, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
if (isElement) {
parentIndexStack[++parentIndexPointer] = parentIndex = phIndex;
}
}
}
else {
// Even indexes are text (including bindings & ICU expressions)
/** @type {?} */
const parts = extractParts(value);
for (let j = 0; j < parts.length; j++) {
if (j & 1) {
// Odd indexes are ICU expressions
/** @type {?} */
const icuExpression = (/** @type {?} */ (parts[j]));
// Verify that ICU expression has the right shape. Translations might contain invalid
// constructions (while original messages were correct), so ICU parsing at runtime may
// not succeed (thus `icuExpression` remains a string).
if (typeof icuExpression !== 'object') {
throw new Error(`Unable to parse ICU expression in "${templateTranslation}" message.`);
}
// Create the comment node that will anchor the ICU expression
/** @type {?} */
const icuNodeIndex = allocNodeIndex(startIndex);
createOpCodes.push(COMMENT_MARKER, ngDevMode ? `ICU ${icuNodeIndex}` : '', icuNodeIndex, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
// Update codes for the ICU expression
/** @type {?} */
const mask = getBindingMask(icuExpression);
icuStart(icuExpressions, icuExpression, icuNodeIndex, icuNodeIndex);
// Since this is recursive, the last TIcu that was pushed is the one we want
/** @type {?} */
const tIcuIndex = icuExpressions.length - 1;
updateOpCodes.push(toMaskBit(icuExpression.mainBinding), // mask of the main binding
3, // skip 3 opCodes if not changed
-1 - icuExpression.mainBinding, icuNodeIndex << 2 /* SHIFT_REF */ | 2 /* IcuSwitch */, tIcuIndex, mask, // mask of all the bindings of this ICU expression
2, // skip 2 opCodes if not changed
icuNodeIndex << 2 /* SHIFT_REF */ | 3 /* IcuUpdate */, tIcuIndex);
}
else if (parts[j] !== '') {
/** @type {?} */
const text = (/** @type {?} */ (parts[j]));
// Even indexes are text (including bindings)
/** @type {?} */
const hasBinding = text.match(BINDING_REGEXP);
// Create text nodes
/** @type {?} */
const textNodeIndex = allocNodeIndex(startIndex);
createOpCodes.push(
// If there is a binding, the value will be set during update
hasBinding ? '' : text, textNodeIndex, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
if (hasBinding) {
addAllToArray(generateBindingUpdateOpCodes(text, textNodeIndex), updateOpCodes);
}
}
}
}
}
}
if (i18nVarsCount > 0) {
allocExpando(tView, lView, i18nVarsCount);
}
ngDevMode &&
attachI18nOpCodesDebug(createOpCodes, updateOpCodes, icuExpressions.length ? icuExpressions : null, lView);
// NOTE: local var needed to properly assert the type of `TI18n`.
/** @type {?} */
const tI18n = {
vars: i18nVarsCount,
create: createOpCodes,
update: updateOpCodes,
icus: icuExpressions.length ? icuExpressions : null,
};
tView.data[index + HEADER_OFFSET] = tI18n;
}
/**
* @param {?} tView
* @param {?} tNode
* @param {?} parentTNode
* @param {?} previousTNode
* @param {?} lView
* @return {?}
*/
function appendI18nNode(tView, tNode, parentTNode, previousTNode, lView) {
ngDevMode && ngDevMode.rendererMoveNode++;
/** @type {?} */
const nextNode = tNode.next;
if (!previousTNode) {
previousTNode = parentTNode;
}
// Re-organize node tree to put this node in the correct position.
if (previousTNode === parentTNode && tNode !== parentTNode.child) {
tNode.next = parentTNode.child;
parentTNode.child = tNode;
}
else if (previousTNode !== parentTNode && tNode !== previousTNode.next) {
tNode.next = previousTNode.next;
previousTNode.next = tNode;
}
else {
tNode.next = null;
}
if (parentTNode !== lView[T_HOST]) {
tNode.parent = (/** @type {?} */ (parentTNode));
}
// If tNode was moved around, we might need to fix a broken link.
/** @type {?} */
let cursor = tNode.next;
while (cursor) {
if (cursor.next === tNode) {
cursor.next = nextNode;
}
cursor = cursor.next;
}
// If the placeholder to append is a projection, we need to move the projected nodes instead
if (tNode.type === 1 /* Projection */) {
applyProjection(tView, lView, (/** @type {?} */ (tNode)));
return tNode;
}
appendChild(tView, lView, getNativeByTNode(tNode, lView), tNode);
/** @type {?} */
const slotValue = lView[tNode.index];
if (tNode.type !== 0 /* Container */ && isLContainer(slotValue)) {
// Nodes that inject ViewContainerRef also have a comment node that should be moved
appendChild(tView, lView, slotValue[NATIVE], tNode);
}
return tNode;
}
/**
* @param {?} subTemplateIndex
* @return {?}
*/
function isRootTemplateMessage(subTemplateIndex) {
return subTemplateIndex === undefined;
}
/**
* Handles message string post-processing for internationalization.
*
* Handles message string post-processing by transforming it from intermediate
* format (that might contain some markers that we need to replace) to the final
* form, consumable by i18nStart instruction. Post processing steps include:
*
* 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�])
* 2. Replace all ICU vars (like "VAR_PLURAL")
* 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
* 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�)
* in case multiple ICUs have the same placeholder name
*
* \@codeGenApi
* @param {?} message Raw translation string for post processing
* @param {?=} replacements Set of replacements that should be applied
*
* @return {?} Transformed string that can be consumed by i18nStart instruction
*
*/
function ɵɵi18nPostprocess(message, replacements = {}) {
/**
* Step 1: resolve all multi-value placeholders like [�#5�|�*1:1��#2:1�|�#4:1�]
*
* Note: due to the way we process nested templates (BFS), multi-value placeholders are typically
* grouped by templates, for example: [�#5�|�#6�|�#1:1�|�#3:2�] where �#5� and �#6� belong to root
* template, �#1:1� belong to nested template with index 1 and �#1:2� - nested template with index
* 3. However in real templates the order might be different: i.e. �#1:1� and/or �#3:2� may go in
* front of �#6�. The post processing step restores the right order by keeping track of the
* template id stack and looks for placeholders that belong to the currently active template.
* @type {?}
*/
let result = message;
if (PP_MULTI_VALUE_PLACEHOLDERS_REGEXP.test(message)) {
/** @type {?} */
const matches = {};
/** @type {?} */
const templateIdsStack = [ROOT_TEMPLATE_ID];
result = result.replace(PP_PLACEHOLDERS_REGEXP, (/**
* @param {?} m
* @param {?} phs
* @param {?} tmpl
* @return {?}
*/
(m, phs, tmpl) => {
/** @type {?} */
const content = phs || tmpl;
/** @type {?} */
const placeholders = matches[content] || [];
if (!placeholders.length) {
content.split('|').forEach((/**
* @param {?} placeholder
* @return {?}
*/
(placeholder) => {
/** @type {?} */
const match = placeholder.match(PP_TEMPLATE_ID_REGEXP);
/** @type {?} */
const templateId = match ? parseInt(match[1], 10) : ROOT_TEMPLATE_ID;
/** @type {?} */
const isCloseTemplateTag = PP_CLOSE_TEMPLATE_REGEXP.test(placeholder);
placeholders.push([templateId, isCloseTemplateTag, placeholder]);
}));
matches[content] = placeholders;
}
if (!placeholders.length) {
throw new Error(`i18n postprocess: unmatched placeholder - ${content}`);
}
/** @type {?} */
const currentTemplateId = templateIdsStack[templateIdsStack.length - 1];
/** @type {?} */
let idx = 0;
// find placeholder index that matches current template id
for (let i = 0; i < placeholders.length; i++) {
if (placeholders[i][0] === currentTemplateId) {
idx = i;
break;
}
}
// update template id stack based on the current tag extracted
const [templateId, isCloseTemplateTag, placeholder] = placeholders[idx];
if (isCloseTemplateTag) {
templateIdsStack.pop();
}
else if (currentTemplateId !== templateId) {
templateIdsStack.push(templateId);
}
// remove processed tag from the list
placeholders.splice(idx, 1);
return placeholder;
}));
}
// return current result if no replacements specified
if (!Object.keys(replacements).length) {
return result;
}
/**
* Step 2: replace all ICU vars (like "VAR_PLURAL")
*/
result = result.replace(PP_ICU_VARS_REGEXP, (/**
* @param {?} match
* @param {?} start
* @param {?} key
* @param {?} _type
* @param {?} _idx
* @param {?} end
* @return {?}
*/
(match, start, key, _type, _idx, end) => {
return replacements.hasOwnProperty(key) ? `${start}${replacements[key]}${end}` : match;
}));
/**
* Step 3: replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
*/
result = result.replace(PP_ICU_PLACEHOLDERS_REGEXP, (/**
* @param {?} match
* @param {?} key
* @return {?}
*/
(match, key) => {
return replacements.hasOwnProperty(key) ? (/** @type {?} */ (replacements[key])) : match;
}));
/**
* Step 4: replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�) in case
* multiple ICUs have the same placeholder name
*/
result = result.replace(PP_ICUS_REGEXP, (/**
* @param {?} match
* @param {?} key
* @return {?}
*/
(match, key) => {
if (replacements.hasOwnProperty(key)) {
/** @type {?} */
const list = (/** @type {?} */ (replacements[key]));
if (!list.length) {
throw new Error(`i18n postprocess: unmatched ICU - ${match} with key: ${key}`);
}
return (/** @type {?} */ (list.shift()));
}
return match;
}));
return result;
}
/**
* Translates a translation block marked by `i18nStart` and `i18nEnd`. It inserts the text/ICU nodes
* into the render tree, moves the placeholder nodes and removes the deleted nodes.
*
* \@codeGenApi
* @return {?}
*/
function ɵɵi18nEnd() {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
ngDevMode && assertDefined(tView, `tView should be defined`);
i18nEndFirstPass(tView, lView);
// Stop delaying projections
setDelayProjection(false);
}
/**
* See `i18nEnd` above.
* @param {?} tView
* @param {?} lView
* @return {?}
*/
function i18nEndFirstPass(tView, lView) {
ngDevMode &&
assertEqual(getBindingIndex(), tView.bindingStartIndex, 'i18nEnd should be called before any binding');
/** @type {?} */
const rootIndex = i18nIndexStack[i18nIndexStackPointer--];
/** @type {?} */
const tI18n = (/** @type {?} */ (tView.data[rootIndex + HEADER_OFFSET]));
ngDevMode && assertDefined(tI18n, `You should call i18nStart before i18nEnd`);
// Find the last node that was added before `i18nEnd`
/** @type {?} */
const lastCreatedNode = getPreviousOrParentTNode();
// Read the instructions to insert/move/remove DOM elements
/** @type {?} */
const visitedNodes = readCreateOpCodes(rootIndex, tI18n.create, tView, lView);
// Remove deleted nodes
/** @type {?} */
let index = rootIndex + 1;
while (index <= lastCreatedNode.index - HEADER_OFFSET) {
if (visitedNodes.indexOf(index) === -1) {
removeNode(tView, lView, index, /* markAsDetached */ true);
}
// Check if an element has any local refs and skip them
/** @type {?} */
const tNode = getTNode(tView, index);
if (tNode &&
(tNode.type === 0 /* Container */ || tNode.type === 3 /* Element */ ||
tNode.type === 4 /* ElementContainer */) &&
tNode.localNames !== null) {
// Divide by 2 to get the number of local refs,
// since they are stored as an array that also includes directive indexes,
// i.e. ["localRef", directiveIndex, ...]
index += tNode.localNames.length >> 1;
}
index++;
}
}
/**
* Creates and stores the dynamic TNode, and unhooks it from the tree for now.
* @param {?} tView
* @param {?} lView
* @param {?} index
* @param {?} type
* @param {?} native
* @param {?} name
* @return {?}
*/
function createDynamicNodeAtIndex(tView, lView, index, type, native, name) {
/** @type {?} */
const previousOrParentTNode = getPreviousOrParentTNode();
ngDevMode && assertDataInRange(lView, index + HEADER_OFFSET);
lView[index + HEADER_OFFSET] = native;
/** @type {?} */
const tNode = getOrCreateTNode(tView, lView[T_HOST], index, (/** @type {?} */ (type)), name, null);
// We are creating a dynamic node, the previous tNode might not be pointing at this node.
// We will link ourselves into the tree later with `appendI18nNode`.
if (previousOrParentTNode && previousOrParentTNode.next === tNode) {
previousOrParentTNode.next = null;
}
return tNode;
}
/**
* @param {?} index
* @param {?} createOpCodes
* @param {?} tView
* @param {?} lView
* @return {?}
*/
function readCreateOpCodes(index, createOpCodes, tView, lView) {
/** @type {?} */
const renderer = lView[RENDERER];
/** @type {?} */
let currentTNode = null;
/** @type {?} */
let previousTNode = null;
/** @type {?} */
const visitedNodes = [];
for (let i = 0; i < createOpCodes.length; i++) {
/** @type {?} */
const opCode = createOpCodes[i];
if (typeof opCode == 'string') {
/** @type {?} */
const textRNode = createTextNode(opCode, renderer);
/** @type {?} */
const textNodeIndex = (/** @type {?} */ (createOpCodes[++i]));
ngDevMode && ngDevMode.rendererCreateTextNode++;
previousTNode = currentTNode;
currentTNode =
createDynamicNodeAtIndex(tView, lView, textNodeIndex, 3 /* Element */, textRNode, null);
visitedNodes.push(textNodeIndex);
setIsNotParent();
}
else if (typeof opCode == 'number') {
switch (opCode & 7 /* MASK_OPCODE */) {
case 1 /* AppendChild */:
/** @type {?} */
const destinationNodeIndex = opCode >>> 17 /* SHIFT_PARENT */;
/** @type {?} */
let destinationTNode;
if (destinationNodeIndex === index) {
// If the destination node is `i18nStart`, we don't have a
// top-level node and we should use the host node instead
destinationTNode = (/** @type {?} */ (lView[T_HOST]));
}
else {
destinationTNode = getTNode(tView, destinationNodeIndex);
}
ngDevMode &&
assertDefined((/** @type {?} */ (currentTNode)), `You need to create or select a node before you can insert it into the DOM`);
previousTNode =
appendI18nNode(tView, (/** @type {?} */ (currentTNode)), destinationTNode, previousTNode, lView);
break;
case 0 /* Select */:
// Negative indicies indicate that a given TNode is a sibling node, not a parent node
// (see `i18nStartFirstPass` for additional information).
/** @type {?} */
const isParent = opCode >= 0;
/** @type {?} */
const nodeIndex = (isParent ? opCode : ~opCode) >>> 3 /* SHIFT_REF */;
visitedNodes.push(nodeIndex);
previousTNode = currentTNode;
currentTNode = getTNode(tView, nodeIndex);
if (currentTNode) {
setPreviousOrParentTNode(currentTNode, isParent);
}
break;
case 5 /* ElementEnd */:
/** @type {?} */
const elementIndex = opCode >>> 3 /* SHIFT_REF */;
previousTNode = currentTNode = getTNode(tView, elementIndex);
setPreviousOrParentTNode(currentTNode, false);
break;
case 4 /* Attr */:
/** @type {?} */
const elementNodeIndex = opCode >>> 3 /* SHIFT_REF */;
/** @type {?} */
const attrName = (/** @type {?} */ (createOpCodes[++i]));
/** @type {?} */
const attrValue = (/** @type {?} */ (createOpCodes[++i]));
// This code is used for ICU expressions only, since we don't support
// directives/components in ICUs, we don't need to worry about inputs here
elementAttributeInternal(getTNode(tView, elementNodeIndex), lView, attrName, attrValue, null, null);
break;
default:
throw new Error(`Unable to determine the type of mutate operation for "${opCode}"`);
}
}
else {
switch (opCode) {
case COMMENT_MARKER:
/** @type {?} */
const commentValue = (/** @type {?} */ (createOpCodes[++i]));
/** @type {?} */
const commentNodeIndex = (/** @type {?} */ (createOpCodes[++i]));
ngDevMode &&
assertEqual(typeof commentValue, 'string', `Expected "${commentValue}" to be a comment node value`);
/** @type {?} */
const commentRNode = renderer.createComment(commentValue);
ngDevMode && ngDevMode.rendererCreateComment++;
previousTNode = currentTNode;
currentTNode = createDynamicNodeAtIndex(tView, lView, commentNodeIndex, 5 /* IcuContainer */, commentRNode, null);
visitedNodes.push(commentNodeIndex);
attachPatchData(commentRNode, lView);
((/** @type {?} */ (currentTNode))).activeCaseIndex = null;
// We will add the case nodes later, during the update phase
setIsNotParent();
break;
case ELEMENT_MARKER:
/** @type {?} */
const tagNameValue = (/** @type {?} */ (createOpCodes[++i]));
/** @type {?} */
const elementNodeIndex = (/** @type {?} */ (createOpCodes[++i]));
ngDevMode &&
assertEqual(typeof tagNameValue, 'string', `Expected "${tagNameValue}" to be an element node tag name`);
/** @type {?} */
const elementRNode = renderer.createElement(tagNameValue);
ngDevMode && ngDevMode.rendererCreateElement++;
previousTNode = currentTNode;
currentTNode = createDynamicNodeAtIndex(tView, lView, elementNodeIndex, 3 /* Element */, elementRNode, tagNameValue);
visitedNodes.push(elementNodeIndex);
break;
default:
throw new Error(`Unable to determine the type of mutate operation for "${opCode}"`);
}
}
}
setIsNotParent();
return visitedNodes;
}
/**
* @param {?} updateOpCodes
* @param {?} icus
* @param {?} bindingsStartIndex
* @param {?} changeMask
* @param {?} tView
* @param {?} lView
* @param {?=} bypassCheckBit
* @return {?}
*/
function readUpdateOpCodes(updateOpCodes, icus, bindingsStartIndex, changeMask, tView, lView, bypassCheckBit = false) {
/** @type {?} */
let caseCreated = false;
for (let i = 0; i < updateOpCodes.length; i++) {
// bit code to check if we should apply the next update
/** @type {?} */
const checkBit = (/** @type {?} */ (updateOpCodes[i]));
// Number of opCodes to skip until next set of update codes
/** @type {?} */
const skipCodes = (/** @type {?} */ (updateOpCodes[++i]));
if (bypassCheckBit || (checkBit & changeMask)) {
// The value has been updated since last checked
/** @type {?} */
let value = '';
for (let j = i + 1; j <= (i + skipCodes); j++) {
/** @type {?} */
const opCode = updateOpCodes[j];
if (typeof opCode == 'string') {
value += opCode;
}
else if (typeof opCode == 'number') {
if (opCode < 0) {
// It's a binding index whose value is negative
value += renderStringify(lView[bindingsStartIndex - opCode]);
}
else {
/** @type {?} */
const nodeIndex = opCode >>> 2 /* SHIFT_REF */;
/** @type {?} */
let tIcuIndex;
/** @type {?} */
let tIcu;
/** @type {?} */
let icuTNode;
switch (opCode & 3 /* MASK_OPCODE */) {
case 1 /* Attr */:
/** @type {?} */
const propName = (/** @type {?} */ (updateOpCodes[++j]));
/** @type {?} */
const sanitizeFn = (/** @type {?} */ (updateOpCodes[++j]));
elementPropertyInternal(tView, getTNode(tView, nodeIndex), lView, propName, value, lView[RENDERER], sanitizeFn, false);
break;
case 0 /* Text */:
textBindingInternal(lView, nodeIndex, value);
break;
case 2 /* IcuSwitch */:
tIcuIndex = (/** @type {?} */ (updateOpCodes[++j]));
tIcu = (/** @type {?} */ (icus))[tIcuIndex];
icuTNode = (/** @type {?} */ (getTNode(tView, nodeIndex)));
// If there is an active case, delete the old nodes
if (icuTNode.activeCaseIndex !== null) {
/** @type {?} */
const removeCodes = tIcu.remove[icuTNode.activeCaseIndex];
for (let k = 0; k < removeCodes.length; k++) {
/** @type {?} */
const removeOpCode = (/** @type {?} */ (removeCodes[k]));
switch (removeOpCode & 7 /* MASK_OPCODE */) {
case 3 /* Remove */:
/** @type {?} */
const nodeIndex = removeOpCode >>> 3 /* SHIFT_REF */;
// Remove DOM element, but do *not* mark TNode as detached, since we are
// just switching ICU cases (while keeping the same TNode), so a DOM element
// representing a new ICU case will be re-created.
removeNode(tView, lView, nodeIndex, /* markAsDetached */ false);
break;
case 6 /* RemoveNestedIcu */:
/** @type {?} */
const nestedIcuNodeIndex = (/** @type {?} */ (removeCodes[k + 1])) >>> 3 /* SHIFT_REF */;
/** @type {?} */
const nestedIcuTNode = (/** @type {?} */ (getTNode(tView, nestedIcuNodeIndex)));
/** @type {?} */
const activeIndex = nestedIcuTNode.activeCaseIndex;
if (activeIndex !== null) {
/** @type {?} */
const nestedIcuTIndex = removeOpCode >>> 3 /* SHIFT_REF */;
/** @type {?} */
const nestedTIcu = (/** @type {?} */ (icus))[nestedIcuTIndex];
addAllToArray(nestedTIcu.remove[activeIndex], removeCodes);
}
break;
}
}
}
// Update the active caseIndex
/** @type {?} */
const caseIndex = getCaseIndex(tIcu, value);
icuTNode.activeCaseIndex = caseIndex !== -1 ? caseIndex : null;
if (caseIndex > -1) {
// Add the nodes for the new case
readCreateOpCodes(-1, tIcu.create[caseIndex], tView, lView);
caseCreated = true;
}
break;
case 3 /* IcuUpdate */:
tIcuIndex = (/** @type {?} */ (updateOpCodes[++j]));
tIcu = (/** @type {?} */ (icus))[tIcuIndex];
icuTNode = (/** @type {?} */ (getTNode(tView, nodeIndex)));
if (icuTNode.activeCaseIndex !== null) {
readUpdateOpCodes(tIcu.update[icuTNode.activeCaseIndex], icus, bindingsStartIndex, changeMask, tView, lView, caseCreated);
}
break;
}
}
}
}
}
i += skipCodes;
}
}
/**
* @param {?} tView
* @param {?} lView
* @param {?} index
* @param {?} markAsDetached
* @return {?}
*/
function removeNode(tView, lView, index, markAsDetached) {
/** @type {?} */
const removedPhTNode = getTNode(tView, index);
/** @type {?} */
const removedPhRNode = getNativeByIndex(index, lView);
if (removedPhRNode) {
nativeRemoveNode(lView[RENDERER], removedPhRNode);
}
/** @type {?} */
const slotValue = (/** @type {?} */ (load(lView, index)));
if (isLContainer(slotValue)) {
/** @type {?} */
const lContainer = (/** @type {?} */ (slotValue));
if (removedPhTNode.type !== 0 /* Container */) {
nativeRemoveNode(lView[RENDERER], lContainer[NATIVE]);
}
}
if (markAsDetached) {
// Define this node as detached to avoid projecting it later
removedPhTNode.flags |= 64 /* isDetached */;
}
ngDevMode && ngDevMode.rendererRemoveNode++;
}
/**
*
* Use this instruction to create a translation block that doesn't contain any placeholder.
* It calls both {\@link i18nStart} and {\@link i18nEnd} in one instruction.
*
* The translation `message` is the value which is locale specific. The translation string may
* contain placeholders which associate inner elements and sub-templates within the translation.
*
* The translation `message` placeholders are:
* - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be
* interpolated into. The placeholder `index` points to the expression binding index. An optional
* `block` that matches the sub-template in which it was declared.
* - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*: Marks the beginning
* and end of DOM element that were embedded in the original translation block. The placeholder
* `index` points to the element index in the template instructions set. An optional `block` that
* matches the sub-template in which it was declared.
* - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be
* split up and translated separately in each angular template function. The `index` points to the
* `template` instruction index. A `block` that matches the sub-template in which it was declared.
*
* \@codeGenApi
* @param {?} index A unique index of the translation in the static block.
* @param {?} message The translation message.
* @param {?=} subTemplateIndex Optional sub-template index in the `message`.
*
* @return {?}
*/
function ɵɵi18n(index, message, subTemplateIndex) {
ɵɵi18nStart(index, message, subTemplateIndex);
ɵɵi18nEnd();
}
/**
* Marks a list of attributes as translatable.
*
* \@codeGenApi
* @param {?} index A unique index in the static block
* @param {?} values
*
* @return {?}
*/
function ɵɵi18nAttributes(index, values) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
ngDevMode && assertDefined(tView, `tView should be defined`);
i18nAttributesFirstPass(lView, tView, index, values);
}
/**
* See `i18nAttributes` above.
* @param {?} lView
* @param {?} tView
* @param {?} index
* @param {?} values
* @return {?}
*/
function i18nAttributesFirstPass(lView, tView, index, values) {
/** @type {?} */
const previousElement = getPreviousOrParentTNode();
/** @type {?} */
const previousElementIndex = previousElement.index - HEADER_OFFSET;
/** @type {?} */
const updateOpCodes = [];
for (let i = 0; i < values.length; i += 2) {
/** @type {?} */
const attrName = values[i];
/** @type {?} */
const message = values[i + 1];
/** @type {?} */
const parts = message.split(ICU_REGEXP);
for (let j = 0; j < parts.length; j++) {
/** @type {?} */
const value = parts[j];
if (j & 1) {
// Odd indexes are ICU expressions
// TODO(ocombe): support ICU expressions in attributes
throw new Error('ICU expressions are not yet supported in attributes');
}
else if (value !== '') {
// Even indexes are text (including bindings)
/** @type {?} */
const hasBinding = !!value.match(BINDING_REGEXP);
if (hasBinding) {
if (tView.firstCreatePass && tView.data[index + HEADER_OFFSET] === null) {
addAllToArray(generateBindingUpdateOpCodes(value, previousElementIndex, attrName), updateOpCodes);
}
}
else {
/** @type {?} */
const tNode = getTNode(tView, previousElementIndex);
// Set attributes for Elements only, for other types (like ElementContainer),
// only set inputs below
if (tNode.type === 3 /* Element */) {
elementAttributeInternal(tNode, lView, attrName, value, null, null);
}
// Check if that attribute is a directive input
/** @type {?} */
const dataValue = tNode.inputs !== null && tNode.inputs[attrName];
if (dataValue) {
setInputsForProperty(tView, lView, dataValue, attrName, value);
if (ngDevMode) {
/** @type {?} */
const element = (/** @type {?} */ (getNativeByIndex(previousElementIndex, lView)));
setNgReflectProperties(lView, element, tNode.type, dataValue, value);
}
}
}
}
}
}
if (tView.firstCreatePass && tView.data[index + HEADER_OFFSET] === null) {
tView.data[index + HEADER_OFFSET] = updateOpCodes;
}
}
/** @type {?} */
let changeMask = 0b0;
/** @type {?} */
let shiftsCounter = 0;
/**
* Stores the values of the bindings during each update cycle in order to determine if we need to
* update the translated nodes.
*
* \@codeGenApi
* @template T
* @param {?} value The binding's value
* @return {?} This function returns itself so that it may be chained
* (e.g. `i18nExp(ctx.name)(ctx.title)`)
*
*/
function ɵɵi18nExp(value) {
/** @type {?} */
const lView = getLView();
if (bindingUpdated(lView, nextBindingIndex(), value)) {
changeMask = changeMask | (1 << shiftsCounter);
}
shiftsCounter++;
return ɵɵi18nExp;
}
/**
* Updates a translation block or an i18n attribute when the bindings have changed.
*
* \@codeGenApi
* @param {?} index Index of either {\@link i18nStart} (translation block) or {\@link i18nAttributes}
* (i18n attribute) on which it should update the content.
*
* @return {?}
*/
function ɵɵi18nApply(index) {
if (shiftsCounter) {
/** @type {?} */
const tView = getTView();
ngDevMode && assertDefined(tView, `tView should be defined`);
/** @type {?} */
const tI18n = tView.data[index + HEADER_OFFSET];
/** @type {?} */
let updateOpCodes;
/** @type {?} */
let icus = null;
if (Array.isArray(tI18n)) {
updateOpCodes = (/** @type {?} */ (tI18n));
}
else {
updateOpCodes = ((/** @type {?} */ (tI18n))).update;
icus = ((/** @type {?} */ (tI18n))).icus;
}
/** @type {?} */
const bindingsStartIndex = getBindingIndex() - shiftsCounter - 1;
/** @type {?} */
const lView = getLView();
readUpdateOpCodes(updateOpCodes, icus, bindingsStartIndex, changeMask, tView, lView);
// Reset changeMask & maskBit to default for the next update cycle
changeMask = 0b0;
shiftsCounter = 0;
}
}
/**
* Returns the index of the current case of an ICU expression depending on the main binding value
*
* @param {?} icuExpression
* @param {?} bindingValue The value of the main binding used by this ICU expression
* @return {?}
*/
function getCaseIndex(icuExpression, bindingValue) {
/** @type {?} */
let index = icuExpression.cases.indexOf(bindingValue);
if (index === -1) {
switch (icuExpression.type) {
case 1 /* plural */: {
/** @type {?} */
const resolvedCase = getPluralCase(bindingValue, getLocaleId());
index = icuExpression.cases.indexOf(resolvedCase);
if (index === -1 && resolvedCase !== 'other') {
index = icuExpression.cases.indexOf('other');
}
break;
}
case 0 /* select */: {
index = icuExpression.cases.indexOf('other');
break;
}
}
}
return index;
}
/**
* Generate the OpCodes for ICU expressions.
*
* @param {?} tIcus
* @param {?} icuExpression
* @param {?} startIndex
* @param {?} expandoStartIndex
* @return {?}
*/
function icuStart(tIcus, icuExpression, startIndex, expandoStartIndex) {
/** @type {?} */
const createCodes = [];
/** @type {?} */
const removeCodes = [];
/** @type {?} */
const updateCodes = [];
/** @type {?} */
const vars = [];
/** @type {?} */
const childIcus = [];
for (let i = 0; i < icuExpression.values.length; i++) {
// Each value is an array of strings & other ICU expressions
/** @type {?} */
const valueArr = icuExpression.values[i];
/** @type {?} */
const nestedIcus = [];
for (let j = 0; j < valueArr.length; j++) {
/** @type {?} */
const value = valueArr[j];
if (typeof value !== 'string') {
// It is an nested ICU expression
/** @type {?} */
const icuIndex = nestedIcus.push((/** @type {?} */ (value))) - 1;
// Replace nested ICU expression by a comment node
valueArr[j] = `<!--�${icuIndex}�-->`;
}
}
/** @type {?} */
const icuCase = parseIcuCase(valueArr.join(''), startIndex, nestedIcus, tIcus, expandoStartIndex);
createCodes.push(icuCase.create);
removeCodes.push(icuCase.remove);
updateCodes.push(icuCase.update);
vars.push(icuCase.vars);
childIcus.push(icuCase.childIcus);
}
/** @type {?} */
const tIcu = {
type: icuExpression.type,
vars,
childIcus,
cases: icuExpression.cases,
create: createCodes,
remove: removeCodes,
update: updateCodes
};
tIcus.push(tIcu);
// Adding the maximum possible of vars needed (based on the cases with the most vars)
i18nVarsCount += Math.max(...vars);
}
/**
* Transforms a string template into an HTML template and a list of instructions used to update
* attributes or nodes that contain bindings.
*
* @param {?} unsafeHtml The string to parse
* @param {?} parentIndex
* @param {?} nestedIcus
* @param {?} tIcus
* @param {?} expandoStartIndex
* @return {?}
*/
function parseIcuCase(unsafeHtml, parentIndex, nestedIcus, tIcus, expandoStartIndex) {
/** @type {?} */
const inertBodyHelper = new InertBodyHelper(getDocument());
/** @type {?} */
const inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
if (!inertBodyElement) {
throw new Error('Unable to generate inert body element');
}
/** @type {?} */
const wrapper = (/** @type {?} */ (getTemplateContent((/** @type {?} */ (inertBodyElement))))) || inertBodyElement;
/** @type {?} */
const opCodes = { vars: 0, childIcus: [], create: [], remove: [], update: [] };
parseNodes(wrapper.firstChild, opCodes, parentIndex, nestedIcus, tIcus, expandoStartIndex);
return opCodes;
}
/** @type {?} */
const NESTED_ICU = /�(\d+)�/;
/**
* Parses a node, its children and its siblings, and generates the mutate & update OpCodes.
*
* @param {?} currentNode The first node to parse
* @param {?} icuCase The data for the ICU expression case that contains those nodes
* @param {?} parentIndex Index of the current node's parent
* @param {?} nestedIcus Data for the nested ICU expressions that this case contains
* @param {?} tIcus Data for all ICU expressions of the current message
* @param {?} expandoStartIndex Expando start index for the current ICU expression
* @return {?}
*/
function parseNodes(currentNode, icuCase, parentIndex, nestedIcus, tIcus, expandoStartIndex) {
if (currentNode) {
/** @type {?} */
const nestedIcusToCreate = [];
while (currentNode) {
/** @type {?} */
const nextNode = currentNode.nextSibling;
/** @type {?} */
const newIndex = expandoStartIndex + ++icuCase.vars;
switch (currentNode.nodeType) {
case Node.ELEMENT_NODE:
/** @type {?} */
const element = (/** @type {?} */ (currentNode));
/** @type {?} */
const tagName = element.tagName.toLowerCase();
if (!VALID_ELEMENTS.hasOwnProperty(tagName)) {
// This isn't a valid element, we won't create an element for it
icuCase.vars--;
}
else {
icuCase.create.push(ELEMENT_MARKER, tagName, newIndex, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
/** @type {?} */
const elAttrs = element.attributes;
for (let i = 0; i < elAttrs.length; i++) {
/** @type {?} */
const attr = (/** @type {?} */ (elAttrs.item(i)));
/** @type {?} */
const lowerAttrName = attr.name.toLowerCase();
/** @type {?} */
const hasBinding = !!attr.value.match(BINDING_REGEXP);
// we assume the input string is safe, unless it's using a binding
if (hasBinding) {
if (VALID_ATTRS.hasOwnProperty(lowerAttrName)) {
if (URI_ATTRS[lowerAttrName]) {
addAllToArray(generateBindingUpdateOpCodes(attr.value, newIndex, attr.name, _sanitizeUrl), icuCase.update);
}
else if (SRCSET_ATTRS[lowerAttrName]) {
addAllToArray(generateBindingUpdateOpCodes(attr.value, newIndex, attr.name, sanitizeSrcset), icuCase.update);
}
else {
addAllToArray(generateBindingUpdateOpCodes(attr.value, newIndex, attr.name), icuCase.update);
}
}
else {
ngDevMode &&
console.warn(`WARNING: ignoring unsafe attribute value ${lowerAttrName} on element ${tagName} (see http://g.co/ng/security#xss)`);
}
}
else {
icuCase.create.push(newIndex << 3 /* SHIFT_REF */ | 4 /* Attr */, attr.name, attr.value);
}
}
// Parse the children of this node (if any)
parseNodes(currentNode.firstChild, icuCase, newIndex, nestedIcus, tIcus, expandoStartIndex);
// Remove the parent node after the children
icuCase.remove.push(newIndex << 3 /* SHIFT_REF */ | 3 /* Remove */);
}
break;
case Node.TEXT_NODE:
/** @type {?} */
const value = currentNode.textContent || '';
/** @type {?} */
const hasBinding = value.match(BINDING_REGEXP);
icuCase.create.push(hasBinding ? '' : value, newIndex, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
icuCase.remove.push(newIndex << 3 /* SHIFT_REF */ | 3 /* Remove */);
if (hasBinding) {
addAllToArray(generateBindingUpdateOpCodes(value, newIndex), icuCase.update);
}
break;
case Node.COMMENT_NODE:
// Check if the comment node is a placeholder for a nested ICU
/** @type {?} */
const match = NESTED_ICU.exec(currentNode.textContent || '');
if (match) {
/** @type {?} */
const nestedIcuIndex = parseInt(match[1], 10);
/** @type {?} */
const newLocal = ngDevMode ? `nested ICU ${nestedIcuIndex}` : '';
// Create the comment node that will anchor the ICU expression
icuCase.create.push(COMMENT_MARKER, newLocal, newIndex, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
/** @type {?} */
const nestedIcu = nestedIcus[nestedIcuIndex];
nestedIcusToCreate.push([nestedIcu, newIndex]);
}
else {
// We do not handle any other type of comment
icuCase.vars--;
}
break;
default:
// We do not handle any other type of element
icuCase.vars--;
}
currentNode = (/** @type {?} */ (nextNode));
}
for (let i = 0; i < nestedIcusToCreate.length; i++) {
/** @type {?} */
const nestedIcu = nestedIcusToCreate[i][0];
/** @type {?} */
const nestedIcuNodeIndex = nestedIcusToCreate[i][1];
icuStart(tIcus, nestedIcu, nestedIcuNodeIndex, expandoStartIndex + icuCase.vars);
// Since this is recursive, the last TIcu that was pushed is the one we want
/** @type {?} */
const nestTIcuIndex = tIcus.length - 1;
icuCase.vars += Math.max(...tIcus[nestTIcuIndex].vars);
icuCase.childIcus.push(nestTIcuIndex);
/** @type {?} */
const mask = getBindingMask(nestedIcu);
icuCase.update.push(toMaskBit(nestedIcu.mainBinding), // mask of the main binding
3, // skip 3 opCodes if not changed
-1 - nestedIcu.mainBinding, nestedIcuNodeIndex << 2 /* SHIFT_REF */ | 2 /* IcuSwitch */, nestTIcuIndex, mask, // mask of all the bindings of this ICU expression
2, // skip 2 opCodes if not changed
nestedIcuNodeIndex << 2 /* SHIFT_REF */ | 3 /* IcuUpdate */, nestTIcuIndex);
icuCase.remove.push(nestTIcuIndex << 3 /* SHIFT_REF */ | 6 /* RemoveNestedIcu */, nestedIcuNodeIndex << 3 /* SHIFT_REF */ | 3 /* Remove */);
}
}
}
/**
* Angular Dart introduced &ngsp; as a placeholder for non-removable space, see:
* https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32
* In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character
* and later on replaced by a space. We are re-implementing the same idea here, since translations
* might contain this special character.
* @type {?}
*/
const NGSP_UNICODE_REGEXP = /\uE500/g;
/**
* @param {?} value
* @return {?}
*/
function replaceNgsp(value) {
return value.replace(NGSP_UNICODE_REGEXP, ' ');
}
/**
* The locale id that the application is currently using (for translations and ICU expressions).
* This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
* but is now defined as a global value.
* @type {?}
*/
let LOCALE_ID = DEFAULT_LOCALE_ID;
/**
* Sets the locale id that will be used for translations and ICU expressions.
* This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
* but is now defined as a global value.
*
* @param {?} localeId
* @return {?}
*/
function setLocaleId(localeId) {
assertDefined(localeId, `Expected localeId to be defined`);
if (typeof localeId === 'string') {
LOCALE_ID = localeId.toLowerCase().replace(/_/g, '-');
}
}
/**
* Gets the locale id that will be used for translations and ICU expressions.
* This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
* but is now defined as a global value.
* @return {?}
*/
function getLocaleId() {
return LOCALE_ID;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/metadata.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @record
*/
function TypeWithMetadata() { }
if (false) {}
/**
* Adds decorator, constructor, and property metadata to a given type via static metadata fields
* on the type.
*
* These metadata fields can later be read with Angular's `ReflectionCapabilities` API.
*
* Calls to `setClassMetadata` can be marked as pure, resulting in the metadata assignments being
* tree-shaken away during production builds.
* @param {?} type
* @param {?} decorators
* @param {?} ctorParameters
* @param {?} propDecorators
* @return {?}
*/
function setClassMetadata(type, decorators, ctorParameters, propDecorators) {
return (/** @type {?} */ (noSideEffects((/**
* @return {?}
*/
() => {
/** @type {?} */
const clazz = (/** @type {?} */ (type));
// We determine whether a class has its own metadata by taking the metadata from the
// parent constructor and checking whether it's the same as the subclass metadata below.
// We can't use `hasOwnProperty` here because it doesn't work correctly in IE10 for
// static fields that are defined by TS. See
// https://github.com/angular/angular/pull/28439#issuecomment-459349218.
/** @type {?} */
const parentPrototype = clazz.prototype ? Object.getPrototypeOf(clazz.prototype) : null;
/** @type {?} */
const parentConstructor = parentPrototype && parentPrototype.constructor;
if (decorators !== null) {
if (clazz.decorators !== undefined &&
(!parentConstructor || parentConstructor.decorators !== clazz.decorators)) {
clazz.decorators.push(...decorators);
}
else {
clazz.decorators = decorators;
}
}
if (ctorParameters !== null) {
// Rather than merging, clobber the existing parameters. If other projects exist which
// use tsickle-style annotations and reflect over them in the same way, this could
// cause issues, but that is vanishingly unlikely.
clazz.ctorParameters = ctorParameters;
}
if (propDecorators !== null) {
// The property decorator objects are merged as it is possible different fields have
// different decorator types. Decorators on individual fields are not merged, as it's
// also incredibly unlikely that a field will be decorated both with an Angular
// decorator and a non-Angular decorator that's also been downleveled.
if (clazz.propDecorators !== undefined &&
(!parentConstructor ||
parentConstructor.propDecorators !== clazz.propDecorators)) {
clazz.propDecorators = Object.assign(Object.assign({}, clazz.propDecorators), propDecorators);
}
else {
clazz.propDecorators = propDecorators;
}
}
}))));
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/ng_module_factory_registration.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Map of module-id to the corresponding NgModule.
* - In pre Ivy we track NgModuleFactory,
* - In post Ivy we track the NgModuleType
* @type {?}
*/
const modules = new Map();
/**
* Registers a loaded module. Should only be called from generated NgModuleFactory code.
* \@publicApi
* @param {?} id
* @param {?} factory
* @return {?}
*/
function registerModuleFactory(id, factory) {
/** @type {?} */
const existing = (/** @type {?} */ (modules.get(id)));
assertSameOrNotExisting(id, existing && existing.moduleType, factory.moduleType);
modules.set(id, factory);
}
/**
* @param {?} id
* @param {?} type
* @param {?} incoming
* @return {?}
*/
function assertSameOrNotExisting(id, type, incoming) {
if (type && type !== incoming) {
throw new Error(`Duplicate module registered for ${id} - ${stringify(type)} vs ${stringify(type.name)}`);
}
}
/**
* @param {?} ngModuleType
* @return {?}
*/
function registerNgModuleType(ngModuleType) {
if (ngModuleType.ɵmod.id !== null) {
/** @type {?} */
const id = ngModuleType.ɵmod.id;
/** @type {?} */
const existing = (/** @type {?} */ (modules.get(id)));
assertSameOrNotExisting(id, existing, ngModuleType);
modules.set(id, ngModuleType);
}
/** @type {?} */
let imports = ngModuleType.ɵmod.imports;
if (imports instanceof Function) {
imports = imports();
}
if (imports) {
imports.forEach((/**
* @param {?} i
* @return {?}
*/
i => registerNgModuleType((/** @type {?} */ (i)))));
}
}
/**
* @return {?}
*/
function clearModulesForTest() {
modules.clear();
}
/**
* @param {?} id
* @return {?}
*/
function getRegisteredNgModuleType(id) {
return modules.get(id) || autoRegisterModuleById[id];
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/ng_module_ref.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @record
* @template T
*/
function NgModuleType() { }
if (false) {}
/**
* @template T
*/
class NgModuleRef$1 extends NgModuleRef {
/**
* @param {?} ngModuleType
* @param {?} _parent
*/
constructor(ngModuleType, _parent) {
super();
this._parent = _parent;
// tslint:disable-next-line:require-internal-with-underscore
this._bootstrapComponents = [];
this.injector = this;
this.destroyCbs = [];
// When bootstrapping a module we have a dependency graph that looks like this:
// ApplicationRef -> ComponentFactoryResolver -> NgModuleRef. The problem is that if the
// module being resolved tries to inject the ComponentFactoryResolver, it'll create a
// circular dependency which will result in a runtime error, because the injector doesn't
// exist yet. We work around the issue by creating the ComponentFactoryResolver ourselves
// and providing it, rather than letting the injector resolve it.
this.componentFactoryResolver = new ComponentFactoryResolver$1(this);
/** @type {?} */
const ngModuleDef = getNgModuleDef(ngModuleType);
ngDevMode &&
assertDefined(ngModuleDef, `NgModule '${stringify(ngModuleType)}' is not a subtype of 'NgModuleType'.`);
/** @type {?} */
const ngLocaleIdDef = getNgLocaleIdDef(ngModuleType);
ngLocaleIdDef && setLocaleId(ngLocaleIdDef);
this._bootstrapComponents = maybeUnwrapFn((/** @type {?} */ (ngModuleDef)).bootstrap);
this._r3Injector = (/** @type {?} */ (createInjectorWithoutInjectorInstances(ngModuleType, _parent, [
{ provide: NgModuleRef, useValue: this }, {
provide: ComponentFactoryResolver,
useValue: this.componentFactoryResolver
}
], stringify(ngModuleType))));
// We need to resolve the injector types separately from the injector creation, because
// the module might be trying to use this ref in its contructor for DI which will cause a
// circular error that will eventually error out, because the injector isn't created yet.
this._r3Injector._resolveInjectorDefTypes();
this.instance = this.get(ngModuleType);
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @param {?=} injectFlags
* @return {?}
*/
get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND, injectFlags = InjectFlags.Default) {
if (token === Injector || token === NgModuleRef || token === INJECTOR) {
return this;
}
return this._r3Injector.get(token, notFoundValue, injectFlags);
}
/**
* @return {?}
*/
destroy() {
ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
/** @type {?} */
const injector = this._r3Injector;
!injector.destroyed && injector.destroy();
(/** @type {?} */ (this.destroyCbs)).forEach((/**
* @param {?} fn
* @return {?}
*/
fn => fn()));
this.destroyCbs = null;
}
/**
* @param {?} callback
* @return {?}
*/
onDestroy(callback) {
ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
(/** @type {?} */ (this.destroyCbs)).push(callback);
}
}
if (false) {}
/**
* @template T
*/
class NgModuleFactory$1 extends NgModuleFactory {
/**
* @param {?} moduleType
*/
constructor(moduleType) {
super();
this.moduleType = moduleType;
/** @type {?} */
const ngModuleDef = getNgModuleDef(moduleType);
if (ngModuleDef !== null) {
// Register the NgModule with Angular's module registry. The location (and hence timing) of
// this call is critical to ensure this works correctly (modules get registered when expected)
// without bloating bundles (modules are registered when otherwise not referenced).
//
// In View Engine, registration occurs in the .ngfactory.js file as a side effect. This has
// several practical consequences:
//
// - If an .ngfactory file is not imported from, the module won't be registered (and can be
// tree shaken).
// - If an .ngfactory file is imported from, the module will be registered even if an instance
// is not actually created (via `create` below).
// - Since an .ngfactory file in View Engine references the .ngfactory files of the NgModule's
// imports,
//
// In Ivy, things are a bit different. .ngfactory files still exist for compatibility, but are
// not a required API to use - there are other ways to obtain an NgModuleFactory for a given
// NgModule. Thus, relying on a side effect in the .ngfactory file is not sufficient. Instead,
// the side effect of registration is added here, in the constructor of NgModuleFactory,
// ensuring no matter how a factory is created, the module is registered correctly.
//
// An alternative would be to include the registration side effect inline following the actual
// NgModule definition. This also has the correct timing, but breaks tree-shaking - modules
// will be registered and retained even if they're otherwise never referenced.
registerNgModuleType((/** @type {?} */ (moduleType)));
}
}
/**
* @param {?} parentInjector
* @return {?}
*/
create(parentInjector) {
return new NgModuleRef$1(this.moduleType, parentInjector);
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/pure_function.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Bindings for pure functions are stored after regular bindings.
*
* |-------decls------|---------vars---------| |----- hostVars (dir1) ------|
* ------------------------------------------------------------------------------------------
* | nodes/refs/pipes | bindings | fn slots | injector | dir1 | host bindings | host slots |
* ------------------------------------------------------------------------------------------
* ^ ^
* TView.bindingStartIndex TView.expandoStartIndex
*
* Pure function instructions are given an offset from the binding root. Adding the offset to the
* binding root gives the first index where the bindings are stored. In component views, the binding
* root is the bindingStartIndex. In host bindings, the binding root is the expandoStartIndex +
* any directive instances + any hostVars in directives evaluated before it.
*
* See VIEW_DATA.md for more information about host binding resolution.
*/
/**
* If the value hasn't been saved, calls the pure function to store and return the
* value. If it has been saved, returns the saved value.
*
* \@codeGenApi
* @template T
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn Function that returns a value
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} value
*
*/
function ɵɵpureFunction0(slotOffset, pureFn, thisArg) {
/** @type {?} */
const bindingIndex = getBindingRoot() + slotOffset;
/** @type {?} */
const lView = getLView();
return lView[bindingIndex] === NO_CHANGE ?
updateBinding(lView, bindingIndex, thisArg ? pureFn.call(thisArg) : pureFn()) :
getBinding(lView, bindingIndex);
}
/**
* If the value of the provided exp has changed, calls the pure function to return
* an updated value. Or if the value has not changed, returns cached value.
*
* \@codeGenApi
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn Function that returns an updated value
* @param {?} exp Updated expression value
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*
*/
function ɵɵpureFunction1(slotOffset, pureFn, exp, thisArg) {
return pureFunction1Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp, thisArg);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* \@codeGenApi
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn
* @param {?} exp1
* @param {?} exp2
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*
*/
function ɵɵpureFunction2(slotOffset, pureFn, exp1, exp2, thisArg) {
return pureFunction2Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, thisArg);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* \@codeGenApi
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn
* @param {?} exp1
* @param {?} exp2
* @param {?} exp3
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*
*/
function ɵɵpureFunction3(slotOffset, pureFn, exp1, exp2, exp3, thisArg) {
return pureFunction3Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, exp3, thisArg);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* \@codeGenApi
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn
* @param {?} exp1
* @param {?} exp2
* @param {?} exp3
* @param {?} exp4
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*
*/
function ɵɵpureFunction4(slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg) {
return pureFunction4Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* \@codeGenApi
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn
* @param {?} exp1
* @param {?} exp2
* @param {?} exp3
* @param {?} exp4
* @param {?} exp5
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*
*/
function ɵɵpureFunction5(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, thisArg) {
/** @type {?} */
const bindingIndex = getBindingRoot() + slotOffset;
/** @type {?} */
const lView = getLView();
/** @type {?} */
const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
return bindingUpdated(lView, bindingIndex + 4, exp5) || different ?
updateBinding(lView, bindingIndex + 5, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5) :
pureFn(exp1, exp2, exp3, exp4, exp5)) :
getBinding(lView, bindingIndex + 5);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* \@codeGenApi
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn
* @param {?} exp1
* @param {?} exp2
* @param {?} exp3
* @param {?} exp4
* @param {?} exp5
* @param {?} exp6
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*
*/
function ɵɵpureFunction6(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, thisArg) {
/** @type {?} */
const bindingIndex = getBindingRoot() + slotOffset;
/** @type {?} */
const lView = getLView();
/** @type {?} */
const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
return bindingUpdated2(lView, bindingIndex + 4, exp5, exp6) || different ?
updateBinding(lView, bindingIndex + 6, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6) :
pureFn(exp1, exp2, exp3, exp4, exp5, exp6)) :
getBinding(lView, bindingIndex + 6);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* \@codeGenApi
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn
* @param {?} exp1
* @param {?} exp2
* @param {?} exp3
* @param {?} exp4
* @param {?} exp5
* @param {?} exp6
* @param {?} exp7
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*
*/
function ɵɵpureFunction7(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, exp7, thisArg) {
/** @type {?} */
const bindingIndex = getBindingRoot() + slotOffset;
/** @type {?} */
const lView = getLView();
/** @type {?} */
let different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
return bindingUpdated3(lView, bindingIndex + 4, exp5, exp6, exp7) || different ?
updateBinding(lView, bindingIndex + 7, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7) :
pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7)) :
getBinding(lView, bindingIndex + 7);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* \@codeGenApi
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn
* @param {?} exp1
* @param {?} exp2
* @param {?} exp3
* @param {?} exp4
* @param {?} exp5
* @param {?} exp6
* @param {?} exp7
* @param {?} exp8
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*
*/
function ɵɵpureFunction8(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8, thisArg) {
/** @type {?} */
const bindingIndex = getBindingRoot() + slotOffset;
/** @type {?} */
const lView = getLView();
/** @type {?} */
const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
return bindingUpdated4(lView, bindingIndex + 4, exp5, exp6, exp7, exp8) || different ?
updateBinding(lView, bindingIndex + 8, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8) :
pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8)) :
getBinding(lView, bindingIndex + 8);
}
/**
* pureFunction instruction that can support any number of bindings.
*
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* \@codeGenApi
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn A pure function that takes binding values and builds an object or array
* containing those values.
* @param {?} exps An array of binding values
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*
*/
function ɵɵpureFunctionV(slotOffset, pureFn, exps, thisArg) {
return pureFunctionVInternal(getLView(), getBindingRoot(), slotOffset, pureFn, exps, thisArg);
}
/**
* Results of a pure function invocation are stored in LView in a dedicated slot that is initialized
* to NO_CHANGE. In rare situations a pure pipe might throw an exception on the very first
* invocation and not produce any valid results. In this case LView would keep holding the NO_CHANGE
* value. The NO_CHANGE is not something that we can use in expressions / bindings thus we convert
* it to `undefined`.
* @param {?} lView
* @param {?} returnValueIndex
* @return {?}
*/
function getPureFunctionReturnValue(lView, returnValueIndex) {
ngDevMode && assertDataInRange(lView, returnValueIndex);
/** @type {?} */
const lastReturnValue = lView[returnValueIndex];
return lastReturnValue === NO_CHANGE ? undefined : lastReturnValue;
}
/**
* If the value of the provided exp has changed, calls the pure function to return
* an updated value. Or if the value has not changed, returns cached value.
*
* @param {?} lView LView in which the function is being executed.
* @param {?} bindingRoot Binding root index.
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn Function that returns an updated value
* @param {?} exp Updated expression value
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*/
function pureFunction1Internal(lView, bindingRoot, slotOffset, pureFn, exp, thisArg) {
/** @type {?} */
const bindingIndex = bindingRoot + slotOffset;
return bindingUpdated(lView, bindingIndex, exp) ?
updateBinding(lView, bindingIndex + 1, thisArg ? pureFn.call(thisArg, exp) : pureFn(exp)) :
getPureFunctionReturnValue(lView, bindingIndex + 1);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param {?} lView LView in which the function is being executed.
* @param {?} bindingRoot Binding root index.
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn
* @param {?} exp1
* @param {?} exp2
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*/
function pureFunction2Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, thisArg) {
/** @type {?} */
const bindingIndex = bindingRoot + slotOffset;
return bindingUpdated2(lView, bindingIndex, exp1, exp2) ?
updateBinding(lView, bindingIndex + 2, thisArg ? pureFn.call(thisArg, exp1, exp2) : pureFn(exp1, exp2)) :
getPureFunctionReturnValue(lView, bindingIndex + 2);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param {?} lView LView in which the function is being executed.
* @param {?} bindingRoot Binding root index.
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn
* @param {?} exp1
* @param {?} exp2
* @param {?} exp3
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*/
function pureFunction3Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, exp3, thisArg) {
/** @type {?} */
const bindingIndex = bindingRoot + slotOffset;
return bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3) ?
updateBinding(lView, bindingIndex + 3, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3) : pureFn(exp1, exp2, exp3)) :
getPureFunctionReturnValue(lView, bindingIndex + 3);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param {?} lView LView in which the function is being executed.
* @param {?} bindingRoot Binding root index.
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn
* @param {?} exp1
* @param {?} exp2
* @param {?} exp3
* @param {?} exp4
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*
*/
function pureFunction4Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg) {
/** @type {?} */
const bindingIndex = bindingRoot + slotOffset;
return bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4) ?
updateBinding(lView, bindingIndex + 4, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4) : pureFn(exp1, exp2, exp3, exp4)) :
getPureFunctionReturnValue(lView, bindingIndex + 4);
}
/**
* pureFunction instruction that can support any number of bindings.
*
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param {?} lView LView in which the function is being executed.
* @param {?} bindingRoot Binding root index.
* @param {?} slotOffset the offset from binding root to the reserved slot
* @param {?} pureFn A pure function that takes binding values and builds an object or array
* containing those values.
* @param {?} exps An array of binding values
* @param {?=} thisArg Optional calling context of pureFn
* @return {?} Updated or cached value
*/
function pureFunctionVInternal(lView, bindingRoot, slotOffset, pureFn, exps, thisArg) {
/** @type {?} */
let bindingIndex = bindingRoot + slotOffset;
/** @type {?} */
let different = false;
for (let i = 0; i < exps.length; i++) {
bindingUpdated(lView, bindingIndex++, exps[i]) && (different = true);
}
return different ? updateBinding(lView, bindingIndex, pureFn.apply(thisArg, exps)) :
getPureFunctionReturnValue(lView, bindingIndex);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/pipe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Create a pipe.
*
* \@codeGenApi
* @param {?} index Pipe index where the pipe will be stored.
* @param {?} pipeName The name of the pipe
* @return {?} T the instance of the pipe.
*
*/
function ɵɵpipe(index, pipeName) {
/** @type {?} */
const tView = getTView();
/** @type {?} */
let pipeDef;
/** @type {?} */
const adjustedIndex = index + HEADER_OFFSET;
if (tView.firstCreatePass) {
pipeDef = getPipeDef$1(pipeName, tView.pipeRegistry);
tView.data[adjustedIndex] = pipeDef;
if (pipeDef.onDestroy) {
(tView.destroyHooks || (tView.destroyHooks = [])).push(adjustedIndex, pipeDef.onDestroy);
}
}
else {
pipeDef = (/** @type {?} */ (tView.data[adjustedIndex]));
}
/** @type {?} */
const pipeFactory = pipeDef.factory || (pipeDef.factory = getFactoryDef(pipeDef.type, true));
/** @type {?} */
const previousInjectImplementation = setInjectImplementation(ɵɵdirectiveInject);
// DI for pipes is supposed to behave like directives when placed on a component
// host node, which means that we have to disable access to `viewProviders`.
/** @type {?} */
const previousIncludeViewProviders = setIncludeViewProviders(false);
/** @type {?} */
const pipeInstance = pipeFactory();
setIncludeViewProviders(previousIncludeViewProviders);
setInjectImplementation(previousInjectImplementation);
store(tView, getLView(), index, pipeInstance);
return pipeInstance;
}
/**
* Searches the pipe registry for a pipe with the given name. If one is found,
* returns the pipe. Otherwise, an error is thrown because the pipe cannot be resolved.
*
* @param {?} name Name of pipe to resolve
* @param {?} registry Full list of available pipes
* @return {?} Matching PipeDef
*/
function getPipeDef$1(name, registry) {
if (registry) {
for (let i = registry.length - 1; i >= 0; i--) {
/** @type {?} */
const pipeDef = registry[i];
if (name === pipeDef.name) {
return pipeDef;
}
}
}
throw new Error(`The pipe '${name}' could not be found!`);
}
/**
* Invokes a pipe with 1 arguments.
*
* This instruction acts as a guard to {\@link PipeTransform#transform} invoking
* the pipe only when an input to the pipe changes.
*
* \@codeGenApi
* @param {?} index Pipe index where the pipe was stored on creation.
* @param {?} slotOffset the offset in the reserved slot space
* @param {?} v1 1st argument to {\@link PipeTransform#transform}.
*
* @return {?}
*/
function ɵɵpipeBind1(index, slotOffset, v1) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const pipeInstance = load(lView, index);
return unwrapValue$1(lView, isPure(lView, index) ?
pureFunction1Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, pipeInstance) :
pipeInstance.transform(v1));
}
/**
* Invokes a pipe with 2 arguments.
*
* This instruction acts as a guard to {\@link PipeTransform#transform} invoking
* the pipe only when an input to the pipe changes.
*
* \@codeGenApi
* @param {?} index Pipe index where the pipe was stored on creation.
* @param {?} slotOffset the offset in the reserved slot space
* @param {?} v1 1st argument to {\@link PipeTransform#transform}.
* @param {?} v2 2nd argument to {\@link PipeTransform#transform}.
*
* @return {?}
*/
function ɵɵpipeBind2(index, slotOffset, v1, v2) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const pipeInstance = load(lView, index);
return unwrapValue$1(lView, isPure(lView, index) ?
pureFunction2Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, pipeInstance) :
pipeInstance.transform(v1, v2));
}
/**
* Invokes a pipe with 3 arguments.
*
* This instruction acts as a guard to {\@link PipeTransform#transform} invoking
* the pipe only when an input to the pipe changes.
*
* \@codeGenApi
* @param {?} index Pipe index where the pipe was stored on creation.
* @param {?} slotOffset the offset in the reserved slot space
* @param {?} v1 1st argument to {\@link PipeTransform#transform}.
* @param {?} v2 2nd argument to {\@link PipeTransform#transform}.
* @param {?} v3 4rd argument to {\@link PipeTransform#transform}.
*
* @return {?}
*/
function ɵɵpipeBind3(index, slotOffset, v1, v2, v3) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const pipeInstance = load(lView, index);
return unwrapValue$1(lView, isPure(lView, index) ? pureFunction3Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, v3, pipeInstance) :
pipeInstance.transform(v1, v2, v3));
}
/**
* Invokes a pipe with 4 arguments.
*
* This instruction acts as a guard to {\@link PipeTransform#transform} invoking
* the pipe only when an input to the pipe changes.
*
* \@codeGenApi
* @param {?} index Pipe index where the pipe was stored on creation.
* @param {?} slotOffset the offset in the reserved slot space
* @param {?} v1 1st argument to {\@link PipeTransform#transform}.
* @param {?} v2 2nd argument to {\@link PipeTransform#transform}.
* @param {?} v3 3rd argument to {\@link PipeTransform#transform}.
* @param {?} v4 4th argument to {\@link PipeTransform#transform}.
*
* @return {?}
*/
function ɵɵpipeBind4(index, slotOffset, v1, v2, v3, v4) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const pipeInstance = load(lView, index);
return unwrapValue$1(lView, isPure(lView, index) ? pureFunction4Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, v3, v4, pipeInstance) :
pipeInstance.transform(v1, v2, v3, v4));
}
/**
* Invokes a pipe with variable number of arguments.
*
* This instruction acts as a guard to {\@link PipeTransform#transform} invoking
* the pipe only when an input to the pipe changes.
*
* \@codeGenApi
* @param {?} index Pipe index where the pipe was stored on creation.
* @param {?} slotOffset the offset in the reserved slot space
* @param {?} values Array of arguments to pass to {\@link PipeTransform#transform} method.
*
* @return {?}
*/
function ɵɵpipeBindV(index, slotOffset, values) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const pipeInstance = load(lView, index);
return unwrapValue$1(lView, isPure(lView, index) ?
pureFunctionVInternal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, values, pipeInstance) :
pipeInstance.transform.apply(pipeInstance, values));
}
/**
* @param {?} lView
* @param {?} index
* @return {?}
*/
function isPure(lView, index) {
return ((/** @type {?} */ (lView[TVIEW].data[index + HEADER_OFFSET]))).pure;
}
/**
* Unwrap the output of a pipe transformation.
* In order to trick change detection into considering that the new value is always different from
* the old one, the old value is overwritten by NO_CHANGE.
*
* @param {?} lView
* @param {?} newValue the pipe transformation output.
* @return {?}
*/
function unwrapValue$1(lView, newValue) {
if (WrappedValue.isWrapped(newValue)) {
newValue = WrappedValue.unwrap(newValue);
// The NO_CHANGE value needs to be written at the index where the impacted binding value is
// stored
/** @type {?} */
const bindingToInvalidateIdx = getBindingIndex();
lView[bindingToInvalidateIdx] = NO_CHANGE;
}
return newValue;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/event_emitter.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Use in components with the `\@Output` directive to emit custom events
* synchronously or asynchronously, and register handlers for those events
* by subscribing to an instance.
*
* \@usageNotes
*
* Extends
* [RxJS `Subject`](https://rxjs.dev/api/index/class/Subject)
* for Angular by adding the `emit()` method.
*
* In the following example, a component defines two output properties
* that create event emitters. When the title is clicked, the emitter
* emits an open or close event to toggle the current visibility state.
*
* ```html
* \@Component({
* selector: 'zippy',
* template: `
* <div class="zippy">
* <div (click)="toggle()">Toggle</div>
* <div [hidden]="!visible">
* <ng-content></ng-content>
* </div>
* </div>`})
* export class Zippy {
* visible: boolean = true;
* \@Output() open: EventEmitter<any> = new EventEmitter();
* \@Output() close: EventEmitter<any> = new EventEmitter();
*
* toggle() {
* this.visible = !this.visible;
* if (this.visible) {
* this.open.emit(null);
* } else {
* this.close.emit(null);
* }
* }
* }
* ```
*
* Access the event object with the `$event` argument passed to the output event
* handler:
*
* ```html
* <zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy>
* ```
*
* @see [Observables in Angular](guide/observables-in-angular)
* \@publicApi
* @template T
*/
class EventEmitter extends rxjs__WEBPACK_IMPORTED_MODULE_0__["Subject"] {
// tslint:disable-line
/**
* Creates an instance of this class that can
* deliver events synchronously or asynchronously.
*
* @param {?=} isAsync When true, deliver events asynchronously.
*
*/
constructor(isAsync = false) {
super();
this.__isAsync = isAsync;
}
/**
* Emits an event containing a given value.
* @param {?=} value The value to emit.
* @return {?}
*/
emit(value) {
super.next(value);
}
/**
* Registers handlers for events emitted by this instance.
* @param {?=} generatorOrNext When supplied, a custom handler for emitted events.
* @param {?=} error When supplied, a custom handler for an error notification
* from this emitter.
* @param {?=} complete When supplied, a custom handler for a completion
* notification from this emitter.
* @return {?}
*/
subscribe(generatorOrNext, error, complete) {
/** @type {?} */
let schedulerFn;
/** @type {?} */
let errorFn = (/**
* @param {?} err
* @return {?}
*/
(err) => null);
/** @type {?} */
let completeFn = (/**
* @return {?}
*/
() => null);
if (generatorOrNext && typeof generatorOrNext === 'object') {
schedulerFn = this.__isAsync ? (/**
* @param {?} value
* @return {?}
*/
(value) => {
setTimeout((/**
* @return {?}
*/
() => generatorOrNext.next(value)));
}) : (/**
* @param {?} value
* @return {?}
*/
(value) => {
generatorOrNext.next(value);
});
if (generatorOrNext.error) {
errorFn = this.__isAsync ? (/**
* @param {?} err
* @return {?}
*/
(err) => {
setTimeout((/**
* @return {?}
*/
() => generatorOrNext.error(err)));
}) : (/**
* @param {?} err
* @return {?}
*/
(err) => {
generatorOrNext.error(err);
});
}
if (generatorOrNext.complete) {
completeFn = this.__isAsync ? (/**
* @return {?}
*/
() => {
setTimeout((/**
* @return {?}
*/
() => generatorOrNext.complete()));
}) : (/**
* @return {?}
*/
() => {
generatorOrNext.complete();
});
}
}
else {
schedulerFn = this.__isAsync ? (/**
* @param {?} value
* @return {?}
*/
(value) => {
setTimeout((/**
* @return {?}
*/
() => generatorOrNext(value)));
}) : (/**
* @param {?} value
* @return {?}
*/
(value) => {
generatorOrNext(value);
});
if (error) {
errorFn = this.__isAsync ? (/**
* @param {?} err
* @return {?}
*/
(err) => {
setTimeout((/**
* @return {?}
*/
() => error(err)));
}) : (/**
* @param {?} err
* @return {?}
*/
(err) => {
error(err);
});
}
if (complete) {
completeFn = this.__isAsync ? (/**
* @return {?}
*/
() => {
setTimeout((/**
* @return {?}
*/
() => complete()));
}) : (/**
* @return {?}
*/
() => {
complete();
});
}
}
/** @type {?} */
const sink = super.subscribe(schedulerFn, errorFn, completeFn);
if (generatorOrNext instanceof rxjs__WEBPACK_IMPORTED_MODULE_0__["Subscription"]) {
generatorOrNext.add(sink);
}
return sink;
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/query_list.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @template T
* @this {?}
* @return {?}
*/
function symbolIterator() {
return ((/** @type {?} */ (((/** @type {?} */ ((/** @type {?} */ (this)))))._results)))[getSymbolIterator()]();
}
/**
* An unmodifiable list of items that Angular keeps up to date when the state
* of the application changes.
*
* The type of object that {\@link ViewChildren}, {\@link ContentChildren}, and {\@link QueryList}
* provide.
*
* Implements an iterable interface, therefore it can be used in both ES6
* javascript `for (var i of items)` loops as well as in Angular templates with
* `*ngFor="let i of myList"`.
*
* Changes can be observed by subscribing to the changes `Observable`.
*
* NOTE: In the future this class will implement an `Observable` interface.
*
* \@usageNotes
* ### Example
* ```typescript
* \@Component({...})
* class Container {
* \@ViewChildren(Item) items:QueryList<Item>;
* }
* ```
*
* \@publicApi
* @template T
*/
class QueryList {
constructor() {
this.dirty = true;
this._results = [];
this.changes = new EventEmitter();
this.length = 0;
// This function should be declared on the prototype, but doing so there will cause the class
// declaration to have side-effects and become not tree-shakable. For this reason we do it in
// the constructor.
// [getSymbolIterator()](): Iterator<T> { ... }
/** @type {?} */
const symbol = getSymbolIterator();
/** @type {?} */
const proto = (/** @type {?} */ (QueryList.prototype));
if (!proto[symbol])
proto[symbol] = symbolIterator;
}
/**
* See
* [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
* @template U
* @param {?} fn
* @return {?}
*/
map(fn) {
return this._results.map(fn);
}
/**
* See
* [Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
* @param {?} fn
* @return {?}
*/
filter(fn) {
return this._results.filter(fn);
}
/**
* See
* [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
* @param {?} fn
* @return {?}
*/
find(fn) {
return this._results.find(fn);
}
/**
* See
* [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
* @template U
* @param {?} fn
* @param {?} init
* @return {?}
*/
reduce(fn, init) {
return this._results.reduce(fn, init);
}
/**
* See
* [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
* @param {?} fn
* @return {?}
*/
forEach(fn) {
this._results.forEach(fn);
}
/**
* See
* [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
* @param {?} fn
* @return {?}
*/
some(fn) {
return this._results.some(fn);
}
/**
* Returns a copy of the internal results list as an Array.
* @return {?}
*/
toArray() {
return this._results.slice();
}
/**
* @return {?}
*/
toString() {
return this._results.toString();
}
/**
* Updates the stored data of the query list, and resets the `dirty` flag to `false`, so that
* on change detection, it will not notify of changes to the queries, unless a new change
* occurs.
*
* @param {?} resultsTree The query results to store
* @return {?}
*/
reset(resultsTree) {
this._results = flatten(resultsTree);
((/** @type {?} */ (this))).dirty = false;
((/** @type {?} */ (this))).length = this._results.length;
((/** @type {?} */ (this))).last = this._results[this.length - 1];
((/** @type {?} */ (this))).first = this._results[0];
}
/**
* Triggers a change event by emitting on the `changes` {\@link EventEmitter}.
* @return {?}
*/
notifyOnChanges() {
((/** @type {?} */ (this.changes))).emit(this);
}
/**
* internal
* @return {?}
*/
setDirty() {
((/** @type {?} */ (this))).dirty = true;
}
/**
* internal
* @return {?}
*/
destroy() {
((/** @type {?} */ (this.changes))).complete();
((/** @type {?} */ (this.changes))).unsubscribe();
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/definition.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @enum {number} */
const RenderFlags = {
/* Whether to run the creation block (e.g. create elements and directives) */
Create: 1,
/* Whether to run the update block (e.g. refresh bindings) */
Update: 2,
};
/**
* A subclass of `Type` which has a static `ɵcmp`:`ComponentDef` field making it
* consumable for rendering.
* @record
* @template T
*/
function ComponentType() { }
if (false) {}
/**
* A subclass of `Type` which has a static `ɵdir`:`DirectiveDef` field making it
* consumable for rendering.
* @record
* @template T
*/
function DirectiveType() { }
if (false) {}
/**
* A subclass of `Type` which has a static `ɵpipe`:`PipeDef` field making it
* consumable for rendering.
* @record
* @template T
*/
function PipeType() { }
if (false) {}
/**
* Runtime link information for Directives.
*
* This is an internal data structure used by the render to link
* directives into templates.
*
* NOTE: Always use `defineDirective` function to create this object,
* never create the object directly since the shape of this object
* can change between versions.
*
* @param Selector type metadata specifying the selector of the directive or component
*
* See: {\@link defineDirective}
* @record
* @template T
*/
function DirectiveDef() { }
if (false) {}
/**
* Runtime link information for Components.
*
* This is an internal data structure used by the render to link
* components into templates.
*
* NOTE: Always use `defineComponent` function to create this object,
* never create the object directly since the shape of this object
* can change between versions.
*
* See: {\@link defineComponent}
* @record
* @template T
*/
function ComponentDef() { }
if (false) {}
/**
* Runtime link information for Pipes.
*
* This is an internal data structure used by the renderer to link
* pipes into templates.
*
* NOTE: Always use `definePipe` function to create this object,
* never create the object directly since the shape of this object
* can change between versions.
*
* See: {\@link definePipe}
* @record
* @template T
*/
function PipeDef() { }
if (false) {}
/**
* @record
*/
function DirectiveDefFeature() { }
if (false) {}
/**
* @record
*/
function ComponentDefFeature() { }
if (false) {}
// Note: This hack is necessary so we don't erroneously get a circular dependency
// failure based on types.
/** @type {?} */
const unusedValueExportToPlacateAjd$7 = 1;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/interfaces/query.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* An object representing query metadata extracted from query annotations.
* @record
*/
function TQueryMetadata() { }
if (false) {}
/**
* TQuery objects represent all the query-related data that remain the same from one view instance
* to another and can be determined on the very first template pass. Most notably TQuery holds all
* the matches for a given view.
* @record
*/
function TQuery() { }
if (false) {}
/**
* TQueries represent a collection of individual TQuery objects tracked in a given view. Most of the
* methods on this interface are simple proxy methods to the corresponding functionality on TQuery.
* @record
*/
function TQueries() { }
if (false) {}
/**
* An interface that represents query-related information specific to a view instance. Most notably
* it contains:
* - materialized query matches;
* - a pointer to a QueryList where materialized query results should be reported.
* @record
* @template T
*/
function LQuery() { }
if (false) {}
/**
* lQueries represent a collection of individual LQuery objects tracked in a given view.
* @record
*/
function LQueries() { }
if (false) {}
// Note: This hack is necessary so we don't erroneously get a circular dependency
// failure based on types.
/** @type {?} */
const unusedValueExportToPlacateAjd$8 = 1;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/query.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const unusedValueToPlacateAjd$2 = unusedValueExportToPlacateAjd$7 + unusedValueExportToPlacateAjd$3 + unusedValueExportToPlacateAjd$4 + unusedValueExportToPlacateAjd$8;
/**
* @template T
*/
class LQuery_ {
/**
* @param {?} queryList
*/
constructor(queryList) {
this.queryList = queryList;
this.matches = null;
}
/**
* @return {?}
*/
clone() {
return new LQuery_(this.queryList);
}
/**
* @return {?}
*/
setDirty() {
this.queryList.setDirty();
}
}
if (false) {}
class LQueries_ {
/**
* @param {?=} queries
*/
constructor(queries = []) {
this.queries = queries;
}
/**
* @param {?} tView
* @return {?}
*/
createEmbeddedView(tView) {
/** @type {?} */
const tQueries = tView.queries;
if (tQueries !== null) {
/** @type {?} */
const noOfInheritedQueries = tView.contentQueries !== null ? tView.contentQueries[0] : tQueries.length;
/** @type {?} */
const viewLQueries = [];
// An embedded view has queries propagated from a declaration view at the beginning of the
// TQueries collection and up until a first content query declared in the embedded view. Only
// propagated LQueries are created at this point (LQuery corresponding to declared content
// queries will be instantiated from the content query instructions for each directive).
for (let i = 0; i < noOfInheritedQueries; i++) {
/** @type {?} */
const tQuery = tQueries.getByIndex(i);
/** @type {?} */
const parentLQuery = this.queries[tQuery.indexInDeclarationView];
viewLQueries.push(parentLQuery.clone());
}
return new LQueries_(viewLQueries);
}
return null;
}
/**
* @param {?} tView
* @return {?}
*/
insertView(tView) {
this.dirtyQueriesWithMatches(tView);
}
/**
* @param {?} tView
* @return {?}
*/
detachView(tView) {
this.dirtyQueriesWithMatches(tView);
}
/**
* @private
* @param {?} tView
* @return {?}
*/
dirtyQueriesWithMatches(tView) {
for (let i = 0; i < this.queries.length; i++) {
if (getTQuery(tView, i).matches !== null) {
this.queries[i].setDirty();
}
}
}
}
if (false) {}
class TQueryMetadata_ {
/**
* @param {?} predicate
* @param {?} descendants
* @param {?} isStatic
* @param {?=} read
*/
constructor(predicate, descendants, isStatic, read = null) {
this.predicate = predicate;
this.descendants = descendants;
this.isStatic = isStatic;
this.read = read;
}
}
if (false) {}
class TQueries_ {
/**
* @param {?=} queries
*/
constructor(queries = []) {
this.queries = queries;
}
/**
* @param {?} tView
* @param {?} tNode
* @return {?}
*/
elementStart(tView, tNode) {
ngDevMode &&
assertFirstCreatePass(tView, 'Queries should collect results on the first template pass only');
for (let i = 0; i < this.queries.length; i++) {
this.queries[i].elementStart(tView, tNode);
}
}
/**
* @param {?} tNode
* @return {?}
*/
elementEnd(tNode) {
for (let i = 0; i < this.queries.length; i++) {
this.queries[i].elementEnd(tNode);
}
}
/**
* @param {?} tNode
* @return {?}
*/
embeddedTView(tNode) {
/** @type {?} */
let queriesForTemplateRef = null;
for (let i = 0; i < this.length; i++) {
/** @type {?} */
const childQueryIndex = queriesForTemplateRef !== null ? queriesForTemplateRef.length : 0;
/** @type {?} */
const tqueryClone = this.getByIndex(i).embeddedTView(tNode, childQueryIndex);
if (tqueryClone) {
tqueryClone.indexInDeclarationView = i;
if (queriesForTemplateRef !== null) {
queriesForTemplateRef.push(tqueryClone);
}
else {
queriesForTemplateRef = [tqueryClone];
}
}
}
return queriesForTemplateRef !== null ? new TQueries_(queriesForTemplateRef) : null;
}
/**
* @param {?} tView
* @param {?} tNode
* @return {?}
*/
template(tView, tNode) {
ngDevMode &&
assertFirstCreatePass(tView, 'Queries should collect results on the first template pass only');
for (let i = 0; i < this.queries.length; i++) {
this.queries[i].template(tView, tNode);
}
}
/**
* @param {?} index
* @return {?}
*/
getByIndex(index) {
ngDevMode && assertDataInRange(this.queries, index);
return this.queries[index];
}
/**
* @return {?}
*/
get length() {
return this.queries.length;
}
/**
* @param {?} tquery
* @return {?}
*/
track(tquery) {
this.queries.push(tquery);
}
}
if (false) {}
class TQuery_ {
/**
* @param {?} metadata
* @param {?=} nodeIndex
*/
constructor(metadata, nodeIndex = -1) {
this.metadata = metadata;
this.matches = null;
this.indexInDeclarationView = -1;
this.crossesNgTemplate = false;
/**
* A flag indicating if a given query still applies to nodes it is crossing. We use this flag
* (alongside with _declarationNodeIndex) to know when to stop applying content queries to
* elements in a template.
*/
this._appliesToNextNode = true;
this._declarationNodeIndex = nodeIndex;
}
/**
* @param {?} tView
* @param {?} tNode
* @return {?}
*/
elementStart(tView, tNode) {
if (this.isApplyingToNode(tNode)) {
this.matchTNode(tView, tNode);
}
}
/**
* @param {?} tNode
* @return {?}
*/
elementEnd(tNode) {
if (this._declarationNodeIndex === tNode.index) {
this._appliesToNextNode = false;
}
}
/**
* @param {?} tView
* @param {?} tNode
* @return {?}
*/
template(tView, tNode) {
this.elementStart(tView, tNode);
}
/**
* @param {?} tNode
* @param {?} childQueryIndex
* @return {?}
*/
embeddedTView(tNode, childQueryIndex) {
if (this.isApplyingToNode(tNode)) {
this.crossesNgTemplate = true;
// A marker indicating a `<ng-template>` element (a placeholder for query results from
// embedded views created based on this `<ng-template>`).
this.addMatch(-tNode.index, childQueryIndex);
return new TQuery_(this.metadata);
}
return null;
}
/**
* @private
* @param {?} tNode
* @return {?}
*/
isApplyingToNode(tNode) {
if (this._appliesToNextNode && this.metadata.descendants === false) {
/** @type {?} */
const declarationNodeIdx = this._declarationNodeIndex;
/** @type {?} */
let parent = tNode.parent;
// Determine if a given TNode is a "direct" child of a node on which a content query was
// declared (only direct children of query's host node can match with the descendants: false
// option). There are 3 main use-case / conditions to consider here:
// - <needs-target><i #target></i></needs-target>: here <i #target> parent node is a query
// host node;
// - <needs-target><ng-template [ngIf]="true"><i #target></i></ng-template></needs-target>:
// here <i #target> parent node is null;
// - <needs-target><ng-container><i #target></i></ng-container></needs-target>: here we need
// to go past `<ng-container>` to determine <i #target> parent node (but we shouldn't traverse
// up past the query's host node!).
while (parent !== null && parent.type === 4 /* ElementContainer */ &&
parent.index !== declarationNodeIdx) {
parent = parent.parent;
}
return declarationNodeIdx === (parent !== null ? parent.index : -1);
}
return this._appliesToNextNode;
}
/**
* @private
* @param {?} tView
* @param {?} tNode
* @return {?}
*/
matchTNode(tView, tNode) {
if (Array.isArray(this.metadata.predicate)) {
/** @type {?} */
const localNames = this.metadata.predicate;
for (let i = 0; i < localNames.length; i++) {
this.matchTNodeWithReadOption(tView, tNode, getIdxOfMatchingSelector(tNode, localNames[i]));
}
}
else {
/** @type {?} */
const typePredicate = (/** @type {?} */ (this.metadata.predicate));
if (typePredicate === TemplateRef) {
if (tNode.type === 0 /* Container */) {
this.matchTNodeWithReadOption(tView, tNode, -1);
}
}
else {
this.matchTNodeWithReadOption(tView, tNode, locateDirectiveOrProvider(tNode, tView, typePredicate, false, false));
}
}
}
/**
* @private
* @param {?} tView
* @param {?} tNode
* @param {?} nodeMatchIdx
* @return {?}
*/
matchTNodeWithReadOption(tView, tNode, nodeMatchIdx) {
if (nodeMatchIdx !== null) {
/** @type {?} */
const read = this.metadata.read;
if (read !== null) {
if (read === ElementRef || read === ViewContainerRef ||
read === TemplateRef && tNode.type === 0 /* Container */) {
this.addMatch(tNode.index, -2);
}
else {
/** @type {?} */
const directiveOrProviderIdx = locateDirectiveOrProvider(tNode, tView, read, false, false);
if (directiveOrProviderIdx !== null) {
this.addMatch(tNode.index, directiveOrProviderIdx);
}
}
}
else {
this.addMatch(tNode.index, nodeMatchIdx);
}
}
}
/**
* @private
* @param {?} tNodeIdx
* @param {?} matchIdx
* @return {?}
*/
addMatch(tNodeIdx, matchIdx) {
if (this.matches === null) {
this.matches = [tNodeIdx, matchIdx];
}
else {
this.matches.push(tNodeIdx, matchIdx);
}
}
}
if (false) {}
/**
* Iterates over local names for a given node and returns directive index
* (or -1 if a local name points to an element).
*
* @param {?} tNode static data of a node to check
* @param {?} selector selector to match
* @return {?} directive index, -1 or null if a selector didn't match any of the local names
*/
function getIdxOfMatchingSelector(tNode, selector) {
/** @type {?} */
const localNames = tNode.localNames;
if (localNames !== null) {
for (let i = 0; i < localNames.length; i += 2) {
if (localNames[i] === selector) {
return (/** @type {?} */ (localNames[i + 1]));
}
}
}
return null;
}
/**
* @param {?} tNode
* @param {?} currentView
* @return {?}
*/
function createResultByTNodeType(tNode, currentView) {
if (tNode.type === 3 /* Element */ || tNode.type === 4 /* ElementContainer */) {
return createElementRef(ElementRef, tNode, currentView);
}
else if (tNode.type === 0 /* Container */) {
return createTemplateRef(TemplateRef, ElementRef, tNode, currentView);
}
return null;
}
/**
* @param {?} lView
* @param {?} tNode
* @param {?} matchingIdx
* @param {?} read
* @return {?}
*/
function createResultForNode(lView, tNode, matchingIdx, read) {
if (matchingIdx === -1) {
// if read token and / or strategy is not specified, detect it using appropriate tNode type
return createResultByTNodeType(tNode, lView);
}
else if (matchingIdx === -2) {
// read a special token from a node injector
return createSpecialToken(lView, tNode, read);
}
else {
// read a token
return getNodeInjectable(lView, lView[TVIEW], matchingIdx, (/** @type {?} */ (tNode)));
}
}
/**
* @param {?} lView
* @param {?} tNode
* @param {?} read
* @return {?}
*/
function createSpecialToken(lView, tNode, read) {
if (read === ElementRef) {
return createElementRef(ElementRef, tNode, lView);
}
else if (read === TemplateRef) {
return createTemplateRef(TemplateRef, ElementRef, tNode, lView);
}
else if (read === ViewContainerRef) {
ngDevMode &&
assertNodeOfPossibleTypes(tNode, 3 /* Element */, 0 /* Container */, 4 /* ElementContainer */);
return createContainerRef(ViewContainerRef, ElementRef, (/** @type {?} */ (tNode)), lView);
}
else {
ngDevMode &&
throwError(`Special token to read should be one of ElementRef, TemplateRef or ViewContainerRef but got ${stringify(read)}.`);
}
}
/**
* A helper function that creates query results for a given view. This function is meant to do the
* processing once and only once for a given view instance (a set of results for a given view
* doesn't change).
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} tQuery
* @param {?} queryIndex
* @return {?}
*/
function materializeViewResults(tView, lView, tQuery, queryIndex) {
/** @type {?} */
const lQuery = (/** @type {?} */ ((/** @type {?} */ (lView[QUERIES])).queries))[queryIndex];
if (lQuery.matches === null) {
/** @type {?} */
const tViewData = tView.data;
/** @type {?} */
const tQueryMatches = (/** @type {?} */ (tQuery.matches));
/** @type {?} */
const result = [];
for (let i = 0; i < tQueryMatches.length; i += 2) {
/** @type {?} */
const matchedNodeIdx = tQueryMatches[i];
if (matchedNodeIdx < 0) {
// we at the <ng-template> marker which might have results in views created based on this
// <ng-template> - those results will be in separate views though, so here we just leave
// null as a placeholder
result.push(null);
}
else {
ngDevMode && assertDataInRange(tViewData, matchedNodeIdx);
/** @type {?} */
const tNode = (/** @type {?} */ (tViewData[matchedNodeIdx]));
result.push(createResultForNode(lView, tNode, tQueryMatches[i + 1], tQuery.metadata.read));
}
}
lQuery.matches = result;
}
return lQuery.matches;
}
/**
* A helper function that collects (already materialized) query results from a tree of views,
* starting with a provided LView.
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} queryIndex
* @param {?} result
* @return {?}
*/
function collectQueryResults(tView, lView, queryIndex, result) {
/** @type {?} */
const tQuery = (/** @type {?} */ (tView.queries)).getByIndex(queryIndex);
/** @type {?} */
const tQueryMatches = tQuery.matches;
if (tQueryMatches !== null) {
/** @type {?} */
const lViewResults = materializeViewResults(tView, lView, tQuery, queryIndex);
for (let i = 0; i < tQueryMatches.length; i += 2) {
/** @type {?} */
const tNodeIdx = tQueryMatches[i];
if (tNodeIdx > 0) {
result.push((/** @type {?} */ (lViewResults[i / 2])));
}
else {
/** @type {?} */
const childQueryIndex = tQueryMatches[i + 1];
/** @type {?} */
const declarationLContainer = (/** @type {?} */ (lView[-tNodeIdx]));
ngDevMode && assertLContainer(declarationLContainer);
// collect matches for views inserted in this container
for (let i = CONTAINER_HEADER_OFFSET; i < declarationLContainer.length; i++) {
/** @type {?} */
const embeddedLView = declarationLContainer[i];
if (embeddedLView[DECLARATION_LCONTAINER] === embeddedLView[PARENT]) {
collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
}
}
// collect matches for views created from this declaration container and inserted into
// different containers
if (declarationLContainer[MOVED_VIEWS] !== null) {
/** @type {?} */
const embeddedLViews = (/** @type {?} */ (declarationLContainer[MOVED_VIEWS]));
for (let i = 0; i < embeddedLViews.length; i++) {
/** @type {?} */
const embeddedLView = embeddedLViews[i];
collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
}
}
}
}
}
return result;
}
/**
* Refreshes a query by combining matches from all active views and removing matches from deleted
* views.
*
* \@codeGenApi
* @param {?} queryList
* @return {?} `true` if a query got dirty during change detection or if this is a static query
* resolving in creation mode, `false` otherwise.
*
*/
function ɵɵqueryRefresh(queryList) {
/** @type {?} */
const lView = getLView();
/** @type {?} */
const tView = getTView();
/** @type {?} */
const queryIndex = getCurrentQueryIndex();
setCurrentQueryIndex(queryIndex + 1);
/** @type {?} */
const tQuery = getTQuery(tView, queryIndex);
if (queryList.dirty && (isCreationMode(lView) === tQuery.metadata.isStatic)) {
if (tQuery.matches === null) {
queryList.reset([]);
}
else {
/** @type {?} */
const result = tQuery.crossesNgTemplate ?
collectQueryResults(tView, lView, queryIndex, []) :
materializeViewResults(tView, lView, tQuery, queryIndex);
queryList.reset(result);
queryList.notifyOnChanges();
}
return true;
}
return false;
}
/**
* Creates new QueryList for a static view query.
*
* \@codeGenApi
* @template T
* @param {?} predicate The type for which the query will search
* @param {?} descend Whether or not to descend into children
* @param {?=} read What to save in the query
*
* @return {?}
*/
function ɵɵstaticViewQuery(predicate, descend, read) {
viewQueryInternal(getTView(), getLView(), predicate, descend, read, true);
}
/**
* Creates new QueryList, stores the reference in LView and returns QueryList.
*
* \@codeGenApi
* @template T
* @param {?} predicate The type for which the query will search
* @param {?} descend Whether or not to descend into children
* @param {?=} read What to save in the query
*
* @return {?}
*/
function ɵɵviewQuery(predicate, descend, read) {
viewQueryInternal(getTView(), getLView(), predicate, descend, read, false);
}
/**
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} predicate
* @param {?} descend
* @param {?} read
* @param {?} isStatic
* @return {?}
*/
function viewQueryInternal(tView, lView, predicate, descend, read, isStatic) {
if (tView.firstCreatePass) {
createTQuery(tView, new TQueryMetadata_(predicate, descend, isStatic, read), -1);
if (isStatic) {
tView.staticViewQueries = true;
}
}
createLQuery(tView, lView);
}
/**
* Registers a QueryList, associated with a content query, for later refresh (part of a view
* refresh).
*
* \@codeGenApi
* @template T
* @param {?} directiveIndex Current directive index
* @param {?} predicate The type for which the query will search
* @param {?} descend Whether or not to descend into children
* @param {?=} read What to save in the query
* @return {?} QueryList<T>
*
*/
function ɵɵcontentQuery(directiveIndex, predicate, descend, read) {
contentQueryInternal(getTView(), getLView(), predicate, descend, read, false, getPreviousOrParentTNode(), directiveIndex);
}
/**
* Registers a QueryList, associated with a static content query, for later refresh
* (part of a view refresh).
*
* \@codeGenApi
* @template T
* @param {?} directiveIndex Current directive index
* @param {?} predicate The type for which the query will search
* @param {?} descend Whether or not to descend into children
* @param {?=} read What to save in the query
* @return {?} QueryList<T>
*
*/
function ɵɵstaticContentQuery(directiveIndex, predicate, descend, read) {
contentQueryInternal(getTView(), getLView(), predicate, descend, read, true, getPreviousOrParentTNode(), directiveIndex);
}
/**
* @template T
* @param {?} tView
* @param {?} lView
* @param {?} predicate
* @param {?} descend
* @param {?} read
* @param {?} isStatic
* @param {?} tNode
* @param {?} directiveIndex
* @return {?}
*/
function contentQueryInternal(tView, lView, predicate, descend, read, isStatic, tNode, directiveIndex) {
if (tView.firstCreatePass) {
createTQuery(tView, new TQueryMetadata_(predicate, descend, isStatic, read), tNode.index);
saveContentQueryAndDirectiveIndex(tView, directiveIndex);
if (isStatic) {
tView.staticContentQueries = true;
}
}
createLQuery(tView, lView);
}
/**
* Loads a QueryList corresponding to the current view or content query.
*
* \@codeGenApi
* @template T
* @return {?}
*/
function ɵɵloadQuery() {
return loadQueryInternal(getLView(), getCurrentQueryIndex());
}
/**
* @template T
* @param {?} lView
* @param {?} queryIndex
* @return {?}
*/
function loadQueryInternal(lView, queryIndex) {
ngDevMode &&
assertDefined(lView[QUERIES], 'LQueries should be defined when trying to load a query');
ngDevMode && assertDataInRange((/** @type {?} */ (lView[QUERIES])).queries, queryIndex);
return (/** @type {?} */ (lView[QUERIES])).queries[queryIndex].queryList;
}
/**
* @template T
* @param {?} tView
* @param {?} lView
* @return {?}
*/
function createLQuery(tView, lView) {
/** @type {?} */
const queryList = new QueryList();
storeCleanupWithContext(tView, lView, queryList, queryList.destroy);
if (lView[QUERIES] === null)
lView[QUERIES] = new LQueries_();
(/** @type {?} */ (lView[QUERIES])).queries.push(new LQuery_(queryList));
}
/**
* @param {?} tView
* @param {?} metadata
* @param {?} nodeIndex
* @return {?}
*/
function createTQuery(tView, metadata, nodeIndex) {
if (tView.queries === null)
tView.queries = new TQueries_();
tView.queries.track(new TQuery_(metadata, nodeIndex));
}
/**
* @param {?} tView
* @param {?} directiveIndex
* @return {?}
*/
function saveContentQueryAndDirectiveIndex(tView, directiveIndex) {
/** @type {?} */
const tViewContentQueries = tView.contentQueries || (tView.contentQueries = []);
/** @type {?} */
const lastSavedDirectiveIndex = tView.contentQueries.length ? tViewContentQueries[tViewContentQueries.length - 1] : -1;
if (directiveIndex !== lastSavedDirectiveIndex) {
tViewContentQueries.push((/** @type {?} */ (tView.queries)).length - 1, directiveIndex);
}
}
/**
* @param {?} tView
* @param {?} index
* @return {?}
*/
function getTQuery(tView, index) {
ngDevMode && assertDefined(tView.queries, 'TQueries must be defined to retrieve a TQuery');
return (/** @type {?} */ (tView.queries)).getByIndex(index);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/view_engine_compatibility_prebound.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Retrieves `TemplateRef` instance from `Injector` when a local reference is placed on the
* `<ng-template>` element.
*
* \@codeGenApi
* @param {?} tNode
* @param {?} currentView
* @return {?}
*/
function ɵɵtemplateRefExtractor(tNode, currentView) {
return createTemplateRef(TemplateRef, ElementRef, tNode, currentView);
}
/**
* Returns the appropriate `ChangeDetectorRef` for a pipe.
*
* \@codeGenApi
* @param {?=} flags
* @return {?}
*/
function ɵɵinjectPipeChangeDetectorRef(flags = InjectFlags.Default) {
/** @type {?} */
const value = injectChangeDetectorRef(true);
if (value == null && !(flags & InjectFlags.Optional)) {
throw new Error(`No provider for ChangeDetectorRef!`);
}
else {
return value;
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/jit/environment.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
const ɵ0$d = /**
* @return {?}
*/
() => ({
'ɵɵattribute': ɵɵattribute,
'ɵɵattributeInterpolate1': ɵɵattributeInterpolate1,
'ɵɵattributeInterpolate2': ɵɵattributeInterpolate2,
'ɵɵattributeInterpolate3': ɵɵattributeInterpolate3,
'ɵɵattributeInterpolate4': ɵɵattributeInterpolate4,
'ɵɵattributeInterpolate5': ɵɵattributeInterpolate5,
'ɵɵattributeInterpolate6': ɵɵattributeInterpolate6,
'ɵɵattributeInterpolate7': ɵɵattributeInterpolate7,
'ɵɵattributeInterpolate8': ɵɵattributeInterpolate8,
'ɵɵattributeInterpolateV': ɵɵattributeInterpolateV,
'ɵɵdefineComponent': ɵɵdefineComponent,
'ɵɵdefineDirective': ɵɵdefineDirective,
'ɵɵdefineInjectable': ɵɵdefineInjectable,
'ɵɵdefineInjector': ɵɵdefineInjector,
'ɵɵdefineNgModule': ɵɵdefineNgModule,
'ɵɵdefinePipe': ɵɵdefinePipe,
'ɵɵdirectiveInject': ɵɵdirectiveInject,
'ɵɵgetFactoryOf': ɵɵgetFactoryOf,
'ɵɵgetInheritedFactory': ɵɵgetInheritedFactory,
'ɵɵinject': ɵɵinject,
'ɵɵinjectAttribute': ɵɵinjectAttribute,
'ɵɵinvalidFactory': ɵɵinvalidFactory,
'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
'ɵɵinjectPipeChangeDetectorRef': ɵɵinjectPipeChangeDetectorRef,
'ɵɵtemplateRefExtractor': ɵɵtemplateRefExtractor,
'ɵɵNgOnChangesFeature': ɵɵNgOnChangesFeature,
'ɵɵProvidersFeature': ɵɵProvidersFeature,
'ɵɵCopyDefinitionFeature': ɵɵCopyDefinitionFeature,
'ɵɵInheritDefinitionFeature': ɵɵInheritDefinitionFeature,
'ɵɵnextContext': ɵɵnextContext,
'ɵɵnamespaceHTML': ɵɵnamespaceHTML,
'ɵɵnamespaceMathML': ɵɵnamespaceMathML,
'ɵɵnamespaceSVG': ɵɵnamespaceSVG,
'ɵɵenableBindings': ɵɵenableBindings,
'ɵɵdisableBindings': ɵɵdisableBindings,
'ɵɵelementStart': ɵɵelementStart,
'ɵɵelementEnd': ɵɵelementEnd,
'ɵɵelement': ɵɵelement,
'ɵɵelementContainerStart': ɵɵelementContainerStart,
'ɵɵelementContainerEnd': ɵɵelementContainerEnd,
'ɵɵelementContainer': ɵɵelementContainer,
'ɵɵpureFunction0': ɵɵpureFunction0,
'ɵɵpureFunction1': ɵɵpureFunction1,
'ɵɵpureFunction2': ɵɵpureFunction2,
'ɵɵpureFunction3': ɵɵpureFunction3,
'ɵɵpureFunction4': ɵɵpureFunction4,
'ɵɵpureFunction5': ɵɵpureFunction5,
'ɵɵpureFunction6': ɵɵpureFunction6,
'ɵɵpureFunction7': ɵɵpureFunction7,
'ɵɵpureFunction8': ɵɵpureFunction8,
'ɵɵpureFunctionV': ɵɵpureFunctionV,
'ɵɵgetCurrentView': ɵɵgetCurrentView,
'ɵɵrestoreView': ɵɵrestoreView,
'ɵɵlistener': ɵɵlistener,
'ɵɵprojection': ɵɵprojection,
'ɵɵupdateSyntheticHostBinding': ɵɵupdateSyntheticHostBinding,
'ɵɵcomponentHostSyntheticListener': ɵɵcomponentHostSyntheticListener,
'ɵɵpipeBind1': ɵɵpipeBind1,
'ɵɵpipeBind2': ɵɵpipeBind2,
'ɵɵpipeBind3': ɵɵpipeBind3,
'ɵɵpipeBind4': ɵɵpipeBind4,
'ɵɵpipeBindV': ɵɵpipeBindV,
'ɵɵprojectionDef': ɵɵprojectionDef,
'ɵɵhostProperty': ɵɵhostProperty,
'ɵɵproperty': ɵɵproperty,
'ɵɵpropertyInterpolate': ɵɵpropertyInterpolate,
'ɵɵpropertyInterpolate1': ɵɵpropertyInterpolate1,
'ɵɵpropertyInterpolate2': ɵɵpropertyInterpolate2,
'ɵɵpropertyInterpolate3': ɵɵpropertyInterpolate3,
'ɵɵpropertyInterpolate4': ɵɵpropertyInterpolate4,
'ɵɵpropertyInterpolate5': ɵɵpropertyInterpolate5,
'ɵɵpropertyInterpolate6': ɵɵpropertyInterpolate6,
'ɵɵpropertyInterpolate7': ɵɵpropertyInterpolate7,
'ɵɵpropertyInterpolate8': ɵɵpropertyInterpolate8,
'ɵɵpropertyInterpolateV': ɵɵpropertyInterpolateV,
'ɵɵpipe': ɵɵpipe,
'ɵɵqueryRefresh': ɵɵqueryRefresh,
'ɵɵviewQuery': ɵɵviewQuery,
'ɵɵstaticViewQuery': ɵɵstaticViewQuery,
'ɵɵstaticContentQuery': ɵɵstaticContentQuery,
'ɵɵloadQuery': ɵɵloadQuery,
'ɵɵcontentQuery': ɵɵcontentQuery,
'ɵɵreference': ɵɵreference,
'ɵɵclassMap': ɵɵclassMap,
'ɵɵclassMapInterpolate1': ɵɵclassMapInterpolate1,
'ɵɵclassMapInterpolate2': ɵɵclassMapInterpolate2,
'ɵɵclassMapInterpolate3': ɵɵclassMapInterpolate3,
'ɵɵclassMapInterpolate4': ɵɵclassMapInterpolate4,
'ɵɵclassMapInterpolate5': ɵɵclassMapInterpolate5,
'ɵɵclassMapInterpolate6': ɵɵclassMapInterpolate6,
'ɵɵclassMapInterpolate7': ɵɵclassMapInterpolate7,
'ɵɵclassMapInterpolate8': ɵɵclassMapInterpolate8,
'ɵɵclassMapInterpolateV': ɵɵclassMapInterpolateV,
'ɵɵstyleMap': ɵɵstyleMap,
'ɵɵstyleMapInterpolate1': ɵɵstyleMapInterpolate1,
'ɵɵstyleMapInterpolate2': ɵɵstyleMapInterpolate2,
'ɵɵstyleMapInterpolate3': ɵɵstyleMapInterpolate3,
'ɵɵstyleMapInterpolate4': ɵɵstyleMapInterpolate4,
'ɵɵstyleMapInterpolate5': ɵɵstyleMapInterpolate5,
'ɵɵstyleMapInterpolate6': ɵɵstyleMapInterpolate6,
'ɵɵstyleMapInterpolate7': ɵɵstyleMapInterpolate7,
'ɵɵstyleMapInterpolate8': ɵɵstyleMapInterpolate8,
'ɵɵstyleMapInterpolateV': ɵɵstyleMapInterpolateV,
'ɵɵstyleProp': ɵɵstyleProp,
'ɵɵstylePropInterpolate1': ɵɵstylePropInterpolate1,
'ɵɵstylePropInterpolate2': ɵɵstylePropInterpolate2,
'ɵɵstylePropInterpolate3': ɵɵstylePropInterpolate3,
'ɵɵstylePropInterpolate4': ɵɵstylePropInterpolate4,
'ɵɵstylePropInterpolate5': ɵɵstylePropInterpolate5,
'ɵɵstylePropInterpolate6': ɵɵstylePropInterpolate6,
'ɵɵstylePropInterpolate7': ɵɵstylePropInterpolate7,
'ɵɵstylePropInterpolate8': ɵɵstylePropInterpolate8,
'ɵɵstylePropInterpolateV': ɵɵstylePropInterpolateV,
'ɵɵstyleSanitizer': ɵɵstyleSanitizer,
'ɵɵclassProp': ɵɵclassProp,
'ɵɵselect': ɵɵselect,
'ɵɵadvance': ɵɵadvance,
'ɵɵtemplate': ɵɵtemplate,
'ɵɵtext': ɵɵtext,
'ɵɵtextInterpolate': ɵɵtextInterpolate,
'ɵɵtextInterpolate1': ɵɵtextInterpolate1,
'ɵɵtextInterpolate2': ɵɵtextInterpolate2,
'ɵɵtextInterpolate3': ɵɵtextInterpolate3,
'ɵɵtextInterpolate4': ɵɵtextInterpolate4,
'ɵɵtextInterpolate5': ɵɵtextInterpolate5,
'ɵɵtextInterpolate6': ɵɵtextInterpolate6,
'ɵɵtextInterpolate7': ɵɵtextInterpolate7,
'ɵɵtextInterpolate8': ɵɵtextInterpolate8,
'ɵɵtextInterpolateV': ɵɵtextInterpolateV,
'ɵɵi18n': ɵɵi18n,
'ɵɵi18nAttributes': ɵɵi18nAttributes,
'ɵɵi18nExp': ɵɵi18nExp,
'ɵɵi18nStart': ɵɵi18nStart,
'ɵɵi18nEnd': ɵɵi18nEnd,
'ɵɵi18nApply': ɵɵi18nApply,
'ɵɵi18nPostprocess': ɵɵi18nPostprocess,
'ɵɵresolveWindow': ɵɵresolveWindow,
'ɵɵresolveDocument': ɵɵresolveDocument,
'ɵɵresolveBody': ɵɵresolveBody,
'ɵɵsetComponentScope': ɵɵsetComponentScope,
'ɵɵsetNgModuleScope': ɵɵsetNgModuleScope,
'ɵɵsanitizeHtml': ɵɵsanitizeHtml,
'ɵɵsanitizeStyle': ɵɵsanitizeStyle,
'ɵɵdefaultStyleSanitizer': ɵɵdefaultStyleSanitizer,
'ɵɵsanitizeResourceUrl': ɵɵsanitizeResourceUrl,
'ɵɵsanitizeScript': ɵɵsanitizeScript,
'ɵɵsanitizeUrl': ɵɵsanitizeUrl,
'ɵɵsanitizeUrlOrResourceUrl': ɵɵsanitizeUrlOrResourceUrl,
});
/**
* A mapping of the \@angular/core API surface used in generated expressions to the actual symbols.
*
* This should be kept up to date with the public exports of \@angular/core.
* @type {?}
*/
const angularCoreEnv = ((ɵ0$d))();
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/jit/jit_options.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @record
*/
function JitCompilerOptions() { }
if (false) {}
/** @type {?} */
let jitOptions = null;
/**
* @param {?} options
* @return {?}
*/
function setJitOptions(options) {
if (jitOptions !== null) {
if (options.defaultEncapsulation !== jitOptions.defaultEncapsulation) {
ngDevMode &&
console.error('Provided value for `defaultEncapsulation` can not be changed once it has been set.');
return;
}
if (options.preserveWhitespaces !== jitOptions.preserveWhitespaces) {
ngDevMode &&
console.error('Provided value for `preserveWhitespaces` can not be changed once it has been set.');
return;
}
}
jitOptions = options;
}
/**
* @return {?}
*/
function getJitOptions() {
return jitOptions;
}
/**
* @return {?}
*/
function resetJitOptions() {
jitOptions = null;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/jit/module.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const EMPTY_ARRAY$5 = [];
/**
* @record
*/
function ModuleQueueItem() { }
if (false) {}
/** @type {?} */
const moduleQueue = [];
/**
* Enqueues moduleDef to be checked later to see if scope can be set on its
* component declarations.
* @param {?} moduleType
* @param {?} ngModule
* @return {?}
*/
function enqueueModuleForDelayedScoping(moduleType, ngModule) {
moduleQueue.push({ moduleType, ngModule });
}
/** @type {?} */
let flushingModuleQueue = false;
/**
* Loops over queued module definitions, if a given module definition has all of its
* declarations resolved, it dequeues that module definition and sets the scope on
* its declarations.
* @return {?}
*/
function flushModuleScopingQueueAsMuchAsPossible() {
if (!flushingModuleQueue) {
flushingModuleQueue = true;
try {
for (let i = moduleQueue.length - 1; i >= 0; i--) {
const { moduleType, ngModule } = moduleQueue[i];
if (ngModule.declarations && ngModule.declarations.every(isResolvedDeclaration)) {
// dequeue
moduleQueue.splice(i, 1);
setScopeOnDeclaredComponents(moduleType, ngModule);
}
}
}
finally {
flushingModuleQueue = false;
}
}
}
/**
* Returns truthy if a declaration has resolved. If the declaration happens to be
* an array of declarations, it will recurse to check each declaration in that array
* (which may also be arrays).
* @param {?} declaration
* @return {?}
*/
function isResolvedDeclaration(declaration) {
if (Array.isArray(declaration)) {
return declaration.every(isResolvedDeclaration);
}
return !!resolveForwardRef(declaration);
}
/**
* Compiles a module in JIT mode.
*
* This function automatically gets called when a class has a `\@NgModule` decorator.
* @param {?} moduleType
* @param {?=} ngModule
* @return {?}
*/
function compileNgModule(moduleType, ngModule = {}) {
compileNgModuleDefs((/** @type {?} */ (moduleType)), ngModule);
// Because we don't know if all declarations have resolved yet at the moment the
// NgModule decorator is executing, we're enqueueing the setting of module scope
// on its declarations to be run at a later time when all declarations for the module,
// including forward refs, have resolved.
enqueueModuleForDelayedScoping(moduleType, ngModule);
}
/**
* Compiles and adds the `ɵmod` and `ɵinj` properties to the module class.
*
* It's possible to compile a module via this API which will allow duplicate declarations in its
* root.
* @param {?} moduleType
* @param {?} ngModule
* @param {?=} allowDuplicateDeclarationsInRoot
* @return {?}
*/
function compileNgModuleDefs(moduleType, ngModule, allowDuplicateDeclarationsInRoot = false) {
ngDevMode && assertDefined(moduleType, 'Required value moduleType');
ngDevMode && assertDefined(ngModule, 'Required value ngModule');
/** @type {?} */
const declarations = flatten(ngModule.declarations || EMPTY_ARRAY$5);
/** @type {?} */
let ngModuleDef = null;
Object.defineProperty(moduleType, NG_MOD_DEF, {
configurable: true,
get: (/**
* @return {?}
*/
() => {
if (ngModuleDef === null) {
if (ngDevMode && ngModule.imports && ngModule.imports.indexOf(moduleType) > -1) {
// We need to assert this immediately, because allowing it to continue will cause it to
// go into an infinite loop before we've reached the point where we throw all the errors.
throw new Error(`'${stringifyForError(moduleType)}' module can't import itself`);
}
ngModuleDef = getCompilerFacade().compileNgModule(angularCoreEnv, `ng:///${moduleType.name}/ɵmod.js`, {
type: moduleType,
bootstrap: flatten(ngModule.bootstrap || EMPTY_ARRAY$5).map(resolveForwardRef),
declarations: declarations.map(resolveForwardRef),
imports: flatten(ngModule.imports || EMPTY_ARRAY$5)
.map(resolveForwardRef)
.map(expandModuleWithProviders),
exports: flatten(ngModule.exports || EMPTY_ARRAY$5)
.map(resolveForwardRef)
.map(expandModuleWithProviders),
schemas: ngModule.schemas ? flatten(ngModule.schemas) : null,
id: ngModule.id || null,
});
// Set `schemas` on ngModuleDef to an empty array in JIT mode to indicate that runtime
// should verify that there are no unknown elements in a template. In AOT mode, that check
// happens at compile time and `schemas` information is not present on Component and Module
// defs after compilation (so the check doesn't happen the second time at runtime).
if (!ngModuleDef.schemas) {
ngModuleDef.schemas = [];
}
}
return ngModuleDef;
})
});
/** @type {?} */
let ngInjectorDef = null;
Object.defineProperty(moduleType, NG_INJ_DEF, {
get: (/**
* @return {?}
*/
() => {
if (ngInjectorDef === null) {
ngDevMode &&
verifySemanticsOfNgModuleDef((/** @type {?} */ ((/** @type {?} */ (moduleType)))), allowDuplicateDeclarationsInRoot);
/** @type {?} */
const meta = {
name: moduleType.name,
type: moduleType,
deps: reflectDependencies(moduleType),
providers: ngModule.providers || EMPTY_ARRAY$5,
imports: [
(ngModule.imports || EMPTY_ARRAY$5).map(resolveForwardRef),
(ngModule.exports || EMPTY_ARRAY$5).map(resolveForwardRef),
],
};
ngInjectorDef = getCompilerFacade().compileInjector(angularCoreEnv, `ng:///${moduleType.name}/ɵinj.js`, meta);
}
return ngInjectorDef;
}),
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
}
/**
* @param {?} moduleType
* @param {?} allowDuplicateDeclarationsInRoot
* @param {?=} importingModule
* @return {?}
*/
function verifySemanticsOfNgModuleDef(moduleType, allowDuplicateDeclarationsInRoot, importingModule) {
if (verifiedNgModule.get(moduleType))
return;
verifiedNgModule.set(moduleType, true);
moduleType = resolveForwardRef(moduleType);
/** @type {?} */
let ngModuleDef;
if (importingModule) {
ngModuleDef = (/** @type {?} */ (getNgModuleDef(moduleType)));
if (!ngModuleDef) {
throw new Error(`Unexpected value '${moduleType.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
}
}
else {
ngModuleDef = getNgModuleDef(moduleType, true);
}
/** @type {?} */
const errors = [];
/** @type {?} */
const declarations = maybeUnwrapFn(ngModuleDef.declarations);
/** @type {?} */
const imports = maybeUnwrapFn(ngModuleDef.imports);
flatten(imports).map(unwrapModuleWithProvidersImports).forEach((/**
* @param {?} mod
* @return {?}
*/
mod => {
verifySemanticsOfNgModuleImport(mod, moduleType);
verifySemanticsOfNgModuleDef(mod, false, moduleType);
}));
/** @type {?} */
const exports = maybeUnwrapFn(ngModuleDef.exports);
declarations.forEach(verifyDeclarationsHaveDefinitions);
declarations.forEach(verifyDirectivesHaveSelector);
/** @type {?} */
const combinedDeclarations = [
...declarations.map(resolveForwardRef),
...flatten(imports.map(computeCombinedExports)).map(resolveForwardRef),
];
exports.forEach(verifyExportsAreDeclaredOrReExported);
declarations.forEach((/**
* @param {?} decl
* @return {?}
*/
decl => verifyDeclarationIsUnique(decl, allowDuplicateDeclarationsInRoot)));
declarations.forEach(verifyComponentEntryComponentsIsPartOfNgModule);
/** @type {?} */
const ngModule = getAnnotation(moduleType, 'NgModule');
if (ngModule) {
ngModule.imports &&
flatten(ngModule.imports).map(unwrapModuleWithProvidersImports).forEach((/**
* @param {?} mod
* @return {?}
*/
mod => {
verifySemanticsOfNgModuleImport(mod, moduleType);
verifySemanticsOfNgModuleDef(mod, false, moduleType);
}));
ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyCorrectBootstrapType);
ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyComponentIsPartOfNgModule);
ngModule.entryComponents &&
deepForEach(ngModule.entryComponents, verifyComponentIsPartOfNgModule);
}
// Throw Error if any errors were detected.
if (errors.length) {
throw new Error(errors.join('\n'));
}
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @param {?} type
* @return {?}
*/
function verifyDeclarationsHaveDefinitions(type) {
type = resolveForwardRef(type);
/** @type {?} */
const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef(type);
if (!def) {
errors.push(`Unexpected value '${stringifyForError(type)}' declared by the module '${stringifyForError(moduleType)}'. Please add a @Pipe/@Directive/@Component annotation.`);
}
}
/**
* @param {?} type
* @return {?}
*/
function verifyDirectivesHaveSelector(type) {
type = resolveForwardRef(type);
/** @type {?} */
const def = getDirectiveDef(type);
if (!getComponentDef(type) && def && def.selectors.length == 0) {
errors.push(`Directive ${stringifyForError(type)} has no selector, please add it!`);
}
}
/**
* @param {?} type
* @return {?}
*/
function verifyExportsAreDeclaredOrReExported(type) {
type = resolveForwardRef(type);
/** @type {?} */
const kind = getComponentDef(type) && 'component' || getDirectiveDef(type) && 'directive' ||
getPipeDef(type) && 'pipe';
if (kind) {
// only checked if we are declared as Component, Directive, or Pipe
// Modules don't need to be declared or imported.
if (combinedDeclarations.lastIndexOf(type) === -1) {
// We are exporting something which we don't explicitly declare or import.
errors.push(`Can't export ${kind} ${stringifyForError(type)} from ${stringifyForError(moduleType)} as it was neither declared nor imported!`);
}
}
}
/**
* @param {?} type
* @param {?} suppressErrors
* @return {?}
*/
function verifyDeclarationIsUnique(type, suppressErrors) {
type = resolveForwardRef(type);
/** @type {?} */
const existingModule = ownerNgModule.get(type);
if (existingModule && existingModule !== moduleType) {
if (!suppressErrors) {
/** @type {?} */
const modules = [existingModule, moduleType].map(stringifyForError).sort();
errors.push(`Type ${stringifyForError(type)} is part of the declarations of 2 modules: ${modules[0]} and ${modules[1]}! ` +
`Please consider moving ${stringifyForError(type)} to a higher module that imports ${modules[0]} and ${modules[1]}. ` +
`You can also create a new NgModule that exports and includes ${stringifyForError(type)} then import that NgModule in ${modules[0]} and ${modules[1]}.`);
}
}
else {
// Mark type as having owner.
ownerNgModule.set(type, moduleType);
}
}
/**
* @param {?} type
* @return {?}
*/
function verifyComponentIsPartOfNgModule(type) {
type = resolveForwardRef(type);
/** @type {?} */
const existingModule = ownerNgModule.get(type);
if (!existingModule) {
errors.push(`Component ${stringifyForError(type)} is not part of any NgModule or the module has not been imported into your module.`);
}
}
/**
* @param {?} type
* @return {?}
*/
function verifyCorrectBootstrapType(type) {
type = resolveForwardRef(type);
if (!getComponentDef(type)) {
errors.push(`${stringifyForError(type)} cannot be used as an entry component.`);
}
}
/**
* @param {?} type
* @return {?}
*/
function verifyComponentEntryComponentsIsPartOfNgModule(type) {
type = resolveForwardRef(type);
if (getComponentDef(type)) {
// We know we are component
/** @type {?} */
const component = getAnnotation(type, 'Component');
if (component && component.entryComponents) {
deepForEach(component.entryComponents, verifyComponentIsPartOfNgModule);
}
}
}
/**
* @param {?} type
* @param {?} importingModule
* @return {?}
*/
function verifySemanticsOfNgModuleImport(type, importingModule) {
type = resolveForwardRef(type);
if (getComponentDef(type) || getDirectiveDef(type)) {
throw new Error(`Unexpected directive '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
}
if (getPipeDef(type)) {
throw new Error(`Unexpected pipe '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
}
}
}
/**
* @param {?} typeOrWithProviders
* @return {?}
*/
function unwrapModuleWithProvidersImports(typeOrWithProviders) {
typeOrWithProviders = resolveForwardRef(typeOrWithProviders);
return ((/** @type {?} */ (typeOrWithProviders))).ngModule || typeOrWithProviders;
}
/**
* @template T
* @param {?} type
* @param {?} name
* @return {?}
*/
function getAnnotation(type, name) {
/** @type {?} */
let annotation = null;
collect(type.__annotations__);
collect(type.decorators);
return annotation;
/**
* @param {?} annotations
* @return {?}
*/
function collect(annotations) {
if (annotations) {
annotations.forEach(readAnnotation);
}
}
/**
* @param {?} decorator
* @return {?}
*/
function readAnnotation(decorator) {
if (!annotation) {
/** @type {?} */
const proto = Object.getPrototypeOf(decorator);
if (proto.ngMetadataName == name) {
annotation = (/** @type {?} */ (decorator));
}
else if (decorator.type) {
/** @type {?} */
const proto = Object.getPrototypeOf(decorator.type);
if (proto.ngMetadataName == name) {
annotation = decorator.args[0];
}
}
}
}
}
/**
* Keep track of compiled components. This is needed because in tests we often want to compile the
* same component with more than one NgModule. This would cause an error unless we reset which
* NgModule the component belongs to. We keep the list of compiled components here so that the
* TestBed can reset it later.
* @type {?}
*/
let ownerNgModule = new Map();
/** @type {?} */
let verifiedNgModule = new Map();
/**
* @return {?}
*/
function resetCompiledComponents() {
ownerNgModule = new Map();
verifiedNgModule = new Map();
moduleQueue.length = 0;
}
/**
* Computes the combined declarations of explicit declarations, as well as declarations inherited by
* traversing the exports of imported modules.
* @param {?} type
* @return {?}
*/
function computeCombinedExports(type) {
type = resolveForwardRef(type);
/** @type {?} */
const ngModuleDef = getNgModuleDef(type, true);
return [...flatten(maybeUnwrapFn(ngModuleDef.exports).map((/**
* @param {?} type
* @return {?}
*/
(type) => {
/** @type {?} */
const ngModuleDef = getNgModuleDef(type);
if (ngModuleDef) {
verifySemanticsOfNgModuleDef((/** @type {?} */ ((/** @type {?} */ (type)))), false);
return computeCombinedExports(type);
}
else {
return type;
}
})))];
}
/**
* Some declared components may be compiled asynchronously, and thus may not have their
* ɵcmp set yet. If this is the case, then a reference to the module is written into
* the `ngSelectorScope` property of the declared type.
* @param {?} moduleType
* @param {?} ngModule
* @return {?}
*/
function setScopeOnDeclaredComponents(moduleType, ngModule) {
/** @type {?} */
const declarations = flatten(ngModule.declarations || EMPTY_ARRAY$5);
/** @type {?} */
const transitiveScopes = transitiveScopesFor(moduleType);
declarations.forEach((/**
* @param {?} declaration
* @return {?}
*/
declaration => {
if (declaration.hasOwnProperty(NG_COMP_DEF)) {
// A `ɵcmp` field exists - go ahead and patch the component directly.
/** @type {?} */
const component = (/** @type {?} */ (declaration));
/** @type {?} */
const componentDef = (/** @type {?} */ (getComponentDef(component)));
patchComponentDefWithScope(componentDef, transitiveScopes);
}
else if (!declaration.hasOwnProperty(NG_DIR_DEF) && !declaration.hasOwnProperty(NG_PIPE_DEF)) {
// Set `ngSelectorScope` for future reference when the component compilation finishes.
((/** @type {?} */ (declaration))).ngSelectorScope = moduleType;
}
}));
}
/**
* Patch the definition of a component with directives and pipes from the compilation scope of
* a given module.
* @template C
* @param {?} componentDef
* @param {?} transitiveScopes
* @return {?}
*/
function patchComponentDefWithScope(componentDef, transitiveScopes) {
componentDef.directiveDefs = (/**
* @return {?}
*/
() => Array.from(transitiveScopes.compilation.directives)
.map((/**
* @param {?} dir
* @return {?}
*/
dir => dir.hasOwnProperty(NG_COMP_DEF) ? (/** @type {?} */ (getComponentDef(dir))) : (/** @type {?} */ (getDirectiveDef(dir)))))
.filter((/**
* @param {?} def
* @return {?}
*/
def => !!def)));
componentDef.pipeDefs = (/**
* @return {?}
*/
() => Array.from(transitiveScopes.compilation.pipes).map((/**
* @param {?} pipe
* @return {?}
*/
pipe => (/** @type {?} */ (getPipeDef(pipe))))));
componentDef.schemas = transitiveScopes.schemas;
// Since we avoid Components/Directives/Pipes recompiling in case there are no overrides, we
// may face a problem where previously compiled defs available to a given Component/Directive
// are cached in TView and may become stale (in case any of these defs gets recompiled). In
// order to avoid this problem, we force fresh TView to be created.
componentDef.tView = null;
}
/**
* Compute the pair of transitive scopes (compilation scope and exported scope) for a given module.
*
* This operation is memoized and the result is cached on the module's definition. This function can
* be called on modules with components that have not fully compiled yet, but the result should not
* be used until they have.
*
* @template T
* @param {?} moduleType module that transitive scope should be calculated for.
* @return {?}
*/
function transitiveScopesFor(moduleType) {
if (!isNgModule(moduleType)) {
throw new Error(`${moduleType.name} does not have a module def (ɵmod property)`);
}
/** @type {?} */
const def = (/** @type {?} */ (getNgModuleDef(moduleType)));
if (def.transitiveCompileScopes !== null) {
return def.transitiveCompileScopes;
}
/** @type {?} */
const scopes = {
schemas: def.schemas || null,
compilation: {
directives: new Set(),
pipes: new Set(),
},
exported: {
directives: new Set(),
pipes: new Set(),
},
};
maybeUnwrapFn(def.imports).forEach((/**
* @template I
* @param {?} imported
* @return {?}
*/
(imported) => {
/** @type {?} */
const importedType = (/** @type {?} */ (imported));
if (!isNgModule(importedType)) {
throw new Error(`Importing ${importedType.name} which does not have a ɵmod property`);
}
// When this module imports another, the imported module's exported directives and pipes are
// added to the compilation scope of this module.
/** @type {?} */
const importedScope = transitiveScopesFor(importedType);
importedScope.exported.directives.forEach((/**
* @param {?} entry
* @return {?}
*/
entry => scopes.compilation.directives.add(entry)));
importedScope.exported.pipes.forEach((/**
* @param {?} entry
* @return {?}
*/
entry => scopes.compilation.pipes.add(entry)));
}));
maybeUnwrapFn(def.declarations).forEach((/**
* @param {?} declared
* @return {?}
*/
declared => {
/** @type {?} */
const declaredWithDefs = (/** @type {?} */ (declared));
if (getPipeDef(declaredWithDefs)) {
scopes.compilation.pipes.add(declared);
}
else {
// Either declared has a ɵcmp or ɵdir, or it's a component which hasn't
// had its template compiled yet. In either case, it gets added to the compilation's
// directives.
scopes.compilation.directives.add(declared);
}
}));
maybeUnwrapFn(def.exports).forEach((/**
* @template E
* @param {?} exported
* @return {?}
*/
(exported) => {
/** @type {?} */
const exportedType = (/** @type {?} */ (exported));
// Either the type is a module, a pipe, or a component/directive (which may not have a
// ɵcmp as it might be compiled asynchronously).
if (isNgModule(exportedType)) {
// When this module exports another, the exported module's exported directives and pipes are
// added to both the compilation and exported scopes of this module.
/** @type {?} */
const exportedScope = transitiveScopesFor(exportedType);
exportedScope.exported.directives.forEach((/**
* @param {?} entry
* @return {?}
*/
entry => {
scopes.compilation.directives.add(entry);
scopes.exported.directives.add(entry);
}));
exportedScope.exported.pipes.forEach((/**
* @param {?} entry
* @return {?}
*/
entry => {
scopes.compilation.pipes.add(entry);
scopes.exported.pipes.add(entry);
}));
}
else if (getPipeDef(exportedType)) {
scopes.exported.pipes.add(exportedType);
}
else {
scopes.exported.directives.add(exportedType);
}
}));
def.transitiveCompileScopes = scopes;
return scopes;
}
/**
* @param {?} value
* @return {?}
*/
function expandModuleWithProviders(value) {
if (isModuleWithProviders(value)) {
return value.ngModule;
}
return value;
}
/**
* @param {?} value
* @return {?}
*/
function isModuleWithProviders(value) {
return ((/** @type {?} */ (value))).ngModule !== undefined;
}
/**
* @template T
* @param {?} value
* @return {?}
*/
function isNgModule(value) {
return !!getNgModuleDef(value);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/jit/directive.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Compile an Angular component according to its decorator metadata, and patch the resulting
* component def (ɵcmp) onto the component type.
*
* Compilation may be asynchronous (due to the need to resolve URLs for the component template or
* other resources, for example). In the event that compilation is not immediate, `compileComponent`
* will enqueue resource resolution into a global queue and will fail to return the `ɵcmp`
* until the global queue has been resolved with a call to `resolveComponentResources`.
* @param {?} type
* @param {?} metadata
* @return {?}
*/
function compileComponent(type, metadata) {
// Initialize ngDevMode. This must be the first statement in compileComponent.
// See the `initNgDevMode` docstring for more information.
(typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
/** @type {?} */
let ngComponentDef = null;
// Metadata may have resources which need to be resolved.
maybeQueueResolutionOfComponentResources(type, metadata);
// Note that we're using the same function as `Directive`, because that's only subset of metadata
// that we need to create the ngFactoryDef. We're avoiding using the component metadata
// because we'd have to resolve the asynchronous templates.
addDirectiveFactoryDef(type, metadata);
Object.defineProperty(type, NG_COMP_DEF, {
get: (/**
* @return {?}
*/
() => {
if (ngComponentDef === null) {
/** @type {?} */
const compiler = getCompilerFacade();
if (componentNeedsResolution(metadata)) {
/** @type {?} */
const error = [`Component '${type.name}' is not resolved:`];
if (metadata.templateUrl) {
error.push(` - templateUrl: ${metadata.templateUrl}`);
}
if (metadata.styleUrls && metadata.styleUrls.length) {
error.push(` - styleUrls: ${JSON.stringify(metadata.styleUrls)}`);
}
error.push(`Did you run and wait for 'resolveComponentResources()'?`);
throw new Error(error.join('\n'));
}
// This const was called `jitOptions` previously but had to be renamed to `options` because
// of a bug with Terser that caused optimized JIT builds to throw a `ReferenceError`.
// This bug was investigated in https://github.com/angular/angular-cli/issues/17264.
// We should not rename it back until https://github.com/terser/terser/issues/615 is fixed.
/** @type {?} */
const options = getJitOptions();
/** @type {?} */
let preserveWhitespaces = metadata.preserveWhitespaces;
if (preserveWhitespaces === undefined) {
if (options !== null && options.preserveWhitespaces !== undefined) {
preserveWhitespaces = options.preserveWhitespaces;
}
else {
preserveWhitespaces = false;
}
}
/** @type {?} */
let encapsulation = metadata.encapsulation;
if (encapsulation === undefined) {
if (options !== null && options.defaultEncapsulation !== undefined) {
encapsulation = options.defaultEncapsulation;
}
else {
encapsulation = ViewEncapsulation$1.Emulated;
}
}
/** @type {?} */
const templateUrl = metadata.templateUrl || `ng:///${type.name}/template.html`;
/** @type {?} */
const meta = Object.assign(Object.assign({}, directiveMetadata(type, metadata)), { typeSourceSpan: compiler.createParseSourceSpan('Component', type.name, templateUrl), template: metadata.template || '', preserveWhitespaces, styles: metadata.styles || EMPTY_ARRAY, animations: metadata.animations, directives: [], changeDetection: metadata.changeDetection, pipes: new Map(), encapsulation, interpolation: metadata.interpolation, viewProviders: metadata.viewProviders || null });
if (meta.usesInheritance) {
addDirectiveDefToUndecoratedParents(type);
}
ngComponentDef = compiler.compileComponent(angularCoreEnv, templateUrl, meta);
// When NgModule decorator executed, we enqueued the module definition such that
// it would only dequeue and add itself as module scope to all of its declarations,
// but only if if all of its declarations had resolved. This call runs the check
// to see if any modules that are in the queue can be dequeued and add scope to
// their declarations.
flushModuleScopingQueueAsMuchAsPossible();
// If component compilation is async, then the @NgModule annotation which declares the
// component may execute and set an ngSelectorScope property on the component type. This
// allows the component to patch itself with directiveDefs from the module after it
// finishes compiling.
if (hasSelectorScope(type)) {
/** @type {?} */
const scopes = transitiveScopesFor(type.ngSelectorScope);
patchComponentDefWithScope(ngComponentDef, scopes);
}
}
return ngComponentDef;
}),
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
}
/**
* @template T
* @param {?} component
* @return {?}
*/
function hasSelectorScope(component) {
return ((/** @type {?} */ (component))).ngSelectorScope !== undefined;
}
/**
* Compile an Angular directive according to its decorator metadata, and patch the resulting
* directive def onto the component type.
*
* In the event that compilation is not immediate, `compileDirective` will return a `Promise` which
* will resolve when compilation completes and the directive becomes usable.
* @param {?} type
* @param {?} directive
* @return {?}
*/
function compileDirective(type, directive) {
/** @type {?} */
let ngDirectiveDef = null;
addDirectiveFactoryDef(type, directive || {});
Object.defineProperty(type, NG_DIR_DEF, {
get: (/**
* @return {?}
*/
() => {
if (ngDirectiveDef === null) {
// `directive` can be null in the case of abstract directives as a base class
// that use `@Directive()` with no selector. In that case, pass empty object to the
// `directiveMetadata` function instead of null.
/** @type {?} */
const meta = getDirectiveMetadata(type, directive || {});
ngDirectiveDef =
getCompilerFacade().compileDirective(angularCoreEnv, meta.sourceMapUrl, meta.metadata);
}
return ngDirectiveDef;
}),
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
}
/**
* @param {?} type
* @param {?} metadata
* @return {?}
*/
function getDirectiveMetadata(type, metadata) {
/** @type {?} */
const name = type && type.name;
/** @type {?} */
const sourceMapUrl = `ng:///${name}/ɵdir.js`;
/** @type {?} */
const compiler = getCompilerFacade();
/** @type {?} */
const facade = directiveMetadata((/** @type {?} */ (type)), metadata);
facade.typeSourceSpan = compiler.createParseSourceSpan('Directive', name, sourceMapUrl);
if (facade.usesInheritance) {
addDirectiveDefToUndecoratedParents(type);
}
return { metadata: facade, sourceMapUrl };
}
/**
* @param {?} type
* @param {?} metadata
* @return {?}
*/
function addDirectiveFactoryDef(type, metadata) {
/** @type {?} */
let ngFactoryDef = null;
Object.defineProperty(type, NG_FACTORY_DEF, {
get: (/**
* @return {?}
*/
() => {
if (ngFactoryDef === null) {
/** @type {?} */
const meta = getDirectiveMetadata(type, metadata);
/** @type {?} */
const compiler = getCompilerFacade();
ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${type.name}/ɵfac.js`, Object.assign(Object.assign({}, meta.metadata), { injectFn: 'directiveInject', target: compiler.R3FactoryTarget.Directive }));
}
return ngFactoryDef;
}),
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
}
/**
* @param {?} type
* @return {?}
*/
function extendsDirectlyFromObject(type) {
return Object.getPrototypeOf(type.prototype) === Object.prototype;
}
/**
* Extract the `R3DirectiveMetadata` for a particular directive (either a `Directive` or a
* `Component`).
* @param {?} type
* @param {?} metadata
* @return {?}
*/
function directiveMetadata(type, metadata) {
// Reflect inputs and outputs.
/** @type {?} */
const reflect = getReflect();
/** @type {?} */
const propMetadata = reflect.ownPropMetadata(type);
return {
name: type.name,
type: type,
typeArgumentCount: 0,
selector: metadata.selector !== undefined ? metadata.selector : null,
deps: reflectDependencies(type),
host: metadata.host || EMPTY_OBJ,
propMetadata: propMetadata,
inputs: metadata.inputs || EMPTY_ARRAY,
outputs: metadata.outputs || EMPTY_ARRAY,
queries: extractQueriesMetadata(type, propMetadata, isContentQuery),
lifecycle: { usesOnChanges: reflect.hasLifecycleHook(type, 'ngOnChanges') },
typeSourceSpan: (/** @type {?} */ (null)),
usesInheritance: !extendsDirectlyFromObject(type),
exportAs: extractExportAs(metadata.exportAs),
providers: metadata.providers || null,
viewQueries: extractQueriesMetadata(type, propMetadata, isViewQuery)
};
}
/**
* Adds a directive definition to all parent classes of a type that don't have an Angular decorator.
* @param {?} type
* @return {?}
*/
function addDirectiveDefToUndecoratedParents(type) {
/** @type {?} */
const objPrototype = Object.prototype;
/** @type {?} */
let parent = Object.getPrototypeOf(type.prototype).constructor;
// Go up the prototype until we hit `Object`.
while (parent && parent !== objPrototype) {
// Since inheritance works if the class was annotated already, we only need to add
// the def if there are no annotations and the def hasn't been created already.
if (!getDirectiveDef(parent) && !getComponentDef(parent) &&
shouldAddAbstractDirective(parent)) {
compileDirective(parent, null);
}
parent = Object.getPrototypeOf(parent);
}
}
/**
* @param {?} selector
* @return {?}
*/
function convertToR3QueryPredicate(selector) {
return typeof selector === 'string' ? splitByComma(selector) : resolveForwardRef(selector);
}
/**
* @param {?} propertyName
* @param {?} ann
* @return {?}
*/
function convertToR3QueryMetadata(propertyName, ann) {
return {
propertyName: propertyName,
predicate: convertToR3QueryPredicate(ann.selector),
descendants: ann.descendants,
first: ann.first,
read: ann.read ? ann.read : null,
static: !!ann.static
};
}
/**
* @param {?} type
* @param {?} propMetadata
* @param {?} isQueryAnn
* @return {?}
*/
function extractQueriesMetadata(type, propMetadata, isQueryAnn) {
/** @type {?} */
const queriesMeta = [];
for (const field in propMetadata) {
if (propMetadata.hasOwnProperty(field)) {
/** @type {?} */
const annotations = propMetadata[field];
annotations.forEach((/**
* @param {?} ann
* @return {?}
*/
ann => {
if (isQueryAnn(ann)) {
if (!ann.selector) {
throw new Error(`Can't construct a query for the property "${field}" of ` +
`"${stringifyForError(type)}" since the query selector wasn't defined.`);
}
if (annotations.some(isInputAnnotation)) {
throw new Error(`Cannot combine @Input decorators with query decorators`);
}
queriesMeta.push(convertToR3QueryMetadata(field, ann));
}
}));
}
}
return queriesMeta;
}
/**
* @param {?} exportAs
* @return {?}
*/
function extractExportAs(exportAs) {
return exportAs === undefined ? null : splitByComma(exportAs);
}
/**
* @param {?} value
* @return {?}
*/
function isContentQuery(value) {
/** @type {?} */
const name = value.ngMetadataName;
return name === 'ContentChild' || name === 'ContentChildren';
}
/**
* @param {?} value
* @return {?}
*/
function isViewQuery(value) {
/** @type {?} */
const name = value.ngMetadataName;
return name === 'ViewChild' || name === 'ViewChildren';
}
/**
* @param {?} value
* @return {?}
*/
function isInputAnnotation(value) {
return value.ngMetadataName === 'Input';
}
/**
* @param {?} value
* @return {?}
*/
function splitByComma(value) {
return value.split(',').map((/**
* @param {?} piece
* @return {?}
*/
piece => piece.trim()));
}
/** @type {?} */
const LIFECYCLE_HOOKS = [
'ngOnChanges', 'ngOnInit', 'ngOnDestroy', 'ngDoCheck', 'ngAfterViewInit', 'ngAfterViewChecked',
'ngAfterContentInit', 'ngAfterContentChecked'
];
/**
* @param {?} type
* @return {?}
*/
function shouldAddAbstractDirective(type) {
/** @type {?} */
const reflect = getReflect();
if (LIFECYCLE_HOOKS.some((/**
* @param {?} hookName
* @return {?}
*/
hookName => reflect.hasLifecycleHook(type, hookName)))) {
return true;
}
/** @type {?} */
const propMetadata = reflect.propMetadata(type);
for (const field in propMetadata) {
/** @type {?} */
const annotations = propMetadata[field];
for (let i = 0; i < annotations.length; i++) {
/** @type {?} */
const current = annotations[i];
/** @type {?} */
const metadataName = current.ngMetadataName;
if (isInputAnnotation(current) || isContentQuery(current) || isViewQuery(current) ||
metadataName === 'Output' || metadataName === 'HostBinding' ||
metadataName === 'HostListener') {
return true;
}
}
}
return false;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render3/jit/pipe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} type
* @param {?} meta
* @return {?}
*/
function compilePipe(type, meta) {
/** @type {?} */
let ngPipeDef = null;
/** @type {?} */
let ngFactoryDef = null;
Object.defineProperty(type, NG_FACTORY_DEF, {
get: (/**
* @return {?}
*/
() => {
if (ngFactoryDef === null) {
/** @type {?} */
const metadata = getPipeMetadata(type, meta);
/** @type {?} */
const compiler = getCompilerFacade();
ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${metadata.name}/ɵfac.js`, Object.assign(Object.assign({}, metadata), { injectFn: 'directiveInject', target: compiler.R3FactoryTarget.Pipe }));
}
return ngFactoryDef;
}),
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
Object.defineProperty(type, NG_PIPE_DEF, {
get: (/**
* @return {?}
*/
() => {
if (ngPipeDef === null) {
/** @type {?} */
const metadata = getPipeMetadata(type, meta);
ngPipeDef = getCompilerFacade().compilePipe(angularCoreEnv, `ng:///${metadata.name}/ɵpipe.js`, metadata);
}
return ngPipeDef;
}),
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
}
/**
* @param {?} type
* @param {?} meta
* @return {?}
*/
function getPipeMetadata(type, meta) {
return {
type: type,
typeArgumentCount: 0,
name: type.name,
deps: reflectDependencies(type),
pipeName: meta.name,
pure: meta.pure !== undefined ? meta.pure : true
};
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/metadata/directives.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Type of the Directive decorator / constructor function.
* \@publicApi
* @record
*/
function DirectiveDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ0$e = /**
* @param {?=} dir
* @return {?}
*/
(dir = {}) => dir, ɵ1$3 = /**
* @param {?} type
* @param {?} meta
* @return {?}
*/
(type, meta) => SWITCH_COMPILE_DIRECTIVE(type, meta);
/**
* Type of the Directive metadata.
*
* \@publicApi
* @type {?}
*/
const Directive = makeDecorator('Directive', (ɵ0$e), undefined, undefined, (ɵ1$3));
/**
* Component decorator interface
*
* \@publicApi
* @record
*/
function ComponentDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ2$1 = /**
* @param {?=} c
* @return {?}
*/
(c = {}) => (Object.assign({ changeDetection: ChangeDetectionStrategy.Default }, c)), ɵ3$1 = /**
* @param {?} type
* @param {?} meta
* @return {?}
*/
(type, meta) => SWITCH_COMPILE_COMPONENT(type, meta);
/**
* Component decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Component = makeDecorator('Component', (ɵ2$1), Directive, undefined, (ɵ3$1));
/**
* Type of the Pipe decorator / constructor function.
*
* \@publicApi
* @record
*/
function PipeDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ4 = /**
* @param {?} p
* @return {?}
*/
(p) => (Object.assign({ pure: true }, p)), ɵ5 = /**
* @param {?} type
* @param {?} meta
* @return {?}
*/
(type, meta) => SWITCH_COMPILE_PIPE(type, meta);
/**
* \@Annotation
* \@publicApi
* @type {?}
*/
const Pipe = makeDecorator('Pipe', (ɵ4), undefined, undefined, (ɵ5));
/**
* \@publicApi
* @record
*/
function InputDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ6 = /**
* @param {?=} bindingPropertyName
* @return {?}
*/
(bindingPropertyName) => ({ bindingPropertyName });
/**
* \@Annotation
* \@publicApi
* @type {?}
*/
const Input = makePropDecorator('Input', (ɵ6));
/**
* Type of the Output decorator / constructor function.
*
* \@publicApi
* @record
*/
function OutputDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ7 = /**
* @param {?=} bindingPropertyName
* @return {?}
*/
(bindingPropertyName) => ({ bindingPropertyName });
/**
* \@Annotation
* \@publicApi
* @type {?}
*/
const Output = makePropDecorator('Output', (ɵ7));
/**
* Type of the HostBinding decorator / constructor function.
*
* \@publicApi
* @record
*/
function HostBindingDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ8 = /**
* @param {?=} hostPropertyName
* @return {?}
*/
(hostPropertyName) => ({ hostPropertyName });
/**
* \@Annotation
* \@publicApi
* @type {?}
*/
const HostBinding = makePropDecorator('HostBinding', (ɵ8));
/**
* Type of the HostListener decorator / constructor function.
*
* \@publicApi
* @record
*/
function HostListenerDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ9 = /**
* @param {?=} eventName
* @param {?=} args
* @return {?}
*/
(eventName, args) => ({ eventName, args });
/**
* Decorator that binds a DOM event to a host listener and supplies configuration metadata.
* Angular invokes the supplied handler method when the host element emits the specified event,
* and updates the bound element with the result.
*
* If the handler method returns false, applies `preventDefault` on the bound element.
*
* \@usageNotes
*
* The following example declares a directive
* that attaches a click listener to a button and counts clicks.
*
* ```ts
* \@Directive({selector: 'button[counting]'})
* class CountClicks {
* numberOfClicks = 0;
*
* \@HostListener('click', ['$event.target'])
* onClick(btn) {
* console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
* }
* }
*
* \@Component({
* selector: 'app',
* template: '<button counting>Increment</button>',
* })
* class App {}
*
* ```
*
* The following example registers another DOM event handler that listens for key-press events.
* ``` ts
* import { HostListener, Component } from "\@angular/core";
*
* \@Component({
* selector: 'app',
* template: `<h1>Hello, you have pressed keys {{counter}} number of times!</h1> Press any key to
* increment the counter.
* <button (click)="resetCounter()">Reset Counter</button>`
* })
* class AppComponent {
* counter = 0;
* \@HostListener('window:keydown', ['$event'])
* handleKeyDown(event: KeyboardEvent) {
* this.counter++;
* }
* resetCounter() {
* this.counter = 0;
* }
* }
* ```
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const HostListener = makePropDecorator('HostListener', (ɵ9));
/** @type {?} */
const SWITCH_COMPILE_COMPONENT__POST_R3__ = compileComponent;
/** @type {?} */
const SWITCH_COMPILE_DIRECTIVE__POST_R3__ = compileDirective;
/** @type {?} */
const SWITCH_COMPILE_PIPE__POST_R3__ = compilePipe;
/** @type {?} */
const SWITCH_COMPILE_COMPONENT__PRE_R3__ = noop;
/** @type {?} */
const SWITCH_COMPILE_DIRECTIVE__PRE_R3__ = noop;
/** @type {?} */
const SWITCH_COMPILE_PIPE__PRE_R3__ = noop;
/** @type {?} */
const SWITCH_COMPILE_COMPONENT = SWITCH_COMPILE_COMPONENT__POST_R3__;
/** @type {?} */
const SWITCH_COMPILE_DIRECTIVE = SWITCH_COMPILE_DIRECTIVE__POST_R3__;
/** @type {?} */
const SWITCH_COMPILE_PIPE = SWITCH_COMPILE_PIPE__POST_R3__;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/metadata/ng_module.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Represents the expansion of an `NgModule` into its scopes.
*
* A scope is a set of directives and pipes that are visible in a particular context. Each
* `NgModule` has two scopes. The `compilation` scope is the set of directives and pipes that will
* be recognized in the templates of components declared by the module. The `exported` scope is the
* set of directives and pipes exported by a module (that is, module B's exported scope gets added
* to module A's compilation scope when module A imports B).
* @record
*/
function NgModuleTransitiveScopes() { }
if (false) {}
/**
* Runtime link information for NgModules.
*
* This is the internal data structure used by the runtime to assemble components, directives,
* pipes, and injectors.
*
* NOTE: Always use `ɵɵdefineNgModule` function to create this object,
* never create the object directly since the shape of this object
* can change between versions.
* @record
* @template T
*/
function NgModuleDef() { }
if (false) {}
/**
* A wrapper around an NgModule that associates it with the providers.
*
* @param T the module type. In Ivy applications, this must be explicitly
* provided.
*
* Note that using ModuleWithProviders without a generic type is deprecated.
* The generic will become required in a future version of Angular.
*
* \@publicApi
* @record
* @template T
*/
function ModuleWithProviders() { }
if (false) {}
/**
* Type of the NgModule decorator / constructor function.
*
* \@publicApi
* @record
*/
function NgModuleDecorator() { }
// WARNING: interface has both a type and a value, skipping emit
const ɵ0$f = /**
* @param {?} ngModule
* @return {?}
*/
(ngModule) => ngModule, ɵ1$4 = /**
* Decorator that marks the following class as an NgModule, and supplies
* configuration metadata for it.
*
* * The `declarations` and `entryComponents` options configure the compiler
* with information about what belongs to the NgModule.
* * The `providers` options configures the NgModule's injector to provide
* dependencies the NgModule members.
* * The `imports` and `exports` options bring in members from other modules, and make
* this module's members available to others.
* @param {?} type
* @param {?} meta
* @return {?}
*/
(type, meta) => SWITCH_COMPILE_NGMODULE(type, meta);
/**
* \@Annotation
* \@publicApi
* @type {?}
*/
const NgModule = makeDecorator('NgModule', (ɵ0$f), undefined, undefined, (ɵ1$4));
/**
* \@description
* Hook for manual bootstrapping of the application instead of using bootstrap array in \@NgModule
* annotation.
*
* Reference to the current application is provided as a parameter.
*
* See ["Bootstrapping"](guide/bootstrapping) and ["Entry components"](guide/entry-components).
*
* \@usageNotes
* ```typescript
* class AppModule implements DoBootstrap {
* ngDoBootstrap(appRef: ApplicationRef) {
* appRef.bootstrap(AppComponent); // Or some other component
* }
* }
* ```
*
* \@publicApi
* @record
*/
function DoBootstrap() { }
if (false) {}
/**
* @param {?} moduleType
* @param {?=} metadata
* @return {?}
*/
function preR3NgModuleCompile(moduleType, metadata) {
/** @type {?} */
let imports = (metadata && metadata.imports) || [];
if (metadata && metadata.exports) {
imports = [...imports, metadata.exports];
}
((/** @type {?} */ (moduleType))).ɵinj = ɵɵdefineInjector({
factory: convertInjectableProviderToFactory(moduleType, { useClass: moduleType }),
providers: metadata && metadata.providers,
imports: imports,
});
}
/** @type {?} */
const SWITCH_COMPILE_NGMODULE__POST_R3__ = compileNgModule;
/** @type {?} */
const SWITCH_COMPILE_NGMODULE__PRE_R3__ = preR3NgModuleCompile;
/** @type {?} */
const SWITCH_COMPILE_NGMODULE = SWITCH_COMPILE_NGMODULE__POST_R3__;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/metadata.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/application_init.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* An injection token that allows you to provide one or more initialization functions.
* These function are injected at application startup and executed during
* app initialization. If any of these functions returns a Promise, initialization
* does not complete until the Promise is resolved.
*
* You can, for example, create a factory function that loads language data
* or an external configuration, and provide that function to the `APP_INITIALIZER` token.
* That way, the function is executed during the application bootstrap process,
* and the needed data is available on startup.
*
* \@publicApi
* @type {?}
*/
const APP_INITIALIZER = new InjectionToken('Application Initializer');
/**
* A class that reflects the state of running {\@link APP_INITIALIZER}s.
*
* \@publicApi
*/
class ApplicationInitStatus {
/**
* @param {?} appInits
*/
constructor(appInits) {
this.appInits = appInits;
this.initialized = false;
this.done = false;
this.donePromise = new Promise((/**
* @param {?} res
* @param {?} rej
* @return {?}
*/
(res, rej) => {
this.resolve = res;
this.reject = rej;
}));
}
/**
* \@internal
* @return {?}
*/
runInitializers() {
if (this.initialized) {
return;
}
/** @type {?} */
const asyncInitPromises = [];
/** @type {?} */
const complete = (/**
* @return {?}
*/
() => {
((/** @type {?} */ (this))).done = true;
this.resolve();
});
if (this.appInits) {
for (let i = 0; i < this.appInits.length; i++) {
/** @type {?} */
const initResult = this.appInits[i]();
if (isPromise(initResult)) {
asyncInitPromises.push(initResult);
}
}
}
Promise.all(asyncInitPromises)
.then((/**
* @return {?}
*/
() => {
complete();
}))
.catch((/**
* @param {?} e
* @return {?}
*/
e => {
this.reject(e);
}));
if (asyncInitPromises.length === 0) {
complete();
}
this.initialized = true;
}
}
ApplicationInitStatus.ɵfac = function ApplicationInitStatus_Factory(t) { return new (t || ApplicationInitStatus)(ɵɵinject(APP_INITIALIZER, 8)); };
ApplicationInitStatus.ɵprov = ɵɵdefineInjectable({ token: ApplicationInitStatus, factory: ApplicationInitStatus.ɵfac });
/** @nocollapse */
ApplicationInitStatus.ctorParameters = () => [
{ type: Array, decorators: [{ type: Inject, args: [APP_INITIALIZER,] }, { type: Optional }] }
];
/*@__PURE__*/ (function () { setClassMetadata(ApplicationInitStatus, [{
type: Injectable
}], function () { return [{ type: Array, decorators: [{
type: Inject,
args: [APP_INITIALIZER]
}, {
type: Optional
}] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/application_tokens.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A DI Token representing a unique string id assigned to the application by Angular and used
* primarily for prefixing application attributes and CSS styles when
* {\@link ViewEncapsulation#Emulated ViewEncapsulation.Emulated} is being used.
*
* If you need to avoid randomly generated value to be used as an application id, you can provide
* a custom value via a DI provider <!-- TODO: provider --> configuring the root {\@link Injector}
* using this token.
* \@publicApi
* @type {?}
*/
const APP_ID = new InjectionToken('AppId');
/**
* @return {?}
*/
function _appIdRandomProviderFactory() {
return `${_randomChar()}${_randomChar()}${_randomChar()}`;
}
/**
* Providers that will generate a random APP_ID_TOKEN.
* \@publicApi
* @type {?}
*/
const APP_ID_RANDOM_PROVIDER = {
provide: APP_ID,
useFactory: _appIdRandomProviderFactory,
deps: (/** @type {?} */ ([])),
};
/**
* @return {?}
*/
function _randomChar() {
return String.fromCharCode(97 + Math.floor(Math.random() * 25));
}
/**
* A function that will be executed when a platform is initialized.
* \@publicApi
* @type {?}
*/
const PLATFORM_INITIALIZER = new InjectionToken('Platform Initializer');
/**
* A token that indicates an opaque platform id.
* \@publicApi
* @type {?}
*/
const PLATFORM_ID = new InjectionToken('Platform ID');
/**
* All callbacks provided via this token will be called for every component that is bootstrapped.
* Signature of the callback:
*
* `(componentRef: ComponentRef) => void`.
*
* \@publicApi
* @type {?}
*/
const APP_BOOTSTRAP_LISTENER = new InjectionToken('appBootstrapListener');
/**
* A token which indicates the root directory of the application
* \@publicApi
* @type {?}
*/
const PACKAGE_ROOT_URL = new InjectionToken('Application Packages Root URL');
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/console.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class Console {
/**
* @param {?} message
* @return {?}
*/
log(message) {
// tslint:disable-next-line:no-console
console.log(message);
}
// Note: for reporting errors use `DOM.logError()` as it is platform specific
/**
* @param {?} message
* @return {?}
*/
warn(message) {
// tslint:disable-next-line:no-console
console.warn(message);
}
}
Console.ɵfac = function Console_Factory(t) { return new (t || Console)(); };
Console.ɵprov = ɵɵdefineInjectable({ token: Console, factory: Console.ɵfac });
/*@__PURE__*/ (function () { setClassMetadata(Console, [{
type: Injectable
}], null, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/i18n/tokens.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Provide this token to set the locale of your application.
* It is used for i18n extraction, by i18n pipes (DatePipe, I18nPluralPipe, CurrencyPipe,
* DecimalPipe and PercentPipe) and by ICU expressions.
*
* See the [i18n guide](guide/i18n#setting-up-locale) for more information.
*
* \@usageNotes
* ### Example
*
* ```typescript
* import { LOCALE_ID } from '\@angular/core';
* import { platformBrowserDynamic } from '\@angular/platform-browser-dynamic';
* import { AppModule } from './app/app.module';
*
* platformBrowserDynamic().bootstrapModule(AppModule, {
* providers: [{provide: LOCALE_ID, useValue: 'en-US' }]
* });
* ```
*
* \@publicApi
* @type {?}
*/
const LOCALE_ID$1 = new InjectionToken('LocaleId');
/**
* Provide this token to set the default currency code your application uses for
* CurrencyPipe when there is no currency code passed into it. This is only used by
* CurrencyPipe and has no relation to locale currency. Defaults to USD if not configured.
*
* See the [i18n guide](guide/i18n#setting-up-locale) for more information.
*
* <div class="alert is-helpful">
*
* **Deprecation notice:**
*
* The default currency code is currently always `USD` but this is deprecated from v9.
*
* **In v10 the default currency code will be taken from the current locale.**
*
* If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in
* your application `NgModule`:
*
* ```ts
* {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'}
* ```
*
* </div>
*
* \@usageNotes
* ### Example
*
* ```typescript
* import { platformBrowserDynamic } from '\@angular/platform-browser-dynamic';
* import { AppModule } from './app/app.module';
*
* platformBrowserDynamic().bootstrapModule(AppModule, {
* providers: [{provide: DEFAULT_CURRENCY_CODE, useValue: 'EUR' }]
* });
* ```
*
* \@publicApi
* @type {?}
*/
const DEFAULT_CURRENCY_CODE = new InjectionToken('DefaultCurrencyCode');
/**
* Use this token at bootstrap to provide the content of your translation file (`xtb`,
* `xlf` or `xlf2`) when you want to translate your application in another language.
*
* See the [i18n guide](guide/i18n#merge) for more information.
*
* \@usageNotes
* ### Example
*
* ```typescript
* import { TRANSLATIONS } from '\@angular/core';
* import { platformBrowserDynamic } from '\@angular/platform-browser-dynamic';
* import { AppModule } from './app/app.module';
*
* // content of your translation file
* const translations = '....';
*
* platformBrowserDynamic().bootstrapModule(AppModule, {
* providers: [{provide: TRANSLATIONS, useValue: translations }]
* });
* ```
*
* \@publicApi
* @type {?}
*/
const TRANSLATIONS = new InjectionToken('Translations');
/**
* Provide this token at bootstrap to set the format of your {\@link TRANSLATIONS}: `xtb`,
* `xlf` or `xlf2`.
*
* See the [i18n guide](guide/i18n#merge) for more information.
*
* \@usageNotes
* ### Example
*
* ```typescript
* import { TRANSLATIONS_FORMAT } from '\@angular/core';
* import { platformBrowserDynamic } from '\@angular/platform-browser-dynamic';
* import { AppModule } from './app/app.module';
*
* platformBrowserDynamic().bootstrapModule(AppModule, {
* providers: [{provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }]
* });
* ```
*
* \@publicApi
* @type {?}
*/
const TRANSLATIONS_FORMAT = new InjectionToken('TranslationsFormat');
/** @enum {number} */
const MissingTranslationStrategy = {
Error: 0,
Warning: 1,
Ignore: 2,
};
MissingTranslationStrategy[MissingTranslationStrategy.Error] = 'Error';
MissingTranslationStrategy[MissingTranslationStrategy.Warning] = 'Warning';
MissingTranslationStrategy[MissingTranslationStrategy.Ignore] = 'Ignore';
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/ivy_switch.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @type {?} */
const SWITCH_IVY_ENABLED__POST_R3__ = true;
/** @type {?} */
const SWITCH_IVY_ENABLED__PRE_R3__ = false;
/** @type {?} */
const ivyEnabled = SWITCH_IVY_ENABLED__POST_R3__;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/compiler.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Combination of NgModuleFactory and ComponentFactorys.
*
* \@publicApi
* @template T
*/
class ModuleWithComponentFactories {
/**
* @param {?} ngModuleFactory
* @param {?} componentFactories
*/
constructor(ngModuleFactory, componentFactories) {
this.ngModuleFactory = ngModuleFactory;
this.componentFactories = componentFactories;
}
}
if (false) {}
/**
* @return {?}
*/
function _throwError() {
throw new Error(`Runtime compiler is not loaded`);
}
/** @type {?} */
const Compiler_compileModuleSync__PRE_R3__ = (/** @type {?} */ (_throwError));
/** @type {?} */
const Compiler_compileModuleSync__POST_R3__ = (/**
* @template T
* @param {?} moduleType
* @return {?}
*/
function (moduleType) {
return new NgModuleFactory$1(moduleType);
});
/** @type {?} */
const Compiler_compileModuleSync = Compiler_compileModuleSync__POST_R3__;
/** @type {?} */
const Compiler_compileModuleAsync__PRE_R3__ = (/** @type {?} */ (_throwError));
/** @type {?} */
const Compiler_compileModuleAsync__POST_R3__ = (/**
* @template T
* @param {?} moduleType
* @return {?}
*/
function (moduleType) {
return Promise.resolve(Compiler_compileModuleSync__POST_R3__(moduleType));
});
/** @type {?} */
const Compiler_compileModuleAsync = Compiler_compileModuleAsync__POST_R3__;
/** @type {?} */
const Compiler_compileModuleAndAllComponentsSync__PRE_R3__ = (/** @type {?} */ (_throwError));
/** @type {?} */
const Compiler_compileModuleAndAllComponentsSync__POST_R3__ = (/**
* @template T
* @param {?} moduleType
* @return {?}
*/
function (moduleType) {
/** @type {?} */
const ngModuleFactory = Compiler_compileModuleSync__POST_R3__(moduleType);
/** @type {?} */
const moduleDef = (/** @type {?} */ (getNgModuleDef(moduleType)));
/** @type {?} */
const componentFactories = maybeUnwrapFn(moduleDef.declarations)
.reduce((/**
* @param {?} factories
* @param {?} declaration
* @return {?}
*/
(factories, declaration) => {
/** @type {?} */
const componentDef = getComponentDef(declaration);
componentDef && factories.push(new ComponentFactory$1(componentDef));
return factories;
}), (/** @type {?} */ ([])));
return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
});
/** @type {?} */
const Compiler_compileModuleAndAllComponentsSync = Compiler_compileModuleAndAllComponentsSync__POST_R3__;
/** @type {?} */
const Compiler_compileModuleAndAllComponentsAsync__PRE_R3__ = (/** @type {?} */ (_throwError));
/** @type {?} */
const Compiler_compileModuleAndAllComponentsAsync__POST_R3__ = (/**
* @template T
* @param {?} moduleType
* @return {?}
*/
function (moduleType) {
return Promise.resolve(Compiler_compileModuleAndAllComponentsSync__POST_R3__(moduleType));
});
/** @type {?} */
const Compiler_compileModuleAndAllComponentsAsync = Compiler_compileModuleAndAllComponentsAsync__POST_R3__;
/**
* Low-level service for running the angular compiler during runtime
* to create {\@link ComponentFactory}s, which
* can later be used to create and render a Component instance.
*
* Each `\@NgModule` provides an own `Compiler` to its injector,
* that will use the directives/pipes of the ng module for compilation
* of components.
*
* \@publicApi
*/
class Compiler {
constructor() {
/**
* Compiles the given NgModule and all of its components. All templates of the components listed
* in `entryComponents` have to be inlined.
*/
this.compileModuleSync = Compiler_compileModuleSync;
/**
* Compiles the given NgModule and all of its components
*/
this.compileModuleAsync = Compiler_compileModuleAsync;
/**
* Same as {\@link #compileModuleSync} but also creates ComponentFactories for all components.
*/
this.compileModuleAndAllComponentsSync = Compiler_compileModuleAndAllComponentsSync;
/**
* Same as {\@link #compileModuleAsync} but also creates ComponentFactories for all components.
*/
this.compileModuleAndAllComponentsAsync = Compiler_compileModuleAndAllComponentsAsync;
}
/**
* Clears all caches.
* @return {?}
*/
clearCache() { }
/**
* Clears the cache for the given component/ngModule.
* @param {?} type
* @return {?}
*/
clearCacheFor(type) { }
/**
* Returns the id for a given NgModule, if one is defined and known to the compiler.
* @param {?} moduleType
* @return {?}
*/
getModuleId(moduleType) {
return undefined;
}
}
Compiler.ɵfac = function Compiler_Factory(t) { return new (t || Compiler)(); };
Compiler.ɵprov = ɵɵdefineInjectable({ token: Compiler, factory: Compiler.ɵfac });
/*@__PURE__*/ (function () { setClassMetadata(Compiler, [{
type: Injectable
}], function () { return []; }, null); })();
if (false) {}
/**
* Token to provide CompilerOptions in the platform injector.
*
* \@publicApi
* @type {?}
*/
const COMPILER_OPTIONS = new InjectionToken('compilerOptions');
/**
* A factory for creating a Compiler
*
* \@publicApi
* @abstract
*/
class CompilerFactory {
}
if (false) {}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const promise = (() => Promise.resolve(0))();
function scheduleMicroTask(fn) {
if (typeof Zone === 'undefined') {
// use promise to schedule microTask instead of use Zone
promise.then(() => {
fn && fn.apply(null, null);
});
}
else {
Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function getNativeRequestAnimationFrame() {
let nativeRequestAnimationFrame = _global['requestAnimationFrame'];
let nativeCancelAnimationFrame = _global['cancelAnimationFrame'];
if (typeof Zone !== 'undefined' && nativeRequestAnimationFrame && nativeCancelAnimationFrame) {
// use unpatched version of requestAnimationFrame(native delegate) if possible
// to avoid another Change detection
const unpatchedRequestAnimationFrame = nativeRequestAnimationFrame[Zone.__symbol__('OriginalDelegate')];
if (unpatchedRequestAnimationFrame) {
nativeRequestAnimationFrame = unpatchedRequestAnimationFrame;
}
const unpatchedCancelAnimationFrame = nativeCancelAnimationFrame[Zone.__symbol__('OriginalDelegate')];
if (unpatchedCancelAnimationFrame) {
nativeCancelAnimationFrame = unpatchedCancelAnimationFrame;
}
}
return { nativeRequestAnimationFrame, nativeCancelAnimationFrame };
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/zone/ng_zone.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* An injectable service for executing work inside or outside of the Angular zone.
*
* The most common use of this service is to optimize performance when starting a work consisting of
* one or more asynchronous tasks that don't require UI updates or error handling to be handled by
* Angular. Such tasks can be kicked off via {\@link #runOutsideAngular} and if needed, these tasks
* can reenter the Angular zone via {\@link #run}.
*
* <!-- TODO: add/fix links to:
* - docs explaining zones and the use of zones in Angular and change-detection
* - link to runOutsideAngular/run (throughout this file!)
* -->
*
* \@usageNotes
* ### Example
*
* ```
* import {Component, NgZone} from '\@angular/core';
* import {NgIf} from '\@angular/common';
*
* \@Component({
* selector: 'ng-zone-demo',
* template: `
* <h2>Demo: NgZone</h2>
*
* <p>Progress: {{progress}}%</p>
* <p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p>
*
* <button (click)="processWithinAngularZone()">Process within Angular zone</button>
* <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button>
* `,
* })
* export class NgZoneDemo {
* progress: number = 0;
* label: string;
*
* constructor(private _ngZone: NgZone) {}
*
* // Loop inside the Angular zone
* // so the UI DOES refresh after each setTimeout cycle
* processWithinAngularZone() {
* this.label = 'inside';
* this.progress = 0;
* this._increaseProgress(() => console.log('Inside Done!'));
* }
*
* // Loop outside of the Angular zone
* // so the UI DOES NOT refresh after each setTimeout cycle
* processOutsideOfAngularZone() {
* this.label = 'outside';
* this.progress = 0;
* this._ngZone.runOutsideAngular(() => {
* this._increaseProgress(() => {
* // reenter the Angular zone and display done
* this._ngZone.run(() => { console.log('Outside Done!'); });
* });
* });
* }
*
* _increaseProgress(doneCallback: () => void) {
* this.progress += 1;
* console.log(`Current progress: ${this.progress}%`);
*
* if (this.progress < 100) {
* window.setTimeout(() => this._increaseProgress(doneCallback), 10);
* } else {
* doneCallback();
* }
* }
* }
* ```
*
* \@publicApi
*/
class NgZone {
/**
* @param {?} __0
*/
constructor({ enableLongStackTrace = false, shouldCoalesceEventChangeDetection = false }) {
this.hasPendingMacrotasks = false;
this.hasPendingMicrotasks = false;
/**
* Whether there are no outstanding microtasks or macrotasks.
*/
this.isStable = true;
/**
* Notifies when code enters Angular Zone. This gets fired first on VM Turn.
*/
this.onUnstable = new EventEmitter(false);
/**
* Notifies when there is no more microtasks enqueued in the current VM Turn.
* This is a hint for Angular to do change detection, which may enqueue more microtasks.
* For this reason this event can fire multiple times per VM Turn.
*/
this.onMicrotaskEmpty = new EventEmitter(false);
/**
* Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which
* implies we are about to relinquish VM turn.
* This event gets called just once.
*/
this.onStable = new EventEmitter(false);
/**
* Notifies that an error has been delivered.
*/
this.onError = new EventEmitter(false);
if (typeof Zone == 'undefined') {
throw new Error(`In this configuration Angular requires Zone.js`);
}
Zone.assertZonePatched();
/** @type {?} */
const self = (/** @type {?} */ ((/** @type {?} */ (this))));
self._nesting = 0;
self._outer = self._inner = Zone.current;
if (((/** @type {?} */ (Zone)))['wtfZoneSpec']) {
self._inner = self._inner.fork(((/** @type {?} */ (Zone)))['wtfZoneSpec']);
}
if (((/** @type {?} */ (Zone)))['TaskTrackingZoneSpec']) {
self._inner = self._inner.fork(new ((/** @type {?} */ (((/** @type {?} */ (Zone)))['TaskTrackingZoneSpec']))));
}
if (enableLongStackTrace && ((/** @type {?} */ (Zone)))['longStackTraceZoneSpec']) {
self._inner = self._inner.fork(((/** @type {?} */ (Zone)))['longStackTraceZoneSpec']);
}
self.shouldCoalesceEventChangeDetection = shouldCoalesceEventChangeDetection;
self.lastRequestAnimationFrameId = -1;
self.nativeRequestAnimationFrame = getNativeRequestAnimationFrame().nativeRequestAnimationFrame;
forkInnerZoneWithAngularBehavior(self);
}
/**
* @return {?}
*/
static isInAngularZone() {
return Zone.current.get('isAngularZone') === true;
}
/**
* @return {?}
*/
static assertInAngularZone() {
if (!NgZone.isInAngularZone()) {
throw new Error('Expected to be in Angular Zone, but it is not!');
}
}
/**
* @return {?}
*/
static assertNotInAngularZone() {
if (NgZone.isInAngularZone()) {
throw new Error('Expected to not be in Angular Zone, but it is!');
}
}
/**
* Executes the `fn` function synchronously within the Angular zone and returns value returned by
* the function.
*
* Running functions via `run` allows you to reenter Angular zone from a task that was executed
* outside of the Angular zone (typically started via {\@link #runOutsideAngular}).
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* within the Angular zone.
*
* If a synchronous error happens it will be rethrown and not reported via `onError`.
* @template T
* @param {?} fn
* @param {?=} applyThis
* @param {?=} applyArgs
* @return {?}
*/
run(fn, applyThis, applyArgs) {
return (/** @type {?} */ (((/** @type {?} */ ((/** @type {?} */ (this)))))._inner.run(fn, applyThis, applyArgs)));
}
/**
* Executes the `fn` function synchronously within the Angular zone as a task and returns value
* returned by the function.
*
* Running functions via `run` allows you to reenter Angular zone from a task that was executed
* outside of the Angular zone (typically started via {\@link #runOutsideAngular}).
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* within the Angular zone.
*
* If a synchronous error happens it will be rethrown and not reported via `onError`.
* @template T
* @param {?} fn
* @param {?=} applyThis
* @param {?=} applyArgs
* @param {?=} name
* @return {?}
*/
runTask(fn, applyThis, applyArgs, name) {
/** @type {?} */
const zone = ((/** @type {?} */ ((/** @type {?} */ (this)))))._inner;
/** @type {?} */
const task = zone.scheduleEventTask('NgZoneEvent: ' + name, fn, EMPTY_PAYLOAD, noop$1, noop$1);
try {
return (/** @type {?} */ (zone.runTask(task, applyThis, applyArgs)));
}
finally {
zone.cancelTask(task);
}
}
/**
* Same as `run`, except that synchronous errors are caught and forwarded via `onError` and not
* rethrown.
* @template T
* @param {?} fn
* @param {?=} applyThis
* @param {?=} applyArgs
* @return {?}
*/
runGuarded(fn, applyThis, applyArgs) {
return (/** @type {?} */ (((/** @type {?} */ ((/** @type {?} */ (this)))))._inner.runGuarded(fn, applyThis, applyArgs)));
}
/**
* Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
* the function.
*
* Running functions via {\@link #runOutsideAngular} allows you to escape Angular's zone and do
* work that
* doesn't trigger Angular change-detection or is subject to Angular's error handling.
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* outside of the Angular zone.
*
* Use {\@link #run} to reenter the Angular zone and do work that updates the application model.
* @template T
* @param {?} fn
* @return {?}
*/
runOutsideAngular(fn) {
return (/** @type {?} */ (((/** @type {?} */ ((/** @type {?} */ (this)))))._outer.run(fn)));
}
}
if (false) {}
/**
* @return {?}
*/
function noop$1() { }
/** @type {?} */
const EMPTY_PAYLOAD = {};
/**
* @record
*/
function NgZonePrivate() { }
if (false) {}
/**
* @param {?} zone
* @return {?}
*/
function checkStable(zone) {
if (zone._nesting == 0 && !zone.hasPendingMicrotasks && !zone.isStable) {
try {
zone._nesting++;
zone.onMicrotaskEmpty.emit(null);
}
finally {
zone._nesting--;
if (!zone.hasPendingMicrotasks) {
try {
zone.runOutsideAngular((/**
* @return {?}
*/
() => zone.onStable.emit(null)));
}
finally {
zone.isStable = true;
}
}
}
}
}
/**
* @param {?} zone
* @return {?}
*/
function delayChangeDetectionForEvents(zone) {
if (zone.lastRequestAnimationFrameId !== -1) {
return;
}
zone.lastRequestAnimationFrameId = zone.nativeRequestAnimationFrame.call(_global, (/**
* @return {?}
*/
() => {
zone.lastRequestAnimationFrameId = -1;
updateMicroTaskStatus(zone);
checkStable(zone);
}));
updateMicroTaskStatus(zone);
}
/**
* @param {?} zone
* @return {?}
*/
function forkInnerZoneWithAngularBehavior(zone) {
/** @type {?} */
const delayChangeDetectionForEventsDelegate = (/**
* @return {?}
*/
() => {
delayChangeDetectionForEvents(zone);
});
/** @type {?} */
const maybeDelayChangeDetection = !!zone.shouldCoalesceEventChangeDetection &&
zone.nativeRequestAnimationFrame && delayChangeDetectionForEventsDelegate;
zone._inner = zone._inner.fork({
name: 'angular',
properties: (/** @type {?} */ ({ 'isAngularZone': true, 'maybeDelayChangeDetection': maybeDelayChangeDetection })),
onInvokeTask: (/**
* @param {?} delegate
* @param {?} current
* @param {?} target
* @param {?} task
* @param {?} applyThis
* @param {?} applyArgs
* @return {?}
*/
(delegate, current, target, task, applyThis, applyArgs) => {
try {
onEnter(zone);
return delegate.invokeTask(target, task, applyThis, applyArgs);
}
finally {
if (maybeDelayChangeDetection && task.type === 'eventTask') {
maybeDelayChangeDetection();
}
onLeave(zone);
}
}),
onInvoke: (/**
* @param {?} delegate
* @param {?} current
* @param {?} target
* @param {?} callback
* @param {?} applyThis
* @param {?=} applyArgs
* @param {?=} source
* @return {?}
*/
(delegate, current, target, callback, applyThis, applyArgs, source) => {
try {
onEnter(zone);
return delegate.invoke(target, callback, applyThis, applyArgs, source);
}
finally {
onLeave(zone);
}
}),
onHasTask: (/**
* @param {?} delegate
* @param {?} current
* @param {?} target
* @param {?} hasTaskState
* @return {?}
*/
(delegate, current, target, hasTaskState) => {
delegate.hasTask(target, hasTaskState);
if (current === target) {
// We are only interested in hasTask events which originate from our zone
// (A child hasTask event is not interesting to us)
if (hasTaskState.change == 'microTask') {
zone._hasPendingMicrotasks = hasTaskState.microTask;
updateMicroTaskStatus(zone);
checkStable(zone);
}
else if (hasTaskState.change == 'macroTask') {
zone.hasPendingMacrotasks = hasTaskState.macroTask;
}
}
}),
onHandleError: (/**
* @param {?} delegate
* @param {?} current
* @param {?} target
* @param {?} error
* @return {?}
*/
(delegate, current, target, error) => {
delegate.handleError(target, error);
zone.runOutsideAngular((/**
* @return {?}
*/
() => zone.onError.emit(error)));
return false;
})
});
}
/**
* @param {?} zone
* @return {?}
*/
function updateMicroTaskStatus(zone) {
if (zone._hasPendingMicrotasks ||
(zone.shouldCoalesceEventChangeDetection && zone.lastRequestAnimationFrameId !== -1)) {
zone.hasPendingMicrotasks = true;
}
else {
zone.hasPendingMicrotasks = false;
}
}
/**
* @param {?} zone
* @return {?}
*/
function onEnter(zone) {
zone._nesting++;
if (zone.isStable) {
zone.isStable = false;
zone.onUnstable.emit(null);
}
}
/**
* @param {?} zone
* @return {?}
*/
function onLeave(zone) {
zone._nesting--;
checkStable(zone);
}
/**
* Provides a noop implementation of `NgZone` which does nothing. This zone requires explicit calls
* to framework to perform rendering.
*/
class NoopNgZone {
constructor() {
this.hasPendingMicrotasks = false;
this.hasPendingMacrotasks = false;
this.isStable = true;
this.onUnstable = new EventEmitter();
this.onMicrotaskEmpty = new EventEmitter();
this.onStable = new EventEmitter();
this.onError = new EventEmitter();
}
/**
* @param {?} fn
* @param {?=} applyThis
* @param {?=} applyArgs
* @return {?}
*/
run(fn, applyThis, applyArgs) {
return fn.apply(applyThis, applyArgs);
}
/**
* @param {?} fn
* @param {?=} applyThis
* @param {?=} applyArgs
* @return {?}
*/
runGuarded(fn, applyThis, applyArgs) {
return fn.apply(applyThis, applyArgs);
}
/**
* @param {?} fn
* @return {?}
*/
runOutsideAngular(fn) {
return fn();
}
/**
* @param {?} fn
* @param {?=} applyThis
* @param {?=} applyArgs
* @param {?=} name
* @return {?}
*/
runTask(fn, applyThis, applyArgs, name) {
return fn.apply(applyThis, applyArgs);
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/testability/testability.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @record
*/
function PendingMacrotask() { }
if (false) {}
/**
* @record
*/
function TaskData() { }
if (false) {}
/**
* @record
*/
function WaitCallback() { }
if (false) {}
/**
* The Testability service provides testing hooks that can be accessed from
* the browser and by services such as Protractor. Each bootstrapped Angular
* application on the page will have an instance of Testability.
* \@publicApi
*/
class Testability {
/**
* @param {?} _ngZone
*/
constructor(_ngZone) {
this._ngZone = _ngZone;
this._pendingCount = 0;
this._isZoneStable = true;
/**
* Whether any work was done since the last 'whenStable' callback. This is
* useful to detect if this could have potentially destabilized another
* component while it is stabilizing.
* \@internal
*/
this._didWork = false;
this._callbacks = [];
this.taskTrackingZone = null;
this._watchAngularEvents();
_ngZone.run((/**
* @return {?}
*/
() => {
this.taskTrackingZone =
typeof Zone == 'undefined' ? null : Zone.current.get('TaskTrackingZone');
}));
}
/**
* @private
* @return {?}
*/
_watchAngularEvents() {
this._ngZone.onUnstable.subscribe({
next: (/**
* @return {?}
*/
() => {
this._didWork = true;
this._isZoneStable = false;
})
});
this._ngZone.runOutsideAngular((/**
* @return {?}
*/
() => {
this._ngZone.onStable.subscribe({
next: (/**
* @return {?}
*/
() => {
NgZone.assertNotInAngularZone();
scheduleMicroTask((/**
* @return {?}
*/
() => {
this._isZoneStable = true;
this._runCallbacksIfReady();
}));
})
});
}));
}
/**
* Increases the number of pending request
* @deprecated pending requests are now tracked with zones.
* @return {?}
*/
increasePendingRequestCount() {
this._pendingCount += 1;
this._didWork = true;
return this._pendingCount;
}
/**
* Decreases the number of pending request
* @deprecated pending requests are now tracked with zones
* @return {?}
*/
decreasePendingRequestCount() {
this._pendingCount -= 1;
if (this._pendingCount < 0) {
throw new Error('pending async requests below zero');
}
this._runCallbacksIfReady();
return this._pendingCount;
}
/**
* Whether an associated application is stable
* @return {?}
*/
isStable() {
return this._isZoneStable && this._pendingCount === 0 && !this._ngZone.hasPendingMacrotasks;
}
/**
* @private
* @return {?}
*/
_runCallbacksIfReady() {
if (this.isStable()) {
// Schedules the call backs in a new frame so that it is always async.
scheduleMicroTask((/**
* @return {?}
*/
() => {
while (this._callbacks.length !== 0) {
/** @type {?} */
let cb = (/** @type {?} */ (this._callbacks.pop()));
clearTimeout(cb.timeoutId);
cb.doneCb(this._didWork);
}
this._didWork = false;
}));
}
else {
// Still not stable, send updates.
/** @type {?} */
let pending = this.getPendingTasks();
this._callbacks = this._callbacks.filter((/**
* @param {?} cb
* @return {?}
*/
(cb) => {
if (cb.updateCb && cb.updateCb(pending)) {
clearTimeout(cb.timeoutId);
return false;
}
return true;
}));
this._didWork = true;
}
}
/**
* @private
* @return {?}
*/
getPendingTasks() {
if (!this.taskTrackingZone) {
return [];
}
// Copy the tasks data so that we don't leak tasks.
return this.taskTrackingZone.macroTasks.map((/**
* @param {?} t
* @return {?}
*/
(t) => {
return {
source: t.source,
// From TaskTrackingZone:
// https://github.com/angular/zone.js/blob/master/lib/zone-spec/task-tracking.ts#L40
creationLocation: (/** @type {?} */ (((/** @type {?} */ (t))).creationLocation)),
data: t.data
};
}));
}
/**
* @private
* @param {?} cb
* @param {?=} timeout
* @param {?=} updateCb
* @return {?}
*/
addCallback(cb, timeout, updateCb) {
/** @type {?} */
let timeoutId = -1;
if (timeout && timeout > 0) {
timeoutId = setTimeout((/**
* @return {?}
*/
() => {
this._callbacks = this._callbacks.filter((/**
* @param {?} cb
* @return {?}
*/
(cb) => cb.timeoutId !== timeoutId));
cb(this._didWork, this.getPendingTasks());
}), timeout);
}
this._callbacks.push((/** @type {?} */ ({ doneCb: cb, timeoutId: timeoutId, updateCb: updateCb })));
}
/**
* Wait for the application to be stable with a timeout. If the timeout is reached before that
* happens, the callback receives a list of the macro tasks that were pending, otherwise null.
*
* @param {?} doneCb The callback to invoke when Angular is stable or the timeout expires
* whichever comes first.
* @param {?=} timeout Optional. The maximum time to wait for Angular to become stable. If not
* specified, whenStable() will wait forever.
* @param {?=} updateCb Optional. If specified, this callback will be invoked whenever the set of
* pending macrotasks changes. If this callback returns true doneCb will not be invoked
* and no further updates will be issued.
* @return {?}
*/
whenStable(doneCb, timeout, updateCb) {
if (updateCb && !this.taskTrackingZone) {
throw new Error('Task tracking zone is required when passing an update callback to ' +
'whenStable(). Is "zone.js/dist/task-tracking.js" loaded?');
}
// These arguments are 'Function' above to keep the public API simple.
this.addCallback((/** @type {?} */ (doneCb)), timeout, (/** @type {?} */ (updateCb)));
this._runCallbacksIfReady();
}
/**
* Get the number of pending requests
* @deprecated pending requests are now tracked with zones
* @return {?}
*/
getPendingRequestCount() {
return this._pendingCount;
}
/**
* Find providers by name
* @param {?} using The root element to search from
* @param {?} provider The name of binding variable
* @param {?} exactMatch Whether using exactMatch
* @return {?}
*/
findProviders(using, provider, exactMatch) {
// TODO(juliemr): implement.
return [];
}
}
Testability.ɵfac = function Testability_Factory(t) { return new (t || Testability)(ɵɵinject(NgZone)); };
Testability.ɵprov = ɵɵdefineInjectable({ token: Testability, factory: Testability.ɵfac });
/** @nocollapse */
Testability.ctorParameters = () => [
{ type: NgZone }
];
/*@__PURE__*/ (function () { setClassMetadata(Testability, [{
type: Injectable
}], function () { return [{ type: NgZone }]; }, null); })();
if (false) {}
/**
* A global registry of {\@link Testability} instances for specific elements.
* \@publicApi
*/
class TestabilityRegistry {
constructor() {
/**
* \@internal
*/
this._applications = new Map();
_testabilityGetter.addToWindow(this);
}
/**
* Registers an application with a testability hook so that it can be tracked
* @param {?} token token of application, root element
* @param {?} testability Testability hook
* @return {?}
*/
registerApplication(token, testability) {
this._applications.set(token, testability);
}
/**
* Unregisters an application.
* @param {?} token token of application, root element
* @return {?}
*/
unregisterApplication(token) {
this._applications.delete(token);
}
/**
* Unregisters all applications
* @return {?}
*/
unregisterAllApplications() {
this._applications.clear();
}
/**
* Get a testability hook associated with the application
* @param {?} elem root element
* @return {?}
*/
getTestability(elem) {
return this._applications.get(elem) || null;
}
/**
* Get all registered testabilities
* @return {?}
*/
getAllTestabilities() {
return Array.from(this._applications.values());
}
/**
* Get all registered applications(root elements)
* @return {?}
*/
getAllRootElements() {
return Array.from(this._applications.keys());
}
/**
* Find testability of a node in the Tree
* @param {?} elem node
* @param {?=} findInAncestors whether finding testability in ancestors if testability was not found in
* current node
* @return {?}
*/
findTestabilityInTree(elem, findInAncestors = true) {
return _testabilityGetter.findTestabilityInTree(this, elem, findInAncestors);
}
}
TestabilityRegistry.ɵfac = function TestabilityRegistry_Factory(t) { return new (t || TestabilityRegistry)(); };
TestabilityRegistry.ɵprov = ɵɵdefineInjectable({ token: TestabilityRegistry, factory: TestabilityRegistry.ɵfac });
/** @nocollapse */
TestabilityRegistry.ctorParameters = () => [];
/*@__PURE__*/ (function () { setClassMetadata(TestabilityRegistry, [{
type: Injectable
}], function () { return []; }, null); })();
if (false) {}
/**
* Adapter interface for retrieving the `Testability` service associated for a
* particular context.
*
* \@publicApi
* @record
*/
function GetTestability() { }
if (false) {}
class _NoopGetTestability {
/**
* @param {?} registry
* @return {?}
*/
addToWindow(registry) { }
/**
* @param {?} registry
* @param {?} elem
* @param {?} findInAncestors
* @return {?}
*/
findTestabilityInTree(registry, elem, findInAncestors) {
return null;
}
}
/**
* Set the {\@link GetTestability} implementation used by the Angular testing framework.
* \@publicApi
* @param {?} getter
* @return {?}
*/
function setTestabilityGetter(getter) {
_testabilityGetter = getter;
}
/** @type {?} */
let _testabilityGetter = new _NoopGetTestability();
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/application_ref.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
let _platform;
/** @type {?} */
let compileNgModuleFactory = compileNgModuleFactory__POST_R3__;
/**
* @template M
* @param {?} injector
* @param {?} options
* @param {?} moduleType
* @return {?}
*/
function compileNgModuleFactory__PRE_R3__(injector, options, moduleType) {
/** @type {?} */
const compilerFactory = injector.get(CompilerFactory);
/** @type {?} */
const compiler = compilerFactory.createCompiler([options]);
return compiler.compileModuleAsync(moduleType);
}
/**
* @template M
* @param {?} injector
* @param {?} options
* @param {?} moduleType
* @return {?}
*/
function compileNgModuleFactory__POST_R3__(injector, options, moduleType) {
ngDevMode && assertNgModuleType(moduleType);
/** @type {?} */
const compilerOptions = injector.get(COMPILER_OPTIONS, []).concat(options);
if (typeof ngJitMode === 'undefined' || ngJitMode) {
// Configure the compiler to use the provided options. This call may fail when multiple modules
// are bootstrapped with incompatible options, as a component can only be compiled according to
// a single set of options.
setJitOptions({
defaultEncapsulation: _lastDefined(compilerOptions.map((/**
* @param {?} options
* @return {?}
*/
options => options.defaultEncapsulation))),
preserveWhitespaces: _lastDefined(compilerOptions.map((/**
* @param {?} options
* @return {?}
*/
options => options.preserveWhitespaces))),
});
}
/** @type {?} */
const moduleFactory = new NgModuleFactory$1(moduleType);
if (isComponentResourceResolutionQueueEmpty()) {
return Promise.resolve(moduleFactory);
}
/** @type {?} */
const compilerProviders = _mergeArrays(compilerOptions.map((/**
* @param {?} o
* @return {?}
*/
o => (/** @type {?} */ (o.providers)))));
// In case there are no compiler providers, we just return the module factory as
// there won't be any resource loader. This can happen with Ivy, because AOT compiled
// modules can be still passed through "bootstrapModule". In that case we shouldn't
// unnecessarily require the JIT compiler.
if (compilerProviders.length === 0) {
return Promise.resolve(moduleFactory);
}
/** @type {?} */
const compiler = getCompilerFacade();
/** @type {?} */
const compilerInjector = Injector.create({ providers: compilerProviders });
/** @type {?} */
const resourceLoader = compilerInjector.get(compiler.ResourceLoader);
// The resource loader can also return a string while the "resolveComponentResources"
// always expects a promise. Therefore we need to wrap the returned value in a promise.
return resolveComponentResources((/**
* @param {?} url
* @return {?}
*/
url => Promise.resolve(resourceLoader.get(url))))
.then((/**
* @return {?}
*/
() => moduleFactory));
}
// the `window.ng` global utilities are only available in non-VE versions of
// Angular. The function switch below will make sure that the code is not
// included into Angular when PRE mode is active.
/**
* @return {?}
*/
function publishDefaultGlobalUtils__PRE_R3__() { }
/**
* @return {?}
*/
function publishDefaultGlobalUtils__POST_R3__() {
ngDevMode && publishDefaultGlobalUtils();
}
/** @type {?} */
let publishDefaultGlobalUtils$1 = publishDefaultGlobalUtils__POST_R3__;
/** @type {?} */
let isBoundToModule = isBoundToModule__POST_R3__;
/**
* @template C
* @param {?} cf
* @return {?}
*/
function isBoundToModule__PRE_R3__(cf) {
return cf instanceof ComponentFactoryBoundToModule;
}
/**
* @template C
* @param {?} cf
* @return {?}
*/
function isBoundToModule__POST_R3__(cf) {
return ((/** @type {?} */ (cf))).isBoundToModule;
}
/** @type {?} */
const ALLOW_MULTIPLE_PLATFORMS = new InjectionToken('AllowMultipleToken');
/**
* A token for third-party components that can register themselves with NgProbe.
*
* \@publicApi
*/
class NgProbeToken {
/**
* @param {?} name
* @param {?} token
*/
constructor(name, token) {
this.name = name;
this.token = token;
}
}
if (false) {}
/**
* Creates a platform.
* Platforms have to be eagerly created via this function.
*
* \@publicApi
* @param {?} injector
* @return {?}
*/
function createPlatform(injector) {
if (_platform && !_platform.destroyed &&
!_platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
throw new Error('There can be only one platform. Destroy the previous one to create a new one.');
}
publishDefaultGlobalUtils$1();
_platform = injector.get(PlatformRef);
/** @type {?} */
const inits = injector.get(PLATFORM_INITIALIZER, null);
if (inits)
inits.forEach((/**
* @param {?} init
* @return {?}
*/
(init) => init()));
return _platform;
}
/**
* Creates a factory for a platform
*
* \@publicApi
* @param {?} parentPlatformFactory
* @param {?} name
* @param {?=} providers
* @return {?}
*/
function createPlatformFactory(parentPlatformFactory, name, providers = []) {
/** @type {?} */
const desc = `Platform: ${name}`;
/** @type {?} */
const marker = new InjectionToken(desc);
return (/**
* @param {?=} extraProviders
* @return {?}
*/
(extraProviders = []) => {
/** @type {?} */
let platform = getPlatform();
if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
if (parentPlatformFactory) {
parentPlatformFactory(providers.concat(extraProviders).concat({ provide: marker, useValue: true }));
}
else {
/** @type {?} */
const injectedProviders = providers.concat(extraProviders).concat({ provide: marker, useValue: true }, {
provide: INJECTOR_SCOPE,
useValue: 'platform'
});
createPlatform(Injector.create({ providers: injectedProviders, name: desc }));
}
}
return assertPlatform(marker);
});
}
/**
* Checks that there currently is a platform which contains the given token as a provider.
*
* \@publicApi
* @param {?} requiredToken
* @return {?}
*/
function assertPlatform(requiredToken) {
/** @type {?} */
const platform = getPlatform();
if (!platform) {
throw new Error('No platform exists!');
}
if (!platform.injector.get(requiredToken, null)) {
throw new Error('A platform with a different configuration has been created. Please destroy it first.');
}
return platform;
}
/**
* Destroy the existing platform.
*
* \@publicApi
* @return {?}
*/
function destroyPlatform() {
if (_platform && !_platform.destroyed) {
_platform.destroy();
}
}
/**
* Returns the current platform.
*
* \@publicApi
* @return {?}
*/
function getPlatform() {
return _platform && !_platform.destroyed ? _platform : null;
}
/**
* Provides additional options to the bootstraping process.
*
*
* @record
*/
function BootstrapOptions() { }
if (false) {}
/**
* The Angular platform is the entry point for Angular on a web page. Each page
* has exactly one platform, and services (such as reflection) which are common
* to every Angular application running on the page are bound in its scope.
*
* A page's platform is initialized implicitly when a platform is created via a platform factory
* (e.g. {\@link platformBrowser}), or explicitly by calling the {\@link createPlatform} function.
*
* \@publicApi
*/
class PlatformRef {
/**
* \@internal
* @param {?} _injector
*/
constructor(_injector) {
this._injector = _injector;
this._modules = [];
this._destroyListeners = [];
this._destroyed = false;
}
/**
* Creates an instance of an `\@NgModule` for the given platform
* for offline compilation.
*
* \@usageNotes
* ### Simple Example
*
* ```typescript
* my_module.ts:
*
* \@NgModule({
* imports: [BrowserModule]
* })
* class MyModule {}
*
* main.ts:
* import {MyModuleNgFactory} from './my_module.ngfactory';
* import {platformBrowser} from '\@angular/platform-browser';
*
* let moduleRef = platformBrowser().bootstrapModuleFactory(MyModuleNgFactory);
* ```
* @template M
* @param {?} moduleFactory
* @param {?=} options
* @return {?}
*/
bootstrapModuleFactory(moduleFactory, options) {
// Note: We need to create the NgZone _before_ we instantiate the module,
// as instantiating the module creates some providers eagerly.
// So we create a mini parent injector that just contains the new NgZone and
// pass that as parent to the NgModuleFactory.
/** @type {?} */
const ngZoneOption = options ? options.ngZone : undefined;
/** @type {?} */
const ngZoneEventCoalescing = (options && options.ngZoneEventCoalescing) || false;
/** @type {?} */
const ngZone = getNgZone(ngZoneOption, ngZoneEventCoalescing);
/** @type {?} */
const providers = [{ provide: NgZone, useValue: ngZone }];
// Attention: Don't use ApplicationRef.run here,
// as we want to be sure that all possible constructor calls are inside `ngZone.run`!
return ngZone.run((/**
* @return {?}
*/
() => {
/** @type {?} */
const ngZoneInjector = Injector.create({ providers: providers, parent: this.injector, name: moduleFactory.moduleType.name });
/** @type {?} */
const moduleRef = (/** @type {?} */ (moduleFactory.create(ngZoneInjector)));
/** @type {?} */
const exceptionHandler = moduleRef.injector.get(ErrorHandler, null);
if (!exceptionHandler) {
throw new Error('No ErrorHandler. Is platform module (BrowserModule) included?');
}
moduleRef.onDestroy((/**
* @return {?}
*/
() => remove(this._modules, moduleRef)));
(/** @type {?} */ (ngZone)).runOutsideAngular((/**
* @return {?}
*/
() => (/** @type {?} */ (ngZone)).onError.subscribe({
next: (/**
* @param {?} error
* @return {?}
*/
(error) => {
exceptionHandler.handleError(error);
})
})));
return _callAndReportToErrorHandler(exceptionHandler, (/** @type {?} */ (ngZone)), (/**
* @return {?}
*/
() => {
/** @type {?} */
const initStatus = moduleRef.injector.get(ApplicationInitStatus);
initStatus.runInitializers();
return initStatus.donePromise.then((/**
* @return {?}
*/
() => {
if (ivyEnabled) {
// If the `LOCALE_ID` provider is defined at bootstrap then we set the value for ivy
/** @type {?} */
const localeId = moduleRef.injector.get(LOCALE_ID$1, DEFAULT_LOCALE_ID);
setLocaleId(localeId || DEFAULT_LOCALE_ID);
}
this._moduleDoBootstrap(moduleRef);
return moduleRef;
}));
}));
}));
}
/**
* Creates an instance of an `\@NgModule` for a given platform using the given runtime compiler.
*
* \@usageNotes
* ### Simple Example
*
* ```typescript
* \@NgModule({
* imports: [BrowserModule]
* })
* class MyModule {}
*
* let moduleRef = platformBrowser().bootstrapModule(MyModule);
* ```
*
* @template M
* @param {?} moduleType
* @param {?=} compilerOptions
* @return {?}
*/
bootstrapModule(moduleType, compilerOptions = []) {
/** @type {?} */
const options = optionsReducer({}, compilerOptions);
return compileNgModuleFactory(this.injector, options, moduleType)
.then((/**
* @param {?} moduleFactory
* @return {?}
*/
moduleFactory => this.bootstrapModuleFactory(moduleFactory, options)));
}
/**
* @private
* @param {?} moduleRef
* @return {?}
*/
_moduleDoBootstrap(moduleRef) {
/** @type {?} */
const appRef = (/** @type {?} */ (moduleRef.injector.get(ApplicationRef)));
if (moduleRef._bootstrapComponents.length > 0) {
moduleRef._bootstrapComponents.forEach((/**
* @param {?} f
* @return {?}
*/
f => appRef.bootstrap(f)));
}
else if (moduleRef.instance.ngDoBootstrap) {
moduleRef.instance.ngDoBootstrap(appRef);
}
else {
throw new Error(`The module ${stringify(moduleRef.instance
.constructor)} was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. ` +
`Please define one of these.`);
}
this._modules.push(moduleRef);
}
/**
* Register a listener to be called when the platform is disposed.
* @param {?} callback
* @return {?}
*/
onDestroy(callback) {
this._destroyListeners.push(callback);
}
/**
* Retrieve the platform {\@link Injector}, which is the parent injector for
* every Angular application on the page and provides singleton providers.
* @return {?}
*/
get injector() {
return this._injector;
}
/**
* Destroy the Angular platform and all Angular applications on the page.
* @return {?}
*/
destroy() {
if (this._destroyed) {
throw new Error('The platform has already been destroyed!');
}
this._modules.slice().forEach((/**
* @param {?} module
* @return {?}
*/
module => module.destroy()));
this._destroyListeners.forEach((/**
* @param {?} listener
* @return {?}
*/
listener => listener()));
this._destroyed = true;
}
/**
* @return {?}
*/
get destroyed() {
return this._destroyed;
}
}
PlatformRef.ɵfac = function PlatformRef_Factory(t) { return new (t || PlatformRef)(ɵɵinject(Injector)); };
PlatformRef.ɵprov = ɵɵdefineInjectable({ token: PlatformRef, factory: PlatformRef.ɵfac });
/** @nocollapse */
PlatformRef.ctorParameters = () => [
{ type: Injector }
];
/*@__PURE__*/ (function () { setClassMetadata(PlatformRef, [{
type: Injectable
}], function () { return [{ type: Injector }]; }, null); })();
if (false) {}
/**
* @param {?} ngZoneOption
* @param {?} ngZoneEventCoalescing
* @return {?}
*/
function getNgZone(ngZoneOption, ngZoneEventCoalescing) {
/** @type {?} */
let ngZone;
if (ngZoneOption === 'noop') {
ngZone = new NoopNgZone();
}
else {
ngZone = (ngZoneOption === 'zone.js' ? undefined : ngZoneOption) || new NgZone({
enableLongStackTrace: isDevMode(),
shouldCoalesceEventChangeDetection: ngZoneEventCoalescing
});
}
return ngZone;
}
/**
* @param {?} errorHandler
* @param {?} ngZone
* @param {?} callback
* @return {?}
*/
function _callAndReportToErrorHandler(errorHandler, ngZone, callback) {
try {
/** @type {?} */
const result = callback();
if (isPromise(result)) {
return result.catch((/**
* @param {?} e
* @return {?}
*/
(e) => {
ngZone.runOutsideAngular((/**
* @return {?}
*/
() => errorHandler.handleError(e)));
// rethrow as the exception handler might not do it
throw e;
}));
}
return result;
}
catch (e) {
ngZone.runOutsideAngular((/**
* @return {?}
*/
() => errorHandler.handleError(e)));
// rethrow as the exception handler might not do it
throw e;
}
}
/**
* @template T
* @param {?} dst
* @param {?} objs
* @return {?}
*/
function optionsReducer(dst, objs) {
if (Array.isArray(objs)) {
dst = objs.reduce(optionsReducer, dst);
}
else {
dst = Object.assign(Object.assign({}, dst), ((/** @type {?} */ (objs))));
}
return dst;
}
/**
* A reference to an Angular application running on a page.
*
* \@usageNotes
*
* {\@a is-stable-examples}
* ### isStable examples and caveats
*
* Note two important points about `isStable`, demonstrated in the examples below:
* - the application will never be stable if you start any kind
* of recurrent asynchronous task when the application starts
* (for example for a polling process, started with a `setInterval`, a `setTimeout`
* or using RxJS operators like `interval`);
* - the `isStable` Observable runs outside of the Angular zone.
*
* Let's imagine that you start a recurrent task
* (here incrementing a counter, using RxJS `interval`),
* and at the same time subscribe to `isStable`.
*
* ```
* constructor(appRef: ApplicationRef) {
* appRef.isStable.pipe(
* filter(stable => stable)
* ).subscribe(() => console.log('App is stable now');
* interval(1000).subscribe(counter => console.log(counter));
* }
* ```
* In this example, `isStable` will never emit `true`,
* and the trace "App is stable now" will never get logged.
*
* If you want to execute something when the app is stable,
* you have to wait for the application to be stable
* before starting your polling process.
*
* ```
* constructor(appRef: ApplicationRef) {
* appRef.isStable.pipe(
* first(stable => stable),
* tap(stable => console.log('App is stable now')),
* switchMap(() => interval(1000))
* ).subscribe(counter => console.log(counter));
* }
* ```
* In this example, the trace "App is stable now" will be logged
* and then the counter starts incrementing every second.
*
* Note also that this Observable runs outside of the Angular zone,
* which means that the code in the subscription
* to this Observable will not trigger the change detection.
*
* Let's imagine that instead of logging the counter value,
* you update a field of your component
* and display it in its template.
*
* ```
* constructor(appRef: ApplicationRef) {
* appRef.isStable.pipe(
* first(stable => stable),
* switchMap(() => interval(1000))
* ).subscribe(counter => this.value = counter);
* }
* ```
* As the `isStable` Observable runs outside the zone,
* the `value` field will be updated properly,
* but the template will not be refreshed!
*
* You'll have to manually trigger the change detection to update the template.
*
* ```
* constructor(appRef: ApplicationRef, cd: ChangeDetectorRef) {
* appRef.isStable.pipe(
* first(stable => stable),
* switchMap(() => interval(1000))
* ).subscribe(counter => {
* this.value = counter;
* cd.detectChanges();
* });
* }
* ```
*
* Or make the subscription callback run inside the zone.
*
* ```
* constructor(appRef: ApplicationRef, zone: NgZone) {
* appRef.isStable.pipe(
* first(stable => stable),
* switchMap(() => interval(1000))
* ).subscribe(counter => zone.run(() => this.value = counter));
* }
* ```
*
* \@publicApi
*/
class ApplicationRef {
/**
* \@internal
* @param {?} _zone
* @param {?} _console
* @param {?} _injector
* @param {?} _exceptionHandler
* @param {?} _componentFactoryResolver
* @param {?} _initStatus
*/
constructor(_zone, _console, _injector, _exceptionHandler, _componentFactoryResolver, _initStatus) {
this._zone = _zone;
this._console = _console;
this._injector = _injector;
this._exceptionHandler = _exceptionHandler;
this._componentFactoryResolver = _componentFactoryResolver;
this._initStatus = _initStatus;
/**
* \@internal
*/
this._bootstrapListeners = [];
this._views = [];
this._runningTick = false;
this._enforceNoNewChanges = false;
this._stable = true;
/**
* Get a list of component types registered to this application.
* This list is populated even before the component is created.
*/
this.componentTypes = [];
/**
* Get a list of components registered to this application.
*/
this.components = [];
this._enforceNoNewChanges = isDevMode();
this._zone.onMicrotaskEmpty.subscribe({
next: (/**
* @return {?}
*/
() => {
this._zone.run((/**
* @return {?}
*/
() => {
this.tick();
}));
})
});
/** @type {?} */
const isCurrentlyStable = new rxjs__WEBPACK_IMPORTED_MODULE_0__["Observable"]((/**
* @param {?} observer
* @return {?}
*/
(observer) => {
this._stable = this._zone.isStable && !this._zone.hasPendingMacrotasks &&
!this._zone.hasPendingMicrotasks;
this._zone.runOutsideAngular((/**
* @return {?}
*/
() => {
observer.next(this._stable);
observer.complete();
}));
}));
/** @type {?} */
const isStable = new rxjs__WEBPACK_IMPORTED_MODULE_0__["Observable"]((/**
* @param {?} observer
* @return {?}
*/
(observer) => {
// Create the subscription to onStable outside the Angular Zone so that
// the callback is run outside the Angular Zone.
/** @type {?} */
let stableSub;
this._zone.runOutsideAngular((/**
* @return {?}
*/
() => {
stableSub = this._zone.onStable.subscribe((/**
* @return {?}
*/
() => {
NgZone.assertNotInAngularZone();
// Check whether there are no pending macro/micro tasks in the next tick
// to allow for NgZone to update the state.
scheduleMicroTask((/**
* @return {?}
*/
() => {
if (!this._stable && !this._zone.hasPendingMacrotasks &&
!this._zone.hasPendingMicrotasks) {
this._stable = true;
observer.next(true);
}
}));
}));
}));
/** @type {?} */
const unstableSub = this._zone.onUnstable.subscribe((/**
* @return {?}
*/
() => {
NgZone.assertInAngularZone();
if (this._stable) {
this._stable = false;
this._zone.runOutsideAngular((/**
* @return {?}
*/
() => {
observer.next(false);
}));
}
}));
return (/**
* @return {?}
*/
() => {
stableSub.unsubscribe();
unstableSub.unsubscribe();
});
}));
((/** @type {?} */ (this))).isStable =
Object(rxjs__WEBPACK_IMPORTED_MODULE_0__["merge"])(isCurrentlyStable, isStable.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_1__["share"])()));
}
/**
* Bootstrap a new component at the root level of the application.
*
* \@usageNotes
* ### Bootstrap process
*
* When bootstrapping a new root component into an application, Angular mounts the
* specified application component onto DOM elements identified by the componentType's
* selector and kicks off automatic change detection to finish initializing the component.
*
* Optionally, a component can be mounted onto a DOM element that does not match the
* componentType's selector.
*
* ### Example
* {\@example core/ts/platform/platform.ts region='longform'}
* @template C
* @param {?} componentOrFactory
* @param {?=} rootSelectorOrNode
* @return {?}
*/
bootstrap(componentOrFactory, rootSelectorOrNode) {
if (!this._initStatus.done) {
throw new Error('Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.');
}
/** @type {?} */
let componentFactory;
if (componentOrFactory instanceof ComponentFactory) {
componentFactory = componentOrFactory;
}
else {
componentFactory =
(/** @type {?} */ (this._componentFactoryResolver.resolveComponentFactory(componentOrFactory)));
}
this.componentTypes.push(componentFactory.componentType);
// Create a factory associated with the current module if it's not bound to some other
/** @type {?} */
const ngModule = isBoundToModule(componentFactory) ? undefined : this._injector.get(NgModuleRef);
/** @type {?} */
const selectorOrNode = rootSelectorOrNode || componentFactory.selector;
/** @type {?} */
const compRef = componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
compRef.onDestroy((/**
* @return {?}
*/
() => {
this._unloadComponent(compRef);
}));
/** @type {?} */
const testability = compRef.injector.get(Testability, null);
if (testability) {
compRef.injector.get(TestabilityRegistry)
.registerApplication(compRef.location.nativeElement, testability);
}
this._loadComponent(compRef);
if (isDevMode()) {
this._console.log(`Angular is running in the development mode. Call enableProdMode() to enable the production mode.`);
}
return compRef;
}
/**
* Invoke this method to explicitly process change detection and its side-effects.
*
* In development mode, `tick()` also performs a second change detection cycle to ensure that no
* further changes are detected. If additional changes are picked up during this second cycle,
* bindings in the app have side-effects that cannot be resolved in a single change detection
* pass.
* In this case, Angular throws an error, since an Angular application can only have one change
* detection pass during which all change detection must complete.
* @return {?}
*/
tick() {
if (this._runningTick) {
throw new Error('ApplicationRef.tick is called recursively');
}
try {
this._runningTick = true;
for (let view of this._views) {
view.detectChanges();
}
if (this._enforceNoNewChanges) {
for (let view of this._views) {
view.checkNoChanges();
}
}
}
catch (e) {
// Attention: Don't rethrow as it could cancel subscriptions to Observables!
this._zone.runOutsideAngular((/**
* @return {?}
*/
() => this._exceptionHandler.handleError(e)));
}
finally {
this._runningTick = false;
}
}
/**
* Attaches a view so that it will be dirty checked.
* The view will be automatically detached when it is destroyed.
* This will throw if the view is already attached to a ViewContainer.
* @param {?} viewRef
* @return {?}
*/
attachView(viewRef) {
/** @type {?} */
const view = ((/** @type {?} */ (viewRef)));
this._views.push(view);
view.attachToAppRef(this);
}
/**
* Detaches a view from dirty checking again.
* @param {?} viewRef
* @return {?}
*/
detachView(viewRef) {
/** @type {?} */
const view = ((/** @type {?} */ (viewRef)));
remove(this._views, view);
view.detachFromAppRef();
}
/**
* @private
* @param {?} componentRef
* @return {?}
*/
_loadComponent(componentRef) {
this.attachView(componentRef.hostView);
this.tick();
this.components.push(componentRef);
// Get the listeners lazily to prevent DI cycles.
/** @type {?} */
const listeners = this._injector.get(APP_BOOTSTRAP_LISTENER, []).concat(this._bootstrapListeners);
listeners.forEach((/**
* @param {?} listener
* @return {?}
*/
(listener) => listener(componentRef)));
}
/**
* @private
* @param {?} componentRef
* @return {?}
*/
_unloadComponent(componentRef) {
this.detachView(componentRef.hostView);
remove(this.components, componentRef);
}
/**
* \@internal
* @return {?}
*/
ngOnDestroy() {
// TODO(alxhub): Dispose of the NgZone.
this._views.slice().forEach((/**
* @param {?} view
* @return {?}
*/
(view) => view.destroy()));
}
/**
* Returns the number of attached views.
* @return {?}
*/
get viewCount() {
return this._views.length;
}
}
ApplicationRef.ɵfac = function ApplicationRef_Factory(t) { return new (t || ApplicationRef)(ɵɵinject(NgZone), ɵɵinject(Console), ɵɵinject(Injector), ɵɵinject(ErrorHandler), ɵɵinject(ComponentFactoryResolver), ɵɵinject(ApplicationInitStatus)); };
ApplicationRef.ɵprov = ɵɵdefineInjectable({ token: ApplicationRef, factory: ApplicationRef.ɵfac });
/** @nocollapse */
ApplicationRef.ctorParameters = () => [
{ type: NgZone },
{ type: Console },
{ type: Injector },
{ type: ErrorHandler },
{ type: ComponentFactoryResolver },
{ type: ApplicationInitStatus }
];
/*@__PURE__*/ (function () { setClassMetadata(ApplicationRef, [{
type: Injectable
}], function () { return [{ type: NgZone }, { type: Console }, { type: Injector }, { type: ErrorHandler }, { type: ComponentFactoryResolver }, { type: ApplicationInitStatus }]; }, null); })();
if (false) {}
/**
* @template T
* @param {?} list
* @param {?} el
* @return {?}
*/
function remove(list, el) {
/** @type {?} */
const index = list.indexOf(el);
if (index > -1) {
list.splice(index, 1);
}
}
/**
* @template T
* @param {?} args
* @return {?}
*/
function _lastDefined(args) {
for (let i = args.length - 1; i >= 0; i--) {
if (args[i] !== undefined) {
return args[i];
}
}
return undefined;
}
/**
* @param {?} parts
* @return {?}
*/
function _mergeArrays(parts) {
/** @type {?} */
const result = [];
parts.forEach((/**
* @param {?} part
* @return {?}
*/
(part) => part && result.push(...part)));
return result;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/zone.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/render.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/ng_module_factory_loader.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Used to load ng module factories.
*
* \@publicApi
* @deprecated the `string` form of `loadChildren` is deprecated, and `NgModuleFactoryLoader` is
* part of its implementation. See `LoadChildren` for more details.
* @abstract
*/
class NgModuleFactoryLoader {
}
if (false) {}
/**
* @param {?} id
* @return {?}
*/
function getModuleFactory__PRE_R3__(id) {
/** @type {?} */
const factory = (/** @type {?} */ (getRegisteredNgModuleType(id)));
if (!factory)
throw noModuleError(id);
return factory;
}
/**
* @param {?} id
* @return {?}
*/
function getModuleFactory__POST_R3__(id) {
/** @type {?} */
const type = (/** @type {?} */ (getRegisteredNgModuleType(id)));
if (!type)
throw noModuleError(id);
return new NgModuleFactory$1(type);
}
/**
* Returns the NgModuleFactory with the given id, if it exists and has been loaded.
* Factories for modules that do not specify an `id` cannot be retrieved. Throws if the module
* cannot be found.
* \@publicApi
* @type {?}
*/
const getModuleFactory = getModuleFactory__POST_R3__;
/**
* @param {?} id
* @return {?}
*/
function noModuleError(id) {
return new Error(`No module with ID ${id} loaded`);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/system_js_ng_module_factory_loader.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const _SEPARATOR = '#';
/** @type {?} */
const FACTORY_CLASS_SUFFIX = 'NgFactory';
/**
* Configuration for SystemJsNgModuleLoader.
* token.
*
* \@publicApi
* @deprecated the `string` form of `loadChildren` is deprecated, and `SystemJsNgModuleLoaderConfig`
* is part of its implementation. See `LoadChildren` for more details.
* @abstract
*/
class SystemJsNgModuleLoaderConfig {
}
if (false) {}
/** @type {?} */
const DEFAULT_CONFIG = {
factoryPathPrefix: '',
factoryPathSuffix: '.ngfactory',
};
/**
* NgModuleFactoryLoader that uses SystemJS to load NgModuleFactory
* \@publicApi
* @deprecated the `string` form of `loadChildren` is deprecated, and `SystemJsNgModuleLoader` is
* part of its implementation. See `LoadChildren` for more details.
*/
class SystemJsNgModuleLoader {
/**
* @param {?} _compiler
* @param {?=} config
*/
constructor(_compiler, config) {
this._compiler = _compiler;
this._config = config || DEFAULT_CONFIG;
}
/**
* @param {?} path
* @return {?}
*/
load(path) {
/** @type {?} */
const legacyOfflineMode = !ivyEnabled && this._compiler instanceof Compiler;
return legacyOfflineMode ? this.loadFactory(path) : this.loadAndCompile(path);
}
/**
* @private
* @param {?} path
* @return {?}
*/
loadAndCompile(path) {
let [module, exportName] = path.split(_SEPARATOR);
if (exportName === undefined) {
exportName = 'default';
}
return __webpack_require__("./$$_lazy_route_resource lazy recursive")(module)
.then((/**
* @param {?} module
* @return {?}
*/
(module) => module[exportName]))
.then((/**
* @param {?} type
* @return {?}
*/
(type) => checkNotEmpty(type, module, exportName)))
.then((/**
* @param {?} type
* @return {?}
*/
(type) => this._compiler.compileModuleAsync(type)));
}
/**
* @private
* @param {?} path
* @return {?}
*/
loadFactory(path) {
let [module, exportName] = path.split(_SEPARATOR);
/** @type {?} */
let factoryClassSuffix = FACTORY_CLASS_SUFFIX;
if (exportName === undefined) {
exportName = 'default';
factoryClassSuffix = '';
}
return __webpack_require__("./$$_lazy_route_resource lazy recursive")(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)
.then((/**
* @param {?} module
* @return {?}
*/
(module) => module[exportName + factoryClassSuffix]))
.then((/**
* @param {?} factory
* @return {?}
*/
(factory) => checkNotEmpty(factory, module, exportName)));
}
}
SystemJsNgModuleLoader.ɵfac = function SystemJsNgModuleLoader_Factory(t) { return new (t || SystemJsNgModuleLoader)(ɵɵinject(Compiler), ɵɵinject(SystemJsNgModuleLoaderConfig, 8)); };
SystemJsNgModuleLoader.ɵprov = ɵɵdefineInjectable({ token: SystemJsNgModuleLoader, factory: SystemJsNgModuleLoader.ɵfac });
/** @nocollapse */
SystemJsNgModuleLoader.ctorParameters = () => [
{ type: Compiler },
{ type: SystemJsNgModuleLoaderConfig, decorators: [{ type: Optional }] }
];
/*@__PURE__*/ (function () { setClassMetadata(SystemJsNgModuleLoader, [{
type: Injectable
}], function () { return [{ type: Compiler }, { type: SystemJsNgModuleLoaderConfig, decorators: [{
type: Optional
}] }]; }, null); })();
if (false) {}
/**
* @param {?} value
* @param {?} modulePath
* @param {?} exportName
* @return {?}
*/
function checkNotEmpty(value, modulePath, exportName) {
if (!value) {
throw new Error(`Cannot find '${exportName}' in '${modulePath}'`);
}
return value;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker/view_ref.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Represents an Angular [view](guide/glossary#view),
* specifically the [host view](guide/glossary#view-tree) that is defined by a component.
* Also serves as the base class
* that adds destroy methods for [embedded views](guide/glossary#view-tree).
*
* @see `EmbeddedViewRef`
*
* \@publicApi
* @abstract
*/
class ViewRef$1 extends ChangeDetectorRef {
}
if (false) {}
/**
* Represents an Angular [view](guide/glossary#view) in a view container.
* An [embedded view](guide/glossary#view-tree) can be referenced from a component
* other than the hosting component whose template defines it, or it can be defined
* independently by a `TemplateRef`.
*
* Properties of elements in a view can change, but the structure (number and order) of elements in
* a view cannot. Change the structure of elements by inserting, moving, or
* removing nested views in a view container.
*
* @see `ViewContainerRef`
*
* \@usageNotes
*
* The following template breaks down into two separate `TemplateRef` instances,
* an outer one and an inner one.
*
* ```
* Count: {{items.length}}
* <ul>
* <li *ngFor="let item of items">{{item}}</li>
* </ul>
* ```
*
* This is the outer `TemplateRef`:
*
* ```
* Count: {{items.length}}
* <ul>
* <ng-template ngFor let-item [ngForOf]="items"></ng-template>
* </ul>
* ```
*
* This is the inner `TemplateRef`:
*
* ```
* <li>{{item}}</li>
* ```
*
* The outer and inner `TemplateRef` instances are assembled into views as follows:
*
* ```
* <!-- ViewRef: outer-0 -->
* Count: 2
* <ul>
* <ng-template view-container-ref></ng-template>
* <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
* <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
* </ul>
* <!-- /ViewRef: outer-0 -->
* ```
* \@publicApi
* @abstract
* @template C
*/
class EmbeddedViewRef extends ViewRef$1 {
}
if (false) {}
/**
* @record
*/
function InternalViewRef() { }
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/linker.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/debug/debug_node.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@publicApi
*/
class DebugEventListener {
/**
* @param {?} name
* @param {?} callback
*/
constructor(name, callback) {
this.name = name;
this.callback = callback;
}
}
if (false) {}
// WARNING: interface has both a type and a value, skipping emit
class DebugNode__PRE_R3__ {
/**
* @param {?} nativeNode
* @param {?} parent
* @param {?} _debugContext
*/
constructor(nativeNode, parent, _debugContext) {
this.listeners = [];
this.parent = null;
this._debugContext = _debugContext;
this.nativeNode = nativeNode;
if (parent && parent instanceof DebugElement__PRE_R3__) {
parent.addChild(this);
}
}
/**
* @return {?}
*/
get injector() {
return this._debugContext.injector;
}
/**
* @return {?}
*/
get componentInstance() {
return this._debugContext.component;
}
/**
* @return {?}
*/
get context() {
return this._debugContext.context;
}
/**
* @return {?}
*/
get references() {
return this._debugContext.references;
}
/**
* @return {?}
*/
get providerTokens() {
return this._debugContext.providerTokens;
}
}
if (false) {}
// WARNING: interface has both a type and a value, skipping emit
class DebugElement__PRE_R3__ extends DebugNode__PRE_R3__ {
/**
* @param {?} nativeNode
* @param {?} parent
* @param {?} _debugContext
*/
constructor(nativeNode, parent, _debugContext) {
super(nativeNode, parent, _debugContext);
this.properties = {};
this.attributes = {};
this.classes = {};
this.styles = {};
this.childNodes = [];
this.nativeElement = nativeNode;
}
/**
* @param {?} child
* @return {?}
*/
addChild(child) {
if (child) {
this.childNodes.push(child);
((/** @type {?} */ (child))).parent = this;
}
}
/**
* @param {?} child
* @return {?}
*/
removeChild(child) {
/** @type {?} */
const childIndex = this.childNodes.indexOf(child);
if (childIndex !== -1) {
((/** @type {?} */ (child))).parent = null;
this.childNodes.splice(childIndex, 1);
}
}
/**
* @param {?} child
* @param {?} newChildren
* @return {?}
*/
insertChildrenAfter(child, newChildren) {
/** @type {?} */
const siblingIndex = this.childNodes.indexOf(child);
if (siblingIndex !== -1) {
this.childNodes.splice(siblingIndex + 1, 0, ...newChildren);
newChildren.forEach((/**
* @param {?} c
* @return {?}
*/
c => {
if (c.parent) {
((/** @type {?} */ (c.parent))).removeChild(c);
}
((/** @type {?} */ (child))).parent = this;
}));
}
}
/**
* @param {?} refChild
* @param {?} newChild
* @return {?}
*/
insertBefore(refChild, newChild) {
/** @type {?} */
const refIndex = this.childNodes.indexOf(refChild);
if (refIndex === -1) {
this.addChild(newChild);
}
else {
if (newChild.parent) {
((/** @type {?} */ (newChild.parent))).removeChild(newChild);
}
((/** @type {?} */ (newChild))).parent = this;
this.childNodes.splice(refIndex, 0, newChild);
}
}
/**
* @param {?} predicate
* @return {?}
*/
query(predicate) {
/** @type {?} */
const results = this.queryAll(predicate);
return results[0] || null;
}
/**
* @param {?} predicate
* @return {?}
*/
queryAll(predicate) {
/** @type {?} */
const matches = [];
_queryElementChildren(this, predicate, matches);
return matches;
}
/**
* @param {?} predicate
* @return {?}
*/
queryAllNodes(predicate) {
/** @type {?} */
const matches = [];
_queryNodeChildren(this, predicate, matches);
return matches;
}
/**
* @return {?}
*/
get children() {
return (/** @type {?} */ (this.childNodes //
.filter((/**
* @param {?} node
* @return {?}
*/
(node) => node instanceof DebugElement__PRE_R3__))));
}
/**
* @param {?} eventName
* @param {?} eventObj
* @return {?}
*/
triggerEventHandler(eventName, eventObj) {
this.listeners.forEach((/**
* @param {?} listener
* @return {?}
*/
(listener) => {
if (listener.name == eventName) {
listener.callback(eventObj);
}
}));
}
}
if (false) {}
/**
* \@publicApi
* @param {?} debugEls
* @return {?}
*/
function asNativeElements(debugEls) {
return debugEls.map((/**
* @param {?} el
* @return {?}
*/
(el) => el.nativeElement));
}
/**
* @param {?} element
* @param {?} predicate
* @param {?} matches
* @return {?}
*/
function _queryElementChildren(element, predicate, matches) {
element.childNodes.forEach((/**
* @param {?} node
* @return {?}
*/
node => {
if (node instanceof DebugElement__PRE_R3__) {
if (predicate(node)) {
matches.push(node);
}
_queryElementChildren(node, predicate, matches);
}
}));
}
/**
* @param {?} parentNode
* @param {?} predicate
* @param {?} matches
* @return {?}
*/
function _queryNodeChildren(parentNode, predicate, matches) {
if (parentNode instanceof DebugElement__PRE_R3__) {
parentNode.childNodes.forEach((/**
* @param {?} node
* @return {?}
*/
node => {
if (predicate(node)) {
matches.push(node);
}
if (node instanceof DebugElement__PRE_R3__) {
_queryNodeChildren(node, predicate, matches);
}
}));
}
}
class DebugNode__POST_R3__ {
/**
* @param {?} nativeNode
*/
constructor(nativeNode) {
this.nativeNode = nativeNode;
}
/**
* @return {?}
*/
get parent() {
/** @type {?} */
const parent = (/** @type {?} */ (this.nativeNode.parentNode));
return parent ? new DebugElement__POST_R3__(parent) : null;
}
/**
* @return {?}
*/
get injector() {
return getInjector(this.nativeNode);
}
/**
* @return {?}
*/
get componentInstance() {
/** @type {?} */
const nativeElement = this.nativeNode;
return nativeElement &&
(getComponent((/** @type {?} */ (nativeElement))) || getOwningComponent(nativeElement));
}
/**
* @return {?}
*/
get context() {
return getComponent((/** @type {?} */ (this.nativeNode))) || getContext((/** @type {?} */ (this.nativeNode)));
}
/**
* @return {?}
*/
get listeners() {
return getListeners((/** @type {?} */ (this.nativeNode))).filter((/**
* @param {?} listener
* @return {?}
*/
listener => listener.type === 'dom'));
}
/**
* @return {?}
*/
get references() {
return getLocalRefs(this.nativeNode);
}
/**
* @return {?}
*/
get providerTokens() {
return getInjectionTokens((/** @type {?} */ (this.nativeNode)));
}
}
if (false) {}
class DebugElement__POST_R3__ extends DebugNode__POST_R3__ {
/**
* @param {?} nativeNode
*/
constructor(nativeNode) {
ngDevMode && assertDomNode(nativeNode);
super(nativeNode);
}
/**
* @return {?}
*/
get nativeElement() {
return this.nativeNode.nodeType == Node.ELEMENT_NODE ? (/** @type {?} */ (this.nativeNode)) : null;
}
/**
* @return {?}
*/
get name() {
try {
/** @type {?} */
const context = (/** @type {?} */ (loadLContext(this.nativeNode)));
/** @type {?} */
const lView = context.lView;
/** @type {?} */
const tData = lView[TVIEW].data;
/** @type {?} */
const tNode = (/** @type {?} */ (tData[context.nodeIndex]));
return (/** @type {?} */ (tNode.tagName));
}
catch (e) {
return this.nativeNode.nodeName;
}
}
/**
* Gets a map of property names to property values for an element.
*
* This map includes:
* - Regular property bindings (e.g. `[id]="id"`)
* - Host property bindings (e.g. `host: { '[id]': "id" }`)
* - Interpolated property bindings (e.g. `id="{{ value }}")
*
* It does not include:
* - input property bindings (e.g. `[myCustomInput]="value"`)
* - attribute bindings (e.g. `[attr.role]="menu"`)
* @return {?}
*/
get properties() {
/** @type {?} */
const context = loadLContext(this.nativeNode, false);
if (context == null) {
return {};
}
/** @type {?} */
const lView = context.lView;
/** @type {?} */
const tData = lView[TVIEW].data;
/** @type {?} */
const tNode = (/** @type {?} */ (tData[context.nodeIndex]));
/** @type {?} */
const properties = {};
// Collect properties from the DOM.
copyDomProperties(this.nativeElement, properties);
// Collect properties from the bindings. This is needed for animation renderer which has
// synthetic properties which don't get reflected into the DOM.
collectPropertyBindings(properties, tNode, lView, tData);
return properties;
}
/**
* @return {?}
*/
get attributes() {
/** @type {?} */
const attributes = {};
/** @type {?} */
const element = this.nativeElement;
if (!element) {
return attributes;
}
/** @type {?} */
const context = loadLContext(element, false);
if (context == null) {
return {};
}
/** @type {?} */
const lView = context.lView;
/** @type {?} */
const tNodeAttrs = ((/** @type {?} */ (lView[TVIEW].data[context.nodeIndex]))).attrs;
/** @type {?} */
const lowercaseTNodeAttrs = [];
// For debug nodes we take the element's attribute directly from the DOM since it allows us
// to account for ones that weren't set via bindings (e.g. ViewEngine keeps track of the ones
// that are set through `Renderer2`). The problem is that the browser will lowercase all names,
// however since we have the attributes already on the TNode, we can preserve the case by going
// through them once, adding them to the `attributes` map and putting their lower-cased name
// into an array. Afterwards when we're going through the native DOM attributes, we can check
// whether we haven't run into an attribute already through the TNode.
if (tNodeAttrs) {
/** @type {?} */
let i = 0;
while (i < tNodeAttrs.length) {
/** @type {?} */
const attrName = tNodeAttrs[i];
// Stop as soon as we hit a marker. We only care about the regular attributes. Everything
// else will be handled below when we read the final attributes off the DOM.
if (typeof attrName !== 'string')
break;
/** @type {?} */
const attrValue = tNodeAttrs[i + 1];
attributes[attrName] = (/** @type {?} */ (attrValue));
lowercaseTNodeAttrs.push(attrName.toLowerCase());
i += 2;
}
}
/** @type {?} */
const eAttrs = element.attributes;
for (let i = 0; i < eAttrs.length; i++) {
/** @type {?} */
const attr = eAttrs[i];
/** @type {?} */
const lowercaseName = attr.name.toLowerCase();
// Make sure that we don't assign the same attribute both in its
// case-sensitive form and the lower-cased one from the browser.
if (lowercaseTNodeAttrs.indexOf(lowercaseName) === -1) {
// Save the lowercase name to align the behavior between browsers.
// IE preserves the case, while all other browser convert it to lower case.
attributes[lowercaseName] = attr.value;
}
}
return attributes;
}
/**
* @return {?}
*/
get styles() {
if (this.nativeElement && ((/** @type {?} */ (this.nativeElement))).style) {
return (/** @type {?} */ (((/** @type {?} */ (this.nativeElement))).style));
}
return {};
}
/**
* @return {?}
*/
get classes() {
/** @type {?} */
const result = {};
/** @type {?} */
const element = (/** @type {?} */ (this.nativeElement));
// SVG elements return an `SVGAnimatedString` instead of a plain string for the `className`.
/** @type {?} */
const className = (/** @type {?} */ (element.className));
/** @type {?} */
const classes = className && typeof className !== 'string' ? className.baseVal.split(' ') :
className.split(' ');
classes.forEach((/**
* @param {?} value
* @return {?}
*/
(value) => result[value] = true));
return result;
}
/**
* @return {?}
*/
get childNodes() {
/** @type {?} */
const childNodes = this.nativeNode.childNodes;
/** @type {?} */
const children = [];
for (let i = 0; i < childNodes.length; i++) {
/** @type {?} */
const element = childNodes[i];
children.push(getDebugNode__POST_R3__(element));
}
return children;
}
/**
* @return {?}
*/
get children() {
/** @type {?} */
const nativeElement = this.nativeElement;
if (!nativeElement)
return [];
/** @type {?} */
const childNodes = nativeElement.children;
/** @type {?} */
const children = [];
for (let i = 0; i < childNodes.length; i++) {
/** @type {?} */
const element = childNodes[i];
children.push(getDebugNode__POST_R3__(element));
}
return children;
}
/**
* @param {?} predicate
* @return {?}
*/
query(predicate) {
/** @type {?} */
const results = this.queryAll(predicate);
return results[0] || null;
}
/**
* @param {?} predicate
* @return {?}
*/
queryAll(predicate) {
/** @type {?} */
const matches = [];
_queryAllR3(this, predicate, matches, true);
return matches;
}
/**
* @param {?} predicate
* @return {?}
*/
queryAllNodes(predicate) {
/** @type {?} */
const matches = [];
_queryAllR3(this, predicate, matches, false);
return matches;
}
/**
* @param {?} eventName
* @param {?} eventObj
* @return {?}
*/
triggerEventHandler(eventName, eventObj) {
/** @type {?} */
const node = (/** @type {?} */ (this.nativeNode));
/** @type {?} */
const invokedListeners = [];
this.listeners.forEach((/**
* @param {?} listener
* @return {?}
*/
listener => {
if (listener.name === eventName) {
/** @type {?} */
const callback = listener.callback;
callback.call(node, eventObj);
invokedListeners.push(callback);
}
}));
// We need to check whether `eventListeners` exists, because it's something
// that Zone.js only adds to `EventTarget` in browser environments.
if (typeof node.eventListeners === 'function') {
// Note that in Ivy we wrap event listeners with a call to `event.preventDefault` in some
// cases. We use '__ngUnwrap__' as a special token that gives us access to the actual event
// listener.
node.eventListeners(eventName).forEach((/**
* @param {?} listener
* @return {?}
*/
(listener) => {
// In order to ensure that we can detect the special __ngUnwrap__ token described above, we
// use `toString` on the listener and see if it contains the token. We use this approach to
// ensure that it still worked with compiled code since it cannot remove or rename string
// literals. We also considered using a special function name (i.e. if(listener.name ===
// special)) but that was more cumbersome and we were also concerned the compiled code could
// strip the name, turning the condition in to ("" === "") and always returning true.
if (listener.toString().indexOf('__ngUnwrap__') !== -1) {
/** @type {?} */
const unwrappedListener = listener('__ngUnwrap__');
return invokedListeners.indexOf(unwrappedListener) === -1 &&
unwrappedListener.call(node, eventObj);
}
}));
}
}
}
/**
* @param {?} element
* @param {?} properties
* @return {?}
*/
function copyDomProperties(element, properties) {
if (element) {
// Skip own properties (as those are patched)
/** @type {?} */
let obj = Object.getPrototypeOf(element);
/** @type {?} */
const NodePrototype = Node.prototype;
while (obj !== null && obj !== NodePrototype) {
/** @type {?} */
const descriptors = Object.getOwnPropertyDescriptors(obj);
for (let key in descriptors) {
if (!key.startsWith('__') && !key.startsWith('on')) {
// don't include properties starting with `__` and `on`.
// `__` are patched values which should not be included.
// `on` are listeners which also should not be included.
/** @type {?} */
const value = ((/** @type {?} */ (element)))[key];
if (isPrimitiveValue(value)) {
properties[key] = value;
}
}
}
obj = Object.getPrototypeOf(obj);
}
}
}
/**
* @param {?} value
* @return {?}
*/
function isPrimitiveValue(value) {
return typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number' ||
value === null;
}
/**
* @param {?} parentElement
* @param {?} predicate
* @param {?} matches
* @param {?} elementsOnly
* @return {?}
*/
function _queryAllR3(parentElement, predicate, matches, elementsOnly) {
/** @type {?} */
const context = loadLContext(parentElement.nativeNode, false);
if (context !== null) {
/** @type {?} */
const parentTNode = (/** @type {?} */ (context.lView[TVIEW].data[context.nodeIndex]));
_queryNodeChildrenR3(parentTNode, context.lView, predicate, matches, elementsOnly, parentElement.nativeNode);
}
else {
// If the context is null, then `parentElement` was either created with Renderer2 or native DOM
// APIs.
_queryNativeNodeDescendants(parentElement.nativeNode, predicate, matches, elementsOnly);
}
}
/**
* Recursively match the current TNode against the predicate, and goes on with the next ones.
*
* @param {?} tNode the current TNode
* @param {?} lView the LView of this TNode
* @param {?} predicate the predicate to match
* @param {?} matches the list of positive matches
* @param {?} elementsOnly whether only elements should be searched
* @param {?} rootNativeNode the root native node on which predicate should not be matched
* @return {?}
*/
function _queryNodeChildrenR3(tNode, lView, predicate, matches, elementsOnly, rootNativeNode) {
/** @type {?} */
const nativeNode = getNativeByTNodeOrNull(tNode, lView);
// For each type of TNode, specific logic is executed.
if (tNode.type === 3 /* Element */ || tNode.type === 4 /* ElementContainer */) {
// Case 1: the TNode is an element
// The native node has to be checked.
_addQueryMatchR3(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
if (isComponentHost(tNode)) {
// If the element is the host of a component, then all nodes in its view have to be processed.
// Note: the component's content (tNode.child) will be processed from the insertion points.
/** @type {?} */
const componentView = getComponentLViewByIndex(tNode.index, lView);
if (componentView && componentView[TVIEW].firstChild) {
_queryNodeChildrenR3((/** @type {?} */ (componentView[TVIEW].firstChild)), componentView, predicate, matches, elementsOnly, rootNativeNode);
}
}
else {
if (tNode.child) {
// Otherwise, its children have to be processed.
_queryNodeChildrenR3(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
}
// We also have to query the DOM directly in order to catch elements inserted through
// Renderer2. Note that this is __not__ optimal, because we're walking similar trees multiple
// times. ViewEngine could do it more efficiently, because all the insertions go through
// Renderer2, however that's not the case in Ivy. This approach is being used because:
// 1. Matching the ViewEngine behavior would mean potentially introducing a depedency
// from `Renderer2` to Ivy which could bring Ivy code into ViewEngine.
// 2. We would have to make `Renderer3` "know" about debug nodes.
// 3. It allows us to capture nodes that were inserted directly via the DOM.
nativeNode && _queryNativeNodeDescendants(nativeNode, predicate, matches, elementsOnly);
}
// In all cases, if a dynamic container exists for this node, each view inside it has to be
// processed.
/** @type {?} */
const nodeOrContainer = lView[tNode.index];
if (isLContainer(nodeOrContainer)) {
_queryNodeChildrenInContainerR3(nodeOrContainer, predicate, matches, elementsOnly, rootNativeNode);
}
}
else if (tNode.type === 0 /* Container */) {
// Case 2: the TNode is a container
// The native node has to be checked.
/** @type {?} */
const lContainer = lView[tNode.index];
_addQueryMatchR3(lContainer[NATIVE], predicate, matches, elementsOnly, rootNativeNode);
// Each view inside the container has to be processed.
_queryNodeChildrenInContainerR3(lContainer, predicate, matches, elementsOnly, rootNativeNode);
}
else if (tNode.type === 1 /* Projection */) {
// Case 3: the TNode is a projection insertion point (i.e. a <ng-content>).
// The nodes projected at this location all need to be processed.
/** @type {?} */
const componentView = (/** @type {?} */ (lView))[DECLARATION_COMPONENT_VIEW];
/** @type {?} */
const componentHost = (/** @type {?} */ (componentView[T_HOST]));
/** @type {?} */
const head = ((/** @type {?} */ (componentHost.projection)))[(/** @type {?} */ (tNode.projection))];
if (Array.isArray(head)) {
for (let nativeNode of head) {
_addQueryMatchR3(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
}
}
else if (head) {
/** @type {?} */
const nextLView = (/** @type {?} */ ((/** @type {?} */ (componentView[PARENT]))));
/** @type {?} */
const nextTNode = (/** @type {?} */ (nextLView[TVIEW].data[head.index]));
_queryNodeChildrenR3(nextTNode, nextLView, predicate, matches, elementsOnly, rootNativeNode);
}
}
else if (tNode.child) {
// Case 4: the TNode is a view.
_queryNodeChildrenR3(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
}
// We don't want to go to the next sibling of the root node.
if (rootNativeNode !== nativeNode) {
// To determine the next node to be processed, we need to use the next or the projectionNext
// link, depending on whether the current node has been projected.
/** @type {?} */
const nextTNode = (tNode.flags & 4 /* isProjected */) ? tNode.projectionNext : tNode.next;
if (nextTNode) {
_queryNodeChildrenR3(nextTNode, lView, predicate, matches, elementsOnly, rootNativeNode);
}
}
}
/**
* Process all TNodes in a given container.
*
* @param {?} lContainer the container to be processed
* @param {?} predicate the predicate to match
* @param {?} matches the list of positive matches
* @param {?} elementsOnly whether only elements should be searched
* @param {?} rootNativeNode the root native node on which predicate should not be matched
* @return {?}
*/
function _queryNodeChildrenInContainerR3(lContainer, predicate, matches, elementsOnly, rootNativeNode) {
for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
/** @type {?} */
const childView = lContainer[i];
_queryNodeChildrenR3((/** @type {?} */ (childView[TVIEW].node)), childView, predicate, matches, elementsOnly, rootNativeNode);
}
}
/**
* Match the current native node against the predicate.
*
* @param {?} nativeNode the current native node
* @param {?} predicate the predicate to match
* @param {?} matches the list of positive matches
* @param {?} elementsOnly whether only elements should be searched
* @param {?} rootNativeNode the root native node on which predicate should not be matched
* @return {?}
*/
function _addQueryMatchR3(nativeNode, predicate, matches, elementsOnly, rootNativeNode) {
if (rootNativeNode !== nativeNode) {
/** @type {?} */
const debugNode = getDebugNode$1(nativeNode);
if (!debugNode) {
return;
}
// Type of the "predicate and "matches" array are set based on the value of
// the "elementsOnly" parameter. TypeScript is not able to properly infer these
// types with generics, so we manually cast the parameters accordingly.
if (elementsOnly && debugNode instanceof DebugElement__POST_R3__ && predicate(debugNode) &&
matches.indexOf(debugNode) === -1) {
matches.push(debugNode);
}
else if (!elementsOnly && ((/** @type {?} */ (predicate)))(debugNode) &&
((/** @type {?} */ (matches))).indexOf(debugNode) === -1) {
((/** @type {?} */ (matches))).push(debugNode);
}
}
}
/**
* Match all the descendants of a DOM node against a predicate.
*
* @param {?} parentNode
* @param {?} predicate the predicate to match
* @param {?} matches the list of positive matches
* @param {?} elementsOnly whether only elements should be searched
* @return {?}
*/
function _queryNativeNodeDescendants(parentNode, predicate, matches, elementsOnly) {
/** @type {?} */
const nodes = parentNode.childNodes;
/** @type {?} */
const length = nodes.length;
for (let i = 0; i < length; i++) {
/** @type {?} */
const node = nodes[i];
/** @type {?} */
const debugNode = getDebugNode$1(node);
if (debugNode) {
if (elementsOnly && debugNode instanceof DebugElement__POST_R3__ && predicate(debugNode) &&
matches.indexOf(debugNode) === -1) {
matches.push(debugNode);
}
else if (!elementsOnly && ((/** @type {?} */ (predicate)))(debugNode) &&
((/** @type {?} */ (matches))).indexOf(debugNode) === -1) {
((/** @type {?} */ (matches))).push(debugNode);
}
_queryNativeNodeDescendants(node, predicate, matches, elementsOnly);
}
}
}
/**
* Iterates through the property bindings for a given node and generates
* a map of property names to values. This map only contains property bindings
* defined in templates, not in host bindings.
* @param {?} properties
* @param {?} tNode
* @param {?} lView
* @param {?} tData
* @return {?}
*/
function collectPropertyBindings(properties, tNode, lView, tData) {
/** @type {?} */
let bindingIndexes = tNode.propertyBindings;
if (bindingIndexes !== null) {
for (let i = 0; i < bindingIndexes.length; i++) {
/** @type {?} */
const bindingIndex = bindingIndexes[i];
/** @type {?} */
const propMetadata = (/** @type {?} */ (tData[bindingIndex]));
/** @type {?} */
const metadataParts = propMetadata.split(INTERPOLATION_DELIMITER);
/** @type {?} */
const propertyName = metadataParts[0];
if (metadataParts.length > 1) {
/** @type {?} */
let value = metadataParts[1];
for (let j = 1; j < metadataParts.length - 1; j++) {
value += renderStringify(lView[bindingIndex + j - 1]) + metadataParts[j + 1];
}
properties[propertyName] = value;
}
else {
properties[propertyName] = lView[bindingIndex];
}
}
}
}
// Need to keep the nodes in a global Map so that multiple angular apps are supported.
/** @type {?} */
const _nativeNodeToDebugNode = new Map();
/**
* @param {?} nativeNode
* @return {?}
*/
function getDebugNode__PRE_R3__(nativeNode) {
return _nativeNodeToDebugNode.get(nativeNode) || null;
}
/** @type {?} */
const NG_DEBUG_PROPERTY = '__ng_debug__';
/**
* @param {?} nativeNode
* @return {?}
*/
function getDebugNode__POST_R3__(nativeNode) {
if (nativeNode instanceof Node) {
if (!(nativeNode.hasOwnProperty(NG_DEBUG_PROPERTY))) {
((/** @type {?} */ (nativeNode)))[NG_DEBUG_PROPERTY] = nativeNode.nodeType == Node.ELEMENT_NODE ?
new DebugElement__POST_R3__((/** @type {?} */ (nativeNode))) :
new DebugNode__POST_R3__(nativeNode);
}
return ((/** @type {?} */ (nativeNode)))[NG_DEBUG_PROPERTY];
}
return null;
}
/**
* \@publicApi
* @type {?}
*/
const getDebugNode$1 = getDebugNode__POST_R3__;
/**
* @param {?} nativeNode
* @return {?}
*/
function getDebugNodeR2__PRE_R3__(nativeNode) {
return getDebugNode__PRE_R3__(nativeNode);
}
/**
* @param {?} _nativeNode
* @return {?}
*/
function getDebugNodeR2__POST_R3__(_nativeNode) {
return null;
}
/** @type {?} */
const getDebugNodeR2 = getDebugNodeR2__POST_R3__;
/**
* @return {?}
*/
function getAllDebugNodes() {
return Array.from(_nativeNodeToDebugNode.values());
}
/**
* @param {?} node
* @return {?}
*/
function indexDebugNode(node) {
_nativeNodeToDebugNode.set(node.nativeNode, node);
}
/**
* @param {?} node
* @return {?}
*/
function removeDebugNodeFromIndex(node) {
_nativeNodeToDebugNode.delete(node.nativeNode);
}
/**
* A boolean-valued function over a value, possibly including context information
* regarding that value's position in an array.
*
* \@publicApi
* @record
* @template T
*/
function Predicate() { }
/**
* \@publicApi
* @type {?}
*/
const DebugNode$1 = DebugNode__POST_R3__;
/**
* \@publicApi
* @type {?}
*/
const DebugElement = DebugElement__POST_R3__;
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/change_detection.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/platform_core_providers.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const _CORE_PLATFORM_PROVIDERS = [
// Set a default platform name for platforms that don't set it explicitly.
{ provide: PLATFORM_ID, useValue: 'unknown' },
{ provide: PlatformRef, deps: [Injector] },
{ provide: TestabilityRegistry, deps: [] },
{ provide: Console, deps: [] },
];
/**
* This platform has to be included in any other platform
*
* \@publicApi
* @type {?}
*/
const platformCore = createPlatformFactory(null, 'core', _CORE_PLATFORM_PROVIDERS);
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/application_module.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @return {?}
*/
function _iterableDiffersFactory() {
return defaultIterableDiffers;
}
/**
* @return {?}
*/
function _keyValueDiffersFactory() {
return defaultKeyValueDiffers;
}
/**
* @param {?=} locale
* @return {?}
*/
function _localeFactory(locale) {
locale = locale || getGlobalLocale();
if (ivyEnabled) {
setLocaleId(locale);
}
return locale;
}
/**
* Work out the locale from the potential global properties.
*
* * Closure Compiler: use `goog.LOCALE`.
* * Ivy enabled: use `$localize.locale`
* @return {?}
*/
function getGlobalLocale() {
if (typeof ngI18nClosureMode !== 'undefined' && ngI18nClosureMode &&
typeof goog !== 'undefined' && goog.LOCALE !== 'en') {
// * The default `goog.LOCALE` value is `en`, while Angular used `en-US`.
// * In order to preserve backwards compatibility, we use Angular default value over
// Closure Compiler's one.
return goog.LOCALE;
}
else {
// KEEP `typeof $localize !== 'undefined' && $localize.locale` IN SYNC WITH THE LOCALIZE
// COMPILE-TIME INLINER.
//
// * During compile time inlining of translations the expression will be replaced
// with a string literal that is the current locale. Other forms of this expression are not
// guaranteed to be replaced.
//
// * During runtime translation evaluation, the developer is required to set `$localize.locale`
// if required, or just to provide their own `LOCALE_ID` provider.
return (ivyEnabled && typeof $localize !== 'undefined' && $localize.locale) ||
DEFAULT_LOCALE_ID;
}
}
const ɵ0$g = USD_CURRENCY_CODE;
/**
* A built-in [dependency injection token](guide/glossary#di-token)
* that is used to configure the root injector for bootstrapping.
* @type {?}
*/
const APPLICATION_MODULE_PROVIDERS = [
{
provide: ApplicationRef,
useClass: ApplicationRef,
deps: [NgZone, Console, Injector, ErrorHandler, ComponentFactoryResolver, ApplicationInitStatus]
},
{ provide: SCHEDULER, deps: [NgZone], useFactory: zoneSchedulerFactory },
{
provide: ApplicationInitStatus,
useClass: ApplicationInitStatus,
deps: [[new Optional(), APP_INITIALIZER]]
},
{ provide: Compiler, useClass: Compiler, deps: [] },
APP_ID_RANDOM_PROVIDER,
{ provide: IterableDiffers, useFactory: _iterableDiffersFactory, deps: [] },
{ provide: KeyValueDiffers, useFactory: _keyValueDiffersFactory, deps: [] },
{
provide: LOCALE_ID$1,
useFactory: _localeFactory,
deps: [[new Inject(LOCALE_ID$1), new Optional(), new SkipSelf()]]
},
{ provide: DEFAULT_CURRENCY_CODE, useValue: ɵ0$g },
];
/**
* Schedule work at next available slot.
*
* In Ivy this is just `requestAnimationFrame`. For compatibility reasons when bootstrapped
* using `platformRef.bootstrap` we need to use `NgZone.onStable` as the scheduling mechanism.
* This overrides the scheduling mechanism in Ivy to `NgZone.onStable`.
*
* @param {?} ngZone NgZone to use for scheduling.
* @return {?}
*/
function zoneSchedulerFactory(ngZone) {
/** @type {?} */
let queue = [];
ngZone.onStable.subscribe((/**
* @return {?}
*/
() => {
while (queue.length) {
(/** @type {?} */ (queue.pop()))();
}
}));
return (/**
* @param {?} fn
* @return {?}
*/
function (fn) {
queue.push(fn);
});
}
/**
* Configures the root injector for an app with
* providers of `\@angular/core` dependencies that `ApplicationRef` needs
* to bootstrap components.
*
* Re-exported by `BrowserModule`, which is included automatically in the root
* `AppModule` when you create a new app with the CLI `new` command.
*
* \@publicApi
*/
class ApplicationModule {
// Inject ApplicationRef to make it eager...
/**
* @param {?} appRef
*/
constructor(appRef) { }
}
ApplicationModule.ɵmod = ɵɵdefineNgModule({ type: ApplicationModule });
ApplicationModule.ɵinj = ɵɵdefineInjector({ factory: function ApplicationModule_Factory(t) { return new (t || ApplicationModule)(ɵɵinject(ApplicationRef)); }, providers: APPLICATION_MODULE_PROVIDERS });
/** @nocollapse */
ApplicationModule.ctorParameters = () => [
{ type: ApplicationRef }
];
/*@__PURE__*/ (function () { setClassMetadata(ApplicationModule, [{
type: NgModule,
args: [{ providers: APPLICATION_MODULE_PROVIDERS }]
}], function () { return [{ type: ApplicationRef }]; }, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/element.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} flags
* @param {?} matchedQueriesDsl
* @param {?} ngContentIndex
* @param {?} childCount
* @param {?=} handleEvent
* @param {?=} templateFactory
* @return {?}
*/
function anchorDef(flags, matchedQueriesDsl, ngContentIndex, childCount, handleEvent, templateFactory) {
flags |= 1 /* TypeElement */;
const { matchedQueries, references, matchedQueryIds } = splitMatchedQueriesDsl(matchedQueriesDsl);
/** @type {?} */
const template = templateFactory ? resolveDefinition(templateFactory) : null;
return {
// will bet set by the view definition
nodeIndex: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
flags,
checkIndex: -1,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
matchedQueries,
matchedQueryIds,
references,
ngContentIndex,
childCount,
bindings: [],
bindingFlags: 0,
outputs: [],
element: {
ns: null,
name: null,
attrs: null,
template,
componentProvider: null,
componentView: null,
componentRendererType: null,
publicProviders: null,
allProviders: null,
handleEvent: handleEvent || NOOP
},
provider: null,
text: null,
query: null,
ngContent: null
};
}
/**
* @param {?} checkIndex
* @param {?} flags
* @param {?} matchedQueriesDsl
* @param {?} ngContentIndex
* @param {?} childCount
* @param {?} namespaceAndName
* @param {?=} fixedAttrs
* @param {?=} bindings
* @param {?=} outputs
* @param {?=} handleEvent
* @param {?=} componentView
* @param {?=} componentRendererType
* @return {?}
*/
function elementDef(checkIndex, flags, matchedQueriesDsl, ngContentIndex, childCount, namespaceAndName, fixedAttrs = [], bindings, outputs, handleEvent, componentView, componentRendererType) {
if (!handleEvent) {
handleEvent = NOOP;
}
const { matchedQueries, references, matchedQueryIds } = splitMatchedQueriesDsl(matchedQueriesDsl);
/** @type {?} */
let ns = (/** @type {?} */ (null));
/** @type {?} */
let name = (/** @type {?} */ (null));
if (namespaceAndName) {
[ns, name] = splitNamespace(namespaceAndName);
}
bindings = bindings || [];
/** @type {?} */
const bindingDefs = [];
for (let i = 0; i < bindings.length; i++) {
const [bindingFlags, namespaceAndName, suffixOrSecurityContext] = bindings[i];
const [ns, name] = splitNamespace(namespaceAndName);
/** @type {?} */
let securityContext = (/** @type {?} */ (undefined));
/** @type {?} */
let suffix = (/** @type {?} */ (undefined));
switch (bindingFlags & 15 /* Types */) {
case 4 /* TypeElementStyle */:
suffix = (/** @type {?} */ (suffixOrSecurityContext));
break;
case 1 /* TypeElementAttribute */:
case 8 /* TypeProperty */:
securityContext = (/** @type {?} */ (suffixOrSecurityContext));
break;
}
bindingDefs[i] =
{ flags: bindingFlags, ns, name, nonMinifiedName: name, securityContext, suffix };
}
outputs = outputs || [];
/** @type {?} */
const outputDefs = [];
for (let i = 0; i < outputs.length; i++) {
const [target, eventName] = outputs[i];
outputDefs[i] =
{ type: 0 /* ElementOutput */, target: (/** @type {?} */ (target)), eventName, propName: null };
}
fixedAttrs = fixedAttrs || [];
/** @type {?} */
const attrs = (/** @type {?} */ (fixedAttrs.map((/**
* @param {?} __0
* @return {?}
*/
([namespaceAndName, value]) => {
const [ns, name] = splitNamespace(namespaceAndName);
return [ns, name, value];
}))));
componentRendererType = resolveRendererType2(componentRendererType);
if (componentView) {
flags |= 33554432 /* ComponentView */;
}
flags |= 1 /* TypeElement */;
return {
// will bet set by the view definition
nodeIndex: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
checkIndex,
flags,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
matchedQueries,
matchedQueryIds,
references,
ngContentIndex,
childCount,
bindings: bindingDefs,
bindingFlags: calcBindingFlags(bindingDefs),
outputs: outputDefs,
element: {
ns,
name,
attrs,
template: null,
// will bet set by the view definition
componentProvider: null,
componentView: componentView || null,
componentRendererType: componentRendererType,
publicProviders: null,
allProviders: null,
handleEvent: handleEvent || NOOP,
},
provider: null,
text: null,
query: null,
ngContent: null
};
}
/**
* @param {?} view
* @param {?} renderHost
* @param {?} def
* @return {?}
*/
function createElement(view, renderHost, def) {
/** @type {?} */
const elDef = (/** @type {?} */ (def.element));
/** @type {?} */
const rootSelectorOrNode = view.root.selectorOrNode;
/** @type {?} */
const renderer = view.renderer;
/** @type {?} */
let el;
if (view.parent || !rootSelectorOrNode) {
if (elDef.name) {
el = renderer.createElement(elDef.name, elDef.ns);
}
else {
el = renderer.createComment('');
}
/** @type {?} */
const parentEl = getParentRenderElement(view, renderHost, def);
if (parentEl) {
renderer.appendChild(parentEl, el);
}
}
else {
// when using native Shadow DOM, do not clear the root element contents to allow slot projection
/** @type {?} */
const preserveContent = (!!elDef.componentRendererType &&
elDef.componentRendererType.encapsulation === ViewEncapsulation$1.ShadowDom);
el = renderer.selectRootElement(rootSelectorOrNode, preserveContent);
}
if (elDef.attrs) {
for (let i = 0; i < elDef.attrs.length; i++) {
const [ns, name, value] = elDef.attrs[i];
renderer.setAttribute(el, name, value, ns);
}
}
return el;
}
/**
* @param {?} view
* @param {?} compView
* @param {?} def
* @param {?} el
* @return {?}
*/
function listenToElementOutputs(view, compView, def, el) {
for (let i = 0; i < def.outputs.length; i++) {
/** @type {?} */
const output = def.outputs[i];
/** @type {?} */
const handleEventClosure = renderEventHandlerClosure(view, def.nodeIndex, elementEventFullName(output.target, output.eventName));
/** @type {?} */
let listenTarget = output.target;
/** @type {?} */
let listenerView = view;
if (output.target === 'component') {
listenTarget = null;
listenerView = compView;
}
/** @type {?} */
const disposable = (/** @type {?} */ (listenerView.renderer.listen(listenTarget || el, output.eventName, handleEventClosure)));
(/** @type {?} */ (view.disposables))[def.outputIndex + i] = disposable;
}
}
/**
* @param {?} view
* @param {?} index
* @param {?} eventName
* @return {?}
*/
function renderEventHandlerClosure(view, index, eventName) {
return (/**
* @param {?} event
* @return {?}
*/
(event) => dispatchEvent(view, index, eventName, event));
}
/**
* @param {?} view
* @param {?} def
* @param {?} v0
* @param {?} v1
* @param {?} v2
* @param {?} v3
* @param {?} v4
* @param {?} v5
* @param {?} v6
* @param {?} v7
* @param {?} v8
* @param {?} v9
* @return {?}
*/
function checkAndUpdateElementInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
/** @type {?} */
const bindLen = def.bindings.length;
/** @type {?} */
let changed = false;
if (bindLen > 0 && checkAndUpdateElementValue(view, def, 0, v0))
changed = true;
if (bindLen > 1 && checkAndUpdateElementValue(view, def, 1, v1))
changed = true;
if (bindLen > 2 && checkAndUpdateElementValue(view, def, 2, v2))
changed = true;
if (bindLen > 3 && checkAndUpdateElementValue(view, def, 3, v3))
changed = true;
if (bindLen > 4 && checkAndUpdateElementValue(view, def, 4, v4))
changed = true;
if (bindLen > 5 && checkAndUpdateElementValue(view, def, 5, v5))
changed = true;
if (bindLen > 6 && checkAndUpdateElementValue(view, def, 6, v6))
changed = true;
if (bindLen > 7 && checkAndUpdateElementValue(view, def, 7, v7))
changed = true;
if (bindLen > 8 && checkAndUpdateElementValue(view, def, 8, v8))
changed = true;
if (bindLen > 9 && checkAndUpdateElementValue(view, def, 9, v9))
changed = true;
return changed;
}
/**
* @param {?} view
* @param {?} def
* @param {?} values
* @return {?}
*/
function checkAndUpdateElementDynamic(view, def, values) {
/** @type {?} */
let changed = false;
for (let i = 0; i < values.length; i++) {
if (checkAndUpdateElementValue(view, def, i, values[i]))
changed = true;
}
return changed;
}
/**
* @param {?} view
* @param {?} def
* @param {?} bindingIdx
* @param {?} value
* @return {?}
*/
function checkAndUpdateElementValue(view, def, bindingIdx, value) {
if (!checkAndUpdateBinding(view, def, bindingIdx, value)) {
return false;
}
/** @type {?} */
const binding = def.bindings[bindingIdx];
/** @type {?} */
const elData = asElementData(view, def.nodeIndex);
/** @type {?} */
const renderNode = elData.renderElement;
/** @type {?} */
const name = (/** @type {?} */ (binding.name));
switch (binding.flags & 15 /* Types */) {
case 1 /* TypeElementAttribute */:
setElementAttribute(view, binding, renderNode, binding.ns, name, value);
break;
case 2 /* TypeElementClass */:
setElementClass(view, renderNode, name, value);
break;
case 4 /* TypeElementStyle */:
setElementStyle(view, binding, renderNode, name, value);
break;
case 8 /* TypeProperty */:
/** @type {?} */
const bindView = (def.flags & 33554432 /* ComponentView */ &&
binding.flags & 32 /* SyntheticHostProperty */) ?
elData.componentView :
view;
setElementProperty(bindView, binding, renderNode, name, value);
break;
}
return true;
}
/**
* @param {?} view
* @param {?} binding
* @param {?} renderNode
* @param {?} ns
* @param {?} name
* @param {?} value
* @return {?}
*/
function setElementAttribute(view, binding, renderNode, ns, name, value) {
/** @type {?} */
const securityContext = binding.securityContext;
/** @type {?} */
let renderValue = securityContext ? view.root.sanitizer.sanitize(securityContext, value) : value;
renderValue = renderValue != null ? renderValue.toString() : null;
/** @type {?} */
const renderer = view.renderer;
if (value != null) {
renderer.setAttribute(renderNode, name, renderValue, ns);
}
else {
renderer.removeAttribute(renderNode, name, ns);
}
}
/**
* @param {?} view
* @param {?} renderNode
* @param {?} name
* @param {?} value
* @return {?}
*/
function setElementClass(view, renderNode, name, value) {
/** @type {?} */
const renderer = view.renderer;
if (value) {
renderer.addClass(renderNode, name);
}
else {
renderer.removeClass(renderNode, name);
}
}
/**
* @param {?} view
* @param {?} binding
* @param {?} renderNode
* @param {?} name
* @param {?} value
* @return {?}
*/
function setElementStyle(view, binding, renderNode, name, value) {
/** @type {?} */
let renderValue = view.root.sanitizer.sanitize(SecurityContext.STYLE, (/** @type {?} */ (value)));
if (renderValue != null) {
renderValue = renderValue.toString();
/** @type {?} */
const unit = binding.suffix;
if (unit != null) {
renderValue = renderValue + unit;
}
}
else {
renderValue = null;
}
/** @type {?} */
const renderer = view.renderer;
if (renderValue != null) {
renderer.setStyle(renderNode, name, renderValue);
}
else {
renderer.removeStyle(renderNode, name);
}
}
/**
* @param {?} view
* @param {?} binding
* @param {?} renderNode
* @param {?} name
* @param {?} value
* @return {?}
*/
function setElementProperty(view, binding, renderNode, name, value) {
/** @type {?} */
const securityContext = binding.securityContext;
/** @type {?} */
let renderValue = securityContext ? view.root.sanitizer.sanitize(securityContext, value) : value;
view.renderer.setProperty(renderNode, name, renderValue);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/query.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} flags
* @param {?} id
* @param {?} bindings
* @return {?}
*/
function queryDef(flags, id, bindings) {
/** @type {?} */
let bindingDefs = [];
for (let propName in bindings) {
/** @type {?} */
const bindingType = bindings[propName];
bindingDefs.push({ propName, bindingType });
}
return {
// will bet set by the view definition
nodeIndex: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
// TODO(vicb): check
checkIndex: -1,
flags,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
ngContentIndex: -1,
matchedQueries: {},
matchedQueryIds: 0,
references: {},
childCount: 0,
bindings: [],
bindingFlags: 0,
outputs: [],
element: null,
provider: null,
text: null,
query: { id, filterId: filterQueryId(id), bindings: bindingDefs },
ngContent: null
};
}
/**
* @return {?}
*/
function createQuery() {
return new QueryList();
}
/**
* @param {?} view
* @return {?}
*/
function dirtyParentQueries(view) {
/** @type {?} */
const queryIds = view.def.nodeMatchedQueries;
while (view.parent && isEmbeddedView(view)) {
/** @type {?} */
let tplDef = (/** @type {?} */ (view.parentNodeDef));
view = view.parent;
// content queries
/** @type {?} */
const end = tplDef.nodeIndex + tplDef.childCount;
for (let i = 0; i <= end; i++) {
/** @type {?} */
const nodeDef = view.def.nodes[i];
if ((nodeDef.flags & 67108864 /* TypeContentQuery */) &&
(nodeDef.flags & 536870912 /* DynamicQuery */) &&
((/** @type {?} */ (nodeDef.query)).filterId & queryIds) === (/** @type {?} */ (nodeDef.query)).filterId) {
asQueryList(view, i).setDirty();
}
if ((nodeDef.flags & 1 /* TypeElement */ && i + nodeDef.childCount < tplDef.nodeIndex) ||
!(nodeDef.childFlags & 67108864 /* TypeContentQuery */) ||
!(nodeDef.childFlags & 536870912 /* DynamicQuery */)) {
// skip elements that don't contain the template element or no query.
i += nodeDef.childCount;
}
}
}
// view queries
if (view.def.nodeFlags & 134217728 /* TypeViewQuery */) {
for (let i = 0; i < view.def.nodes.length; i++) {
/** @type {?} */
const nodeDef = view.def.nodes[i];
if ((nodeDef.flags & 134217728 /* TypeViewQuery */) && (nodeDef.flags & 536870912 /* DynamicQuery */)) {
asQueryList(view, i).setDirty();
}
// only visit the root nodes
i += nodeDef.childCount;
}
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @return {?}
*/
function checkAndUpdateQuery(view, nodeDef) {
/** @type {?} */
const queryList = asQueryList(view, nodeDef.nodeIndex);
if (!queryList.dirty) {
return;
}
/** @type {?} */
let directiveInstance;
/** @type {?} */
let newValues = (/** @type {?} */ (undefined));
if (nodeDef.flags & 67108864 /* TypeContentQuery */) {
/** @type {?} */
const elementDef = (/** @type {?} */ ((/** @type {?} */ (nodeDef.parent)).parent));
newValues = calcQueryValues(view, elementDef.nodeIndex, elementDef.nodeIndex + elementDef.childCount, (/** @type {?} */ (nodeDef.query)), []);
directiveInstance = asProviderData(view, (/** @type {?} */ (nodeDef.parent)).nodeIndex).instance;
}
else if (nodeDef.flags & 134217728 /* TypeViewQuery */) {
newValues = calcQueryValues(view, 0, view.def.nodes.length - 1, (/** @type {?} */ (nodeDef.query)), []);
directiveInstance = view.component;
}
queryList.reset(newValues);
/** @type {?} */
const bindings = (/** @type {?} */ (nodeDef.query)).bindings;
/** @type {?} */
let notify = false;
for (let i = 0; i < bindings.length; i++) {
/** @type {?} */
const binding = bindings[i];
/** @type {?} */
let boundValue;
switch (binding.bindingType) {
case 0 /* First */:
boundValue = queryList.first;
break;
case 1 /* All */:
boundValue = queryList;
notify = true;
break;
}
directiveInstance[binding.propName] = boundValue;
}
if (notify) {
queryList.notifyOnChanges();
}
}
/**
* @param {?} view
* @param {?} startIndex
* @param {?} endIndex
* @param {?} queryDef
* @param {?} values
* @return {?}
*/
function calcQueryValues(view, startIndex, endIndex, queryDef, values) {
for (let i = startIndex; i <= endIndex; i++) {
/** @type {?} */
const nodeDef = view.def.nodes[i];
/** @type {?} */
const valueType = nodeDef.matchedQueries[queryDef.id];
if (valueType != null) {
values.push(getQueryValue(view, nodeDef, valueType));
}
if (nodeDef.flags & 1 /* TypeElement */ && (/** @type {?} */ (nodeDef.element)).template &&
((/** @type {?} */ ((/** @type {?} */ (nodeDef.element)).template)).nodeMatchedQueries & queryDef.filterId) ===
queryDef.filterId) {
/** @type {?} */
const elementData = asElementData(view, i);
// check embedded views that were attached at the place of their template,
// but process child nodes first if some match the query (see issue #16568)
if ((nodeDef.childMatchedQueries & queryDef.filterId) === queryDef.filterId) {
calcQueryValues(view, i + 1, i + nodeDef.childCount, queryDef, values);
i += nodeDef.childCount;
}
if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
/** @type {?} */
const embeddedViews = (/** @type {?} */ (elementData.viewContainer))._embeddedViews;
for (let k = 0; k < embeddedViews.length; k++) {
/** @type {?} */
const embeddedView = embeddedViews[k];
/** @type {?} */
const dvc = declaredViewContainer(embeddedView);
if (dvc && dvc === elementData) {
calcQueryValues(embeddedView, 0, embeddedView.def.nodes.length - 1, queryDef, values);
}
}
}
/** @type {?} */
const projectedViews = elementData.template._projectedViews;
if (projectedViews) {
for (let k = 0; k < projectedViews.length; k++) {
/** @type {?} */
const projectedView = projectedViews[k];
calcQueryValues(projectedView, 0, projectedView.def.nodes.length - 1, queryDef, values);
}
}
}
if ((nodeDef.childMatchedQueries & queryDef.filterId) !== queryDef.filterId) {
// if no child matches the query, skip the children.
i += nodeDef.childCount;
}
}
return values;
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} queryValueType
* @return {?}
*/
function getQueryValue(view, nodeDef, queryValueType) {
if (queryValueType != null) {
// a match
switch (queryValueType) {
case 1 /* RenderElement */:
return asElementData(view, nodeDef.nodeIndex).renderElement;
case 0 /* ElementRef */:
return new ElementRef(asElementData(view, nodeDef.nodeIndex).renderElement);
case 2 /* TemplateRef */:
return asElementData(view, nodeDef.nodeIndex).template;
case 3 /* ViewContainerRef */:
return asElementData(view, nodeDef.nodeIndex).viewContainer;
case 4 /* Provider */:
return asProviderData(view, nodeDef.nodeIndex).instance;
}
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/ng_content.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} ngContentIndex
* @param {?} index
* @return {?}
*/
function ngContentDef(ngContentIndex, index) {
return {
// will bet set by the view definition
nodeIndex: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
checkIndex: -1,
flags: 8 /* TypeNgContent */,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
matchedQueries: {},
matchedQueryIds: 0,
references: {},
ngContentIndex,
childCount: 0,
bindings: [],
bindingFlags: 0,
outputs: [],
element: null,
provider: null,
text: null,
query: null,
ngContent: { index }
};
}
/**
* @param {?} view
* @param {?} renderHost
* @param {?} def
* @return {?}
*/
function appendNgContent(view, renderHost, def) {
/** @type {?} */
const parentEl = getParentRenderElement(view, renderHost, def);
if (!parentEl) {
// Nothing to do if there is no parent element.
return;
}
/** @type {?} */
const ngContentIndex = (/** @type {?} */ (def.ngContent)).index;
visitProjectedRenderNodes(view, ngContentIndex, 1 /* AppendChild */, parentEl, null, undefined);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/pure_expression.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} checkIndex
* @param {?} argCount
* @return {?}
*/
function purePipeDef(checkIndex, argCount) {
// argCount + 1 to include the pipe as first arg
return _pureExpressionDef(128 /* TypePurePipe */, checkIndex, newArray(argCount + 1));
}
/**
* @param {?} checkIndex
* @param {?} argCount
* @return {?}
*/
function pureArrayDef(checkIndex, argCount) {
return _pureExpressionDef(32 /* TypePureArray */, checkIndex, newArray(argCount));
}
/**
* @param {?} checkIndex
* @param {?} propToIndex
* @return {?}
*/
function pureObjectDef(checkIndex, propToIndex) {
/** @type {?} */
const keys = Object.keys(propToIndex);
/** @type {?} */
const nbKeys = keys.length;
/** @type {?} */
const propertyNames = [];
for (let i = 0; i < nbKeys; i++) {
/** @type {?} */
const key = keys[i];
/** @type {?} */
const index = propToIndex[key];
propertyNames.push(key);
}
return _pureExpressionDef(64 /* TypePureObject */, checkIndex, propertyNames);
}
/**
* @param {?} flags
* @param {?} checkIndex
* @param {?} propertyNames
* @return {?}
*/
function _pureExpressionDef(flags, checkIndex, propertyNames) {
/** @type {?} */
const bindings = [];
for (let i = 0; i < propertyNames.length; i++) {
/** @type {?} */
const prop = propertyNames[i];
bindings.push({
flags: 8 /* TypeProperty */,
name: prop,
ns: null,
nonMinifiedName: prop,
securityContext: null,
suffix: null
});
}
return {
// will bet set by the view definition
nodeIndex: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
checkIndex,
flags,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
matchedQueries: {},
matchedQueryIds: 0,
references: {},
ngContentIndex: -1,
childCount: 0,
bindings,
bindingFlags: calcBindingFlags(bindings),
outputs: [],
element: null,
provider: null,
text: null,
query: null,
ngContent: null
};
}
/**
* @param {?} view
* @param {?} def
* @return {?}
*/
function createPureExpression(view, def) {
return { value: undefined };
}
/**
* @param {?} view
* @param {?} def
* @param {?} v0
* @param {?} v1
* @param {?} v2
* @param {?} v3
* @param {?} v4
* @param {?} v5
* @param {?} v6
* @param {?} v7
* @param {?} v8
* @param {?} v9
* @return {?}
*/
function checkAndUpdatePureExpressionInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
/** @type {?} */
const bindings = def.bindings;
/** @type {?} */
let changed = false;
/** @type {?} */
const bindLen = bindings.length;
if (bindLen > 0 && checkAndUpdateBinding(view, def, 0, v0))
changed = true;
if (bindLen > 1 && checkAndUpdateBinding(view, def, 1, v1))
changed = true;
if (bindLen > 2 && checkAndUpdateBinding(view, def, 2, v2))
changed = true;
if (bindLen > 3 && checkAndUpdateBinding(view, def, 3, v3))
changed = true;
if (bindLen > 4 && checkAndUpdateBinding(view, def, 4, v4))
changed = true;
if (bindLen > 5 && checkAndUpdateBinding(view, def, 5, v5))
changed = true;
if (bindLen > 6 && checkAndUpdateBinding(view, def, 6, v6))
changed = true;
if (bindLen > 7 && checkAndUpdateBinding(view, def, 7, v7))
changed = true;
if (bindLen > 8 && checkAndUpdateBinding(view, def, 8, v8))
changed = true;
if (bindLen > 9 && checkAndUpdateBinding(view, def, 9, v9))
changed = true;
if (changed) {
/** @type {?} */
const data = asPureExpressionData(view, def.nodeIndex);
/** @type {?} */
let value;
switch (def.flags & 201347067 /* Types */) {
case 32 /* TypePureArray */:
value = [];
if (bindLen > 0)
value.push(v0);
if (bindLen > 1)
value.push(v1);
if (bindLen > 2)
value.push(v2);
if (bindLen > 3)
value.push(v3);
if (bindLen > 4)
value.push(v4);
if (bindLen > 5)
value.push(v5);
if (bindLen > 6)
value.push(v6);
if (bindLen > 7)
value.push(v7);
if (bindLen > 8)
value.push(v8);
if (bindLen > 9)
value.push(v9);
break;
case 64 /* TypePureObject */:
value = {};
if (bindLen > 0)
value[(/** @type {?} */ (bindings[0].name))] = v0;
if (bindLen > 1)
value[(/** @type {?} */ (bindings[1].name))] = v1;
if (bindLen > 2)
value[(/** @type {?} */ (bindings[2].name))] = v2;
if (bindLen > 3)
value[(/** @type {?} */ (bindings[3].name))] = v3;
if (bindLen > 4)
value[(/** @type {?} */ (bindings[4].name))] = v4;
if (bindLen > 5)
value[(/** @type {?} */ (bindings[5].name))] = v5;
if (bindLen > 6)
value[(/** @type {?} */ (bindings[6].name))] = v6;
if (bindLen > 7)
value[(/** @type {?} */ (bindings[7].name))] = v7;
if (bindLen > 8)
value[(/** @type {?} */ (bindings[8].name))] = v8;
if (bindLen > 9)
value[(/** @type {?} */ (bindings[9].name))] = v9;
break;
case 128 /* TypePurePipe */:
/** @type {?} */
const pipe = v0;
switch (bindLen) {
case 1:
value = pipe.transform(v0);
break;
case 2:
value = pipe.transform(v1);
break;
case 3:
value = pipe.transform(v1, v2);
break;
case 4:
value = pipe.transform(v1, v2, v3);
break;
case 5:
value = pipe.transform(v1, v2, v3, v4);
break;
case 6:
value = pipe.transform(v1, v2, v3, v4, v5);
break;
case 7:
value = pipe.transform(v1, v2, v3, v4, v5, v6);
break;
case 8:
value = pipe.transform(v1, v2, v3, v4, v5, v6, v7);
break;
case 9:
value = pipe.transform(v1, v2, v3, v4, v5, v6, v7, v8);
break;
case 10:
value = pipe.transform(v1, v2, v3, v4, v5, v6, v7, v8, v9);
break;
}
break;
}
data.value = value;
}
return changed;
}
/**
* @param {?} view
* @param {?} def
* @param {?} values
* @return {?}
*/
function checkAndUpdatePureExpressionDynamic(view, def, values) {
/** @type {?} */
const bindings = def.bindings;
/** @type {?} */
let changed = false;
for (let i = 0; i < values.length; i++) {
// Note: We need to loop over all values, so that
// the old values are updates as well!
if (checkAndUpdateBinding(view, def, i, values[i])) {
changed = true;
}
}
if (changed) {
/** @type {?} */
const data = asPureExpressionData(view, def.nodeIndex);
/** @type {?} */
let value;
switch (def.flags & 201347067 /* Types */) {
case 32 /* TypePureArray */:
value = values;
break;
case 64 /* TypePureObject */:
value = {};
for (let i = 0; i < values.length; i++) {
value[(/** @type {?} */ (bindings[i].name))] = values[i];
}
break;
case 128 /* TypePurePipe */:
/** @type {?} */
const pipe = values[0];
/** @type {?} */
const params = values.slice(1);
value = ((/** @type {?} */ (pipe.transform)))(...params);
break;
}
data.value = value;
}
return changed;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/text.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} checkIndex
* @param {?} ngContentIndex
* @param {?} staticText
* @return {?}
*/
function textDef(checkIndex, ngContentIndex, staticText) {
/** @type {?} */
const bindings = [];
for (let i = 1; i < staticText.length; i++) {
bindings[i - 1] = {
flags: 8 /* TypeProperty */,
name: null,
ns: null,
nonMinifiedName: null,
securityContext: null,
suffix: staticText[i],
};
}
return {
// will bet set by the view definition
nodeIndex: -1,
parent: null,
renderParent: null,
bindingIndex: -1,
outputIndex: -1,
// regular values
checkIndex,
flags: 2 /* TypeText */,
childFlags: 0,
directChildFlags: 0,
childMatchedQueries: 0,
matchedQueries: {},
matchedQueryIds: 0,
references: {},
ngContentIndex,
childCount: 0,
bindings,
bindingFlags: 8 /* TypeProperty */,
outputs: [],
element: null,
provider: null,
text: { prefix: staticText[0] },
query: null,
ngContent: null,
};
}
/**
* @param {?} view
* @param {?} renderHost
* @param {?} def
* @return {?}
*/
function createText(view, renderHost, def) {
/** @type {?} */
let renderNode;
/** @type {?} */
const renderer = view.renderer;
renderNode = renderer.createText((/** @type {?} */ (def.text)).prefix);
/** @type {?} */
const parentEl = getParentRenderElement(view, renderHost, def);
if (parentEl) {
renderer.appendChild(parentEl, renderNode);
}
return { renderText: renderNode };
}
/**
* @param {?} view
* @param {?} def
* @param {?} v0
* @param {?} v1
* @param {?} v2
* @param {?} v3
* @param {?} v4
* @param {?} v5
* @param {?} v6
* @param {?} v7
* @param {?} v8
* @param {?} v9
* @return {?}
*/
function checkAndUpdateTextInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
/** @type {?} */
let changed = false;
/** @type {?} */
const bindings = def.bindings;
/** @type {?} */
const bindLen = bindings.length;
if (bindLen > 0 && checkAndUpdateBinding(view, def, 0, v0))
changed = true;
if (bindLen > 1 && checkAndUpdateBinding(view, def, 1, v1))
changed = true;
if (bindLen > 2 && checkAndUpdateBinding(view, def, 2, v2))
changed = true;
if (bindLen > 3 && checkAndUpdateBinding(view, def, 3, v3))
changed = true;
if (bindLen > 4 && checkAndUpdateBinding(view, def, 4, v4))
changed = true;
if (bindLen > 5 && checkAndUpdateBinding(view, def, 5, v5))
changed = true;
if (bindLen > 6 && checkAndUpdateBinding(view, def, 6, v6))
changed = true;
if (bindLen > 7 && checkAndUpdateBinding(view, def, 7, v7))
changed = true;
if (bindLen > 8 && checkAndUpdateBinding(view, def, 8, v8))
changed = true;
if (bindLen > 9 && checkAndUpdateBinding(view, def, 9, v9))
changed = true;
if (changed) {
/** @type {?} */
let value = (/** @type {?} */ (def.text)).prefix;
if (bindLen > 0)
value += _addInterpolationPart(v0, bindings[0]);
if (bindLen > 1)
value += _addInterpolationPart(v1, bindings[1]);
if (bindLen > 2)
value += _addInterpolationPart(v2, bindings[2]);
if (bindLen > 3)
value += _addInterpolationPart(v3, bindings[3]);
if (bindLen > 4)
value += _addInterpolationPart(v4, bindings[4]);
if (bindLen > 5)
value += _addInterpolationPart(v5, bindings[5]);
if (bindLen > 6)
value += _addInterpolationPart(v6, bindings[6]);
if (bindLen > 7)
value += _addInterpolationPart(v7, bindings[7]);
if (bindLen > 8)
value += _addInterpolationPart(v8, bindings[8]);
if (bindLen > 9)
value += _addInterpolationPart(v9, bindings[9]);
/** @type {?} */
const renderNode = asTextData(view, def.nodeIndex).renderText;
view.renderer.setValue(renderNode, value);
}
return changed;
}
/**
* @param {?} view
* @param {?} def
* @param {?} values
* @return {?}
*/
function checkAndUpdateTextDynamic(view, def, values) {
/** @type {?} */
const bindings = def.bindings;
/** @type {?} */
let changed = false;
for (let i = 0; i < values.length; i++) {
// Note: We need to loop over all values, so that
// the old values are updates as well!
if (checkAndUpdateBinding(view, def, i, values[i])) {
changed = true;
}
}
if (changed) {
/** @type {?} */
let value = '';
for (let i = 0; i < values.length; i++) {
value = value + _addInterpolationPart(values[i], bindings[i]);
}
value = (/** @type {?} */ (def.text)).prefix + value;
/** @type {?} */
const renderNode = asTextData(view, def.nodeIndex).renderText;
view.renderer.setValue(renderNode, value);
}
return changed;
}
/**
* @param {?} value
* @param {?} binding
* @return {?}
*/
function _addInterpolationPart(value, binding) {
/** @type {?} */
const valueStr = value != null ? value.toString() : '';
return valueStr + binding.suffix;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/view.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} flags
* @param {?} nodes
* @param {?=} updateDirectives
* @param {?=} updateRenderer
* @return {?}
*/
function viewDef(flags, nodes, updateDirectives, updateRenderer) {
// clone nodes and set auto calculated values
/** @type {?} */
let viewBindingCount = 0;
/** @type {?} */
let viewDisposableCount = 0;
/** @type {?} */
let viewNodeFlags = 0;
/** @type {?} */
let viewRootNodeFlags = 0;
/** @type {?} */
let viewMatchedQueries = 0;
/** @type {?} */
let currentParent = null;
/** @type {?} */
let currentRenderParent = null;
/** @type {?} */
let currentElementHasPublicProviders = false;
/** @type {?} */
let currentElementHasPrivateProviders = false;
/** @type {?} */
let lastRenderRootNode = null;
for (let i = 0; i < nodes.length; i++) {
/** @type {?} */
const node = nodes[i];
node.nodeIndex = i;
node.parent = currentParent;
node.bindingIndex = viewBindingCount;
node.outputIndex = viewDisposableCount;
node.renderParent = currentRenderParent;
viewNodeFlags |= node.flags;
viewMatchedQueries |= node.matchedQueryIds;
if (node.element) {
/** @type {?} */
const elDef = node.element;
elDef.publicProviders =
currentParent ? (/** @type {?} */ (currentParent.element)).publicProviders : Object.create(null);
elDef.allProviders = elDef.publicProviders;
// Note: We assume that all providers of an element are before any child element!
currentElementHasPublicProviders = false;
currentElementHasPrivateProviders = false;
if (node.element.template) {
viewMatchedQueries |= node.element.template.nodeMatchedQueries;
}
}
validateNode(currentParent, node, nodes.length);
viewBindingCount += node.bindings.length;
viewDisposableCount += node.outputs.length;
if (!currentRenderParent && (node.flags & 3 /* CatRenderNode */)) {
lastRenderRootNode = node;
}
if (node.flags & 20224 /* CatProvider */) {
if (!currentElementHasPublicProviders) {
currentElementHasPublicProviders = true;
// Use prototypical inheritance to not get O(n^2) complexity...
(/** @type {?} */ ((/** @type {?} */ (currentParent)).element)).publicProviders =
Object.create((/** @type {?} */ ((/** @type {?} */ (currentParent)).element)).publicProviders);
(/** @type {?} */ ((/** @type {?} */ (currentParent)).element)).allProviders = (/** @type {?} */ ((/** @type {?} */ (currentParent)).element)).publicProviders;
}
/** @type {?} */
const isPrivateService = (node.flags & 8192 /* PrivateProvider */) !== 0;
/** @type {?} */
const isComponent = (node.flags & 32768 /* Component */) !== 0;
if (!isPrivateService || isComponent) {
(/** @type {?} */ ((/** @type {?} */ ((/** @type {?} */ (currentParent)).element)).publicProviders))[tokenKey((/** @type {?} */ (node.provider)).token)] = node;
}
else {
if (!currentElementHasPrivateProviders) {
currentElementHasPrivateProviders = true;
// Use prototypical inheritance to not get O(n^2) complexity...
(/** @type {?} */ ((/** @type {?} */ (currentParent)).element)).allProviders =
Object.create((/** @type {?} */ ((/** @type {?} */ (currentParent)).element)).publicProviders);
}
(/** @type {?} */ ((/** @type {?} */ ((/** @type {?} */ (currentParent)).element)).allProviders))[tokenKey((/** @type {?} */ (node.provider)).token)] = node;
}
if (isComponent) {
(/** @type {?} */ ((/** @type {?} */ (currentParent)).element)).componentProvider = node;
}
}
if (currentParent) {
currentParent.childFlags |= node.flags;
currentParent.directChildFlags |= node.flags;
currentParent.childMatchedQueries |= node.matchedQueryIds;
if (node.element && node.element.template) {
currentParent.childMatchedQueries |= node.element.template.nodeMatchedQueries;
}
}
else {
viewRootNodeFlags |= node.flags;
}
if (node.childCount > 0) {
currentParent = node;
if (!isNgContainer(node)) {
currentRenderParent = node;
}
}
else {
// When the current node has no children, check if it is the last children of its parent.
// When it is, propagate the flags up.
// The loop is required because an element could be the last transitive children of several
// elements. We loop to either the root or the highest opened element (= with remaining
// children)
while (currentParent && i === currentParent.nodeIndex + currentParent.childCount) {
/** @type {?} */
const newParent = currentParent.parent;
if (newParent) {
newParent.childFlags |= currentParent.childFlags;
newParent.childMatchedQueries |= currentParent.childMatchedQueries;
}
currentParent = newParent;
// We also need to update the render parent & account for ng-container
if (currentParent && isNgContainer(currentParent)) {
currentRenderParent = currentParent.renderParent;
}
else {
currentRenderParent = currentParent;
}
}
}
}
/** @type {?} */
const handleEvent = (/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} eventName
* @param {?} event
* @return {?}
*/
(view, nodeIndex, eventName, event) => (/** @type {?} */ ((/** @type {?} */ (nodes[nodeIndex].element)).handleEvent))(view, eventName, event));
return {
// Will be filled later...
factory: null,
nodeFlags: viewNodeFlags,
rootNodeFlags: viewRootNodeFlags,
nodeMatchedQueries: viewMatchedQueries,
flags,
nodes: nodes,
updateDirectives: updateDirectives || NOOP,
updateRenderer: updateRenderer || NOOP,
handleEvent,
bindingCount: viewBindingCount,
outputCount: viewDisposableCount,
lastRenderRootNode
};
}
/**
* @param {?} node
* @return {?}
*/
function isNgContainer(node) {
return (node.flags & 1 /* TypeElement */) !== 0 && (/** @type {?} */ (node.element)).name === null;
}
/**
* @param {?} parent
* @param {?} node
* @param {?} nodeCount
* @return {?}
*/
function validateNode(parent, node, nodeCount) {
/** @type {?} */
const template = node.element && node.element.template;
if (template) {
if (!template.lastRenderRootNode) {
throw new Error(`Illegal State: Embedded templates without nodes are not allowed!`);
}
if (template.lastRenderRootNode &&
template.lastRenderRootNode.flags & 16777216 /* EmbeddedViews */) {
throw new Error(`Illegal State: Last root node of a template can't have embedded views, at index ${node.nodeIndex}!`);
}
}
if (node.flags & 20224 /* CatProvider */) {
/** @type {?} */
const parentFlags = parent ? parent.flags : 0;
if ((parentFlags & 1 /* TypeElement */) === 0) {
throw new Error(`Illegal State: StaticProvider/Directive nodes need to be children of elements or anchors, at index ${node.nodeIndex}!`);
}
}
if (node.query) {
if (node.flags & 67108864 /* TypeContentQuery */ &&
(!parent || (parent.flags & 16384 /* TypeDirective */) === 0)) {
throw new Error(`Illegal State: Content Query nodes need to be children of directives, at index ${node.nodeIndex}!`);
}
if (node.flags & 134217728 /* TypeViewQuery */ && parent) {
throw new Error(`Illegal State: View Query nodes have to be top level nodes, at index ${node.nodeIndex}!`);
}
}
if (node.childCount) {
/** @type {?} */
const parentEnd = parent ? parent.nodeIndex + parent.childCount : nodeCount - 1;
if (node.nodeIndex <= parentEnd && node.nodeIndex + node.childCount > parentEnd) {
throw new Error(`Illegal State: childCount of node leads outside of parent, at index ${node.nodeIndex}!`);
}
}
}
/**
* @param {?} parent
* @param {?} anchorDef
* @param {?} viewDef
* @param {?=} context
* @return {?}
*/
function createEmbeddedView(parent, anchorDef, viewDef, context) {
// embedded views are seen as siblings to the anchor, so we need
// to get the parent of the anchor and use it as parentIndex.
/** @type {?} */
const view = createView(parent.root, parent.renderer, parent, anchorDef, viewDef);
initView(view, parent.component, context);
createViewNodes(view);
return view;
}
/**
* @param {?} root
* @param {?} def
* @param {?=} context
* @return {?}
*/
function createRootView(root, def, context) {
/** @type {?} */
const view = createView(root, root.renderer, null, null, def);
initView(view, context, context);
createViewNodes(view);
return view;
}
/**
* @param {?} parentView
* @param {?} nodeDef
* @param {?} viewDef
* @param {?} hostElement
* @return {?}
*/
function createComponentView(parentView, nodeDef, viewDef, hostElement) {
/** @type {?} */
const rendererType = (/** @type {?} */ (nodeDef.element)).componentRendererType;
/** @type {?} */
let compRenderer;
if (!rendererType) {
compRenderer = parentView.root.renderer;
}
else {
compRenderer = parentView.root.rendererFactory.createRenderer(hostElement, rendererType);
}
return createView(parentView.root, compRenderer, parentView, (/** @type {?} */ (nodeDef.element)).componentProvider, viewDef);
}
/**
* @param {?} root
* @param {?} renderer
* @param {?} parent
* @param {?} parentNodeDef
* @param {?} def
* @return {?}
*/
function createView(root, renderer, parent, parentNodeDef, def) {
/** @type {?} */
const nodes = new Array(def.nodes.length);
/** @type {?} */
const disposables = def.outputCount ? new Array(def.outputCount) : null;
/** @type {?} */
const view = {
def,
parent,
viewContainerParent: null,
parentNodeDef,
context: null,
component: null,
nodes,
state: 13 /* CatInit */,
root,
renderer,
oldValues: new Array(def.bindingCount),
disposables,
initIndex: -1
};
return view;
}
/**
* @param {?} view
* @param {?} component
* @param {?} context
* @return {?}
*/
function initView(view, component, context) {
view.component = component;
view.context = context;
}
/**
* @param {?} view
* @return {?}
*/
function createViewNodes(view) {
/** @type {?} */
let renderHost;
if (isComponentView(view)) {
/** @type {?} */
const hostDef = view.parentNodeDef;
renderHost = asElementData((/** @type {?} */ (view.parent)), (/** @type {?} */ ((/** @type {?} */ (hostDef)).parent)).nodeIndex).renderElement;
}
/** @type {?} */
const def = view.def;
/** @type {?} */
const nodes = view.nodes;
for (let i = 0; i < def.nodes.length; i++) {
/** @type {?} */
const nodeDef = def.nodes[i];
Services.setCurrentNode(view, i);
/** @type {?} */
let nodeData;
switch (nodeDef.flags & 201347067 /* Types */) {
case 1 /* TypeElement */:
/** @type {?} */
const el = (/** @type {?} */ (createElement(view, renderHost, nodeDef)));
/** @type {?} */
let componentView = (/** @type {?} */ (undefined));
if (nodeDef.flags & 33554432 /* ComponentView */) {
/** @type {?} */
const compViewDef = resolveDefinition((/** @type {?} */ ((/** @type {?} */ (nodeDef.element)).componentView)));
componentView = Services.createComponentView(view, nodeDef, compViewDef, el);
}
listenToElementOutputs(view, componentView, nodeDef, el);
nodeData = (/** @type {?} */ ({
renderElement: el,
componentView,
viewContainer: null,
template: (/** @type {?} */ (nodeDef.element)).template ? createTemplateData(view, nodeDef) : undefined
}));
if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
nodeData.viewContainer = createViewContainerData(view, nodeDef, nodeData);
}
break;
case 2 /* TypeText */:
nodeData = (/** @type {?} */ (createText(view, renderHost, nodeDef)));
break;
case 512 /* TypeClassProvider */:
case 1024 /* TypeFactoryProvider */:
case 2048 /* TypeUseExistingProvider */:
case 256 /* TypeValueProvider */: {
nodeData = nodes[i];
if (!nodeData && !(nodeDef.flags & 4096 /* LazyProvider */)) {
/** @type {?} */
const instance = createProviderInstance(view, nodeDef);
nodeData = (/** @type {?} */ ({ instance }));
}
break;
}
case 16 /* TypePipe */: {
/** @type {?} */
const instance = createPipeInstance(view, nodeDef);
nodeData = (/** @type {?} */ ({ instance }));
break;
}
case 16384 /* TypeDirective */: {
nodeData = nodes[i];
if (!nodeData) {
/** @type {?} */
const instance = createDirectiveInstance(view, nodeDef);
nodeData = (/** @type {?} */ ({ instance }));
}
if (nodeDef.flags & 32768 /* Component */) {
/** @type {?} */
const compView = asElementData(view, (/** @type {?} */ (nodeDef.parent)).nodeIndex).componentView;
initView(compView, nodeData.instance, nodeData.instance);
}
break;
}
case 32 /* TypePureArray */:
case 64 /* TypePureObject */:
case 128 /* TypePurePipe */:
nodeData = (/** @type {?} */ (createPureExpression(view, nodeDef)));
break;
case 67108864 /* TypeContentQuery */:
case 134217728 /* TypeViewQuery */:
nodeData = (/** @type {?} */ (createQuery()));
break;
case 8 /* TypeNgContent */:
appendNgContent(view, renderHost, nodeDef);
// no runtime data needed for NgContent...
nodeData = undefined;
break;
}
nodes[i] = nodeData;
}
// Create the ViewData.nodes of component views after we created everything else,
// so that e.g. ng-content works
execComponentViewsAction(view, ViewAction.CreateViewNodes);
// fill static content and view queries
execQueriesAction(view, 67108864 /* TypeContentQuery */ | 134217728 /* TypeViewQuery */, 268435456 /* StaticQuery */, 0 /* CheckAndUpdate */);
}
/**
* @param {?} view
* @return {?}
*/
function checkNoChangesView(view) {
markProjectedViewsForCheck(view);
Services.updateDirectives(view, 1 /* CheckNoChanges */);
execEmbeddedViewsAction(view, ViewAction.CheckNoChanges);
Services.updateRenderer(view, 1 /* CheckNoChanges */);
execComponentViewsAction(view, ViewAction.CheckNoChanges);
// Note: We don't check queries for changes as we didn't do this in v2.x.
// TODO(tbosch): investigate if we can enable the check again in v5.x with a nicer error message.
view.state &= ~(64 /* CheckProjectedViews */ | 32 /* CheckProjectedView */);
}
/**
* @param {?} view
* @return {?}
*/
function checkAndUpdateView(view) {
if (view.state & 1 /* BeforeFirstCheck */) {
view.state &= ~1 /* BeforeFirstCheck */;
view.state |= 2 /* FirstCheck */;
}
else {
view.state &= ~2 /* FirstCheck */;
}
shiftInitState(view, 0 /* InitState_BeforeInit */, 256 /* InitState_CallingOnInit */);
markProjectedViewsForCheck(view);
Services.updateDirectives(view, 0 /* CheckAndUpdate */);
execEmbeddedViewsAction(view, ViewAction.CheckAndUpdate);
execQueriesAction(view, 67108864 /* TypeContentQuery */, 536870912 /* DynamicQuery */, 0 /* CheckAndUpdate */);
/** @type {?} */
let callInit = shiftInitState(view, 256 /* InitState_CallingOnInit */, 512 /* InitState_CallingAfterContentInit */);
callLifecycleHooksChildrenFirst(view, 2097152 /* AfterContentChecked */ | (callInit ? 1048576 /* AfterContentInit */ : 0));
Services.updateRenderer(view, 0 /* CheckAndUpdate */);
execComponentViewsAction(view, ViewAction.CheckAndUpdate);
execQueriesAction(view, 134217728 /* TypeViewQuery */, 536870912 /* DynamicQuery */, 0 /* CheckAndUpdate */);
callInit = shiftInitState(view, 512 /* InitState_CallingAfterContentInit */, 768 /* InitState_CallingAfterViewInit */);
callLifecycleHooksChildrenFirst(view, 8388608 /* AfterViewChecked */ | (callInit ? 4194304 /* AfterViewInit */ : 0));
if (view.def.flags & 2 /* OnPush */) {
view.state &= ~8 /* ChecksEnabled */;
}
view.state &= ~(64 /* CheckProjectedViews */ | 32 /* CheckProjectedView */);
shiftInitState(view, 768 /* InitState_CallingAfterViewInit */, 1024 /* InitState_AfterInit */);
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} argStyle
* @param {?=} v0
* @param {?=} v1
* @param {?=} v2
* @param {?=} v3
* @param {?=} v4
* @param {?=} v5
* @param {?=} v6
* @param {?=} v7
* @param {?=} v8
* @param {?=} v9
* @return {?}
*/
function checkAndUpdateNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
if (argStyle === 0 /* Inline */) {
return checkAndUpdateNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
}
else {
return checkAndUpdateNodeDynamic(view, nodeDef, v0);
}
}
/**
* @param {?} view
* @return {?}
*/
function markProjectedViewsForCheck(view) {
/** @type {?} */
const def = view.def;
if (!(def.nodeFlags & 4 /* ProjectedTemplate */)) {
return;
}
for (let i = 0; i < def.nodes.length; i++) {
/** @type {?} */
const nodeDef = def.nodes[i];
if (nodeDef.flags & 4 /* ProjectedTemplate */) {
/** @type {?} */
const projectedViews = asElementData(view, i).template._projectedViews;
if (projectedViews) {
for (let i = 0; i < projectedViews.length; i++) {
/** @type {?} */
const projectedView = projectedViews[i];
projectedView.state |= 32 /* CheckProjectedView */;
markParentViewsForCheckProjectedViews(projectedView, view);
}
}
}
else if ((nodeDef.childFlags & 4 /* ProjectedTemplate */) === 0) {
// a parent with leafs
// no child is a component,
// then skip the children
i += nodeDef.childCount;
}
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?=} v0
* @param {?=} v1
* @param {?=} v2
* @param {?=} v3
* @param {?=} v4
* @param {?=} v5
* @param {?=} v6
* @param {?=} v7
* @param {?=} v8
* @param {?=} v9
* @return {?}
*/
function checkAndUpdateNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
switch (nodeDef.flags & 201347067 /* Types */) {
case 1 /* TypeElement */:
return checkAndUpdateElementInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
case 2 /* TypeText */:
return checkAndUpdateTextInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
case 16384 /* TypeDirective */:
return checkAndUpdateDirectiveInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
case 32 /* TypePureArray */:
case 64 /* TypePureObject */:
case 128 /* TypePurePipe */:
return checkAndUpdatePureExpressionInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
default:
throw 'unreachable';
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} values
* @return {?}
*/
function checkAndUpdateNodeDynamic(view, nodeDef, values) {
switch (nodeDef.flags & 201347067 /* Types */) {
case 1 /* TypeElement */:
return checkAndUpdateElementDynamic(view, nodeDef, values);
case 2 /* TypeText */:
return checkAndUpdateTextDynamic(view, nodeDef, values);
case 16384 /* TypeDirective */:
return checkAndUpdateDirectiveDynamic(view, nodeDef, values);
case 32 /* TypePureArray */:
case 64 /* TypePureObject */:
case 128 /* TypePurePipe */:
return checkAndUpdatePureExpressionDynamic(view, nodeDef, values);
default:
throw 'unreachable';
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} argStyle
* @param {?=} v0
* @param {?=} v1
* @param {?=} v2
* @param {?=} v3
* @param {?=} v4
* @param {?=} v5
* @param {?=} v6
* @param {?=} v7
* @param {?=} v8
* @param {?=} v9
* @return {?}
*/
function checkNoChangesNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
if (argStyle === 0 /* Inline */) {
checkNoChangesNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
}
else {
checkNoChangesNodeDynamic(view, nodeDef, v0);
}
// Returning false is ok here as we would have thrown in case of a change.
return false;
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} v0
* @param {?} v1
* @param {?} v2
* @param {?} v3
* @param {?} v4
* @param {?} v5
* @param {?} v6
* @param {?} v7
* @param {?} v8
* @param {?} v9
* @return {?}
*/
function checkNoChangesNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
/** @type {?} */
const bindLen = nodeDef.bindings.length;
if (bindLen > 0)
checkBindingNoChanges(view, nodeDef, 0, v0);
if (bindLen > 1)
checkBindingNoChanges(view, nodeDef, 1, v1);
if (bindLen > 2)
checkBindingNoChanges(view, nodeDef, 2, v2);
if (bindLen > 3)
checkBindingNoChanges(view, nodeDef, 3, v3);
if (bindLen > 4)
checkBindingNoChanges(view, nodeDef, 4, v4);
if (bindLen > 5)
checkBindingNoChanges(view, nodeDef, 5, v5);
if (bindLen > 6)
checkBindingNoChanges(view, nodeDef, 6, v6);
if (bindLen > 7)
checkBindingNoChanges(view, nodeDef, 7, v7);
if (bindLen > 8)
checkBindingNoChanges(view, nodeDef, 8, v8);
if (bindLen > 9)
checkBindingNoChanges(view, nodeDef, 9, v9);
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} values
* @return {?}
*/
function checkNoChangesNodeDynamic(view, nodeDef, values) {
for (let i = 0; i < values.length; i++) {
checkBindingNoChanges(view, nodeDef, i, values[i]);
}
}
/**
* Workaround https://github.com/angular/tsickle/issues/497
* @suppress {misplacedTypeAnnotation}
* @param {?} view
* @param {?} nodeDef
* @return {?}
*/
function checkNoChangesQuery(view, nodeDef) {
/** @type {?} */
const queryList = asQueryList(view, nodeDef.nodeIndex);
if (queryList.dirty) {
throw expressionChangedAfterItHasBeenCheckedError(Services.createDebugContext(view, nodeDef.nodeIndex), `Query ${(/** @type {?} */ (nodeDef.query)).id} not dirty`, `Query ${(/** @type {?} */ (nodeDef.query)).id} dirty`, (view.state & 1 /* BeforeFirstCheck */) !== 0);
}
}
/**
* @param {?} view
* @return {?}
*/
function destroyView(view) {
if (view.state & 128 /* Destroyed */) {
return;
}
execEmbeddedViewsAction(view, ViewAction.Destroy);
execComponentViewsAction(view, ViewAction.Destroy);
callLifecycleHooksChildrenFirst(view, 131072 /* OnDestroy */);
if (view.disposables) {
for (let i = 0; i < view.disposables.length; i++) {
view.disposables[i]();
}
}
detachProjectedView(view);
if (view.renderer.destroyNode) {
destroyViewNodes(view);
}
if (isComponentView(view)) {
view.renderer.destroy();
}
view.state |= 128 /* Destroyed */;
}
/**
* @param {?} view
* @return {?}
*/
function destroyViewNodes(view) {
/** @type {?} */
const len = view.def.nodes.length;
for (let i = 0; i < len; i++) {
/** @type {?} */
const def = view.def.nodes[i];
if (def.flags & 1 /* TypeElement */) {
(/** @type {?} */ (view.renderer.destroyNode))(asElementData(view, i).renderElement);
}
else if (def.flags & 2 /* TypeText */) {
(/** @type {?} */ (view.renderer.destroyNode))(asTextData(view, i).renderText);
}
else if (def.flags & 67108864 /* TypeContentQuery */ || def.flags & 134217728 /* TypeViewQuery */) {
asQueryList(view, i).destroy();
}
}
}
/** @enum {number} */
const ViewAction = {
CreateViewNodes: 0,
CheckNoChanges: 1,
CheckNoChangesProjectedViews: 2,
CheckAndUpdate: 3,
CheckAndUpdateProjectedViews: 4,
Destroy: 5,
};
ViewAction[ViewAction.CreateViewNodes] = 'CreateViewNodes';
ViewAction[ViewAction.CheckNoChanges] = 'CheckNoChanges';
ViewAction[ViewAction.CheckNoChangesProjectedViews] = 'CheckNoChangesProjectedViews';
ViewAction[ViewAction.CheckAndUpdate] = 'CheckAndUpdate';
ViewAction[ViewAction.CheckAndUpdateProjectedViews] = 'CheckAndUpdateProjectedViews';
ViewAction[ViewAction.Destroy] = 'Destroy';
/**
* @param {?} view
* @param {?} action
* @return {?}
*/
function execComponentViewsAction(view, action) {
/** @type {?} */
const def = view.def;
if (!(def.nodeFlags & 33554432 /* ComponentView */)) {
return;
}
for (let i = 0; i < def.nodes.length; i++) {
/** @type {?} */
const nodeDef = def.nodes[i];
if (nodeDef.flags & 33554432 /* ComponentView */) {
// a leaf
callViewAction(asElementData(view, i).componentView, action);
}
else if ((nodeDef.childFlags & 33554432 /* ComponentView */) === 0) {
// a parent with leafs
// no child is a component,
// then skip the children
i += nodeDef.childCount;
}
}
}
/**
* @param {?} view
* @param {?} action
* @return {?}
*/
function execEmbeddedViewsAction(view, action) {
/** @type {?} */
const def = view.def;
if (!(def.nodeFlags & 16777216 /* EmbeddedViews */)) {
return;
}
for (let i = 0; i < def.nodes.length; i++) {
/** @type {?} */
const nodeDef = def.nodes[i];
if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
// a leaf
/** @type {?} */
const embeddedViews = (/** @type {?} */ (asElementData(view, i).viewContainer))._embeddedViews;
for (let k = 0; k < embeddedViews.length; k++) {
callViewAction(embeddedViews[k], action);
}
}
else if ((nodeDef.childFlags & 16777216 /* EmbeddedViews */) === 0) {
// a parent with leafs
// no child is a component,
// then skip the children
i += nodeDef.childCount;
}
}
}
/**
* @param {?} view
* @param {?} action
* @return {?}
*/
function callViewAction(view, action) {
/** @type {?} */
const viewState = view.state;
switch (action) {
case ViewAction.CheckNoChanges:
if ((viewState & 128 /* Destroyed */) === 0) {
if ((viewState & 12 /* CatDetectChanges */) === 12 /* CatDetectChanges */) {
checkNoChangesView(view);
}
else if (viewState & 64 /* CheckProjectedViews */) {
execProjectedViewsAction(view, ViewAction.CheckNoChangesProjectedViews);
}
}
break;
case ViewAction.CheckNoChangesProjectedViews:
if ((viewState & 128 /* Destroyed */) === 0) {
if (viewState & 32 /* CheckProjectedView */) {
checkNoChangesView(view);
}
else if (viewState & 64 /* CheckProjectedViews */) {
execProjectedViewsAction(view, action);
}
}
break;
case ViewAction.CheckAndUpdate:
if ((viewState & 128 /* Destroyed */) === 0) {
if ((viewState & 12 /* CatDetectChanges */) === 12 /* CatDetectChanges */) {
checkAndUpdateView(view);
}
else if (viewState & 64 /* CheckProjectedViews */) {
execProjectedViewsAction(view, ViewAction.CheckAndUpdateProjectedViews);
}
}
break;
case ViewAction.CheckAndUpdateProjectedViews:
if ((viewState & 128 /* Destroyed */) === 0) {
if (viewState & 32 /* CheckProjectedView */) {
checkAndUpdateView(view);
}
else if (viewState & 64 /* CheckProjectedViews */) {
execProjectedViewsAction(view, action);
}
}
break;
case ViewAction.Destroy:
// Note: destroyView recurses over all views,
// so we don't need to special case projected views here.
destroyView(view);
break;
case ViewAction.CreateViewNodes:
createViewNodes(view);
break;
}
}
/**
* @param {?} view
* @param {?} action
* @return {?}
*/
function execProjectedViewsAction(view, action) {
execEmbeddedViewsAction(view, action);
execComponentViewsAction(view, action);
}
/**
* @param {?} view
* @param {?} queryFlags
* @param {?} staticDynamicQueryFlag
* @param {?} checkType
* @return {?}
*/
function execQueriesAction(view, queryFlags, staticDynamicQueryFlag, checkType) {
if (!(view.def.nodeFlags & queryFlags) || !(view.def.nodeFlags & staticDynamicQueryFlag)) {
return;
}
/** @type {?} */
const nodeCount = view.def.nodes.length;
for (let i = 0; i < nodeCount; i++) {
/** @type {?} */
const nodeDef = view.def.nodes[i];
if ((nodeDef.flags & queryFlags) && (nodeDef.flags & staticDynamicQueryFlag)) {
Services.setCurrentNode(view, nodeDef.nodeIndex);
switch (checkType) {
case 0 /* CheckAndUpdate */:
checkAndUpdateQuery(view, nodeDef);
break;
case 1 /* CheckNoChanges */:
checkNoChangesQuery(view, nodeDef);
break;
}
}
if (!(nodeDef.childFlags & queryFlags) || !(nodeDef.childFlags & staticDynamicQueryFlag)) {
// no child has a matching query
// then skip the children
i += nodeDef.childCount;
}
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/services.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
let initialized = false;
/**
* @return {?}
*/
function initServicesIfNeeded() {
if (initialized) {
return;
}
initialized = true;
/** @type {?} */
const services = isDevMode() ? createDebugServices() : createProdServices();
Services.setCurrentNode = services.setCurrentNode;
Services.createRootView = services.createRootView;
Services.createEmbeddedView = services.createEmbeddedView;
Services.createComponentView = services.createComponentView;
Services.createNgModuleRef = services.createNgModuleRef;
Services.overrideProvider = services.overrideProvider;
Services.overrideComponentView = services.overrideComponentView;
Services.clearOverrides = services.clearOverrides;
Services.checkAndUpdateView = services.checkAndUpdateView;
Services.checkNoChangesView = services.checkNoChangesView;
Services.destroyView = services.destroyView;
Services.resolveDep = resolveDep;
Services.createDebugContext = services.createDebugContext;
Services.handleEvent = services.handleEvent;
Services.updateDirectives = services.updateDirectives;
Services.updateRenderer = services.updateRenderer;
Services.dirtyParentQueries = dirtyParentQueries;
}
/**
* @return {?}
*/
function createProdServices() {
return {
setCurrentNode: (/**
* @return {?}
*/
() => { }),
createRootView: createProdRootView,
createEmbeddedView: createEmbeddedView,
createComponentView: createComponentView,
createNgModuleRef: createNgModuleRef,
overrideProvider: NOOP,
overrideComponentView: NOOP,
clearOverrides: NOOP,
checkAndUpdateView: checkAndUpdateView,
checkNoChangesView: checkNoChangesView,
destroyView: destroyView,
createDebugContext: (/**
* @param {?} view
* @param {?} nodeIndex
* @return {?}
*/
(view, nodeIndex) => new DebugContext_(view, nodeIndex)),
handleEvent: (/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} eventName
* @param {?} event
* @return {?}
*/
(view, nodeIndex, eventName, event) => view.def.handleEvent(view, nodeIndex, eventName, event)),
updateDirectives: (/**
* @param {?} view
* @param {?} checkType
* @return {?}
*/
(view, checkType) => view.def.updateDirectives(checkType === 0 /* CheckAndUpdate */ ? prodCheckAndUpdateNode : prodCheckNoChangesNode, view)),
updateRenderer: (/**
* @param {?} view
* @param {?} checkType
* @return {?}
*/
(view, checkType) => view.def.updateRenderer(checkType === 0 /* CheckAndUpdate */ ? prodCheckAndUpdateNode : prodCheckNoChangesNode, view)),
};
}
/**
* @return {?}
*/
function createDebugServices() {
return {
setCurrentNode: debugSetCurrentNode,
createRootView: debugCreateRootView,
createEmbeddedView: debugCreateEmbeddedView,
createComponentView: debugCreateComponentView,
createNgModuleRef: debugCreateNgModuleRef,
overrideProvider: debugOverrideProvider,
overrideComponentView: debugOverrideComponentView,
clearOverrides: debugClearOverrides,
checkAndUpdateView: debugCheckAndUpdateView,
checkNoChangesView: debugCheckNoChangesView,
destroyView: debugDestroyView,
createDebugContext: (/**
* @param {?} view
* @param {?} nodeIndex
* @return {?}
*/
(view, nodeIndex) => new DebugContext_(view, nodeIndex)),
handleEvent: debugHandleEvent,
updateDirectives: debugUpdateDirectives,
updateRenderer: debugUpdateRenderer,
};
}
/**
* @param {?} elInjector
* @param {?} projectableNodes
* @param {?} rootSelectorOrNode
* @param {?} def
* @param {?} ngModule
* @param {?=} context
* @return {?}
*/
function createProdRootView(elInjector, projectableNodes, rootSelectorOrNode, def, ngModule, context) {
/** @type {?} */
const rendererFactory = ngModule.injector.get(RendererFactory2);
return createRootView(createRootData(elInjector, ngModule, rendererFactory, projectableNodes, rootSelectorOrNode), def, context);
}
/**
* @param {?} elInjector
* @param {?} projectableNodes
* @param {?} rootSelectorOrNode
* @param {?} def
* @param {?} ngModule
* @param {?=} context
* @return {?}
*/
function debugCreateRootView(elInjector, projectableNodes, rootSelectorOrNode, def, ngModule, context) {
/** @type {?} */
const rendererFactory = ngModule.injector.get(RendererFactory2);
/** @type {?} */
const root = createRootData(elInjector, ngModule, new DebugRendererFactory2(rendererFactory), projectableNodes, rootSelectorOrNode);
/** @type {?} */
const defWithOverride = applyProviderOverridesToView(def);
return callWithDebugContext(DebugAction.create, createRootView, null, [root, defWithOverride, context]);
}
/**
* @param {?} elInjector
* @param {?} ngModule
* @param {?} rendererFactory
* @param {?} projectableNodes
* @param {?} rootSelectorOrNode
* @return {?}
*/
function createRootData(elInjector, ngModule, rendererFactory, projectableNodes, rootSelectorOrNode) {
/** @type {?} */
const sanitizer = ngModule.injector.get(Sanitizer);
/** @type {?} */
const errorHandler = ngModule.injector.get(ErrorHandler);
/** @type {?} */
const renderer = rendererFactory.createRenderer(null, null);
return {
ngModule,
injector: elInjector,
projectableNodes,
selectorOrNode: rootSelectorOrNode,
sanitizer,
rendererFactory,
renderer,
errorHandler
};
}
/**
* @param {?} parentView
* @param {?} anchorDef
* @param {?} viewDef
* @param {?=} context
* @return {?}
*/
function debugCreateEmbeddedView(parentView, anchorDef, viewDef, context) {
/** @type {?} */
const defWithOverride = applyProviderOverridesToView(viewDef);
return callWithDebugContext(DebugAction.create, createEmbeddedView, null, [parentView, anchorDef, defWithOverride, context]);
}
/**
* @param {?} parentView
* @param {?} nodeDef
* @param {?} viewDef
* @param {?} hostElement
* @return {?}
*/
function debugCreateComponentView(parentView, nodeDef, viewDef, hostElement) {
/** @type {?} */
const overrideComponentView = viewDefOverrides.get((/** @type {?} */ ((/** @type {?} */ ((/** @type {?} */ (nodeDef.element)).componentProvider)).provider)).token);
if (overrideComponentView) {
viewDef = overrideComponentView;
}
else {
viewDef = applyProviderOverridesToView(viewDef);
}
return callWithDebugContext(DebugAction.create, createComponentView, null, [parentView, nodeDef, viewDef, hostElement]);
}
/**
* @param {?} moduleType
* @param {?} parentInjector
* @param {?} bootstrapComponents
* @param {?} def
* @return {?}
*/
function debugCreateNgModuleRef(moduleType, parentInjector, bootstrapComponents, def) {
/** @type {?} */
const defWithOverride = applyProviderOverridesToNgModule(def);
return createNgModuleRef(moduleType, parentInjector, bootstrapComponents, defWithOverride);
}
/** @type {?} */
const providerOverrides = new Map();
/** @type {?} */
const providerOverridesWithScope = new Map();
/** @type {?} */
const viewDefOverrides = new Map();
/**
* @param {?} override
* @return {?}
*/
function debugOverrideProvider(override) {
providerOverrides.set(override.token, override);
/** @type {?} */
let injectableDef;
if (typeof override.token === 'function' && (injectableDef = getInjectableDef(override.token)) &&
typeof injectableDef.providedIn === 'function') {
providerOverridesWithScope.set((/** @type {?} */ (override.token)), override);
}
}
/**
* @param {?} comp
* @param {?} compFactory
* @return {?}
*/
function debugOverrideComponentView(comp, compFactory) {
/** @type {?} */
const hostViewDef = resolveDefinition(getComponentViewDefinitionFactory(compFactory));
/** @type {?} */
const compViewDef = resolveDefinition((/** @type {?} */ ((/** @type {?} */ (hostViewDef.nodes[0].element)).componentView)));
viewDefOverrides.set(comp, compViewDef);
}
/**
* @return {?}
*/
function debugClearOverrides() {
providerOverrides.clear();
providerOverridesWithScope.clear();
viewDefOverrides.clear();
}
// Notes about the algorithm:
// 1) Locate the providers of an element and check if one of them was overwritten
// 2) Change the providers of that element
//
// We only create new datastructures if we need to, to keep perf impact
// reasonable.
/**
* @param {?} def
* @return {?}
*/
function applyProviderOverridesToView(def) {
if (providerOverrides.size === 0) {
return def;
}
/** @type {?} */
const elementIndicesWithOverwrittenProviders = findElementIndicesWithOverwrittenProviders(def);
if (elementIndicesWithOverwrittenProviders.length === 0) {
return def;
}
// clone the whole view definition,
// as it maintains references between the nodes that are hard to update.
def = (/** @type {?} */ (def.factory))((/**
* @return {?}
*/
() => NOOP));
for (let i = 0; i < elementIndicesWithOverwrittenProviders.length; i++) {
applyProviderOverridesToElement(def, elementIndicesWithOverwrittenProviders[i]);
}
return def;
/**
* @param {?} def
* @return {?}
*/
function findElementIndicesWithOverwrittenProviders(def) {
/** @type {?} */
const elIndicesWithOverwrittenProviders = [];
/** @type {?} */
let lastElementDef = null;
for (let i = 0; i < def.nodes.length; i++) {
/** @type {?} */
const nodeDef = def.nodes[i];
if (nodeDef.flags & 1 /* TypeElement */) {
lastElementDef = nodeDef;
}
if (lastElementDef && nodeDef.flags & 3840 /* CatProviderNoDirective */ &&
providerOverrides.has((/** @type {?} */ (nodeDef.provider)).token)) {
elIndicesWithOverwrittenProviders.push((/** @type {?} */ (lastElementDef)).nodeIndex);
lastElementDef = null;
}
}
return elIndicesWithOverwrittenProviders;
}
/**
* @param {?} viewDef
* @param {?} elIndex
* @return {?}
*/
function applyProviderOverridesToElement(viewDef, elIndex) {
for (let i = elIndex + 1; i < viewDef.nodes.length; i++) {
/** @type {?} */
const nodeDef = viewDef.nodes[i];
if (nodeDef.flags & 1 /* TypeElement */) {
// stop at the next element
return;
}
if (nodeDef.flags & 3840 /* CatProviderNoDirective */) {
/** @type {?} */
const provider = (/** @type {?} */ (nodeDef.provider));
/** @type {?} */
const override = providerOverrides.get(provider.token);
if (override) {
nodeDef.flags = (nodeDef.flags & ~3840 /* CatProviderNoDirective */) | override.flags;
provider.deps = splitDepsDsl(override.deps);
provider.value = override.value;
}
}
}
}
}
// Notes about the algorithm:
// We only create new datastructures if we need to, to keep perf impact
// reasonable.
/**
* @param {?} def
* @return {?}
*/
function applyProviderOverridesToNgModule(def) {
const { hasOverrides, hasDeprecatedOverrides } = calcHasOverrides(def);
if (!hasOverrides) {
return def;
}
// clone the whole view definition,
// as it maintains references between the nodes that are hard to update.
def = (/** @type {?} */ (def.factory))((/**
* @return {?}
*/
() => NOOP));
applyProviderOverrides(def);
return def;
/**
* @param {?} def
* @return {?}
*/
function calcHasOverrides(def) {
/** @type {?} */
let hasOverrides = false;
/** @type {?} */
let hasDeprecatedOverrides = false;
if (providerOverrides.size === 0) {
return { hasOverrides, hasDeprecatedOverrides };
}
def.providers.forEach((/**
* @param {?} node
* @return {?}
*/
node => {
/** @type {?} */
const override = providerOverrides.get(node.token);
if ((node.flags & 3840 /* CatProviderNoDirective */) && override) {
hasOverrides = true;
hasDeprecatedOverrides = hasDeprecatedOverrides || override.deprecatedBehavior;
}
}));
def.modules.forEach((/**
* @param {?} module
* @return {?}
*/
module => {
providerOverridesWithScope.forEach((/**
* @param {?} override
* @param {?} token
* @return {?}
*/
(override, token) => {
if ((/** @type {?} */ (getInjectableDef(token))).providedIn === module) {
hasOverrides = true;
hasDeprecatedOverrides = hasDeprecatedOverrides || override.deprecatedBehavior;
}
}));
}));
return { hasOverrides, hasDeprecatedOverrides };
}
/**
* @param {?} def
* @return {?}
*/
function applyProviderOverrides(def) {
for (let i = 0; i < def.providers.length; i++) {
/** @type {?} */
const provider = def.providers[i];
if (hasDeprecatedOverrides) {
// We had a bug where me made
// all providers lazy. Keep this logic behind a flag
// for migrating existing users.
provider.flags |= 4096 /* LazyProvider */;
}
/** @type {?} */
const override = providerOverrides.get(provider.token);
if (override) {
provider.flags = (provider.flags & ~3840 /* CatProviderNoDirective */) | override.flags;
provider.deps = splitDepsDsl(override.deps);
provider.value = override.value;
}
}
if (providerOverridesWithScope.size > 0) {
/** @type {?} */
let moduleSet = new Set(def.modules);
providerOverridesWithScope.forEach((/**
* @param {?} override
* @param {?} token
* @return {?}
*/
(override, token) => {
if (moduleSet.has((/** @type {?} */ (getInjectableDef(token))).providedIn)) {
/** @type {?} */
let provider = {
token: token,
flags: override.flags | (hasDeprecatedOverrides ? 4096 /* LazyProvider */ : 0 /* None */),
deps: splitDepsDsl(override.deps),
value: override.value,
index: def.providers.length,
};
def.providers.push(provider);
def.providersByKey[tokenKey(token)] = provider;
}
}));
}
}
}
/**
* @param {?} view
* @param {?} checkIndex
* @param {?} argStyle
* @param {?=} v0
* @param {?=} v1
* @param {?=} v2
* @param {?=} v3
* @param {?=} v4
* @param {?=} v5
* @param {?=} v6
* @param {?=} v7
* @param {?=} v8
* @param {?=} v9
* @return {?}
*/
function prodCheckAndUpdateNode(view, checkIndex, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
/** @type {?} */
const nodeDef = view.def.nodes[checkIndex];
checkAndUpdateNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
return (nodeDef.flags & 224 /* CatPureExpression */) ?
asPureExpressionData(view, checkIndex).value :
undefined;
}
/**
* @param {?} view
* @param {?} checkIndex
* @param {?} argStyle
* @param {?=} v0
* @param {?=} v1
* @param {?=} v2
* @param {?=} v3
* @param {?=} v4
* @param {?=} v5
* @param {?=} v6
* @param {?=} v7
* @param {?=} v8
* @param {?=} v9
* @return {?}
*/
function prodCheckNoChangesNode(view, checkIndex, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
/** @type {?} */
const nodeDef = view.def.nodes[checkIndex];
checkNoChangesNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
return (nodeDef.flags & 224 /* CatPureExpression */) ?
asPureExpressionData(view, checkIndex).value :
undefined;
}
/**
* @param {?} view
* @return {?}
*/
function debugCheckAndUpdateView(view) {
return callWithDebugContext(DebugAction.detectChanges, checkAndUpdateView, null, [view]);
}
/**
* @param {?} view
* @return {?}
*/
function debugCheckNoChangesView(view) {
return callWithDebugContext(DebugAction.checkNoChanges, checkNoChangesView, null, [view]);
}
/**
* @param {?} view
* @return {?}
*/
function debugDestroyView(view) {
return callWithDebugContext(DebugAction.destroy, destroyView, null, [view]);
}
/** @enum {number} */
const DebugAction = {
create: 0,
detectChanges: 1,
checkNoChanges: 2,
destroy: 3,
handleEvent: 4,
};
DebugAction[DebugAction.create] = 'create';
DebugAction[DebugAction.detectChanges] = 'detectChanges';
DebugAction[DebugAction.checkNoChanges] = 'checkNoChanges';
DebugAction[DebugAction.destroy] = 'destroy';
DebugAction[DebugAction.handleEvent] = 'handleEvent';
/** @type {?} */
let _currentAction;
/** @type {?} */
let _currentView;
/** @type {?} */
let _currentNodeIndex;
/**
* @param {?} view
* @param {?} nodeIndex
* @return {?}
*/
function debugSetCurrentNode(view, nodeIndex) {
_currentView = view;
_currentNodeIndex = nodeIndex;
}
/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} eventName
* @param {?} event
* @return {?}
*/
function debugHandleEvent(view, nodeIndex, eventName, event) {
debugSetCurrentNode(view, nodeIndex);
return callWithDebugContext(DebugAction.handleEvent, view.def.handleEvent, null, [view, nodeIndex, eventName, event]);
}
/**
* @param {?} view
* @param {?} checkType
* @return {?}
*/
function debugUpdateDirectives(view, checkType) {
if (view.state & 128 /* Destroyed */) {
throw viewDestroyedError(DebugAction[_currentAction]);
}
debugSetCurrentNode(view, nextDirectiveWithBinding(view, 0));
return view.def.updateDirectives(debugCheckDirectivesFn, view);
/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} argStyle
* @param {...?} values
* @return {?}
*/
function debugCheckDirectivesFn(view, nodeIndex, argStyle, ...values) {
/** @type {?} */
const nodeDef = view.def.nodes[nodeIndex];
if (checkType === 0 /* CheckAndUpdate */) {
debugCheckAndUpdateNode(view, nodeDef, argStyle, values);
}
else {
debugCheckNoChangesNode(view, nodeDef, argStyle, values);
}
if (nodeDef.flags & 16384 /* TypeDirective */) {
debugSetCurrentNode(view, nextDirectiveWithBinding(view, nodeIndex));
}
return (nodeDef.flags & 224 /* CatPureExpression */) ?
asPureExpressionData(view, nodeDef.nodeIndex).value :
undefined;
}
}
/**
* @param {?} view
* @param {?} checkType
* @return {?}
*/
function debugUpdateRenderer(view, checkType) {
if (view.state & 128 /* Destroyed */) {
throw viewDestroyedError(DebugAction[_currentAction]);
}
debugSetCurrentNode(view, nextRenderNodeWithBinding(view, 0));
return view.def.updateRenderer(debugCheckRenderNodeFn, view);
/**
* @param {?} view
* @param {?} nodeIndex
* @param {?} argStyle
* @param {...?} values
* @return {?}
*/
function debugCheckRenderNodeFn(view, nodeIndex, argStyle, ...values) {
/** @type {?} */
const nodeDef = view.def.nodes[nodeIndex];
if (checkType === 0 /* CheckAndUpdate */) {
debugCheckAndUpdateNode(view, nodeDef, argStyle, values);
}
else {
debugCheckNoChangesNode(view, nodeDef, argStyle, values);
}
if (nodeDef.flags & 3 /* CatRenderNode */) {
debugSetCurrentNode(view, nextRenderNodeWithBinding(view, nodeIndex));
}
return (nodeDef.flags & 224 /* CatPureExpression */) ?
asPureExpressionData(view, nodeDef.nodeIndex).value :
undefined;
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} argStyle
* @param {?} givenValues
* @return {?}
*/
function debugCheckAndUpdateNode(view, nodeDef, argStyle, givenValues) {
/** @type {?} */
const changed = ((/** @type {?} */ (checkAndUpdateNode)))(view, nodeDef, argStyle, ...givenValues);
if (changed) {
/** @type {?} */
const values = argStyle === 1 /* Dynamic */ ? givenValues[0] : givenValues;
if (nodeDef.flags & 16384 /* TypeDirective */) {
/** @type {?} */
const bindingValues = {};
for (let i = 0; i < nodeDef.bindings.length; i++) {
/** @type {?} */
const binding = nodeDef.bindings[i];
/** @type {?} */
const value = values[i];
if (binding.flags & 8 /* TypeProperty */) {
bindingValues[normalizeDebugBindingName((/** @type {?} */ (binding.nonMinifiedName)))] =
normalizeDebugBindingValue(value);
}
}
/** @type {?} */
const elDef = (/** @type {?} */ (nodeDef.parent));
/** @type {?} */
const el = asElementData(view, elDef.nodeIndex).renderElement;
if (!(/** @type {?} */ (elDef.element)).name) {
// a comment.
view.renderer.setValue(el, escapeCommentText(`bindings=${JSON.stringify(bindingValues, null, 2)}`));
}
else {
// a regular element.
for (let attr in bindingValues) {
/** @type {?} */
const value = bindingValues[attr];
if (value != null) {
view.renderer.setAttribute(el, attr, value);
}
else {
view.renderer.removeAttribute(el, attr);
}
}
}
}
}
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} argStyle
* @param {?} values
* @return {?}
*/
function debugCheckNoChangesNode(view, nodeDef, argStyle, values) {
((/** @type {?} */ (checkNoChangesNode)))(view, nodeDef, argStyle, ...values);
}
/**
* @param {?} view
* @param {?} nodeIndex
* @return {?}
*/
function nextDirectiveWithBinding(view, nodeIndex) {
for (let i = nodeIndex; i < view.def.nodes.length; i++) {
/** @type {?} */
const nodeDef = view.def.nodes[i];
if (nodeDef.flags & 16384 /* TypeDirective */ && nodeDef.bindings && nodeDef.bindings.length) {
return i;
}
}
return null;
}
/**
* @param {?} view
* @param {?} nodeIndex
* @return {?}
*/
function nextRenderNodeWithBinding(view, nodeIndex) {
for (let i = nodeIndex; i < view.def.nodes.length; i++) {
/** @type {?} */
const nodeDef = view.def.nodes[i];
if ((nodeDef.flags & 3 /* CatRenderNode */) && nodeDef.bindings && nodeDef.bindings.length) {
return i;
}
}
return null;
}
class DebugContext_ {
/**
* @param {?} view
* @param {?} nodeIndex
*/
constructor(view, nodeIndex) {
this.view = view;
this.nodeIndex = nodeIndex;
if (nodeIndex == null) {
this.nodeIndex = nodeIndex = 0;
}
this.nodeDef = view.def.nodes[nodeIndex];
/** @type {?} */
let elDef = this.nodeDef;
/** @type {?} */
let elView = view;
while (elDef && (elDef.flags & 1 /* TypeElement */) === 0) {
elDef = (/** @type {?} */ (elDef.parent));
}
if (!elDef) {
while (!elDef && elView) {
elDef = (/** @type {?} */ (viewParentEl(elView)));
elView = (/** @type {?} */ (elView.parent));
}
}
this.elDef = elDef;
this.elView = elView;
}
/**
* @private
* @return {?}
*/
get elOrCompView() {
// Has to be done lazily as we use the DebugContext also during creation of elements...
return asElementData(this.elView, this.elDef.nodeIndex).componentView || this.view;
}
/**
* @return {?}
*/
get injector() {
return createInjector$1(this.elView, this.elDef);
}
/**
* @return {?}
*/
get component() {
return this.elOrCompView.component;
}
/**
* @return {?}
*/
get context() {
return this.elOrCompView.context;
}
/**
* @return {?}
*/
get providerTokens() {
/** @type {?} */
const tokens = [];
if (this.elDef) {
for (let i = this.elDef.nodeIndex + 1; i <= this.elDef.nodeIndex + this.elDef.childCount; i++) {
/** @type {?} */
const childDef = this.elView.def.nodes[i];
if (childDef.flags & 20224 /* CatProvider */) {
tokens.push((/** @type {?} */ (childDef.provider)).token);
}
i += childDef.childCount;
}
}
return tokens;
}
/**
* @return {?}
*/
get references() {
/** @type {?} */
const references = {};
if (this.elDef) {
collectReferences(this.elView, this.elDef, references);
for (let i = this.elDef.nodeIndex + 1; i <= this.elDef.nodeIndex + this.elDef.childCount; i++) {
/** @type {?} */
const childDef = this.elView.def.nodes[i];
if (childDef.flags & 20224 /* CatProvider */) {
collectReferences(this.elView, childDef, references);
}
i += childDef.childCount;
}
}
return references;
}
/**
* @return {?}
*/
get componentRenderElement() {
/** @type {?} */
const elData = findHostElement(this.elOrCompView);
return elData ? elData.renderElement : undefined;
}
/**
* @return {?}
*/
get renderNode() {
return this.nodeDef.flags & 2 /* TypeText */ ? renderNode(this.view, this.nodeDef) :
renderNode(this.elView, this.elDef);
}
/**
* @param {?} console
* @param {...?} values
* @return {?}
*/
logError(console, ...values) {
/** @type {?} */
let logViewDef;
/** @type {?} */
let logNodeIndex;
if (this.nodeDef.flags & 2 /* TypeText */) {
logViewDef = this.view.def;
logNodeIndex = this.nodeDef.nodeIndex;
}
else {
logViewDef = this.elView.def;
logNodeIndex = this.elDef.nodeIndex;
}
// Note: we only generate a log function for text and element nodes
// to make the generated code as small as possible.
/** @type {?} */
const renderNodeIndex = getRenderNodeIndex(logViewDef, logNodeIndex);
/** @type {?} */
let currRenderNodeIndex = -1;
/** @type {?} */
let nodeLogger = (/**
* @return {?}
*/
() => {
currRenderNodeIndex++;
if (currRenderNodeIndex === renderNodeIndex) {
return console.error.bind(console, ...values);
}
else {
return NOOP;
}
});
(/** @type {?} */ (logViewDef.factory))(nodeLogger);
if (currRenderNodeIndex < renderNodeIndex) {
console.error('Illegal state: the ViewDefinitionFactory did not call the logger!');
((/** @type {?} */ (console.error)))(...values);
}
}
}
if (false) {}
/**
* @param {?} viewDef
* @param {?} nodeIndex
* @return {?}
*/
function getRenderNodeIndex(viewDef, nodeIndex) {
/** @type {?} */
let renderNodeIndex = -1;
for (let i = 0; i <= nodeIndex; i++) {
/** @type {?} */
const nodeDef = viewDef.nodes[i];
if (nodeDef.flags & 3 /* CatRenderNode */) {
renderNodeIndex++;
}
}
return renderNodeIndex;
}
/**
* @param {?} view
* @return {?}
*/
function findHostElement(view) {
while (view && !isComponentView(view)) {
view = (/** @type {?} */ (view.parent));
}
if (view.parent) {
return asElementData(view.parent, (/** @type {?} */ (viewParentEl(view))).nodeIndex);
}
return null;
}
/**
* @param {?} view
* @param {?} nodeDef
* @param {?} references
* @return {?}
*/
function collectReferences(view, nodeDef, references) {
for (let refName in nodeDef.references) {
references[refName] = getQueryValue(view, nodeDef, nodeDef.references[refName]);
}
}
/**
* @param {?} action
* @param {?} fn
* @param {?} self
* @param {?} args
* @return {?}
*/
function callWithDebugContext(action, fn, self, args) {
/** @type {?} */
const oldAction = _currentAction;
/** @type {?} */
const oldView = _currentView;
/** @type {?} */
const oldNodeIndex = _currentNodeIndex;
try {
_currentAction = action;
/** @type {?} */
const result = fn.apply(self, args);
_currentView = oldView;
_currentNodeIndex = oldNodeIndex;
_currentAction = oldAction;
return result;
}
catch (e) {
if (isViewDebugError(e) || !_currentView) {
throw e;
}
throw viewWrappedDebugError(e, (/** @type {?} */ (getCurrentDebugContext())));
}
}
/**
* @return {?}
*/
function getCurrentDebugContext() {
return _currentView ? new DebugContext_(_currentView, _currentNodeIndex) : null;
}
class DebugRendererFactory2 {
/**
* @param {?} delegate
*/
constructor(delegate) {
this.delegate = delegate;
}
/**
* @param {?} element
* @param {?} renderData
* @return {?}
*/
createRenderer(element, renderData) {
return new DebugRenderer2(this.delegate.createRenderer(element, renderData));
}
/**
* @return {?}
*/
begin() {
if (this.delegate.begin) {
this.delegate.begin();
}
}
/**
* @return {?}
*/
end() {
if (this.delegate.end) {
this.delegate.end();
}
}
/**
* @return {?}
*/
whenRenderingDone() {
if (this.delegate.whenRenderingDone) {
return this.delegate.whenRenderingDone();
}
return Promise.resolve(null);
}
}
if (false) {}
class DebugRenderer2 {
/**
* @param {?} delegate
*/
constructor(delegate) {
this.delegate = delegate;
/**
* Factory function used to create a `DebugContext` when a node is created.
*
* The `DebugContext` allows to retrieve information about the nodes that are useful in tests.
*
* The factory is configurable so that the `DebugRenderer2` could instantiate either a View Engine
* or a Render context.
*/
this.debugContextFactory = getCurrentDebugContext;
this.data = this.delegate.data;
}
/**
* @private
* @param {?} nativeElement
* @return {?}
*/
createDebugContext(nativeElement) {
return this.debugContextFactory(nativeElement);
}
/**
* @param {?} node
* @return {?}
*/
destroyNode(node) {
/** @type {?} */
const debugNode = (/** @type {?} */ (getDebugNode$1(node)));
removeDebugNodeFromIndex(debugNode);
if (debugNode instanceof DebugNode__PRE_R3__) {
debugNode.listeners.length = 0;
}
if (this.delegate.destroyNode) {
this.delegate.destroyNode(node);
}
}
/**
* @return {?}
*/
destroy() {
this.delegate.destroy();
}
/**
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
createElement(name, namespace) {
/** @type {?} */
const el = this.delegate.createElement(name, namespace);
/** @type {?} */
const debugCtx = this.createDebugContext(el);
if (debugCtx) {
/** @type {?} */
const debugEl = new DebugElement__PRE_R3__(el, null, debugCtx);
((/** @type {?} */ (debugEl))).name = name;
indexDebugNode(debugEl);
}
return el;
}
/**
* @param {?} value
* @return {?}
*/
createComment(value) {
/** @type {?} */
const comment = this.delegate.createComment(escapeCommentText(value));
/** @type {?} */
const debugCtx = this.createDebugContext(comment);
if (debugCtx) {
indexDebugNode(new DebugNode__PRE_R3__(comment, null, debugCtx));
}
return comment;
}
/**
* @param {?} value
* @return {?}
*/
createText(value) {
/** @type {?} */
const text = this.delegate.createText(value);
/** @type {?} */
const debugCtx = this.createDebugContext(text);
if (debugCtx) {
indexDebugNode(new DebugNode__PRE_R3__(text, null, debugCtx));
}
return text;
}
/**
* @param {?} parent
* @param {?} newChild
* @return {?}
*/
appendChild(parent, newChild) {
/** @type {?} */
const debugEl = getDebugNode$1(parent);
/** @type {?} */
const debugChildEl = getDebugNode$1(newChild);
if (debugEl && debugChildEl && debugEl instanceof DebugElement__PRE_R3__) {
debugEl.addChild(debugChildEl);
}
this.delegate.appendChild(parent, newChild);
}
/**
* @param {?} parent
* @param {?} newChild
* @param {?} refChild
* @return {?}
*/
insertBefore(parent, newChild, refChild) {
/** @type {?} */
const debugEl = getDebugNode$1(parent);
/** @type {?} */
const debugChildEl = getDebugNode$1(newChild);
/** @type {?} */
const debugRefEl = (/** @type {?} */ (getDebugNode$1(refChild)));
if (debugEl && debugChildEl && debugEl instanceof DebugElement__PRE_R3__) {
debugEl.insertBefore(debugRefEl, debugChildEl);
}
this.delegate.insertBefore(parent, newChild, refChild);
}
/**
* @param {?} parent
* @param {?} oldChild
* @return {?}
*/
removeChild(parent, oldChild) {
/** @type {?} */
const debugEl = getDebugNode$1(parent);
/** @type {?} */
const debugChildEl = getDebugNode$1(oldChild);
if (debugEl && debugChildEl && debugEl instanceof DebugElement__PRE_R3__) {
debugEl.removeChild(debugChildEl);
}
this.delegate.removeChild(parent, oldChild);
}
/**
* @param {?} selectorOrNode
* @param {?=} preserveContent
* @return {?}
*/
selectRootElement(selectorOrNode, preserveContent) {
/** @type {?} */
const el = this.delegate.selectRootElement(selectorOrNode, preserveContent);
/** @type {?} */
const debugCtx = getCurrentDebugContext();
if (debugCtx) {
indexDebugNode(new DebugElement__PRE_R3__(el, null, debugCtx));
}
return el;
}
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @param {?=} namespace
* @return {?}
*/
setAttribute(el, name, value, namespace) {
/** @type {?} */
const debugEl = getDebugNode$1(el);
if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
/** @type {?} */
const fullName = namespace ? namespace + ':' + name : name;
debugEl.attributes[fullName] = value;
}
this.delegate.setAttribute(el, name, value, namespace);
}
/**
* @param {?} el
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
removeAttribute(el, name, namespace) {
/** @type {?} */
const debugEl = getDebugNode$1(el);
if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
/** @type {?} */
const fullName = namespace ? namespace + ':' + name : name;
debugEl.attributes[fullName] = null;
}
this.delegate.removeAttribute(el, name, namespace);
}
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
addClass(el, name) {
/** @type {?} */
const debugEl = getDebugNode$1(el);
if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
debugEl.classes[name] = true;
}
this.delegate.addClass(el, name);
}
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
removeClass(el, name) {
/** @type {?} */
const debugEl = getDebugNode$1(el);
if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
debugEl.classes[name] = false;
}
this.delegate.removeClass(el, name);
}
/**
* @param {?} el
* @param {?} style
* @param {?} value
* @param {?} flags
* @return {?}
*/
setStyle(el, style, value, flags) {
/** @type {?} */
const debugEl = getDebugNode$1(el);
if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
debugEl.styles[style] = value;
}
this.delegate.setStyle(el, style, value, flags);
}
/**
* @param {?} el
* @param {?} style
* @param {?} flags
* @return {?}
*/
removeStyle(el, style, flags) {
/** @type {?} */
const debugEl = getDebugNode$1(el);
if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
debugEl.styles[style] = null;
}
this.delegate.removeStyle(el, style, flags);
}
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
setProperty(el, name, value) {
/** @type {?} */
const debugEl = getDebugNode$1(el);
if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
debugEl.properties[name] = value;
}
this.delegate.setProperty(el, name, value);
}
/**
* @param {?} target
* @param {?} eventName
* @param {?} callback
* @return {?}
*/
listen(target, eventName, callback) {
if (typeof target !== 'string') {
/** @type {?} */
const debugEl = getDebugNode$1(target);
if (debugEl) {
debugEl.listeners.push(new DebugEventListener(eventName, callback));
}
}
return this.delegate.listen(target, eventName, callback);
}
/**
* @param {?} node
* @return {?}
*/
parentNode(node) {
return this.delegate.parentNode(node);
}
/**
* @param {?} node
* @return {?}
*/
nextSibling(node) {
return this.delegate.nextSibling(node);
}
/**
* @param {?} node
* @param {?} value
* @return {?}
*/
setValue(node, value) {
return this.delegate.setValue(node, value);
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/entrypoint.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} override
* @return {?}
*/
function overrideProvider(override) {
initServicesIfNeeded();
return Services.overrideProvider(override);
}
/**
* @param {?} comp
* @param {?} componentFactory
* @return {?}
*/
function overrideComponentView(comp, componentFactory) {
initServicesIfNeeded();
return Services.overrideComponentView(comp, componentFactory);
}
/**
* @return {?}
*/
function clearOverrides() {
initServicesIfNeeded();
return Services.clearOverrides();
}
// Attention: this function is called as top level function.
// Putting any logic in here will destroy closure tree shaking!
/**
* @param {?} ngModuleType
* @param {?} bootstrapComponents
* @param {?} defFactory
* @return {?}
*/
function createNgModuleFactory(ngModuleType, bootstrapComponents, defFactory) {
return new NgModuleFactory_(ngModuleType, bootstrapComponents, defFactory);
}
/**
* @param {?} def
* @return {?}
*/
function cloneNgModuleDefinition(def) {
/** @type {?} */
const providers = Array.from(def.providers);
/** @type {?} */
const modules = Array.from(def.modules);
/** @type {?} */
const providersByKey = {};
for (const key in def.providersByKey) {
providersByKey[key] = def.providersByKey[key];
}
return {
factory: def.factory,
scope: def.scope,
providers,
modules,
providersByKey,
};
}
class NgModuleFactory_ extends NgModuleFactory {
/**
* @param {?} moduleType
* @param {?} _bootstrapComponents
* @param {?} _ngModuleDefFactory
*/
constructor(moduleType, _bootstrapComponents, _ngModuleDefFactory) {
// Attention: this ctor is called as top level function.
// Putting any logic in here will destroy closure tree shaking!
super();
this.moduleType = moduleType;
this._bootstrapComponents = _bootstrapComponents;
this._ngModuleDefFactory = _ngModuleDefFactory;
}
/**
* @param {?} parentInjector
* @return {?}
*/
create(parentInjector) {
initServicesIfNeeded();
// Clone the NgModuleDefinition so that any tree shakeable provider definition
// added to this instance of the NgModuleRef doesn't affect the cached copy.
// See https://github.com/angular/angular/issues/25018.
/** @type {?} */
const def = cloneNgModuleDefinition(resolveDefinition(this._ngModuleDefFactory));
return Services.createNgModuleRef(this.moduleType, parentInjector || Injector.NULL, this._bootstrapComponents, def);
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/view/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/core_private_export.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/core_render3_private_export.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/codegen_private_exports.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/src/core.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
if (ngDevMode) {
// This helper is to give a reasonable error message to people upgrading to v9 that have not yet
// installed `@angular/localize` in their app.
// tslint:disable-next-line: no-toplevel-property-access
_global.$localize = _global.$localize || (/**
* @return {?}
*/
function () {
throw new Error('It looks like your application or one of its dependencies is using i18n.\n' +
'Angular 9 introduced a global `$localize()` function that needs to be loaded.\n' +
'Please run `ng add @angular/localize` from the Angular CLI.\n' +
'(For non-CLI projects, add `import \'@angular/localize/init\';` to your `polyfills.ts` file.\n' +
'For server-side rendering applications add the import to your `main.server.ts` file.)');
});
}
/**
* @fileoverview added by tsickle
* Generated from: packages/core/public_api.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/core/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Generated bundle index. Do not edit.
*/
//# sourceMappingURL=core.js.map
/***/ }),
/***/ "./node_modules/@angular/platform-browser/__ivy_ngcc__/fesm2015/platform-browser.js":
/*!******************************************************************************************!*\
!*** ./node_modules/@angular/platform-browser/__ivy_ngcc__/fesm2015/platform-browser.js ***!
\******************************************************************************************/
/*! exports provided: ɵgetDOM, BrowserModule, BrowserTransferStateModule, By, DomSanitizer, EVENT_MANAGER_PLUGINS, EventManager, HAMMER_GESTURE_CONFIG, HAMMER_LOADER, HammerGestureConfig, HammerModule, Meta, Title, TransferState, VERSION, disableDebugTools, enableDebugTools, makeStateKey, platformBrowser, ɵBROWSER_SANITIZATION_PROVIDERS, ɵBROWSER_SANITIZATION_PROVIDERS__POST_R3__, ɵBrowserDomAdapter, ɵBrowserGetTestability, ɵDomEventsPlugin, ɵDomRendererFactory2, ɵDomSanitizerImpl, ɵDomSharedStylesHost, ɵELEMENT_PROBE_PROVIDERS, ɵELEMENT_PROBE_PROVIDERS__POST_R3__, ɵHAMMER_PROVIDERS__POST_R3__, ɵHammerGesturesPlugin, ɵINTERNAL_BROWSER_PLATFORM_PROVIDERS, ɵKeyEventsPlugin, ɵNAMESPACE_URIS, ɵSharedStylesHost, ɵTRANSITION_ID, ɵangular_packages_platform_browser_platform_browser_a, ɵangular_packages_platform_browser_platform_browser_b, ɵangular_packages_platform_browser_platform_browser_c, ɵangular_packages_platform_browser_platform_browser_d, ɵangular_packages_platform_browser_platform_browser_e, ɵangular_packages_platform_browser_platform_browser_f, ɵangular_packages_platform_browser_platform_browser_g, ɵangular_packages_platform_browser_platform_browser_h, ɵangular_packages_platform_browser_platform_browser_i, ɵangular_packages_platform_browser_platform_browser_j, ɵangular_packages_platform_browser_platform_browser_k, ɵangular_packages_platform_browser_platform_browser_l, ɵangular_packages_platform_browser_platform_browser_m, ɵangular_packages_platform_browser_platform_browser_n, ɵangular_packages_platform_browser_platform_browser_o, ɵescapeHtml, ɵflattenStyles, ɵinitDomAdapter, ɵshimContentAttribute, ɵshimHostAttribute */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BrowserModule", function() { return BrowserModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BrowserTransferStateModule", function() { return BrowserTransferStateModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "By", function() { return By; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DomSanitizer", function() { return DomSanitizer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EVENT_MANAGER_PLUGINS", function() { return EVENT_MANAGER_PLUGINS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EventManager", function() { return EventManager; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HAMMER_GESTURE_CONFIG", function() { return HAMMER_GESTURE_CONFIG; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HAMMER_LOADER", function() { return HAMMER_LOADER; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HammerGestureConfig", function() { return HammerGestureConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HammerModule", function() { return HammerModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Meta", function() { return Meta; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Title", function() { return Title; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransferState", function() { return TransferState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return VERSION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "disableDebugTools", function() { return disableDebugTools; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableDebugTools", function() { return enableDebugTools; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeStateKey", function() { return makeStateKey; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "platformBrowser", function() { return platformBrowser; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵBROWSER_SANITIZATION_PROVIDERS", function() { return BROWSER_SANITIZATION_PROVIDERS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵBROWSER_SANITIZATION_PROVIDERS__POST_R3__", function() { return BROWSER_SANITIZATION_PROVIDERS__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵBrowserDomAdapter", function() { return BrowserDomAdapter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵBrowserGetTestability", function() { return BrowserGetTestability; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵDomEventsPlugin", function() { return DomEventsPlugin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵDomRendererFactory2", function() { return DomRendererFactory2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵDomSanitizerImpl", function() { return DomSanitizerImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵDomSharedStylesHost", function() { return DomSharedStylesHost; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵELEMENT_PROBE_PROVIDERS", function() { return ELEMENT_PROBE_PROVIDERS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵELEMENT_PROBE_PROVIDERS__POST_R3__", function() { return ELEMENT_PROBE_PROVIDERS__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵHAMMER_PROVIDERS__POST_R3__", function() { return HAMMER_PROVIDERS__POST_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵHammerGesturesPlugin", function() { return HammerGesturesPlugin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵINTERNAL_BROWSER_PLATFORM_PROVIDERS", function() { return INTERNAL_BROWSER_PLATFORM_PROVIDERS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵKeyEventsPlugin", function() { return KeyEventsPlugin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵNAMESPACE_URIS", function() { return NAMESPACE_URIS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵSharedStylesHost", function() { return SharedStylesHost; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵTRANSITION_ID", function() { return TRANSITION_ID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_a", function() { return errorHandler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_b", function() { return _document; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_c", function() { return BROWSER_MODULE_PROVIDERS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_d", function() { return createMeta; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_e", function() { return createTitle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_f", function() { return initTransferState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_g", function() { return EventManagerPlugin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_h", function() { return HAMMER_PROVIDERS__PRE_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_i", function() { return HAMMER_PROVIDERS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_j", function() { return domSanitizerImplFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_k", function() { return appInitializerFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_l", function() { return SERVER_TRANSITION_PROVIDERS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_m", function() { return _createNgProbeR2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_n", function() { return ELEMENT_PROBE_PROVIDERS__PRE_R3__; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_platform_browser_platform_browser_o", function() { return GenericBrowserDomAdapter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵescapeHtml", function() { return escapeHtml; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵflattenStyles", function() { return flattenStyles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵinitDomAdapter", function() { return initDomAdapter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵshimContentAttribute", function() { return shimContentAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵshimHostAttribute", function() { return shimHostAttribute; });
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/__ivy_ngcc__/fesm2015/common.js");
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ɵgetDOM", function() { return _angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"]; });
/**
* @license Angular v9.1.13
* (c) 2010-2020 Google LLC. https://angular.io/
* License: MIT
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser/generic_browser_adapter.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Provides DOM operations in any browser environment.
*
* \@security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
* @abstract
*/
class GenericBrowserDomAdapter extends _angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵDomAdapter"] {
constructor() {
super();
}
/**
* @return {?}
*/
supportsDOMEvents() {
return true;
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser/browser_adapter.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
const ɵ0 = /**
* @return {?}
*/
() => {
if (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['Node']) {
return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['Node'].prototype.contains || (/**
* @this {?}
* @param {?} node
* @return {?}
*/
function (node) {
return !!(this.compareDocumentPosition(node) & 16);
});
}
return (/** @type {?} */ (undefined));
};
/** @type {?} */
const nodeContains = ((ɵ0))();
/**
* A `DomAdapter` powered by full browser DOM APIs.
*
* \@security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
*/
/* tslint:disable:requireParameterType no-console */
class BrowserDomAdapter extends GenericBrowserDomAdapter {
/**
* @return {?}
*/
static makeCurrent() {
Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵsetRootDomAdapter"])(new BrowserDomAdapter());
}
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
getProperty(el, name) {
return ((/** @type {?} */ (el)))[name];
}
/**
* @param {?} error
* @return {?}
*/
log(error) {
if (window.console) {
window.console.log && window.console.log(error);
}
}
/**
* @param {?} error
* @return {?}
*/
logGroup(error) {
if (window.console) {
window.console.group && window.console.group(error);
}
}
/**
* @return {?}
*/
logGroupEnd() {
if (window.console) {
window.console.groupEnd && window.console.groupEnd();
}
}
/**
* @param {?} el
* @param {?} evt
* @param {?} listener
* @return {?}
*/
onAndCancel(el, evt, listener) {
el.addEventListener(evt, listener, false);
// Needed to follow Dart's subscription semantic, until fix of
// https://code.google.com/p/dart/issues/detail?id=17406
return (/**
* @return {?}
*/
() => {
el.removeEventListener(evt, listener, false);
});
}
/**
* @param {?} el
* @param {?} evt
* @return {?}
*/
dispatchEvent(el, evt) {
el.dispatchEvent(evt);
}
/**
* @param {?} node
* @return {?}
*/
remove(node) {
if (node.parentNode) {
node.parentNode.removeChild(node);
}
return node;
}
/**
* @param {?} el
* @return {?}
*/
getValue(el) {
return el.value;
}
/**
* @param {?} tagName
* @param {?=} doc
* @return {?}
*/
createElement(tagName, doc) {
doc = doc || this.getDefaultDocument();
return doc.createElement(tagName);
}
/**
* @return {?}
*/
createHtmlDocument() {
return document.implementation.createHTMLDocument('fakeTitle');
}
/**
* @return {?}
*/
getDefaultDocument() {
return document;
}
/**
* @param {?} node
* @return {?}
*/
isElementNode(node) {
return node.nodeType === Node.ELEMENT_NODE;
}
/**
* @param {?} node
* @return {?}
*/
isShadowRoot(node) {
return node instanceof DocumentFragment;
}
/**
* @param {?} doc
* @param {?} target
* @return {?}
*/
getGlobalEventTarget(doc, target) {
if (target === 'window') {
return window;
}
if (target === 'document') {
return doc;
}
if (target === 'body') {
return doc.body;
}
return null;
}
/**
* @return {?}
*/
getHistory() {
return window.history;
}
/**
* @return {?}
*/
getLocation() {
return window.location;
}
/**
* @param {?} doc
* @return {?}
*/
getBaseHref(doc) {
/** @type {?} */
const href = getBaseElementHref();
return href == null ? null : relativePath(href);
}
/**
* @return {?}
*/
resetBaseElement() {
baseElement = null;
}
/**
* @return {?}
*/
getUserAgent() {
return window.navigator.userAgent;
}
/**
* @return {?}
*/
performanceNow() {
// performance.now() is not available in all browsers, see
// http://caniuse.com/#search=performance.now
return window.performance && window.performance.now ? window.performance.now() :
new Date().getTime();
}
/**
* @return {?}
*/
supportsCookies() {
return true;
}
/**
* @param {?} name
* @return {?}
*/
getCookie(name) {
return Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵparseCookieValue"])(document.cookie, name);
}
}
/** @type {?} */
let baseElement = null;
/**
* @return {?}
*/
function getBaseElementHref() {
if (!baseElement) {
baseElement = (/** @type {?} */ (document.querySelector('base')));
if (!baseElement) {
return null;
}
}
return baseElement.getAttribute('href');
}
// based on urlUtils.js in AngularJS 1
/** @type {?} */
let urlParsingNode;
/**
* @param {?} url
* @return {?}
*/
function relativePath(url) {
if (!urlParsingNode) {
urlParsingNode = document.createElement('a');
}
urlParsingNode.setAttribute('href', url);
return (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname :
'/' + urlParsingNode.pathname;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser/server-transition.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* An id that identifies a particular application being bootstrapped, that should
* match across the client/server boundary.
* @type {?}
*/
const TRANSITION_ID = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["InjectionToken"]('TRANSITION_ID');
/**
* @param {?} transitionId
* @param {?} document
* @param {?} injector
* @return {?}
*/
function appInitializerFactory(transitionId, document, injector) {
return (/**
* @return {?}
*/
() => {
// Wait for all application initializers to be completed before removing the styles set by
// the server.
injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ApplicationInitStatus"]).donePromise.then((/**
* @return {?}
*/
() => {
/** @type {?} */
const dom = Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])();
/** @type {?} */
const styles = Array.prototype.slice.apply(document.querySelectorAll(`style[ng-transition]`));
styles.filter((/**
* @param {?} el
* @return {?}
*/
el => el.getAttribute('ng-transition') === transitionId))
.forEach((/**
* @param {?} el
* @return {?}
*/
el => dom.remove(el)));
}));
});
}
/** @type {?} */
const SERVER_TRANSITION_PROVIDERS = [
{
provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_INITIALIZER"],
useFactory: appInitializerFactory,
deps: [TRANSITION_ID, _angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injector"]],
multi: true
},
];
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser/testability.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class BrowserGetTestability {
/**
* @return {?}
*/
static init() {
Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["setTestabilityGetter"])(new BrowserGetTestability());
}
/**
* @param {?} registry
* @return {?}
*/
addToWindow(registry) {
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['getAngularTestability'] = (/**
* @param {?} elem
* @param {?=} findInAncestors
* @return {?}
*/
(elem, findInAncestors = true) => {
/** @type {?} */
const testability = registry.findTestabilityInTree(elem, findInAncestors);
if (testability == null) {
throw new Error('Could not find testability for element.');
}
return testability;
});
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['getAllAngularTestabilities'] = (/**
* @return {?}
*/
() => registry.getAllTestabilities());
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['getAllAngularRootElements'] = (/**
* @return {?}
*/
() => registry.getAllRootElements());
/** @type {?} */
const whenAllStable = (/**
* @param {?} callback
* @return {?}
*/
(callback /** TODO #9100 */) => {
/** @type {?} */
const testabilities = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['getAllAngularTestabilities']();
/** @type {?} */
let count = testabilities.length;
/** @type {?} */
let didWork = false;
/** @type {?} */
const decrement = (/**
* @param {?} didWork_
* @return {?}
*/
function (didWork_ /** TODO #9100 */) {
didWork = didWork || didWork_;
count--;
if (count == 0) {
callback(didWork);
}
});
testabilities.forEach((/**
* @param {?} testability
* @return {?}
*/
function (testability /** TODO #9100 */) {
testability.whenStable(decrement);
}));
});
if (!_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['frameworkStabilizers']) {
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['frameworkStabilizers'] = [];
}
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['frameworkStabilizers'].push(whenAllStable);
}
/**
* @param {?} registry
* @param {?} elem
* @param {?} findInAncestors
* @return {?}
*/
findTestabilityInTree(registry, elem, findInAncestors) {
if (elem == null) {
return null;
}
/** @type {?} */
const t = registry.getTestability(elem);
if (t != null) {
return t;
}
else if (!findInAncestors) {
return null;
}
if (Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().isShadowRoot(elem)) {
return this.findTestabilityInTree(registry, ((/** @type {?} */ (elem))).host, true);
}
return this.findTestabilityInTree(registry, elem.parentElement, true);
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/dom/util.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const CAMEL_CASE_REGEXP = /([A-Z])/g;
/** @type {?} */
const DASH_CASE_REGEXP = /-([a-z])/g;
/**
* @param {?} input
* @return {?}
*/
function camelCaseToDashCase(input) {
return input.replace(CAMEL_CASE_REGEXP, (/**
* @param {...?} m
* @return {?}
*/
(...m) => '-' + m[1].toLowerCase()));
}
/**
* @param {?} input
* @return {?}
*/
function dashCaseToCamelCase(input) {
return input.replace(DASH_CASE_REGEXP, (/**
* @param {...?} m
* @return {?}
*/
(...m) => m[1].toUpperCase()));
}
/**
* Exports the value under a given `name` in the global property `ng`. For example `ng.probe` if
* `name` is `'probe'`.
* @param {?} name Name under which it will be exported. Keep in mind this will be a property of the
* global `ng` object.
* @param {?} value The value to export.
* @return {?}
*/
function exportNgVar(name, value) {
if (typeof COMPILED === 'undefined' || !COMPILED) {
// Note: we can't export `ng` when using closure enhanced optimization as:
// - closure declares globals itself for minified names, which sometimes clobber our `ng` global
// - we can't declare a closure extern as the namespace `ng` is already used within Google
// for typings for angularJS (via `goog.provide('ng....')`).
/** @type {?} */
const ng = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['ng'] = ((/** @type {?} */ (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['ng']))) || {};
ng[name] = value;
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/dom/debug/ng_probe.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
const ɵ0$1 = /**
* @return {?}
*/
() => ({
'ApplicationRef': _angular_core__WEBPACK_IMPORTED_MODULE_1__["ApplicationRef"],
'NgZone': _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"],
});
/** @type {?} */
const CORE_TOKENS = ((ɵ0$1))();
/** @type {?} */
const INSPECT_GLOBAL_NAME = 'probe';
/** @type {?} */
const CORE_TOKENS_GLOBAL_NAME = 'coreTokens';
/**
* Returns a {\@link DebugElement} for the given native DOM element, or
* null if the given native element does not have an Angular view associated
* with it.
* @param {?} element
* @return {?}
*/
function inspectNativeElementR2(element) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵgetDebugNodeR2"])(element);
}
/**
* @param {?} coreTokens
* @return {?}
*/
function _createNgProbeR2(coreTokens) {
exportNgVar(INSPECT_GLOBAL_NAME, inspectNativeElementR2);
exportNgVar(CORE_TOKENS_GLOBAL_NAME, Object.assign(Object.assign({}, CORE_TOKENS), _ngProbeTokensToMap(coreTokens || [])));
return (/**
* @return {?}
*/
() => inspectNativeElementR2);
}
/**
* @param {?} tokens
* @return {?}
*/
function _ngProbeTokensToMap(tokens) {
return tokens.reduce((/**
* @param {?} prev
* @param {?} t
* @return {?}
*/
(prev, t) => (prev[t.name] = t.token, prev)), {});
}
/**
* In Ivy, we don't support NgProbe because we have our own set of testing utilities
* with more robust functionality.
*
* We shouldn't bring in NgProbe because it prevents DebugNode and friends from
* tree-shaking properly.
* @type {?}
*/
const ELEMENT_PROBE_PROVIDERS__POST_R3__ = [];
/**
* Providers which support debugging Angular applications (e.g. via `ng.probe`).
* @type {?}
*/
const ELEMENT_PROBE_PROVIDERS__PRE_R3__ = [
{
provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_INITIALIZER"],
useFactory: _createNgProbeR2,
deps: [
[_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgProbeToken"], new _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"]()],
],
multi: true,
},
];
/** @type {?} */
const ELEMENT_PROBE_PROVIDERS = ELEMENT_PROBE_PROVIDERS__POST_R3__;
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/dom/events/event_manager.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* The injection token for the event-manager plug-in service.
*
* \@publicApi
* @type {?}
*/
const EVENT_MANAGER_PLUGINS = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["InjectionToken"]('EventManagerPlugins');
/**
* An injectable service that provides event management for Angular
* through a browser plug-in.
*
* \@publicApi
*/
class EventManager {
/**
* Initializes an instance of the event-manager service.
* @param {?} plugins
* @param {?} _zone
*/
constructor(plugins, _zone) {
this._zone = _zone;
this._eventNameToPlugin = new Map();
plugins.forEach((/**
* @template THIS
* @this {THIS}
* @param {?} p
* @return {THIS}
*/
p => p.manager = this));
this._plugins = plugins.slice().reverse();
}
/**
* Registers a handler for a specific element and event.
*
* @param {?} element The HTML element to receive event notifications.
* @param {?} eventName The name of the event to listen for.
* @param {?} handler A function to call when the notification occurs. Receives the
* event object as an argument.
* @return {?} A callback function that can be used to remove the handler.
*/
addEventListener(element, eventName, handler) {
/** @type {?} */
const plugin = this._findPluginFor(eventName);
return plugin.addEventListener(element, eventName, handler);
}
/**
* Registers a global handler for an event in a target view.
*
* @param {?} target A target for global event notifications. One of "window", "document", or "body".
* @param {?} eventName The name of the event to listen for.
* @param {?} handler A function to call when the notification occurs. Receives the
* event object as an argument.
* @return {?} A callback function that can be used to remove the handler.
*/
addGlobalEventListener(target, eventName, handler) {
/** @type {?} */
const plugin = this._findPluginFor(eventName);
return plugin.addGlobalEventListener(target, eventName, handler);
}
/**
* Retrieves the compilation zone in which event listeners are registered.
* @return {?}
*/
getZone() {
return this._zone;
}
/**
* \@internal
* @param {?} eventName
* @return {?}
*/
_findPluginFor(eventName) {
/** @type {?} */
const plugin = this._eventNameToPlugin.get(eventName);
if (plugin) {
return plugin;
}
/** @type {?} */
const plugins = this._plugins;
for (let i = 0; i < plugins.length; i++) {
/** @type {?} */
const plugin = plugins[i];
if (plugin.supports(eventName)) {
this._eventNameToPlugin.set(eventName, plugin);
return plugin;
}
}
throw new Error(`No event manager plugin found for event ${eventName}`);
}
}
EventManager.ɵfac = function EventManager_Factory(t) { return new (t || EventManager)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](EVENT_MANAGER_PLUGINS), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"])); };
EventManager.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: EventManager, factory: EventManager.ɵfac });
/** @nocollapse */
EventManager.ctorParameters = () => [
{ type: Array, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [EVENT_MANAGER_PLUGINS,] }] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](EventManager, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return [{ type: Array, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [EVENT_MANAGER_PLUGINS]
}] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"] }]; }, null); })();
if (false) {}
/**
* @abstract
*/
class EventManagerPlugin {
/**
* @param {?} _doc
*/
constructor(_doc) {
this._doc = _doc;
}
/**
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
addGlobalEventListener(element, eventName, handler) {
/** @type {?} */
const target = Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().getGlobalEventTarget(this._doc, element);
if (!target) {
throw new Error(`Unsupported event target ${target} for event ${eventName}`);
}
return this.addEventListener(target, eventName, handler);
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/dom/shared_styles_host.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class SharedStylesHost {
constructor() {
/**
* \@internal
*/
this._stylesSet = new Set();
}
/**
* @param {?} styles
* @return {?}
*/
addStyles(styles) {
/** @type {?} */
const additions = new Set();
styles.forEach((/**
* @param {?} style
* @return {?}
*/
style => {
if (!this._stylesSet.has(style)) {
this._stylesSet.add(style);
additions.add(style);
}
}));
this.onStylesAdded(additions);
}
/**
* @param {?} additions
* @return {?}
*/
onStylesAdded(additions) { }
/**
* @return {?}
*/
getAllStyles() {
return Array.from(this._stylesSet);
}
}
SharedStylesHost.ɵfac = function SharedStylesHost_Factory(t) { return new (t || SharedStylesHost)(); };
SharedStylesHost.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: SharedStylesHost, factory: SharedStylesHost.ɵfac });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](SharedStylesHost, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return []; }, null); })();
if (false) {}
class DomSharedStylesHost extends SharedStylesHost {
/**
* @param {?} _doc
*/
constructor(_doc) {
super();
this._doc = _doc;
this._hostNodes = new Set();
this._styleNodes = new Set();
this._hostNodes.add(_doc.head);
}
/**
* @private
* @param {?} styles
* @param {?} host
* @return {?}
*/
_addStylesToHost(styles, host) {
styles.forEach((/**
* @param {?} style
* @return {?}
*/
(style) => {
/** @type {?} */
const styleEl = this._doc.createElement('style');
styleEl.textContent = style;
this._styleNodes.add(host.appendChild(styleEl));
}));
}
/**
* @param {?} hostNode
* @return {?}
*/
addHost(hostNode) {
this._addStylesToHost(this._stylesSet, hostNode);
this._hostNodes.add(hostNode);
}
/**
* @param {?} hostNode
* @return {?}
*/
removeHost(hostNode) {
this._hostNodes.delete(hostNode);
}
/**
* @param {?} additions
* @return {?}
*/
onStylesAdded(additions) {
this._hostNodes.forEach((/**
* @param {?} hostNode
* @return {?}
*/
hostNode => this._addStylesToHost(additions, hostNode)));
}
/**
* @return {?}
*/
ngOnDestroy() {
this._styleNodes.forEach((/**
* @param {?} styleNode
* @return {?}
*/
styleNode => Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().remove(styleNode)));
}
}
DomSharedStylesHost.ɵfac = function DomSharedStylesHost_Factory(t) { return new (t || DomSharedStylesHost)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"])); };
DomSharedStylesHost.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: DomSharedStylesHost, factory: DomSharedStylesHost.ɵfac });
/** @nocollapse */
DomSharedStylesHost.ctorParameters = () => [
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"],] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](DomSharedStylesHost, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return [{ type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]]
}] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/dom/dom_renderer.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const NAMESPACE_URIS = {
'svg': 'http://www.w3.org/2000/svg',
'xhtml': 'http://www.w3.org/1999/xhtml',
'xlink': 'http://www.w3.org/1999/xlink',
'xml': 'http://www.w3.org/XML/1998/namespace',
'xmlns': 'http://www.w3.org/2000/xmlns/',
};
/** @type {?} */
const COMPONENT_REGEX = /%COMP%/g;
/** @type {?} */
const NG_DEV_MODE = typeof ngDevMode === 'undefined' || !!ngDevMode;
/** @type {?} */
const COMPONENT_VARIABLE = '%COMP%';
/** @type {?} */
const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
/** @type {?} */
const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
/**
* @param {?} componentShortId
* @return {?}
*/
function shimContentAttribute(componentShortId) {
return CONTENT_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
/**
* @param {?} componentShortId
* @return {?}
*/
function shimHostAttribute(componentShortId) {
return HOST_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
/**
* @param {?} compId
* @param {?} styles
* @param {?} target
* @return {?}
*/
function flattenStyles(compId, styles, target) {
for (let i = 0; i < styles.length; i++) {
/** @type {?} */
let style = styles[i];
if (Array.isArray(style)) {
flattenStyles(compId, style, target);
}
else {
style = style.replace(COMPONENT_REGEX, compId);
target.push(style);
}
}
return target;
}
/**
* @param {?} eventHandler
* @return {?}
*/
function decoratePreventDefault(eventHandler) {
// `DebugNode.triggerEventHandler` needs to know if the listener was created with
// decoratePreventDefault or is a listener added outside the Angular context so it can handle the
// two differently. In the first case, the special '__ngUnwrap__' token is passed to the unwrap
// the listener (see below).
return (/**
* @param {?} event
* @return {?}
*/
(event) => {
// Ivy uses '__ngUnwrap__' as a special token that allows us to unwrap the function
// so that it can be invoked programmatically by `DebugNode.triggerEventHandler`. The debug_node
// can inspect the listener toString contents for the existence of this special token. Because
// the token is a string literal, it is ensured to not be modified by compiled code.
if (event === '__ngUnwrap__') {
return eventHandler;
}
/** @type {?} */
const allowDefaultBehavior = eventHandler(event);
if (allowDefaultBehavior === false) {
// TODO(tbosch): move preventDefault into event plugins...
event.preventDefault();
event.returnValue = false;
}
return undefined;
});
}
class DomRendererFactory2 {
/**
* @param {?} eventManager
* @param {?} sharedStylesHost
* @param {?} appId
*/
constructor(eventManager, sharedStylesHost, appId) {
this.eventManager = eventManager;
this.sharedStylesHost = sharedStylesHost;
this.appId = appId;
this.rendererByCompId = new Map();
this.defaultRenderer = new DefaultDomRenderer2(eventManager);
}
/**
* @param {?} element
* @param {?} type
* @return {?}
*/
createRenderer(element, type) {
if (!element || !type) {
return this.defaultRenderer;
}
switch (type.encapsulation) {
case _angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewEncapsulation"].Emulated: {
/** @type {?} */
let renderer = this.rendererByCompId.get(type.id);
if (!renderer) {
renderer = new EmulatedEncapsulationDomRenderer2(this.eventManager, this.sharedStylesHost, type, this.appId);
this.rendererByCompId.set(type.id, renderer);
}
((/** @type {?} */ (renderer))).applyToHost(element);
return renderer;
}
case _angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewEncapsulation"].Native:
case _angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewEncapsulation"].ShadowDom:
return new ShadowDomRenderer(this.eventManager, this.sharedStylesHost, element, type);
default: {
if (!this.rendererByCompId.has(type.id)) {
/** @type {?} */
const styles = flattenStyles(type.id, type.styles, []);
this.sharedStylesHost.addStyles(styles);
this.rendererByCompId.set(type.id, this.defaultRenderer);
}
return this.defaultRenderer;
}
}
}
/**
* @return {?}
*/
begin() { }
/**
* @return {?}
*/
end() { }
}
DomRendererFactory2.ɵfac = function DomRendererFactory2_Factory(t) { return new (t || DomRendererFactory2)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](EventManager), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](DomSharedStylesHost), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_ID"])); };
DomRendererFactory2.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: DomRendererFactory2, factory: DomRendererFactory2.ɵfac });
/** @nocollapse */
DomRendererFactory2.ctorParameters = () => [
{ type: EventManager },
{ type: DomSharedStylesHost },
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_ID"],] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](DomRendererFactory2, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return [{ type: EventManager }, { type: DomSharedStylesHost }, { type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_ID"]]
}] }]; }, null); })();
if (false) {}
class DefaultDomRenderer2 {
/**
* @param {?} eventManager
*/
constructor(eventManager) {
this.eventManager = eventManager;
this.data = Object.create(null);
}
/**
* @return {?}
*/
destroy() { }
/**
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
createElement(name, namespace) {
if (namespace) {
// In cases where Ivy (not ViewEngine) is giving us the actual namespace, the look up by key
// will result in undefined, so we just return the namespace here.
return document.createElementNS(NAMESPACE_URIS[namespace] || namespace, name);
}
return document.createElement(name);
}
/**
* @param {?} value
* @return {?}
*/
createComment(value) {
return document.createComment(value);
}
/**
* @param {?} value
* @return {?}
*/
createText(value) {
return document.createTextNode(value);
}
/**
* @param {?} parent
* @param {?} newChild
* @return {?}
*/
appendChild(parent, newChild) {
parent.appendChild(newChild);
}
/**
* @param {?} parent
* @param {?} newChild
* @param {?} refChild
* @return {?}
*/
insertBefore(parent, newChild, refChild) {
if (parent) {
parent.insertBefore(newChild, refChild);
}
}
/**
* @param {?} parent
* @param {?} oldChild
* @return {?}
*/
removeChild(parent, oldChild) {
if (parent) {
parent.removeChild(oldChild);
}
}
/**
* @param {?} selectorOrNode
* @param {?=} preserveContent
* @return {?}
*/
selectRootElement(selectorOrNode, preserveContent) {
/** @type {?} */
let el = typeof selectorOrNode === 'string' ? document.querySelector(selectorOrNode) :
selectorOrNode;
if (!el) {
throw new Error(`The selector "${selectorOrNode}" did not match any elements`);
}
if (!preserveContent) {
el.textContent = '';
}
return el;
}
/**
* @param {?} node
* @return {?}
*/
parentNode(node) {
return node.parentNode;
}
/**
* @param {?} node
* @return {?}
*/
nextSibling(node) {
return node.nextSibling;
}
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @param {?=} namespace
* @return {?}
*/
setAttribute(el, name, value, namespace) {
if (namespace) {
name = namespace + ':' + name;
// TODO(FW-811): Ivy may cause issues here because it's passing around
// full URIs for namespaces, therefore this lookup will fail.
/** @type {?} */
const namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.setAttributeNS(namespaceUri, name, value);
}
else {
el.setAttribute(name, value);
}
}
else {
el.setAttribute(name, value);
}
}
/**
* @param {?} el
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
removeAttribute(el, name, namespace) {
if (namespace) {
// TODO(FW-811): Ivy may cause issues here because it's passing around
// full URIs for namespaces, therefore this lookup will fail.
/** @type {?} */
const namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.removeAttributeNS(namespaceUri, name);
}
else {
// TODO(FW-811): Since ivy is passing around full URIs for namespaces
// this could result in properties like `http://www.w3.org/2000/svg:cx="123"`,
// which is wrong.
el.removeAttribute(`${namespace}:${name}`);
}
}
else {
el.removeAttribute(name);
}
}
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
addClass(el, name) {
el.classList.add(name);
}
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
removeClass(el, name) {
el.classList.remove(name);
}
/**
* @param {?} el
* @param {?} style
* @param {?} value
* @param {?} flags
* @return {?}
*/
setStyle(el, style, value, flags) {
if (flags & _angular_core__WEBPACK_IMPORTED_MODULE_1__["RendererStyleFlags2"].DashCase) {
el.style.setProperty(style, value, !!(flags & _angular_core__WEBPACK_IMPORTED_MODULE_1__["RendererStyleFlags2"].Important) ? 'important' : '');
}
else {
el.style[style] = value;
}
}
/**
* @param {?} el
* @param {?} style
* @param {?} flags
* @return {?}
*/
removeStyle(el, style, flags) {
if (flags & _angular_core__WEBPACK_IMPORTED_MODULE_1__["RendererStyleFlags2"].DashCase) {
el.style.removeProperty(style);
}
else {
// IE requires '' instead of null
// see https://github.com/angular/angular/issues/7916
el.style[style] = '';
}
}
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
setProperty(el, name, value) {
NG_DEV_MODE && checkNoSyntheticProp(name, 'property');
el[name] = value;
}
/**
* @param {?} node
* @param {?} value
* @return {?}
*/
setValue(node, value) {
node.nodeValue = value;
}
/**
* @param {?} target
* @param {?} event
* @param {?} callback
* @return {?}
*/
listen(target, event, callback) {
NG_DEV_MODE && checkNoSyntheticProp(event, 'listener');
if (typeof target === 'string') {
return (/** @type {?} */ (this.eventManager.addGlobalEventListener(target, event, decoratePreventDefault(callback))));
}
return (/** @type {?} */ ((/** @type {?} */ (this.eventManager.addEventListener(target, event, decoratePreventDefault(callback))))));
}
}
if (false) {}
const ɵ0$2 = /**
* @return {?}
*/
() => '@'.charCodeAt(0);
/** @type {?} */
const AT_CHARCODE = ((ɵ0$2))();
/**
* @param {?} name
* @param {?} nameKind
* @return {?}
*/
function checkNoSyntheticProp(name, nameKind) {
if (name.charCodeAt(0) === AT_CHARCODE) {
throw new Error(`Found the synthetic ${nameKind} ${name}. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.`);
}
}
class EmulatedEncapsulationDomRenderer2 extends DefaultDomRenderer2 {
/**
* @param {?} eventManager
* @param {?} sharedStylesHost
* @param {?} component
* @param {?} appId
*/
constructor(eventManager, sharedStylesHost, component, appId) {
super(eventManager);
this.component = component;
/** @type {?} */
const styles = flattenStyles(appId + '-' + component.id, component.styles, []);
sharedStylesHost.addStyles(styles);
this.contentAttr = shimContentAttribute(appId + '-' + component.id);
this.hostAttr = shimHostAttribute(appId + '-' + component.id);
}
/**
* @param {?} element
* @return {?}
*/
applyToHost(element) {
super.setAttribute(element, this.hostAttr, '');
}
/**
* @param {?} parent
* @param {?} name
* @return {?}
*/
createElement(parent, name) {
/** @type {?} */
const el = super.createElement(parent, name);
super.setAttribute(el, this.contentAttr, '');
return el;
}
}
if (false) {}
class ShadowDomRenderer extends DefaultDomRenderer2 {
/**
* @param {?} eventManager
* @param {?} sharedStylesHost
* @param {?} hostEl
* @param {?} component
*/
constructor(eventManager, sharedStylesHost, hostEl, component) {
super(eventManager);
this.sharedStylesHost = sharedStylesHost;
this.hostEl = hostEl;
this.component = component;
if (component.encapsulation === _angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewEncapsulation"].ShadowDom) {
this.shadowRoot = ((/** @type {?} */ (hostEl))).attachShadow({ mode: 'open' });
}
else {
this.shadowRoot = ((/** @type {?} */ (hostEl))).createShadowRoot();
}
this.sharedStylesHost.addHost(this.shadowRoot);
/** @type {?} */
const styles = flattenStyles(component.id, component.styles, []);
for (let i = 0; i < styles.length; i++) {
/** @type {?} */
const styleEl = document.createElement('style');
styleEl.textContent = styles[i];
this.shadowRoot.appendChild(styleEl);
}
}
/**
* @private
* @param {?} node
* @return {?}
*/
nodeOrShadowRoot(node) {
return node === this.hostEl ? this.shadowRoot : node;
}
/**
* @return {?}
*/
destroy() {
this.sharedStylesHost.removeHost(this.shadowRoot);
}
/**
* @param {?} parent
* @param {?} newChild
* @return {?}
*/
appendChild(parent, newChild) {
return super.appendChild(this.nodeOrShadowRoot(parent), newChild);
}
/**
* @param {?} parent
* @param {?} newChild
* @param {?} refChild
* @return {?}
*/
insertBefore(parent, newChild, refChild) {
return super.insertBefore(this.nodeOrShadowRoot(parent), newChild, refChild);
}
/**
* @param {?} parent
* @param {?} oldChild
* @return {?}
*/
removeChild(parent, oldChild) {
return super.removeChild(this.nodeOrShadowRoot(parent), oldChild);
}
/**
* @param {?} node
* @return {?}
*/
parentNode(node) {
return this.nodeOrShadowRoot(super.parentNode(this.nodeOrShadowRoot(node)));
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/dom/events/dom_events.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class DomEventsPlugin extends EventManagerPlugin {
/**
* @param {?} doc
*/
constructor(doc) {
super(doc);
}
// This plugin should come last in the list of plugins, because it accepts all
// events.
/**
* @param {?} eventName
* @return {?}
*/
supports(eventName) {
return true;
}
/**
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
addEventListener(element, eventName, handler) {
element.addEventListener(eventName, (/** @type {?} */ (handler)), false);
return (/**
* @return {?}
*/
() => this.removeEventListener(element, eventName, (/** @type {?} */ (handler))));
}
/**
* @param {?} target
* @param {?} eventName
* @param {?} callback
* @return {?}
*/
removeEventListener(target, eventName, callback) {
return target.removeEventListener(eventName, (/** @type {?} */ (callback)));
}
}
DomEventsPlugin.ɵfac = function DomEventsPlugin_Factory(t) { return new (t || DomEventsPlugin)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"])); };
DomEventsPlugin.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: DomEventsPlugin, factory: DomEventsPlugin.ɵfac });
/** @nocollapse */
DomEventsPlugin.ctorParameters = () => [
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"],] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](DomEventsPlugin, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return [{ type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]]
}] }]; }, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/dom/events/hammer_gestures.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Supported HammerJS recognizer event names.
* @type {?}
*/
const EVENT_NAMES = {
// pan
'pan': true,
'panstart': true,
'panmove': true,
'panend': true,
'pancancel': true,
'panleft': true,
'panright': true,
'panup': true,
'pandown': true,
// pinch
'pinch': true,
'pinchstart': true,
'pinchmove': true,
'pinchend': true,
'pinchcancel': true,
'pinchin': true,
'pinchout': true,
// press
'press': true,
'pressup': true,
// rotate
'rotate': true,
'rotatestart': true,
'rotatemove': true,
'rotateend': true,
'rotatecancel': true,
// swipe
'swipe': true,
'swipeleft': true,
'swiperight': true,
'swipeup': true,
'swipedown': true,
// tap
'tap': true,
};
/**
* DI token for providing [HammerJS](http://hammerjs.github.io/) support to Angular.
* @see `HammerGestureConfig`
*
* \@ngModule HammerModule
* \@publicApi
* @type {?}
*/
const HAMMER_GESTURE_CONFIG = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["InjectionToken"]('HammerGestureConfig');
/**
* Injection token used to provide a {\@link HammerLoader} to Angular.
*
* \@publicApi
* @type {?}
*/
const HAMMER_LOADER = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["InjectionToken"]('HammerLoader');
/**
* @record
*/
function HammerInstance() { }
if (false) {}
/**
* An injectable [HammerJS Manager](http://hammerjs.github.io/api/#hammer.manager)
* for gesture recognition. Configures specific event recognition.
* \@publicApi
*/
class HammerGestureConfig {
constructor() {
/**
* A set of supported event names for gestures to be used in Angular.
* Angular supports all built-in recognizers, as listed in
* [HammerJS documentation](http://hammerjs.github.io/).
*/
this.events = [];
/**
* Maps gesture event names to a set of configuration options
* that specify overrides to the default values for specific properties.
*
* The key is a supported event name to be configured,
* and the options object contains a set of properties, with override values
* to be applied to the named recognizer event.
* For example, to disable recognition of the rotate event, specify
* `{"rotate": {"enable": false}}`.
*
* Properties that are not present take the HammerJS default values.
* For information about which properties are supported for which events,
* and their allowed and default values, see
* [HammerJS documentation](http://hammerjs.github.io/).
*
*/
this.overrides = {};
}
/**
* Creates a [HammerJS Manager](http://hammerjs.github.io/api/#hammer.manager)
* and attaches it to a given HTML element.
* @param {?} element The element that will recognize gestures.
* @return {?} A HammerJS event-manager object.
*/
buildHammer(element) {
/** @type {?} */
const mc = new (/** @type {?} */ (Hammer))(element, this.options);
mc.get('pinch').set({ enable: true });
mc.get('rotate').set({ enable: true });
for (const eventName in this.overrides) {
mc.get(eventName).set(this.overrides[eventName]);
}
return mc;
}
}
HammerGestureConfig.ɵfac = function HammerGestureConfig_Factory(t) { return new (t || HammerGestureConfig)(); };
HammerGestureConfig.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: HammerGestureConfig, factory: HammerGestureConfig.ɵfac });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](HammerGestureConfig, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return []; }, null); })();
if (false) {}
/**
* Event plugin that adds Hammer support to an application.
*
* \@ngModule HammerModule
*/
class HammerGesturesPlugin extends EventManagerPlugin {
/**
* @param {?} doc
* @param {?} _config
* @param {?} console
* @param {?=} loader
*/
constructor(doc, _config, console, loader) {
super(doc);
this._config = _config;
this.console = console;
this.loader = loader;
}
/**
* @param {?} eventName
* @return {?}
*/
supports(eventName) {
if (!EVENT_NAMES.hasOwnProperty(eventName.toLowerCase()) && !this.isCustomEvent(eventName)) {
return false;
}
if (!((/** @type {?} */ (window))).Hammer && !this.loader) {
this.console.warn(`The "${eventName}" event cannot be bound because Hammer.JS is not ` +
`loaded and no custom loader has been specified.`);
return false;
}
return true;
}
/**
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
addEventListener(element, eventName, handler) {
/** @type {?} */
const zone = this.manager.getZone();
eventName = eventName.toLowerCase();
// If Hammer is not present but a loader is specified, we defer adding the event listener
// until Hammer is loaded.
if (!((/** @type {?} */ (window))).Hammer && this.loader) {
// This `addEventListener` method returns a function to remove the added listener.
// Until Hammer is loaded, the returned function needs to *cancel* the registration rather
// than remove anything.
/** @type {?} */
let cancelRegistration = false;
/** @type {?} */
let deregister = (/**
* @return {?}
*/
() => {
cancelRegistration = true;
});
this.loader()
.then((/**
* @return {?}
*/
() => {
// If Hammer isn't actually loaded when the custom loader resolves, give up.
if (!((/** @type {?} */ (window))).Hammer) {
this.console.warn(`The custom HAMMER_LOADER completed, but Hammer.JS is not present.`);
deregister = (/**
* @return {?}
*/
() => { });
return;
}
if (!cancelRegistration) {
// Now that Hammer is loaded and the listener is being loaded for real,
// the deregistration function changes from canceling registration to removal.
deregister = this.addEventListener(element, eventName, handler);
}
}))
.catch((/**
* @return {?}
*/
() => {
this.console.warn(`The "${eventName}" event cannot be bound because the custom ` +
`Hammer.JS loader failed.`);
deregister = (/**
* @return {?}
*/
() => { });
}));
// Return a function that *executes* `deregister` (and not `deregister` itself) so that we
// can change the behavior of `deregister` once the listener is added. Using a closure in
// this way allows us to avoid any additional data structures to track listener removal.
return (/**
* @return {?}
*/
() => {
deregister();
});
}
return zone.runOutsideAngular((/**
* @return {?}
*/
() => {
// Creating the manager bind events, must be done outside of angular
/** @type {?} */
const mc = this._config.buildHammer(element);
/** @type {?} */
const callback = (/**
* @param {?} eventObj
* @return {?}
*/
function (eventObj) {
zone.runGuarded((/**
* @return {?}
*/
function () {
handler(eventObj);
}));
});
mc.on(eventName, callback);
return (/**
* @return {?}
*/
() => {
mc.off(eventName, callback);
// destroy mc to prevent memory leak
if (typeof mc.destroy === 'function') {
mc.destroy();
}
});
}));
}
/**
* @param {?} eventName
* @return {?}
*/
isCustomEvent(eventName) {
return this._config.events.indexOf(eventName) > -1;
}
}
HammerGesturesPlugin.ɵfac = function HammerGesturesPlugin_Factory(t) { return new (t || HammerGesturesPlugin)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](HAMMER_GESTURE_CONFIG), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵConsole"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](HAMMER_LOADER, 8)); };
HammerGesturesPlugin.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: HammerGesturesPlugin, factory: HammerGesturesPlugin.ɵfac });
/** @nocollapse */
HammerGesturesPlugin.ctorParameters = () => [
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"],] }] },
{ type: HammerGestureConfig, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [HAMMER_GESTURE_CONFIG,] }] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵConsole"] },
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [HAMMER_LOADER,] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](HammerGesturesPlugin, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return [{ type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]]
}] }, { type: HammerGestureConfig, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [HAMMER_GESTURE_CONFIG]
}] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵConsole"] }, { type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"]
}, {
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [HAMMER_LOADER]
}] }]; }, null); })();
if (false) {}
/**
* In Ivy, support for Hammer gestures is optional, so applications must
* import the `HammerModule` at root to turn on support. This means that
* Hammer-specific code can be tree-shaken away if not needed.
* @type {?}
*/
const HAMMER_PROVIDERS__POST_R3__ = [];
/**
* In View Engine, support for Hammer gestures is built-in by default.
* @type {?}
*/
const HAMMER_PROVIDERS__PRE_R3__ = [
{
provide: EVENT_MANAGER_PLUGINS,
useClass: HammerGesturesPlugin,
multi: true,
deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"], HAMMER_GESTURE_CONFIG, _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵConsole"], [new _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"](), HAMMER_LOADER]]
},
{ provide: HAMMER_GESTURE_CONFIG, useClass: HammerGestureConfig, deps: [] },
];
/** @type {?} */
const HAMMER_PROVIDERS = HAMMER_PROVIDERS__POST_R3__;
/**
* Adds support for HammerJS.
*
* Import this module at the root of your application so that Angular can work with
* HammerJS to detect gesture events.
*
* Note that applications still need to include the HammerJS script itself. This module
* simply sets up the coordination layer between HammerJS and Angular's EventManager.
*
* \@publicApi
*/
class HammerModule {
}
HammerModule.ɵmod = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineNgModule"]({ type: HammerModule });
HammerModule.ɵinj = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjector"]({ factory: function HammerModule_Factory(t) { return new (t || HammerModule)(); }, providers: HAMMER_PROVIDERS__PRE_R3__ });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](HammerModule, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModule"],
args: [{ providers: HAMMER_PROVIDERS__PRE_R3__ }]
}], null, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/dom/events/key_events.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Defines supported modifiers for key events.
* @type {?}
*/
const MODIFIER_KEYS = ['alt', 'control', 'meta', 'shift'];
/** @type {?} */
const DOM_KEY_LOCATION_NUMPAD = 3;
// Map to convert some key or keyIdentifier values to what will be returned by getEventKey
/** @type {?} */
const _keyMap = {
// The following values are here for cross-browser compatibility and to match the W3C standard
// cf http://www.w3.org/TR/DOM-Level-3-Events-key/
'\b': 'Backspace',
'\t': 'Tab',
'\x7F': 'Delete',
'\x1B': 'Escape',
'Del': 'Delete',
'Esc': 'Escape',
'Left': 'ArrowLeft',
'Right': 'ArrowRight',
'Up': 'ArrowUp',
'Down': 'ArrowDown',
'Menu': 'ContextMenu',
'Scroll': 'ScrollLock',
'Win': 'OS'
};
// There is a bug in Chrome for numeric keypad keys:
// https://code.google.com/p/chromium/issues/detail?id=155654
// 1, 2, 3 ... are reported as A, B, C ...
/** @type {?} */
const _chromeNumKeyPadMap = {
'A': '1',
'B': '2',
'C': '3',
'D': '4',
'E': '5',
'F': '6',
'G': '7',
'H': '8',
'I': '9',
'J': '*',
'K': '+',
'M': '-',
'N': '.',
'O': '/',
'\x60': '0',
'\x90': 'NumLock'
};
const ɵ0$3 = /**
* @param {?} event
* @return {?}
*/
(event) => event.altKey, ɵ1 = /**
* @param {?} event
* @return {?}
*/
(event) => event.ctrlKey, ɵ2 = /**
* @param {?} event
* @return {?}
*/
(event) => event.metaKey, ɵ3 = /**
* @param {?} event
* @return {?}
*/
(event) => event.shiftKey;
/**
* Retrieves modifiers from key-event objects.
* @type {?}
*/
const MODIFIER_KEY_GETTERS = {
'alt': (ɵ0$3),
'control': (ɵ1),
'meta': (ɵ2),
'shift': (ɵ3)
};
/**
* \@publicApi
* A browser plug-in that provides support for handling of key events in Angular.
*/
class KeyEventsPlugin extends EventManagerPlugin {
/**
* Initializes an instance of the browser plug-in.
* @param {?} doc The document in which key events will be detected.
*/
constructor(doc) {
super(doc);
}
/**
* Reports whether a named key event is supported.
* @param {?} eventName The event name to query.
* @return {?} True if the named key event is supported.
*/
supports(eventName) {
return KeyEventsPlugin.parseEventName(eventName) != null;
}
/**
* Registers a handler for a specific element and key event.
* @param {?} element The HTML element to receive event notifications.
* @param {?} eventName The name of the key event to listen for.
* @param {?} handler A function to call when the notification occurs. Receives the
* event object as an argument.
* @return {?} The key event that was registered.
*/
addEventListener(element, eventName, handler) {
/** @type {?} */
const parsedEvent = (/** @type {?} */ (KeyEventsPlugin.parseEventName(eventName)));
/** @type {?} */
const outsideHandler = KeyEventsPlugin.eventCallback(parsedEvent['fullKey'], handler, this.manager.getZone());
return this.manager.getZone().runOutsideAngular((/**
* @return {?}
*/
() => {
return Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().onAndCancel(element, parsedEvent['domEventName'], outsideHandler);
}));
}
/**
* @param {?} eventName
* @return {?}
*/
static parseEventName(eventName) {
/** @type {?} */
const parts = eventName.toLowerCase().split('.');
/** @type {?} */
const domEventName = parts.shift();
if ((parts.length === 0) || !(domEventName === 'keydown' || domEventName === 'keyup')) {
return null;
}
/** @type {?} */
const key = KeyEventsPlugin._normalizeKey((/** @type {?} */ (parts.pop())));
/** @type {?} */
let fullKey = '';
MODIFIER_KEYS.forEach((/**
* @param {?} modifierName
* @return {?}
*/
modifierName => {
/** @type {?} */
const index = parts.indexOf(modifierName);
if (index > -1) {
parts.splice(index, 1);
fullKey += modifierName + '.';
}
}));
fullKey += key;
if (parts.length != 0 || key.length === 0) {
// returning null instead of throwing to let another plugin process the event
return null;
}
/** @type {?} */
const result = {};
result['domEventName'] = domEventName;
result['fullKey'] = fullKey;
return result;
}
/**
* @param {?} event
* @return {?}
*/
static getEventFullKey(event) {
/** @type {?} */
let fullKey = '';
/** @type {?} */
let key = getEventKey(event);
key = key.toLowerCase();
if (key === ' ') {
key = 'space'; // for readability
}
else if (key === '.') {
key = 'dot'; // because '.' is used as a separator in event names
}
MODIFIER_KEYS.forEach((/**
* @param {?} modifierName
* @return {?}
*/
modifierName => {
if (modifierName != key) {
/** @type {?} */
const modifierGetter = MODIFIER_KEY_GETTERS[modifierName];
if (modifierGetter(event)) {
fullKey += modifierName + '.';
}
}
}));
fullKey += key;
return fullKey;
}
/**
* Configures a handler callback for a key event.
* @param {?} fullKey The event name that combines all simultaneous keystrokes.
* @param {?} handler The function that responds to the key event.
* @param {?} zone The zone in which the event occurred.
* @return {?} A callback function.
*/
static eventCallback(fullKey, handler, zone) {
return (/**
* @param {?} event
* @return {?}
*/
(event /** TODO #9100 */) => {
if (KeyEventsPlugin.getEventFullKey(event) === fullKey) {
zone.runGuarded((/**
* @return {?}
*/
() => handler(event)));
}
});
}
/**
* \@internal
* @param {?} keyName
* @return {?}
*/
static _normalizeKey(keyName) {
// TODO: switch to a Map if the mapping grows too much
switch (keyName) {
case 'esc':
return 'escape';
default:
return keyName;
}
}
}
KeyEventsPlugin.ɵfac = function KeyEventsPlugin_Factory(t) { return new (t || KeyEventsPlugin)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"])); };
KeyEventsPlugin.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: KeyEventsPlugin, factory: KeyEventsPlugin.ɵfac });
/** @nocollapse */
KeyEventsPlugin.ctorParameters = () => [
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"],] }] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](KeyEventsPlugin, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return [{ type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]]
}] }]; }, null); })();
/**
* @param {?} event
* @return {?}
*/
function getEventKey(event) {
/** @type {?} */
let key = event.key;
if (key == null) {
key = event.keyIdentifier;
// keyIdentifier is defined in the old draft of DOM Level 3 Events implemented by Chrome and
// Safari cf
// http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/events.html#Events-KeyboardEvents-Interfaces
if (key == null) {
return 'Unidentified';
}
if (key.startsWith('U+')) {
key = String.fromCharCode(parseInt(key.substring(2), 16));
if (event.location === DOM_KEY_LOCATION_NUMPAD && _chromeNumKeyPadMap.hasOwnProperty(key)) {
// There is a bug in Chrome for numeric keypad keys:
// https://code.google.com/p/chromium/issues/detail?id=155654
// 1, 2, 3 ... are reported as A, B, C ...
key = ((/** @type {?} */ (_chromeNumKeyPadMap)))[key];
}
}
}
return _keyMap[key] || key;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/security/dom_sanitization_service.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Marker interface for a value that's safe to use in a particular context.
*
* \@publicApi
* @record
*/
function SafeValue() { }
/**
* Marker interface for a value that's safe to use as HTML.
*
* \@publicApi
* @record
*/
function SafeHtml() { }
/**
* Marker interface for a value that's safe to use as style (CSS).
*
* \@publicApi
* @record
*/
function SafeStyle() { }
/**
* Marker interface for a value that's safe to use as JavaScript.
*
* \@publicApi
* @record
*/
function SafeScript() { }
/**
* Marker interface for a value that's safe to use as a URL linking to a document.
*
* \@publicApi
* @record
*/
function SafeUrl() { }
/**
* Marker interface for a value that's safe to use as a URL to load executable code from.
*
* \@publicApi
* @record
*/
function SafeResourceUrl() { }
/**
* DomSanitizer helps preventing Cross Site Scripting Security bugs (XSS) by sanitizing
* values to be safe to use in the different DOM contexts.
*
* For example, when binding a URL in an `<a [href]="someValue">` hyperlink, `someValue` will be
* sanitized so that an attacker cannot inject e.g. a `javascript:` URL that would execute code on
* the website.
*
* In specific situations, it might be necessary to disable sanitization, for example if the
* application genuinely needs to produce a `javascript:` style link with a dynamic value in it.
* Users can bypass security by constructing a value with one of the `bypassSecurityTrust...`
* methods, and then binding to that value from the template.
*
* These situations should be very rare, and extraordinary care must be taken to avoid creating a
* Cross Site Scripting (XSS) security bug!
*
* When using `bypassSecurityTrust...`, make sure to call the method as early as possible and as
* close as possible to the source of the value, to make it easy to verify no security bug is
* created by its use.
*
* It is not required (and not recommended) to bypass security if the value is safe, e.g. a URL that
* does not start with a suspicious protocol, or an HTML snippet that does not contain dangerous
* code. The sanitizer leaves safe values intact.
*
* \@security Calling any of the `bypassSecurityTrust...` APIs disables Angular's built-in
* sanitization for the value passed in. Carefully check and audit all values and code paths going
* into this call. Make sure any user data is appropriately escaped for this security context.
* For more detail, see the [Security Guide](http://g.co/ng/security).
*
* \@publicApi
* @abstract
*/
class DomSanitizer {
}
DomSanitizer.ɵfac = function DomSanitizer_Factory(t) { return new (t || DomSanitizer)(); };
/** @nocollapse */ DomSanitizer.ɵprov = Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"])({ factory: function DomSanitizer_Factory() { return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"])(DomSanitizerImpl); }, token: DomSanitizer, providedIn: "root" });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](DomSanitizer, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"],
args: [{ providedIn: 'root', useExisting: Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["forwardRef"])(( /**
* @return {?}
*/() => DomSanitizerImpl)) }]
}], null, null); })();
if (false) {}
/**
* @param {?} injector
* @return {?}
*/
function domSanitizerImplFactory(injector) {
return new DomSanitizerImpl(injector.get(_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]));
}
class DomSanitizerImpl extends DomSanitizer {
/**
* @param {?} _doc
*/
constructor(_doc) {
super();
this._doc = _doc;
}
/**
* @param {?} ctx
* @param {?} value
* @return {?}
*/
sanitize(ctx, value) {
if (value == null)
return null;
switch (ctx) {
case _angular_core__WEBPACK_IMPORTED_MODULE_1__["SecurityContext"].NONE:
return (/** @type {?} */ (value));
case _angular_core__WEBPACK_IMPORTED_MODULE_1__["SecurityContext"].HTML:
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵallowSanitizationBypassAndThrow"])(value, "HTML" /* Html */)) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
}
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵ_sanitizeHtml"])(this._doc, String(value));
case _angular_core__WEBPACK_IMPORTED_MODULE_1__["SecurityContext"].STYLE:
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵallowSanitizationBypassAndThrow"])(value, "Style" /* Style */)) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
}
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵ_sanitizeStyle"])((/** @type {?} */ (value)));
case _angular_core__WEBPACK_IMPORTED_MODULE_1__["SecurityContext"].SCRIPT:
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵallowSanitizationBypassAndThrow"])(value, "Script" /* Script */)) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
}
throw new Error('unsafe value used in a script context');
case _angular_core__WEBPACK_IMPORTED_MODULE_1__["SecurityContext"].URL:
/** @type {?} */
const type = Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵgetSanitizationBypassType"])(value);
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵallowSanitizationBypassAndThrow"])(value, "URL" /* Url */)) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
}
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵ_sanitizeUrl"])(String(value));
case _angular_core__WEBPACK_IMPORTED_MODULE_1__["SecurityContext"].RESOURCE_URL:
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵallowSanitizationBypassAndThrow"])(value, "ResourceURL" /* ResourceUrl */)) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
}
throw new Error('unsafe value used in a resource URL context (see http://g.co/ng/security#xss)');
default:
throw new Error(`Unexpected SecurityContext ${ctx} (see http://g.co/ng/security#xss)`);
}
}
/**
* @param {?} value
* @return {?}
*/
bypassSecurityTrustHtml(value) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵbypassSanitizationTrustHtml"])(value);
}
/**
* @param {?} value
* @return {?}
*/
bypassSecurityTrustStyle(value) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵbypassSanitizationTrustStyle"])(value);
}
/**
* @param {?} value
* @return {?}
*/
bypassSecurityTrustScript(value) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵbypassSanitizationTrustScript"])(value);
}
/**
* @param {?} value
* @return {?}
*/
bypassSecurityTrustUrl(value) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵbypassSanitizationTrustUrl"])(value);
}
/**
* @param {?} value
* @return {?}
*/
bypassSecurityTrustResourceUrl(value) {
return Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵbypassSanitizationTrustResourceUrl"])(value);
}
}
DomSanitizerImpl.ɵfac = function DomSanitizerImpl_Factory(t) { return new (t || DomSanitizerImpl)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"])); };
/** @nocollapse */
DomSanitizerImpl.ctorParameters = () => [
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"],] }] }
];
/** @nocollapse */ DomSanitizerImpl.ɵprov = Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"])({ factory: function DomSanitizerImpl_Factory() { return domSanitizerImplFactory(Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"])(_angular_core__WEBPACK_IMPORTED_MODULE_1__["INJECTOR"])); }, token: DomSanitizerImpl, providedIn: "root" });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](DomSanitizerImpl, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"],
args: [{ providedIn: 'root', useFactory: domSanitizerImplFactory, deps: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["Injector"]] }]
}], function () { return [{ type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]]
}] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @return {?}
*/
function initDomAdapter() {
BrowserDomAdapter.makeCurrent();
BrowserGetTestability.init();
}
/**
* @return {?}
*/
function errorHandler() {
return new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ErrorHandler"]();
}
/**
* @return {?}
*/
function _document() {
// Tell ivy about the global document
Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetDocument"])(document);
return document;
}
const ɵ0$4 = _angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵPLATFORM_BROWSER_ID"];
/** @type {?} */
const INTERNAL_BROWSER_PLATFORM_PROVIDERS = [
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["PLATFORM_ID"], useValue: ɵ0$4 },
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["PLATFORM_INITIALIZER"], useValue: initDomAdapter, multi: true },
{ provide: _angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"], useFactory: _document, deps: [] },
];
/** @type {?} */
const BROWSER_SANITIZATION_PROVIDERS__PRE_R3__ = [
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Sanitizer"], useExisting: DomSanitizer },
{ provide: DomSanitizer, useClass: DomSanitizerImpl, deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]] },
];
/** @type {?} */
const BROWSER_SANITIZATION_PROVIDERS__POST_R3__ = [];
/**
* \@security Replacing built-in sanitization providers exposes the application to XSS risks.
* Attacker-controlled data introduced by an unsanitized provider could expose your
* application to XSS risks. For more detail, see the [Security Guide](http://g.co/ng/security).
* \@publicApi
* @type {?}
*/
const BROWSER_SANITIZATION_PROVIDERS = BROWSER_SANITIZATION_PROVIDERS__POST_R3__;
/**
* \@publicApi
* @type {?}
*/
const platformBrowser = Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["createPlatformFactory"])(_angular_core__WEBPACK_IMPORTED_MODULE_1__["platformCore"], 'browser', INTERNAL_BROWSER_PLATFORM_PROVIDERS);
/** @type {?} */
const BROWSER_MODULE_PROVIDERS = [
BROWSER_SANITIZATION_PROVIDERS,
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵINJECTOR_SCOPE"], useValue: 'root' },
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ErrorHandler"], useFactory: errorHandler, deps: [] },
{
provide: EVENT_MANAGER_PLUGINS,
useClass: DomEventsPlugin,
multi: true,
deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["PLATFORM_ID"]]
},
{ provide: EVENT_MANAGER_PLUGINS, useClass: KeyEventsPlugin, multi: true, deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]] },
HAMMER_PROVIDERS,
{
provide: DomRendererFactory2,
useClass: DomRendererFactory2,
deps: [EventManager, DomSharedStylesHost, _angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_ID"]]
},
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["RendererFactory2"], useExisting: DomRendererFactory2 },
{ provide: SharedStylesHost, useExisting: DomSharedStylesHost },
{ provide: DomSharedStylesHost, useClass: DomSharedStylesHost, deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]] },
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Testability"], useClass: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Testability"], deps: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"]] },
{ provide: EventManager, useClass: EventManager, deps: [EVENT_MANAGER_PLUGINS, _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"]] },
ELEMENT_PROBE_PROVIDERS,
];
/**
* Exports required infrastructure for all Angular apps.
* Included by default in all Angular apps created with the CLI
* `new` command.
* Re-exports `CommonModule` and `ApplicationModule`, making their
* exports and providers available to all apps.
*
* \@publicApi
*/
class BrowserModule {
/**
* @param {?} parentModule
*/
constructor(parentModule) {
if (parentModule) {
throw new Error(`BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.`);
}
}
/**
* Configures a browser-based app to transition from a server-rendered app, if
* one is present on the page.
*
* @param {?} params An object containing an identifier for the app to transition.
* The ID must match between the client and server versions of the app.
* @return {?} The reconfigured `BrowserModule` to import into the app's root `AppModule`.
*/
static withServerTransition(params) {
return {
ngModule: BrowserModule,
providers: [
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_ID"], useValue: params.appId },
{ provide: TRANSITION_ID, useExisting: _angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_ID"] },
SERVER_TRANSITION_PROVIDERS,
],
};
}
}
BrowserModule.ɵmod = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineNgModule"]({ type: BrowserModule });
BrowserModule.ɵinj = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjector"]({ factory: function BrowserModule_Factory(t) { return new (t || BrowserModule)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](BrowserModule, 12)); }, providers: BROWSER_MODULE_PROVIDERS, imports: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["CommonModule"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ApplicationModule"]] });
/** @nocollapse */
BrowserModule.ctorParameters = () => [
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["SkipSelf"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [BrowserModule,] }] }
];
(function () { (typeof ngJitMode === "undefined" || ngJitMode) && _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵsetNgModuleScope"](BrowserModule, { exports: function () { return [_angular_common__WEBPACK_IMPORTED_MODULE_0__["CommonModule"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ApplicationModule"]]; } }); })();
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](BrowserModule, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModule"],
args: [{ providers: BROWSER_MODULE_PROVIDERS, exports: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["CommonModule"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ApplicationModule"]] }]
}], function () { return [{ type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"]
}, {
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["SkipSelf"]
}, {
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [BrowserModule]
}] }]; }, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser/meta.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Factory to create Meta service.
* @return {?}
*/
function createMeta() {
return new Meta(Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"])(_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]));
}
/**
* A service that can be used to get and add meta tags.
*
* \@publicApi
*/
class Meta {
/**
* @param {?} _doc
*/
constructor(_doc) {
this._doc = _doc;
this._dom = Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])();
}
/**
* @param {?} tag
* @param {?=} forceCreation
* @return {?}
*/
addTag(tag, forceCreation = false) {
if (!tag)
return null;
return this._getOrCreateElement(tag, forceCreation);
}
/**
* @param {?} tags
* @param {?=} forceCreation
* @return {?}
*/
addTags(tags, forceCreation = false) {
if (!tags)
return [];
return tags.reduce((/**
* @param {?} result
* @param {?} tag
* @return {?}
*/
(result, tag) => {
if (tag) {
result.push(this._getOrCreateElement(tag, forceCreation));
}
return result;
}), []);
}
/**
* @param {?} attrSelector
* @return {?}
*/
getTag(attrSelector) {
if (!attrSelector)
return null;
return this._doc.querySelector(`meta[${attrSelector}]`) || null;
}
/**
* @param {?} attrSelector
* @return {?}
*/
getTags(attrSelector) {
if (!attrSelector)
return [];
/** @type {?} */
const list /*NodeList*/ = this._doc.querySelectorAll(`meta[${attrSelector}]`);
return list ? [].slice.call(list) : [];
}
/**
* @param {?} tag
* @param {?=} selector
* @return {?}
*/
updateTag(tag, selector) {
if (!tag)
return null;
selector = selector || this._parseSelector(tag);
/** @type {?} */
const meta = (/** @type {?} */ (this.getTag(selector)));
if (meta) {
return this._setMetaElementAttributes(tag, meta);
}
return this._getOrCreateElement(tag, true);
}
/**
* @param {?} attrSelector
* @return {?}
*/
removeTag(attrSelector) {
this.removeTagElement((/** @type {?} */ (this.getTag(attrSelector))));
}
/**
* @param {?} meta
* @return {?}
*/
removeTagElement(meta) {
if (meta) {
this._dom.remove(meta);
}
}
/**
* @private
* @param {?} meta
* @param {?=} forceCreation
* @return {?}
*/
_getOrCreateElement(meta, forceCreation = false) {
if (!forceCreation) {
/** @type {?} */
const selector = this._parseSelector(meta);
/** @type {?} */
const elem = (/** @type {?} */ (this.getTag(selector)));
// It's allowed to have multiple elements with the same name so it's not enough to
// just check that element with the same name already present on the page. We also need to
// check if element has tag attributes
if (elem && this._containsAttributes(meta, elem))
return elem;
}
/** @type {?} */
const element = (/** @type {?} */ (this._dom.createElement('meta')));
this._setMetaElementAttributes(meta, element);
/** @type {?} */
const head = this._doc.getElementsByTagName('head')[0];
head.appendChild(element);
return element;
}
/**
* @private
* @param {?} tag
* @param {?} el
* @return {?}
*/
_setMetaElementAttributes(tag, el) {
Object.keys(tag).forEach((/**
* @param {?} prop
* @return {?}
*/
(prop) => el.setAttribute(prop, tag[prop])));
return el;
}
/**
* @private
* @param {?} tag
* @return {?}
*/
_parseSelector(tag) {
/** @type {?} */
const attr = tag.name ? 'name' : 'property';
return `${attr}="${tag[attr]}"`;
}
/**
* @private
* @param {?} tag
* @param {?} elem
* @return {?}
*/
_containsAttributes(tag, elem) {
return Object.keys(tag).every((/**
* @param {?} key
* @return {?}
*/
(key) => elem.getAttribute(key) === tag[key]));
}
}
Meta.ɵfac = function Meta_Factory(t) { return new (t || Meta)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"])); };
/** @nocollapse */
Meta.ctorParameters = () => [
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"],] }] }
];
/** @nocollapse */ Meta.ɵprov = Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"])({ factory: createMeta, token: Meta, providedIn: "root" });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](Meta, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"],
args: [{ providedIn: 'root', useFactory: createMeta, deps: [] }]
}], function () { return [{ type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]]
}] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser/title.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Factory to create Title service.
* @return {?}
*/
function createTitle() {
return new Title(Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"])(_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]));
}
/**
* A service that can be used to get and set the title of a current HTML document.
*
* Since an Angular application can't be bootstrapped on the entire HTML document (`<html>` tag)
* it is not possible to bind to the `text` property of the `HTMLTitleElement` elements
* (representing the `<title>` tag). Instead, this service can be used to set and get the current
* title value.
*
* \@publicApi
*/
class Title {
/**
* @param {?} _doc
*/
constructor(_doc) {
this._doc = _doc;
}
/**
* Get the title of the current HTML document.
* @return {?}
*/
getTitle() {
return this._doc.title;
}
/**
* Set the title of the current HTML document.
* @param {?} newTitle
* @return {?}
*/
setTitle(newTitle) {
this._doc.title = newTitle || '';
}
}
Title.ɵfac = function Title_Factory(t) { return new (t || Title)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"])); };
/** @nocollapse */
Title.ctorParameters = () => [
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"],] }] }
];
/** @nocollapse */ Title.ɵprov = Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"])({ factory: createTitle, token: Title, providedIn: "root" });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](Title, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"],
args: [{ providedIn: 'root', useFactory: createTitle, deps: [] }]
}], function () { return [{ type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"]]
}] }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser/tools/browser.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** @type {?} */
const win = typeof window !== 'undefined' && window || (/** @type {?} */ ({}));
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser/tools/common_tools.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class ChangeDetectionPerfRecord {
/**
* @param {?} msPerTick
* @param {?} numTicks
*/
constructor(msPerTick, numTicks) {
this.msPerTick = msPerTick;
this.numTicks = numTicks;
}
}
if (false) {}
/**
* Entry point for all Angular profiling-related debug tools. This object
* corresponds to the `ng.profiler` in the dev console.
*/
class AngularProfiler {
/**
* @param {?} ref
*/
constructor(ref) {
this.appRef = ref.injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ApplicationRef"]);
}
// tslint:disable:no-console
/**
* Exercises change detection in a loop and then prints the average amount of
* time in milliseconds how long a single round of change detection takes for
* the current state of the UI. It runs a minimum of 5 rounds for a minimum
* of 500 milliseconds.
*
* Optionally, a user may pass a `config` parameter containing a map of
* options. Supported options are:
*
* `record` (boolean) - causes the profiler to record a CPU profile while
* it exercises the change detector. Example:
*
* ```
* ng.profiler.timeChangeDetection({record: true})
* ```
* @param {?} config
* @return {?}
*/
timeChangeDetection(config) {
/** @type {?} */
const record = config && config['record'];
/** @type {?} */
const profileName = 'Change Detection';
// Profiler is not available in Android browsers, nor in IE 9 without dev tools opened
/** @type {?} */
const isProfilerAvailable = win.console.profile != null;
if (record && isProfilerAvailable) {
win.console.profile(profileName);
}
/** @type {?} */
const start = Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().performanceNow();
/** @type {?} */
let numTicks = 0;
while (numTicks < 5 || (Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().performanceNow() - start) < 500) {
this.appRef.tick();
numTicks++;
}
/** @type {?} */
const end = Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().performanceNow();
if (record && isProfilerAvailable) {
win.console.profileEnd(profileName);
}
/** @type {?} */
const msPerTick = (end - start) / numTicks;
win.console.log(`ran ${numTicks} change detection cycles`);
win.console.log(`${msPerTick.toFixed(2)} ms per check`);
return new ChangeDetectionPerfRecord(msPerTick, numTicks);
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser/tools/tools.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const PROFILER_GLOBAL_NAME = 'profiler';
/**
* Enabled Angular debug tools that are accessible via your browser's
* developer console.
*
* Usage:
*
* 1. Open developer console (e.g. in Chrome Ctrl + Shift + j)
* 1. Type `ng.` (usually the console will show auto-complete suggestion)
* 1. Try the change detection profiler `ng.profiler.timeChangeDetection()`
* then hit Enter.
*
* \@publicApi
* @template T
* @param {?} ref
* @return {?}
*/
function enableDebugTools(ref) {
exportNgVar(PROFILER_GLOBAL_NAME, new AngularProfiler(ref));
return ref;
}
/**
* Disables Angular tools.
*
* \@publicApi
* @return {?}
*/
function disableDebugTools() {
exportNgVar(PROFILER_GLOBAL_NAME, null);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/browser/transfer_state.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} text
* @return {?}
*/
function escapeHtml(text) {
/** @type {?} */
const escapedText = {
'&': '&a;',
'"': '&q;',
'\'': '&s;',
'<': '&l;',
'>': '&g;',
};
return text.replace(/[&"'<>]/g, (/**
* @param {?} s
* @return {?}
*/
s => escapedText[s]));
}
/**
* @param {?} text
* @return {?}
*/
function unescapeHtml(text) {
/** @type {?} */
const unescapedText = {
'&a;': '&',
'&q;': '"',
'&s;': '\'',
'&l;': '<',
'&g;': '>',
};
return text.replace(/&[^;]+;/g, (/**
* @param {?} s
* @return {?}
*/
s => unescapedText[s]));
}
/**
* Create a `StateKey<T>` that can be used to store value of type T with `TransferState`.
*
* Example:
*
* ```
* const COUNTER_KEY = makeStateKey<number>('counter');
* let value = 10;
*
* transferState.set(COUNTER_KEY, value);
* ```
*
* \@publicApi
* @template T
* @param {?} key
* @return {?}
*/
function makeStateKey(key) {
return (/** @type {?} */ (key));
}
/**
* A key value store that is transferred from the application on the server side to the application
* on the client side.
*
* `TransferState` will be available as an injectable token. To use it import
* `ServerTransferStateModule` on the server and `BrowserTransferStateModule` on the client.
*
* The values in the store are serialized/deserialized using JSON.stringify/JSON.parse. So only
* boolean, number, string, null and non-class objects will be serialized and deserialzied in a
* non-lossy manner.
*
* \@publicApi
*/
class TransferState {
constructor() {
this.store = {};
this.onSerializeCallbacks = {};
}
/**
* \@internal
* @param {?} initState
* @return {?}
*/
static init(initState) {
/** @type {?} */
const transferState = new TransferState();
transferState.store = initState;
return transferState;
}
/**
* Get the value corresponding to a key. Return `defaultValue` if key is not found.
* @template T
* @param {?} key
* @param {?} defaultValue
* @return {?}
*/
get(key, defaultValue) {
return this.store[key] !== undefined ? (/** @type {?} */ (this.store[key])) : defaultValue;
}
/**
* Set the value corresponding to a key.
* @template T
* @param {?} key
* @param {?} value
* @return {?}
*/
set(key, value) {
this.store[key] = value;
}
/**
* Remove a key from the store.
* @template T
* @param {?} key
* @return {?}
*/
remove(key) {
delete this.store[key];
}
/**
* Test whether a key exists in the store.
* @template T
* @param {?} key
* @return {?}
*/
hasKey(key) {
return this.store.hasOwnProperty(key);
}
/**
* Register a callback to provide the value for a key when `toJson` is called.
* @template T
* @param {?} key
* @param {?} callback
* @return {?}
*/
onSerialize(key, callback) {
this.onSerializeCallbacks[key] = callback;
}
/**
* Serialize the current state of the store to JSON.
* @return {?}
*/
toJson() {
// Call the onSerialize callbacks and put those values into the store.
for (const key in this.onSerializeCallbacks) {
if (this.onSerializeCallbacks.hasOwnProperty(key)) {
try {
this.store[key] = this.onSerializeCallbacks[key]();
}
catch (e) {
console.warn('Exception in onSerialize callback: ', e);
}
}
}
return JSON.stringify(this.store);
}
}
TransferState.ɵfac = function TransferState_Factory(t) { return new (t || TransferState)(); };
TransferState.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: TransferState, factory: TransferState.ɵfac });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](TransferState, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return []; }, null); })();
if (false) {}
/**
* @param {?} doc
* @param {?} appId
* @return {?}
*/
function initTransferState(doc, appId) {
// Locate the script tag with the JSON data transferred from the server.
// The id of the script tag is set to the Angular appId + 'state'.
/** @type {?} */
const script = doc.getElementById(appId + '-state');
/** @type {?} */
let initialState = {};
if (script && script.textContent) {
try {
initialState = JSON.parse(unescapeHtml(script.textContent));
}
catch (e) {
console.warn('Exception while restoring TransferState for app ' + appId, e);
}
}
return TransferState.init(initialState);
}
/**
* NgModule to install on the client side while using the `TransferState` to transfer state from
* server to client.
*
* \@publicApi
*/
class BrowserTransferStateModule {
}
BrowserTransferStateModule.ɵmod = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineNgModule"]({ type: BrowserTransferStateModule });
BrowserTransferStateModule.ɵinj = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjector"]({ factory: function BrowserTransferStateModule_Factory(t) { return new (t || BrowserTransferStateModule)(); }, providers: [{ provide: TransferState, useFactory: initTransferState, deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_ID"]] }] });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](BrowserTransferStateModule, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModule"],
args: [{
providers: [{ provide: TransferState, useFactory: initTransferState, deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["DOCUMENT"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_ID"]] }]
}]
}], null, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/dom/debug/by.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Predicates for use with {\@link DebugElement}'s query functions.
*
* \@publicApi
*/
class By {
/**
* Match all nodes.
*
* \@usageNotes
* ### Example
*
* {\@example platform-browser/dom/debug/ts/by/by.ts region='by_all'}
* @return {?}
*/
static all() {
return (/**
* @return {?}
*/
() => true);
}
/**
* Match elements by the given CSS selector.
*
* \@usageNotes
* ### Example
*
* {\@example platform-browser/dom/debug/ts/by/by.ts region='by_css'}
* @param {?} selector
* @return {?}
*/
static css(selector) {
return (/**
* @param {?} debugElement
* @return {?}
*/
(debugElement) => {
return debugElement.nativeElement != null ?
elementMatches(debugElement.nativeElement, selector) :
false;
});
}
/**
* Match nodes that have the given directive present.
*
* \@usageNotes
* ### Example
*
* {\@example platform-browser/dom/debug/ts/by/by.ts region='by_directive'}
* @param {?} type
* @return {?}
*/
static directive(type) {
return (/**
* @param {?} debugNode
* @return {?}
*/
(debugNode) => (/** @type {?} */ (debugNode.providerTokens)).indexOf(type) !== -1);
}
}
/**
* @param {?} n
* @param {?} selector
* @return {?}
*/
function elementMatches(n, selector) {
if (Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().isElementNode(n)) {
return n.matches && n.matches(selector) ||
n.msMatchesSelector && n.msMatchesSelector(selector) ||
n.webkitMatchesSelector && n.webkitMatchesSelector(selector);
}
return false;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/private_export.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/version.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@publicApi
* @type {?}
*/
const VERSION = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["Version"]('9.1.13');
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/src/platform-browser.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/public_api.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/platform-browser/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Generated bundle index. Do not edit.
*/
//# sourceMappingURL=platform-browser.js.map
/***/ }),
/***/ "./node_modules/@angular/router/__ivy_ngcc__/fesm2015/router.js":
/*!**********************************************************************!*\
!*** ./node_modules/@angular/router/__ivy_ngcc__/fesm2015/router.js ***!
\**********************************************************************/
/*! exports provided: ActivatedRoute, ActivatedRouteSnapshot, ActivationEnd, ActivationStart, ChildActivationEnd, ChildActivationStart, ChildrenOutletContexts, DefaultUrlSerializer, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, NoPreloading, OutletContext, PRIMARY_OUTLET, PreloadAllModules, PreloadingStrategy, ROUTER_CONFIGURATION, ROUTER_INITIALIZER, ROUTES, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouteReuseStrategy, Router, RouterEvent, RouterLink, RouterLinkActive, RouterLinkWithHref, RouterModule, RouterOutlet, RouterPreloader, RouterState, RouterStateSnapshot, RoutesRecognized, Scroll, UrlHandlingStrategy, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree, VERSION, convertToParamMap, provideRoutes, ɵEmptyOutletComponent, ɵROUTER_PROVIDERS, ɵangular_packages_router_router_a, ɵangular_packages_router_router_b, ɵangular_packages_router_router_c, ɵangular_packages_router_router_d, ɵangular_packages_router_router_e, ɵangular_packages_router_router_f, ɵangular_packages_router_router_g, ɵangular_packages_router_router_h, ɵangular_packages_router_router_i, ɵangular_packages_router_router_j, ɵangular_packages_router_router_k, ɵangular_packages_router_router_l, ɵangular_packages_router_router_m, ɵangular_packages_router_router_n, ɵangular_packages_router_router_o, ɵflatten */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActivatedRoute", function() { return ActivatedRoute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActivatedRouteSnapshot", function() { return ActivatedRouteSnapshot; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActivationEnd", function() { return ActivationEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActivationStart", function() { return ActivationStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChildActivationEnd", function() { return ChildActivationEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChildActivationStart", function() { return ChildActivationStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChildrenOutletContexts", function() { return ChildrenOutletContexts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultUrlSerializer", function() { return DefaultUrlSerializer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GuardsCheckEnd", function() { return GuardsCheckEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GuardsCheckStart", function() { return GuardsCheckStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NavigationCancel", function() { return NavigationCancel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NavigationEnd", function() { return NavigationEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NavigationError", function() { return NavigationError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NavigationStart", function() { return NavigationStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NoPreloading", function() { return NoPreloading; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OutletContext", function() { return OutletContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PRIMARY_OUTLET", function() { return PRIMARY_OUTLET; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PreloadAllModules", function() { return PreloadAllModules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PreloadingStrategy", function() { return PreloadingStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ROUTER_CONFIGURATION", function() { return ROUTER_CONFIGURATION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ROUTER_INITIALIZER", function() { return ROUTER_INITIALIZER; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ROUTES", function() { return ROUTES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ResolveEnd", function() { return ResolveEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ResolveStart", function() { return ResolveStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouteConfigLoadEnd", function() { return RouteConfigLoadEnd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouteConfigLoadStart", function() { return RouteConfigLoadStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouteReuseStrategy", function() { return RouteReuseStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Router", function() { return Router; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouterEvent", function() { return RouterEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouterLink", function() { return RouterLink; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouterLinkActive", function() { return RouterLinkActive; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouterLinkWithHref", function() { return RouterLinkWithHref; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouterModule", function() { return RouterModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouterOutlet", function() { return RouterOutlet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouterPreloader", function() { return RouterPreloader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouterState", function() { return RouterState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RouterStateSnapshot", function() { return RouterStateSnapshot; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RoutesRecognized", function() { return RoutesRecognized; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Scroll", function() { return Scroll; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UrlHandlingStrategy", function() { return UrlHandlingStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UrlSegment", function() { return UrlSegment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UrlSegmentGroup", function() { return UrlSegmentGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UrlSerializer", function() { return UrlSerializer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UrlTree", function() { return UrlTree; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return VERSION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertToParamMap", function() { return convertToParamMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "provideRoutes", function() { return provideRoutes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵEmptyOutletComponent", function() { return ɵEmptyOutletComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵROUTER_PROVIDERS", function() { return ROUTER_PROVIDERS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_a", function() { return ROUTER_FORROOT_GUARD; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_b", function() { return routerNgProbeToken; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_c", function() { return createRouterScroller; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_d", function() { return provideLocationStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_e", function() { return provideForRootGuard; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_f", function() { return setupRouter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_g", function() { return rootRoute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_h", function() { return RouterInitializer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_i", function() { return getAppInitializer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_j", function() { return getBootstrapListener; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_k", function() { return provideRouterInitializer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_l", function() { return ɵEmptyOutletComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_m", function() { return Tree; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_n", function() { return TreeNode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵangular_packages_router_router_o", function() { return RouterScroller; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ɵflatten", function() { return flatten; });
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/__ivy_ngcc__/fesm2015/common.js");
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js");
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm2015/index.js");
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs/operators */ "./node_modules/rxjs/_esm2015/operators/index.js");
/**
* @license Angular v9.1.13
* (c) 2010-2020 Google LLC. https://angular.io/
* License: MIT
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/events.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Base for events the router goes through, as opposed to events tied to a specific
* route. Fired one time for any given navigation.
*
* \@usageNotes
*
* ```ts
* class MyService {
* constructor(public router: Router, logger: Logger) {
* router.events.pipe(
* filter((e: Event): e is RouterEvent => e instanceof RouterEvent)
* ).subscribe((e: RouterEvent) => {
* logger.log(e.id, e.url);
* });
* }
* }
* ```
*
* @see `Event`
* \@publicApi
*/
class RouterEvent {
/**
* @param {?} id
* @param {?} url
*/
constructor(id, url) {
this.id = id;
this.url = url;
}
}
if (false) {}
/**
* An event triggered when a navigation starts.
*
* \@publicApi
*/
class NavigationStart extends RouterEvent {
/**
* @param {?} id
* @param {?} url
* @param {?=} navigationTrigger
* @param {?=} restoredState
*/
constructor(
/** @docsNotRequired */
id,
/** @docsNotRequired */
url,
/** @docsNotRequired */
navigationTrigger = 'imperative',
/** @docsNotRequired */
restoredState = null) {
super(id, url);
this.navigationTrigger = navigationTrigger;
this.restoredState = restoredState;
}
/**
* \@docsNotRequired
* @return {?}
*/
toString() {
return `NavigationStart(id: ${this.id}, url: '${this.url}')`;
}
}
if (false) {}
/**
* An event triggered when a navigation ends successfully.
*
* \@publicApi
*/
class NavigationEnd extends RouterEvent {
/**
* @param {?} id
* @param {?} url
* @param {?} urlAfterRedirects
*/
constructor(
/** @docsNotRequired */
id,
/** @docsNotRequired */
url, urlAfterRedirects) {
super(id, url);
this.urlAfterRedirects = urlAfterRedirects;
}
/**
* \@docsNotRequired
* @return {?}
*/
toString() {
return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`;
}
}
if (false) {}
/**
* An event triggered when a navigation is canceled, directly or indirectly.
*
* This can happen when a [route guard](guide/router#milestone-5-route-guards)
* returns `false` or initiates a redirect by returning a `UrlTree`.
*
* \@publicApi
*/
class NavigationCancel extends RouterEvent {
/**
* @param {?} id
* @param {?} url
* @param {?} reason
*/
constructor(
/** @docsNotRequired */
id,
/** @docsNotRequired */
url, reason) {
super(id, url);
this.reason = reason;
}
/**
* \@docsNotRequired
* @return {?}
*/
toString() {
return `NavigationCancel(id: ${this.id}, url: '${this.url}')`;
}
}
if (false) {}
/**
* An event triggered when a navigation fails due to an unexpected error.
*
* \@publicApi
*/
class NavigationError extends RouterEvent {
/**
* @param {?} id
* @param {?} url
* @param {?} error
*/
constructor(
/** @docsNotRequired */
id,
/** @docsNotRequired */
url, error) {
super(id, url);
this.error = error;
}
/**
* \@docsNotRequired
* @return {?}
*/
toString() {
return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`;
}
}
if (false) {}
/**
* An event triggered when routes are recognized.
*
* \@publicApi
*/
class RoutesRecognized extends RouterEvent {
/**
* @param {?} id
* @param {?} url
* @param {?} urlAfterRedirects
* @param {?} state
*/
constructor(
/** @docsNotRequired */
id,
/** @docsNotRequired */
url, urlAfterRedirects, state) {
super(id, url);
this.urlAfterRedirects = urlAfterRedirects;
this.state = state;
}
/**
* \@docsNotRequired
* @return {?}
*/
toString() {
return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
}
}
if (false) {}
/**
* An event triggered at the start of the Guard phase of routing.
*
* \@publicApi
*/
class GuardsCheckStart extends RouterEvent {
/**
* @param {?} id
* @param {?} url
* @param {?} urlAfterRedirects
* @param {?} state
*/
constructor(
/** @docsNotRequired */
id,
/** @docsNotRequired */
url, urlAfterRedirects, state) {
super(id, url);
this.urlAfterRedirects = urlAfterRedirects;
this.state = state;
}
/**
* @return {?}
*/
toString() {
return `GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
}
}
if (false) {}
/**
* An event triggered at the end of the Guard phase of routing.
*
* \@publicApi
*/
class GuardsCheckEnd extends RouterEvent {
/**
* @param {?} id
* @param {?} url
* @param {?} urlAfterRedirects
* @param {?} state
* @param {?} shouldActivate
*/
constructor(
/** @docsNotRequired */
id,
/** @docsNotRequired */
url, urlAfterRedirects, state, shouldActivate) {
super(id, url);
this.urlAfterRedirects = urlAfterRedirects;
this.state = state;
this.shouldActivate = shouldActivate;
}
/**
* @return {?}
*/
toString() {
return `GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`;
}
}
if (false) {}
/**
* An event triggered at the the start of the Resolve phase of routing.
*
* Runs in the "resolve" phase whether or not there is anything to resolve.
* In future, may change to only run when there are things to be resolved.
*
* \@publicApi
*/
class ResolveStart extends RouterEvent {
/**
* @param {?} id
* @param {?} url
* @param {?} urlAfterRedirects
* @param {?} state
*/
constructor(
/** @docsNotRequired */
id,
/** @docsNotRequired */
url, urlAfterRedirects, state) {
super(id, url);
this.urlAfterRedirects = urlAfterRedirects;
this.state = state;
}
/**
* @return {?}
*/
toString() {
return `ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
}
}
if (false) {}
/**
* An event triggered at the end of the Resolve phase of routing.
* @see `ResolveStart`.
*
* \@publicApi
*/
class ResolveEnd extends RouterEvent {
/**
* @param {?} id
* @param {?} url
* @param {?} urlAfterRedirects
* @param {?} state
*/
constructor(
/** @docsNotRequired */
id,
/** @docsNotRequired */
url, urlAfterRedirects, state) {
super(id, url);
this.urlAfterRedirects = urlAfterRedirects;
this.state = state;
}
/**
* @return {?}
*/
toString() {
return `ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
}
}
if (false) {}
/**
* An event triggered before lazy loading a route configuration.
*
* \@publicApi
*/
class RouteConfigLoadStart {
/**
* @param {?} route
*/
constructor(route) {
this.route = route;
}
/**
* @return {?}
*/
toString() {
return `RouteConfigLoadStart(path: ${this.route.path})`;
}
}
if (false) {}
/**
* An event triggered when a route has been lazy loaded.
*
* \@publicApi
*/
class RouteConfigLoadEnd {
/**
* @param {?} route
*/
constructor(route) {
this.route = route;
}
/**
* @return {?}
*/
toString() {
return `RouteConfigLoadEnd(path: ${this.route.path})`;
}
}
if (false) {}
/**
* An event triggered at the start of the child-activation
* part of the Resolve phase of routing.
* @see `ChildActivationEnd`
* @see `ResolveStart`
*
* \@publicApi
*/
class ChildActivationStart {
/**
* @param {?} snapshot
*/
constructor(snapshot) {
this.snapshot = snapshot;
}
/**
* @return {?}
*/
toString() {
/** @type {?} */
const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
return `ChildActivationStart(path: '${path}')`;
}
}
if (false) {}
/**
* An event triggered at the end of the child-activation part
* of the Resolve phase of routing.
* @see `ChildActivationStart`
* @see `ResolveStart` *
* \@publicApi
*/
class ChildActivationEnd {
/**
* @param {?} snapshot
*/
constructor(snapshot) {
this.snapshot = snapshot;
}
/**
* @return {?}
*/
toString() {
/** @type {?} */
const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
return `ChildActivationEnd(path: '${path}')`;
}
}
if (false) {}
/**
* An event triggered at the start of the activation part
* of the Resolve phase of routing.
* @see ActivationEnd`
* @see `ResolveStart`
*
* \@publicApi
*/
class ActivationStart {
/**
* @param {?} snapshot
*/
constructor(snapshot) {
this.snapshot = snapshot;
}
/**
* @return {?}
*/
toString() {
/** @type {?} */
const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
return `ActivationStart(path: '${path}')`;
}
}
if (false) {}
/**
* An event triggered at the end of the activation part
* of the Resolve phase of routing.
* @see `ActivationStart`
* @see `ResolveStart`
*
* \@publicApi
*/
class ActivationEnd {
/**
* @param {?} snapshot
*/
constructor(snapshot) {
this.snapshot = snapshot;
}
/**
* @return {?}
*/
toString() {
/** @type {?} */
const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
return `ActivationEnd(path: '${path}')`;
}
}
if (false) {}
/**
* An event triggered by scrolling.
*
* \@publicApi
*/
class Scroll {
/**
* @param {?} routerEvent
* @param {?} position
* @param {?} anchor
*/
constructor(routerEvent, position, anchor) {
this.routerEvent = routerEvent;
this.position = position;
this.anchor = anchor;
}
/**
* @return {?}
*/
toString() {
/** @type {?} */
const pos = this.position ? `${this.position[0]}, ${this.position[1]}` : null;
return `Scroll(anchor: '${this.anchor}', position: '${pos}')`;
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/components/empty_outlet.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* This component is used internally within the router to be a placeholder when an empty
* router-outlet is needed. For example, with a config such as:
*
* `{path: 'parent', outlet: 'nav', children: [...]}`
*
* In order to render, there needs to be a component on this config, which will default
* to this `EmptyOutletComponent`.
*/
class ɵEmptyOutletComponent {
}
ɵEmptyOutletComponent.ɵfac = function ɵEmptyOutletComponent_Factory(t) { return new (t || ɵEmptyOutletComponent)(); };
ɵEmptyOutletComponent.ɵcmp = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineComponent"]({ type: ɵEmptyOutletComponent, selectors: [["ng-component"]], decls: 1, vars: 0, template: function ɵEmptyOutletComponent_Template(rf, ctx) { if (rf & 1) {
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelement"](0, "router-outlet");
} }, directives: function () { return [RouterOutlet]; }, encapsulation: 2 });
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](ɵEmptyOutletComponent, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Component"],
args: [{ template: `<router-outlet></router-outlet>` }]
}], null, null); })();
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/shared.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* The primary routing outlet.
*
* \@publicApi
* @type {?}
*/
const PRIMARY_OUTLET = 'primary';
/**
* A map that provides access to the required and optional parameters
* specific to a route.
* The map supports retrieving a single value with `get()`
* or multiple values with `getAll()`.
*
* @see [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
*
* \@publicApi
* @record
*/
function ParamMap() { }
if (false) {}
class ParamsAsMap {
/**
* @param {?} params
*/
constructor(params) {
this.params = params || {};
}
/**
* @param {?} name
* @return {?}
*/
has(name) {
return this.params.hasOwnProperty(name);
}
/**
* @param {?} name
* @return {?}
*/
get(name) {
if (this.has(name)) {
/** @type {?} */
const v = this.params[name];
return Array.isArray(v) ? v[0] : v;
}
return null;
}
/**
* @param {?} name
* @return {?}
*/
getAll(name) {
if (this.has(name)) {
/** @type {?} */
const v = this.params[name];
return Array.isArray(v) ? v : [v];
}
return [];
}
/**
* @return {?}
*/
get keys() {
return Object.keys(this.params);
}
}
if (false) {}
/**
* Converts a `Params` instance to a `ParamMap`.
* \@publicApi
* @param {?} params The instance to convert.
* @return {?} The new map instance.
*
*/
function convertToParamMap(params) {
return new ParamsAsMap(params);
}
/** @type {?} */
const NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError';
/**
* @param {?} message
* @return {?}
*/
function navigationCancelingError(message) {
/** @type {?} */
const error = Error('NavigationCancelingError: ' + message);
((/** @type {?} */ (error)))[NAVIGATION_CANCELING_ERROR] = true;
return error;
}
/**
* @param {?} error
* @return {?}
*/
function isNavigationCancelingError(error) {
return error && ((/** @type {?} */ (error)))[NAVIGATION_CANCELING_ERROR];
}
// Matches the route configuration (`route`) against the actual URL (`segments`).
/**
* @param {?} segments
* @param {?} segmentGroup
* @param {?} route
* @return {?}
*/
function defaultUrlMatcher(segments, segmentGroup, route) {
/** @type {?} */
const parts = (/** @type {?} */ (route.path)).split('/');
if (parts.length > segments.length) {
// The actual URL is shorter than the config, no match
return null;
}
if (route.pathMatch === 'full' &&
(segmentGroup.hasChildren() || parts.length < segments.length)) {
// The config is longer than the actual URL but we are looking for a full match, return null
return null;
}
/** @type {?} */
const posParams = {};
// Check each config part against the actual URL
for (let index = 0; index < parts.length; index++) {
/** @type {?} */
const part = parts[index];
/** @type {?} */
const segment = segments[index];
/** @type {?} */
const isParameter = part.startsWith(':');
if (isParameter) {
posParams[part.substring(1)] = segment;
}
else if (part !== segment.path) {
// The actual URL part does not match the config, no match
return null;
}
}
return { consumed: segments.slice(0, parts.length), posParams };
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/config.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A configuration object that defines a single route.
* A set of routes are collected in a `Routes` array to define a `Router` configuration.
* The router attempts to match segments of a given URL against each route,
* using the configuration options defined in this object.
*
* Supports static, parameterized, redirect, and wildcard routes, as well as
* custom route data and resolve methods.
*
* For detailed usage information, see the [Routing Guide](guide/router).
*
* \@usageNotes
*
* ### Simple Configuration
*
* The following route specifies that when navigating to, for example,
* `/team/11/user/bob`, the router creates the 'Team' component
* with the 'User' child component in it.
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: 'user/:name',
* component: User
* }]
* }]
* ```
*
* ### Multiple Outlets
*
* The following route creates sibling components with multiple outlets.
* When navigating to `/team/11(aux:chat/jim)`, the router creates the 'Team' component next to
* the 'Chat' component. The 'Chat' component is placed into the 'aux' outlet.
*
* ```
* [{
* path: 'team/:id',
* component: Team
* }, {
* path: 'chat/:user',
* component: Chat
* outlet: 'aux'
* }]
* ```
*
* ### Wild Cards
*
* The following route uses wild-card notation to specify a component
* that is always instantiated regardless of where you navigate to.
*
* ```
* [{
* path: '**',
* component: WildcardComponent
* }]
* ```
*
* ### Redirects
*
* The following route uses the `redirectTo` property to ignore a segment of
* a given URL when looking for a child path.
*
* When navigating to '/team/11/legacy/user/jim', the router changes the URL segment
* '/team/11/legacy/user/jim' to '/team/11/user/jim', and then instantiates
* the Team component with the User child component in it.
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: 'legacy/user/:name',
* redirectTo: 'user/:name'
* }, {
* path: 'user/:name',
* component: User
* }]
* }]
* ```
*
* The redirect path can be relative, as shown in this example, or absolute.
* If we change the `redirectTo` value in the example to the absolute URL segment '/user/:name',
* the result URL is also absolute, '/user/jim'.
* ### Empty Path
*
* Empty-path route configurations can be used to instantiate components that do not 'consume'
* any URL segments.
*
* In the following configuration, when navigating to
* `/team/11`, the router instantiates the 'AllUsers' component.
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: '',
* component: AllUsers
* }, {
* path: 'user/:name',
* component: User
* }]
* }]
* ```
*
* Empty-path routes can have children. In the following example, when navigating
* to `/team/11/user/jim`, the router instantiates the wrapper component with
* the user component in it.
*
* Note that an empty path route inherits its parent's parameters and data.
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: '',
* component: WrapperCmp,
* children: [{
* path: 'user/:name',
* component: User
* }]
* }]
* }]
* ```
*
* ### Matching Strategy
*
* The default path-match strategy is 'prefix', which means that the router
* checks URL elements from the left to see if the URL matches a specified path.
* For example, '/team/11/user' matches 'team/:id'.
*
* ```
* [{
* path: '',
* pathMatch: 'prefix', //default
* redirectTo: 'main'
* }, {
* path: 'main',
* component: Main
* }]
* ```
*
* You can specify the path-match strategy 'full' to make sure that the path
* covers the whole unconsumed URL. It is important to do this when redirecting
* empty-path routes. Otherwise, because an empty path is a prefix of any URL,
* the router would apply the redirect even when navigating to the redirect destination,
* creating an endless loop.
*
* In the following example, supplying the 'full' `pathMatch` strategy ensures
* that the router applies the redirect if and only if navigating to '/'.
*
* ```
* [{
* path: '',
* pathMatch: 'full',
* redirectTo: 'main'
* }, {
* path: 'main',
* component: Main
* }]
* ```
*
* ### Componentless Routes
*
* You can share parameters between sibling components.
* For example, suppose that two sibling components should go next to each other,
* and both of them require an ID parameter. You can accomplish this using a route
* that does not specify a component at the top level.
*
* In the following example, 'MainChild' and 'AuxChild' are siblings.
* When navigating to 'parent/10/(a//aux:b)', the route instantiates
* the main child and aux child components next to each other.
* For this to work, the application component must have the primary and aux outlets defined.
*
* ```
* [{
* path: 'parent/:id',
* children: [
* { path: 'a', component: MainChild },
* { path: 'b', component: AuxChild, outlet: 'aux' }
* ]
* }]
* ```
*
* The router merges the parameters, data, and resolve of the componentless
* parent into the parameters, data, and resolve of the children.
*
* This is especially useful when child components are defined
* with an empty path string, as in the following example.
* With this configuration, navigating to '/parent/10' creates
* the main child and aux components.
*
* ```
* [{
* path: 'parent/:id',
* children: [
* { path: '', component: MainChild },
* { path: '', component: AuxChild, outlet: 'aux' }
* ]
* }]
* ```
*
* ### Lazy Loading
*
* Lazy loading speeds up application load time by splitting the application
* into multiple bundles and loading them on demand.
* To use lazy loading, provide the `loadChildren` property instead of the `children` property.
*
* Given the following example route, the router will lazy load
* the associated module on demand using the browser native import system.
*
* ```
* [{
* path: 'lazy',
* loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule),
* }];
* ```
*
* \@publicApi
* @record
*/
function Route() { }
if (false) {}
class LoadedRouterConfig {
/**
* @param {?} routes
* @param {?} module
*/
constructor(routes, module) {
this.routes = routes;
this.module = module;
}
}
if (false) {}
/**
* @param {?} config
* @param {?=} parentPath
* @return {?}
*/
function validateConfig(config, parentPath = '') {
// forEach doesn't iterate undefined values
for (let i = 0; i < config.length; i++) {
/** @type {?} */
const route = config[i];
/** @type {?} */
const fullPath = getFullPath(parentPath, route);
validateNode(route, fullPath);
}
}
/**
* @param {?} route
* @param {?} fullPath
* @return {?}
*/
function validateNode(route, fullPath) {
if (!route) {
throw new Error(`
Invalid configuration of route '${fullPath}': Encountered undefined route.
The reason might be an extra comma.
Example:
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },, << two commas
{ path: 'detail/:id', component: HeroDetailComponent }
];
`);
}
if (Array.isArray(route)) {
throw new Error(`Invalid configuration of route '${fullPath}': Array cannot be specified`);
}
if (!route.component && !route.children && !route.loadChildren &&
(route.outlet && route.outlet !== PRIMARY_OUTLET)) {
throw new Error(`Invalid configuration of route '${fullPath}': a componentless route without children or loadChildren cannot have a named outlet set`);
}
if (route.redirectTo && route.children) {
throw new Error(`Invalid configuration of route '${fullPath}': redirectTo and children cannot be used together`);
}
if (route.redirectTo && route.loadChildren) {
throw new Error(`Invalid configuration of route '${fullPath}': redirectTo and loadChildren cannot be used together`);
}
if (route.children && route.loadChildren) {
throw new Error(`Invalid configuration of route '${fullPath}': children and loadChildren cannot be used together`);
}
if (route.redirectTo && route.component) {
throw new Error(`Invalid configuration of route '${fullPath}': redirectTo and component cannot be used together`);
}
if (route.path && route.matcher) {
throw new Error(`Invalid configuration of route '${fullPath}': path and matcher cannot be used together`);
}
if (route.redirectTo === void 0 && !route.component && !route.children && !route.loadChildren) {
throw new Error(`Invalid configuration of route '${fullPath}'. One of the following must be provided: component, redirectTo, children or loadChildren`);
}
if (route.path === void 0 && route.matcher === void 0) {
throw new Error(`Invalid configuration of route '${fullPath}': routes must have either a path or a matcher specified`);
}
if (typeof route.path === 'string' && route.path.charAt(0) === '/') {
throw new Error(`Invalid configuration of route '${fullPath}': path cannot start with a slash`);
}
if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) {
/** @type {?} */
const exp = `The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.`;
throw new Error(`Invalid configuration of route '{path: "${fullPath}", redirectTo: "${route.redirectTo}"}': please provide 'pathMatch'. ${exp}`);
}
if (route.pathMatch !== void 0 && route.pathMatch !== 'full' && route.pathMatch !== 'prefix') {
throw new Error(`Invalid configuration of route '${fullPath}': pathMatch can only be set to 'prefix' or 'full'`);
}
if (route.children) {
validateConfig(route.children, fullPath);
}
}
/**
* @param {?} parentPath
* @param {?} currentRoute
* @return {?}
*/
function getFullPath(parentPath, currentRoute) {
if (!currentRoute) {
return parentPath;
}
if (!parentPath && !currentRoute.path) {
return '';
}
else if (parentPath && !currentRoute.path) {
return `${parentPath}/`;
}
else if (!parentPath && currentRoute.path) {
return currentRoute.path;
}
else {
return `${parentPath}/${currentRoute.path}`;
}
}
/**
* Makes a copy of the config and adds any default required properties.
* @param {?} r
* @return {?}
*/
function standardizeConfig(r) {
/** @type {?} */
const children = r.children && r.children.map(standardizeConfig);
/** @type {?} */
const c = children ? Object.assign(Object.assign({}, r), { children }) : Object.assign({}, r);
if (!c.component && (children || c.loadChildren) && (c.outlet && c.outlet !== PRIMARY_OUTLET)) {
c.component = ɵEmptyOutletComponent;
}
return c;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/utils/collection.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function shallowEqualArrays(a, b) {
if (a.length !== b.length)
return false;
for (let i = 0; i < a.length; ++i) {
if (!shallowEqual(a[i], b[i]))
return false;
}
return true;
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function shallowEqual(a, b) {
// Casting Object.keys return values to include `undefined` as there are some cases
// in IE 11 where this can happen. Cannot provide a test because the behavior only
// exists in certain circumstances in IE 11, therefore doing this cast ensures the
// logic is correct for when this edge case is hit.
/** @type {?} */
const k1 = (/** @type {?} */ (Object.keys(a)));
/** @type {?} */
const k2 = (/** @type {?} */ (Object.keys(b)));
if (!k1 || !k2 || k1.length != k2.length) {
return false;
}
/** @type {?} */
let key;
for (let i = 0; i < k1.length; i++) {
key = k1[i];
if (!equalArraysOrString(a[key], b[key])) {
return false;
}
}
return true;
}
/**
* Test equality for arrays of strings or a string.
* @param {?} a
* @param {?} b
* @return {?}
*/
function equalArraysOrString(a, b) {
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length != b.length)
return false;
return a.every((/**
* @param {?} aItem
* @return {?}
*/
aItem => b.indexOf(aItem) > -1));
}
else {
return a === b;
}
}
/**
* Flattens single-level nested arrays.
* @template T
* @param {?} arr
* @return {?}
*/
function flatten(arr) {
return Array.prototype.concat.apply([], arr);
}
/**
* Return the last element of an array.
* @template T
* @param {?} a
* @return {?}
*/
function last(a) {
return a.length > 0 ? a[a.length - 1] : null;
}
/**
* Verifys all booleans in an array are `true`.
* @param {?} bools
* @return {?}
*/
function and(bools) {
return !bools.some((/**
* @param {?} v
* @return {?}
*/
v => !v));
}
/**
* @template K, V
* @param {?} map
* @param {?} callback
* @return {?}
*/
function forEach(map, callback) {
for (const prop in map) {
if (map.hasOwnProperty(prop)) {
callback(map[prop], prop);
}
}
}
/**
* @template A, B
* @param {?} obj
* @param {?} fn
* @return {?}
*/
function waitForMap(obj, fn) {
if (Object.keys(obj).length === 0) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])({});
}
/** @type {?} */
const waitHead = [];
/** @type {?} */
const waitTail = [];
/** @type {?} */
const res = {};
forEach(obj, (/**
* @param {?} a
* @param {?} k
* @return {?}
*/
(a, k) => {
/** @type {?} */
const mapped = fn(k, a).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} r
* @return {?}
*/
(r) => res[k] = r)));
if (k === PRIMARY_OUTLET) {
waitHead.push(mapped);
}
else {
waitTail.push(mapped);
}
}));
// Closure compiler has problem with using spread operator here. So we use "Array.concat".
// Note that we also need to cast the new promise because TypeScript cannot infer the type
// when calling the "of" function through "Function.apply"
return ((/** @type {?} */ (rxjs__WEBPACK_IMPORTED_MODULE_2__["of"].apply(null, waitHead.concat(waitTail)))))
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["concatAll"])(), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["last"])(), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @return {?}
*/
() => res)));
}
/**
* @template T
* @param {?} value
* @return {?}
*/
function wrapIntoObservable(value) {
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵisObservable"])(value)) {
return value;
}
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵisPromise"])(value)) {
// Use `Promise.resolve()` to wrap promise-like instances.
// Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the
// change detection.
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(Promise.resolve(value));
}
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(value);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/url_tree.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @return {?}
*/
function createEmptyUrlTree() {
return new UrlTree(new UrlSegmentGroup([], {}), {}, null);
}
/**
* @param {?} container
* @param {?} containee
* @param {?} exact
* @return {?}
*/
function containsTree(container, containee, exact) {
if (exact) {
return equalQueryParams(container.queryParams, containee.queryParams) &&
equalSegmentGroups(container.root, containee.root);
}
return containsQueryParams(container.queryParams, containee.queryParams) &&
containsSegmentGroup(container.root, containee.root);
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function equalQueryParams(container, containee) {
// TODO: This does not handle array params correctly.
return shallowEqual(container, containee);
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function equalSegmentGroups(container, containee) {
if (!equalPath(container.segments, containee.segments))
return false;
if (container.numberOfChildren !== containee.numberOfChildren)
return false;
for (const c in containee.children) {
if (!container.children[c])
return false;
if (!equalSegmentGroups(container.children[c], containee.children[c]))
return false;
}
return true;
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function containsQueryParams(container, containee) {
// TODO: This does not handle array params correctly.
return Object.keys(containee).length <= Object.keys(container).length &&
Object.keys(containee).every((/**
* @param {?} key
* @return {?}
*/
key => equalArraysOrString(container[key], containee[key])));
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function containsSegmentGroup(container, containee) {
return containsSegmentGroupHelper(container, containee, containee.segments);
}
/**
* @param {?} container
* @param {?} containee
* @param {?} containeePaths
* @return {?}
*/
function containsSegmentGroupHelper(container, containee, containeePaths) {
if (container.segments.length > containeePaths.length) {
/** @type {?} */
const current = container.segments.slice(0, containeePaths.length);
if (!equalPath(current, containeePaths))
return false;
if (containee.hasChildren())
return false;
return true;
}
else if (container.segments.length === containeePaths.length) {
if (!equalPath(container.segments, containeePaths))
return false;
for (const c in containee.children) {
if (!container.children[c])
return false;
if (!containsSegmentGroup(container.children[c], containee.children[c]))
return false;
}
return true;
}
else {
/** @type {?} */
const current = containeePaths.slice(0, container.segments.length);
/** @type {?} */
const next = containeePaths.slice(container.segments.length);
if (!equalPath(container.segments, current))
return false;
if (!container.children[PRIMARY_OUTLET])
return false;
return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next);
}
}
/**
* \@description
*
* Represents the parsed URL.
*
* Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a
* serialized tree.
* UrlTree is a data structure that provides a lot of affordances in dealing with URLs
*
* \@usageNotes
* ### Example
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const tree: UrlTree =
* router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');
* const f = tree.fragment; // return 'fragment'
* const q = tree.queryParams; // returns {debug: 'true'}
* const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
* const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'
* g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'
* g.children['support'].segments; // return 1 segment 'help'
* }
* }
* ```
*
* \@publicApi
*/
class UrlTree {
/**
* \@internal
* @param {?} root
* @param {?} queryParams
* @param {?} fragment
*/
constructor(root, queryParams, fragment) {
this.root = root;
this.queryParams = queryParams;
this.fragment = fragment;
}
/**
* @return {?}
*/
get queryParamMap() {
if (!this._queryParamMap) {
this._queryParamMap = convertToParamMap(this.queryParams);
}
return this._queryParamMap;
}
/**
* \@docsNotRequired
* @return {?}
*/
toString() {
return DEFAULT_SERIALIZER.serialize(this);
}
}
if (false) {}
/**
* \@description
*
* Represents the parsed URL segment group.
*
* See `UrlTree` for more information.
*
* \@publicApi
*/
class UrlSegmentGroup {
/**
* @param {?} segments
* @param {?} children
*/
constructor(segments, children) {
this.segments = segments;
this.children = children;
/**
* The parent node in the url tree
*/
this.parent = null;
forEach(children, (/**
* @template THIS
* @this {THIS}
* @param {?} v
* @param {?} k
* @return {THIS}
*/
(v, k) => v.parent = this));
}
/**
* Whether the segment has child segments
* @return {?}
*/
hasChildren() {
return this.numberOfChildren > 0;
}
/**
* Number of child segments
* @return {?}
*/
get numberOfChildren() {
return Object.keys(this.children).length;
}
/**
* \@docsNotRequired
* @return {?}
*/
toString() {
return serializePaths(this);
}
}
if (false) {}
/**
* \@description
*
* Represents a single URL segment.
*
* A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix
* parameters associated with the segment.
*
* \@usageNotes
* ### Example
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const tree: UrlTree = router.parseUrl('/team;id=33');
* const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
* const s: UrlSegment[] = g.segments;
* s[0].path; // returns 'team'
* s[0].parameters; // returns {id: 33}
* }
* }
* ```
*
* \@publicApi
*/
class UrlSegment {
/**
* @param {?} path
* @param {?} parameters
*/
constructor(path, parameters) {
this.path = path;
this.parameters = parameters;
}
/**
* @return {?}
*/
get parameterMap() {
if (!this._parameterMap) {
this._parameterMap = convertToParamMap(this.parameters);
}
return this._parameterMap;
}
/**
* \@docsNotRequired
* @return {?}
*/
toString() {
return serializePath(this);
}
}
if (false) {}
/**
* @param {?} as
* @param {?} bs
* @return {?}
*/
function equalSegments(as, bs) {
return equalPath(as, bs) && as.every((/**
* @param {?} a
* @param {?} i
* @return {?}
*/
(a, i) => shallowEqual(a.parameters, bs[i].parameters)));
}
/**
* @param {?} as
* @param {?} bs
* @return {?}
*/
function equalPath(as, bs) {
if (as.length !== bs.length)
return false;
return as.every((/**
* @param {?} a
* @param {?} i
* @return {?}
*/
(a, i) => a.path === bs[i].path));
}
/**
* @template T
* @param {?} segment
* @param {?} fn
* @return {?}
*/
function mapChildrenIntoArray(segment, fn) {
/** @type {?} */
let res = [];
forEach(segment.children, (/**
* @param {?} child
* @param {?} childOutlet
* @return {?}
*/
(child, childOutlet) => {
if (childOutlet === PRIMARY_OUTLET) {
res = res.concat(fn(child, childOutlet));
}
}));
forEach(segment.children, (/**
* @param {?} child
* @param {?} childOutlet
* @return {?}
*/
(child, childOutlet) => {
if (childOutlet !== PRIMARY_OUTLET) {
res = res.concat(fn(child, childOutlet));
}
}));
return res;
}
/**
* \@description
*
* Serializes and deserializes a URL string into a URL tree.
*
* The url serialization strategy is customizable. You can
* make all URLs case insensitive by providing a custom UrlSerializer.
*
* See `DefaultUrlSerializer` for an example of a URL serializer.
*
* \@publicApi
* @abstract
*/
class UrlSerializer {
}
if (false) {}
/**
* \@description
*
* A default implementation of the `UrlSerializer`.
*
* Example URLs:
*
* ```
* /inbox/33(popup:compose)
* /inbox/33;open=true/messages/44
* ```
*
* DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
* colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
* specify route specific parameters.
*
* \@publicApi
*/
class DefaultUrlSerializer {
/**
* Parses a url into a `UrlTree`
* @param {?} url
* @return {?}
*/
parse(url) {
/** @type {?} */
const p = new UrlParser(url);
return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());
}
/**
* Converts a `UrlTree` into a url
* @param {?} tree
* @return {?}
*/
serialize(tree) {
/** @type {?} */
const segment = `/${serializeSegment(tree.root, true)}`;
/** @type {?} */
const query = serializeQueryParams(tree.queryParams);
/** @type {?} */
const fragment = typeof tree.fragment === `string` ? `#${encodeUriFragment((/** @type {?} */ (tree.fragment)))}` : '';
return `${segment}${query}${fragment}`;
}
}
/** @type {?} */
const DEFAULT_SERIALIZER = new DefaultUrlSerializer();
/**
* @param {?} segment
* @return {?}
*/
function serializePaths(segment) {
return segment.segments.map((/**
* @param {?} p
* @return {?}
*/
p => serializePath(p))).join('/');
}
/**
* @param {?} segment
* @param {?} root
* @return {?}
*/
function serializeSegment(segment, root) {
if (!segment.hasChildren()) {
return serializePaths(segment);
}
if (root) {
/** @type {?} */
const primary = segment.children[PRIMARY_OUTLET] ?
serializeSegment(segment.children[PRIMARY_OUTLET], false) :
'';
/** @type {?} */
const children = [];
forEach(segment.children, (/**
* @param {?} v
* @param {?} k
* @return {?}
*/
(v, k) => {
if (k !== PRIMARY_OUTLET) {
children.push(`${k}:${serializeSegment(v, false)}`);
}
}));
return children.length > 0 ? `${primary}(${children.join('//')})` : primary;
}
else {
/** @type {?} */
const children = mapChildrenIntoArray(segment, (/**
* @param {?} v
* @param {?} k
* @return {?}
*/
(v, k) => {
if (k === PRIMARY_OUTLET) {
return [serializeSegment(segment.children[PRIMARY_OUTLET], false)];
}
return [`${k}:${serializeSegment(v, false)}`];
}));
return `${serializePaths(segment)}/(${children.join('//')})`;
}
}
/**
* Encodes a URI string with the default encoding. This function will only ever be called from
* `encodeUriQuery` or `encodeUriSegment` as it's the base set of encodings to be used. We need
* a custom encoding because encodeURIComponent is too aggressive and encodes stuff that doesn't
* have to be encoded per https://url.spec.whatwg.org.
* @param {?} s
* @return {?}
*/
function encodeUriString(s) {
return encodeURIComponent(s)
.replace(/%40/g, '@')
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',');
}
/**
* This function should be used to encode both keys and values in a query string key/value. In
* the following URL, you need to call encodeUriQuery on "k" and "v":
*
* http://www.site.org/html;mk=mv?k=v#f
* @param {?} s
* @return {?}
*/
function encodeUriQuery(s) {
return encodeUriString(s).replace(/%3B/gi, ';');
}
/**
* This function should be used to encode a URL fragment. In the following URL, you need to call
* encodeUriFragment on "f":
*
* http://www.site.org/html;mk=mv?k=v#f
* @param {?} s
* @return {?}
*/
function encodeUriFragment(s) {
return encodeURI(s);
}
/**
* This function should be run on any URI segment as well as the key and value in a key/value
* pair for matrix params. In the following URL, you need to call encodeUriSegment on "html",
* "mk", and "mv":
*
* http://www.site.org/html;mk=mv?k=v#f
* @param {?} s
* @return {?}
*/
function encodeUriSegment(s) {
return encodeUriString(s).replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%26/gi, '&');
}
/**
* @param {?} s
* @return {?}
*/
function decode(s) {
return decodeURIComponent(s);
}
// Query keys/values should have the "+" replaced first, as "+" in a query string is " ".
// decodeURIComponent function will not decode "+" as a space.
/**
* @param {?} s
* @return {?}
*/
function decodeQuery(s) {
return decode(s.replace(/\+/g, '%20'));
}
/**
* @param {?} path
* @return {?}
*/
function serializePath(path) {
return `${encodeUriSegment(path.path)}${serializeMatrixParams(path.parameters)}`;
}
/**
* @param {?} params
* @return {?}
*/
function serializeMatrixParams(params) {
return Object.keys(params)
.map((/**
* @param {?} key
* @return {?}
*/
key => `;${encodeUriSegment(key)}=${encodeUriSegment(params[key])}`))
.join('');
}
/**
* @param {?} params
* @return {?}
*/
function serializeQueryParams(params) {
/** @type {?} */
const strParams = Object.keys(params).map((/**
* @param {?} name
* @return {?}
*/
(name) => {
/** @type {?} */
const value = params[name];
return Array.isArray(value) ?
value.map((/**
* @param {?} v
* @return {?}
*/
v => `${encodeUriQuery(name)}=${encodeUriQuery(v)}`)).join('&') :
`${encodeUriQuery(name)}=${encodeUriQuery(value)}`;
}));
return strParams.length ? `?${strParams.join('&')}` : '';
}
/** @type {?} */
const SEGMENT_RE = /^[^\/()?;=#]+/;
/**
* @param {?} str
* @return {?}
*/
function matchSegments(str) {
/** @type {?} */
const match = str.match(SEGMENT_RE);
return match ? match[0] : '';
}
/** @type {?} */
const QUERY_PARAM_RE = /^[^=?&#]+/;
// Return the name of the query param at the start of the string or an empty string
/**
* @param {?} str
* @return {?}
*/
function matchQueryParams(str) {
/** @type {?} */
const match = str.match(QUERY_PARAM_RE);
return match ? match[0] : '';
}
/** @type {?} */
const QUERY_PARAM_VALUE_RE = /^[^?&#]+/;
// Return the value of the query param at the start of the string or an empty string
/**
* @param {?} str
* @return {?}
*/
function matchUrlQueryParamValue(str) {
/** @type {?} */
const match = str.match(QUERY_PARAM_VALUE_RE);
return match ? match[0] : '';
}
class UrlParser {
/**
* @param {?} url
*/
constructor(url) {
this.url = url;
this.remaining = url;
}
/**
* @return {?}
*/
parseRootSegment() {
this.consumeOptional('/');
if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) {
return new UrlSegmentGroup([], {});
}
// The root segment group never has segments
return new UrlSegmentGroup([], this.parseChildren());
}
/**
* @return {?}
*/
parseQueryParams() {
/** @type {?} */
const params = {};
if (this.consumeOptional('?')) {
do {
this.parseQueryParam(params);
} while (this.consumeOptional('&'));
}
return params;
}
/**
* @return {?}
*/
parseFragment() {
return this.consumeOptional('#') ? decodeURIComponent(this.remaining) : null;
}
/**
* @private
* @return {?}
*/
parseChildren() {
if (this.remaining === '') {
return {};
}
this.consumeOptional('/');
/** @type {?} */
const segments = [];
if (!this.peekStartsWith('(')) {
segments.push(this.parseSegment());
}
while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) {
this.capture('/');
segments.push(this.parseSegment());
}
/** @type {?} */
let children = {};
if (this.peekStartsWith('/(')) {
this.capture('/');
children = this.parseParens(true);
}
/** @type {?} */
let res = {};
if (this.peekStartsWith('(')) {
res = this.parseParens(false);
}
if (segments.length > 0 || Object.keys(children).length > 0) {
res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children);
}
return res;
}
// parse a segment with its matrix parameters
// ie `name;k1=v1;k2`
/**
* @private
* @return {?}
*/
parseSegment() {
/** @type {?} */
const path = matchSegments(this.remaining);
if (path === '' && this.peekStartsWith(';')) {
throw new Error(`Empty path url segment cannot have parameters: '${this.remaining}'.`);
}
this.capture(path);
return new UrlSegment(decode(path), this.parseMatrixParams());
}
/**
* @private
* @return {?}
*/
parseMatrixParams() {
/** @type {?} */
const params = {};
while (this.consumeOptional(';')) {
this.parseParam(params);
}
return params;
}
/**
* @private
* @param {?} params
* @return {?}
*/
parseParam(params) {
/** @type {?} */
const key = matchSegments(this.remaining);
if (!key) {
return;
}
this.capture(key);
/** @type {?} */
let value = '';
if (this.consumeOptional('=')) {
/** @type {?} */
const valueMatch = matchSegments(this.remaining);
if (valueMatch) {
value = valueMatch;
this.capture(value);
}
}
params[decode(key)] = decode(value);
}
// Parse a single query parameter `name[=value]`
/**
* @private
* @param {?} params
* @return {?}
*/
parseQueryParam(params) {
/** @type {?} */
const key = matchQueryParams(this.remaining);
if (!key) {
return;
}
this.capture(key);
/** @type {?} */
let value = '';
if (this.consumeOptional('=')) {
/** @type {?} */
const valueMatch = matchUrlQueryParamValue(this.remaining);
if (valueMatch) {
value = valueMatch;
this.capture(value);
}
}
/** @type {?} */
const decodedKey = decodeQuery(key);
/** @type {?} */
const decodedVal = decodeQuery(value);
if (params.hasOwnProperty(decodedKey)) {
// Append to existing values
/** @type {?} */
let currentVal = params[decodedKey];
if (!Array.isArray(currentVal)) {
currentVal = [currentVal];
params[decodedKey] = currentVal;
}
currentVal.push(decodedVal);
}
else {
// Create a new value
params[decodedKey] = decodedVal;
}
}
// parse `(a/b//outlet_name:c/d)`
/**
* @private
* @param {?} allowPrimary
* @return {?}
*/
parseParens(allowPrimary) {
/** @type {?} */
const segments = {};
this.capture('(');
while (!this.consumeOptional(')') && this.remaining.length > 0) {
/** @type {?} */
const path = matchSegments(this.remaining);
/** @type {?} */
const next = this.remaining[path.length];
// if is is not one of these characters, then the segment was unescaped
// or the group was not closed
if (next !== '/' && next !== ')' && next !== ';') {
throw new Error(`Cannot parse url '${this.url}'`);
}
/** @type {?} */
let outletName = (/** @type {?} */ (undefined));
if (path.indexOf(':') > -1) {
outletName = path.substr(0, path.indexOf(':'));
this.capture(outletName);
this.capture(':');
}
else if (allowPrimary) {
outletName = PRIMARY_OUTLET;
}
/** @type {?} */
const children = this.parseChildren();
segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] :
new UrlSegmentGroup([], children);
this.consumeOptional('//');
}
return segments;
}
/**
* @private
* @param {?} str
* @return {?}
*/
peekStartsWith(str) {
return this.remaining.startsWith(str);
}
// Consumes the prefix when it is present and returns whether it has been consumed
/**
* @private
* @param {?} str
* @return {?}
*/
consumeOptional(str) {
if (this.peekStartsWith(str)) {
this.remaining = this.remaining.substring(str.length);
return true;
}
return false;
}
/**
* @private
* @param {?} str
* @return {?}
*/
capture(str) {
if (!this.consumeOptional(str)) {
throw new Error(`Expected "${str}".`);
}
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/utils/tree.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @template T
*/
class Tree {
/**
* @param {?} root
*/
constructor(root) {
this._root = root;
}
/**
* @return {?}
*/
get root() {
return this._root.value;
}
/**
* \@internal
* @param {?} t
* @return {?}
*/
parent(t) {
/** @type {?} */
const p = this.pathFromRoot(t);
return p.length > 1 ? p[p.length - 2] : null;
}
/**
* \@internal
* @param {?} t
* @return {?}
*/
children(t) {
/** @type {?} */
const n = findNode(t, this._root);
return n ? n.children.map((/**
* @param {?} t
* @return {?}
*/
t => t.value)) : [];
}
/**
* \@internal
* @param {?} t
* @return {?}
*/
firstChild(t) {
/** @type {?} */
const n = findNode(t, this._root);
return n && n.children.length > 0 ? n.children[0].value : null;
}
/**
* \@internal
* @param {?} t
* @return {?}
*/
siblings(t) {
/** @type {?} */
const p = findPath(t, this._root);
if (p.length < 2)
return [];
/** @type {?} */
const c = p[p.length - 2].children.map((/**
* @param {?} c
* @return {?}
*/
c => c.value));
return c.filter((/**
* @param {?} cc
* @return {?}
*/
cc => cc !== t));
}
/**
* \@internal
* @param {?} t
* @return {?}
*/
pathFromRoot(t) {
return findPath(t, this._root).map((/**
* @param {?} s
* @return {?}
*/
s => s.value));
}
}
if (false) {}
// DFS for the node matching the value
/**
* @template T
* @param {?} value
* @param {?} node
* @return {?}
*/
function findNode(value, node) {
if (value === node.value)
return node;
for (const child of node.children) {
/** @type {?} */
const node = findNode(value, child);
if (node)
return node;
}
return null;
}
// Return the path to the node with the given value using DFS
/**
* @template T
* @param {?} value
* @param {?} node
* @return {?}
*/
function findPath(value, node) {
if (value === node.value)
return [node];
for (const child of node.children) {
/** @type {?} */
const path = findPath(value, child);
if (path.length) {
path.unshift(node);
return path;
}
}
return [];
}
/**
* @template T
*/
class TreeNode {
/**
* @param {?} value
* @param {?} children
*/
constructor(value, children) {
this.value = value;
this.children = children;
}
/**
* @return {?}
*/
toString() {
return `TreeNode(${this.value})`;
}
}
if (false) {}
// Return the list of T indexed by outlet name
/**
* @template T
* @param {?} node
* @return {?}
*/
function nodeChildrenAsMap(node) {
/** @type {?} */
const map = {};
if (node) {
node.children.forEach((/**
* @param {?} child
* @return {?}
*/
child => map[child.value.outlet] = child));
}
return map;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/router_state.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Represents the state of the router as a tree of activated routes.
*
* \@usageNotes
*
* Every node in the route tree is an `ActivatedRoute` instance
* that knows about the "consumed" URL segments, the extracted parameters,
* and the resolved data.
* Use the `ActivatedRoute` properties to traverse the tree from any node.
*
* ### Example
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const state: RouterState = router.routerState;
* const root: ActivatedRoute = state.root;
* const child = root.firstChild;
* const id: Observable<string> = child.params.map(p => p.id);
* //...
* }
* }
* ```
*
* @see `ActivatedRoute`
*
* \@publicApi
*/
class RouterState extends Tree {
/**
* \@internal
* @param {?} root
* @param {?} snapshot
*/
constructor(root, snapshot) {
super(root);
this.snapshot = snapshot;
setRouterState((/** @type {?} */ (this)), root);
}
/**
* @return {?}
*/
toString() {
return this.snapshot.toString();
}
}
if (false) {}
/**
* @param {?} urlTree
* @param {?} rootComponent
* @return {?}
*/
function createEmptyState(urlTree, rootComponent) {
/** @type {?} */
const snapshot = createEmptyStateSnapshot(urlTree, rootComponent);
/** @type {?} */
const emptyUrl = new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"]([new UrlSegment('', {})]);
/** @type {?} */
const emptyParams = new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"]({});
/** @type {?} */
const emptyData = new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"]({});
/** @type {?} */
const emptyQueryParams = new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"]({});
/** @type {?} */
const fragment = new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"]('');
/** @type {?} */
const activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root);
activated.snapshot = snapshot.root;
return new RouterState(new TreeNode(activated, []), snapshot);
}
/**
* @param {?} urlTree
* @param {?} rootComponent
* @return {?}
*/
function createEmptyStateSnapshot(urlTree, rootComponent) {
/** @type {?} */
const emptyParams = {};
/** @type {?} */
const emptyData = {};
/** @type {?} */
const emptyQueryParams = {};
/** @type {?} */
const fragment = '';
/** @type {?} */
const activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, urlTree.root, -1, {});
return new RouterStateSnapshot('', new TreeNode(activated, []));
}
/**
* Provides access to information about a route associated with a component
* that is loaded in an outlet.
* Use to traverse the `RouterState` tree and extract information from nodes.
*
* {\@example router/activated-route/module.ts region="activated-route"
* header="activated-route.component.ts"}
*
* \@publicApi
*/
class ActivatedRoute {
/**
* \@internal
* @param {?} url
* @param {?} params
* @param {?} queryParams
* @param {?} fragment
* @param {?} data
* @param {?} outlet
* @param {?} component
* @param {?} futureSnapshot
*/
constructor(url, params, queryParams, fragment, data, outlet, component, futureSnapshot) {
this.url = url;
this.params = params;
this.queryParams = queryParams;
this.fragment = fragment;
this.data = data;
this.outlet = outlet;
this.component = component;
this._futureSnapshot = futureSnapshot;
}
/**
* The configuration used to match this route.
* @return {?}
*/
get routeConfig() {
return this._futureSnapshot.routeConfig;
}
/**
* The root of the router state.
* @return {?}
*/
get root() {
return this._routerState.root;
}
/**
* The parent of this route in the router state tree.
* @return {?}
*/
get parent() {
return this._routerState.parent(this);
}
/**
* The first child of this route in the router state tree.
* @return {?}
*/
get firstChild() {
return this._routerState.firstChild(this);
}
/**
* The children of this route in the router state tree.
* @return {?}
*/
get children() {
return this._routerState.children(this);
}
/**
* The path from the root of the router state tree to this route.
* @return {?}
*/
get pathFromRoot() {
return this._routerState.pathFromRoot(this);
}
/**
* An Observable that contains a map of the required and optional parameters
* specific to the route.
* The map supports retrieving single and multiple values from the same parameter.
* @return {?}
*/
get paramMap() {
if (!this._paramMap) {
this._paramMap = this.params.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} p
* @return {?}
*/
(p) => convertToParamMap(p))));
}
return this._paramMap;
}
/**
* An Observable that contains a map of the query parameters available to all routes.
* The map supports retrieving single and multiple values from the query parameter.
* @return {?}
*/
get queryParamMap() {
if (!this._queryParamMap) {
this._queryParamMap =
this.queryParams.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} p
* @return {?}
*/
(p) => convertToParamMap(p))));
}
return this._queryParamMap;
}
/**
* @return {?}
*/
toString() {
return this.snapshot ? this.snapshot.toString() : `Future(${this._futureSnapshot})`;
}
}
if (false) {}
/**
* Returns the inherited params, data, and resolve for a given route.
* By default, this only inherits values up to the nearest path-less or component-less route.
* \@internal
* @param {?} route
* @param {?=} paramsInheritanceStrategy
* @return {?}
*/
function inheritedParamsDataResolve(route, paramsInheritanceStrategy = 'emptyOnly') {
/** @type {?} */
const pathFromRoot = route.pathFromRoot;
/** @type {?} */
let inheritingStartingFrom = 0;
if (paramsInheritanceStrategy !== 'always') {
inheritingStartingFrom = pathFromRoot.length - 1;
while (inheritingStartingFrom >= 1) {
/** @type {?} */
const current = pathFromRoot[inheritingStartingFrom];
/** @type {?} */
const parent = pathFromRoot[inheritingStartingFrom - 1];
// current route is an empty path => inherits its parent's params and data
if (current.routeConfig && current.routeConfig.path === '') {
inheritingStartingFrom--;
// parent is componentless => current route should inherit its params and data
}
else if (!parent.component) {
inheritingStartingFrom--;
}
else {
break;
}
}
}
return flattenInherited(pathFromRoot.slice(inheritingStartingFrom));
}
/**
* \@internal
* @param {?} pathFromRoot
* @return {?}
*/
function flattenInherited(pathFromRoot) {
return pathFromRoot.reduce((/**
* @param {?} res
* @param {?} curr
* @return {?}
*/
(res, curr) => {
/** @type {?} */
const params = Object.assign(Object.assign({}, res.params), curr.params);
/** @type {?} */
const data = Object.assign(Object.assign({}, res.data), curr.data);
/** @type {?} */
const resolve = Object.assign(Object.assign({}, res.resolve), curr._resolvedData);
return { params, data, resolve };
}), (/** @type {?} */ ({ params: {}, data: {}, resolve: {} })));
}
/**
* \@description
*
* Contains the information about a route associated with a component loaded in an
* outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to
* traverse the router state tree.
*
* ```
* \@Component({templateUrl:'./my-component.html'})
* class MyComponent {
* constructor(route: ActivatedRoute) {
* const id: string = route.snapshot.params.id;
* const url: string = route.snapshot.url.join('');
* const user = route.snapshot.data.user;
* }
* }
* ```
*
* \@publicApi
*/
class ActivatedRouteSnapshot {
/**
* \@internal
* @param {?} url
* @param {?} params
* @param {?} queryParams
* @param {?} fragment
* @param {?} data
* @param {?} outlet
* @param {?} component
* @param {?} routeConfig
* @param {?} urlSegment
* @param {?} lastPathIndex
* @param {?} resolve
*/
constructor(url, params, queryParams, fragment, data, outlet, component, routeConfig, urlSegment, lastPathIndex, resolve) {
this.url = url;
this.params = params;
this.queryParams = queryParams;
this.fragment = fragment;
this.data = data;
this.outlet = outlet;
this.component = component;
this.routeConfig = routeConfig;
this._urlSegment = urlSegment;
this._lastPathIndex = lastPathIndex;
this._resolve = resolve;
}
/**
* The root of the router state
* @return {?}
*/
get root() {
return this._routerState.root;
}
/**
* The parent of this route in the router state tree
* @return {?}
*/
get parent() {
return this._routerState.parent(this);
}
/**
* The first child of this route in the router state tree
* @return {?}
*/
get firstChild() {
return this._routerState.firstChild(this);
}
/**
* The children of this route in the router state tree
* @return {?}
*/
get children() {
return this._routerState.children(this);
}
/**
* The path from the root of the router state tree to this route
* @return {?}
*/
get pathFromRoot() {
return this._routerState.pathFromRoot(this);
}
/**
* @return {?}
*/
get paramMap() {
if (!this._paramMap) {
this._paramMap = convertToParamMap(this.params);
}
return this._paramMap;
}
/**
* @return {?}
*/
get queryParamMap() {
if (!this._queryParamMap) {
this._queryParamMap = convertToParamMap(this.queryParams);
}
return this._queryParamMap;
}
/**
* @return {?}
*/
toString() {
/** @type {?} */
const url = this.url.map((/**
* @param {?} segment
* @return {?}
*/
segment => segment.toString())).join('/');
/** @type {?} */
const matched = this.routeConfig ? this.routeConfig.path : '';
return `Route(url:'${url}', path:'${matched}')`;
}
}
if (false) {}
/**
* \@description
*
* Represents the state of the router at a moment in time.
*
* This is a tree of activated route snapshots. Every node in this tree knows about
* the "consumed" URL segments, the extracted parameters, and the resolved data.
*
* \@usageNotes
* ### Example
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const state: RouterState = router.routerState;
* const snapshot: RouterStateSnapshot = state.snapshot;
* const root: ActivatedRouteSnapshot = snapshot.root;
* const child = root.firstChild;
* const id: Observable<string> = child.params.map(p => p.id);
* //...
* }
* }
* ```
*
* \@publicApi
*/
class RouterStateSnapshot extends Tree {
/**
* \@internal
* @param {?} url
* @param {?} root
*/
constructor(url, root) {
super(root);
this.url = url;
setRouterState((/** @type {?} */ (this)), root);
}
/**
* @return {?}
*/
toString() {
return serializeNode(this._root);
}
}
if (false) {}
/**
* @template U, T
* @param {?} state
* @param {?} node
* @return {?}
*/
function setRouterState(state, node) {
node.value._routerState = state;
node.children.forEach((/**
* @param {?} c
* @return {?}
*/
c => setRouterState(state, c)));
}
/**
* @param {?} node
* @return {?}
*/
function serializeNode(node) {
/** @type {?} */
const c = node.children.length > 0 ? ` { ${node.children.map(serializeNode).join(', ')} } ` : '';
return `${node.value}${c}`;
}
/**
* The expectation is that the activate route is created with the right set of parameters.
* So we push new values into the observables only when they are not the initial values.
* And we detect that by checking if the snapshot field is set.
* @param {?} route
* @return {?}
*/
function advanceActivatedRoute(route) {
if (route.snapshot) {
/** @type {?} */
const currentSnapshot = route.snapshot;
/** @type {?} */
const nextSnapshot = route._futureSnapshot;
route.snapshot = nextSnapshot;
if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) {
((/** @type {?} */ (route.queryParams))).next(nextSnapshot.queryParams);
}
if (currentSnapshot.fragment !== nextSnapshot.fragment) {
((/** @type {?} */ (route.fragment))).next(nextSnapshot.fragment);
}
if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) {
((/** @type {?} */ (route.params))).next(nextSnapshot.params);
}
if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) {
((/** @type {?} */ (route.url))).next(nextSnapshot.url);
}
if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) {
((/** @type {?} */ (route.data))).next(nextSnapshot.data);
}
}
else {
route.snapshot = route._futureSnapshot;
// this is for resolved data
((/** @type {?} */ (route.data))).next(route._futureSnapshot.data);
}
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function equalParamsAndUrlSegments(a, b) {
/** @type {?} */
const equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url);
/** @type {?} */
const parentsMismatch = !a.parent !== !b.parent;
return equalUrlParams && !parentsMismatch &&
(!a.parent || equalParamsAndUrlSegments(a.parent, (/** @type {?} */ (b.parent))));
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/create_router_state.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} routeReuseStrategy
* @param {?} curr
* @param {?} prevState
* @return {?}
*/
function createRouterState(routeReuseStrategy, curr, prevState) {
/** @type {?} */
const root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined);
return new RouterState(root, curr);
}
/**
* @param {?} routeReuseStrategy
* @param {?} curr
* @param {?=} prevState
* @return {?}
*/
function createNode(routeReuseStrategy, curr, prevState) {
// reuse an activated route that is currently displayed on the screen
if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) {
/** @type {?} */
const value = prevState.value;
value._futureSnapshot = curr.value;
/** @type {?} */
const children = createOrReuseChildren(routeReuseStrategy, curr, prevState);
return new TreeNode(value, children);
// retrieve an activated route that is used to be displayed, but is not currently displayed
}
else {
/** @type {?} */
const detachedRouteHandle = (/** @type {?} */ (routeReuseStrategy.retrieve(curr.value)));
if (detachedRouteHandle) {
/** @type {?} */
const tree = detachedRouteHandle.route;
setFutureSnapshotsOfActivatedRoutes(curr, tree);
return tree;
}
else {
/** @type {?} */
const value = createActivatedRoute(curr.value);
/** @type {?} */
const children = curr.children.map((/**
* @param {?} c
* @return {?}
*/
c => createNode(routeReuseStrategy, c)));
return new TreeNode(value, children);
}
}
}
/**
* @param {?} curr
* @param {?} result
* @return {?}
*/
function setFutureSnapshotsOfActivatedRoutes(curr, result) {
if (curr.value.routeConfig !== result.value.routeConfig) {
throw new Error('Cannot reattach ActivatedRouteSnapshot created from a different route');
}
if (curr.children.length !== result.children.length) {
throw new Error('Cannot reattach ActivatedRouteSnapshot with a different number of children');
}
result.value._futureSnapshot = curr.value;
for (let i = 0; i < curr.children.length; ++i) {
setFutureSnapshotsOfActivatedRoutes(curr.children[i], result.children[i]);
}
}
/**
* @param {?} routeReuseStrategy
* @param {?} curr
* @param {?} prevState
* @return {?}
*/
function createOrReuseChildren(routeReuseStrategy, curr, prevState) {
return curr.children.map((/**
* @param {?} child
* @return {?}
*/
child => {
for (const p of prevState.children) {
if (routeReuseStrategy.shouldReuseRoute(p.value.snapshot, child.value)) {
return createNode(routeReuseStrategy, child, p);
}
}
return createNode(routeReuseStrategy, child);
}));
}
/**
* @param {?} c
* @return {?}
*/
function createActivatedRoute(c) {
return new ActivatedRoute(new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"](c.url), new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"](c.params), new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"](c.queryParams), new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"](c.fragment), new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"](c.data), c.outlet, c.component, c);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/create_url_tree.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} route
* @param {?} urlTree
* @param {?} commands
* @param {?} queryParams
* @param {?} fragment
* @return {?}
*/
function createUrlTree(route, urlTree, commands, queryParams, fragment) {
if (commands.length === 0) {
return tree(urlTree.root, urlTree.root, urlTree, queryParams, fragment);
}
/** @type {?} */
const nav = computeNavigation(commands);
if (nav.toRoot()) {
return tree(urlTree.root, new UrlSegmentGroup([], {}), urlTree, queryParams, fragment);
}
/** @type {?} */
const startingPosition = findStartingPosition(nav, urlTree, route);
/** @type {?} */
const segmentGroup = startingPosition.processChildren ?
updateSegmentGroupChildren(startingPosition.segmentGroup, startingPosition.index, nav.commands) :
updateSegmentGroup(startingPosition.segmentGroup, startingPosition.index, nav.commands);
return tree(startingPosition.segmentGroup, segmentGroup, urlTree, queryParams, fragment);
}
/**
* @param {?} command
* @return {?}
*/
function isMatrixParams(command) {
return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath;
}
/**
* @param {?} oldSegmentGroup
* @param {?} newSegmentGroup
* @param {?} urlTree
* @param {?} queryParams
* @param {?} fragment
* @return {?}
*/
function tree(oldSegmentGroup, newSegmentGroup, urlTree, queryParams, fragment) {
/** @type {?} */
let qp = {};
if (queryParams) {
forEach(queryParams, (/**
* @param {?} value
* @param {?} name
* @return {?}
*/
(value, name) => {
qp[name] = Array.isArray(value) ? value.map((/**
* @param {?} v
* @return {?}
*/
(v) => `${v}`)) : `${value}`;
}));
}
if (urlTree.root === oldSegmentGroup) {
return new UrlTree(newSegmentGroup, qp, fragment);
}
return new UrlTree(replaceSegment(urlTree.root, oldSegmentGroup, newSegmentGroup), qp, fragment);
}
/**
* @param {?} current
* @param {?} oldSegment
* @param {?} newSegment
* @return {?}
*/
function replaceSegment(current, oldSegment, newSegment) {
/** @type {?} */
const children = {};
forEach(current.children, (/**
* @param {?} c
* @param {?} outletName
* @return {?}
*/
(c, outletName) => {
if (c === oldSegment) {
children[outletName] = newSegment;
}
else {
children[outletName] = replaceSegment(c, oldSegment, newSegment);
}
}));
return new UrlSegmentGroup(current.segments, children);
}
class Navigation {
/**
* @param {?} isAbsolute
* @param {?} numberOfDoubleDots
* @param {?} commands
*/
constructor(isAbsolute, numberOfDoubleDots, commands) {
this.isAbsolute = isAbsolute;
this.numberOfDoubleDots = numberOfDoubleDots;
this.commands = commands;
if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) {
throw new Error('Root segment cannot have matrix parameters');
}
/** @type {?} */
const cmdWithOutlet = commands.find((/**
* @param {?} c
* @return {?}
*/
c => typeof c === 'object' && c != null && c.outlets));
if (cmdWithOutlet && cmdWithOutlet !== last(commands)) {
throw new Error('{outlets:{}} has to be the last command');
}
}
/**
* @return {?}
*/
toRoot() {
return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/';
}
}
if (false) {}
/**
* Transforms commands to a normalized `Navigation`
* @param {?} commands
* @return {?}
*/
function computeNavigation(commands) {
if ((typeof commands[0] === 'string') && commands.length === 1 && commands[0] === '/') {
return new Navigation(true, 0, commands);
}
/** @type {?} */
let numberOfDoubleDots = 0;
/** @type {?} */
let isAbsolute = false;
/** @type {?} */
const res = commands.reduce((/**
* @param {?} res
* @param {?} cmd
* @param {?} cmdIdx
* @return {?}
*/
(res, cmd, cmdIdx) => {
if (typeof cmd === 'object' && cmd != null) {
if (cmd.outlets) {
/** @type {?} */
const outlets = {};
forEach(cmd.outlets, (/**
* @param {?} commands
* @param {?} name
* @return {?}
*/
(commands, name) => {
outlets[name] = typeof commands === 'string' ? commands.split('/') : commands;
}));
return [...res, { outlets }];
}
if (cmd.segmentPath) {
return [...res, cmd.segmentPath];
}
}
if (!(typeof cmd === 'string')) {
return [...res, cmd];
}
if (cmdIdx === 0) {
cmd.split('/').forEach((/**
* @param {?} urlPart
* @param {?} partIndex
* @return {?}
*/
(urlPart, partIndex) => {
if (partIndex == 0 && urlPart === '.') {
// skip './a'
}
else if (partIndex == 0 && urlPart === '') { // '/a'
isAbsolute = true;
}
else if (urlPart === '..') { // '../a'
numberOfDoubleDots++;
}
else if (urlPart != '') {
res.push(urlPart);
}
}));
return res;
}
return [...res, cmd];
}), []);
return new Navigation(isAbsolute, numberOfDoubleDots, res);
}
class Position {
/**
* @param {?} segmentGroup
* @param {?} processChildren
* @param {?} index
*/
constructor(segmentGroup, processChildren, index) {
this.segmentGroup = segmentGroup;
this.processChildren = processChildren;
this.index = index;
}
}
if (false) {}
/**
* @param {?} nav
* @param {?} tree
* @param {?} route
* @return {?}
*/
function findStartingPosition(nav, tree, route) {
if (nav.isAbsolute) {
return new Position(tree.root, true, 0);
}
if (route.snapshot._lastPathIndex === -1) {
return new Position(route.snapshot._urlSegment, true, 0);
}
/** @type {?} */
const modifier = isMatrixParams(nav.commands[0]) ? 0 : 1;
/** @type {?} */
const index = route.snapshot._lastPathIndex + modifier;
return createPositionApplyingDoubleDots(route.snapshot._urlSegment, index, nav.numberOfDoubleDots);
}
/**
* @param {?} group
* @param {?} index
* @param {?} numberOfDoubleDots
* @return {?}
*/
function createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) {
/** @type {?} */
let g = group;
/** @type {?} */
let ci = index;
/** @type {?} */
let dd = numberOfDoubleDots;
while (dd > ci) {
dd -= ci;
g = (/** @type {?} */ (g.parent));
if (!g) {
throw new Error('Invalid number of \'../\'');
}
ci = g.segments.length;
}
return new Position(g, false, ci - dd);
}
/**
* @param {?} command
* @return {?}
*/
function getPath(command) {
if (typeof command === 'object' && command != null && command.outlets) {
return command.outlets[PRIMARY_OUTLET];
}
return `${command}`;
}
/**
* @param {?} commands
* @return {?}
*/
function getOutlets(commands) {
if (!(typeof commands[0] === 'object'))
return { [PRIMARY_OUTLET]: commands };
if (commands[0].outlets === undefined)
return { [PRIMARY_OUTLET]: commands };
return commands[0].outlets;
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function updateSegmentGroup(segmentGroup, startIndex, commands) {
if (!segmentGroup) {
segmentGroup = new UrlSegmentGroup([], {});
}
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return updateSegmentGroupChildren(segmentGroup, startIndex, commands);
}
/** @type {?} */
const m = prefixedWith(segmentGroup, startIndex, commands);
/** @type {?} */
const slicedCommands = commands.slice(m.commandIndex);
if (m.match && m.pathIndex < segmentGroup.segments.length) {
/** @type {?} */
const g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {});
g.children[PRIMARY_OUTLET] =
new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children);
return updateSegmentGroupChildren(g, 0, slicedCommands);
}
else if (m.match && slicedCommands.length === 0) {
return new UrlSegmentGroup(segmentGroup.segments, {});
}
else if (m.match && !segmentGroup.hasChildren()) {
return createNewSegmentGroup(segmentGroup, startIndex, commands);
}
else if (m.match) {
return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands);
}
else {
return createNewSegmentGroup(segmentGroup, startIndex, commands);
}
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function updateSegmentGroupChildren(segmentGroup, startIndex, commands) {
if (commands.length === 0) {
return new UrlSegmentGroup(segmentGroup.segments, {});
}
else {
/** @type {?} */
const outlets = getOutlets(commands);
/** @type {?} */
const children = {};
forEach(outlets, (/**
* @param {?} commands
* @param {?} outlet
* @return {?}
*/
(commands, outlet) => {
if (commands !== null) {
children[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands);
}
}));
forEach(segmentGroup.children, (/**
* @param {?} child
* @param {?} childOutlet
* @return {?}
*/
(child, childOutlet) => {
if (outlets[childOutlet] === undefined) {
children[childOutlet] = child;
}
}));
return new UrlSegmentGroup(segmentGroup.segments, children);
}
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function prefixedWith(segmentGroup, startIndex, commands) {
/** @type {?} */
let currentCommandIndex = 0;
/** @type {?} */
let currentPathIndex = startIndex;
/** @type {?} */
const noMatch = { match: false, pathIndex: 0, commandIndex: 0 };
while (currentPathIndex < segmentGroup.segments.length) {
if (currentCommandIndex >= commands.length)
return noMatch;
/** @type {?} */
const path = segmentGroup.segments[currentPathIndex];
/** @type {?} */
const curr = getPath(commands[currentCommandIndex]);
/** @type {?} */
const next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;
if (currentPathIndex > 0 && curr === undefined)
break;
if (curr && next && (typeof next === 'object') && next.outlets === undefined) {
if (!compare(curr, next, path))
return noMatch;
currentCommandIndex += 2;
}
else {
if (!compare(curr, {}, path))
return noMatch;
currentCommandIndex++;
}
currentPathIndex++;
}
return { match: true, pathIndex: currentPathIndex, commandIndex: currentCommandIndex };
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function createNewSegmentGroup(segmentGroup, startIndex, commands) {
/** @type {?} */
const paths = segmentGroup.segments.slice(0, startIndex);
/** @type {?} */
let i = 0;
while (i < commands.length) {
if (typeof commands[i] === 'object' && commands[i].outlets !== undefined) {
/** @type {?} */
const children = createNewSegmentChildren(commands[i].outlets);
return new UrlSegmentGroup(paths, children);
}
// if we start with an object literal, we need to reuse the path part from the segment
if (i === 0 && isMatrixParams(commands[0])) {
/** @type {?} */
const p = segmentGroup.segments[startIndex];
paths.push(new UrlSegment(p.path, commands[0]));
i++;
continue;
}
/** @type {?} */
const curr = getPath(commands[i]);
/** @type {?} */
const next = (i < commands.length - 1) ? commands[i + 1] : null;
if (curr && next && isMatrixParams(next)) {
paths.push(new UrlSegment(curr, stringify(next)));
i += 2;
}
else {
paths.push(new UrlSegment(curr, {}));
i++;
}
}
return new UrlSegmentGroup(paths, {});
}
/**
* @param {?} outlets
* @return {?}
*/
function createNewSegmentChildren(outlets) {
/** @type {?} */
const children = {};
forEach(outlets, (/**
* @param {?} commands
* @param {?} outlet
* @return {?}
*/
(commands, outlet) => {
if (commands !== null) {
children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands);
}
}));
return children;
}
/**
* @param {?} params
* @return {?}
*/
function stringify(params) {
/** @type {?} */
const res = {};
forEach(params, (/**
* @param {?} v
* @param {?} k
* @return {?}
*/
(v, k) => res[k] = `${v}`));
return res;
}
/**
* @param {?} path
* @param {?} params
* @param {?} segment
* @return {?}
*/
function compare(path, params, segment) {
return path == segment.path && shallowEqual(params, segment.parameters);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/operators/activate_routes.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const activateRoutes = (/**
* @param {?} rootContexts
* @param {?} routeReuseStrategy
* @param {?} forwardEvent
* @return {?}
*/
(rootContexts, routeReuseStrategy, forwardEvent) => Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} t
* @return {?}
*/
t => {
new ActivateRoutes(routeReuseStrategy, (/** @type {?} */ (t.targetRouterState)), t.currentRouterState, forwardEvent)
.activate(rootContexts);
return t;
})));
class ActivateRoutes {
/**
* @param {?} routeReuseStrategy
* @param {?} futureState
* @param {?} currState
* @param {?} forwardEvent
*/
constructor(routeReuseStrategy, futureState, currState, forwardEvent) {
this.routeReuseStrategy = routeReuseStrategy;
this.futureState = futureState;
this.currState = currState;
this.forwardEvent = forwardEvent;
}
/**
* @param {?} parentContexts
* @return {?}
*/
activate(parentContexts) {
/** @type {?} */
const futureRoot = this.futureState._root;
/** @type {?} */
const currRoot = this.currState ? this.currState._root : null;
this.deactivateChildRoutes(futureRoot, currRoot, parentContexts);
advanceActivatedRoute(this.futureState.root);
this.activateChildRoutes(futureRoot, currRoot, parentContexts);
}
// De-activate the child route that are not re-used for the future state
/**
* @private
* @param {?} futureNode
* @param {?} currNode
* @param {?} contexts
* @return {?}
*/
deactivateChildRoutes(futureNode, currNode, contexts) {
/** @type {?} */
const children = nodeChildrenAsMap(currNode);
// Recurse on the routes active in the future state to de-activate deeper children
futureNode.children.forEach((/**
* @param {?} futureChild
* @return {?}
*/
futureChild => {
/** @type {?} */
const childOutletName = futureChild.value.outlet;
this.deactivateRoutes(futureChild, children[childOutletName], contexts);
delete children[childOutletName];
}));
// De-activate the routes that will not be re-used
forEach(children, (/**
* @param {?} v
* @param {?} childName
* @return {?}
*/
(v, childName) => {
this.deactivateRouteAndItsChildren(v, contexts);
}));
}
/**
* @private
* @param {?} futureNode
* @param {?} currNode
* @param {?} parentContext
* @return {?}
*/
deactivateRoutes(futureNode, currNode, parentContext) {
/** @type {?} */
const future = futureNode.value;
/** @type {?} */
const curr = currNode ? currNode.value : null;
if (future === curr) {
// Reusing the node, check to see if the children need to be de-activated
if (future.component) {
// If we have a normal route, we need to go through an outlet.
/** @type {?} */
const context = parentContext.getContext(future.outlet);
if (context) {
this.deactivateChildRoutes(futureNode, currNode, context.children);
}
}
else {
// if we have a componentless route, we recurse but keep the same outlet map.
this.deactivateChildRoutes(futureNode, currNode, parentContext);
}
}
else {
if (curr) {
// Deactivate the current route which will not be re-used
this.deactivateRouteAndItsChildren(currNode, parentContext);
}
}
}
/**
* @private
* @param {?} route
* @param {?} parentContexts
* @return {?}
*/
deactivateRouteAndItsChildren(route, parentContexts) {
if (this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {
this.detachAndStoreRouteSubtree(route, parentContexts);
}
else {
this.deactivateRouteAndOutlet(route, parentContexts);
}
}
/**
* @private
* @param {?} route
* @param {?} parentContexts
* @return {?}
*/
detachAndStoreRouteSubtree(route, parentContexts) {
/** @type {?} */
const context = parentContexts.getContext(route.value.outlet);
if (context && context.outlet) {
/** @type {?} */
const componentRef = context.outlet.detach();
/** @type {?} */
const contexts = context.children.onOutletDeactivated();
this.routeReuseStrategy.store(route.value.snapshot, { componentRef, route, contexts });
}
}
/**
* @private
* @param {?} route
* @param {?} parentContexts
* @return {?}
*/
deactivateRouteAndOutlet(route, parentContexts) {
/** @type {?} */
const context = parentContexts.getContext(route.value.outlet);
if (context) {
/** @type {?} */
const children = nodeChildrenAsMap(route);
/** @type {?} */
const contexts = route.value.component ? context.children : parentContexts;
forEach(children, (/**
* @param {?} v
* @param {?} k
* @return {?}
*/
(v, k) => this.deactivateRouteAndItsChildren(v, contexts)));
if (context.outlet) {
// Destroy the component
context.outlet.deactivate();
// Destroy the contexts for all the outlets that were in the component
context.children.onOutletDeactivated();
}
}
}
/**
* @private
* @param {?} futureNode
* @param {?} currNode
* @param {?} contexts
* @return {?}
*/
activateChildRoutes(futureNode, currNode, contexts) {
/** @type {?} */
const children = nodeChildrenAsMap(currNode);
futureNode.children.forEach((/**
* @param {?} c
* @return {?}
*/
c => {
this.activateRoutes(c, children[c.value.outlet], contexts);
this.forwardEvent(new ActivationEnd(c.value.snapshot));
}));
if (futureNode.children.length) {
this.forwardEvent(new ChildActivationEnd(futureNode.value.snapshot));
}
}
/**
* @private
* @param {?} futureNode
* @param {?} currNode
* @param {?} parentContexts
* @return {?}
*/
activateRoutes(futureNode, currNode, parentContexts) {
/** @type {?} */
const future = futureNode.value;
/** @type {?} */
const curr = currNode ? currNode.value : null;
advanceActivatedRoute(future);
// reusing the node
if (future === curr) {
if (future.component) {
// If we have a normal route, we need to go through an outlet.
/** @type {?} */
const context = parentContexts.getOrCreateContext(future.outlet);
this.activateChildRoutes(futureNode, currNode, context.children);
}
else {
// if we have a componentless route, we recurse but keep the same outlet map.
this.activateChildRoutes(futureNode, currNode, parentContexts);
}
}
else {
if (future.component) {
// if we have a normal route, we need to place the component into the outlet and recurse.
/** @type {?} */
const context = parentContexts.getOrCreateContext(future.outlet);
if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {
/** @type {?} */
const stored = ((/** @type {?} */ (this.routeReuseStrategy.retrieve(future.snapshot))));
this.routeReuseStrategy.store(future.snapshot, null);
context.children.onOutletReAttached(stored.contexts);
context.attachRef = stored.componentRef;
context.route = stored.route.value;
if (context.outlet) {
// Attach right away when the outlet has already been instantiated
// Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated
context.outlet.attach(stored.componentRef, stored.route.value);
}
advanceActivatedRouteNodeAndItsChildren(stored.route);
}
else {
/** @type {?} */
const config = parentLoadedConfig(future.snapshot);
/** @type {?} */
const cmpFactoryResolver = config ? config.module.componentFactoryResolver : null;
context.attachRef = null;
context.route = future;
context.resolver = cmpFactoryResolver;
if (context.outlet) {
// Activate the outlet when it has already been instantiated
// Otherwise it will get activated from its `ngOnInit` when instantiated
context.outlet.activateWith(future, cmpFactoryResolver);
}
this.activateChildRoutes(futureNode, null, context.children);
}
}
else {
// if we have a componentless route, we recurse but keep the same outlet map.
this.activateChildRoutes(futureNode, null, parentContexts);
}
}
}
}
if (false) {}
/**
* @param {?} node
* @return {?}
*/
function advanceActivatedRouteNodeAndItsChildren(node) {
advanceActivatedRoute(node.value);
node.children.forEach(advanceActivatedRouteNodeAndItsChildren);
}
/**
* @param {?} snapshot
* @return {?}
*/
function parentLoadedConfig(snapshot) {
for (let s = snapshot.parent; s; s = s.parent) {
/** @type {?} */
const route = s.routeConfig;
if (route && route._loadedConfig)
return route._loadedConfig;
if (route && route.component)
return null;
}
return null;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/utils/type_guards.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Simple function check, but generic so type inference will flow. Example:
*
* function product(a: number, b: number) {
* return a * b;
* }
*
* if (isFunction<product>(fn)) {
* return fn(1, 2);
* } else {
* throw "Must provide the `product` function";
* }
* @template T
* @param {?} v
* @return {?}
*/
function isFunction(v) {
return typeof v === 'function';
}
/**
* @param {?} v
* @return {?}
*/
function isBoolean(v) {
return typeof v === 'boolean';
}
/**
* @param {?} v
* @return {?}
*/
function isUrlTree(v) {
return v instanceof UrlTree;
}
/**
* @param {?} guard
* @return {?}
*/
function isCanLoad(guard) {
return guard && isFunction(guard.canLoad);
}
/**
* @param {?} guard
* @return {?}
*/
function isCanActivate(guard) {
return guard && isFunction(guard.canActivate);
}
/**
* @param {?} guard
* @return {?}
*/
function isCanActivateChild(guard) {
return guard && isFunction(guard.canActivateChild);
}
/**
* @template T
* @param {?} guard
* @return {?}
*/
function isCanDeactivate(guard) {
return guard && isFunction(guard.canDeactivate);
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/apply_redirects.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class NoMatch {
/**
* @param {?=} segmentGroup
*/
constructor(segmentGroup) {
this.segmentGroup = segmentGroup || null;
}
}
if (false) {}
class AbsoluteRedirect {
/**
* @param {?} urlTree
*/
constructor(urlTree) {
this.urlTree = urlTree;
}
}
if (false) {}
/**
* @param {?} segmentGroup
* @return {?}
*/
function noMatch(segmentGroup) {
return new rxjs__WEBPACK_IMPORTED_MODULE_2__["Observable"]((/**
* @param {?} obs
* @return {?}
*/
(obs) => obs.error(new NoMatch(segmentGroup))));
}
/**
* @param {?} newTree
* @return {?}
*/
function absoluteRedirect(newTree) {
return new rxjs__WEBPACK_IMPORTED_MODULE_2__["Observable"]((/**
* @param {?} obs
* @return {?}
*/
(obs) => obs.error(new AbsoluteRedirect(newTree))));
}
/**
* @param {?} redirectTo
* @return {?}
*/
function namedOutletsRedirect(redirectTo) {
return new rxjs__WEBPACK_IMPORTED_MODULE_2__["Observable"]((/**
* @param {?} obs
* @return {?}
*/
(obs) => obs.error(new Error(`Only absolute redirects can have named outlets. redirectTo: '${redirectTo}'`))));
}
/**
* @param {?} route
* @return {?}
*/
function canLoadFails(route) {
return new rxjs__WEBPACK_IMPORTED_MODULE_2__["Observable"]((/**
* @param {?} obs
* @return {?}
*/
(obs) => obs.error(navigationCancelingError(`Cannot load children because the guard of the route "path: '${route.path}'" returned false`))));
}
/**
* Returns the `UrlTree` with the redirection applied.
*
* Lazy modules are loaded along the way.
* @param {?} moduleInjector
* @param {?} configLoader
* @param {?} urlSerializer
* @param {?} urlTree
* @param {?} config
* @return {?}
*/
function applyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) {
return new ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config).apply();
}
class ApplyRedirects {
/**
* @param {?} moduleInjector
* @param {?} configLoader
* @param {?} urlSerializer
* @param {?} urlTree
* @param {?} config
*/
constructor(moduleInjector, configLoader, urlSerializer, urlTree, config) {
this.configLoader = configLoader;
this.urlSerializer = urlSerializer;
this.urlTree = urlTree;
this.config = config;
this.allowRedirects = true;
this.ngModule = moduleInjector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModuleRef"]);
}
/**
* @return {?}
*/
apply() {
/** @type {?} */
const expanded$ = this.expandSegmentGroup(this.ngModule, this.config, this.urlTree.root, PRIMARY_OUTLET);
/** @type {?} */
const urlTrees$ = expanded$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} rootSegmentGroup
* @return {?}
*/
(rootSegmentGroup) => this.createUrlTree(rootSegmentGroup, this.urlTree.queryParams, (/** @type {?} */ (this.urlTree.fragment))))));
return urlTrees$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["catchError"])((/**
* @param {?} e
* @return {?}
*/
(e) => {
if (e instanceof AbsoluteRedirect) {
// after an absolute redirect we do not apply any more redirects!
this.allowRedirects = false;
// we need to run matching, so we can fetch all lazy-loaded modules
return this.match(e.urlTree);
}
if (e instanceof NoMatch) {
throw this.noMatchError(e);
}
throw e;
})));
}
/**
* @private
* @param {?} tree
* @return {?}
*/
match(tree) {
/** @type {?} */
const expanded$ = this.expandSegmentGroup(this.ngModule, this.config, tree.root, PRIMARY_OUTLET);
/** @type {?} */
const mapped$ = expanded$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} rootSegmentGroup
* @return {?}
*/
(rootSegmentGroup) => this.createUrlTree(rootSegmentGroup, tree.queryParams, (/** @type {?} */ (tree.fragment))))));
return mapped$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["catchError"])((/**
* @param {?} e
* @return {?}
*/
(e) => {
if (e instanceof NoMatch) {
throw this.noMatchError(e);
}
throw e;
})));
}
/**
* @private
* @param {?} e
* @return {?}
*/
noMatchError(e) {
return new Error(`Cannot match any routes. URL Segment: '${e.segmentGroup}'`);
}
/**
* @private
* @param {?} rootCandidate
* @param {?} queryParams
* @param {?} fragment
* @return {?}
*/
createUrlTree(rootCandidate, queryParams, fragment) {
/** @type {?} */
const root = rootCandidate.segments.length > 0 ?
new UrlSegmentGroup([], { [PRIMARY_OUTLET]: rootCandidate }) :
rootCandidate;
return new UrlTree(root, queryParams, fragment);
}
/**
* @private
* @param {?} ngModule
* @param {?} routes
* @param {?} segmentGroup
* @param {?} outlet
* @return {?}
*/
expandSegmentGroup(ngModule, routes, segmentGroup, outlet) {
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return this.expandChildren(ngModule, routes, segmentGroup)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} children
* @return {?}
*/
(children) => new UrlSegmentGroup([], children))));
}
return this.expandSegment(ngModule, segmentGroup, routes, segmentGroup.segments, outlet, true);
}
// Recursively expand segment groups for all the child outlets
/**
* @private
* @param {?} ngModule
* @param {?} routes
* @param {?} segmentGroup
* @return {?}
*/
expandChildren(ngModule, routes, segmentGroup) {
return waitForMap(segmentGroup.children, (/**
* @param {?} childOutlet
* @param {?} child
* @return {?}
*/
(childOutlet, child) => this.expandSegmentGroup(ngModule, routes, child, childOutlet)));
}
/**
* @private
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} segments
* @param {?} outlet
* @param {?} allowRedirects
* @return {?}
*/
expandSegment(ngModule, segmentGroup, routes, segments, outlet, allowRedirects) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(...routes).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} r
* @return {?}
*/
(r) => {
/** @type {?} */
const expanded$ = this.expandSegmentAgainstRoute(ngModule, segmentGroup, routes, r, segments, outlet, allowRedirects);
return expanded$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["catchError"])((/**
* @param {?} e
* @return {?}
*/
(e) => {
if (e instanceof NoMatch) {
// TODO(i): this return type doesn't match the declared Observable<UrlSegmentGroup> -
// talk to Jason
return (/** @type {?} */ (Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(null)));
}
throw e;
})));
})), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["concatAll"])(), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["first"])((/**
* @param {?} s
* @return {?}
*/
(s) => !!s)), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["catchError"])((/**
* @param {?} e
* @param {?} _
* @return {?}
*/
(e, _) => {
if (e instanceof rxjs__WEBPACK_IMPORTED_MODULE_2__["EmptyError"] || e.name === 'EmptyError') {
if (this.noLeftoversInUrl(segmentGroup, segments, outlet)) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(new UrlSegmentGroup([], {}));
}
throw new NoMatch(segmentGroup);
}
throw e;
})));
}
/**
* @private
* @param {?} segmentGroup
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
noLeftoversInUrl(segmentGroup, segments, outlet) {
return segments.length === 0 && !segmentGroup.children[outlet];
}
/**
* @private
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} route
* @param {?} paths
* @param {?} outlet
* @param {?} allowRedirects
* @return {?}
*/
expandSegmentAgainstRoute(ngModule, segmentGroup, routes, route, paths, outlet, allowRedirects) {
if (getOutlet(route) !== outlet) {
return noMatch(segmentGroup);
}
if (route.redirectTo === undefined) {
return this.matchSegmentAgainstRoute(ngModule, segmentGroup, route, paths);
}
if (allowRedirects && this.allowRedirects) {
return this.expandSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, paths, outlet);
}
return noMatch(segmentGroup);
}
/**
* @private
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} route
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
expandSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet) {
if (route.path === '**') {
return this.expandWildCardWithParamsAgainstRouteUsingRedirect(ngModule, routes, route, outlet);
}
return this.expandRegularSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet);
}
/**
* @private
* @param {?} ngModule
* @param {?} routes
* @param {?} route
* @param {?} outlet
* @return {?}
*/
expandWildCardWithParamsAgainstRouteUsingRedirect(ngModule, routes, route, outlet) {
/** @type {?} */
const newTree = this.applyRedirectCommands([], (/** @type {?} */ (route.redirectTo)), {});
if ((/** @type {?} */ (route.redirectTo)).startsWith('/')) {
return absoluteRedirect(newTree);
}
return this.lineralizeSegments(route, newTree).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} newSegments
* @return {?}
*/
(newSegments) => {
/** @type {?} */
const group = new UrlSegmentGroup(newSegments, {});
return this.expandSegment(ngModule, group, routes, newSegments, outlet, false);
})));
}
/**
* @private
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} route
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
expandRegularSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet) {
const { matched, consumedSegments, lastChild, positionalParamSegments } = match(segmentGroup, route, segments);
if (!matched)
return noMatch(segmentGroup);
/** @type {?} */
const newTree = this.applyRedirectCommands(consumedSegments, (/** @type {?} */ (route.redirectTo)), (/** @type {?} */ (positionalParamSegments)));
if ((/** @type {?} */ (route.redirectTo)).startsWith('/')) {
return absoluteRedirect(newTree);
}
return this.lineralizeSegments(route, newTree).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} newSegments
* @return {?}
*/
(newSegments) => {
return this.expandSegment(ngModule, segmentGroup, routes, newSegments.concat(segments.slice(lastChild)), outlet, false);
})));
}
/**
* @private
* @param {?} ngModule
* @param {?} rawSegmentGroup
* @param {?} route
* @param {?} segments
* @return {?}
*/
matchSegmentAgainstRoute(ngModule, rawSegmentGroup, route, segments) {
if (route.path === '**') {
if (route.loadChildren) {
return this.configLoader.load(ngModule.injector, route)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} cfg
* @return {?}
*/
(cfg) => {
route._loadedConfig = cfg;
return new UrlSegmentGroup(segments, {});
})));
}
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(new UrlSegmentGroup(segments, {}));
}
const { matched, consumedSegments, lastChild } = match(rawSegmentGroup, route, segments);
if (!matched)
return noMatch(rawSegmentGroup);
/** @type {?} */
const rawSlicedSegments = segments.slice(lastChild);
/** @type {?} */
const childConfig$ = this.getChildConfig(ngModule, route, segments);
return childConfig$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} routerConfig
* @return {?}
*/
(routerConfig) => {
/** @type {?} */
const childModule = routerConfig.module;
/** @type {?} */
const childConfig = routerConfig.routes;
const { segmentGroup, slicedSegments } = split(rawSegmentGroup, consumedSegments, rawSlicedSegments, childConfig);
if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
/** @type {?} */
const expanded$ = this.expandChildren(childModule, childConfig, segmentGroup);
return expanded$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} children
* @return {?}
*/
(children) => new UrlSegmentGroup(consumedSegments, children))));
}
if (childConfig.length === 0 && slicedSegments.length === 0) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(new UrlSegmentGroup(consumedSegments, {}));
}
/** @type {?} */
const expanded$ = this.expandSegment(childModule, segmentGroup, childConfig, slicedSegments, PRIMARY_OUTLET, true);
return expanded$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} cs
* @return {?}
*/
(cs) => new UrlSegmentGroup(consumedSegments.concat(cs.segments), cs.children))));
})));
}
/**
* @private
* @param {?} ngModule
* @param {?} route
* @param {?} segments
* @return {?}
*/
getChildConfig(ngModule, route, segments) {
if (route.children) {
// The children belong to the same module
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(new LoadedRouterConfig(route.children, ngModule));
}
if (route.loadChildren) {
// lazy children belong to the loaded module
if (route._loadedConfig !== undefined) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(route._loadedConfig);
}
return runCanLoadGuard(ngModule.injector, route, segments)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} shouldLoad
* @return {?}
*/
(shouldLoad) => {
if (shouldLoad) {
return this.configLoader.load(ngModule.injector, route)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} cfg
* @return {?}
*/
(cfg) => {
route._loadedConfig = cfg;
return cfg;
})));
}
return canLoadFails(route);
})));
}
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(new LoadedRouterConfig([], ngModule));
}
/**
* @private
* @param {?} route
* @param {?} urlTree
* @return {?}
*/
lineralizeSegments(route, urlTree) {
/** @type {?} */
let res = [];
/** @type {?} */
let c = urlTree.root;
while (true) {
res = res.concat(c.segments);
if (c.numberOfChildren === 0) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(res);
}
if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) {
return namedOutletsRedirect((/** @type {?} */ (route.redirectTo)));
}
c = c.children[PRIMARY_OUTLET];
}
}
/**
* @private
* @param {?} segments
* @param {?} redirectTo
* @param {?} posParams
* @return {?}
*/
applyRedirectCommands(segments, redirectTo, posParams) {
return this.applyRedirectCreatreUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);
}
/**
* @private
* @param {?} redirectTo
* @param {?} urlTree
* @param {?} segments
* @param {?} posParams
* @return {?}
*/
applyRedirectCreatreUrlTree(redirectTo, urlTree, segments, posParams) {
/** @type {?} */
const newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);
return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment);
}
/**
* @private
* @param {?} redirectToParams
* @param {?} actualParams
* @return {?}
*/
createQueryParams(redirectToParams, actualParams) {
/** @type {?} */
const res = {};
forEach(redirectToParams, (/**
* @param {?} v
* @param {?} k
* @return {?}
*/
(v, k) => {
/** @type {?} */
const copySourceValue = typeof v === 'string' && v.startsWith(':');
if (copySourceValue) {
/** @type {?} */
const sourceName = v.substring(1);
res[k] = actualParams[sourceName];
}
else {
res[k] = v;
}
}));
return res;
}
/**
* @private
* @param {?} redirectTo
* @param {?} group
* @param {?} segments
* @param {?} posParams
* @return {?}
*/
createSegmentGroup(redirectTo, group, segments, posParams) {
/** @type {?} */
const updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);
/** @type {?} */
let children = {};
forEach(group.children, (/**
* @param {?} child
* @param {?} name
* @return {?}
*/
(child, name) => {
children[name] = this.createSegmentGroup(redirectTo, child, segments, posParams);
}));
return new UrlSegmentGroup(updatedSegments, children);
}
/**
* @private
* @param {?} redirectTo
* @param {?} redirectToSegments
* @param {?} actualSegments
* @param {?} posParams
* @return {?}
*/
createSegments(redirectTo, redirectToSegments, actualSegments, posParams) {
return redirectToSegments.map((/**
* @param {?} s
* @return {?}
*/
s => s.path.startsWith(':') ? this.findPosParam(redirectTo, s, posParams) :
this.findOrReturn(s, actualSegments)));
}
/**
* @private
* @param {?} redirectTo
* @param {?} redirectToUrlSegment
* @param {?} posParams
* @return {?}
*/
findPosParam(redirectTo, redirectToUrlSegment, posParams) {
/** @type {?} */
const pos = posParams[redirectToUrlSegment.path.substring(1)];
if (!pos)
throw new Error(`Cannot redirect to '${redirectTo}'. Cannot find '${redirectToUrlSegment.path}'.`);
return pos;
}
/**
* @private
* @param {?} redirectToUrlSegment
* @param {?} actualSegments
* @return {?}
*/
findOrReturn(redirectToUrlSegment, actualSegments) {
/** @type {?} */
let idx = 0;
for (const s of actualSegments) {
if (s.path === redirectToUrlSegment.path) {
actualSegments.splice(idx);
return s;
}
idx++;
}
return redirectToUrlSegment;
}
}
if (false) {}
/**
* @param {?} moduleInjector
* @param {?} route
* @param {?} segments
* @return {?}
*/
function runCanLoadGuard(moduleInjector, route, segments) {
/** @type {?} */
const canLoad = route.canLoad;
if (!canLoad || canLoad.length === 0)
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(true);
/** @type {?} */
const obs = Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(canLoad).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} injectionToken
* @return {?}
*/
(injectionToken) => {
/** @type {?} */
const guard = moduleInjector.get(injectionToken);
/** @type {?} */
let guardVal;
if (isCanLoad(guard)) {
guardVal = guard.canLoad(route, segments);
}
else if (isFunction(guard)) {
guardVal = guard(route, segments);
}
else {
throw new Error('Invalid CanLoad guard');
}
return wrapIntoObservable(guardVal);
})));
return obs.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["concatAll"])(), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["every"])((/**
* @param {?} result
* @return {?}
*/
result => result === true)));
}
/**
* @param {?} segmentGroup
* @param {?} route
* @param {?} segments
* @return {?}
*/
function match(segmentGroup, route, segments) {
if (route.path === '') {
if ((route.pathMatch === 'full') && (segmentGroup.hasChildren() || segments.length > 0)) {
return { matched: false, consumedSegments: [], lastChild: 0, positionalParamSegments: {} };
}
return { matched: true, consumedSegments: [], lastChild: 0, positionalParamSegments: {} };
}
/** @type {?} */
const matcher = route.matcher || defaultUrlMatcher;
/** @type {?} */
const res = matcher(segments, segmentGroup, route);
if (!res) {
return {
matched: false,
consumedSegments: (/** @type {?} */ ([])),
lastChild: 0,
positionalParamSegments: {},
};
}
return {
matched: true,
consumedSegments: (/** @type {?} */ (res.consumed)),
lastChild: (/** @type {?} */ (res.consumed.length)),
positionalParamSegments: (/** @type {?} */ (res.posParams)),
};
}
/**
* @param {?} segmentGroup
* @param {?} consumedSegments
* @param {?} slicedSegments
* @param {?} config
* @return {?}
*/
function split(segmentGroup, consumedSegments, slicedSegments, config) {
if (slicedSegments.length > 0 &&
containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, slicedSegments, config)) {
/** @type {?} */
const s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptySegments(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
return { segmentGroup: mergeTrivialChildren(s), slicedSegments: [] };
}
if (slicedSegments.length === 0 &&
containsEmptyPathRedirects(segmentGroup, slicedSegments, config)) {
/** @type {?} */
const s = new UrlSegmentGroup(segmentGroup.segments, addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children));
return { segmentGroup: mergeTrivialChildren(s), slicedSegments };
}
return { segmentGroup, slicedSegments };
}
/**
* @param {?} s
* @return {?}
*/
function mergeTrivialChildren(s) {
if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {
/** @type {?} */
const c = s.children[PRIMARY_OUTLET];
return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);
}
return s;
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @param {?} children
* @return {?}
*/
function addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) {
/** @type {?} */
const res = {};
for (const r of routes) {
if (isEmptyPathRedirect(segmentGroup, slicedSegments, r) && !children[getOutlet(r)]) {
res[getOutlet(r)] = new UrlSegmentGroup([], {});
}
}
return Object.assign(Object.assign({}, children), res);
}
/**
* @param {?} routes
* @param {?} primarySegmentGroup
* @return {?}
*/
function createChildrenForEmptySegments(routes, primarySegmentGroup) {
/** @type {?} */
const res = {};
res[PRIMARY_OUTLET] = primarySegmentGroup;
for (const r of routes) {
if (r.path === '' && getOutlet(r) !== PRIMARY_OUTLET) {
res[getOutlet(r)] = new UrlSegmentGroup([], {});
}
}
return res;
}
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, segments, routes) {
return routes.some((/**
* @param {?} r
* @return {?}
*/
r => isEmptyPathRedirect(segmentGroup, segments, r) && getOutlet(r) !== PRIMARY_OUTLET));
}
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathRedirects(segmentGroup, segments, routes) {
return routes.some((/**
* @param {?} r
* @return {?}
*/
r => isEmptyPathRedirect(segmentGroup, segments, r)));
}
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} r
* @return {?}
*/
function isEmptyPathRedirect(segmentGroup, segments, r) {
if ((segmentGroup.hasChildren() || segments.length > 0) && r.pathMatch === 'full') {
return false;
}
return r.path === '' && r.redirectTo !== undefined;
}
/**
* @param {?} route
* @return {?}
*/
function getOutlet(route) {
return route.outlet || PRIMARY_OUTLET;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/operators/apply_redirects.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} moduleInjector
* @param {?} configLoader
* @param {?} urlSerializer
* @param {?} config
* @return {?}
*/
function applyRedirects$1(moduleInjector, configLoader, urlSerializer, config) {
return (/**
* @param {?} source
* @return {?}
*/
function (source) {
return source.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["switchMap"])((/**
* @param {?} t
* @return {?}
*/
t => applyRedirects(moduleInjector, configLoader, urlSerializer, t.extractedUrl, config)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} urlAfterRedirects
* @return {?}
*/
urlAfterRedirects => (Object.assign(Object.assign({}, t), { urlAfterRedirects }))))))));
});
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/utils/preactivation.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class CanActivate {
/**
* @param {?} path
*/
constructor(path) {
this.path = path;
this.route = this.path[this.path.length - 1];
}
}
if (false) {}
class CanDeactivate {
/**
* @param {?} component
* @param {?} route
*/
constructor(component, route) {
this.component = component;
this.route = route;
}
}
if (false) {}
/**
* @param {?} future
* @param {?} curr
* @param {?} parentContexts
* @return {?}
*/
function getAllRouteGuards(future, curr, parentContexts) {
/** @type {?} */
const futureRoot = future._root;
/** @type {?} */
const currRoot = curr ? curr._root : null;
return getChildRouteGuards(futureRoot, currRoot, parentContexts, [futureRoot.value]);
}
/**
* @param {?} p
* @return {?}
*/
function getCanActivateChild(p) {
/** @type {?} */
const canActivateChild = p.routeConfig ? p.routeConfig.canActivateChild : null;
if (!canActivateChild || canActivateChild.length === 0)
return null;
return { node: p, guards: canActivateChild };
}
/**
* @param {?} token
* @param {?} snapshot
* @param {?} moduleInjector
* @return {?}
*/
function getToken(token, snapshot, moduleInjector) {
/** @type {?} */
const config = getClosestLoadedConfig(snapshot);
/** @type {?} */
const injector = config ? config.module.injector : moduleInjector;
return injector.get(token);
}
/**
* @param {?} snapshot
* @return {?}
*/
function getClosestLoadedConfig(snapshot) {
if (!snapshot)
return null;
for (let s = snapshot.parent; s; s = s.parent) {
/** @type {?} */
const route = s.routeConfig;
if (route && route._loadedConfig)
return route._loadedConfig;
}
return null;
}
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} contexts
* @param {?} futurePath
* @param {?=} checks
* @return {?}
*/
function getChildRouteGuards(futureNode, currNode, contexts, futurePath, checks = {
canDeactivateChecks: [],
canActivateChecks: []
}) {
/** @type {?} */
const prevChildren = nodeChildrenAsMap(currNode);
// Process the children of the future route
futureNode.children.forEach((/**
* @param {?} c
* @return {?}
*/
c => {
getRouteGuards(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value]), checks);
delete prevChildren[c.value.outlet];
}));
// Process any children left from the current route (not active for the future route)
forEach(prevChildren, (/**
* @param {?} v
* @param {?} k
* @return {?}
*/
(v, k) => deactivateRouteAndItsChildren(v, (/** @type {?} */ (contexts)).getContext(k), checks)));
return checks;
}
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} parentContexts
* @param {?} futurePath
* @param {?=} checks
* @return {?}
*/
function getRouteGuards(futureNode, currNode, parentContexts, futurePath, checks = {
canDeactivateChecks: [],
canActivateChecks: []
}) {
/** @type {?} */
const future = futureNode.value;
/** @type {?} */
const curr = currNode ? currNode.value : null;
/** @type {?} */
const context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null;
// reusing the node
if (curr && future.routeConfig === curr.routeConfig) {
/** @type {?} */
const shouldRun = shouldRunGuardsAndResolvers(curr, future, (/** @type {?} */ (future.routeConfig)).runGuardsAndResolvers);
if (shouldRun) {
checks.canActivateChecks.push(new CanActivate(futurePath));
}
else {
// we need to set the data
future.data = curr.data;
future._resolvedData = curr._resolvedData;
}
// If we have a component, we need to go through an outlet.
if (future.component) {
getChildRouteGuards(futureNode, currNode, context ? context.children : null, futurePath, checks);
// if we have a componentless route, we recurse but keep the same outlet map.
}
else {
getChildRouteGuards(futureNode, currNode, parentContexts, futurePath, checks);
}
if (shouldRun) {
/** @type {?} */
const component = context && context.outlet && context.outlet.component || null;
checks.canDeactivateChecks.push(new CanDeactivate(component, curr));
}
}
else {
if (curr) {
deactivateRouteAndItsChildren(currNode, context, checks);
}
checks.canActivateChecks.push(new CanActivate(futurePath));
// If we have a component, we need to go through an outlet.
if (future.component) {
getChildRouteGuards(futureNode, null, context ? context.children : null, futurePath, checks);
// if we have a componentless route, we recurse but keep the same outlet map.
}
else {
getChildRouteGuards(futureNode, null, parentContexts, futurePath, checks);
}
}
return checks;
}
/**
* @param {?} curr
* @param {?} future
* @param {?} mode
* @return {?}
*/
function shouldRunGuardsAndResolvers(curr, future, mode) {
if (typeof mode === 'function') {
return mode(curr, future);
}
switch (mode) {
case 'pathParamsChange':
return !equalPath(curr.url, future.url);
case 'pathParamsOrQueryParamsChange':
return !equalPath(curr.url, future.url) ||
!shallowEqual(curr.queryParams, future.queryParams);
case 'always':
return true;
case 'paramsOrQueryParamsChange':
return !equalParamsAndUrlSegments(curr, future) ||
!shallowEqual(curr.queryParams, future.queryParams);
case 'paramsChange':
default:
return !equalParamsAndUrlSegments(curr, future);
}
}
/**
* @param {?} route
* @param {?} context
* @param {?} checks
* @return {?}
*/
function deactivateRouteAndItsChildren(route, context, checks) {
/** @type {?} */
const children = nodeChildrenAsMap(route);
/** @type {?} */
const r = route.value;
forEach(children, (/**
* @param {?} node
* @param {?} childName
* @return {?}
*/
(node, childName) => {
if (!r.component) {
deactivateRouteAndItsChildren(node, context, checks);
}
else if (context) {
deactivateRouteAndItsChildren(node, context.children.getContext(childName), checks);
}
else {
deactivateRouteAndItsChildren(node, null, checks);
}
}));
if (!r.component) {
checks.canDeactivateChecks.push(new CanDeactivate(null, r));
}
else if (context && context.outlet && context.outlet.isActivated) {
checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r));
}
else {
checks.canDeactivateChecks.push(new CanDeactivate(null, r));
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/operators/prioritized_guard_value.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const INITIAL_VALUE = Symbol('INITIAL_VALUE');
/**
* @return {?}
*/
function prioritizedGuardValue() {
return Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["switchMap"])((/**
* @param {?} obs
* @return {?}
*/
obs => {
return (/** @type {?} */ (Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["combineLatest"])(...obs.map((/**
* @param {?} o
* @return {?}
*/
o => o.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["take"])(1), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["startWith"])((/** @type {?} */ (INITIAL_VALUE)))))))
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["scan"])((/**
* @param {?} acc
* @param {?} list
* @return {?}
*/
(acc, list) => {
/** @type {?} */
let isPending = false;
return list.reduce((/**
* @param {?} innerAcc
* @param {?} val
* @param {?} i
* @return {?}
*/
(innerAcc, val, i) => {
if (innerAcc !== INITIAL_VALUE)
return innerAcc;
// Toggle pending flag if any values haven't been set yet
if (val === INITIAL_VALUE)
isPending = true;
// Any other return values are only valid if we haven't yet hit a pending
// call. This guarantees that in the case of a guard at the bottom of the
// tree that returns a redirect, we will wait for the higher priority
// guard at the top to finish before performing the redirect.
if (!isPending) {
// Early return when we hit a `false` value as that should always
// cancel navigation
if (val === false)
return val;
if (i === list.length - 1 || isUrlTree(val)) {
return val;
}
}
return innerAcc;
}), acc);
}), INITIAL_VALUE), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["filter"])((/**
* @param {?} item
* @return {?}
*/
item => item !== INITIAL_VALUE)), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} item
* @return {?}
*/
item => isUrlTree(item) ? item : item === true)), //
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["take"])(1))));
}));
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/operators/check_guards.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} moduleInjector
* @param {?=} forwardEvent
* @return {?}
*/
function checkGuards(moduleInjector, forwardEvent) {
return (/**
* @param {?} source
* @return {?}
*/
function (source) {
return source.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} t
* @return {?}
*/
t => {
const { targetSnapshot, currentSnapshot, guards: { canActivateChecks, canDeactivateChecks } } = t;
if (canDeactivateChecks.length === 0 && canActivateChecks.length === 0) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(Object.assign(Object.assign({}, t), { guardsResult: true }));
}
return runCanDeactivateChecks(canDeactivateChecks, (/** @type {?} */ (targetSnapshot)), currentSnapshot, moduleInjector)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} canDeactivate
* @return {?}
*/
canDeactivate => {
return canDeactivate && isBoolean(canDeactivate) ?
runCanActivateChecks((/** @type {?} */ (targetSnapshot)), canActivateChecks, moduleInjector, forwardEvent) :
Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(canDeactivate);
})), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} guardsResult
* @return {?}
*/
guardsResult => (Object.assign(Object.assign({}, t), { guardsResult })))));
})));
});
}
/**
* @param {?} checks
* @param {?} futureRSS
* @param {?} currRSS
* @param {?} moduleInjector
* @return {?}
*/
function runCanDeactivateChecks(checks, futureRSS, currRSS, moduleInjector) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(checks).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} check
* @return {?}
*/
check => runCanDeactivate(check.component, check.route, currRSS, futureRSS, moduleInjector))), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["first"])((/**
* @param {?} result
* @return {?}
*/
result => {
return result !== true;
}), (/** @type {?} */ (true))));
}
/**
* @param {?} futureSnapshot
* @param {?} checks
* @param {?} moduleInjector
* @param {?=} forwardEvent
* @return {?}
*/
function runCanActivateChecks(futureSnapshot, checks, moduleInjector, forwardEvent) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(checks).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["concatMap"])((/**
* @param {?} check
* @return {?}
*/
(check) => {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])([
fireChildActivationStart(check.route.parent, forwardEvent),
fireActivationStart(check.route, forwardEvent),
runCanActivateChild(futureSnapshot, check.path, moduleInjector),
runCanActivate(futureSnapshot, check.route, moduleInjector)
])
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["concatAll"])(), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["first"])((/**
* @param {?} result
* @return {?}
*/
result => {
return result !== true;
}), (/** @type {?} */ (true))));
})), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["first"])((/**
* @param {?} result
* @return {?}
*/
result => {
return result !== true;
}), (/** @type {?} */ (true))));
}
/**
* This should fire off `ActivationStart` events for each route being activated at this
* level.
* In other words, if you're activating `a` and `b` below, `path` will contain the
* `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always
* return
* `true` so checks continue to run.
* @param {?} snapshot
* @param {?=} forwardEvent
* @return {?}
*/
function fireActivationStart(snapshot, forwardEvent) {
if (snapshot !== null && forwardEvent) {
forwardEvent(new ActivationStart(snapshot));
}
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(true);
}
/**
* This should fire off `ChildActivationStart` events for each route being activated at this
* level.
* In other words, if you're activating `a` and `b` below, `path` will contain the
* `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always
* return
* `true` so checks continue to run.
* @param {?} snapshot
* @param {?=} forwardEvent
* @return {?}
*/
function fireChildActivationStart(snapshot, forwardEvent) {
if (snapshot !== null && forwardEvent) {
forwardEvent(new ChildActivationStart(snapshot));
}
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(true);
}
/**
* @param {?} futureRSS
* @param {?} futureARS
* @param {?} moduleInjector
* @return {?}
*/
function runCanActivate(futureRSS, futureARS, moduleInjector) {
/** @type {?} */
const canActivate = futureARS.routeConfig ? futureARS.routeConfig.canActivate : null;
if (!canActivate || canActivate.length === 0)
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(true);
/** @type {?} */
const canActivateObservables = canActivate.map((/**
* @param {?} c
* @return {?}
*/
(c) => {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["defer"])((/**
* @return {?}
*/
() => {
/** @type {?} */
const guard = getToken(c, futureARS, moduleInjector);
/** @type {?} */
let observable;
if (isCanActivate(guard)) {
observable = wrapIntoObservable(guard.canActivate(futureARS, futureRSS));
}
else if (isFunction(guard)) {
observable = wrapIntoObservable(guard(futureARS, futureRSS));
}
else {
throw new Error('Invalid CanActivate guard');
}
return observable.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["first"])());
}));
}));
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(canActivateObservables).pipe(prioritizedGuardValue());
}
/**
* @param {?} futureRSS
* @param {?} path
* @param {?} moduleInjector
* @return {?}
*/
function runCanActivateChild(futureRSS, path, moduleInjector) {
/** @type {?} */
const futureARS = path[path.length - 1];
/** @type {?} */
const canActivateChildGuards = path.slice(0, path.length - 1)
.reverse()
.map((/**
* @param {?} p
* @return {?}
*/
p => getCanActivateChild(p)))
.filter((/**
* @param {?} _
* @return {?}
*/
_ => _ !== null));
/** @type {?} */
const canActivateChildGuardsMapped = canActivateChildGuards.map((/**
* @param {?} d
* @return {?}
*/
(d) => {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["defer"])((/**
* @return {?}
*/
() => {
/** @type {?} */
const guardsMapped = d.guards.map((/**
* @param {?} c
* @return {?}
*/
(c) => {
/** @type {?} */
const guard = getToken(c, d.node, moduleInjector);
/** @type {?} */
let observable;
if (isCanActivateChild(guard)) {
observable = wrapIntoObservable(guard.canActivateChild(futureARS, futureRSS));
}
else if (isFunction(guard)) {
observable = wrapIntoObservable(guard(futureARS, futureRSS));
}
else {
throw new Error('Invalid CanActivateChild guard');
}
return observable.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["first"])());
}));
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(guardsMapped).pipe(prioritizedGuardValue());
}));
}));
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(canActivateChildGuardsMapped).pipe(prioritizedGuardValue());
}
/**
* @param {?} component
* @param {?} currARS
* @param {?} currRSS
* @param {?} futureRSS
* @param {?} moduleInjector
* @return {?}
*/
function runCanDeactivate(component, currARS, currRSS, futureRSS, moduleInjector) {
/** @type {?} */
const canDeactivate = currARS && currARS.routeConfig ? currARS.routeConfig.canDeactivate : null;
if (!canDeactivate || canDeactivate.length === 0)
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(true);
/** @type {?} */
const canDeactivateObservables = canDeactivate.map((/**
* @param {?} c
* @return {?}
*/
(c) => {
/** @type {?} */
const guard = getToken(c, currARS, moduleInjector);
/** @type {?} */
let observable;
if (isCanDeactivate(guard)) {
observable = wrapIntoObservable(guard.canDeactivate((/** @type {?} */ (component)), currARS, currRSS, futureRSS));
}
else if (isFunction(guard)) {
observable = wrapIntoObservable(guard(component, currARS, currRSS, futureRSS));
}
else {
throw new Error('Invalid CanDeactivate guard');
}
return observable.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["first"])());
}));
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(canDeactivateObservables).pipe(prioritizedGuardValue());
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/recognize.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class NoMatch$1 {
}
/**
* @param {?} rootComponentType
* @param {?} config
* @param {?} urlTree
* @param {?} url
* @param {?=} paramsInheritanceStrategy
* @param {?=} relativeLinkResolution
* @return {?}
*/
function recognize(rootComponentType, config, urlTree, url, paramsInheritanceStrategy = 'emptyOnly', relativeLinkResolution = 'legacy') {
return new Recognizer(rootComponentType, config, urlTree, url, paramsInheritanceStrategy, relativeLinkResolution)
.recognize();
}
class Recognizer {
/**
* @param {?} rootComponentType
* @param {?} config
* @param {?} urlTree
* @param {?} url
* @param {?} paramsInheritanceStrategy
* @param {?} relativeLinkResolution
*/
constructor(rootComponentType, config, urlTree, url, paramsInheritanceStrategy, relativeLinkResolution) {
this.rootComponentType = rootComponentType;
this.config = config;
this.urlTree = urlTree;
this.url = url;
this.paramsInheritanceStrategy = paramsInheritanceStrategy;
this.relativeLinkResolution = relativeLinkResolution;
}
/**
* @return {?}
*/
recognize() {
try {
/** @type {?} */
const rootSegmentGroup = split$1(this.urlTree.root, [], [], this.config, this.relativeLinkResolution).segmentGroup;
/** @type {?} */
const children = this.processSegmentGroup(this.config, rootSegmentGroup, PRIMARY_OUTLET);
/** @type {?} */
const root = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze(Object.assign({}, this.urlTree.queryParams)), (/** @type {?} */ (this.urlTree.fragment)), {}, PRIMARY_OUTLET, this.rootComponentType, null, this.urlTree.root, -1, {});
/** @type {?} */
const rootNode = new TreeNode(root, children);
/** @type {?} */
const routeState = new RouterStateSnapshot(this.url, rootNode);
this.inheritParamsAndData(routeState._root);
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(routeState);
}
catch (e) {
return new rxjs__WEBPACK_IMPORTED_MODULE_2__["Observable"]((/**
* @param {?} obs
* @return {?}
*/
(obs) => obs.error(e)));
}
}
/**
* @param {?} routeNode
* @return {?}
*/
inheritParamsAndData(routeNode) {
/** @type {?} */
const route = routeNode.value;
/** @type {?} */
const i = inheritedParamsDataResolve(route, this.paramsInheritanceStrategy);
route.params = Object.freeze(i.params);
route.data = Object.freeze(i.data);
routeNode.children.forEach((/**
* @param {?} n
* @return {?}
*/
n => this.inheritParamsAndData(n)));
}
/**
* @param {?} config
* @param {?} segmentGroup
* @param {?} outlet
* @return {?}
*/
processSegmentGroup(config, segmentGroup, outlet) {
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return this.processChildren(config, segmentGroup);
}
return this.processSegment(config, segmentGroup, segmentGroup.segments, outlet);
}
/**
* @param {?} config
* @param {?} segmentGroup
* @return {?}
*/
processChildren(config, segmentGroup) {
/** @type {?} */
const children = mapChildrenIntoArray(segmentGroup, (/**
* @param {?} child
* @param {?} childOutlet
* @return {?}
*/
(child, childOutlet) => this.processSegmentGroup(config, child, childOutlet)));
checkOutletNameUniqueness(children);
sortActivatedRouteSnapshots(children);
return children;
}
/**
* @param {?} config
* @param {?} segmentGroup
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
processSegment(config, segmentGroup, segments, outlet) {
for (const r of config) {
try {
return this.processSegmentAgainstRoute(r, segmentGroup, segments, outlet);
}
catch (e) {
if (!(e instanceof NoMatch$1))
throw e;
}
}
if (this.noLeftoversInUrl(segmentGroup, segments, outlet)) {
return [];
}
throw new NoMatch$1();
}
/**
* @private
* @param {?} segmentGroup
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
noLeftoversInUrl(segmentGroup, segments, outlet) {
return segments.length === 0 && !segmentGroup.children[outlet];
}
/**
* @param {?} route
* @param {?} rawSegment
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
processSegmentAgainstRoute(route, rawSegment, segments, outlet) {
if (route.redirectTo)
throw new NoMatch$1();
if ((route.outlet || PRIMARY_OUTLET) !== outlet)
throw new NoMatch$1();
/** @type {?} */
let snapshot;
/** @type {?} */
let consumedSegments = [];
/** @type {?} */
let rawSlicedSegments = [];
if (route.path === '**') {
/** @type {?} */
const params = segments.length > 0 ? (/** @type {?} */ (last(segments))).parameters : {};
snapshot = new ActivatedRouteSnapshot(segments, params, Object.freeze(Object.assign({}, this.urlTree.queryParams)), (/** @type {?} */ (this.urlTree.fragment)), getData(route), outlet, (/** @type {?} */ (route.component)), route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + segments.length, getResolve(route));
}
else {
/** @type {?} */
const result = match$1(rawSegment, route, segments);
consumedSegments = result.consumedSegments;
rawSlicedSegments = segments.slice(result.lastChild);
snapshot = new ActivatedRouteSnapshot(consumedSegments, result.parameters, Object.freeze(Object.assign({}, this.urlTree.queryParams)), (/** @type {?} */ (this.urlTree.fragment)), getData(route), outlet, (/** @type {?} */ (route.component)), route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + consumedSegments.length, getResolve(route));
}
/** @type {?} */
const childConfig = getChildConfig(route);
const { segmentGroup, slicedSegments } = split$1(rawSegment, consumedSegments, rawSlicedSegments, childConfig, this.relativeLinkResolution);
if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
/** @type {?} */
const children = this.processChildren(childConfig, segmentGroup);
return [new TreeNode(snapshot, children)];
}
if (childConfig.length === 0 && slicedSegments.length === 0) {
return [new TreeNode(snapshot, [])];
}
/** @type {?} */
const children = this.processSegment(childConfig, segmentGroup, slicedSegments, PRIMARY_OUTLET);
return [new TreeNode(snapshot, children)];
}
}
if (false) {}
/**
* @param {?} nodes
* @return {?}
*/
function sortActivatedRouteSnapshots(nodes) {
nodes.sort((/**
* @param {?} a
* @param {?} b
* @return {?}
*/
(a, b) => {
if (a.value.outlet === PRIMARY_OUTLET)
return -1;
if (b.value.outlet === PRIMARY_OUTLET)
return 1;
return a.value.outlet.localeCompare(b.value.outlet);
}));
}
/**
* @param {?} route
* @return {?}
*/
function getChildConfig(route) {
if (route.children) {
return route.children;
}
if (route.loadChildren) {
return (/** @type {?} */ (route._loadedConfig)).routes;
}
return [];
}
/**
* @record
*/
function MatchResult() { }
if (false) {}
/**
* @param {?} segmentGroup
* @param {?} route
* @param {?} segments
* @return {?}
*/
function match$1(segmentGroup, route, segments) {
if (route.path === '') {
if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) {
throw new NoMatch$1();
}
return { consumedSegments: [], lastChild: 0, parameters: {} };
}
/** @type {?} */
const matcher = route.matcher || defaultUrlMatcher;
/** @type {?} */
const res = matcher(segments, segmentGroup, route);
if (!res)
throw new NoMatch$1();
/** @type {?} */
const posParams = {};
forEach((/** @type {?} */ (res.posParams)), (/**
* @param {?} v
* @param {?} k
* @return {?}
*/
(v, k) => {
posParams[k] = v.path;
}));
/** @type {?} */
const parameters = res.consumed.length > 0 ? Object.assign(Object.assign({}, posParams), res.consumed[res.consumed.length - 1].parameters) :
posParams;
return { consumedSegments: res.consumed, lastChild: res.consumed.length, parameters };
}
/**
* @param {?} nodes
* @return {?}
*/
function checkOutletNameUniqueness(nodes) {
/** @type {?} */
const names = {};
nodes.forEach((/**
* @param {?} n
* @return {?}
*/
n => {
/** @type {?} */
const routeWithSameOutletName = names[n.value.outlet];
if (routeWithSameOutletName) {
/** @type {?} */
const p = routeWithSameOutletName.url.map((/**
* @param {?} s
* @return {?}
*/
s => s.toString())).join('/');
/** @type {?} */
const c = n.value.url.map((/**
* @param {?} s
* @return {?}
*/
s => s.toString())).join('/');
throw new Error(`Two segments cannot have the same outlet name: '${p}' and '${c}'.`);
}
names[n.value.outlet] = n.value;
}));
}
/**
* @param {?} segmentGroup
* @return {?}
*/
function getSourceSegmentGroup(segmentGroup) {
/** @type {?} */
let s = segmentGroup;
while (s._sourceSegment) {
s = s._sourceSegment;
}
return s;
}
/**
* @param {?} segmentGroup
* @return {?}
*/
function getPathIndexShift(segmentGroup) {
/** @type {?} */
let s = segmentGroup;
/** @type {?} */
let res = (s._segmentIndexShift ? s._segmentIndexShift : 0);
while (s._sourceSegment) {
s = s._sourceSegment;
res += (s._segmentIndexShift ? s._segmentIndexShift : 0);
}
return res - 1;
}
/**
* @param {?} segmentGroup
* @param {?} consumedSegments
* @param {?} slicedSegments
* @param {?} config
* @param {?} relativeLinkResolution
* @return {?}
*/
function split$1(segmentGroup, consumedSegments, slicedSegments, config, relativeLinkResolution) {
if (slicedSegments.length > 0 &&
containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) {
/** @type {?} */
const s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(segmentGroup, consumedSegments, config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
s._sourceSegment = segmentGroup;
s._segmentIndexShift = consumedSegments.length;
return { segmentGroup: s, slicedSegments: [] };
}
if (slicedSegments.length === 0 &&
containsEmptyPathMatches(segmentGroup, slicedSegments, config)) {
/** @type {?} */
const s = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, consumedSegments, slicedSegments, config, segmentGroup.children, relativeLinkResolution));
s._sourceSegment = segmentGroup;
s._segmentIndexShift = consumedSegments.length;
return { segmentGroup: s, slicedSegments };
}
/** @type {?} */
const s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children);
s._sourceSegment = segmentGroup;
s._segmentIndexShift = consumedSegments.length;
return { segmentGroup: s, slicedSegments };
}
/**
* @param {?} segmentGroup
* @param {?} consumedSegments
* @param {?} slicedSegments
* @param {?} routes
* @param {?} children
* @param {?} relativeLinkResolution
* @return {?}
*/
function addEmptyPathsToChildrenIfNeeded(segmentGroup, consumedSegments, slicedSegments, routes, children, relativeLinkResolution) {
/** @type {?} */
const res = {};
for (const r of routes) {
if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet$1(r)]) {
/** @type {?} */
const s = new UrlSegmentGroup([], {});
s._sourceSegment = segmentGroup;
if (relativeLinkResolution === 'legacy') {
s._segmentIndexShift = segmentGroup.segments.length;
}
else {
s._segmentIndexShift = consumedSegments.length;
}
res[getOutlet$1(r)] = s;
}
}
return Object.assign(Object.assign({}, children), res);
}
/**
* @param {?} segmentGroup
* @param {?} consumedSegments
* @param {?} routes
* @param {?} primarySegment
* @return {?}
*/
function createChildrenForEmptyPaths(segmentGroup, consumedSegments, routes, primarySegment) {
/** @type {?} */
const res = {};
res[PRIMARY_OUTLET] = primarySegment;
primarySegment._sourceSegment = segmentGroup;
primarySegment._segmentIndexShift = consumedSegments.length;
for (const r of routes) {
if (r.path === '' && getOutlet$1(r) !== PRIMARY_OUTLET) {
/** @type {?} */
const s = new UrlSegmentGroup([], {});
s._sourceSegment = segmentGroup;
s._segmentIndexShift = consumedSegments.length;
res[getOutlet$1(r)] = s;
}
}
return res;
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) {
return routes.some((/**
* @param {?} r
* @return {?}
*/
r => emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet$1(r) !== PRIMARY_OUTLET));
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathMatches(segmentGroup, slicedSegments, routes) {
return routes.some((/**
* @param {?} r
* @return {?}
*/
r => emptyPathMatch(segmentGroup, slicedSegments, r)));
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} r
* @return {?}
*/
function emptyPathMatch(segmentGroup, slicedSegments, r) {
if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') {
return false;
}
return r.path === '' && r.redirectTo === undefined;
}
/**
* @param {?} route
* @return {?}
*/
function getOutlet$1(route) {
return route.outlet || PRIMARY_OUTLET;
}
/**
* @param {?} route
* @return {?}
*/
function getData(route) {
return route.data || {};
}
/**
* @param {?} route
* @return {?}
*/
function getResolve(route) {
return route.resolve || {};
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/operators/recognize.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} rootComponentType
* @param {?} config
* @param {?} serializer
* @param {?} paramsInheritanceStrategy
* @param {?} relativeLinkResolution
* @return {?}
*/
function recognize$1(rootComponentType, config, serializer, paramsInheritanceStrategy, relativeLinkResolution) {
return (/**
* @param {?} source
* @return {?}
*/
function (source) {
return source.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} t
* @return {?}
*/
t => recognize(rootComponentType, config, t.urlAfterRedirects, serializer(t.urlAfterRedirects), paramsInheritanceStrategy, relativeLinkResolution)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} targetSnapshot
* @return {?}
*/
targetSnapshot => (Object.assign(Object.assign({}, t), { targetSnapshot }))))))));
});
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/operators/resolve_data.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} paramsInheritanceStrategy
* @param {?} moduleInjector
* @return {?}
*/
function resolveData(paramsInheritanceStrategy, moduleInjector) {
return (/**
* @param {?} source
* @return {?}
*/
function (source) {
return source.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} t
* @return {?}
*/
t => {
const { targetSnapshot, guards: { canActivateChecks } } = t;
if (!canActivateChecks.length) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(t);
}
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(canActivateChecks)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["concatMap"])((/**
* @param {?} check
* @return {?}
*/
check => runResolve(check.route, (/** @type {?} */ (targetSnapshot)), paramsInheritanceStrategy, moduleInjector))), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["reduce"])((/**
* @param {?} _
* @param {?} __
* @return {?}
*/
(_, __) => _)), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} _
* @return {?}
*/
_ => t)));
})));
});
}
/**
* @param {?} futureARS
* @param {?} futureRSS
* @param {?} paramsInheritanceStrategy
* @param {?} moduleInjector
* @return {?}
*/
function runResolve(futureARS, futureRSS, paramsInheritanceStrategy, moduleInjector) {
/** @type {?} */
const resolve = futureARS._resolve;
return resolveNode(resolve, futureARS, futureRSS, moduleInjector)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} resolvedData
* @return {?}
*/
(resolvedData) => {
futureARS._resolvedData = resolvedData;
futureARS.data = Object.assign(Object.assign({}, futureARS.data), inheritedParamsDataResolve(futureARS, paramsInheritanceStrategy).resolve);
return null;
})));
}
/**
* @param {?} resolve
* @param {?} futureARS
* @param {?} futureRSS
* @param {?} moduleInjector
* @return {?}
*/
function resolveNode(resolve, futureARS, futureRSS, moduleInjector) {
/** @type {?} */
const keys = Object.keys(resolve);
if (keys.length === 0) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])({});
}
if (keys.length === 1) {
/** @type {?} */
const key = keys[0];
return getResolver(resolve[key], futureARS, futureRSS, moduleInjector)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} value
* @return {?}
*/
(value) => {
return { [key]: value };
})));
}
/** @type {?} */
const data = {};
/** @type {?} */
const runningResolvers$ = Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(keys).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} key
* @return {?}
*/
(key) => {
return getResolver(resolve[key], futureARS, futureRSS, moduleInjector)
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} value
* @return {?}
*/
(value) => {
data[key] = value;
return value;
})));
})));
return runningResolvers$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["last"])(), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @return {?}
*/
() => data)));
}
/**
* @param {?} injectionToken
* @param {?} futureARS
* @param {?} futureRSS
* @param {?} moduleInjector
* @return {?}
*/
function getResolver(injectionToken, futureARS, futureRSS, moduleInjector) {
/** @type {?} */
const resolver = getToken(injectionToken, futureARS, moduleInjector);
return resolver.resolve ? wrapIntoObservable(resolver.resolve(futureARS, futureRSS)) :
wrapIntoObservable(resolver(futureARS, futureRSS));
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/operators/switch_tap.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Perform a side effect through a switchMap for every emission on the source Observable,
* but return an Observable that is identical to the source. It's essentially the same as
* the `tap` operator, but if the side effectful `next` function returns an ObservableInput,
* it will wait before continuing with the original value.
* @template T
* @param {?} next
* @return {?}
*/
function switchTap(next) {
return (/**
* @param {?} source
* @return {?}
*/
function (source) {
return source.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["switchMap"])((/**
* @param {?} v
* @return {?}
*/
v => {
/** @type {?} */
const nextResult = next(v);
if (nextResult) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(nextResult).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @return {?}
*/
() => v)));
}
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])([v]);
})));
});
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/route_reuse_strategy.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@description
*
* Provides a way to customize when activated routes get reused.
*
* \@publicApi
* @abstract
*/
class RouteReuseStrategy {
}
if (false) {}
/**
* Does not detach any subtrees. Reuses routes as long as their route config is the same.
*/
class DefaultRouteReuseStrategy {
/**
* @param {?} route
* @return {?}
*/
shouldDetach(route) {
return false;
}
/**
* @param {?} route
* @param {?} detachedTree
* @return {?}
*/
store(route, detachedTree) { }
/**
* @param {?} route
* @return {?}
*/
shouldAttach(route) {
return false;
}
/**
* @param {?} route
* @return {?}
*/
retrieve(route) {
return null;
}
/**
* @param {?} future
* @param {?} curr
* @return {?}
*/
shouldReuseRoute(future, curr) {
return future.routeConfig === curr.routeConfig;
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/router_config_loader.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* The [DI token](guide/glossary/#di-token) for a router configuration.
* @see `ROUTES`
* \@publicApi
* @type {?}
*/
const ROUTES = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["InjectionToken"]('ROUTES');
class RouterConfigLoader {
/**
* @param {?} loader
* @param {?} compiler
* @param {?=} onLoadStartListener
* @param {?=} onLoadEndListener
*/
constructor(loader, compiler, onLoadStartListener, onLoadEndListener) {
this.loader = loader;
this.compiler = compiler;
this.onLoadStartListener = onLoadStartListener;
this.onLoadEndListener = onLoadEndListener;
}
/**
* @param {?} parentInjector
* @param {?} route
* @return {?}
*/
load(parentInjector, route) {
if (this.onLoadStartListener) {
this.onLoadStartListener(route);
}
/** @type {?} */
const moduleFactory$ = this.loadModuleFactory((/** @type {?} */ (route.loadChildren)));
return moduleFactory$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} factory
* @return {?}
*/
(factory) => {
if (this.onLoadEndListener) {
this.onLoadEndListener(route);
}
/** @type {?} */
const module = factory.create(parentInjector);
return new LoadedRouterConfig(flatten(module.injector.get(ROUTES)).map(standardizeConfig), module);
})));
}
/**
* @private
* @param {?} loadChildren
* @return {?}
*/
loadModuleFactory(loadChildren) {
if (typeof loadChildren === 'string') {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(this.loader.load(loadChildren));
}
else {
return wrapIntoObservable(loadChildren()).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} t
* @return {?}
*/
(t) => {
if (t instanceof _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModuleFactory"]) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(t);
}
else {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(this.compiler.compileModuleAsync(t));
}
})));
}
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/url_handling_strategy.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@description
*
* Provides a way to migrate AngularJS applications to Angular.
*
* \@publicApi
* @abstract
*/
class UrlHandlingStrategy {
}
if (false) {}
/**
* \@publicApi
*/
class DefaultUrlHandlingStrategy {
/**
* @param {?} url
* @return {?}
*/
shouldProcessUrl(url) {
return true;
}
/**
* @param {?} url
* @return {?}
*/
extract(url) {
return url;
}
/**
* @param {?} newUrlPart
* @param {?} wholeUrl
* @return {?}
*/
merge(newUrlPart, wholeUrl) {
return newUrlPart;
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/router.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@description
*
* Options that modify the navigation strategy.
*
* \@publicApi
* @record
*/
function NavigationExtras() { }
if (false) {}
/**
* @param {?} error
* @return {?}
*/
function defaultErrorHandler(error) {
throw error;
}
/**
* @param {?} error
* @param {?} urlSerializer
* @param {?} url
* @return {?}
*/
function defaultMalformedUriErrorHandler(error, urlSerializer, url) {
return urlSerializer.parse('/');
}
/**
* \@internal
* @param {?} snapshot
* @param {?} runExtras
* @return {?}
*/
function defaultRouterHook(snapshot, runExtras) {
return (/** @type {?} */ (Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(null)));
}
/**
* \@description
*
* A service that provides navigation and URL manipulation capabilities.
*
* @see `Route`.
* @see [Routing and Navigation Guide](guide/router).
*
* \@ngModule RouterModule
*
* \@publicApi
*/
class Router {
/**
* Creates the router service.
* @param {?} rootComponentType
* @param {?} urlSerializer
* @param {?} rootContexts
* @param {?} location
* @param {?} injector
* @param {?} loader
* @param {?} compiler
* @param {?} config
*/
// TODO: vsavkin make internal after the final is out.
constructor(rootComponentType, urlSerializer, rootContexts, location, injector, loader, compiler, config) {
this.rootComponentType = rootComponentType;
this.urlSerializer = urlSerializer;
this.rootContexts = rootContexts;
this.location = location;
this.config = config;
this.lastSuccessfulNavigation = null;
this.currentNavigation = null;
this.navigationId = 0;
this.isNgZoneEnabled = false;
/**
* An event stream for routing events in this NgModule.
*/
this.events = new rxjs__WEBPACK_IMPORTED_MODULE_2__["Subject"]();
/**
* A handler for navigation errors in this NgModule.
*/
this.errorHandler = defaultErrorHandler;
/**
* A handler for errors thrown by `Router.parseUrl(url)`
* when `url` contains an invalid character.
* The most common case is a `%` sign
* that's not encoded and is not part of a percent encoded sequence.
*/
this.malformedUriErrorHandler = defaultMalformedUriErrorHandler;
/**
* True if at least one navigation event has occurred,
* false otherwise.
*/
this.navigated = false;
this.lastSuccessfulId = -1;
/**
* Hooks that enable you to pause navigation,
* either before or after the preactivation phase.
* Used by `RouterModule`.
*
* \@internal
*/
this.hooks = { beforePreactivation: defaultRouterHook, afterPreactivation: defaultRouterHook };
/**
* A strategy for extracting and merging URLs.
* Used for AngularJS to Angular migrations.
*/
this.urlHandlingStrategy = new DefaultUrlHandlingStrategy();
/**
* A strategy for re-using routes.
*/
this.routeReuseStrategy = new DefaultRouteReuseStrategy();
/**
* How to handle a navigation request to the current URL. One of:
* - `'ignore'` : The router ignores the request.
* - `'reload'` : The router reloads the URL. Use to implement a "refresh" feature.
*/
this.onSameUrlNavigation = 'ignore';
/**
* How to merge parameters, data, and resolved data from parent to child
* routes. One of:
*
* - `'emptyOnly'` : Inherit parent parameters, data, and resolved data
* for path-less or component-less routes.
* - `'always'` : Inherit parent parameters, data, and resolved data
* for all child routes.
*/
this.paramsInheritanceStrategy = 'emptyOnly';
/**
* Determines when the router updates the browser URL.
* By default (`"deferred"`), updates the browser URL after navigation has finished.
* Set to `'eager'` to update the browser URL at the beginning of navigation.
* You can choose to update early so that, if navigation fails,
* you can show an error message with the URL that failed.
*/
this.urlUpdateStrategy = 'deferred';
/**
* Enables a bug fix that corrects relative link resolution in components with empty paths.
* @see `RouterModule`
*/
this.relativeLinkResolution = 'legacy';
/** @type {?} */
const onLoadStart = (/**
* @param {?} r
* @return {?}
*/
(r) => this.triggerEvent(new RouteConfigLoadStart(r)));
/** @type {?} */
const onLoadEnd = (/**
* @param {?} r
* @return {?}
*/
(r) => this.triggerEvent(new RouteConfigLoadEnd(r)));
this.ngModule = injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModuleRef"]);
this.console = injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵConsole"]);
/** @type {?} */
const ngZone = injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"]);
this.isNgZoneEnabled = ngZone instanceof _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"];
this.resetConfig(config);
this.currentUrlTree = createEmptyUrlTree();
this.rawUrlTree = this.currentUrlTree;
this.browserUrlTree = this.currentUrlTree;
this.configLoader = new RouterConfigLoader(loader, compiler, onLoadStart, onLoadEnd);
this.routerState = createEmptyState(this.currentUrlTree, this.rootComponentType);
this.transitions = new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"]({
id: 0,
currentUrlTree: this.currentUrlTree,
currentRawUrl: this.currentUrlTree,
extractedUrl: this.urlHandlingStrategy.extract(this.currentUrlTree),
urlAfterRedirects: this.urlHandlingStrategy.extract(this.currentUrlTree),
rawUrl: this.currentUrlTree,
extras: {},
resolve: null,
reject: null,
promise: Promise.resolve(true),
source: 'imperative',
restoredState: null,
currentSnapshot: this.routerState.snapshot,
targetSnapshot: null,
currentRouterState: this.routerState,
targetRouterState: null,
guards: { canActivateChecks: [], canDeactivateChecks: [] },
guardsResult: null,
});
this.navigations = this.setupNavigations(this.transitions);
this.processNavigations();
}
/**
* @private
* @param {?} transitions
* @return {?}
*/
setupNavigations(transitions) {
/** @type {?} */
const eventsSubject = ((/** @type {?} */ (this.events)));
return (/** @type {?} */ ((/** @type {?} */ (transitions.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["filter"])((/**
* @param {?} t
* @return {?}
*/
t => t.id !== 0)),
// Extract URL
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} t
* @return {?}
*/
t => ((/** @type {?} */ (Object.assign(Object.assign({}, t), { extractedUrl: this.urlHandlingStrategy.extract(t.rawUrl) })))))),
// Using switchMap so we cancel executing navigations when a new one comes in
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["switchMap"])((/**
* @param {?} t
* @return {?}
*/
t => {
/** @type {?} */
let completed = false;
/** @type {?} */
let errored = false;
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(t).pipe(
// Store the Navigation object
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])((/**
* @param {?} t
* @return {?}
*/
t => {
this.currentNavigation = {
id: t.id,
initialUrl: t.currentRawUrl,
extractedUrl: t.extractedUrl,
trigger: t.source,
extras: t.extras,
previousNavigation: this.lastSuccessfulNavigation ? Object.assign(Object.assign({}, this.lastSuccessfulNavigation), { previousNavigation: null }) :
null
};
})), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["switchMap"])((/**
* @param {?} t
* @return {?}
*/
t => {
/** @type {?} */
const urlTransition = !this.navigated ||
t.extractedUrl.toString() !== this.browserUrlTree.toString();
/** @type {?} */
const processCurrentUrl = (this.onSameUrlNavigation === 'reload' ? true : urlTransition) &&
this.urlHandlingStrategy.shouldProcessUrl(t.rawUrl);
if (processCurrentUrl) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(t).pipe(
// Fire NavigationStart event
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["switchMap"])((/**
* @param {?} t
* @return {?}
*/
t => {
/** @type {?} */
const transition = this.transitions.getValue();
eventsSubject.next(new NavigationStart(t.id, this.serializeUrl(t.extractedUrl), t.source, t.restoredState));
if (transition !== this.transitions.getValue()) {
return rxjs__WEBPACK_IMPORTED_MODULE_2__["EMPTY"];
}
return [t];
})),
// This delay is required to match old behavior that forced navigation
// to always be async
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["switchMap"])((/**
* @param {?} t
* @return {?}
*/
t => Promise.resolve(t))),
// ApplyRedirects
applyRedirects$1(this.ngModule.injector, this.configLoader, this.urlSerializer, this.config),
// Update the currentNavigation
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])((/**
* @param {?} t
* @return {?}
*/
t => {
this.currentNavigation = Object.assign(Object.assign({}, (/** @type {?} */ (this.currentNavigation))), { finalUrl: t.urlAfterRedirects });
})),
// Recognize
recognize$1(this.rootComponentType, this.config, (/**
* @param {?} url
* @return {?}
*/
(url) => this.serializeUrl(url)), this.paramsInheritanceStrategy, this.relativeLinkResolution),
// Update URL if in `eager` update mode
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])((/**
* @param {?} t
* @return {?}
*/
t => {
if (this.urlUpdateStrategy === 'eager') {
if (!t.extras.skipLocationChange) {
this.setBrowserUrl(t.urlAfterRedirects, !!t.extras.replaceUrl, t.id, t.extras.state);
}
this.browserUrlTree = t.urlAfterRedirects;
}
})),
// Fire RoutesRecognized
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])((/**
* @param {?} t
* @return {?}
*/
t => {
/** @type {?} */
const routesRecognized = new RoutesRecognized(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(t.urlAfterRedirects), (/** @type {?} */ (t.targetSnapshot)));
eventsSubject.next(routesRecognized);
})));
}
else {
/** @type {?} */
const processPreviousUrl = urlTransition && this.rawUrlTree &&
this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree);
/* When the current URL shouldn't be processed, but the previous one was,
* we handle this "error condition" by navigating to the previously
* successful URL, but leaving the URL intact.*/
if (processPreviousUrl) {
const { id, extractedUrl, source, restoredState, extras } = t;
/** @type {?} */
const navStart = new NavigationStart(id, this.serializeUrl(extractedUrl), source, restoredState);
eventsSubject.next(navStart);
/** @type {?} */
const targetSnapshot = createEmptyState(extractedUrl, this.rootComponentType).snapshot;
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(Object.assign(Object.assign({}, t), { targetSnapshot, urlAfterRedirects: extractedUrl, extras: Object.assign(Object.assign({}, extras), { skipLocationChange: false, replaceUrl: false }) }));
}
else {
/* When neither the current or previous URL can be processed, do nothing
* other than update router's internal reference to the current "settled"
* URL. This way the next navigation will be coming from the current URL
* in the browser.
*/
this.rawUrlTree = t.rawUrl;
this.browserUrlTree = t.urlAfterRedirects;
t.resolve(null);
return rxjs__WEBPACK_IMPORTED_MODULE_2__["EMPTY"];
}
}
})),
// Before Preactivation
switchTap((/**
* @param {?} t
* @return {?}
*/
t => {
const { targetSnapshot, id: navigationId, extractedUrl: appliedUrlTree, rawUrl: rawUrlTree, extras: { skipLocationChange, replaceUrl } } = t;
return this.hooks.beforePreactivation((/** @type {?} */ (targetSnapshot)), {
navigationId,
appliedUrlTree,
rawUrlTree,
skipLocationChange: !!skipLocationChange,
replaceUrl: !!replaceUrl,
});
})),
// --- GUARDS ---
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])((/**
* @param {?} t
* @return {?}
*/
t => {
/** @type {?} */
const guardsStart = new GuardsCheckStart(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(t.urlAfterRedirects), (/** @type {?} */ (t.targetSnapshot)));
this.triggerEvent(guardsStart);
})), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} t
* @return {?}
*/
t => (Object.assign(Object.assign({}, t), { guards: getAllRouteGuards((/** @type {?} */ (t.targetSnapshot)), t.currentSnapshot, this.rootContexts) })))), checkGuards(this.ngModule.injector, (/**
* @param {?} evt
* @return {?}
*/
(evt) => this.triggerEvent(evt))), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])((/**
* @param {?} t
* @return {?}
*/
t => {
if (isUrlTree(t.guardsResult)) {
/** @type {?} */
const error = navigationCancelingError(`Redirecting to "${this.serializeUrl(t.guardsResult)}"`);
error.url = t.guardsResult;
throw error;
}
})), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])((/**
* @param {?} t
* @return {?}
*/
t => {
/** @type {?} */
const guardsEnd = new GuardsCheckEnd(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(t.urlAfterRedirects), (/** @type {?} */ (t.targetSnapshot)), !!t.guardsResult);
this.triggerEvent(guardsEnd);
})), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["filter"])((/**
* @param {?} t
* @return {?}
*/
t => {
if (!t.guardsResult) {
this.resetUrlToCurrentUrlTree();
/** @type {?} */
const navCancel = new NavigationCancel(t.id, this.serializeUrl(t.extractedUrl), '');
eventsSubject.next(navCancel);
t.resolve(false);
return false;
}
return true;
})),
// --- RESOLVE ---
switchTap((/**
* @param {?} t
* @return {?}
*/
t => {
if (t.guards.canActivateChecks.length) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(t).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])((/**
* @param {?} t
* @return {?}
*/
t => {
/** @type {?} */
const resolveStart = new ResolveStart(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(t.urlAfterRedirects), (/** @type {?} */ (t.targetSnapshot)));
this.triggerEvent(resolveStart);
})), resolveData(this.paramsInheritanceStrategy, this.ngModule.injector), //
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])((/**
* @param {?} t
* @return {?}
*/
t => {
/** @type {?} */
const resolveEnd = new ResolveEnd(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(t.urlAfterRedirects), (/** @type {?} */ (t.targetSnapshot)));
this.triggerEvent(resolveEnd);
})));
}
return undefined;
})),
// --- AFTER PREACTIVATION ---
switchTap((/**
* @param {?} t
* @return {?}
*/
(t) => {
const { targetSnapshot, id: navigationId, extractedUrl: appliedUrlTree, rawUrl: rawUrlTree, extras: { skipLocationChange, replaceUrl } } = t;
return this.hooks.afterPreactivation((/** @type {?} */ (targetSnapshot)), {
navigationId,
appliedUrlTree,
rawUrlTree,
skipLocationChange: !!skipLocationChange,
replaceUrl: !!replaceUrl,
});
})), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} t
* @return {?}
*/
(t) => {
/** @type {?} */
const targetRouterState = createRouterState(this.routeReuseStrategy, (/** @type {?} */ (t.targetSnapshot)), t.currentRouterState);
return (Object.assign(Object.assign({}, t), { targetRouterState }));
})),
/* Once here, we are about to activate syncronously. The assumption is this
will succeed, and user code may read from the Router service. Therefore
before activation, we need to update router properties storing the current
URL and the RouterState, as well as updated the browser URL. All this should
happen *before* activating. */
Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])((/**
* @param {?} t
* @return {?}
*/
(t) => {
this.currentUrlTree = t.urlAfterRedirects;
this.rawUrlTree =
this.urlHandlingStrategy.merge(this.currentUrlTree, t.rawUrl);
((/** @type {?} */ (this))).routerState = (/** @type {?} */ (t.targetRouterState));
if (this.urlUpdateStrategy === 'deferred') {
if (!t.extras.skipLocationChange) {
this.setBrowserUrl(this.rawUrlTree, !!t.extras.replaceUrl, t.id, t.extras.state);
}
this.browserUrlTree = t.urlAfterRedirects;
}
})), activateRoutes(this.rootContexts, this.routeReuseStrategy, (/**
* @param {?} evt
* @return {?}
*/
(evt) => this.triggerEvent(evt))), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])({
/**
* @return {?}
*/
next() {
completed = true;
},
/**
* @return {?}
*/
complete() {
completed = true;
}
}), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["finalize"])((/**
* @return {?}
*/
() => {
/* When the navigation stream finishes either through error or success, we
* set the `completed` or `errored` flag. However, there are some situations
* where we could get here without either of those being set. For instance, a
* redirect during NavigationStart. Therefore, this is a catch-all to make
* sure the NavigationCancel
* event is fired when a navigation gets cancelled but not caught by other
* means. */
if (!completed && !errored) {
// Must reset to current URL tree here to ensure history.state is set. On a
// fresh page load, if a new navigation comes in before a successful
// navigation completes, there will be nothing in
// history.state.navigationId. This can cause sync problems with AngularJS
// sync code which looks for a value here in order to determine whether or
// not to handle a given popstate event or to leave it to the Angualr
// router.
this.resetUrlToCurrentUrlTree();
/** @type {?} */
const navCancel = new NavigationCancel(t.id, this.serializeUrl(t.extractedUrl), `Navigation ID ${t.id} is not equal to the current navigation id ${this.navigationId}`);
eventsSubject.next(navCancel);
t.resolve(false);
}
// currentNavigation should always be reset to null here. If navigation was
// successful, lastSuccessfulTransition will have already been set. Therefore
// we can safely set currentNavigation to null here.
this.currentNavigation = null;
})), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["catchError"])((/**
* @param {?} e
* @return {?}
*/
(e) => {
errored = true;
/* This error type is issued during Redirect, and is handled as a
* cancellation rather than an error. */
if (isNavigationCancelingError(e)) {
/** @type {?} */
const redirecting = isUrlTree(e.url);
if (!redirecting) {
// Set property only if we're not redirecting. If we landed on a page and
// redirect to `/` route, the new navigation is going to see the `/`
// isn't a change from the default currentUrlTree and won't navigate.
// This is only applicable with initial navigation, so setting
// `navigated` only when not redirecting resolves this scenario.
this.navigated = true;
this.resetStateAndUrl(t.currentRouterState, t.currentUrlTree, t.rawUrl);
}
/** @type {?} */
const navCancel = new NavigationCancel(t.id, this.serializeUrl(t.extractedUrl), e.message);
eventsSubject.next(navCancel);
// When redirecting, we need to delay resolving the navigation
// promise and push it to the redirect navigation
if (!redirecting) {
t.resolve(false);
}
else {
// setTimeout is required so this navigation finishes with
// the return EMPTY below. If it isn't allowed to finish
// processing, there can be multiple navigations to the same
// URL.
setTimeout((/**
* @return {?}
*/
() => {
/** @type {?} */
const mergedTree = this.urlHandlingStrategy.merge(e.url, this.rawUrlTree);
/** @type {?} */
const extras = {
skipLocationChange: t.extras.skipLocationChange,
replaceUrl: this.urlUpdateStrategy === 'eager'
};
return this.scheduleNavigation(mergedTree, 'imperative', null, extras, { resolve: t.resolve, reject: t.reject, promise: t.promise });
}), 0);
}
/* All other errors should reset to the router's internal URL reference to
* the pre-error state. */
}
else {
this.resetStateAndUrl(t.currentRouterState, t.currentUrlTree, t.rawUrl);
/** @type {?} */
const navError = new NavigationError(t.id, this.serializeUrl(t.extractedUrl), e);
eventsSubject.next(navError);
try {
t.resolve(this.errorHandler(e));
}
catch (ee) {
t.reject(ee);
}
}
return rxjs__WEBPACK_IMPORTED_MODULE_2__["EMPTY"];
})));
// TODO(jasonaden): remove cast once g3 is on updated TypeScript
})))))));
}
/**
* \@internal
* TODO: this should be removed once the constructor of the router made internal
* @param {?} rootComponentType
* @return {?}
*/
resetRootComponentType(rootComponentType) {
this.rootComponentType = rootComponentType;
// TODO: vsavkin router 4.0 should make the root component set to null
// this will simplify the lifecycle of the router.
this.routerState.root.component = this.rootComponentType;
}
/**
* @private
* @return {?}
*/
getTransition() {
/** @type {?} */
const transition = this.transitions.value;
// This value needs to be set. Other values such as extractedUrl are set on initial navigation
// but the urlAfterRedirects may not get set if we aren't processing the new URL *and* not
// processing the previous URL.
transition.urlAfterRedirects = this.browserUrlTree;
return transition;
}
/**
* @private
* @param {?} t
* @return {?}
*/
setTransition(t) {
this.transitions.next(Object.assign(Object.assign({}, this.getTransition()), t));
}
/**
* Sets up the location change listener and performs the initial navigation.
* @return {?}
*/
initialNavigation() {
this.setUpLocationChangeListener();
if (this.navigationId === 0) {
this.navigateByUrl(this.location.path(true), { replaceUrl: true });
}
}
/**
* Sets up the location change listener.
* @return {?}
*/
setUpLocationChangeListener() {
// Don't need to use Zone.wrap any more, because zone.js
// already patch onPopState, so location change callback will
// run into ngZone
if (!this.locationSubscription) {
this.locationSubscription = (/** @type {?} */ (this.location.subscribe((/**
* @param {?} change
* @return {?}
*/
(change) => {
/** @type {?} */
let rawUrlTree = this.parseUrl(change['url']);
/** @type {?} */
const source = change['type'] === 'popstate' ? 'popstate' : 'hashchange';
// Navigations coming from Angular router have a navigationId state property. When this
// exists, restore the state.
/** @type {?} */
const state = change.state && change.state.navigationId ? change.state : null;
setTimeout((/**
* @return {?}
*/
() => {
this.scheduleNavigation(rawUrlTree, source, state, { replaceUrl: true });
}), 0);
}))));
}
}
/**
* The current URL.
* @return {?}
*/
get url() {
return this.serializeUrl(this.currentUrlTree);
}
/**
* The current Navigation object if one exists
* @return {?}
*/
getCurrentNavigation() {
return this.currentNavigation;
}
/**
* \@internal
* @param {?} event
* @return {?}
*/
triggerEvent(event) {
((/** @type {?} */ (this.events))).next(event);
}
/**
* Resets the configuration used for navigation and generating links.
*
* \@usageNotes
*
* ```
* router.resetConfig([
* { path: 'team/:id', component: TeamCmp, children: [
* { path: 'simple', component: SimpleCmp },
* { path: 'user/:name', component: UserCmp }
* ]}
* ]);
* ```
* @param {?} config The route array for the new configuration.
*
* @return {?}
*/
resetConfig(config) {
validateConfig(config);
this.config = config.map(standardizeConfig);
this.navigated = false;
this.lastSuccessfulId = -1;
}
/**
* \@docsNotRequired
* @return {?}
*/
ngOnDestroy() {
this.dispose();
}
/**
* Disposes of the router.
* @return {?}
*/
dispose() {
if (this.locationSubscription) {
this.locationSubscription.unsubscribe();
this.locationSubscription = (/** @type {?} */ (null));
}
}
/**
* Applies an array of commands to the current URL tree and creates a new URL tree.
*
* When given an activated route, applies the given commands starting from the route.
* Otherwise, applies the given command starting from the root.
*
* \@usageNotes
*
* ```
* // create /team/33/user/11
* router.createUrlTree(['/team', 33, 'user', 11]);
*
* // create /team/33;expand=true/user/11
* router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);
*
* // you can collapse static segments like this (this works only with the first passed-in value):
* router.createUrlTree(['/team/33/user', userId]);
*
* // If the first segment can contain slashes, and you do not want the router to split it,
* // you can do the following:
* router.createUrlTree([{segmentPath: '/one/two'}]);
*
* // create /team/33/(user/11//right:chat)
* router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);
*
* // remove the right secondary node
* router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
*
* // assuming the current url is `/team/33/user/11` and the route points to `user/11`
*
* // navigate to /team/33/user/11/details
* router.createUrlTree(['details'], {relativeTo: route});
*
* // navigate to /team/33/user/22
* router.createUrlTree(['../22'], {relativeTo: route});
*
* // navigate to /team/44/user/22
* router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});
* ```
* @param {?} commands An array of commands to apply.
* @param {?=} navigationExtras Options that control the navigation strategy. This function
* only utilizes properties in `NavigationExtras` that would change the provided URL.
* @return {?} The new URL tree.
*
*/
createUrlTree(commands, navigationExtras = {}) {
const { relativeTo, queryParams, fragment, preserveQueryParams, queryParamsHandling, preserveFragment } = navigationExtras;
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["isDevMode"])() && preserveQueryParams && (/** @type {?} */ (console)) && (/** @type {?} */ (console.warn))) {
console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
}
/** @type {?} */
const a = relativeTo || this.routerState.root;
/** @type {?} */
const f = preserveFragment ? this.currentUrlTree.fragment : fragment;
/** @type {?} */
let q = null;
if (queryParamsHandling) {
switch (queryParamsHandling) {
case 'merge':
q = Object.assign(Object.assign({}, this.currentUrlTree.queryParams), queryParams);
break;
case 'preserve':
q = this.currentUrlTree.queryParams;
break;
default:
q = queryParams || null;
}
}
else {
q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams || null;
}
if (q !== null) {
q = this.removeEmptyProps(q);
}
return createUrlTree(a, this.currentUrlTree, commands, (/** @type {?} */ (q)), (/** @type {?} */ (f)));
}
/**
* Navigate based on the provided URL, which must be absolute.
*
* \@usageNotes
*
* ```
* router.navigateByUrl("/team/33/user/11");
*
* // Navigate without updating the URL
* router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
* ```
*
* @param {?} url An absolute URL. The function does not apply any delta to the current URL.
* @param {?=} extras An object containing properties that modify the navigation strategy.
* The function ignores any properties in the `NavigationExtras` that would change the
* provided URL.
*
* @return {?} A Promise that resolves to 'true' when navigation succeeds,
* to 'false' when navigation fails, or is rejected on error.
*
*/
navigateByUrl(url, extras = { skipLocationChange: false }) {
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["isDevMode"])() && this.isNgZoneEnabled && !_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"].isInAngularZone()) {
this.console.warn(`Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?`);
}
/** @type {?} */
const urlTree = isUrlTree(url) ? url : this.parseUrl(url);
/** @type {?} */
const mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree);
return this.scheduleNavigation(mergedTree, 'imperative', null, extras);
}
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* \@usageNotes
*
* ```
* router.navigate(['team', 33, 'user', 11], {relativeTo: route});
*
* // Navigate without updating the URL
* router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
* ```
*
* The first parameter of `navigate()` is a delta to be applied to the current URL
* or the one provided in the `relativeTo` property of the second parameter (the
* `NavigationExtras`).
*
* In order to affect this browser's `history.state` entry, the `state`
* parameter can be passed. This must be an object because the router
* will add the `navigationId` property to this object before creating
* the new history item.
* @param {?} commands
* @param {?=} extras
* @return {?}
*/
navigate(commands, extras = { skipLocationChange: false }) {
validateCommands(commands);
return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
}
/**
* Serializes a `UrlTree` into a string
* @param {?} url
* @return {?}
*/
serializeUrl(url) {
return this.urlSerializer.serialize(url);
}
/**
* Parses a string into a `UrlTree`
* @param {?} url
* @return {?}
*/
parseUrl(url) {
/** @type {?} */
let urlTree;
try {
urlTree = this.urlSerializer.parse(url);
}
catch (e) {
urlTree = this.malformedUriErrorHandler(e, this.urlSerializer, url);
}
return urlTree;
}
/**
* Returns whether the url is activated
* @param {?} url
* @param {?} exact
* @return {?}
*/
isActive(url, exact) {
if (isUrlTree(url)) {
return containsTree(this.currentUrlTree, url, exact);
}
/** @type {?} */
const urlTree = this.parseUrl(url);
return containsTree(this.currentUrlTree, urlTree, exact);
}
/**
* @private
* @param {?} params
* @return {?}
*/
removeEmptyProps(params) {
return Object.keys(params).reduce((/**
* @param {?} result
* @param {?} key
* @return {?}
*/
(result, key) => {
/** @type {?} */
const value = params[key];
if (value !== null && value !== undefined) {
result[key] = value;
}
return result;
}), {});
}
/**
* @private
* @return {?}
*/
processNavigations() {
this.navigations.subscribe((/**
* @param {?} t
* @return {?}
*/
t => {
this.navigated = true;
this.lastSuccessfulId = t.id;
((/** @type {?} */ (this.events)))
.next(new NavigationEnd(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(this.currentUrlTree)));
this.lastSuccessfulNavigation = this.currentNavigation;
this.currentNavigation = null;
t.resolve(true);
}), (/**
* @param {?} e
* @return {?}
*/
e => {
this.console.warn(`Unhandled Navigation Error: `);
}));
}
/**
* @private
* @param {?} rawUrl
* @param {?} source
* @param {?} restoredState
* @param {?} extras
* @param {?=} priorPromise
* @return {?}
*/
scheduleNavigation(rawUrl, source, restoredState, extras, priorPromise) {
/** @type {?} */
const lastNavigation = this.getTransition();
// If the user triggers a navigation imperatively (e.g., by using navigateByUrl),
// and that navigation results in 'replaceState' that leads to the same URL,
// we should skip those.
if (lastNavigation && source !== 'imperative' && lastNavigation.source === 'imperative' &&
lastNavigation.rawUrl.toString() === rawUrl.toString()) {
return Promise.resolve(true); // return value is not used
}
// Because of a bug in IE and Edge, the location class fires two events (popstate and
// hashchange) every single time. The second one should be ignored. Otherwise, the URL will
// flicker. Handles the case when a popstate was emitted first.
if (lastNavigation && source == 'hashchange' && lastNavigation.source === 'popstate' &&
lastNavigation.rawUrl.toString() === rawUrl.toString()) {
return Promise.resolve(true); // return value is not used
}
// Because of a bug in IE and Edge, the location class fires two events (popstate and
// hashchange) every single time. The second one should be ignored. Otherwise, the URL will
// flicker. Handles the case when a hashchange was emitted first.
if (lastNavigation && source == 'popstate' && lastNavigation.source === 'hashchange' &&
lastNavigation.rawUrl.toString() === rawUrl.toString()) {
return Promise.resolve(true); // return value is not used
}
/** @type {?} */
let resolve;
/** @type {?} */
let reject;
/** @type {?} */
let promise;
if (priorPromise) {
resolve = priorPromise.resolve;
reject = priorPromise.reject;
promise = priorPromise.promise;
}
else {
promise = new Promise((/**
* @param {?} res
* @param {?} rej
* @return {?}
*/
(res, rej) => {
resolve = res;
reject = rej;
}));
}
/** @type {?} */
const id = ++this.navigationId;
this.setTransition({
id,
source,
restoredState,
currentUrlTree: this.currentUrlTree,
currentRawUrl: this.rawUrlTree,
rawUrl,
extras,
resolve,
reject,
promise,
currentSnapshot: this.routerState.snapshot,
currentRouterState: this.routerState
});
// Make sure that the error is propagated even though `processNavigations` catch
// handler does not rethrow
return promise.catch((/**
* @param {?} e
* @return {?}
*/
(e) => {
return Promise.reject(e);
}));
}
/**
* @private
* @param {?} url
* @param {?} replaceUrl
* @param {?} id
* @param {?=} state
* @return {?}
*/
setBrowserUrl(url, replaceUrl, id, state) {
/** @type {?} */
const path = this.urlSerializer.serialize(url);
state = state || {};
if (this.location.isCurrentPathEqualTo(path) || replaceUrl) {
// TODO(jasonaden): Remove first `navigationId` and rely on `ng` namespace.
this.location.replaceState(path, '', Object.assign(Object.assign({}, state), { navigationId: id }));
}
else {
this.location.go(path, '', Object.assign(Object.assign({}, state), { navigationId: id }));
}
}
/**
* @private
* @param {?} storedState
* @param {?} storedUrl
* @param {?} rawUrl
* @return {?}
*/
resetStateAndUrl(storedState, storedUrl, rawUrl) {
((/** @type {?} */ (this))).routerState = storedState;
this.currentUrlTree = storedUrl;
this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, rawUrl);
this.resetUrlToCurrentUrlTree();
}
/**
* @private
* @return {?}
*/
resetUrlToCurrentUrlTree() {
this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree), '', { navigationId: this.lastSuccessfulId });
}
}
Router.ɵfac = function Router_Factory(t) { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinvalidFactory"](); };
Router.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({ type: Router });
if (false) {}
/**
* @param {?} commands
* @return {?}
*/
function validateCommands(commands) {
for (let i = 0; i < commands.length; i++) {
/** @type {?} */
const cmd = commands[i];
if (cmd == null) {
throw new Error(`The requested path contains ${cmd} segment at index ${i}`);
}
}
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/directives/router_link.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@description
*
* Lets you link to specific routes in your app.
*
* Consider the following route configuration:
* `[{ path: 'user/:name', component: UserCmp }]`.
* When linking to this `user/:name` route, you use the `RouterLink` directive.
*
* If the link is static, you can use the directive as follows:
* `<a routerLink="/user/bob">link to user component</a>`
*
* If you use dynamic values to generate the link, you can pass an array of path
* segments, followed by the params for each segment.
*
* For instance `['/team', teamId, 'user', userName, {details: true}]`
* means that we want to generate a link to `/team/11/user/bob;details=true`.
*
* Multiple static segments can be merged into one
* (e.g., `['/team/11/user', userName, {details: true}]`).
*
* The first segment name can be prepended with `/`, `./`, or `../`:
* * If the first segment begins with `/`, the router will look up the route from the root of the
* app.
* * If the first segment begins with `./`, or doesn't begin with a slash, the router will
* instead look in the children of the current activated route.
* * And if the first segment begins with `../`, the router will go up one level.
*
* You can set query params and fragment as follows:
*
* ```
* <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
* link to user component
* </a>
* ```
* RouterLink will use these to generate this link: `/user/bob#education?debug=true`.
*
* (Deprecated in v4.0.0 use `queryParamsHandling` instead) You can also tell the
* directive to preserve the current query params and fragment:
*
* ```
* <a [routerLink]="['/user/bob']" preserveQueryParams preserveFragment>
* link to user component
* </a>
* ```
*
* You can tell the directive how to handle queryParams. Available options are:
* - `'merge'`: merge the queryParams into the current queryParams
* - `'preserve'`: preserve the current queryParams
* - default/`''`: use the queryParams only
*
* Same options for {\@link NavigationExtras#queryParamsHandling
* NavigationExtras#queryParamsHandling}.
*
* ```
* <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge">
* link to user component
* </a>
* ```
*
* You can provide a `state` value to be persisted to the browser's History.state
* property (See https://developer.mozilla.org/en-US/docs/Web/API/History#Properties). It's
* used as follows:
*
* ```
* <a [routerLink]="['/user/bob']" [state]="{tracingId: 123}">
* link to user component
* </a>
* ```
*
* And later the value can be read from the router through `router.getCurrentNavigation`.
* For example, to capture the `tracingId` above during the `NavigationStart` event:
*
* ```
* // Get NavigationStart events
* router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => {
* const navigation = router.getCurrentNavigation();
* tracingService.trace({id: navigation.extras.state.tracingId});
* });
* ```
*
* The router link directive always treats the provided input as a delta to the current url.
*
* For instance, if the current url is `/user/(box//aux:team)`.
*
* Then the following link `<a [routerLink]="['/user/jim']">Jim</a>` will generate the link
* `/user/(jim//aux:team)`.
*
* See {\@link Router#createUrlTree createUrlTree} for more information.
*
* \@ngModule RouterModule
*
* \@publicApi
*/
class RouterLink {
/**
* @param {?} router
* @param {?} route
* @param {?} tabIndex
* @param {?} renderer
* @param {?} el
*/
constructor(router, route, tabIndex, renderer, el) {
this.router = router;
this.route = route;
this.commands = [];
if (tabIndex == null) {
renderer.setAttribute(el.nativeElement, 'tabindex', '0');
}
}
/**
* @see {\@link Router#createUrlTree Router#createUrlTree}
* @param {?} commands An array of commands to pass to {\@link Router#createUrlTree
* Router#createUrlTree}.
* - **array**: commands to pass to {\@link Router#createUrlTree Router#createUrlTree}.
* - **string**: shorthand for array of commands with just the string, i.e. `['/route']`
* - **null|undefined**: shorthand for an empty array of commands, i.e. `[]`
* @return {?}
*/
set routerLink(commands) {
if (commands != null) {
this.commands = Array.isArray(commands) ? commands : [commands];
}
else {
this.commands = [];
}
}
/**
* @deprecated As of Angular v4.0 use `queryParamsHandling` instead.
* @param {?} value
* @return {?}
*/
set preserveQueryParams(value) {
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["isDevMode"])() && (/** @type {?} */ (console)) && (/** @type {?} */ (console.warn))) {
console.warn('preserveQueryParams is deprecated!, use queryParamsHandling instead.');
}
this.preserve = value;
}
/**
* @return {?}
*/
onClick() {
/** @type {?} */
const extras = {
skipLocationChange: attrBoolValue(this.skipLocationChange),
replaceUrl: attrBoolValue(this.replaceUrl),
state: this.state,
};
this.router.navigateByUrl(this.urlTree, extras);
return true;
}
/**
* @return {?}
*/
get urlTree() {
return this.router.createUrlTree(this.commands, {
relativeTo: this.route,
queryParams: this.queryParams,
fragment: this.fragment,
preserveQueryParams: attrBoolValue(this.preserve),
queryParamsHandling: this.queryParamsHandling,
preserveFragment: attrBoolValue(this.preserveFragment),
});
}
}
RouterLink.ɵfac = function RouterLink_Factory(t) { return new (t || RouterLink)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](Router), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](ActivatedRoute), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinjectAttribute"]('tabindex'), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["Renderer2"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["ElementRef"])); };
RouterLink.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({ type: RouterLink, selectors: [["", "routerLink", "", 5, "a", 5, "area"]], hostBindings: function RouterLink_HostBindings(rf, ctx) { if (rf & 1) {
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵlistener"]("click", function RouterLink_click_HostBindingHandler() { return ctx.onClick(); });
} }, inputs: { routerLink: "routerLink", preserveQueryParams: "preserveQueryParams", queryParams: "queryParams", fragment: "fragment", queryParamsHandling: "queryParamsHandling", preserveFragment: "preserveFragment", skipLocationChange: "skipLocationChange", replaceUrl: "replaceUrl", state: "state" } });
/** @nocollapse */
RouterLink.ctorParameters = () => [
{ type: Router },
{ type: ActivatedRoute },
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Attribute"], args: ['tabindex',] }] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Renderer2"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ElementRef"] }
];
RouterLink.propDecorators = {
queryParams: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
fragment: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
queryParamsHandling: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
preserveFragment: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
skipLocationChange: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
replaceUrl: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
state: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
routerLink: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
preserveQueryParams: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
onClick: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["HostListener"], args: ['click',] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](RouterLink, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Directive"],
args: [{ selector: ':not(a):not(area)[routerLink]' }]
}], function () { return [{ type: Router }, { type: ActivatedRoute }, { type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Attribute"],
args: ['tabindex']
}] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Renderer2"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ElementRef"] }]; }, { routerLink: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], preserveQueryParams: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], onClick: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["HostListener"],
args: ['click']
}], queryParams: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], fragment: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], queryParamsHandling: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], preserveFragment: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], skipLocationChange: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], replaceUrl: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], state: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}] }); })();
if (false) {}
/**
* \@description
*
* Lets you link to specific routes in your app.
*
* See `RouterLink` for more information.
*
* \@ngModule RouterModule
*
* \@publicApi
*/
class RouterLinkWithHref {
/**
* @param {?} router
* @param {?} route
* @param {?} locationStrategy
*/
constructor(router, route, locationStrategy) {
this.router = router;
this.route = route;
this.locationStrategy = locationStrategy;
this.commands = [];
this.subscription = router.events.subscribe((/**
* @param {?} s
* @return {?}
*/
(s) => {
if (s instanceof NavigationEnd) {
this.updateTargetUrlAndHref();
}
}));
}
/**
* @see {\@link Router#createUrlTree Router#createUrlTree}
* @param {?} commands An array of commands to pass to {\@link Router#createUrlTree
* Router#createUrlTree}.
* - **array**: commands to pass to {\@link Router#createUrlTree Router#createUrlTree}.
* - **string**: shorthand for array of commands with just the string, i.e. `['/route']`
* - **null|undefined**: shorthand for an empty array of commands, i.e. `[]`
* @return {?}
*/
set routerLink(commands) {
if (commands != null) {
this.commands = Array.isArray(commands) ? commands : [commands];
}
else {
this.commands = [];
}
}
/**
* @deprecated As of Angular v4.0 use `queryParamsHandling` instead.
* @param {?} value
* @return {?}
*/
set preserveQueryParams(value) {
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["isDevMode"])() && (/** @type {?} */ (console)) && (/** @type {?} */ (console.warn))) {
console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
}
this.preserve = value;
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
this.updateTargetUrlAndHref();
}
/**
* @return {?}
*/
ngOnDestroy() {
this.subscription.unsubscribe();
}
/**
* @param {?} button
* @param {?} ctrlKey
* @param {?} metaKey
* @param {?} shiftKey
* @return {?}
*/
onClick(button, ctrlKey, metaKey, shiftKey) {
if (button !== 0 || ctrlKey || metaKey || shiftKey) {
return true;
}
if (typeof this.target === 'string' && this.target != '_self') {
return true;
}
/** @type {?} */
const extras = {
skipLocationChange: attrBoolValue(this.skipLocationChange),
replaceUrl: attrBoolValue(this.replaceUrl),
state: this.state
};
this.router.navigateByUrl(this.urlTree, extras);
return false;
}
/**
* @private
* @return {?}
*/
updateTargetUrlAndHref() {
this.href = this.locationStrategy.prepareExternalUrl(this.router.serializeUrl(this.urlTree));
}
/**
* @return {?}
*/
get urlTree() {
return this.router.createUrlTree(this.commands, {
relativeTo: this.route,
queryParams: this.queryParams,
fragment: this.fragment,
preserveQueryParams: attrBoolValue(this.preserve),
queryParamsHandling: this.queryParamsHandling,
preserveFragment: attrBoolValue(this.preserveFragment),
});
}
}
RouterLinkWithHref.ɵfac = function RouterLinkWithHref_Factory(t) { return new (t || RouterLinkWithHref)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](Router), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](ActivatedRoute), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__["LocationStrategy"])); };
RouterLinkWithHref.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({ type: RouterLinkWithHref, selectors: [["a", "routerLink", ""], ["area", "routerLink", ""]], hostVars: 2, hostBindings: function RouterLinkWithHref_HostBindings(rf, ctx) { if (rf & 1) {
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵlistener"]("click", function RouterLinkWithHref_click_HostBindingHandler($event) { return ctx.onClick($event.button, $event.ctrlKey, $event.metaKey, $event.shiftKey); });
} if (rf & 2) {
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵhostProperty"]("href", ctx.href, _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵsanitizeUrl"]);
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵattribute"]("target", ctx.target);
} }, inputs: { routerLink: "routerLink", preserveQueryParams: "preserveQueryParams", target: "target", queryParams: "queryParams", fragment: "fragment", queryParamsHandling: "queryParamsHandling", preserveFragment: "preserveFragment", skipLocationChange: "skipLocationChange", replaceUrl: "replaceUrl", state: "state" }, features: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵNgOnChangesFeature"]] });
/** @nocollapse */
RouterLinkWithHref.ctorParameters = () => [
{ type: Router },
{ type: ActivatedRoute },
{ type: _angular_common__WEBPACK_IMPORTED_MODULE_0__["LocationStrategy"] }
];
RouterLinkWithHref.propDecorators = {
target: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["HostBinding"], args: ['attr.target',] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
queryParams: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
fragment: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
queryParamsHandling: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
preserveFragment: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
skipLocationChange: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
replaceUrl: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
state: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
href: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["HostBinding"] }],
routerLink: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
preserveQueryParams: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
onClick: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["HostListener"], args: ['click', ['$event.button', '$event.ctrlKey', '$event.metaKey', '$event.shiftKey'],] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](RouterLinkWithHref, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Directive"],
args: [{ selector: 'a[routerLink],area[routerLink]' }]
}], function () { return [{ type: Router }, { type: ActivatedRoute }, { type: _angular_common__WEBPACK_IMPORTED_MODULE_0__["LocationStrategy"] }]; }, { routerLink: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], preserveQueryParams: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], onClick: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["HostListener"],
args: ['click', ['$event.button', '$event.ctrlKey', '$event.metaKey', '$event.shiftKey']]
}], href: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["HostBinding"]
}], target: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["HostBinding"],
args: ['attr.target']
}, {
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], queryParams: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], fragment: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], queryParamsHandling: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], preserveFragment: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], skipLocationChange: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], replaceUrl: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], state: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}] }); })();
if (false) {}
/**
* @param {?} s
* @return {?}
*/
function attrBoolValue(s) {
return s === '' || !!s;
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/directives/router_link_active.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
*
* \@description
*
* Lets you add a CSS class to an element when the link's route becomes active.
*
* This directive lets you add a CSS class to an element when the link's route
* becomes active.
*
* Consider the following example:
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
* ```
*
* When the url is either '/user' or '/user/bob', the active-link class will
* be added to the `a` tag. If the url changes, the class will be removed.
*
* You can set more than one class, as follows:
*
* ```
* <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
* <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
* ```
*
* You can configure RouterLinkActive by passing `exact: true`. This will add the classes
* only when the url matches the link exactly.
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
* true}">Bob</a>
* ```
*
* You can assign the RouterLinkActive instance to a template variable and directly check
* the `isActive` status.
* ```
* <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
* Bob {{ rla.isActive ? '(already open)' : ''}}
* </a>
* ```
*
* Finally, you can apply the RouterLinkActive directive to an ancestor of a RouterLink.
*
* ```
* <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
* <a routerLink="/user/jim">Jim</a>
* <a routerLink="/user/bob">Bob</a>
* </div>
* ```
*
* This will set the active-link class on the div tag if the url is either '/user/jim' or
* '/user/bob'.
*
* \@ngModule RouterModule
*
* \@publicApi
*/
class RouterLinkActive {
/**
* @param {?} router
* @param {?} element
* @param {?} renderer
* @param {?=} link
* @param {?=} linkWithHref
*/
constructor(router, element, renderer, link, linkWithHref) {
this.router = router;
this.element = element;
this.renderer = renderer;
this.link = link;
this.linkWithHref = linkWithHref;
this.classes = [];
this.isActive = false;
this.routerLinkActiveOptions = { exact: false };
this.subscription = router.events.subscribe((/**
* @param {?} s
* @return {?}
*/
(s) => {
if (s instanceof NavigationEnd) {
this.update();
}
}));
}
/**
* @return {?}
*/
ngAfterContentInit() {
this.links.changes.subscribe((/**
* @param {?} _
* @return {?}
*/
_ => this.update()));
this.linksWithHrefs.changes.subscribe((/**
* @param {?} _
* @return {?}
*/
_ => this.update()));
this.update();
}
/**
* @param {?} data
* @return {?}
*/
set routerLinkActive(data) {
/** @type {?} */
const classes = Array.isArray(data) ? data : data.split(' ');
this.classes = classes.filter((/**
* @param {?} c
* @return {?}
*/
c => !!c));
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
this.update();
}
/**
* @return {?}
*/
ngOnDestroy() {
this.subscription.unsubscribe();
}
/**
* @private
* @return {?}
*/
update() {
if (!this.links || !this.linksWithHrefs || !this.router.navigated)
return;
Promise.resolve().then((/**
* @return {?}
*/
() => {
/** @type {?} */
const hasActiveLinks = this.hasActiveLinks();
if (this.isActive !== hasActiveLinks) {
((/** @type {?} */ (this))).isActive = hasActiveLinks;
this.classes.forEach((/**
* @param {?} c
* @return {?}
*/
(c) => {
if (hasActiveLinks) {
this.renderer.addClass(this.element.nativeElement, c);
}
else {
this.renderer.removeClass(this.element.nativeElement, c);
}
}));
}
}));
}
/**
* @private
* @param {?} router
* @return {?}
*/
isLinkActive(router) {
return (/**
* @param {?} link
* @return {?}
*/
(link) => router.isActive(link.urlTree, this.routerLinkActiveOptions.exact));
}
/**
* @private
* @return {?}
*/
hasActiveLinks() {
/** @type {?} */
const isActiveCheckFn = this.isLinkActive(this.router);
return this.link && isActiveCheckFn(this.link) ||
this.linkWithHref && isActiveCheckFn(this.linkWithHref) ||
this.links.some(isActiveCheckFn) || this.linksWithHrefs.some(isActiveCheckFn);
}
}
RouterLinkActive.ɵfac = function RouterLinkActive_Factory(t) { return new (t || RouterLinkActive)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](Router), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["ElementRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["Renderer2"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](RouterLink, 8), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](RouterLinkWithHref, 8)); };
RouterLinkActive.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({ type: RouterLinkActive, selectors: [["", "routerLinkActive", ""]], contentQueries: function RouterLinkActive_ContentQueries(rf, ctx, dirIndex) { if (rf & 1) {
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵcontentQuery"](dirIndex, RouterLink, true);
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵcontentQuery"](dirIndex, RouterLinkWithHref, true);
} if (rf & 2) {
var _t;
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵloadQuery"]()) && (ctx.links = _t);
_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵloadQuery"]()) && (ctx.linksWithHrefs = _t);
} }, inputs: { routerLinkActiveOptions: "routerLinkActiveOptions", routerLinkActive: "routerLinkActive" }, exportAs: ["routerLinkActive"], features: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵNgOnChangesFeature"]] });
/** @nocollapse */
RouterLinkActive.ctorParameters = () => [
{ type: Router },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ElementRef"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Renderer2"] },
{ type: RouterLink, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"] }] },
{ type: RouterLinkWithHref, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"] }] }
];
RouterLinkActive.propDecorators = {
links: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ContentChildren"], args: [RouterLink, { descendants: true },] }],
linksWithHrefs: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ContentChildren"], args: [RouterLinkWithHref, { descendants: true },] }],
routerLinkActiveOptions: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }],
routerLinkActive: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](RouterLinkActive, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Directive"],
args: [{
selector: '[routerLinkActive]',
exportAs: 'routerLinkActive'
}]
}], function () { return [{ type: Router }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ElementRef"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Renderer2"] }, { type: RouterLink, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"]
}] }, { type: RouterLinkWithHref, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"]
}] }]; }, { routerLinkActiveOptions: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], routerLinkActive: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Input"]
}], links: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ContentChildren"],
args: [RouterLink, { descendants: true }]
}], linksWithHrefs: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ContentChildren"],
args: [RouterLinkWithHref, { descendants: true }]
}] }); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/router_outlet_context.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Store contextual information about a `RouterOutlet`
*
* \@publicApi
*/
class OutletContext {
constructor() {
this.outlet = null;
this.route = null;
this.resolver = null;
this.children = new ChildrenOutletContexts();
this.attachRef = null;
}
}
if (false) {}
/**
* Store contextual information about the children (= nested) `RouterOutlet`
*
* \@publicApi
*/
class ChildrenOutletContexts {
constructor() {
// contexts for child outlets, by name.
this.contexts = new Map();
}
/**
* Called when a `RouterOutlet` directive is instantiated
* @param {?} childName
* @param {?} outlet
* @return {?}
*/
onChildOutletCreated(childName, outlet) {
/** @type {?} */
const context = this.getOrCreateContext(childName);
context.outlet = outlet;
this.contexts.set(childName, context);
}
/**
* Called when a `RouterOutlet` directive is destroyed.
* We need to keep the context as the outlet could be destroyed inside a NgIf and might be
* re-created later.
* @param {?} childName
* @return {?}
*/
onChildOutletDestroyed(childName) {
/** @type {?} */
const context = this.getContext(childName);
if (context) {
context.outlet = null;
}
}
/**
* Called when the corresponding route is deactivated during navigation.
* Because the component get destroyed, all children outlet are destroyed.
* @return {?}
*/
onOutletDeactivated() {
/** @type {?} */
const contexts = this.contexts;
this.contexts = new Map();
return contexts;
}
/**
* @param {?} contexts
* @return {?}
*/
onOutletReAttached(contexts) {
this.contexts = contexts;
}
/**
* @param {?} childName
* @return {?}
*/
getOrCreateContext(childName) {
/** @type {?} */
let context = this.getContext(childName);
if (!context) {
context = new OutletContext();
this.contexts.set(childName, context);
}
return context;
}
/**
* @param {?} childName
* @return {?}
*/
getContext(childName) {
return this.contexts.get(childName) || null;
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/directives/router_outlet.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@description
*
* Acts as a placeholder that Angular dynamically fills based on the current router state.
*
* Each outlet can have a unique name, determined by the optional `name` attribute.
* The name cannot be set or changed dynamically. If not set, default value is "primary".
*
* ```
* <router-outlet></router-outlet>
* <router-outlet name='left'></router-outlet>
* <router-outlet name='right'></router-outlet>
* ```
*
* A router outlet emits an activate event when a new component is instantiated,
* and a deactivate event when a component is destroyed.
*
* ```
* <router-outlet
* (activate)='onActivate($event)'
* (deactivate)='onDeactivate($event)'></router-outlet>
* ```
* \@ngModule RouterModule
*
* \@publicApi
*/
class RouterOutlet {
/**
* @param {?} parentContexts
* @param {?} location
* @param {?} resolver
* @param {?} name
* @param {?} changeDetector
*/
constructor(parentContexts, location, resolver, name, changeDetector) {
this.parentContexts = parentContexts;
this.location = location;
this.resolver = resolver;
this.changeDetector = changeDetector;
this.activated = null;
this._activatedRoute = null;
this.activateEvents = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["EventEmitter"]();
this.deactivateEvents = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["EventEmitter"]();
this.name = name || PRIMARY_OUTLET;
parentContexts.onChildOutletCreated(this.name, this);
}
/**
* @return {?}
*/
ngOnDestroy() {
this.parentContexts.onChildOutletDestroyed(this.name);
}
/**
* @return {?}
*/
ngOnInit() {
if (!this.activated) {
// If the outlet was not instantiated at the time the route got activated we need to populate
// the outlet when it is initialized (ie inside a NgIf)
/** @type {?} */
const context = this.parentContexts.getContext(this.name);
if (context && context.route) {
if (context.attachRef) {
// `attachRef` is populated when there is an existing component to mount
this.attach(context.attachRef, context.route);
}
else {
// otherwise the component defined in the configuration is created
this.activateWith(context.route, context.resolver || null);
}
}
}
}
/**
* @return {?}
*/
get isActivated() {
return !!this.activated;
}
/**
* @return {?}
*/
get component() {
if (!this.activated)
throw new Error('Outlet is not activated');
return this.activated.instance;
}
/**
* @return {?}
*/
get activatedRoute() {
if (!this.activated)
throw new Error('Outlet is not activated');
return (/** @type {?} */ (this._activatedRoute));
}
/**
* @return {?}
*/
get activatedRouteData() {
if (this._activatedRoute) {
return this._activatedRoute.snapshot.data;
}
return {};
}
/**
* Called when the `RouteReuseStrategy` instructs to detach the subtree
* @return {?}
*/
detach() {
if (!this.activated)
throw new Error('Outlet is not activated');
this.location.detach();
/** @type {?} */
const cmp = this.activated;
this.activated = null;
this._activatedRoute = null;
return cmp;
}
/**
* Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree
* @param {?} ref
* @param {?} activatedRoute
* @return {?}
*/
attach(ref, activatedRoute) {
this.activated = ref;
this._activatedRoute = activatedRoute;
this.location.insert(ref.hostView);
}
/**
* @return {?}
*/
deactivate() {
if (this.activated) {
/** @type {?} */
const c = this.component;
this.activated.destroy();
this.activated = null;
this._activatedRoute = null;
this.deactivateEvents.emit(c);
}
}
/**
* @param {?} activatedRoute
* @param {?} resolver
* @return {?}
*/
activateWith(activatedRoute, resolver) {
if (this.isActivated) {
throw new Error('Cannot activate an already activated outlet');
}
this._activatedRoute = activatedRoute;
/** @type {?} */
const snapshot = activatedRoute._futureSnapshot;
/** @type {?} */
const component = (/** @type {?} */ ((/** @type {?} */ (snapshot.routeConfig)).component));
resolver = resolver || this.resolver;
/** @type {?} */
const factory = resolver.resolveComponentFactory(component);
/** @type {?} */
const childContexts = this.parentContexts.getOrCreateContext(this.name).children;
/** @type {?} */
const injector = new OutletInjector(activatedRoute, childContexts, this.location.injector);
this.activated = this.location.createComponent(factory, this.location.length, injector);
// Calling `markForCheck` to make sure we will run the change detection when the
// `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component.
this.changeDetector.markForCheck();
this.activateEvents.emit(this.activated.instance);
}
}
RouterOutlet.ɵfac = function RouterOutlet_Factory(t) { return new (t || RouterOutlet)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](ChildrenOutletContexts), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["ComponentFactoryResolver"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinjectAttribute"]('name'), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["ChangeDetectorRef"])); };
RouterOutlet.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({ type: RouterOutlet, selectors: [["router-outlet"]], outputs: { activateEvents: "activate", deactivateEvents: "deactivate" }, exportAs: ["outlet"] });
/** @nocollapse */
RouterOutlet.ctorParameters = () => [
{ type: ChildrenOutletContexts },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ComponentFactoryResolver"] },
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Attribute"], args: ['name',] }] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ChangeDetectorRef"] }
];
RouterOutlet.propDecorators = {
activateEvents: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Output"], args: ['activate',] }],
deactivateEvents: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Output"], args: ['deactivate',] }]
};
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](RouterOutlet, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Directive"],
args: [{ selector: 'router-outlet', exportAs: 'outlet' }]
}], function () { return [{ type: ChildrenOutletContexts }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ComponentFactoryResolver"] }, { type: String, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Attribute"],
args: ['name']
}] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ChangeDetectorRef"] }]; }, { activateEvents: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Output"],
args: ['activate']
}], deactivateEvents: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Output"],
args: ['deactivate']
}] }); })();
if (false) {}
class OutletInjector {
/**
* @param {?} route
* @param {?} childContexts
* @param {?} parent
*/
constructor(route, childContexts, parent) {
this.route = route;
this.childContexts = childContexts;
this.parent = parent;
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
get(token, notFoundValue) {
if (token === ActivatedRoute) {
return this.route;
}
if (token === ChildrenOutletContexts) {
return this.childContexts;
}
return this.parent.get(token, notFoundValue);
}
}
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/router_preloader.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@description
*
* Provides a preloading strategy.
*
* \@publicApi
* @abstract
*/
class PreloadingStrategy {
}
if (false) {}
/**
* \@description
*
* Provides a preloading strategy that preloads all modules as quickly as possible.
*
* ```
* RouteModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})
* ```
*
* \@publicApi
*/
class PreloadAllModules {
/**
* @param {?} route
* @param {?} fn
* @return {?}
*/
preload(route, fn) {
return fn().pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["catchError"])((/**
* @return {?}
*/
() => Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(null))));
}
}
/**
* \@description
*
* Provides a preloading strategy that does not preload any modules.
*
* This strategy is enabled by default.
*
* \@publicApi
*/
class NoPreloading {
/**
* @param {?} route
* @param {?} fn
* @return {?}
*/
preload(route, fn) {
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(null);
}
}
/**
* The preloader optimistically loads all router configurations to
* make navigations into lazily-loaded sections of the application faster.
*
* The preloader runs in the background. When the router bootstraps, the preloader
* starts listening to all navigation events. After every such event, the preloader
* will check if any configurations can be loaded lazily.
*
* If a route is protected by `canLoad` guards, the preloaded will not load it.
*
* \@publicApi
*/
class RouterPreloader {
/**
* @param {?} router
* @param {?} moduleLoader
* @param {?} compiler
* @param {?} injector
* @param {?} preloadingStrategy
*/
constructor(router, moduleLoader, compiler, injector, preloadingStrategy) {
this.router = router;
this.injector = injector;
this.preloadingStrategy = preloadingStrategy;
/** @type {?} */
const onStartLoad = (/**
* @param {?} r
* @return {?}
*/
(r) => router.triggerEvent(new RouteConfigLoadStart(r)));
/** @type {?} */
const onEndLoad = (/**
* @param {?} r
* @return {?}
*/
(r) => router.triggerEvent(new RouteConfigLoadEnd(r)));
this.loader = new RouterConfigLoader(moduleLoader, compiler, onStartLoad, onEndLoad);
}
/**
* @return {?}
*/
setUpPreloading() {
this.subscription =
this.router.events
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["filter"])((/**
* @param {?} e
* @return {?}
*/
(e) => e instanceof NavigationEnd)), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["concatMap"])((/**
* @return {?}
*/
() => this.preload())))
.subscribe((/**
* @return {?}
*/
() => { }));
}
/**
* @return {?}
*/
preload() {
/** @type {?} */
const ngModule = this.injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModuleRef"]);
return this.processRoutes(ngModule, this.router.config);
}
// TODO(jasonaden): This class relies on code external to the class to call setUpPreloading. If
// this hasn't been done, ngOnDestroy will fail as this.subscription will be undefined. This
// should be refactored.
/**
* @return {?}
*/
ngOnDestroy() {
this.subscription.unsubscribe();
}
/**
* @private
* @param {?} ngModule
* @param {?} routes
* @return {?}
*/
processRoutes(ngModule, routes) {
/** @type {?} */
const res = [];
for (const route of routes) {
// we already have the config loaded, just recurse
if (route.loadChildren && !route.canLoad && route._loadedConfig) {
/** @type {?} */
const childConfig = route._loadedConfig;
res.push(this.processRoutes(childConfig.module, childConfig.routes));
// no config loaded, fetch the config
}
else if (route.loadChildren && !route.canLoad) {
res.push(this.preloadConfig(ngModule, route));
// recurse into children
}
else if (route.children) {
res.push(this.processRoutes(ngModule, route.children));
}
}
return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["from"])(res).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeAll"])(), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])((/**
* @param {?} _
* @return {?}
*/
(_) => void 0)));
}
/**
* @private
* @param {?} ngModule
* @param {?} route
* @return {?}
*/
preloadConfig(ngModule, route) {
return this.preloadingStrategy.preload(route, (/**
* @return {?}
*/
() => {
/** @type {?} */
const loaded$ = this.loader.load(ngModule.injector, route);
return loaded$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mergeMap"])((/**
* @param {?} config
* @return {?}
*/
(config) => {
route._loadedConfig = config;
return this.processRoutes(config.module, config.routes);
})));
}));
}
}
RouterPreloader.ɵfac = function RouterPreloader_Factory(t) { return new (t || RouterPreloader)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](Router), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModuleFactoryLoader"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["Compiler"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["Injector"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](PreloadingStrategy)); };
RouterPreloader.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: RouterPreloader, factory: RouterPreloader.ɵfac });
/** @nocollapse */
RouterPreloader.ctorParameters = () => [
{ type: Router },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModuleFactoryLoader"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Compiler"] },
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injector"] },
{ type: PreloadingStrategy }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](RouterPreloader, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return [{ type: Router }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModuleFactoryLoader"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Compiler"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injector"] }, { type: PreloadingStrategy }]; }, null); })();
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/router_scroller.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class RouterScroller {
/**
* @param {?} router
* @param {?} viewportScroller
* @param {?=} options
*/
constructor(router, viewportScroller, options = {}) {
this.router = router;
this.viewportScroller = viewportScroller;
this.options = options;
this.lastId = 0;
this.lastSource = 'imperative';
this.restoredId = 0;
this.store = {};
// Default both options to 'disabled'
options.scrollPositionRestoration = options.scrollPositionRestoration || 'disabled';
options.anchorScrolling = options.anchorScrolling || 'disabled';
}
/**
* @return {?}
*/
init() {
// we want to disable the automatic scrolling because having two places
// responsible for scrolling results race conditions, especially given
// that browser don't implement this behavior consistently
if (this.options.scrollPositionRestoration !== 'disabled') {
this.viewportScroller.setHistoryScrollRestoration('manual');
}
this.routerEventsSubscription = this.createScrollEvents();
this.scrollEventsSubscription = this.consumeScrollEvents();
}
/**
* @private
* @return {?}
*/
createScrollEvents() {
return this.router.events.subscribe((/**
* @param {?} e
* @return {?}
*/
e => {
if (e instanceof NavigationStart) {
// store the scroll position of the current stable navigations.
this.store[this.lastId] = this.viewportScroller.getScrollPosition();
this.lastSource = e.navigationTrigger;
this.restoredId = e.restoredState ? e.restoredState.navigationId : 0;
}
else if (e instanceof NavigationEnd) {
this.lastId = e.id;
this.scheduleScrollEvent(e, this.router.parseUrl(e.urlAfterRedirects).fragment);
}
}));
}
/**
* @private
* @return {?}
*/
consumeScrollEvents() {
return this.router.events.subscribe((/**
* @param {?} e
* @return {?}
*/
e => {
if (!(e instanceof Scroll))
return;
// a popstate event. The pop state event will always ignore anchor scrolling.
if (e.position) {
if (this.options.scrollPositionRestoration === 'top') {
this.viewportScroller.scrollToPosition([0, 0]);
}
else if (this.options.scrollPositionRestoration === 'enabled') {
this.viewportScroller.scrollToPosition(e.position);
}
// imperative navigation "forward"
}
else {
if (e.anchor && this.options.anchorScrolling === 'enabled') {
this.viewportScroller.scrollToAnchor(e.anchor);
}
else if (this.options.scrollPositionRestoration !== 'disabled') {
this.viewportScroller.scrollToPosition([0, 0]);
}
}
}));
}
/**
* @private
* @param {?} routerEvent
* @param {?} anchor
* @return {?}
*/
scheduleScrollEvent(routerEvent, anchor) {
this.router.triggerEvent(new Scroll(routerEvent, this.lastSource === 'popstate' ? this.store[this.restoredId] : null, anchor));
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this.routerEventsSubscription) {
this.routerEventsSubscription.unsubscribe();
}
if (this.scrollEventsSubscription) {
this.scrollEventsSubscription.unsubscribe();
}
}
}
RouterScroller.ɵfac = function RouterScroller_Factory(t) { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinvalidFactory"](); };
RouterScroller.ɵdir = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({ type: RouterScroller });
if (false) {}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/router_module.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* The directives defined in the `RouterModule`.
* @type {?}
*/
const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive, ɵEmptyOutletComponent];
/**
* A [DI token](guide/glossary/#di-token) for the router service.
*
* \@publicApi
* @type {?}
*/
const ROUTER_CONFIGURATION = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["InjectionToken"]('ROUTER_CONFIGURATION');
/**
* \@docsNotRequired
* @type {?}
*/
const ROUTER_FORROOT_GUARD = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["InjectionToken"]('ROUTER_FORROOT_GUARD');
const ɵ0 = { enableTracing: false };
/** @type {?} */
const ROUTER_PROVIDERS = [
_angular_common__WEBPACK_IMPORTED_MODULE_0__["Location"],
{ provide: UrlSerializer, useClass: DefaultUrlSerializer },
{
provide: Router,
useFactory: setupRouter,
deps: [
UrlSerializer, ChildrenOutletContexts, _angular_common__WEBPACK_IMPORTED_MODULE_0__["Location"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injector"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModuleFactoryLoader"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["Compiler"],
ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"]()],
[RouteReuseStrategy, new _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"]()]
]
},
ChildrenOutletContexts,
{ provide: ActivatedRoute, useFactory: rootRoute, deps: [Router] },
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModuleFactoryLoader"], useClass: _angular_core__WEBPACK_IMPORTED_MODULE_1__["SystemJsNgModuleLoader"] },
RouterPreloader,
NoPreloading,
PreloadAllModules,
{ provide: ROUTER_CONFIGURATION, useValue: ɵ0 },
];
/**
* @return {?}
*/
function routerNgProbeToken() {
return new _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgProbeToken"]('Router', Router);
}
/**
* \@usageNotes
*
* RouterModule can be imported multiple times: once per lazily-loaded bundle.
* Since the router deals with a global shared resource--location, we cannot have
* more than one router service active.
*
* That is why there are two ways to create the module: `RouterModule.forRoot` and
* `RouterModule.forChild`.
*
* * `forRoot` creates a module that contains all the directives, the given routes, and the router
* service itself.
* * `forChild` creates a module that contains all the directives and the given routes, but does not
* include the router service.
*
* When registered at the root, the module should be used as follows
*
* ```
* \@NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* For submodules and lazy loaded submodules the module should be used as follows:
*
* ```
* \@NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* \@description
*
* Adds router directives and providers.
*
* Managing state transitions is one of the hardest parts of building applications. This is
* especially true on the web, where you also need to ensure that the state is reflected in the URL.
* In addition, we often want to split applications into multiple bundles and load them on demand.
* Doing this transparently is not trivial.
*
* The Angular router service solves these problems. Using the router, you can declaratively specify
* application states, manage state transitions while taking care of the URL, and load bundles on
* demand.
*
* @see [Routing and Navigation](guide/router.html) for an
* overview of how the router service should be used.
*
* \@publicApi
*/
class RouterModule {
// Note: We are injecting the Router so it gets created eagerly...
/**
* @param {?} guard
* @param {?} router
*/
constructor(guard, router) { }
/**
* Creates and configures a module with all the router providers and directives.
* Optionally sets up an application listener to perform an initial navigation.
*
* @param {?} routes An array of `Route` objects that define the navigation paths for the application.
* @param {?=} config An `ExtraOptions` configuration object that controls how navigation is performed.
* @return {?} The new router module.
*/
static forRoot(routes, config) {
return {
ngModule: RouterModule,
providers: [
ROUTER_PROVIDERS,
provideRoutes(routes),
{
provide: ROUTER_FORROOT_GUARD,
useFactory: provideForRootGuard,
deps: [[Router, new _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"](), new _angular_core__WEBPACK_IMPORTED_MODULE_1__["SkipSelf"]()]]
},
{ provide: ROUTER_CONFIGURATION, useValue: config ? config : {} },
{
provide: _angular_common__WEBPACK_IMPORTED_MODULE_0__["LocationStrategy"],
useFactory: provideLocationStrategy,
deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__["PlatformLocation"], [new _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__["APP_BASE_HREF"]), new _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"]()], ROUTER_CONFIGURATION]
},
{
provide: RouterScroller,
useFactory: createRouterScroller,
deps: [Router, _angular_common__WEBPACK_IMPORTED_MODULE_0__["ViewportScroller"], ROUTER_CONFIGURATION]
},
{
provide: PreloadingStrategy,
useExisting: config && config.preloadingStrategy ? config.preloadingStrategy :
NoPreloading
},
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgProbeToken"], multi: true, useFactory: routerNgProbeToken },
provideRouterInitializer(),
],
};
}
/**
* Creates a module with all the router directives and a provider registering routes.
* @param {?} routes
* @return {?}
*/
static forChild(routes) {
return { ngModule: RouterModule, providers: [provideRoutes(routes)] };
}
}
RouterModule.ɵmod = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineNgModule"]({ type: RouterModule });
RouterModule.ɵinj = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjector"]({ factory: function RouterModule_Factory(t) { return new (t || RouterModule)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](ROUTER_FORROOT_GUARD, 8), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](Router, 8)); } });
/** @nocollapse */
RouterModule.ctorParameters = () => [
{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"], args: [ROUTER_FORROOT_GUARD,] }] },
{ type: Router, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"] }] }
];
(function () { (typeof ngJitMode === "undefined" || ngJitMode) && _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵsetNgModuleScope"](RouterModule, { declarations: [RouterOutlet,
RouterLink,
RouterLinkWithHref,
RouterLinkActive,
ɵEmptyOutletComponent], exports: [RouterOutlet,
RouterLink,
RouterLinkWithHref,
RouterLinkActive,
ɵEmptyOutletComponent] }); })();
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](RouterModule, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModule"],
args: [{
declarations: ROUTER_DIRECTIVES,
exports: ROUTER_DIRECTIVES,
entryComponents: [ɵEmptyOutletComponent]
}]
}], function () { return [{ type: undefined, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"]
}, {
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Inject"],
args: [ROUTER_FORROOT_GUARD]
}] }, { type: Router, decorators: [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Optional"]
}] }]; }, null); })();
/**
* @param {?} router
* @param {?} viewportScroller
* @param {?} config
* @return {?}
*/
function createRouterScroller(router, viewportScroller, config) {
if (config.scrollOffset) {
viewportScroller.setOffset(config.scrollOffset);
}
return new RouterScroller(router, viewportScroller, config);
}
/**
* @param {?} platformLocationStrategy
* @param {?} baseHref
* @param {?=} options
* @return {?}
*/
function provideLocationStrategy(platformLocationStrategy, baseHref, options = {}) {
return options.useHash ? new _angular_common__WEBPACK_IMPORTED_MODULE_0__["HashLocationStrategy"](platformLocationStrategy, baseHref) :
new _angular_common__WEBPACK_IMPORTED_MODULE_0__["PathLocationStrategy"](platformLocationStrategy, baseHref);
}
/**
* @param {?} router
* @return {?}
*/
function provideForRootGuard(router) {
if (router) {
throw new Error(`RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.`);
}
return 'guarded';
}
/**
* Registers a [DI provider](guide/glossary#provider) for a set of routes.
* \@usageNotes
*
* ```
* \@NgModule({
* imports: [RouterModule.forChild(ROUTES)],
* providers: [provideRoutes(EXTRA_ROUTES)]
* })
* class MyNgModule {}
* ```
*
* \@publicApi
* @param {?} routes The route configuration to provide.
*
* @return {?}
*/
function provideRoutes(routes) {
return [
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ANALYZE_FOR_ENTRY_COMPONENTS"], multi: true, useValue: routes },
{ provide: ROUTES, multi: true, useValue: routes },
];
}
/**
* A set of configuration options for a router module, provided in the
* `forRoot()` method.
*
* \@publicApi
* @record
*/
function ExtraOptions() { }
if (false) {}
/**
* @param {?} urlSerializer
* @param {?} contexts
* @param {?} location
* @param {?} injector
* @param {?} loader
* @param {?} compiler
* @param {?} config
* @param {?=} opts
* @param {?=} urlHandlingStrategy
* @param {?=} routeReuseStrategy
* @return {?}
*/
function setupRouter(urlSerializer, contexts, location, injector, loader, compiler, config, opts = {}, urlHandlingStrategy, routeReuseStrategy) {
/** @type {?} */
const router = new Router(null, urlSerializer, contexts, location, injector, loader, compiler, flatten(config));
if (urlHandlingStrategy) {
router.urlHandlingStrategy = urlHandlingStrategy;
}
if (routeReuseStrategy) {
router.routeReuseStrategy = routeReuseStrategy;
}
if (opts.errorHandler) {
router.errorHandler = opts.errorHandler;
}
if (opts.malformedUriErrorHandler) {
router.malformedUriErrorHandler = opts.malformedUriErrorHandler;
}
if (opts.enableTracing) {
/** @type {?} */
const dom = Object(_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])();
router.events.subscribe((/**
* @param {?} e
* @return {?}
*/
(e) => {
dom.logGroup(`Router Event: ${((/** @type {?} */ (e.constructor))).name}`);
dom.log(e.toString());
dom.log(e);
dom.logGroupEnd();
}));
}
if (opts.onSameUrlNavigation) {
router.onSameUrlNavigation = opts.onSameUrlNavigation;
}
if (opts.paramsInheritanceStrategy) {
router.paramsInheritanceStrategy = opts.paramsInheritanceStrategy;
}
if (opts.urlUpdateStrategy) {
router.urlUpdateStrategy = opts.urlUpdateStrategy;
}
if (opts.relativeLinkResolution) {
router.relativeLinkResolution = opts.relativeLinkResolution;
}
return router;
}
/**
* @param {?} router
* @return {?}
*/
function rootRoute(router) {
return router.routerState.root;
}
/**
* Router initialization requires two steps:
*
* First, we start the navigation in a `APP_INITIALIZER` to block the bootstrap if
* a resolver or a guard executes asynchronously.
*
* Next, we actually run activation in a `BOOTSTRAP_LISTENER`, using the
* `afterPreactivation` hook provided by the router.
* The router navigation starts, reaches the point when preactivation is done, and then
* pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener.
*/
class RouterInitializer {
/**
* @param {?} injector
*/
constructor(injector) {
this.injector = injector;
this.initNavigation = false;
this.resultOfPreactivationDone = new rxjs__WEBPACK_IMPORTED_MODULE_2__["Subject"]();
}
/**
* @return {?}
*/
appInitializer() {
/** @type {?} */
const p = this.injector.get(_angular_common__WEBPACK_IMPORTED_MODULE_0__["LOCATION_INITIALIZED"], Promise.resolve(null));
return p.then((/**
* @return {?}
*/
() => {
/** @type {?} */
let resolve = (/** @type {?} */ (null));
/** @type {?} */
const res = new Promise((/**
* @param {?} r
* @return {?}
*/
r => resolve = r));
/** @type {?} */
const router = this.injector.get(Router);
/** @type {?} */
const opts = this.injector.get(ROUTER_CONFIGURATION);
if (this.isLegacyDisabled(opts) || this.isLegacyEnabled(opts)) {
resolve(true);
}
else if (opts.initialNavigation === 'disabled') {
router.setUpLocationChangeListener();
resolve(true);
}
else if (opts.initialNavigation === 'enabled') {
router.hooks.afterPreactivation = (/**
* @return {?}
*/
() => {
// only the initial navigation should be delayed
if (!this.initNavigation) {
this.initNavigation = true;
resolve(true);
return this.resultOfPreactivationDone;
// subsequent navigations should not be delayed
}
else {
return (/** @type {?} */ (Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])(null)));
}
});
router.initialNavigation();
}
else {
throw new Error(`Invalid initialNavigation options: '${opts.initialNavigation}'`);
}
return res;
}));
}
/**
* @param {?} bootstrappedComponentRef
* @return {?}
*/
bootstrapListener(bootstrappedComponentRef) {
/** @type {?} */
const opts = this.injector.get(ROUTER_CONFIGURATION);
/** @type {?} */
const preloader = this.injector.get(RouterPreloader);
/** @type {?} */
const routerScroller = this.injector.get(RouterScroller);
/** @type {?} */
const router = this.injector.get(Router);
/** @type {?} */
const ref = this.injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ApplicationRef"]);
if (bootstrappedComponentRef !== ref.components[0]) {
return;
}
if (this.isLegacyEnabled(opts)) {
router.initialNavigation();
}
else if (this.isLegacyDisabled(opts)) {
router.setUpLocationChangeListener();
}
preloader.setUpPreloading();
routerScroller.init();
router.resetRootComponentType(ref.componentTypes[0]);
this.resultOfPreactivationDone.next((/** @type {?} */ (null)));
this.resultOfPreactivationDone.complete();
}
/**
* @private
* @param {?} opts
* @return {?}
*/
isLegacyEnabled(opts) {
return opts.initialNavigation === 'legacy_enabled' || opts.initialNavigation === true ||
opts.initialNavigation === undefined;
}
/**
* @private
* @param {?} opts
* @return {?}
*/
isLegacyDisabled(opts) {
return opts.initialNavigation === 'legacy_disabled' || opts.initialNavigation === false;
}
}
RouterInitializer.ɵfac = function RouterInitializer_Factory(t) { return new (t || RouterInitializer)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["Injector"])); };
RouterInitializer.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ token: RouterInitializer, factory: RouterInitializer.ɵfac });
/** @nocollapse */
RouterInitializer.ctorParameters = () => [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injector"] }
];
/*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](RouterInitializer, [{
type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injectable"]
}], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["Injector"] }]; }, null); })();
if (false) {}
/**
* @param {?} r
* @return {?}
*/
function getAppInitializer(r) {
return r.appInitializer.bind(r);
}
/**
* @param {?} r
* @return {?}
*/
function getBootstrapListener(r) {
return r.bootstrapListener.bind(r);
}
/**
* A [DI token](guide/glossary/#di-token) for the router initializer that
* is called after the app is bootstrapped.
*
* \@publicApi
* @type {?}
*/
const ROUTER_INITIALIZER = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["InjectionToken"]('Router Initializer');
/**
* @return {?}
*/
function provideRouterInitializer() {
return [
RouterInitializer,
{
provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_INITIALIZER"],
multi: true,
useFactory: getAppInitializer,
deps: [RouterInitializer]
},
{ provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener, deps: [RouterInitializer] },
{ provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["APP_BOOTSTRAP_LISTENER"], multi: true, useExisting: ROUTER_INITIALIZER },
];
}
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/version.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@publicApi
* @type {?}
*/
const VERSION = new _angular_core__WEBPACK_IMPORTED_MODULE_1__["Version"]('9.1.13');
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/private_export.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/router/src/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/router/public_api.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: packages/router/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Generated bundle index. Do not edit.
*/
//# sourceMappingURL=router.js.map
/***/ }),
/***/ "./node_modules/javascript-color-gradient/src/index.js":
/*!*************************************************************!*\
!*** ./node_modules/javascript-color-gradient/src/index.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
class GradientColor {
constructor(startColor = "", endColor = "", minNum = 0, maxNum = 10) {
this.setColorGradient = (colorStart, colorEnd) => {
startColor = getHexColor(colorStart);
endColor = getHexColor(colorEnd);
};
this.setMidpoint = (minNumber, maxNumber) => {
minNum = minNumber;
maxNum = maxNumber;
};
this.getColor = (numberValue) => {
if (numberValue) {
return (
"#" +
generateHex(
numberValue,
startColor.substring(0, 2),
endColor.substring(0, 2)
) +
generateHex(
numberValue,
startColor.substring(2, 4),
endColor.substring(2, 4)
) +
generateHex(
numberValue,
startColor.substring(4, 6),
endColor.substring(4, 6)
)
);
}
};
const generateHex = (number, start, end) => {
if (number < minNum) {
number = minNum;
} else if (number > maxNum) {
number = maxNum;
}
const midPoint = maxNum - minNum;
const startBase = parseInt(start, 16);
const endBase = parseInt(end, 16);
const average = (endBase - startBase) / midPoint;
const finalBase = Math.round(average * (number - minNum) + startBase);
const balancedFinalBase =
finalBase < 16 ? "0" + finalBase.toString(16) : finalBase.toString(16);
return balancedFinalBase;
};
const getHexColor = (color) => {
return color.substring(color.length - 6, color.length);
};
}
}
class Gradient {
constructor(
colorGradients = "",
maxNum = 10,
colors = ["", ""],
intervals = []
) {
const setColorGradient = (gradientColors) => {
if (gradientColors.length < 2) {
throw new Error(
`setColorGradient should have more than ${gradientColors.length} color`
);
} else {
const increment = maxNum / (gradientColors.length - 1);
const firstColorGradient = new GradientColor();
const lower = 0;
const upper = 0 + increment;
firstColorGradient.setColorGradient(
gradientColors[0],
gradientColors[1]
);
firstColorGradient.setMidpoint(lower, upper);
colorGradients = [firstColorGradient];
intervals = [
{
lower,
upper,
},
];
for (let i = 1; i < gradientColors.length - 1; i++) {
const gradientColor = new GradientColor();
const lower = 0 + increment * i;
const upper = 0 + increment * (i + 1);
gradientColor.setColorGradient(
gradientColors[i],
gradientColors[i + 1]
);
gradientColor.setMidpoint(lower, upper);
colorGradients[i] = gradientColor;
intervals[i] = {
lower,
upper,
};
}
colors = gradientColors;
}
};
this.setColorGradient = (...gradientColors) => {
setColorGradient(gradientColors);
return this;
};
this.getColors = () => {
const gradientColorsArray = [];
for (let j = 0; j < intervals.length; j++) {
const interval = intervals[j];
const start = interval.lower === 0 ? 1 : Math.ceil(interval.lower);
const end =
interval.upper === maxNum
? interval.upper + 1
: Math.ceil(interval.upper);
for (let i = start; i < end; i++) {
gradientColorsArray.push(colorGradients[j].getColor(i));
}
}
return gradientColorsArray;
};
this.getColor = (numberValue) => {
if (isNaN(numberValue)) {
throw new TypeError(`getColor should be a number`);
} else if (numberValue <= 0) {
throw new TypeError(`getColor should be greater than ${numberValue}`);
} else {
const toInsert = numberValue + 1;
const segment = (maxNum - 0) / colorGradients.length;
const index = Math.min(
Math.floor((Math.max(numberValue, 0) - 0) / segment),
colorGradients.length - 1
);
return colorGradients[index].getColor(toInsert);
}
};
this.setMidpoint = (maxNumber) => {
if (!isNaN(maxNumber) && maxNumber >= 0) {
maxNum = maxNumber;
setColorGradient(colors);
} else if (maxNumber <= 0) {
throw new RangeError(`midPoint should be greater than ${maxNumber}`);
} else {
throw new RangeError("midPoint should be a number");
}
return this;
};
}
}
module.exports = Gradient;
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/index.js":
/*!*********************************************!*\
!*** ./node_modules/rxjs/_esm2015/index.js ***!
\*********************************************/
/*! exports provided: Observable, ConnectableObservable, GroupedObservable, observable, Subject, BehaviorSubject, ReplaySubject, AsyncSubject, asapScheduler, asyncScheduler, queueScheduler, animationFrameScheduler, VirtualTimeScheduler, VirtualAction, Scheduler, Subscription, Subscriber, Notification, NotificationKind, pipe, noop, identity, isObservable, ArgumentOutOfRangeError, EmptyError, ObjectUnsubscribedError, UnsubscriptionError, TimeoutError, bindCallback, bindNodeCallback, combineLatest, concat, defer, empty, forkJoin, from, fromEvent, fromEventPattern, generate, iif, interval, merge, never, of, onErrorResumeNext, pairs, partition, race, range, throwError, timer, using, zip, scheduled, EMPTY, NEVER, config */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _internal_Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./internal/Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Observable", function() { return _internal_Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]; });
/* harmony import */ var _internal_observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./internal/observable/ConnectableObservable */ "./node_modules/rxjs/_esm2015/internal/observable/ConnectableObservable.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConnectableObservable", function() { return _internal_observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_1__["ConnectableObservable"]; });
/* harmony import */ var _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./internal/operators/groupBy */ "./node_modules/rxjs/_esm2015/internal/operators/groupBy.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GroupedObservable", function() { return _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_2__["GroupedObservable"]; });
/* harmony import */ var _internal_symbol_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./internal/symbol/observable */ "./node_modules/rxjs/_esm2015/internal/symbol/observable.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "observable", function() { return _internal_symbol_observable__WEBPACK_IMPORTED_MODULE_3__["observable"]; });
/* harmony import */ var _internal_Subject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./internal/Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subject", function() { return _internal_Subject__WEBPACK_IMPORTED_MODULE_4__["Subject"]; });
/* harmony import */ var _internal_BehaviorSubject__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./internal/BehaviorSubject */ "./node_modules/rxjs/_esm2015/internal/BehaviorSubject.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BehaviorSubject", function() { return _internal_BehaviorSubject__WEBPACK_IMPORTED_MODULE_5__["BehaviorSubject"]; });
/* harmony import */ var _internal_ReplaySubject__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./internal/ReplaySubject */ "./node_modules/rxjs/_esm2015/internal/ReplaySubject.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReplaySubject", function() { return _internal_ReplaySubject__WEBPACK_IMPORTED_MODULE_6__["ReplaySubject"]; });
/* harmony import */ var _internal_AsyncSubject__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./internal/AsyncSubject */ "./node_modules/rxjs/_esm2015/internal/AsyncSubject.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AsyncSubject", function() { return _internal_AsyncSubject__WEBPACK_IMPORTED_MODULE_7__["AsyncSubject"]; });
/* harmony import */ var _internal_scheduler_asap__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./internal/scheduler/asap */ "./node_modules/rxjs/_esm2015/internal/scheduler/asap.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "asapScheduler", function() { return _internal_scheduler_asap__WEBPACK_IMPORTED_MODULE_8__["asap"]; });
/* harmony import */ var _internal_scheduler_async__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./internal/scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "asyncScheduler", function() { return _internal_scheduler_async__WEBPACK_IMPORTED_MODULE_9__["async"]; });
/* harmony import */ var _internal_scheduler_queue__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./internal/scheduler/queue */ "./node_modules/rxjs/_esm2015/internal/scheduler/queue.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "queueScheduler", function() { return _internal_scheduler_queue__WEBPACK_IMPORTED_MODULE_10__["queue"]; });
/* harmony import */ var _internal_scheduler_animationFrame__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./internal/scheduler/animationFrame */ "./node_modules/rxjs/_esm2015/internal/scheduler/animationFrame.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "animationFrameScheduler", function() { return _internal_scheduler_animationFrame__WEBPACK_IMPORTED_MODULE_11__["animationFrame"]; });
/* harmony import */ var _internal_scheduler_VirtualTimeScheduler__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./internal/scheduler/VirtualTimeScheduler */ "./node_modules/rxjs/_esm2015/internal/scheduler/VirtualTimeScheduler.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualTimeScheduler", function() { return _internal_scheduler_VirtualTimeScheduler__WEBPACK_IMPORTED_MODULE_12__["VirtualTimeScheduler"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualAction", function() { return _internal_scheduler_VirtualTimeScheduler__WEBPACK_IMPORTED_MODULE_12__["VirtualAction"]; });
/* harmony import */ var _internal_Scheduler__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./internal/Scheduler */ "./node_modules/rxjs/_esm2015/internal/Scheduler.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Scheduler", function() { return _internal_Scheduler__WEBPACK_IMPORTED_MODULE_13__["Scheduler"]; });
/* harmony import */ var _internal_Subscription__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./internal/Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return _internal_Subscription__WEBPACK_IMPORTED_MODULE_14__["Subscription"]; });
/* harmony import */ var _internal_Subscriber__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./internal/Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return _internal_Subscriber__WEBPACK_IMPORTED_MODULE_15__["Subscriber"]; });
/* harmony import */ var _internal_Notification__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./internal/Notification */ "./node_modules/rxjs/_esm2015/internal/Notification.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return _internal_Notification__WEBPACK_IMPORTED_MODULE_16__["Notification"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotificationKind", function() { return _internal_Notification__WEBPACK_IMPORTED_MODULE_16__["NotificationKind"]; });
/* harmony import */ var _internal_util_pipe__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./internal/util/pipe */ "./node_modules/rxjs/_esm2015/internal/util/pipe.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pipe", function() { return _internal_util_pipe__WEBPACK_IMPORTED_MODULE_17__["pipe"]; });
/* harmony import */ var _internal_util_noop__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./internal/util/noop */ "./node_modules/rxjs/_esm2015/internal/util/noop.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "noop", function() { return _internal_util_noop__WEBPACK_IMPORTED_MODULE_18__["noop"]; });
/* harmony import */ var _internal_util_identity__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./internal/util/identity */ "./node_modules/rxjs/_esm2015/internal/util/identity.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return _internal_util_identity__WEBPACK_IMPORTED_MODULE_19__["identity"]; });
/* harmony import */ var _internal_util_isObservable__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./internal/util/isObservable */ "./node_modules/rxjs/_esm2015/internal/util/isObservable.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isObservable", function() { return _internal_util_isObservable__WEBPACK_IMPORTED_MODULE_20__["isObservable"]; });
/* harmony import */ var _internal_util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./internal/util/ArgumentOutOfRangeError */ "./node_modules/rxjs/_esm2015/internal/util/ArgumentOutOfRangeError.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArgumentOutOfRangeError", function() { return _internal_util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_21__["ArgumentOutOfRangeError"]; });
/* harmony import */ var _internal_util_EmptyError__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./internal/util/EmptyError */ "./node_modules/rxjs/_esm2015/internal/util/EmptyError.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmptyError", function() { return _internal_util_EmptyError__WEBPACK_IMPORTED_MODULE_22__["EmptyError"]; });
/* harmony import */ var _internal_util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./internal/util/ObjectUnsubscribedError */ "./node_modules/rxjs/_esm2015/internal/util/ObjectUnsubscribedError.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ObjectUnsubscribedError", function() { return _internal_util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_23__["ObjectUnsubscribedError"]; });
/* harmony import */ var _internal_util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./internal/util/UnsubscriptionError */ "./node_modules/rxjs/_esm2015/internal/util/UnsubscriptionError.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UnsubscriptionError", function() { return _internal_util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_24__["UnsubscriptionError"]; });
/* harmony import */ var _internal_util_TimeoutError__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./internal/util/TimeoutError */ "./node_modules/rxjs/_esm2015/internal/util/TimeoutError.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return _internal_util_TimeoutError__WEBPACK_IMPORTED_MODULE_25__["TimeoutError"]; });
/* harmony import */ var _internal_observable_bindCallback__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./internal/observable/bindCallback */ "./node_modules/rxjs/_esm2015/internal/observable/bindCallback.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bindCallback", function() { return _internal_observable_bindCallback__WEBPACK_IMPORTED_MODULE_26__["bindCallback"]; });
/* harmony import */ var _internal_observable_bindNodeCallback__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./internal/observable/bindNodeCallback */ "./node_modules/rxjs/_esm2015/internal/observable/bindNodeCallback.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bindNodeCallback", function() { return _internal_observable_bindNodeCallback__WEBPACK_IMPORTED_MODULE_27__["bindNodeCallback"]; });
/* harmony import */ var _internal_observable_combineLatest__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./internal/observable/combineLatest */ "./node_modules/rxjs/_esm2015/internal/observable/combineLatest.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return _internal_observable_combineLatest__WEBPACK_IMPORTED_MODULE_28__["combineLatest"]; });
/* harmony import */ var _internal_observable_concat__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./internal/observable/concat */ "./node_modules/rxjs/_esm2015/internal/observable/concat.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return _internal_observable_concat__WEBPACK_IMPORTED_MODULE_29__["concat"]; });
/* harmony import */ var _internal_observable_defer__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./internal/observable/defer */ "./node_modules/rxjs/_esm2015/internal/observable/defer.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return _internal_observable_defer__WEBPACK_IMPORTED_MODULE_30__["defer"]; });
/* harmony import */ var _internal_observable_empty__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./internal/observable/empty */ "./node_modules/rxjs/_esm2015/internal/observable/empty.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "empty", function() { return _internal_observable_empty__WEBPACK_IMPORTED_MODULE_31__["empty"]; });
/* harmony import */ var _internal_observable_forkJoin__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./internal/observable/forkJoin */ "./node_modules/rxjs/_esm2015/internal/observable/forkJoin.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "forkJoin", function() { return _internal_observable_forkJoin__WEBPACK_IMPORTED_MODULE_32__["forkJoin"]; });
/* harmony import */ var _internal_observable_from__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./internal/observable/from */ "./node_modules/rxjs/_esm2015/internal/observable/from.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "from", function() { return _internal_observable_from__WEBPACK_IMPORTED_MODULE_33__["from"]; });
/* harmony import */ var _internal_observable_fromEvent__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./internal/observable/fromEvent */ "./node_modules/rxjs/_esm2015/internal/observable/fromEvent.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromEvent", function() { return _internal_observable_fromEvent__WEBPACK_IMPORTED_MODULE_34__["fromEvent"]; });
/* harmony import */ var _internal_observable_fromEventPattern__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./internal/observable/fromEventPattern */ "./node_modules/rxjs/_esm2015/internal/observable/fromEventPattern.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromEventPattern", function() { return _internal_observable_fromEventPattern__WEBPACK_IMPORTED_MODULE_35__["fromEventPattern"]; });
/* harmony import */ var _internal_observable_generate__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./internal/observable/generate */ "./node_modules/rxjs/_esm2015/internal/observable/generate.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "generate", function() { return _internal_observable_generate__WEBPACK_IMPORTED_MODULE_36__["generate"]; });
/* harmony import */ var _internal_observable_iif__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./internal/observable/iif */ "./node_modules/rxjs/_esm2015/internal/observable/iif.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "iif", function() { return _internal_observable_iif__WEBPACK_IMPORTED_MODULE_37__["iif"]; });
/* harmony import */ var _internal_observable_interval__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./internal/observable/interval */ "./node_modules/rxjs/_esm2015/internal/observable/interval.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "interval", function() { return _internal_observable_interval__WEBPACK_IMPORTED_MODULE_38__["interval"]; });
/* harmony import */ var _internal_observable_merge__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./internal/observable/merge */ "./node_modules/rxjs/_esm2015/internal/observable/merge.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return _internal_observable_merge__WEBPACK_IMPORTED_MODULE_39__["merge"]; });
/* harmony import */ var _internal_observable_never__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./internal/observable/never */ "./node_modules/rxjs/_esm2015/internal/observable/never.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "never", function() { return _internal_observable_never__WEBPACK_IMPORTED_MODULE_40__["never"]; });
/* harmony import */ var _internal_observable_of__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./internal/observable/of */ "./node_modules/rxjs/_esm2015/internal/observable/of.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "of", function() { return _internal_observable_of__WEBPACK_IMPORTED_MODULE_41__["of"]; });
/* harmony import */ var _internal_observable_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./internal/observable/onErrorResumeNext */ "./node_modules/rxjs/_esm2015/internal/observable/onErrorResumeNext.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return _internal_observable_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_42__["onErrorResumeNext"]; });
/* harmony import */ var _internal_observable_pairs__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./internal/observable/pairs */ "./node_modules/rxjs/_esm2015/internal/observable/pairs.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pairs", function() { return _internal_observable_pairs__WEBPACK_IMPORTED_MODULE_43__["pairs"]; });
/* harmony import */ var _internal_observable_partition__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./internal/observable/partition */ "./node_modules/rxjs/_esm2015/internal/observable/partition.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return _internal_observable_partition__WEBPACK_IMPORTED_MODULE_44__["partition"]; });
/* harmony import */ var _internal_observable_race__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./internal/observable/race */ "./node_modules/rxjs/_esm2015/internal/observable/race.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "race", function() { return _internal_observable_race__WEBPACK_IMPORTED_MODULE_45__["race"]; });
/* harmony import */ var _internal_observable_range__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./internal/observable/range */ "./node_modules/rxjs/_esm2015/internal/observable/range.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "range", function() { return _internal_observable_range__WEBPACK_IMPORTED_MODULE_46__["range"]; });
/* harmony import */ var _internal_observable_throwError__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./internal/observable/throwError */ "./node_modules/rxjs/_esm2015/internal/observable/throwError.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throwError", function() { return _internal_observable_throwError__WEBPACK_IMPORTED_MODULE_47__["throwError"]; });
/* harmony import */ var _internal_observable_timer__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./internal/observable/timer */ "./node_modules/rxjs/_esm2015/internal/observable/timer.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timer", function() { return _internal_observable_timer__WEBPACK_IMPORTED_MODULE_48__["timer"]; });
/* harmony import */ var _internal_observable_using__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./internal/observable/using */ "./node_modules/rxjs/_esm2015/internal/observable/using.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "using", function() { return _internal_observable_using__WEBPACK_IMPORTED_MODULE_49__["using"]; });
/* harmony import */ var _internal_observable_zip__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! ./internal/observable/zip */ "./node_modules/rxjs/_esm2015/internal/observable/zip.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return _internal_observable_zip__WEBPACK_IMPORTED_MODULE_50__["zip"]; });
/* harmony import */ var _internal_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ./internal/scheduled/scheduled */ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduled.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "scheduled", function() { return _internal_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_51__["scheduled"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EMPTY", function() { return _internal_observable_empty__WEBPACK_IMPORTED_MODULE_31__["EMPTY"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NEVER", function() { return _internal_observable_never__WEBPACK_IMPORTED_MODULE_40__["NEVER"]; });
/* harmony import */ var _internal_config__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(/*! ./internal/config */ "./node_modules/rxjs/_esm2015/internal/config.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "config", function() { return _internal_config__WEBPACK_IMPORTED_MODULE_52__["config"]; });
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/AsyncSubject.js":
/*!*************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/AsyncSubject.js ***!
\*************************************************************/
/*! exports provided: AsyncSubject */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncSubject", function() { return AsyncSubject; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
class AsyncSubject extends _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"] {
constructor() {
super(...arguments);
this.value = null;
this.hasNext = false;
this.hasCompleted = false;
}
_subscribe(subscriber) {
if (this.hasError) {
subscriber.error(this.thrownError);
return _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"].EMPTY;
}
else if (this.hasCompleted && this.hasNext) {
subscriber.next(this.value);
subscriber.complete();
return _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"].EMPTY;
}
return super._subscribe(subscriber);
}
next(value) {
if (!this.hasCompleted) {
this.value = value;
this.hasNext = true;
}
}
error(error) {
if (!this.hasCompleted) {
super.error(error);
}
}
complete() {
this.hasCompleted = true;
if (this.hasNext) {
super.next(this.value);
}
super.complete();
}
}
//# sourceMappingURL=AsyncSubject.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/BehaviorSubject.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/BehaviorSubject.js ***!
\****************************************************************/
/*! exports provided: BehaviorSubject */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BehaviorSubject", function() { return BehaviorSubject; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/ObjectUnsubscribedError */ "./node_modules/rxjs/_esm2015/internal/util/ObjectUnsubscribedError.js");
class BehaviorSubject extends _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"] {
constructor(_value) {
super();
this._value = _value;
}
get value() {
return this.getValue();
}
_subscribe(subscriber) {
const subscription = super._subscribe(subscriber);
if (subscription && !subscription.closed) {
subscriber.next(this._value);
}
return subscription;
}
getValue() {
if (this.hasError) {
throw this.thrownError;
}
else if (this.closed) {
throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_1__["ObjectUnsubscribedError"]();
}
else {
return this._value;
}
}
next(value) {
super.next(this._value = value);
}
}
//# sourceMappingURL=BehaviorSubject.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/InnerSubscriber.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/InnerSubscriber.js ***!
\****************************************************************/
/*! exports provided: InnerSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InnerSubscriber", function() { return InnerSubscriber; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
class InnerSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(parent, outerValue, outerIndex) {
super();
this.parent = parent;
this.outerValue = outerValue;
this.outerIndex = outerIndex;
this.index = 0;
}
_next(value) {
this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
}
_error(error) {
this.parent.notifyError(error, this);
this.unsubscribe();
}
_complete() {
this.parent.notifyComplete(this);
this.unsubscribe();
}
}
//# sourceMappingURL=InnerSubscriber.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/Notification.js":
/*!*************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/Notification.js ***!
\*************************************************************/
/*! exports provided: NotificationKind, Notification */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotificationKind", function() { return NotificationKind; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return Notification; });
/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./observable/empty */ "./node_modules/rxjs/_esm2015/internal/observable/empty.js");
/* harmony import */ var _observable_of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./observable/of */ "./node_modules/rxjs/_esm2015/internal/observable/of.js");
/* harmony import */ var _observable_throwError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./observable/throwError */ "./node_modules/rxjs/_esm2015/internal/observable/throwError.js");
var NotificationKind;
(function (NotificationKind) {
NotificationKind["NEXT"] = "N";
NotificationKind["ERROR"] = "E";
NotificationKind["COMPLETE"] = "C";
})(NotificationKind || (NotificationKind = {}));
class Notification {
constructor(kind, value, error) {
this.kind = kind;
this.value = value;
this.error = error;
this.hasValue = kind === 'N';
}
observe(observer) {
switch (this.kind) {
case 'N':
return observer.next && observer.next(this.value);
case 'E':
return observer.error && observer.error(this.error);
case 'C':
return observer.complete && observer.complete();
}
}
do(next, error, complete) {
const kind = this.kind;
switch (kind) {
case 'N':
return next && next(this.value);
case 'E':
return error && error(this.error);
case 'C':
return complete && complete();
}
}
accept(nextOrObserver, error, complete) {
if (nextOrObserver && typeof nextOrObserver.next === 'function') {
return this.observe(nextOrObserver);
}
else {
return this.do(nextOrObserver, error, complete);
}
}
toObservable() {
const kind = this.kind;
switch (kind) {
case 'N':
return Object(_observable_of__WEBPACK_IMPORTED_MODULE_1__["of"])(this.value);
case 'E':
return Object(_observable_throwError__WEBPACK_IMPORTED_MODULE_2__["throwError"])(this.error);
case 'C':
return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_0__["empty"])();
}
throw new Error('unexpected notification kind value');
}
static createNext(value) {
if (typeof value !== 'undefined') {
return new Notification('N', value);
}
return Notification.undefinedValueNotification;
}
static createError(err) {
return new Notification('E', undefined, err);
}
static createComplete() {
return Notification.completeNotification;
}
}
Notification.completeNotification = new Notification('C');
Notification.undefinedValueNotification = new Notification('N', undefined);
//# sourceMappingURL=Notification.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/Observable.js":
/*!***********************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/Observable.js ***!
\***********************************************************/
/*! exports provided: Observable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Observable", function() { return Observable; });
/* harmony import */ var _util_canReportError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/canReportError */ "./node_modules/rxjs/_esm2015/internal/util/canReportError.js");
/* harmony import */ var _util_toSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/toSubscriber */ "./node_modules/rxjs/_esm2015/internal/util/toSubscriber.js");
/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./symbol/observable */ "./node_modules/rxjs/_esm2015/internal/symbol/observable.js");
/* harmony import */ var _util_pipe__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./util/pipe */ "./node_modules/rxjs/_esm2015/internal/util/pipe.js");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./config */ "./node_modules/rxjs/_esm2015/internal/config.js");
class Observable {
constructor(subscribe) {
this._isScalar = false;
if (subscribe) {
this._subscribe = subscribe;
}
}
lift(operator) {
const observable = new Observable();
observable.source = this;
observable.operator = operator;
return observable;
}
subscribe(observerOrNext, error, complete) {
const { operator } = this;
const sink = Object(_util_toSubscriber__WEBPACK_IMPORTED_MODULE_1__["toSubscriber"])(observerOrNext, error, complete);
if (operator) {
sink.add(operator.call(sink, this.source));
}
else {
sink.add(this.source || (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
this._subscribe(sink) :
this._trySubscribe(sink));
}
if (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling) {
if (sink.syncErrorThrowable) {
sink.syncErrorThrowable = false;
if (sink.syncErrorThrown) {
throw sink.syncErrorValue;
}
}
}
return sink;
}
_trySubscribe(sink) {
try {
return this._subscribe(sink);
}
catch (err) {
if (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling) {
sink.syncErrorThrown = true;
sink.syncErrorValue = err;
}
if (Object(_util_canReportError__WEBPACK_IMPORTED_MODULE_0__["canReportError"])(sink)) {
sink.error(err);
}
else {
console.warn(err);
}
}
}
forEach(next, promiseCtor) {
promiseCtor = getPromiseCtor(promiseCtor);
return new promiseCtor((resolve, reject) => {
let subscription;
subscription = this.subscribe((value) => {
try {
next(value);
}
catch (err) {
reject(err);
if (subscription) {
subscription.unsubscribe();
}
}
}, reject, resolve);
});
}
_subscribe(subscriber) {
const { source } = this;
return source && source.subscribe(subscriber);
}
[_symbol_observable__WEBPACK_IMPORTED_MODULE_2__["observable"]]() {
return this;
}
pipe(...operations) {
if (operations.length === 0) {
return this;
}
return Object(_util_pipe__WEBPACK_IMPORTED_MODULE_3__["pipeFromArray"])(operations)(this);
}
toPromise(promiseCtor) {
promiseCtor = getPromiseCtor(promiseCtor);
return new promiseCtor((resolve, reject) => {
let value;
this.subscribe((x) => value = x, (err) => reject(err), () => resolve(value));
});
}
}
Observable.create = (subscribe) => {
return new Observable(subscribe);
};
function getPromiseCtor(promiseCtor) {
if (!promiseCtor) {
promiseCtor = _config__WEBPACK_IMPORTED_MODULE_4__["config"].Promise || Promise;
}
if (!promiseCtor) {
throw new Error('no Promise impl found');
}
return promiseCtor;
}
//# sourceMappingURL=Observable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/Observer.js":
/*!*********************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/Observer.js ***!
\*********************************************************/
/*! exports provided: empty */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "empty", function() { return empty; });
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./config */ "./node_modules/rxjs/_esm2015/internal/config.js");
/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/hostReportError */ "./node_modules/rxjs/_esm2015/internal/util/hostReportError.js");
const empty = {
closed: true,
next(value) { },
error(err) {
if (_config__WEBPACK_IMPORTED_MODULE_0__["config"].useDeprecatedSynchronousErrorHandling) {
throw err;
}
else {
Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_1__["hostReportError"])(err);
}
},
complete() { }
};
//# sourceMappingURL=Observer.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js ***!
\****************************************************************/
/*! exports provided: OuterSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OuterSubscriber", function() { return OuterSubscriber; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
class OuterSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.destination.next(innerValue);
}
notifyError(error, innerSub) {
this.destination.error(error);
}
notifyComplete(innerSub) {
this.destination.complete();
}
}
//# sourceMappingURL=OuterSubscriber.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/ReplaySubject.js":
/*!**************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/ReplaySubject.js ***!
\**************************************************************/
/*! exports provided: ReplaySubject */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReplaySubject", function() { return ReplaySubject; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _scheduler_queue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./scheduler/queue */ "./node_modules/rxjs/_esm2015/internal/scheduler/queue.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony import */ var _operators_observeOn__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./operators/observeOn */ "./node_modules/rxjs/_esm2015/internal/operators/observeOn.js");
/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./util/ObjectUnsubscribedError */ "./node_modules/rxjs/_esm2015/internal/util/ObjectUnsubscribedError.js");
/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SubjectSubscription */ "./node_modules/rxjs/_esm2015/internal/SubjectSubscription.js");
class ReplaySubject extends _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"] {
constructor(bufferSize = Number.POSITIVE_INFINITY, windowTime = Number.POSITIVE_INFINITY, scheduler) {
super();
this.scheduler = scheduler;
this._events = [];
this._infiniteTimeWindow = false;
this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
this._windowTime = windowTime < 1 ? 1 : windowTime;
if (windowTime === Number.POSITIVE_INFINITY) {
this._infiniteTimeWindow = true;
this.next = this.nextInfiniteTimeWindow;
}
else {
this.next = this.nextTimeWindow;
}
}
nextInfiniteTimeWindow(value) {
const _events = this._events;
_events.push(value);
if (_events.length > this._bufferSize) {
_events.shift();
}
super.next(value);
}
nextTimeWindow(value) {
this._events.push(new ReplayEvent(this._getNow(), value));
this._trimBufferThenGetEvents();
super.next(value);
}
_subscribe(subscriber) {
const _infiniteTimeWindow = this._infiniteTimeWindow;
const _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();
const scheduler = this.scheduler;
const len = _events.length;
let subscription;
if (this.closed) {
throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"]();
}
else if (this.isStopped || this.hasError) {
subscription = _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"].EMPTY;
}
else {
this.observers.push(subscriber);
subscription = new _SubjectSubscription__WEBPACK_IMPORTED_MODULE_5__["SubjectSubscription"](this, subscriber);
}
if (scheduler) {
subscriber.add(subscriber = new _operators_observeOn__WEBPACK_IMPORTED_MODULE_3__["ObserveOnSubscriber"](subscriber, scheduler));
}
if (_infiniteTimeWindow) {
for (let i = 0; i < len && !subscriber.closed; i++) {
subscriber.next(_events[i]);
}
}
else {
for (let i = 0; i < len && !subscriber.closed; i++) {
subscriber.next(_events[i].value);
}
}
if (this.hasError) {
subscriber.error(this.thrownError);
}
else if (this.isStopped) {
subscriber.complete();
}
return subscription;
}
_getNow() {
return (this.scheduler || _scheduler_queue__WEBPACK_IMPORTED_MODULE_1__["queue"]).now();
}
_trimBufferThenGetEvents() {
const now = this._getNow();
const _bufferSize = this._bufferSize;
const _windowTime = this._windowTime;
const _events = this._events;
const eventsCount = _events.length;
let spliceCount = 0;
while (spliceCount < eventsCount) {
if ((now - _events[spliceCount].time) < _windowTime) {
break;
}
spliceCount++;
}
if (eventsCount > _bufferSize) {
spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
}
if (spliceCount > 0) {
_events.splice(0, spliceCount);
}
return _events;
}
}
class ReplayEvent {
constructor(time, value) {
this.time = time;
this.value = value;
}
}
//# sourceMappingURL=ReplaySubject.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/Scheduler.js":
/*!**********************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/Scheduler.js ***!
\**********************************************************/
/*! exports provided: Scheduler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Scheduler", function() { return Scheduler; });
class Scheduler {
constructor(SchedulerAction, now = Scheduler.now) {
this.SchedulerAction = SchedulerAction;
this.now = now;
}
schedule(work, delay = 0, state) {
return new this.SchedulerAction(this, work).schedule(state, delay);
}
}
Scheduler.now = () => Date.now();
//# sourceMappingURL=Scheduler.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/Subject.js":
/*!********************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/Subject.js ***!
\********************************************************/
/*! exports provided: SubjectSubscriber, Subject, AnonymousSubject */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubjectSubscriber", function() { return SubjectSubscriber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subject", function() { return Subject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnonymousSubject", function() { return AnonymousSubject; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./util/ObjectUnsubscribedError */ "./node_modules/rxjs/_esm2015/internal/util/ObjectUnsubscribedError.js");
/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SubjectSubscription */ "./node_modules/rxjs/_esm2015/internal/SubjectSubscription.js");
/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../internal/symbol/rxSubscriber */ "./node_modules/rxjs/_esm2015/internal/symbol/rxSubscriber.js");
class SubjectSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"] {
constructor(destination) {
super(destination);
this.destination = destination;
}
}
class Subject extends _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"] {
constructor() {
super();
this.observers = [];
this.closed = false;
this.isStopped = false;
this.hasError = false;
this.thrownError = null;
}
[_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_5__["rxSubscriber"]]() {
return new SubjectSubscriber(this);
}
lift(operator) {
const subject = new AnonymousSubject(this, this);
subject.operator = operator;
return subject;
}
next(value) {
if (this.closed) {
throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_3__["ObjectUnsubscribedError"]();
}
if (!this.isStopped) {
const { observers } = this;
const len = observers.length;
const copy = observers.slice();
for (let i = 0; i < len; i++) {
copy[i].next(value);
}
}
}
error(err) {
if (this.closed) {
throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_3__["ObjectUnsubscribedError"]();
}
this.hasError = true;
this.thrownError = err;
this.isStopped = true;
const { observers } = this;
const len = observers.length;
const copy = observers.slice();
for (let i = 0; i < len; i++) {
copy[i].error(err);
}
this.observers.length = 0;
}
complete() {
if (this.closed) {
throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_3__["ObjectUnsubscribedError"]();
}
this.isStopped = true;
const { observers } = this;
const len = observers.length;
const copy = observers.slice();
for (let i = 0; i < len; i++) {
copy[i].complete();
}
this.observers.length = 0;
}
unsubscribe() {
this.isStopped = true;
this.closed = true;
this.observers = null;
}
_trySubscribe(subscriber) {
if (this.closed) {
throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_3__["ObjectUnsubscribedError"]();
}
else {
return super._trySubscribe(subscriber);
}
}
_subscribe(subscriber) {
if (this.closed) {
throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_3__["ObjectUnsubscribedError"]();
}
else if (this.hasError) {
subscriber.error(this.thrownError);
return _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"].EMPTY;
}
else if (this.isStopped) {
subscriber.complete();
return _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"].EMPTY;
}
else {
this.observers.push(subscriber);
return new _SubjectSubscription__WEBPACK_IMPORTED_MODULE_4__["SubjectSubscription"](this, subscriber);
}
}
asObservable() {
const observable = new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
observable.source = this;
return observable;
}
}
Subject.create = (destination, source) => {
return new AnonymousSubject(destination, source);
};
class AnonymousSubject extends Subject {
constructor(destination, source) {
super();
this.destination = destination;
this.source = source;
}
next(value) {
const { destination } = this;
if (destination && destination.next) {
destination.next(value);
}
}
error(err) {
const { destination } = this;
if (destination && destination.error) {
this.destination.error(err);
}
}
complete() {
const { destination } = this;
if (destination && destination.complete) {
this.destination.complete();
}
}
_subscribe(subscriber) {
const { source } = this;
if (source) {
return this.source.subscribe(subscriber);
}
else {
return _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"].EMPTY;
}
}
}
//# sourceMappingURL=Subject.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/SubjectSubscription.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/SubjectSubscription.js ***!
\********************************************************************/
/*! exports provided: SubjectSubscription */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubjectSubscription", function() { return SubjectSubscription; });
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
class SubjectSubscription extends _Subscription__WEBPACK_IMPORTED_MODULE_0__["Subscription"] {
constructor(subject, subscriber) {
super();
this.subject = subject;
this.subscriber = subscriber;
this.closed = false;
}
unsubscribe() {
if (this.closed) {
return;
}
this.closed = true;
const subject = this.subject;
const observers = subject.observers;
this.subject = null;
if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
return;
}
const subscriberIndex = observers.indexOf(this.subscriber);
if (subscriberIndex !== -1) {
observers.splice(subscriberIndex, 1);
}
}
}
//# sourceMappingURL=SubjectSubscription.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/Subscriber.js":
/*!***********************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/Subscriber.js ***!
\***********************************************************/
/*! exports provided: Subscriber, SafeSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return Subscriber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SafeSubscriber", function() { return SafeSubscriber; });
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/isFunction */ "./node_modules/rxjs/_esm2015/internal/util/isFunction.js");
/* harmony import */ var _Observer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Observer */ "./node_modules/rxjs/_esm2015/internal/Observer.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../internal/symbol/rxSubscriber */ "./node_modules/rxjs/_esm2015/internal/symbol/rxSubscriber.js");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./config */ "./node_modules/rxjs/_esm2015/internal/config.js");
/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./util/hostReportError */ "./node_modules/rxjs/_esm2015/internal/util/hostReportError.js");
class Subscriber extends _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"] {
constructor(destinationOrNext, error, complete) {
super();
this.syncErrorValue = null;
this.syncErrorThrown = false;
this.syncErrorThrowable = false;
this.isStopped = false;
switch (arguments.length) {
case 0:
this.destination = _Observer__WEBPACK_IMPORTED_MODULE_1__["empty"];
break;
case 1:
if (!destinationOrNext) {
this.destination = _Observer__WEBPACK_IMPORTED_MODULE_1__["empty"];
break;
}
if (typeof destinationOrNext === 'object') {
if (destinationOrNext instanceof Subscriber) {
this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
this.destination = destinationOrNext;
destinationOrNext.add(this);
}
else {
this.syncErrorThrowable = true;
this.destination = new SafeSubscriber(this, destinationOrNext);
}
break;
}
default:
this.syncErrorThrowable = true;
this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
break;
}
}
[_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_3__["rxSubscriber"]]() { return this; }
static create(next, error, complete) {
const subscriber = new Subscriber(next, error, complete);
subscriber.syncErrorThrowable = false;
return subscriber;
}
next(value) {
if (!this.isStopped) {
this._next(value);
}
}
error(err) {
if (!this.isStopped) {
this.isStopped = true;
this._error(err);
}
}
complete() {
if (!this.isStopped) {
this.isStopped = true;
this._complete();
}
}
unsubscribe() {
if (this.closed) {
return;
}
this.isStopped = true;
super.unsubscribe();
}
_next(value) {
this.destination.next(value);
}
_error(err) {
this.destination.error(err);
this.unsubscribe();
}
_complete() {
this.destination.complete();
this.unsubscribe();
}
_unsubscribeAndRecycle() {
const { _parentOrParents } = this;
this._parentOrParents = null;
this.unsubscribe();
this.closed = false;
this.isStopped = false;
this._parentOrParents = _parentOrParents;
return this;
}
}
class SafeSubscriber extends Subscriber {
constructor(_parentSubscriber, observerOrNext, error, complete) {
super();
this._parentSubscriber = _parentSubscriber;
let next;
let context = this;
if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(observerOrNext)) {
next = observerOrNext;
}
else if (observerOrNext) {
next = observerOrNext.next;
error = observerOrNext.error;
complete = observerOrNext.complete;
if (observerOrNext !== _Observer__WEBPACK_IMPORTED_MODULE_1__["empty"]) {
context = Object.create(observerOrNext);
if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(context.unsubscribe)) {
this.add(context.unsubscribe.bind(context));
}
context.unsubscribe = this.unsubscribe.bind(this);
}
}
this._context = context;
this._next = next;
this._error = error;
this._complete = complete;
}
next(value) {
if (!this.isStopped && this._next) {
const { _parentSubscriber } = this;
if (!_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
this.__tryOrUnsub(this._next, value);
}
else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
this.unsubscribe();
}
}
}
error(err) {
if (!this.isStopped) {
const { _parentSubscriber } = this;
const { useDeprecatedSynchronousErrorHandling } = _config__WEBPACK_IMPORTED_MODULE_4__["config"];
if (this._error) {
if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
this.__tryOrUnsub(this._error, err);
this.unsubscribe();
}
else {
this.__tryOrSetError(_parentSubscriber, this._error, err);
this.unsubscribe();
}
}
else if (!_parentSubscriber.syncErrorThrowable) {
this.unsubscribe();
if (useDeprecatedSynchronousErrorHandling) {
throw err;
}
Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_5__["hostReportError"])(err);
}
else {
if (useDeprecatedSynchronousErrorHandling) {
_parentSubscriber.syncErrorValue = err;
_parentSubscriber.syncErrorThrown = true;
}
else {
Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_5__["hostReportError"])(err);
}
this.unsubscribe();
}
}
}
complete() {
if (!this.isStopped) {
const { _parentSubscriber } = this;
if (this._complete) {
const wrappedComplete = () => this._complete.call(this._context);
if (!_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
this.__tryOrUnsub(wrappedComplete);
this.unsubscribe();
}
else {
this.__tryOrSetError(_parentSubscriber, wrappedComplete);
this.unsubscribe();
}
}
else {
this.unsubscribe();
}
}
}
__tryOrUnsub(fn, value) {
try {
fn.call(this._context, value);
}
catch (err) {
this.unsubscribe();
if (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling) {
throw err;
}
else {
Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_5__["hostReportError"])(err);
}
}
}
__tryOrSetError(parent, fn, value) {
if (!_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling) {
throw new Error('bad call');
}
try {
fn.call(this._context, value);
}
catch (err) {
if (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling) {
parent.syncErrorValue = err;
parent.syncErrorThrown = true;
return true;
}
else {
Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_5__["hostReportError"])(err);
return true;
}
}
return false;
}
_unsubscribe() {
const { _parentSubscriber } = this;
this._context = null;
this._parentSubscriber = null;
_parentSubscriber.unsubscribe();
}
}
//# sourceMappingURL=Subscriber.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/Subscription.js":
/*!*************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/Subscription.js ***!
\*************************************************************/
/*! exports provided: Subscription */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return Subscription; });
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _util_isObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/isObject */ "./node_modules/rxjs/_esm2015/internal/util/isObject.js");
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util/isFunction */ "./node_modules/rxjs/_esm2015/internal/util/isFunction.js");
/* harmony import */ var _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./util/UnsubscriptionError */ "./node_modules/rxjs/_esm2015/internal/util/UnsubscriptionError.js");
class Subscription {
constructor(unsubscribe) {
this.closed = false;
this._parentOrParents = null;
this._subscriptions = null;
if (unsubscribe) {
this._unsubscribe = unsubscribe;
}
}
unsubscribe() {
let errors;
if (this.closed) {
return;
}
let { _parentOrParents, _unsubscribe, _subscriptions } = this;
this.closed = true;
this._parentOrParents = null;
this._subscriptions = null;
if (_parentOrParents instanceof Subscription) {
_parentOrParents.remove(this);
}
else if (_parentOrParents !== null) {
for (let index = 0; index < _parentOrParents.length; ++index) {
const parent = _parentOrParents[index];
parent.remove(this);
}
}
if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(_unsubscribe)) {
try {
_unsubscribe.call(this);
}
catch (e) {
errors = e instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"] ? flattenUnsubscriptionErrors(e.errors) : [e];
}
}
if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(_subscriptions)) {
let index = -1;
let len = _subscriptions.length;
while (++index < len) {
const sub = _subscriptions[index];
if (Object(_util_isObject__WEBPACK_IMPORTED_MODULE_1__["isObject"])(sub)) {
try {
sub.unsubscribe();
}
catch (e) {
errors = errors || [];
if (e instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"]) {
errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
}
else {
errors.push(e);
}
}
}
}
}
if (errors) {
throw new _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"](errors);
}
}
add(teardown) {
let subscription = teardown;
if (!teardown) {
return Subscription.EMPTY;
}
switch (typeof teardown) {
case 'function':
subscription = new Subscription(teardown);
case 'object':
if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
return subscription;
}
else if (this.closed) {
subscription.unsubscribe();
return subscription;
}
else if (!(subscription instanceof Subscription)) {
const tmp = subscription;
subscription = new Subscription();
subscription._subscriptions = [tmp];
}
break;
default: {
throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
}
}
let { _parentOrParents } = subscription;
if (_parentOrParents === null) {
subscription._parentOrParents = this;
}
else if (_parentOrParents instanceof Subscription) {
if (_parentOrParents === this) {
return subscription;
}
subscription._parentOrParents = [_parentOrParents, this];
}
else if (_parentOrParents.indexOf(this) === -1) {
_parentOrParents.push(this);
}
else {
return subscription;
}
const subscriptions = this._subscriptions;
if (subscriptions === null) {
this._subscriptions = [subscription];
}
else {
subscriptions.push(subscription);
}
return subscription;
}
remove(subscription) {
const subscriptions = this._subscriptions;
if (subscriptions) {
const subscriptionIndex = subscriptions.indexOf(subscription);
if (subscriptionIndex !== -1) {
subscriptions.splice(subscriptionIndex, 1);
}
}
}
}
Subscription.EMPTY = (function (empty) {
empty.closed = true;
return empty;
}(new Subscription()));
function flattenUnsubscriptionErrors(errors) {
return errors.reduce((errs, err) => errs.concat((err instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"]) ? err.errors : err), []);
}
//# sourceMappingURL=Subscription.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/config.js":
/*!*******************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/config.js ***!
\*******************************************************/
/*! exports provided: config */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "config", function() { return config; });
let _enable_super_gross_mode_that_will_cause_bad_things = false;
const config = {
Promise: undefined,
set useDeprecatedSynchronousErrorHandling(value) {
if (value) {
const error = new Error();
console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
}
else if (_enable_super_gross_mode_that_will_cause_bad_things) {
console.log('RxJS: Back to a better error behavior. Thank you. <3');
}
_enable_super_gross_mode_that_will_cause_bad_things = value;
},
get useDeprecatedSynchronousErrorHandling() {
return _enable_super_gross_mode_that_will_cause_bad_things;
},
};
//# sourceMappingURL=config.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/ConnectableObservable.js":
/*!*********************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/ConnectableObservable.js ***!
\*********************************************************************************/
/*! exports provided: ConnectableObservable, connectableObservableDescriptor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConnectableObservable", function() { return ConnectableObservable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "connectableObservableDescriptor", function() { return connectableObservableDescriptor; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony import */ var _operators_refCount__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../operators/refCount */ "./node_modules/rxjs/_esm2015/internal/operators/refCount.js");
class ConnectableObservable extends _Observable__WEBPACK_IMPORTED_MODULE_1__["Observable"] {
constructor(source, subjectFactory) {
super();
this.source = source;
this.subjectFactory = subjectFactory;
this._refCount = 0;
this._isComplete = false;
}
_subscribe(subscriber) {
return this.getSubject().subscribe(subscriber);
}
getSubject() {
const subject = this._subject;
if (!subject || subject.isStopped) {
this._subject = this.subjectFactory();
}
return this._subject;
}
connect() {
let connection = this._connection;
if (!connection) {
this._isComplete = false;
connection = this._connection = new _Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"]();
connection.add(this.source
.subscribe(new ConnectableSubscriber(this.getSubject(), this)));
if (connection.closed) {
this._connection = null;
connection = _Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"].EMPTY;
}
}
return connection;
}
refCount() {
return Object(_operators_refCount__WEBPACK_IMPORTED_MODULE_4__["refCount"])()(this);
}
}
const connectableObservableDescriptor = (() => {
const connectableProto = ConnectableObservable.prototype;
return {
operator: { value: null },
_refCount: { value: 0, writable: true },
_subject: { value: null, writable: true },
_connection: { value: null, writable: true },
_subscribe: { value: connectableProto._subscribe },
_isComplete: { value: connectableProto._isComplete, writable: true },
getSubject: { value: connectableProto.getSubject },
connect: { value: connectableProto.connect },
refCount: { value: connectableProto.refCount }
};
})();
class ConnectableSubscriber extends _Subject__WEBPACK_IMPORTED_MODULE_0__["SubjectSubscriber"] {
constructor(destination, connectable) {
super(destination);
this.connectable = connectable;
}
_error(err) {
this._unsubscribe();
super._error(err);
}
_complete() {
this.connectable._isComplete = true;
this._unsubscribe();
super._complete();
}
_unsubscribe() {
const connectable = this.connectable;
if (connectable) {
this.connectable = null;
const connection = connectable._connection;
connectable._refCount = 0;
connectable._subject = null;
connectable._connection = null;
if (connection) {
connection.unsubscribe();
}
}
}
}
class RefCountOperator {
constructor(connectable) {
this.connectable = connectable;
}
call(subscriber, source) {
const { connectable } = this;
connectable._refCount++;
const refCounter = new RefCountSubscriber(subscriber, connectable);
const subscription = source.subscribe(refCounter);
if (!refCounter.closed) {
refCounter.connection = connectable.connect();
}
return subscription;
}
}
class RefCountSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_2__["Subscriber"] {
constructor(destination, connectable) {
super(destination);
this.connectable = connectable;
}
_unsubscribe() {
const { connectable } = this;
if (!connectable) {
this.connection = null;
return;
}
this.connectable = null;
const refCount = connectable._refCount;
if (refCount <= 0) {
this.connection = null;
return;
}
connectable._refCount = refCount - 1;
if (refCount > 1) {
this.connection = null;
return;
}
const { connection } = this;
const sharedConnection = connectable._connection;
this.connection = null;
if (sharedConnection && (!connection || sharedConnection === connection)) {
sharedConnection.unsubscribe();
}
}
}
//# sourceMappingURL=ConnectableObservable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/SubscribeOnObservable.js":
/*!*********************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/SubscribeOnObservable.js ***!
\*********************************************************************************/
/*! exports provided: SubscribeOnObservable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeOnObservable", function() { return SubscribeOnObservable; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _scheduler_asap__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scheduler/asap */ "./node_modules/rxjs/_esm2015/internal/scheduler/asap.js");
/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isNumeric */ "./node_modules/rxjs/_esm2015/internal/util/isNumeric.js");
class SubscribeOnObservable extends _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"] {
constructor(source, delayTime = 0, scheduler = _scheduler_asap__WEBPACK_IMPORTED_MODULE_1__["asap"]) {
super();
this.source = source;
this.delayTime = delayTime;
this.scheduler = scheduler;
if (!Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__["isNumeric"])(delayTime) || delayTime < 0) {
this.delayTime = 0;
}
if (!scheduler || typeof scheduler.schedule !== 'function') {
this.scheduler = _scheduler_asap__WEBPACK_IMPORTED_MODULE_1__["asap"];
}
}
static create(source, delay = 0, scheduler = _scheduler_asap__WEBPACK_IMPORTED_MODULE_1__["asap"]) {
return new SubscribeOnObservable(source, delay, scheduler);
}
static dispatch(arg) {
const { source, subscriber } = arg;
return this.add(source.subscribe(subscriber));
}
_subscribe(subscriber) {
const delay = this.delayTime;
const source = this.source;
const scheduler = this.scheduler;
return scheduler.schedule(SubscribeOnObservable.dispatch, delay, {
source, subscriber
});
}
}
//# sourceMappingURL=SubscribeOnObservable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/bindCallback.js":
/*!************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/bindCallback.js ***!
\************************************************************************/
/*! exports provided: bindCallback */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bindCallback", function() { return bindCallback; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../AsyncSubject */ "./node_modules/rxjs/_esm2015/internal/AsyncSubject.js");
/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../operators/map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
/* harmony import */ var _util_canReportError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/canReportError */ "./node_modules/rxjs/_esm2015/internal/util/canReportError.js");
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js");
function bindCallback(callbackFunc, resultSelector, scheduler) {
if (resultSelector) {
if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_5__["isScheduler"])(resultSelector)) {
scheduler = resultSelector;
}
else {
return (...args) => bindCallback(callbackFunc, scheduler)(...args).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])((args) => Object(_util_isArray__WEBPACK_IMPORTED_MODULE_4__["isArray"])(args) ? resultSelector(...args) : resultSelector(args)));
}
}
return function (...args) {
const context = this;
let subject;
const params = {
context,
subject,
callbackFunc,
scheduler,
};
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
if (!scheduler) {
if (!subject) {
subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"]();
const handler = (...innerArgs) => {
subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
subject.complete();
};
try {
callbackFunc.apply(context, [...args, handler]);
}
catch (err) {
if (Object(_util_canReportError__WEBPACK_IMPORTED_MODULE_3__["canReportError"])(subject)) {
subject.error(err);
}
else {
console.warn(err);
}
}
}
return subject.subscribe(subscriber);
}
else {
const state = {
args, subscriber, params,
};
return scheduler.schedule(dispatch, 0, state);
}
});
};
}
function dispatch(state) {
const self = this;
const { args, subscriber, params } = state;
const { callbackFunc, context, scheduler } = params;
let { subject } = params;
if (!subject) {
subject = params.subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"]();
const handler = (...innerArgs) => {
const value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
this.add(scheduler.schedule(dispatchNext, 0, { value, subject }));
};
try {
callbackFunc.apply(context, [...args, handler]);
}
catch (err) {
subject.error(err);
}
}
this.add(subject.subscribe(subscriber));
}
function dispatchNext(state) {
const { value, subject } = state;
subject.next(value);
subject.complete();
}
function dispatchError(state) {
const { err, subject } = state;
subject.error(err);
}
//# sourceMappingURL=bindCallback.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/bindNodeCallback.js":
/*!****************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/bindNodeCallback.js ***!
\****************************************************************************/
/*! exports provided: bindNodeCallback */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bindNodeCallback", function() { return bindNodeCallback; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../AsyncSubject */ "./node_modules/rxjs/_esm2015/internal/AsyncSubject.js");
/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../operators/map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
/* harmony import */ var _util_canReportError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/canReportError */ "./node_modules/rxjs/_esm2015/internal/util/canReportError.js");
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js");
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
function bindNodeCallback(callbackFunc, resultSelector, scheduler) {
if (resultSelector) {
if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_4__["isScheduler"])(resultSelector)) {
scheduler = resultSelector;
}
else {
return (...args) => bindNodeCallback(callbackFunc, scheduler)(...args).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])(args => Object(_util_isArray__WEBPACK_IMPORTED_MODULE_5__["isArray"])(args) ? resultSelector(...args) : resultSelector(args)));
}
}
return function (...args) {
const params = {
subject: undefined,
args,
callbackFunc,
scheduler,
context: this,
};
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const { context } = params;
let { subject } = params;
if (!scheduler) {
if (!subject) {
subject = params.subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"]();
const handler = (...innerArgs) => {
const err = innerArgs.shift();
if (err) {
subject.error(err);
return;
}
subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
subject.complete();
};
try {
callbackFunc.apply(context, [...args, handler]);
}
catch (err) {
if (Object(_util_canReportError__WEBPACK_IMPORTED_MODULE_3__["canReportError"])(subject)) {
subject.error(err);
}
else {
console.warn(err);
}
}
}
return subject.subscribe(subscriber);
}
else {
return scheduler.schedule(dispatch, 0, { params, subscriber, context });
}
});
};
}
function dispatch(state) {
const { params, subscriber, context } = state;
const { callbackFunc, args, scheduler } = params;
let subject = params.subject;
if (!subject) {
subject = params.subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"]();
const handler = (...innerArgs) => {
const err = innerArgs.shift();
if (err) {
this.add(scheduler.schedule(dispatchError, 0, { err, subject }));
}
else {
const value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
this.add(scheduler.schedule(dispatchNext, 0, { value, subject }));
}
};
try {
callbackFunc.apply(context, [...args, handler]);
}
catch (err) {
this.add(scheduler.schedule(dispatchError, 0, { err, subject }));
}
}
this.add(subject.subscribe(subscriber));
}
function dispatchNext(arg) {
const { value, subject } = arg;
subject.next(value);
subject.complete();
}
function dispatchError(arg) {
const { err, subject } = arg;
subject.error(err);
}
//# sourceMappingURL=bindNodeCallback.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/combineLatest.js":
/*!*************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/combineLatest.js ***!
\*************************************************************************/
/*! exports provided: combineLatest, CombineLatestOperator, CombineLatestSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return combineLatest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CombineLatestOperator", function() { return CombineLatestOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CombineLatestSubscriber", function() { return CombineLatestSubscriber; });
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js");
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fromArray */ "./node_modules/rxjs/_esm2015/internal/observable/fromArray.js");
const NONE = {};
function combineLatest(...observables) {
let resultSelector = null;
let scheduler = null;
if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_0__["isScheduler"])(observables[observables.length - 1])) {
scheduler = observables.pop();
}
if (typeof observables[observables.length - 1] === 'function') {
resultSelector = observables.pop();
}
if (observables.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(observables[0])) {
observables = observables[0];
}
return Object(_fromArray__WEBPACK_IMPORTED_MODULE_4__["fromArray"])(observables, scheduler).lift(new CombineLatestOperator(resultSelector));
}
class CombineLatestOperator {
constructor(resultSelector) {
this.resultSelector = resultSelector;
}
call(subscriber, source) {
return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));
}
}
class CombineLatestSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"] {
constructor(destination, resultSelector) {
super(destination);
this.resultSelector = resultSelector;
this.active = 0;
this.values = [];
this.observables = [];
}
_next(observable) {
this.values.push(NONE);
this.observables.push(observable);
}
_complete() {
const observables = this.observables;
const len = observables.length;
if (len === 0) {
this.destination.complete();
}
else {
this.active = len;
this.toRespond = len;
for (let i = 0; i < len; i++) {
const observable = observables[i];
this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, observable, observable, i));
}
}
}
notifyComplete(unused) {
if ((this.active -= 1) === 0) {
this.destination.complete();
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
const values = this.values;
const oldVal = values[outerIndex];
const toRespond = !this.toRespond
? 0
: oldVal === NONE ? --this.toRespond : this.toRespond;
values[outerIndex] = innerValue;
if (toRespond === 0) {
if (this.resultSelector) {
this._tryResultSelector(values);
}
else {
this.destination.next(values.slice());
}
}
}
_tryResultSelector(values) {
let result;
try {
result = this.resultSelector.apply(this, values);
}
catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
}
}
//# sourceMappingURL=combineLatest.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/concat.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/concat.js ***!
\******************************************************************/
/*! exports provided: concat */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return concat; });
/* harmony import */ var _of__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./of */ "./node_modules/rxjs/_esm2015/internal/observable/of.js");
/* harmony import */ var _operators_concatAll__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../operators/concatAll */ "./node_modules/rxjs/_esm2015/internal/operators/concatAll.js");
function concat(...observables) {
return Object(_operators_concatAll__WEBPACK_IMPORTED_MODULE_1__["concatAll"])()(Object(_of__WEBPACK_IMPORTED_MODULE_0__["of"])(...observables));
}
//# sourceMappingURL=concat.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/defer.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/defer.js ***!
\*****************************************************************/
/*! exports provided: defer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return defer; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./from */ "./node_modules/rxjs/_esm2015/internal/observable/from.js");
/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./empty */ "./node_modules/rxjs/_esm2015/internal/observable/empty.js");
function defer(observableFactory) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
let input;
try {
input = observableFactory();
}
catch (err) {
subscriber.error(err);
return undefined;
}
const source = input ? Object(_from__WEBPACK_IMPORTED_MODULE_1__["from"])(input) : Object(_empty__WEBPACK_IMPORTED_MODULE_2__["empty"])();
return source.subscribe(subscriber);
});
}
//# sourceMappingURL=defer.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/empty.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/empty.js ***!
\*****************************************************************/
/*! exports provided: EMPTY, empty */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EMPTY", function() { return EMPTY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "empty", function() { return empty; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
const EMPTY = new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => subscriber.complete());
function empty(scheduler) {
return scheduler ? emptyScheduled(scheduler) : EMPTY;
}
function emptyScheduled(scheduler) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => scheduler.schedule(() => subscriber.complete()));
}
//# sourceMappingURL=empty.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/forkJoin.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/forkJoin.js ***!
\********************************************************************/
/*! exports provided: forkJoin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forkJoin", function() { return forkJoin; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../operators/map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
/* harmony import */ var _util_isObject__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/isObject */ "./node_modules/rxjs/_esm2015/internal/util/isObject.js");
/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./from */ "./node_modules/rxjs/_esm2015/internal/observable/from.js");
function forkJoin(...sources) {
if (sources.length === 1) {
const first = sources[0];
if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(first)) {
return forkJoinInternal(first, null);
}
if (Object(_util_isObject__WEBPACK_IMPORTED_MODULE_3__["isObject"])(first) && Object.getPrototypeOf(first) === Object.prototype) {
const keys = Object.keys(first);
return forkJoinInternal(keys.map(key => first[key]), keys);
}
}
if (typeof sources[sources.length - 1] === 'function') {
const resultSelector = sources.pop();
sources = (sources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(sources[0])) ? sources[0] : sources;
return forkJoinInternal(sources, null).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])((args) => resultSelector(...args)));
}
return forkJoinInternal(sources, null);
}
function forkJoinInternal(sources, keys) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const len = sources.length;
if (len === 0) {
subscriber.complete();
return;
}
const values = new Array(len);
let completed = 0;
let emitted = 0;
for (let i = 0; i < len; i++) {
const source = Object(_from__WEBPACK_IMPORTED_MODULE_4__["from"])(sources[i]);
let hasValue = false;
subscriber.add(source.subscribe({
next: value => {
if (!hasValue) {
hasValue = true;
emitted++;
}
values[i] = value;
},
error: err => subscriber.error(err),
complete: () => {
completed++;
if (completed === len || !hasValue) {
if (emitted === len) {
subscriber.next(keys ?
keys.reduce((result, key, i) => (result[key] = values[i], result), {}) :
values);
}
subscriber.complete();
}
}
}));
}
});
}
//# sourceMappingURL=forkJoin.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/from.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/from.js ***!
\****************************************************************/
/*! exports provided: from */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "from", function() { return from; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeTo */ "./node_modules/rxjs/_esm2015/internal/util/subscribeTo.js");
/* harmony import */ var _scheduled_scheduled__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../scheduled/scheduled */ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduled.js");
function from(input, scheduler) {
if (!scheduler) {
if (input instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]) {
return input;
}
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](Object(_util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(input));
}
else {
return Object(_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_2__["scheduled"])(input, scheduler);
}
}
//# sourceMappingURL=from.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/fromArray.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/fromArray.js ***!
\*********************************************************************/
/*! exports provided: fromArray */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromArray", function() { return fromArray; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _util_subscribeToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToArray */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToArray.js");
/* harmony import */ var _scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../scheduled/scheduleArray */ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduleArray.js");
function fromArray(input, scheduler) {
if (!scheduler) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](Object(_util_subscribeToArray__WEBPACK_IMPORTED_MODULE_1__["subscribeToArray"])(input));
}
else {
return Object(_scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__["scheduleArray"])(input, scheduler);
}
}
//# sourceMappingURL=fromArray.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/fromEvent.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/fromEvent.js ***!
\*********************************************************************/
/*! exports provided: fromEvent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromEvent", function() { return fromEvent; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isFunction */ "./node_modules/rxjs/_esm2015/internal/util/isFunction.js");
/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../operators/map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
const toString = (() => Object.prototype.toString)();
function fromEvent(target, eventName, options, resultSelector) {
if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(options)) {
resultSelector = options;
options = undefined;
}
if (resultSelector) {
return fromEvent(target, eventName, options).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_3__["map"])(args => Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(args) ? resultSelector(...args) : resultSelector(args)));
}
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
function handler(e) {
if (arguments.length > 1) {
subscriber.next(Array.prototype.slice.call(arguments));
}
else {
subscriber.next(e);
}
}
setupSubscription(target, eventName, handler, subscriber, options);
});
}
function setupSubscription(sourceObj, eventName, handler, subscriber, options) {
let unsubscribe;
if (isEventTarget(sourceObj)) {
const source = sourceObj;
sourceObj.addEventListener(eventName, handler, options);
unsubscribe = () => source.removeEventListener(eventName, handler, options);
}
else if (isJQueryStyleEventEmitter(sourceObj)) {
const source = sourceObj;
sourceObj.on(eventName, handler);
unsubscribe = () => source.off(eventName, handler);
}
else if (isNodeStyleEventEmitter(sourceObj)) {
const source = sourceObj;
sourceObj.addListener(eventName, handler);
unsubscribe = () => source.removeListener(eventName, handler);
}
else if (sourceObj && sourceObj.length) {
for (let i = 0, len = sourceObj.length; i < len; i++) {
setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
}
}
else {
throw new TypeError('Invalid event target');
}
subscriber.add(unsubscribe);
}
function isNodeStyleEventEmitter(sourceObj) {
return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
}
function isJQueryStyleEventEmitter(sourceObj) {
return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
}
function isEventTarget(sourceObj) {
return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
}
//# sourceMappingURL=fromEvent.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/fromEventPattern.js":
/*!****************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/fromEventPattern.js ***!
\****************************************************************************/
/*! exports provided: fromEventPattern */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromEventPattern", function() { return fromEventPattern; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isFunction */ "./node_modules/rxjs/_esm2015/internal/util/isFunction.js");
/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../operators/map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
function fromEventPattern(addHandler, removeHandler, resultSelector) {
if (resultSelector) {
return fromEventPattern(addHandler, removeHandler).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_3__["map"])(args => Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(args) ? resultSelector(...args) : resultSelector(args)));
}
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const handler = (...e) => subscriber.next(e.length === 1 ? e[0] : e);
let retValue;
try {
retValue = addHandler(handler);
}
catch (err) {
subscriber.error(err);
return undefined;
}
if (!Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(removeHandler)) {
return undefined;
}
return () => removeHandler(handler, retValue);
});
}
//# sourceMappingURL=fromEventPattern.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/generate.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/generate.js ***!
\********************************************************************/
/*! exports provided: generate */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generate", function() { return generate; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/identity */ "./node_modules/rxjs/_esm2015/internal/util/identity.js");
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js");
function generate(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) {
let resultSelector;
let initialState;
if (arguments.length == 1) {
const options = initialStateOrOptions;
initialState = options.initialState;
condition = options.condition;
iterate = options.iterate;
resultSelector = options.resultSelector || _util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"];
scheduler = options.scheduler;
}
else if (resultSelectorOrObservable === undefined || Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_2__["isScheduler"])(resultSelectorOrObservable)) {
initialState = initialStateOrOptions;
resultSelector = _util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"];
scheduler = resultSelectorOrObservable;
}
else {
initialState = initialStateOrOptions;
resultSelector = resultSelectorOrObservable;
}
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
let state = initialState;
if (scheduler) {
return scheduler.schedule(dispatch, 0, {
subscriber,
iterate,
condition,
resultSelector,
state
});
}
do {
if (condition) {
let conditionResult;
try {
conditionResult = condition(state);
}
catch (err) {
subscriber.error(err);
return undefined;
}
if (!conditionResult) {
subscriber.complete();
break;
}
}
let value;
try {
value = resultSelector(state);
}
catch (err) {
subscriber.error(err);
return undefined;
}
subscriber.next(value);
if (subscriber.closed) {
break;
}
try {
state = iterate(state);
}
catch (err) {
subscriber.error(err);
return undefined;
}
} while (true);
return undefined;
});
}
function dispatch(state) {
const { subscriber, condition } = state;
if (subscriber.closed) {
return undefined;
}
if (state.needIterate) {
try {
state.state = state.iterate(state.state);
}
catch (err) {
subscriber.error(err);
return undefined;
}
}
else {
state.needIterate = true;
}
if (condition) {
let conditionResult;
try {
conditionResult = condition(state.state);
}
catch (err) {
subscriber.error(err);
return undefined;
}
if (!conditionResult) {
subscriber.complete();
return undefined;
}
if (subscriber.closed) {
return undefined;
}
}
let value;
try {
value = state.resultSelector(state.state);
}
catch (err) {
subscriber.error(err);
return undefined;
}
if (subscriber.closed) {
return undefined;
}
subscriber.next(value);
if (subscriber.closed) {
return undefined;
}
return this.schedule(state);
}
//# sourceMappingURL=generate.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/iif.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/iif.js ***!
\***************************************************************/
/*! exports provided: iif */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iif", function() { return iif; });
/* harmony import */ var _defer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./defer */ "./node_modules/rxjs/_esm2015/internal/observable/defer.js");
/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./empty */ "./node_modules/rxjs/_esm2015/internal/observable/empty.js");
function iif(condition, trueResult = _empty__WEBPACK_IMPORTED_MODULE_1__["EMPTY"], falseResult = _empty__WEBPACK_IMPORTED_MODULE_1__["EMPTY"]) {
return Object(_defer__WEBPACK_IMPORTED_MODULE_0__["defer"])(() => condition() ? trueResult : falseResult);
}
//# sourceMappingURL=iif.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/interval.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/interval.js ***!
\********************************************************************/
/*! exports provided: interval */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "interval", function() { return interval; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isNumeric */ "./node_modules/rxjs/_esm2015/internal/util/isNumeric.js");
function interval(period = 0, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]) {
if (!Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__["isNumeric"])(period) || period < 0) {
period = 0;
}
if (!scheduler || typeof scheduler.schedule !== 'function') {
scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"];
}
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
subscriber.add(scheduler.schedule(dispatch, period, { subscriber, counter: 0, period }));
return subscriber;
});
}
function dispatch(state) {
const { subscriber, counter, period } = state;
subscriber.next(counter);
this.schedule({ subscriber, counter: counter + 1, period }, period);
}
//# sourceMappingURL=interval.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/merge.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/merge.js ***!
\*****************************************************************/
/*! exports provided: merge */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return merge; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js");
/* harmony import */ var _operators_mergeAll__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../operators/mergeAll */ "./node_modules/rxjs/_esm2015/internal/operators/mergeAll.js");
/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fromArray */ "./node_modules/rxjs/_esm2015/internal/observable/fromArray.js");
function merge(...observables) {
let concurrent = Number.POSITIVE_INFINITY;
let scheduler = null;
let last = observables[observables.length - 1];
if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__["isScheduler"])(last)) {
scheduler = observables.pop();
if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
concurrent = observables.pop();
}
}
else if (typeof last === 'number') {
concurrent = observables.pop();
}
if (scheduler === null && observables.length === 1 && observables[0] instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]) {
return observables[0];
}
return Object(_operators_mergeAll__WEBPACK_IMPORTED_MODULE_2__["mergeAll"])(concurrent)(Object(_fromArray__WEBPACK_IMPORTED_MODULE_3__["fromArray"])(observables, scheduler));
}
//# sourceMappingURL=merge.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/never.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/never.js ***!
\*****************************************************************/
/*! exports provided: NEVER, never */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NEVER", function() { return NEVER; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "never", function() { return never; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _util_noop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/noop */ "./node_modules/rxjs/_esm2015/internal/util/noop.js");
const NEVER = new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](_util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"]);
function never() {
return NEVER;
}
//# sourceMappingURL=never.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/of.js":
/*!**************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/of.js ***!
\**************************************************************/
/*! exports provided: of */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "of", function() { return of; });
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js");
/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fromArray */ "./node_modules/rxjs/_esm2015/internal/observable/fromArray.js");
/* harmony import */ var _scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../scheduled/scheduleArray */ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduleArray.js");
function of(...args) {
let scheduler = args[args.length - 1];
if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_0__["isScheduler"])(scheduler)) {
args.pop();
return Object(_scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__["scheduleArray"])(args, scheduler);
}
else {
return Object(_fromArray__WEBPACK_IMPORTED_MODULE_1__["fromArray"])(args);
}
}
//# sourceMappingURL=of.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/onErrorResumeNext.js":
/*!*****************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/onErrorResumeNext.js ***!
\*****************************************************************************/
/*! exports provided: onErrorResumeNext */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return onErrorResumeNext; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./from */ "./node_modules/rxjs/_esm2015/internal/observable/from.js");
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./empty */ "./node_modules/rxjs/_esm2015/internal/observable/empty.js");
function onErrorResumeNext(...sources) {
if (sources.length === 0) {
return _empty__WEBPACK_IMPORTED_MODULE_3__["EMPTY"];
}
const [first, ...remainder] = sources;
if (sources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(first)) {
return onErrorResumeNext(...first);
}
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const subNext = () => subscriber.add(onErrorResumeNext(...remainder).subscribe(subscriber));
return Object(_from__WEBPACK_IMPORTED_MODULE_1__["from"])(first).subscribe({
next(value) { subscriber.next(value); },
error: subNext,
complete: subNext,
});
});
}
//# sourceMappingURL=onErrorResumeNext.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/pairs.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/pairs.js ***!
\*****************************************************************/
/*! exports provided: pairs, dispatch */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pairs", function() { return pairs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dispatch", function() { return dispatch; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
function pairs(obj, scheduler) {
if (!scheduler) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length && !subscriber.closed; i++) {
const key = keys[i];
if (obj.hasOwnProperty(key)) {
subscriber.next([key, obj[key]]);
}
}
subscriber.complete();
});
}
else {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const keys = Object.keys(obj);
const subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"]();
subscription.add(scheduler.schedule(dispatch, 0, { keys, index: 0, subscriber, subscription, obj }));
return subscription;
});
}
}
function dispatch(state) {
const { keys, index, subscriber, subscription, obj } = state;
if (!subscriber.closed) {
if (index < keys.length) {
const key = keys[index];
subscriber.next([key, obj[key]]);
subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
}
else {
subscriber.complete();
}
}
}
//# sourceMappingURL=pairs.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/partition.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/partition.js ***!
\*********************************************************************/
/*! exports provided: partition */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return partition; });
/* harmony import */ var _util_not__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/not */ "./node_modules/rxjs/_esm2015/internal/util/not.js");
/* harmony import */ var _util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeTo */ "./node_modules/rxjs/_esm2015/internal/util/subscribeTo.js");
/* harmony import */ var _operators_filter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../operators/filter */ "./node_modules/rxjs/_esm2015/internal/operators/filter.js");
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
function partition(source, predicate, thisArg) {
return [
Object(_operators_filter__WEBPACK_IMPORTED_MODULE_2__["filter"])(predicate, thisArg)(new _Observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](Object(_util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(source))),
Object(_operators_filter__WEBPACK_IMPORTED_MODULE_2__["filter"])(Object(_util_not__WEBPACK_IMPORTED_MODULE_0__["not"])(predicate, thisArg))(new _Observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](Object(_util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(source)))
];
}
//# sourceMappingURL=partition.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/race.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/race.js ***!
\****************************************************************/
/*! exports provided: race, RaceOperator, RaceSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "race", function() { return race; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RaceOperator", function() { return RaceOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RaceSubscriber", function() { return RaceSubscriber; });
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fromArray */ "./node_modules/rxjs/_esm2015/internal/observable/fromArray.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function race(...observables) {
if (observables.length === 1) {
if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(observables[0])) {
observables = observables[0];
}
else {
return observables[0];
}
}
return Object(_fromArray__WEBPACK_IMPORTED_MODULE_1__["fromArray"])(observables, undefined).lift(new RaceOperator());
}
class RaceOperator {
call(subscriber, source) {
return source.subscribe(new RaceSubscriber(subscriber));
}
}
class RaceSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"] {
constructor(destination) {
super(destination);
this.hasFirst = false;
this.observables = [];
this.subscriptions = [];
}
_next(observable) {
this.observables.push(observable);
}
_complete() {
const observables = this.observables;
const len = observables.length;
if (len === 0) {
this.destination.complete();
}
else {
for (let i = 0; i < len && !this.hasFirst; i++) {
let observable = observables[i];
let subscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, observable, observable, i);
if (this.subscriptions) {
this.subscriptions.push(subscription);
}
this.add(subscription);
}
this.observables = null;
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
if (!this.hasFirst) {
this.hasFirst = true;
for (let i = 0; i < this.subscriptions.length; i++) {
if (i !== outerIndex) {
let subscription = this.subscriptions[i];
subscription.unsubscribe();
this.remove(subscription);
}
}
this.subscriptions = null;
}
this.destination.next(innerValue);
}
}
//# sourceMappingURL=race.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/range.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/range.js ***!
\*****************************************************************/
/*! exports provided: range, dispatch */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "range", function() { return range; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dispatch", function() { return dispatch; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
function range(start = 0, count, scheduler) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
if (count === undefined) {
count = start;
start = 0;
}
let index = 0;
let current = start;
if (scheduler) {
return scheduler.schedule(dispatch, 0, {
index, count, start, subscriber
});
}
else {
do {
if (index++ >= count) {
subscriber.complete();
break;
}
subscriber.next(current++);
if (subscriber.closed) {
break;
}
} while (true);
}
return undefined;
});
}
function dispatch(state) {
const { start, index, count, subscriber } = state;
if (index >= count) {
subscriber.complete();
return;
}
subscriber.next(start);
if (subscriber.closed) {
return;
}
state.index = index + 1;
state.start = start + 1;
this.schedule(state);
}
//# sourceMappingURL=range.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/throwError.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/throwError.js ***!
\**********************************************************************/
/*! exports provided: throwError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throwError", function() { return throwError; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
function throwError(error, scheduler) {
if (!scheduler) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => subscriber.error(error));
}
else {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => scheduler.schedule(dispatch, 0, { error, subscriber }));
}
}
function dispatch({ error, subscriber }) {
subscriber.error(error);
}
//# sourceMappingURL=throwError.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/timer.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/timer.js ***!
\*****************************************************************/
/*! exports provided: timer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timer", function() { return timer; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isNumeric */ "./node_modules/rxjs/_esm2015/internal/util/isNumeric.js");
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js");
function timer(dueTime = 0, periodOrScheduler, scheduler) {
let period = -1;
if (Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__["isNumeric"])(periodOrScheduler)) {
period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);
}
else if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__["isScheduler"])(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (!Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__["isScheduler"])(scheduler)) {
scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"];
}
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const due = Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__["isNumeric"])(dueTime)
? dueTime
: (+dueTime - scheduler.now());
return scheduler.schedule(dispatch, due, {
index: 0, period, subscriber
});
});
}
function dispatch(state) {
const { index, period, subscriber } = state;
subscriber.next(index);
if (subscriber.closed) {
return;
}
else if (period === -1) {
return subscriber.complete();
}
state.index = index + 1;
this.schedule(state, period);
}
//# sourceMappingURL=timer.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/using.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/using.js ***!
\*****************************************************************/
/*! exports provided: using */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "using", function() { return using; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./from */ "./node_modules/rxjs/_esm2015/internal/observable/from.js");
/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./empty */ "./node_modules/rxjs/_esm2015/internal/observable/empty.js");
function using(resourceFactory, observableFactory) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
let resource;
try {
resource = resourceFactory();
}
catch (err) {
subscriber.error(err);
return undefined;
}
let result;
try {
result = observableFactory(resource);
}
catch (err) {
subscriber.error(err);
return undefined;
}
const source = result ? Object(_from__WEBPACK_IMPORTED_MODULE_1__["from"])(result) : _empty__WEBPACK_IMPORTED_MODULE_2__["EMPTY"];
const subscription = source.subscribe(subscriber);
return () => {
subscription.unsubscribe();
if (resource) {
resource.unsubscribe();
}
};
});
}
//# sourceMappingURL=using.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/observable/zip.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/observable/zip.js ***!
\***************************************************************/
/*! exports provided: zip, ZipOperator, ZipSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return zip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZipOperator", function() { return ZipOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZipSubscriber", function() { return ZipSubscriber; });
/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./fromArray */ "./node_modules/rxjs/_esm2015/internal/observable/fromArray.js");
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
/* harmony import */ var _internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../internal/symbol/iterator */ "./node_modules/rxjs/_esm2015/internal/symbol/iterator.js");
function zip(...observables) {
const resultSelector = observables[observables.length - 1];
if (typeof resultSelector === 'function') {
observables.pop();
}
return Object(_fromArray__WEBPACK_IMPORTED_MODULE_0__["fromArray"])(observables, undefined).lift(new ZipOperator(resultSelector));
}
class ZipOperator {
constructor(resultSelector) {
this.resultSelector = resultSelector;
}
call(subscriber, source) {
return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));
}
}
class ZipSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_2__["Subscriber"] {
constructor(destination, resultSelector, values = Object.create(null)) {
super(destination);
this.iterators = [];
this.active = 0;
this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : null;
this.values = values;
}
_next(value) {
const iterators = this.iterators;
if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(value)) {
iterators.push(new StaticArrayIterator(value));
}
else if (typeof value[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_5__["iterator"]] === 'function') {
iterators.push(new StaticIterator(value[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_5__["iterator"]]()));
}
else {
iterators.push(new ZipBufferIterator(this.destination, this, value));
}
}
_complete() {
const iterators = this.iterators;
const len = iterators.length;
this.unsubscribe();
if (len === 0) {
this.destination.complete();
return;
}
this.active = len;
for (let i = 0; i < len; i++) {
let iterator = iterators[i];
if (iterator.stillUnsubscribed) {
const destination = this.destination;
destination.add(iterator.subscribe(iterator, i));
}
else {
this.active--;
}
}
}
notifyInactive() {
this.active--;
if (this.active === 0) {
this.destination.complete();
}
}
checkIterators() {
const iterators = this.iterators;
const len = iterators.length;
const destination = this.destination;
for (let i = 0; i < len; i++) {
let iterator = iterators[i];
if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
return;
}
}
let shouldComplete = false;
const args = [];
for (let i = 0; i < len; i++) {
let iterator = iterators[i];
let result = iterator.next();
if (iterator.hasCompleted()) {
shouldComplete = true;
}
if (result.done) {
destination.complete();
return;
}
args.push(result.value);
}
if (this.resultSelector) {
this._tryresultSelector(args);
}
else {
destination.next(args);
}
if (shouldComplete) {
destination.complete();
}
}
_tryresultSelector(args) {
let result;
try {
result = this.resultSelector.apply(this, args);
}
catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
}
}
class StaticIterator {
constructor(iterator) {
this.iterator = iterator;
this.nextResult = iterator.next();
}
hasValue() {
return true;
}
next() {
const result = this.nextResult;
this.nextResult = this.iterator.next();
return result;
}
hasCompleted() {
const nextResult = this.nextResult;
return nextResult && nextResult.done;
}
}
class StaticArrayIterator {
constructor(array) {
this.array = array;
this.index = 0;
this.length = 0;
this.length = array.length;
}
[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_5__["iterator"]]() {
return this;
}
next(value) {
const i = this.index++;
const array = this.array;
return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
}
hasValue() {
return this.array.length > this.index;
}
hasCompleted() {
return this.array.length === this.index;
}
}
class ZipBufferIterator extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"] {
constructor(destination, parent, observable) {
super(destination);
this.parent = parent;
this.observable = observable;
this.stillUnsubscribed = true;
this.buffer = [];
this.isComplete = false;
}
[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_5__["iterator"]]() {
return this;
}
next() {
const buffer = this.buffer;
if (buffer.length === 0 && this.isComplete) {
return { value: null, done: true };
}
else {
return { value: buffer.shift(), done: false };
}
}
hasValue() {
return this.buffer.length > 0;
}
hasCompleted() {
return this.buffer.length === 0 && this.isComplete;
}
notifyComplete() {
if (this.buffer.length > 0) {
this.isComplete = true;
this.parent.notifyInactive();
}
else {
this.destination.complete();
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.buffer.push(innerValue);
this.parent.checkIterators();
}
subscribe(value, index) {
return Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(this, this.observable, this, index);
}
}
//# sourceMappingURL=zip.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/audit.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/audit.js ***!
\****************************************************************/
/*! exports provided: audit */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "audit", function() { return audit; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function audit(durationSelector) {
return function auditOperatorFunction(source) {
return source.lift(new AuditOperator(durationSelector));
};
}
class AuditOperator {
constructor(durationSelector) {
this.durationSelector = durationSelector;
}
call(subscriber, source) {
return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));
}
}
class AuditSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, durationSelector) {
super(destination);
this.durationSelector = durationSelector;
this.hasValue = false;
}
_next(value) {
this.value = value;
this.hasValue = true;
if (!this.throttled) {
let duration;
try {
const { durationSelector } = this;
duration = durationSelector(value);
}
catch (err) {
return this.destination.error(err);
}
const innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, duration);
if (!innerSubscription || innerSubscription.closed) {
this.clearThrottle();
}
else {
this.add(this.throttled = innerSubscription);
}
}
}
clearThrottle() {
const { value, hasValue, throttled } = this;
if (throttled) {
this.remove(throttled);
this.throttled = null;
throttled.unsubscribe();
}
if (hasValue) {
this.value = null;
this.hasValue = false;
this.destination.next(value);
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex) {
this.clearThrottle();
}
notifyComplete() {
this.clearThrottle();
}
}
//# sourceMappingURL=audit.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/auditTime.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/auditTime.js ***!
\********************************************************************/
/*! exports provided: auditTime */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "auditTime", function() { return auditTime; });
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _audit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./audit */ "./node_modules/rxjs/_esm2015/internal/operators/audit.js");
/* harmony import */ var _observable_timer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../observable/timer */ "./node_modules/rxjs/_esm2015/internal/observable/timer.js");
function auditTime(duration, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]) {
return Object(_audit__WEBPACK_IMPORTED_MODULE_1__["audit"])(() => Object(_observable_timer__WEBPACK_IMPORTED_MODULE_2__["timer"])(duration, scheduler));
}
//# sourceMappingURL=auditTime.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/buffer.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/buffer.js ***!
\*****************************************************************/
/*! exports provided: buffer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return buffer; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function buffer(closingNotifier) {
return function bufferOperatorFunction(source) {
return source.lift(new BufferOperator(closingNotifier));
};
}
class BufferOperator {
constructor(closingNotifier) {
this.closingNotifier = closingNotifier;
}
call(subscriber, source) {
return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
}
}
class BufferSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, closingNotifier) {
super(destination);
this.buffer = [];
this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, closingNotifier));
}
_next(value) {
this.buffer.push(value);
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
const buffer = this.buffer;
this.buffer = [];
this.destination.next(buffer);
}
}
//# sourceMappingURL=buffer.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/bufferCount.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/bufferCount.js ***!
\**********************************************************************/
/*! exports provided: bufferCount */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferCount", function() { return bufferCount; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function bufferCount(bufferSize, startBufferEvery = null) {
return function bufferCountOperatorFunction(source) {
return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));
};
}
class BufferCountOperator {
constructor(bufferSize, startBufferEvery) {
this.bufferSize = bufferSize;
this.startBufferEvery = startBufferEvery;
if (!startBufferEvery || bufferSize === startBufferEvery) {
this.subscriberClass = BufferCountSubscriber;
}
else {
this.subscriberClass = BufferSkipCountSubscriber;
}
}
call(subscriber, source) {
return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
}
}
class BufferCountSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, bufferSize) {
super(destination);
this.bufferSize = bufferSize;
this.buffer = [];
}
_next(value) {
const buffer = this.buffer;
buffer.push(value);
if (buffer.length == this.bufferSize) {
this.destination.next(buffer);
this.buffer = [];
}
}
_complete() {
const buffer = this.buffer;
if (buffer.length > 0) {
this.destination.next(buffer);
}
super._complete();
}
}
class BufferSkipCountSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, bufferSize, startBufferEvery) {
super(destination);
this.bufferSize = bufferSize;
this.startBufferEvery = startBufferEvery;
this.buffers = [];
this.count = 0;
}
_next(value) {
const { bufferSize, startBufferEvery, buffers, count } = this;
this.count++;
if (count % startBufferEvery === 0) {
buffers.push([]);
}
for (let i = buffers.length; i--;) {
const buffer = buffers[i];
buffer.push(value);
if (buffer.length === bufferSize) {
buffers.splice(i, 1);
this.destination.next(buffer);
}
}
}
_complete() {
const { buffers, destination } = this;
while (buffers.length > 0) {
let buffer = buffers.shift();
if (buffer.length > 0) {
destination.next(buffer);
}
}
super._complete();
}
}
//# sourceMappingURL=bufferCount.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/bufferTime.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/bufferTime.js ***!
\*********************************************************************/
/*! exports provided: bufferTime */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferTime", function() { return bufferTime; });
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js");
function bufferTime(bufferTimeSpan) {
let length = arguments.length;
let scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"];
if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_2__["isScheduler"])(arguments[arguments.length - 1])) {
scheduler = arguments[arguments.length - 1];
length--;
}
let bufferCreationInterval = null;
if (length >= 2) {
bufferCreationInterval = arguments[1];
}
let maxBufferSize = Number.POSITIVE_INFINITY;
if (length >= 3) {
maxBufferSize = arguments[2];
}
return function bufferTimeOperatorFunction(source) {
return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));
};
}
class BufferTimeOperator {
constructor(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
this.bufferTimeSpan = bufferTimeSpan;
this.bufferCreationInterval = bufferCreationInterval;
this.maxBufferSize = maxBufferSize;
this.scheduler = scheduler;
}
call(subscriber, source) {
return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler));
}
}
class Context {
constructor() {
this.buffer = [];
}
}
class BufferTimeSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"] {
constructor(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
super(destination);
this.bufferTimeSpan = bufferTimeSpan;
this.bufferCreationInterval = bufferCreationInterval;
this.maxBufferSize = maxBufferSize;
this.scheduler = scheduler;
this.contexts = [];
const context = this.openContext();
this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;
if (this.timespanOnly) {
const timeSpanOnlyState = { subscriber: this, context, bufferTimeSpan };
this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
}
else {
const closeState = { subscriber: this, context };
const creationState = { bufferTimeSpan, bufferCreationInterval, subscriber: this, scheduler };
this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState));
this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState));
}
}
_next(value) {
const contexts = this.contexts;
const len = contexts.length;
let filledBufferContext;
for (let i = 0; i < len; i++) {
const context = contexts[i];
const buffer = context.buffer;
buffer.push(value);
if (buffer.length == this.maxBufferSize) {
filledBufferContext = context;
}
}
if (filledBufferContext) {
this.onBufferFull(filledBufferContext);
}
}
_error(err) {
this.contexts.length = 0;
super._error(err);
}
_complete() {
const { contexts, destination } = this;
while (contexts.length > 0) {
const context = contexts.shift();
destination.next(context.buffer);
}
super._complete();
}
_unsubscribe() {
this.contexts = null;
}
onBufferFull(context) {
this.closeContext(context);
const closeAction = context.closeAction;
closeAction.unsubscribe();
this.remove(closeAction);
if (!this.closed && this.timespanOnly) {
context = this.openContext();
const bufferTimeSpan = this.bufferTimeSpan;
const timeSpanOnlyState = { subscriber: this, context, bufferTimeSpan };
this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
}
}
openContext() {
const context = new Context();
this.contexts.push(context);
return context;
}
closeContext(context) {
this.destination.next(context.buffer);
const contexts = this.contexts;
const spliceIndex = contexts ? contexts.indexOf(context) : -1;
if (spliceIndex >= 0) {
contexts.splice(contexts.indexOf(context), 1);
}
}
}
function dispatchBufferTimeSpanOnly(state) {
const subscriber = state.subscriber;
const prevContext = state.context;
if (prevContext) {
subscriber.closeContext(prevContext);
}
if (!subscriber.closed) {
state.context = subscriber.openContext();
state.context.closeAction = this.schedule(state, state.bufferTimeSpan);
}
}
function dispatchBufferCreation(state) {
const { bufferCreationInterval, bufferTimeSpan, subscriber, scheduler } = state;
const context = subscriber.openContext();
const action = this;
if (!subscriber.closed) {
subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber, context }));
action.schedule(state, bufferCreationInterval);
}
}
function dispatchBufferClose(arg) {
const { subscriber, context } = arg;
subscriber.closeContext(context);
}
//# sourceMappingURL=bufferTime.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/bufferToggle.js":
/*!***********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/bufferToggle.js ***!
\***********************************************************************/
/*! exports provided: bufferToggle */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferToggle", function() { return bufferToggle; });
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
function bufferToggle(openings, closingSelector) {
return function bufferToggleOperatorFunction(source) {
return source.lift(new BufferToggleOperator(openings, closingSelector));
};
}
class BufferToggleOperator {
constructor(openings, closingSelector) {
this.openings = openings;
this.closingSelector = closingSelector;
}
call(subscriber, source) {
return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector));
}
}
class BufferToggleSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"] {
constructor(destination, openings, closingSelector) {
super(destination);
this.openings = openings;
this.closingSelector = closingSelector;
this.contexts = [];
this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, openings));
}
_next(value) {
const contexts = this.contexts;
const len = contexts.length;
for (let i = 0; i < len; i++) {
contexts[i].buffer.push(value);
}
}
_error(err) {
const contexts = this.contexts;
while (contexts.length > 0) {
const context = contexts.shift();
context.subscription.unsubscribe();
context.buffer = null;
context.subscription = null;
}
this.contexts = null;
super._error(err);
}
_complete() {
const contexts = this.contexts;
while (contexts.length > 0) {
const context = contexts.shift();
this.destination.next(context.buffer);
context.subscription.unsubscribe();
context.buffer = null;
context.subscription = null;
}
this.contexts = null;
super._complete();
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue);
}
notifyComplete(innerSub) {
this.closeBuffer(innerSub.context);
}
openBuffer(value) {
try {
const closingSelector = this.closingSelector;
const closingNotifier = closingSelector.call(this, value);
if (closingNotifier) {
this.trySubscribe(closingNotifier);
}
}
catch (err) {
this._error(err);
}
}
closeBuffer(context) {
const contexts = this.contexts;
if (contexts && context) {
const { buffer, subscription } = context;
this.destination.next(buffer);
contexts.splice(contexts.indexOf(context), 1);
this.remove(subscription);
subscription.unsubscribe();
}
}
trySubscribe(closingNotifier) {
const contexts = this.contexts;
const buffer = [];
const subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_0__["Subscription"]();
const context = { buffer, subscription };
contexts.push(context);
const innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, closingNotifier, context);
if (!innerSubscription || innerSubscription.closed) {
this.closeBuffer(context);
}
else {
innerSubscription.context = context;
this.add(innerSubscription);
subscription.add(innerSubscription);
}
}
}
//# sourceMappingURL=bufferToggle.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/bufferWhen.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/bufferWhen.js ***!
\*********************************************************************/
/*! exports provided: bufferWhen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferWhen", function() { return bufferWhen; });
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function bufferWhen(closingSelector) {
return function (source) {
return source.lift(new BufferWhenOperator(closingSelector));
};
}
class BufferWhenOperator {
constructor(closingSelector) {
this.closingSelector = closingSelector;
}
call(subscriber, source) {
return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
}
}
class BufferWhenSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"] {
constructor(destination, closingSelector) {
super(destination);
this.closingSelector = closingSelector;
this.subscribing = false;
this.openBuffer();
}
_next(value) {
this.buffer.push(value);
}
_complete() {
const buffer = this.buffer;
if (buffer) {
this.destination.next(buffer);
}
super._complete();
}
_unsubscribe() {
this.buffer = null;
this.subscribing = false;
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.openBuffer();
}
notifyComplete() {
if (this.subscribing) {
this.complete();
}
else {
this.openBuffer();
}
}
openBuffer() {
let { closingSubscription } = this;
if (closingSubscription) {
this.remove(closingSubscription);
closingSubscription.unsubscribe();
}
const buffer = this.buffer;
if (this.buffer) {
this.destination.next(buffer);
}
this.buffer = [];
let closingNotifier;
try {
const { closingSelector } = this;
closingNotifier = closingSelector();
}
catch (err) {
return this.error(err);
}
closingSubscription = new _Subscription__WEBPACK_IMPORTED_MODULE_0__["Subscription"]();
this.closingSubscription = closingSubscription;
this.add(closingSubscription);
this.subscribing = true;
closingSubscription.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, closingNotifier));
this.subscribing = false;
}
}
//# sourceMappingURL=bufferWhen.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/catchError.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/catchError.js ***!
\*********************************************************************/
/*! exports provided: catchError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "catchError", function() { return catchError; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../InnerSubscriber */ "./node_modules/rxjs/_esm2015/internal/InnerSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function catchError(selector) {
return function catchErrorOperatorFunction(source) {
const operator = new CatchOperator(selector);
const caught = source.lift(operator);
return (operator.caught = caught);
};
}
class CatchOperator {
constructor(selector) {
this.selector = selector;
}
call(subscriber, source) {
return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
}
}
class CatchSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, selector, caught) {
super(destination);
this.selector = selector;
this.caught = caught;
}
error(err) {
if (!this.isStopped) {
let result;
try {
result = this.selector(err, this.caught);
}
catch (err2) {
super.error(err2);
return;
}
this._unsubscribeAndRecycle();
const innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_1__["InnerSubscriber"](this, undefined, undefined);
this.add(innerSubscriber);
const innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, result, undefined, undefined, innerSubscriber);
if (innerSubscription !== innerSubscriber) {
this.add(innerSubscription);
}
}
}
}
//# sourceMappingURL=catchError.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/combineAll.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/combineAll.js ***!
\*********************************************************************/
/*! exports provided: combineAll */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "combineAll", function() { return combineAll; });
/* harmony import */ var _observable_combineLatest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/combineLatest */ "./node_modules/rxjs/_esm2015/internal/observable/combineLatest.js");
function combineAll(project) {
return (source) => source.lift(new _observable_combineLatest__WEBPACK_IMPORTED_MODULE_0__["CombineLatestOperator"](project));
}
//# sourceMappingURL=combineAll.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/combineLatest.js":
/*!************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/combineLatest.js ***!
\************************************************************************/
/*! exports provided: combineLatest */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return combineLatest; });
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _observable_combineLatest__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../observable/combineLatest */ "./node_modules/rxjs/_esm2015/internal/observable/combineLatest.js");
/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../observable/from */ "./node_modules/rxjs/_esm2015/internal/observable/from.js");
const none = {};
function combineLatest(...observables) {
let project = null;
if (typeof observables[observables.length - 1] === 'function') {
project = observables.pop();
}
if (observables.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(observables[0])) {
observables = observables[0].slice();
}
return (source) => source.lift.call(Object(_observable_from__WEBPACK_IMPORTED_MODULE_2__["from"])([source, ...observables]), new _observable_combineLatest__WEBPACK_IMPORTED_MODULE_1__["CombineLatestOperator"](project));
}
//# sourceMappingURL=combineLatest.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/concat.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/concat.js ***!
\*****************************************************************/
/*! exports provided: concat */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return concat; });
/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/concat */ "./node_modules/rxjs/_esm2015/internal/observable/concat.js");
function concat(...observables) {
return (source) => source.lift.call(Object(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"])(source, ...observables));
}
//# sourceMappingURL=concat.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/concatAll.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/concatAll.js ***!
\********************************************************************/
/*! exports provided: concatAll */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatAll", function() { return concatAll; });
/* harmony import */ var _mergeAll__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mergeAll */ "./node_modules/rxjs/_esm2015/internal/operators/mergeAll.js");
function concatAll() {
return Object(_mergeAll__WEBPACK_IMPORTED_MODULE_0__["mergeAll"])(1);
}
//# sourceMappingURL=concatAll.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/concatMap.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/concatMap.js ***!
\********************************************************************/
/*! exports provided: concatMap */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatMap", function() { return concatMap; });
/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mergeMap */ "./node_modules/rxjs/_esm2015/internal/operators/mergeMap.js");
function concatMap(project, resultSelector) {
return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(project, resultSelector, 1);
}
//# sourceMappingURL=concatMap.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/concatMapTo.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/concatMapTo.js ***!
\**********************************************************************/
/*! exports provided: concatMapTo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatMapTo", function() { return concatMapTo; });
/* harmony import */ var _concatMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./concatMap */ "./node_modules/rxjs/_esm2015/internal/operators/concatMap.js");
function concatMapTo(innerObservable, resultSelector) {
return Object(_concatMap__WEBPACK_IMPORTED_MODULE_0__["concatMap"])(() => innerObservable, resultSelector);
}
//# sourceMappingURL=concatMapTo.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/count.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/count.js ***!
\****************************************************************/
/*! exports provided: count */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "count", function() { return count; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function count(predicate) {
return (source) => source.lift(new CountOperator(predicate, source));
}
class CountOperator {
constructor(predicate, source) {
this.predicate = predicate;
this.source = source;
}
call(subscriber, source) {
return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source));
}
}
class CountSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, predicate, source) {
super(destination);
this.predicate = predicate;
this.source = source;
this.count = 0;
this.index = 0;
}
_next(value) {
if (this.predicate) {
this._tryPredicate(value);
}
else {
this.count++;
}
}
_tryPredicate(value) {
let result;
try {
result = this.predicate(value, this.index++, this.source);
}
catch (err) {
this.destination.error(err);
return;
}
if (result) {
this.count++;
}
}
_complete() {
this.destination.next(this.count);
this.destination.complete();
}
}
//# sourceMappingURL=count.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/debounce.js":
/*!*******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/debounce.js ***!
\*******************************************************************/
/*! exports provided: debounce */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return debounce; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function debounce(durationSelector) {
return (source) => source.lift(new DebounceOperator(durationSelector));
}
class DebounceOperator {
constructor(durationSelector) {
this.durationSelector = durationSelector;
}
call(subscriber, source) {
return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector));
}
}
class DebounceSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, durationSelector) {
super(destination);
this.durationSelector = durationSelector;
this.hasValue = false;
this.durationSubscription = null;
}
_next(value) {
try {
const result = this.durationSelector.call(this, value);
if (result) {
this._tryNext(value, result);
}
}
catch (err) {
this.destination.error(err);
}
}
_complete() {
this.emitValue();
this.destination.complete();
}
_tryNext(value, duration) {
let subscription = this.durationSubscription;
this.value = value;
this.hasValue = true;
if (subscription) {
subscription.unsubscribe();
this.remove(subscription);
}
subscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, duration);
if (subscription && !subscription.closed) {
this.add(this.durationSubscription = subscription);
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.emitValue();
}
notifyComplete() {
this.emitValue();
}
emitValue() {
if (this.hasValue) {
const value = this.value;
const subscription = this.durationSubscription;
if (subscription) {
this.durationSubscription = null;
subscription.unsubscribe();
this.remove(subscription);
}
this.value = null;
this.hasValue = false;
super._next(value);
}
}
}
//# sourceMappingURL=debounce.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/debounceTime.js":
/*!***********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/debounceTime.js ***!
\***********************************************************************/
/*! exports provided: debounceTime */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debounceTime", function() { return debounceTime; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
function debounceTime(dueTime, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]) {
return (source) => source.lift(new DebounceTimeOperator(dueTime, scheduler));
}
class DebounceTimeOperator {
constructor(dueTime, scheduler) {
this.dueTime = dueTime;
this.scheduler = scheduler;
}
call(subscriber, source) {
return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
}
}
class DebounceTimeSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, dueTime, scheduler) {
super(destination);
this.dueTime = dueTime;
this.scheduler = scheduler;
this.debouncedSubscription = null;
this.lastValue = null;
this.hasValue = false;
}
_next(value) {
this.clearDebounce();
this.lastValue = value;
this.hasValue = true;
this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
}
_complete() {
this.debouncedNext();
this.destination.complete();
}
debouncedNext() {
this.clearDebounce();
if (this.hasValue) {
const { lastValue } = this;
this.lastValue = null;
this.hasValue = false;
this.destination.next(lastValue);
}
}
clearDebounce() {
const debouncedSubscription = this.debouncedSubscription;
if (debouncedSubscription !== null) {
this.remove(debouncedSubscription);
debouncedSubscription.unsubscribe();
this.debouncedSubscription = null;
}
}
}
function dispatchNext(subscriber) {
subscriber.debouncedNext();
}
//# sourceMappingURL=debounceTime.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/defaultIfEmpty.js":
/*!*************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/defaultIfEmpty.js ***!
\*************************************************************************/
/*! exports provided: defaultIfEmpty */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultIfEmpty", function() { return defaultIfEmpty; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function defaultIfEmpty(defaultValue = null) {
return (source) => source.lift(new DefaultIfEmptyOperator(defaultValue));
}
class DefaultIfEmptyOperator {
constructor(defaultValue) {
this.defaultValue = defaultValue;
}
call(subscriber, source) {
return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
}
}
class DefaultIfEmptySubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, defaultValue) {
super(destination);
this.defaultValue = defaultValue;
this.isEmpty = true;
}
_next(value) {
this.isEmpty = false;
this.destination.next(value);
}
_complete() {
if (this.isEmpty) {
this.destination.next(this.defaultValue);
}
this.destination.complete();
}
}
//# sourceMappingURL=defaultIfEmpty.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/delay.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/delay.js ***!
\****************************************************************/
/*! exports provided: delay */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "delay", function() { return delay; });
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _util_isDate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isDate */ "./node_modules/rxjs/_esm2015/internal/util/isDate.js");
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Notification */ "./node_modules/rxjs/_esm2015/internal/Notification.js");
function delay(delay, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]) {
const absoluteDelay = Object(_util_isDate__WEBPACK_IMPORTED_MODULE_1__["isDate"])(delay);
const delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
return (source) => source.lift(new DelayOperator(delayFor, scheduler));
}
class DelayOperator {
constructor(delay, scheduler) {
this.delay = delay;
this.scheduler = scheduler;
}
call(subscriber, source) {
return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
}
}
class DelaySubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_2__["Subscriber"] {
constructor(destination, delay, scheduler) {
super(destination);
this.delay = delay;
this.scheduler = scheduler;
this.queue = [];
this.active = false;
this.errored = false;
}
static dispatch(state) {
const source = state.source;
const queue = source.queue;
const scheduler = state.scheduler;
const destination = state.destination;
while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
queue.shift().notification.observe(destination);
}
if (queue.length > 0) {
const delay = Math.max(0, queue[0].time - scheduler.now());
this.schedule(state, delay);
}
else {
this.unsubscribe();
source.active = false;
}
}
_schedule(scheduler) {
this.active = true;
const destination = this.destination;
destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
source: this, destination: this.destination, scheduler: scheduler
}));
}
scheduleNotification(notification) {
if (this.errored === true) {
return;
}
const scheduler = this.scheduler;
const message = new DelayMessage(scheduler.now() + this.delay, notification);
this.queue.push(message);
if (this.active === false) {
this._schedule(scheduler);
}
}
_next(value) {
this.scheduleNotification(_Notification__WEBPACK_IMPORTED_MODULE_3__["Notification"].createNext(value));
}
_error(err) {
this.errored = true;
this.queue = [];
this.destination.error(err);
this.unsubscribe();
}
_complete() {
this.scheduleNotification(_Notification__WEBPACK_IMPORTED_MODULE_3__["Notification"].createComplete());
this.unsubscribe();
}
}
class DelayMessage {
constructor(time, notification) {
this.time = time;
this.notification = notification;
}
}
//# sourceMappingURL=delay.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/delayWhen.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/delayWhen.js ***!
\********************************************************************/
/*! exports provided: delayWhen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "delayWhen", function() { return delayWhen; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function delayWhen(delayDurationSelector, subscriptionDelay) {
if (subscriptionDelay) {
return (source) => new SubscriptionDelayObservable(source, subscriptionDelay)
.lift(new DelayWhenOperator(delayDurationSelector));
}
return (source) => source.lift(new DelayWhenOperator(delayDurationSelector));
}
class DelayWhenOperator {
constructor(delayDurationSelector) {
this.delayDurationSelector = delayDurationSelector;
}
call(subscriber, source) {
return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector));
}
}
class DelayWhenSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"] {
constructor(destination, delayDurationSelector) {
super(destination);
this.delayDurationSelector = delayDurationSelector;
this.completed = false;
this.delayNotifierSubscriptions = [];
this.index = 0;
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.destination.next(outerValue);
this.removeSubscription(innerSub);
this.tryComplete();
}
notifyError(error, innerSub) {
this._error(error);
}
notifyComplete(innerSub) {
const value = this.removeSubscription(innerSub);
if (value) {
this.destination.next(value);
}
this.tryComplete();
}
_next(value) {
const index = this.index++;
try {
const delayNotifier = this.delayDurationSelector(value, index);
if (delayNotifier) {
this.tryDelay(delayNotifier, value);
}
}
catch (err) {
this.destination.error(err);
}
}
_complete() {
this.completed = true;
this.tryComplete();
this.unsubscribe();
}
removeSubscription(subscription) {
subscription.unsubscribe();
const subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);
if (subscriptionIdx !== -1) {
this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);
}
return subscription.outerValue;
}
tryDelay(delayNotifier, value) {
const notifierSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, delayNotifier, value);
if (notifierSubscription && !notifierSubscription.closed) {
const destination = this.destination;
destination.add(notifierSubscription);
this.delayNotifierSubscriptions.push(notifierSubscription);
}
}
tryComplete() {
if (this.completed && this.delayNotifierSubscriptions.length === 0) {
this.destination.complete();
}
}
}
class SubscriptionDelayObservable extends _Observable__WEBPACK_IMPORTED_MODULE_1__["Observable"] {
constructor(source, subscriptionDelay) {
super();
this.source = source;
this.subscriptionDelay = subscriptionDelay;
}
_subscribe(subscriber) {
this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source));
}
}
class SubscriptionDelaySubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(parent, source) {
super();
this.parent = parent;
this.source = source;
this.sourceSubscribed = false;
}
_next(unused) {
this.subscribeToSource();
}
_error(err) {
this.unsubscribe();
this.parent.error(err);
}
_complete() {
this.unsubscribe();
this.subscribeToSource();
}
subscribeToSource() {
if (!this.sourceSubscribed) {
this.sourceSubscribed = true;
this.unsubscribe();
this.source.subscribe(this.parent);
}
}
}
//# sourceMappingURL=delayWhen.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/dematerialize.js":
/*!************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/dematerialize.js ***!
\************************************************************************/
/*! exports provided: dematerialize */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dematerialize", function() { return dematerialize; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function dematerialize() {
return function dematerializeOperatorFunction(source) {
return source.lift(new DeMaterializeOperator());
};
}
class DeMaterializeOperator {
call(subscriber, source) {
return source.subscribe(new DeMaterializeSubscriber(subscriber));
}
}
class DeMaterializeSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination) {
super(destination);
}
_next(value) {
value.observe(this.destination);
}
}
//# sourceMappingURL=dematerialize.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/distinct.js":
/*!*******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/distinct.js ***!
\*******************************************************************/
/*! exports provided: distinct, DistinctSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "distinct", function() { return distinct; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DistinctSubscriber", function() { return DistinctSubscriber; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function distinct(keySelector, flushes) {
return (source) => source.lift(new DistinctOperator(keySelector, flushes));
}
class DistinctOperator {
constructor(keySelector, flushes) {
this.keySelector = keySelector;
this.flushes = flushes;
}
call(subscriber, source) {
return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
}
}
class DistinctSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, keySelector, flushes) {
super(destination);
this.keySelector = keySelector;
this.values = new Set();
if (flushes) {
this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, flushes));
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.values.clear();
}
notifyError(error, innerSub) {
this._error(error);
}
_next(value) {
if (this.keySelector) {
this._useKeySelector(value);
}
else {
this._finalizeNext(value, value);
}
}
_useKeySelector(value) {
let key;
const { destination } = this;
try {
key = this.keySelector(value);
}
catch (err) {
destination.error(err);
return;
}
this._finalizeNext(key, value);
}
_finalizeNext(key, value) {
const { values } = this;
if (!values.has(key)) {
values.add(key);
this.destination.next(value);
}
}
}
//# sourceMappingURL=distinct.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/distinctUntilChanged.js":
/*!*******************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/distinctUntilChanged.js ***!
\*******************************************************************************/
/*! exports provided: distinctUntilChanged */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "distinctUntilChanged", function() { return distinctUntilChanged; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function distinctUntilChanged(compare, keySelector) {
return (source) => source.lift(new DistinctUntilChangedOperator(compare, keySelector));
}
class DistinctUntilChangedOperator {
constructor(compare, keySelector) {
this.compare = compare;
this.keySelector = keySelector;
}
call(subscriber, source) {
return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
}
}
class DistinctUntilChangedSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, compare, keySelector) {
super(destination);
this.keySelector = keySelector;
this.hasKey = false;
if (typeof compare === 'function') {
this.compare = compare;
}
}
compare(x, y) {
return x === y;
}
_next(value) {
let key;
try {
const { keySelector } = this;
key = keySelector ? keySelector(value) : value;
}
catch (err) {
return this.destination.error(err);
}
let result = false;
if (this.hasKey) {
try {
const { compare } = this;
result = compare(this.key, key);
}
catch (err) {
return this.destination.error(err);
}
}
else {
this.hasKey = true;
}
if (!result) {
this.key = key;
this.destination.next(value);
}
}
}
//# sourceMappingURL=distinctUntilChanged.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/distinctUntilKeyChanged.js":
/*!**********************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/distinctUntilKeyChanged.js ***!
\**********************************************************************************/
/*! exports provided: distinctUntilKeyChanged */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "distinctUntilKeyChanged", function() { return distinctUntilKeyChanged; });
/* harmony import */ var _distinctUntilChanged__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./distinctUntilChanged */ "./node_modules/rxjs/_esm2015/internal/operators/distinctUntilChanged.js");
function distinctUntilKeyChanged(key, compare) {
return Object(_distinctUntilChanged__WEBPACK_IMPORTED_MODULE_0__["distinctUntilChanged"])((x, y) => compare ? compare(x[key], y[key]) : x[key] === y[key]);
}
//# sourceMappingURL=distinctUntilKeyChanged.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/elementAt.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/elementAt.js ***!
\********************************************************************/
/*! exports provided: elementAt */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "elementAt", function() { return elementAt; });
/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/ArgumentOutOfRangeError */ "./node_modules/rxjs/_esm2015/internal/util/ArgumentOutOfRangeError.js");
/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./filter */ "./node_modules/rxjs/_esm2015/internal/operators/filter.js");
/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./throwIfEmpty */ "./node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js");
/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./defaultIfEmpty */ "./node_modules/rxjs/_esm2015/internal/operators/defaultIfEmpty.js");
/* harmony import */ var _take__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./take */ "./node_modules/rxjs/_esm2015/internal/operators/take.js");
function elementAt(index, defaultValue) {
if (index < 0) {
throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_0__["ArgumentOutOfRangeError"]();
}
const hasDefaultValue = arguments.length >= 2;
return (source) => source.pipe(Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])((v, i) => i === index), Object(_take__WEBPACK_IMPORTED_MODULE_4__["take"])(1), hasDefaultValue
? Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__["defaultIfEmpty"])(defaultValue)
: Object(_throwIfEmpty__WEBPACK_IMPORTED_MODULE_2__["throwIfEmpty"])(() => new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_0__["ArgumentOutOfRangeError"]()));
}
//# sourceMappingURL=elementAt.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/endWith.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/endWith.js ***!
\******************************************************************/
/*! exports provided: endWith */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "endWith", function() { return endWith; });
/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/concat */ "./node_modules/rxjs/_esm2015/internal/observable/concat.js");
/* harmony import */ var _observable_of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../observable/of */ "./node_modules/rxjs/_esm2015/internal/observable/of.js");
function endWith(...array) {
return (source) => Object(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"])(source, Object(_observable_of__WEBPACK_IMPORTED_MODULE_1__["of"])(...array));
}
//# sourceMappingURL=endWith.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/every.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/every.js ***!
\****************************************************************/
/*! exports provided: every */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "every", function() { return every; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function every(predicate, thisArg) {
return (source) => source.lift(new EveryOperator(predicate, thisArg, source));
}
class EveryOperator {
constructor(predicate, thisArg, source) {
this.predicate = predicate;
this.thisArg = thisArg;
this.source = source;
}
call(observer, source) {
return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));
}
}
class EverySubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, predicate, thisArg, source) {
super(destination);
this.predicate = predicate;
this.thisArg = thisArg;
this.source = source;
this.index = 0;
this.thisArg = thisArg || this;
}
notifyComplete(everyValueMatch) {
this.destination.next(everyValueMatch);
this.destination.complete();
}
_next(value) {
let result = false;
try {
result = this.predicate.call(this.thisArg, value, this.index++, this.source);
}
catch (err) {
this.destination.error(err);
return;
}
if (!result) {
this.notifyComplete(false);
}
}
_complete() {
this.notifyComplete(true);
}
}
//# sourceMappingURL=every.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/exhaust.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/exhaust.js ***!
\******************************************************************/
/*! exports provided: exhaust */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exhaust", function() { return exhaust; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function exhaust() {
return (source) => source.lift(new SwitchFirstOperator());
}
class SwitchFirstOperator {
call(subscriber, source) {
return source.subscribe(new SwitchFirstSubscriber(subscriber));
}
}
class SwitchFirstSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination) {
super(destination);
this.hasCompleted = false;
this.hasSubscription = false;
}
_next(value) {
if (!this.hasSubscription) {
this.hasSubscription = true;
this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, value));
}
}
_complete() {
this.hasCompleted = true;
if (!this.hasSubscription) {
this.destination.complete();
}
}
notifyComplete(innerSub) {
this.remove(innerSub);
this.hasSubscription = false;
if (this.hasCompleted) {
this.destination.complete();
}
}
}
//# sourceMappingURL=exhaust.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/exhaustMap.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/exhaustMap.js ***!
\*********************************************************************/
/*! exports provided: exhaustMap */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exhaustMap", function() { return exhaustMap; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../InnerSubscriber */ "./node_modules/rxjs/_esm2015/internal/InnerSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../observable/from */ "./node_modules/rxjs/_esm2015/internal/observable/from.js");
function exhaustMap(project, resultSelector) {
if (resultSelector) {
return (source) => source.pipe(exhaustMap((a, i) => Object(_observable_from__WEBPACK_IMPORTED_MODULE_4__["from"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_3__["map"])((b, ii) => resultSelector(a, b, i, ii)))));
}
return (source) => source.lift(new ExhaustMapOperator(project));
}
class ExhaustMapOperator {
constructor(project) {
this.project = project;
}
call(subscriber, source) {
return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project));
}
}
class ExhaustMapSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, project) {
super(destination);
this.project = project;
this.hasSubscription = false;
this.hasCompleted = false;
this.index = 0;
}
_next(value) {
if (!this.hasSubscription) {
this.tryNext(value);
}
}
tryNext(value) {
let result;
const index = this.index++;
try {
result = this.project(value, index);
}
catch (err) {
this.destination.error(err);
return;
}
this.hasSubscription = true;
this._innerSub(result, value, index);
}
_innerSub(result, value, index) {
const innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_1__["InnerSubscriber"](this, value, index);
const destination = this.destination;
destination.add(innerSubscriber);
const innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, result, undefined, undefined, innerSubscriber);
if (innerSubscription !== innerSubscriber) {
destination.add(innerSubscription);
}
}
_complete() {
this.hasCompleted = true;
if (!this.hasSubscription) {
this.destination.complete();
}
this.unsubscribe();
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.destination.next(innerValue);
}
notifyError(err) {
this.destination.error(err);
}
notifyComplete(innerSub) {
const destination = this.destination;
destination.remove(innerSub);
this.hasSubscription = false;
if (this.hasCompleted) {
this.destination.complete();
}
}
}
//# sourceMappingURL=exhaustMap.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/expand.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/expand.js ***!
\*****************************************************************/
/*! exports provided: expand, ExpandOperator, ExpandSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expand", function() { return expand; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExpandOperator", function() { return ExpandOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExpandSubscriber", function() { return ExpandSubscriber; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function expand(project, concurrent = Number.POSITIVE_INFINITY, scheduler = undefined) {
concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
return (source) => source.lift(new ExpandOperator(project, concurrent, scheduler));
}
class ExpandOperator {
constructor(project, concurrent, scheduler) {
this.project = project;
this.concurrent = concurrent;
this.scheduler = scheduler;
}
call(subscriber, source) {
return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
}
}
class ExpandSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, project, concurrent, scheduler) {
super(destination);
this.project = project;
this.concurrent = concurrent;
this.scheduler = scheduler;
this.index = 0;
this.active = 0;
this.hasCompleted = false;
if (concurrent < Number.POSITIVE_INFINITY) {
this.buffer = [];
}
}
static dispatch(arg) {
const { subscriber, result, value, index } = arg;
subscriber.subscribeToProjection(result, value, index);
}
_next(value) {
const destination = this.destination;
if (destination.closed) {
this._complete();
return;
}
const index = this.index++;
if (this.active < this.concurrent) {
destination.next(value);
try {
const { project } = this;
const result = project(value, index);
if (!this.scheduler) {
this.subscribeToProjection(result, value, index);
}
else {
const state = { subscriber: this, result, value, index };
const destination = this.destination;
destination.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
}
}
catch (e) {
destination.error(e);
}
}
else {
this.buffer.push(value);
}
}
subscribeToProjection(result, value, index) {
this.active++;
const destination = this.destination;
destination.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, result, value, index));
}
_complete() {
this.hasCompleted = true;
if (this.hasCompleted && this.active === 0) {
this.destination.complete();
}
this.unsubscribe();
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this._next(innerValue);
}
notifyComplete(innerSub) {
const buffer = this.buffer;
const destination = this.destination;
destination.remove(innerSub);
this.active--;
if (buffer && buffer.length > 0) {
this._next(buffer.shift());
}
if (this.hasCompleted && this.active === 0) {
this.destination.complete();
}
}
}
//# sourceMappingURL=expand.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/filter.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/filter.js ***!
\*****************************************************************/
/*! exports provided: filter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return filter; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function filter(predicate, thisArg) {
return function filterOperatorFunction(source) {
return source.lift(new FilterOperator(predicate, thisArg));
};
}
class FilterOperator {
constructor(predicate, thisArg) {
this.predicate = predicate;
this.thisArg = thisArg;
}
call(subscriber, source) {
return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
}
}
class FilterSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, predicate, thisArg) {
super(destination);
this.predicate = predicate;
this.thisArg = thisArg;
this.count = 0;
}
_next(value) {
let result;
try {
result = this.predicate.call(this.thisArg, value, this.count++);
}
catch (err) {
this.destination.error(err);
return;
}
if (result) {
this.destination.next(value);
}
}
}
//# sourceMappingURL=filter.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/finalize.js":
/*!*******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/finalize.js ***!
\*******************************************************************/
/*! exports provided: finalize */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "finalize", function() { return finalize; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
function finalize(callback) {
return (source) => source.lift(new FinallyOperator(callback));
}
class FinallyOperator {
constructor(callback) {
this.callback = callback;
}
call(subscriber, source) {
return source.subscribe(new FinallySubscriber(subscriber, this.callback));
}
}
class FinallySubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, callback) {
super(destination);
this.add(new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](callback));
}
}
//# sourceMappingURL=finalize.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/find.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/find.js ***!
\***************************************************************/
/*! exports provided: find, FindValueOperator, FindValueSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "find", function() { return find; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FindValueOperator", function() { return FindValueOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FindValueSubscriber", function() { return FindValueSubscriber; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function find(predicate, thisArg) {
if (typeof predicate !== 'function') {
throw new TypeError('predicate is not a function');
}
return (source) => source.lift(new FindValueOperator(predicate, source, false, thisArg));
}
class FindValueOperator {
constructor(predicate, source, yieldIndex, thisArg) {
this.predicate = predicate;
this.source = source;
this.yieldIndex = yieldIndex;
this.thisArg = thisArg;
}
call(observer, source) {
return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));
}
}
class FindValueSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, predicate, source, yieldIndex, thisArg) {
super(destination);
this.predicate = predicate;
this.source = source;
this.yieldIndex = yieldIndex;
this.thisArg = thisArg;
this.index = 0;
}
notifyComplete(value) {
const destination = this.destination;
destination.next(value);
destination.complete();
this.unsubscribe();
}
_next(value) {
const { predicate, thisArg } = this;
const index = this.index++;
try {
const result = predicate.call(thisArg || this, value, index, this.source);
if (result) {
this.notifyComplete(this.yieldIndex ? index : value);
}
}
catch (err) {
this.destination.error(err);
}
}
_complete() {
this.notifyComplete(this.yieldIndex ? -1 : undefined);
}
}
//# sourceMappingURL=find.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/findIndex.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/findIndex.js ***!
\********************************************************************/
/*! exports provided: findIndex */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findIndex", function() { return findIndex; });
/* harmony import */ var _operators_find__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../operators/find */ "./node_modules/rxjs/_esm2015/internal/operators/find.js");
function findIndex(predicate, thisArg) {
return (source) => source.lift(new _operators_find__WEBPACK_IMPORTED_MODULE_0__["FindValueOperator"](predicate, source, true, thisArg));
}
//# sourceMappingURL=findIndex.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/first.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/first.js ***!
\****************************************************************/
/*! exports provided: first */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "first", function() { return first; });
/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/EmptyError */ "./node_modules/rxjs/_esm2015/internal/util/EmptyError.js");
/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./filter */ "./node_modules/rxjs/_esm2015/internal/operators/filter.js");
/* harmony import */ var _take__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./take */ "./node_modules/rxjs/_esm2015/internal/operators/take.js");
/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./defaultIfEmpty */ "./node_modules/rxjs/_esm2015/internal/operators/defaultIfEmpty.js");
/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./throwIfEmpty */ "./node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js");
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/identity */ "./node_modules/rxjs/_esm2015/internal/util/identity.js");
function first(predicate, defaultValue) {
const hasDefaultValue = arguments.length >= 2;
return (source) => source.pipe(predicate ? Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])((v, i) => predicate(v, i, source)) : _util_identity__WEBPACK_IMPORTED_MODULE_5__["identity"], Object(_take__WEBPACK_IMPORTED_MODULE_2__["take"])(1), hasDefaultValue ? Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__["defaultIfEmpty"])(defaultValue) : Object(_throwIfEmpty__WEBPACK_IMPORTED_MODULE_4__["throwIfEmpty"])(() => new _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__["EmptyError"]()));
}
//# sourceMappingURL=first.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/groupBy.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/groupBy.js ***!
\******************************************************************/
/*! exports provided: groupBy, GroupedObservable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return groupBy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GroupedObservable", function() { return GroupedObservable; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) {
return (source) => source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));
}
class GroupByOperator {
constructor(keySelector, elementSelector, durationSelector, subjectSelector) {
this.keySelector = keySelector;
this.elementSelector = elementSelector;
this.durationSelector = durationSelector;
this.subjectSelector = subjectSelector;
}
call(subscriber, source) {
return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector));
}
}
class GroupBySubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, keySelector, elementSelector, durationSelector, subjectSelector) {
super(destination);
this.keySelector = keySelector;
this.elementSelector = elementSelector;
this.durationSelector = durationSelector;
this.subjectSelector = subjectSelector;
this.groups = null;
this.attemptedToUnsubscribe = false;
this.count = 0;
}
_next(value) {
let key;
try {
key = this.keySelector(value);
}
catch (err) {
this.error(err);
return;
}
this._group(value, key);
}
_group(value, key) {
let groups = this.groups;
if (!groups) {
groups = this.groups = new Map();
}
let group = groups.get(key);
let element;
if (this.elementSelector) {
try {
element = this.elementSelector(value);
}
catch (err) {
this.error(err);
}
}
else {
element = value;
}
if (!group) {
group = (this.subjectSelector ? this.subjectSelector() : new _Subject__WEBPACK_IMPORTED_MODULE_3__["Subject"]());
groups.set(key, group);
const groupedObservable = new GroupedObservable(key, group, this);
this.destination.next(groupedObservable);
if (this.durationSelector) {
let duration;
try {
duration = this.durationSelector(new GroupedObservable(key, group));
}
catch (err) {
this.error(err);
return;
}
this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));
}
}
if (!group.closed) {
group.next(element);
}
}
_error(err) {
const groups = this.groups;
if (groups) {
groups.forEach((group, key) => {
group.error(err);
});
groups.clear();
}
this.destination.error(err);
}
_complete() {
const groups = this.groups;
if (groups) {
groups.forEach((group, key) => {
group.complete();
});
groups.clear();
}
this.destination.complete();
}
removeGroup(key) {
this.groups.delete(key);
}
unsubscribe() {
if (!this.closed) {
this.attemptedToUnsubscribe = true;
if (this.count === 0) {
super.unsubscribe();
}
}
}
}
class GroupDurationSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(key, group, parent) {
super(group);
this.key = key;
this.group = group;
this.parent = parent;
}
_next(value) {
this.complete();
}
_unsubscribe() {
const { parent, key } = this;
this.key = this.parent = null;
if (parent) {
parent.removeGroup(key);
}
}
}
class GroupedObservable extends _Observable__WEBPACK_IMPORTED_MODULE_2__["Observable"] {
constructor(key, groupSubject, refCountSubscription) {
super();
this.key = key;
this.groupSubject = groupSubject;
this.refCountSubscription = refCountSubscription;
}
_subscribe(subscriber) {
const subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"]();
const { refCountSubscription, groupSubject } = this;
if (refCountSubscription && !refCountSubscription.closed) {
subscription.add(new InnerRefCountSubscription(refCountSubscription));
}
subscription.add(groupSubject.subscribe(subscriber));
return subscription;
}
}
class InnerRefCountSubscription extends _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"] {
constructor(parent) {
super();
this.parent = parent;
parent.count++;
}
unsubscribe() {
const parent = this.parent;
if (!parent.closed && !this.closed) {
super.unsubscribe();
parent.count -= 1;
if (parent.count === 0 && parent.attemptedToUnsubscribe) {
parent.unsubscribe();
}
}
}
}
//# sourceMappingURL=groupBy.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/ignoreElements.js":
/*!*************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/ignoreElements.js ***!
\*************************************************************************/
/*! exports provided: ignoreElements */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ignoreElements", function() { return ignoreElements; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function ignoreElements() {
return function ignoreElementsOperatorFunction(source) {
return source.lift(new IgnoreElementsOperator());
};
}
class IgnoreElementsOperator {
call(subscriber, source) {
return source.subscribe(new IgnoreElementsSubscriber(subscriber));
}
}
class IgnoreElementsSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
_next(unused) {
}
}
//# sourceMappingURL=ignoreElements.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/isEmpty.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/isEmpty.js ***!
\******************************************************************/
/*! exports provided: isEmpty */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return isEmpty; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function isEmpty() {
return (source) => source.lift(new IsEmptyOperator());
}
class IsEmptyOperator {
call(observer, source) {
return source.subscribe(new IsEmptySubscriber(observer));
}
}
class IsEmptySubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination) {
super(destination);
}
notifyComplete(isEmpty) {
const destination = this.destination;
destination.next(isEmpty);
destination.complete();
}
_next(value) {
this.notifyComplete(false);
}
_complete() {
this.notifyComplete(true);
}
}
//# sourceMappingURL=isEmpty.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/last.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/last.js ***!
\***************************************************************/
/*! exports provided: last */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "last", function() { return last; });
/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/EmptyError */ "./node_modules/rxjs/_esm2015/internal/util/EmptyError.js");
/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./filter */ "./node_modules/rxjs/_esm2015/internal/operators/filter.js");
/* harmony import */ var _takeLast__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./takeLast */ "./node_modules/rxjs/_esm2015/internal/operators/takeLast.js");
/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./throwIfEmpty */ "./node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js");
/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./defaultIfEmpty */ "./node_modules/rxjs/_esm2015/internal/operators/defaultIfEmpty.js");
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/identity */ "./node_modules/rxjs/_esm2015/internal/util/identity.js");
function last(predicate, defaultValue) {
const hasDefaultValue = arguments.length >= 2;
return (source) => source.pipe(predicate ? Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])((v, i) => predicate(v, i, source)) : _util_identity__WEBPACK_IMPORTED_MODULE_5__["identity"], Object(_takeLast__WEBPACK_IMPORTED_MODULE_2__["takeLast"])(1), hasDefaultValue ? Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_4__["defaultIfEmpty"])(defaultValue) : Object(_throwIfEmpty__WEBPACK_IMPORTED_MODULE_3__["throwIfEmpty"])(() => new _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__["EmptyError"]()));
}
//# sourceMappingURL=last.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/map.js":
/*!**************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/map.js ***!
\**************************************************************/
/*! exports provided: map, MapOperator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "map", function() { return map; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MapOperator", function() { return MapOperator; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function map(project, thisArg) {
return function mapOperation(source) {
if (typeof project !== 'function') {
throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
}
return source.lift(new MapOperator(project, thisArg));
};
}
class MapOperator {
constructor(project, thisArg) {
this.project = project;
this.thisArg = thisArg;
}
call(subscriber, source) {
return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
}
}
class MapSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, project, thisArg) {
super(destination);
this.project = project;
this.count = 0;
this.thisArg = thisArg || this;
}
_next(value) {
let result;
try {
result = this.project.call(this.thisArg, value, this.count++);
}
catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
}
}
//# sourceMappingURL=map.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/mapTo.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/mapTo.js ***!
\****************************************************************/
/*! exports provided: mapTo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapTo", function() { return mapTo; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function mapTo(value) {
return (source) => source.lift(new MapToOperator(value));
}
class MapToOperator {
constructor(value) {
this.value = value;
}
call(subscriber, source) {
return source.subscribe(new MapToSubscriber(subscriber, this.value));
}
}
class MapToSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, value) {
super(destination);
this.value = value;
}
_next(x) {
this.destination.next(this.value);
}
}
//# sourceMappingURL=mapTo.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/materialize.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/materialize.js ***!
\**********************************************************************/
/*! exports provided: materialize */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "materialize", function() { return materialize; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Notification */ "./node_modules/rxjs/_esm2015/internal/Notification.js");
function materialize() {
return function materializeOperatorFunction(source) {
return source.lift(new MaterializeOperator());
};
}
class MaterializeOperator {
call(subscriber, source) {
return source.subscribe(new MaterializeSubscriber(subscriber));
}
}
class MaterializeSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination) {
super(destination);
}
_next(value) {
this.destination.next(_Notification__WEBPACK_IMPORTED_MODULE_1__["Notification"].createNext(value));
}
_error(err) {
const destination = this.destination;
destination.next(_Notification__WEBPACK_IMPORTED_MODULE_1__["Notification"].createError(err));
destination.complete();
}
_complete() {
const destination = this.destination;
destination.next(_Notification__WEBPACK_IMPORTED_MODULE_1__["Notification"].createComplete());
destination.complete();
}
}
//# sourceMappingURL=materialize.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/max.js":
/*!**************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/max.js ***!
\**************************************************************/
/*! exports provided: max */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "max", function() { return max; });
/* harmony import */ var _reduce__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reduce */ "./node_modules/rxjs/_esm2015/internal/operators/reduce.js");
function max(comparer) {
const max = (typeof comparer === 'function')
? (x, y) => comparer(x, y) > 0 ? x : y
: (x, y) => x > y ? x : y;
return Object(_reduce__WEBPACK_IMPORTED_MODULE_0__["reduce"])(max);
}
//# sourceMappingURL=max.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/merge.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/merge.js ***!
\****************************************************************/
/*! exports provided: merge */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return merge; });
/* harmony import */ var _observable_merge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/merge */ "./node_modules/rxjs/_esm2015/internal/observable/merge.js");
function merge(...observables) {
return (source) => source.lift.call(Object(_observable_merge__WEBPACK_IMPORTED_MODULE_0__["merge"])(source, ...observables));
}
//# sourceMappingURL=merge.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/mergeAll.js":
/*!*******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/mergeAll.js ***!
\*******************************************************************/
/*! exports provided: mergeAll */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeAll", function() { return mergeAll; });
/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mergeMap */ "./node_modules/rxjs/_esm2015/internal/operators/mergeMap.js");
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/identity */ "./node_modules/rxjs/_esm2015/internal/util/identity.js");
function mergeAll(concurrent = Number.POSITIVE_INFINITY) {
return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(_util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"], concurrent);
}
//# sourceMappingURL=mergeAll.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/mergeMap.js":
/*!*******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/mergeMap.js ***!
\*******************************************************************/
/*! exports provided: mergeMap, MergeMapOperator, MergeMapSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeMap", function() { return mergeMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeMapOperator", function() { return MergeMapOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeMapSubscriber", function() { return MergeMapSubscriber; });
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../InnerSubscriber */ "./node_modules/rxjs/_esm2015/internal/InnerSubscriber.js");
/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../observable/from */ "./node_modules/rxjs/_esm2015/internal/observable/from.js");
function mergeMap(project, resultSelector, concurrent = Number.POSITIVE_INFINITY) {
if (typeof resultSelector === 'function') {
return (source) => source.pipe(mergeMap((a, i) => Object(_observable_from__WEBPACK_IMPORTED_MODULE_4__["from"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_3__["map"])((b, ii) => resultSelector(a, b, i, ii))), concurrent));
}
else if (typeof resultSelector === 'number') {
concurrent = resultSelector;
}
return (source) => source.lift(new MergeMapOperator(project, concurrent));
}
class MergeMapOperator {
constructor(project, concurrent = Number.POSITIVE_INFINITY) {
this.project = project;
this.concurrent = concurrent;
}
call(observer, source) {
return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));
}
}
class MergeMapSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"] {
constructor(destination, project, concurrent = Number.POSITIVE_INFINITY) {
super(destination);
this.project = project;
this.concurrent = concurrent;
this.hasCompleted = false;
this.buffer = [];
this.active = 0;
this.index = 0;
}
_next(value) {
if (this.active < this.concurrent) {
this._tryNext(value);
}
else {
this.buffer.push(value);
}
}
_tryNext(value) {
let result;
const index = this.index++;
try {
result = this.project(value, index);
}
catch (err) {
this.destination.error(err);
return;
}
this.active++;
this._innerSub(result, value, index);
}
_innerSub(ish, value, index) {
const innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__["InnerSubscriber"](this, value, index);
const destination = this.destination;
destination.add(innerSubscriber);
const innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_0__["subscribeToResult"])(this, ish, undefined, undefined, innerSubscriber);
if (innerSubscription !== innerSubscriber) {
destination.add(innerSubscription);
}
}
_complete() {
this.hasCompleted = true;
if (this.active === 0 && this.buffer.length === 0) {
this.destination.complete();
}
this.unsubscribe();
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.destination.next(innerValue);
}
notifyComplete(innerSub) {
const buffer = this.buffer;
this.remove(innerSub);
this.active--;
if (buffer.length > 0) {
this._next(buffer.shift());
}
else if (this.active === 0 && this.hasCompleted) {
this.destination.complete();
}
}
}
//# sourceMappingURL=mergeMap.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/mergeMapTo.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/mergeMapTo.js ***!
\*********************************************************************/
/*! exports provided: mergeMapTo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeMapTo", function() { return mergeMapTo; });
/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mergeMap */ "./node_modules/rxjs/_esm2015/internal/operators/mergeMap.js");
function mergeMapTo(innerObservable, resultSelector, concurrent = Number.POSITIVE_INFINITY) {
if (typeof resultSelector === 'function') {
return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(() => innerObservable, resultSelector, concurrent);
}
if (typeof resultSelector === 'number') {
concurrent = resultSelector;
}
return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(() => innerObservable, concurrent);
}
//# sourceMappingURL=mergeMapTo.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/mergeScan.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/mergeScan.js ***!
\********************************************************************/
/*! exports provided: mergeScan, MergeScanOperator, MergeScanSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeScan", function() { return mergeScan; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeScanOperator", function() { return MergeScanOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeScanSubscriber", function() { return MergeScanSubscriber; });
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../InnerSubscriber */ "./node_modules/rxjs/_esm2015/internal/InnerSubscriber.js");
function mergeScan(accumulator, seed, concurrent = Number.POSITIVE_INFINITY) {
return (source) => source.lift(new MergeScanOperator(accumulator, seed, concurrent));
}
class MergeScanOperator {
constructor(accumulator, seed, concurrent) {
this.accumulator = accumulator;
this.seed = seed;
this.concurrent = concurrent;
}
call(subscriber, source) {
return source.subscribe(new MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent));
}
}
class MergeScanSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"] {
constructor(destination, accumulator, acc, concurrent) {
super(destination);
this.accumulator = accumulator;
this.acc = acc;
this.concurrent = concurrent;
this.hasValue = false;
this.hasCompleted = false;
this.buffer = [];
this.active = 0;
this.index = 0;
}
_next(value) {
if (this.active < this.concurrent) {
const index = this.index++;
const destination = this.destination;
let ish;
try {
const { accumulator } = this;
ish = accumulator(this.acc, value, index);
}
catch (e) {
return destination.error(e);
}
this.active++;
this._innerSub(ish, value, index);
}
else {
this.buffer.push(value);
}
}
_innerSub(ish, value, index) {
const innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__["InnerSubscriber"](this, value, index);
const destination = this.destination;
destination.add(innerSubscriber);
const innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_0__["subscribeToResult"])(this, ish, undefined, undefined, innerSubscriber);
if (innerSubscription !== innerSubscriber) {
destination.add(innerSubscription);
}
}
_complete() {
this.hasCompleted = true;
if (this.active === 0 && this.buffer.length === 0) {
if (this.hasValue === false) {
this.destination.next(this.acc);
}
this.destination.complete();
}
this.unsubscribe();
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
const { destination } = this;
this.acc = innerValue;
this.hasValue = true;
destination.next(innerValue);
}
notifyComplete(innerSub) {
const buffer = this.buffer;
const destination = this.destination;
destination.remove(innerSub);
this.active--;
if (buffer.length > 0) {
this._next(buffer.shift());
}
else if (this.active === 0 && this.hasCompleted) {
if (this.hasValue === false) {
this.destination.next(this.acc);
}
this.destination.complete();
}
}
}
//# sourceMappingURL=mergeScan.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/min.js":
/*!**************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/min.js ***!
\**************************************************************/
/*! exports provided: min */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "min", function() { return min; });
/* harmony import */ var _reduce__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reduce */ "./node_modules/rxjs/_esm2015/internal/operators/reduce.js");
function min(comparer) {
const min = (typeof comparer === 'function')
? (x, y) => comparer(x, y) < 0 ? x : y
: (x, y) => x < y ? x : y;
return Object(_reduce__WEBPACK_IMPORTED_MODULE_0__["reduce"])(min);
}
//# sourceMappingURL=min.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/multicast.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/multicast.js ***!
\********************************************************************/
/*! exports provided: multicast, MulticastOperator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "multicast", function() { return multicast; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MulticastOperator", function() { return MulticastOperator; });
/* harmony import */ var _observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/ConnectableObservable */ "./node_modules/rxjs/_esm2015/internal/observable/ConnectableObservable.js");
function multicast(subjectOrSubjectFactory, selector) {
return function multicastOperatorFunction(source) {
let subjectFactory;
if (typeof subjectOrSubjectFactory === 'function') {
subjectFactory = subjectOrSubjectFactory;
}
else {
subjectFactory = function subjectFactory() {
return subjectOrSubjectFactory;
};
}
if (typeof selector === 'function') {
return source.lift(new MulticastOperator(subjectFactory, selector));
}
const connectable = Object.create(source, _observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_0__["connectableObservableDescriptor"]);
connectable.source = source;
connectable.subjectFactory = subjectFactory;
return connectable;
};
}
class MulticastOperator {
constructor(subjectFactory, selector) {
this.subjectFactory = subjectFactory;
this.selector = selector;
}
call(subscriber, source) {
const { selector } = this;
const subject = this.subjectFactory();
const subscription = selector(subject).subscribe(subscriber);
subscription.add(source.subscribe(subject));
return subscription;
}
}
//# sourceMappingURL=multicast.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/observeOn.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/observeOn.js ***!
\********************************************************************/
/*! exports provided: observeOn, ObserveOnOperator, ObserveOnSubscriber, ObserveOnMessage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "observeOn", function() { return observeOn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObserveOnOperator", function() { return ObserveOnOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObserveOnSubscriber", function() { return ObserveOnSubscriber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObserveOnMessage", function() { return ObserveOnMessage; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Notification */ "./node_modules/rxjs/_esm2015/internal/Notification.js");
function observeOn(scheduler, delay = 0) {
return function observeOnOperatorFunction(source) {
return source.lift(new ObserveOnOperator(scheduler, delay));
};
}
class ObserveOnOperator {
constructor(scheduler, delay = 0) {
this.scheduler = scheduler;
this.delay = delay;
}
call(subscriber, source) {
return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
}
}
class ObserveOnSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, scheduler, delay = 0) {
super(destination);
this.scheduler = scheduler;
this.delay = delay;
}
static dispatch(arg) {
const { notification, destination } = arg;
notification.observe(destination);
this.unsubscribe();
}
scheduleMessage(notification) {
const destination = this.destination;
destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
}
_next(value) {
this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_1__["Notification"].createNext(value));
}
_error(err) {
this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_1__["Notification"].createError(err));
this.unsubscribe();
}
_complete() {
this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_1__["Notification"].createComplete());
this.unsubscribe();
}
}
class ObserveOnMessage {
constructor(notification, destination) {
this.notification = notification;
this.destination = destination;
}
}
//# sourceMappingURL=observeOn.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/onErrorResumeNext.js":
/*!****************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/onErrorResumeNext.js ***!
\****************************************************************************/
/*! exports provided: onErrorResumeNext, onErrorResumeNextStatic */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return onErrorResumeNext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNextStatic", function() { return onErrorResumeNextStatic; });
/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/from */ "./node_modules/rxjs/_esm2015/internal/observable/from.js");
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../InnerSubscriber */ "./node_modules/rxjs/_esm2015/internal/InnerSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function onErrorResumeNext(...nextSources) {
if (nextSources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(nextSources[0])) {
nextSources = nextSources[0];
}
return (source) => source.lift(new OnErrorResumeNextOperator(nextSources));
}
function onErrorResumeNextStatic(...nextSources) {
let source = null;
if (nextSources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(nextSources[0])) {
nextSources = nextSources[0];
}
source = nextSources.shift();
return Object(_observable_from__WEBPACK_IMPORTED_MODULE_0__["from"])(source, null).lift(new OnErrorResumeNextOperator(nextSources));
}
class OnErrorResumeNextOperator {
constructor(nextSources) {
this.nextSources = nextSources;
}
call(subscriber, source) {
return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources));
}
}
class OnErrorResumeNextSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"] {
constructor(destination, nextSources) {
super(destination);
this.destination = destination;
this.nextSources = nextSources;
}
notifyError(error, innerSub) {
this.subscribeToNextSource();
}
notifyComplete(innerSub) {
this.subscribeToNextSource();
}
_error(err) {
this.subscribeToNextSource();
this.unsubscribe();
}
_complete() {
this.subscribeToNextSource();
this.unsubscribe();
}
subscribeToNextSource() {
const next = this.nextSources.shift();
if (!!next) {
const innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__["InnerSubscriber"](this, undefined, undefined);
const destination = this.destination;
destination.add(innerSubscriber);
const innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(this, next, undefined, undefined, innerSubscriber);
if (innerSubscription !== innerSubscriber) {
destination.add(innerSubscription);
}
}
else {
this.destination.complete();
}
}
}
//# sourceMappingURL=onErrorResumeNext.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/pairwise.js":
/*!*******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/pairwise.js ***!
\*******************************************************************/
/*! exports provided: pairwise */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pairwise", function() { return pairwise; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function pairwise() {
return (source) => source.lift(new PairwiseOperator());
}
class PairwiseOperator {
call(subscriber, source) {
return source.subscribe(new PairwiseSubscriber(subscriber));
}
}
class PairwiseSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination) {
super(destination);
this.hasPrev = false;
}
_next(value) {
let pair;
if (this.hasPrev) {
pair = [this.prev, value];
}
else {
this.hasPrev = true;
}
this.prev = value;
if (pair) {
this.destination.next(pair);
}
}
}
//# sourceMappingURL=pairwise.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/partition.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/partition.js ***!
\********************************************************************/
/*! exports provided: partition */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return partition; });
/* harmony import */ var _util_not__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/not */ "./node_modules/rxjs/_esm2015/internal/util/not.js");
/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./filter */ "./node_modules/rxjs/_esm2015/internal/operators/filter.js");
function partition(predicate, thisArg) {
return (source) => [
Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(predicate, thisArg)(source),
Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(Object(_util_not__WEBPACK_IMPORTED_MODULE_0__["not"])(predicate, thisArg))(source)
];
}
//# sourceMappingURL=partition.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/pluck.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/pluck.js ***!
\****************************************************************/
/*! exports provided: pluck */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pluck", function() { return pluck; });
/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
function pluck(...properties) {
const length = properties.length;
if (length === 0) {
throw new Error('list of properties cannot be empty.');
}
return (source) => Object(_map__WEBPACK_IMPORTED_MODULE_0__["map"])(plucker(properties, length))(source);
}
function plucker(props, length) {
const mapper = (x) => {
let currentProp = x;
for (let i = 0; i < length; i++) {
const p = currentProp[props[i]];
if (typeof p !== 'undefined') {
currentProp = p;
}
else {
return undefined;
}
}
return currentProp;
};
return mapper;
}
//# sourceMappingURL=pluck.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/publish.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/publish.js ***!
\******************************************************************/
/*! exports provided: publish */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publish", function() { return publish; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./multicast */ "./node_modules/rxjs/_esm2015/internal/operators/multicast.js");
function publish(selector) {
return selector ?
Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(() => new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"](), selector) :
Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"]());
}
//# sourceMappingURL=publish.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/publishBehavior.js":
/*!**************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/publishBehavior.js ***!
\**************************************************************************/
/*! exports provided: publishBehavior */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publishBehavior", function() { return publishBehavior; });
/* harmony import */ var _BehaviorSubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../BehaviorSubject */ "./node_modules/rxjs/_esm2015/internal/BehaviorSubject.js");
/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./multicast */ "./node_modules/rxjs/_esm2015/internal/operators/multicast.js");
function publishBehavior(value) {
return (source) => Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(new _BehaviorSubject__WEBPACK_IMPORTED_MODULE_0__["BehaviorSubject"](value))(source);
}
//# sourceMappingURL=publishBehavior.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/publishLast.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/publishLast.js ***!
\**********************************************************************/
/*! exports provided: publishLast */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publishLast", function() { return publishLast; });
/* harmony import */ var _AsyncSubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../AsyncSubject */ "./node_modules/rxjs/_esm2015/internal/AsyncSubject.js");
/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./multicast */ "./node_modules/rxjs/_esm2015/internal/operators/multicast.js");
function publishLast() {
return (source) => Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(new _AsyncSubject__WEBPACK_IMPORTED_MODULE_0__["AsyncSubject"]())(source);
}
//# sourceMappingURL=publishLast.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/publishReplay.js":
/*!************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/publishReplay.js ***!
\************************************************************************/
/*! exports provided: publishReplay */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publishReplay", function() { return publishReplay; });
/* harmony import */ var _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../ReplaySubject */ "./node_modules/rxjs/_esm2015/internal/ReplaySubject.js");
/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./multicast */ "./node_modules/rxjs/_esm2015/internal/operators/multicast.js");
function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {
scheduler = selectorOrScheduler;
}
const selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;
const subject = new _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__["ReplaySubject"](bufferSize, windowTime, scheduler);
return (source) => Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(() => subject, selector)(source);
}
//# sourceMappingURL=publishReplay.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/race.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/race.js ***!
\***************************************************************/
/*! exports provided: race */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "race", function() { return race; });
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
/* harmony import */ var _observable_race__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../observable/race */ "./node_modules/rxjs/_esm2015/internal/observable/race.js");
function race(...observables) {
return function raceOperatorFunction(source) {
if (observables.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(observables[0])) {
observables = observables[0];
}
return source.lift.call(Object(_observable_race__WEBPACK_IMPORTED_MODULE_1__["race"])(source, ...observables));
};
}
//# sourceMappingURL=race.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/reduce.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/reduce.js ***!
\*****************************************************************/
/*! exports provided: reduce */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return reduce; });
/* harmony import */ var _scan__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./scan */ "./node_modules/rxjs/_esm2015/internal/operators/scan.js");
/* harmony import */ var _takeLast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./takeLast */ "./node_modules/rxjs/_esm2015/internal/operators/takeLast.js");
/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./defaultIfEmpty */ "./node_modules/rxjs/_esm2015/internal/operators/defaultIfEmpty.js");
/* harmony import */ var _util_pipe__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/pipe */ "./node_modules/rxjs/_esm2015/internal/util/pipe.js");
function reduce(accumulator, seed) {
if (arguments.length >= 2) {
return function reduceOperatorFunctionWithSeed(source) {
return Object(_util_pipe__WEBPACK_IMPORTED_MODULE_3__["pipe"])(Object(_scan__WEBPACK_IMPORTED_MODULE_0__["scan"])(accumulator, seed), Object(_takeLast__WEBPACK_IMPORTED_MODULE_1__["takeLast"])(1), Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_2__["defaultIfEmpty"])(seed))(source);
};
}
return function reduceOperatorFunction(source) {
return Object(_util_pipe__WEBPACK_IMPORTED_MODULE_3__["pipe"])(Object(_scan__WEBPACK_IMPORTED_MODULE_0__["scan"])((acc, value, index) => accumulator(acc, value, index + 1)), Object(_takeLast__WEBPACK_IMPORTED_MODULE_1__["takeLast"])(1))(source);
};
}
//# sourceMappingURL=reduce.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/refCount.js":
/*!*******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/refCount.js ***!
\*******************************************************************/
/*! exports provided: refCount */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "refCount", function() { return refCount; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function refCount() {
return function refCountOperatorFunction(source) {
return source.lift(new RefCountOperator(source));
};
}
class RefCountOperator {
constructor(connectable) {
this.connectable = connectable;
}
call(subscriber, source) {
const { connectable } = this;
connectable._refCount++;
const refCounter = new RefCountSubscriber(subscriber, connectable);
const subscription = source.subscribe(refCounter);
if (!refCounter.closed) {
refCounter.connection = connectable.connect();
}
return subscription;
}
}
class RefCountSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, connectable) {
super(destination);
this.connectable = connectable;
}
_unsubscribe() {
const { connectable } = this;
if (!connectable) {
this.connection = null;
return;
}
this.connectable = null;
const refCount = connectable._refCount;
if (refCount <= 0) {
this.connection = null;
return;
}
connectable._refCount = refCount - 1;
if (refCount > 1) {
this.connection = null;
return;
}
const { connection } = this;
const sharedConnection = connectable._connection;
this.connection = null;
if (sharedConnection && (!connection || sharedConnection === connection)) {
sharedConnection.unsubscribe();
}
}
}
//# sourceMappingURL=refCount.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/repeat.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/repeat.js ***!
\*****************************************************************/
/*! exports provided: repeat */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "repeat", function() { return repeat; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../observable/empty */ "./node_modules/rxjs/_esm2015/internal/observable/empty.js");
function repeat(count = -1) {
return (source) => {
if (count === 0) {
return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_1__["empty"])();
}
else if (count < 0) {
return source.lift(new RepeatOperator(-1, source));
}
else {
return source.lift(new RepeatOperator(count - 1, source));
}
};
}
class RepeatOperator {
constructor(count, source) {
this.count = count;
this.source = source;
}
call(subscriber, source) {
return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source));
}
}
class RepeatSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, count, source) {
super(destination);
this.count = count;
this.source = source;
}
complete() {
if (!this.isStopped) {
const { source, count } = this;
if (count === 0) {
return super.complete();
}
else if (count > -1) {
this.count = count - 1;
}
source.subscribe(this._unsubscribeAndRecycle());
}
}
}
//# sourceMappingURL=repeat.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/repeatWhen.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/repeatWhen.js ***!
\*********************************************************************/
/*! exports provided: repeatWhen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "repeatWhen", function() { return repeatWhen; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function repeatWhen(notifier) {
return (source) => source.lift(new RepeatWhenOperator(notifier));
}
class RepeatWhenOperator {
constructor(notifier) {
this.notifier = notifier;
}
call(subscriber, source) {
return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source));
}
}
class RepeatWhenSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"] {
constructor(destination, notifier, source) {
super(destination);
this.notifier = notifier;
this.source = source;
this.sourceIsBeingSubscribedTo = true;
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.sourceIsBeingSubscribedTo = true;
this.source.subscribe(this);
}
notifyComplete(innerSub) {
if (this.sourceIsBeingSubscribedTo === false) {
return super.complete();
}
}
complete() {
this.sourceIsBeingSubscribedTo = false;
if (!this.isStopped) {
if (!this.retries) {
this.subscribeToRetries();
}
if (!this.retriesSubscription || this.retriesSubscription.closed) {
return super.complete();
}
this._unsubscribeAndRecycle();
this.notifications.next();
}
}
_unsubscribe() {
const { notifications, retriesSubscription } = this;
if (notifications) {
notifications.unsubscribe();
this.notifications = null;
}
if (retriesSubscription) {
retriesSubscription.unsubscribe();
this.retriesSubscription = null;
}
this.retries = null;
}
_unsubscribeAndRecycle() {
const { _unsubscribe } = this;
this._unsubscribe = null;
super._unsubscribeAndRecycle();
this._unsubscribe = _unsubscribe;
return this;
}
subscribeToRetries() {
this.notifications = new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"]();
let retries;
try {
const { notifier } = this;
retries = notifier(this.notifications);
}
catch (e) {
return super.complete();
}
this.retries = retries;
this.retriesSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, retries);
}
}
//# sourceMappingURL=repeatWhen.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/retry.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/retry.js ***!
\****************************************************************/
/*! exports provided: retry */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "retry", function() { return retry; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function retry(count = -1) {
return (source) => source.lift(new RetryOperator(count, source));
}
class RetryOperator {
constructor(count, source) {
this.count = count;
this.source = source;
}
call(subscriber, source) {
return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
}
}
class RetrySubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, count, source) {
super(destination);
this.count = count;
this.source = source;
}
error(err) {
if (!this.isStopped) {
const { source, count } = this;
if (count === 0) {
return super.error(err);
}
else if (count > -1) {
this.count = count - 1;
}
source.subscribe(this._unsubscribeAndRecycle());
}
}
}
//# sourceMappingURL=retry.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/retryWhen.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/retryWhen.js ***!
\********************************************************************/
/*! exports provided: retryWhen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "retryWhen", function() { return retryWhen; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function retryWhen(notifier) {
return (source) => source.lift(new RetryWhenOperator(notifier, source));
}
class RetryWhenOperator {
constructor(notifier, source) {
this.notifier = notifier;
this.source = source;
}
call(subscriber, source) {
return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));
}
}
class RetryWhenSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"] {
constructor(destination, notifier, source) {
super(destination);
this.notifier = notifier;
this.source = source;
}
error(err) {
if (!this.isStopped) {
let errors = this.errors;
let retries = this.retries;
let retriesSubscription = this.retriesSubscription;
if (!retries) {
errors = new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"]();
try {
const { notifier } = this;
retries = notifier(errors);
}
catch (e) {
return super.error(e);
}
retriesSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, retries);
}
else {
this.errors = null;
this.retriesSubscription = null;
}
this._unsubscribeAndRecycle();
this.errors = errors;
this.retries = retries;
this.retriesSubscription = retriesSubscription;
errors.next(err);
}
}
_unsubscribe() {
const { errors, retriesSubscription } = this;
if (errors) {
errors.unsubscribe();
this.errors = null;
}
if (retriesSubscription) {
retriesSubscription.unsubscribe();
this.retriesSubscription = null;
}
this.retries = null;
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
const { _unsubscribe } = this;
this._unsubscribe = null;
this._unsubscribeAndRecycle();
this._unsubscribe = _unsubscribe;
this.source.subscribe(this);
}
}
//# sourceMappingURL=retryWhen.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/sample.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/sample.js ***!
\*****************************************************************/
/*! exports provided: sample */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sample", function() { return sample; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function sample(notifier) {
return (source) => source.lift(new SampleOperator(notifier));
}
class SampleOperator {
constructor(notifier) {
this.notifier = notifier;
}
call(subscriber, source) {
const sampleSubscriber = new SampleSubscriber(subscriber);
const subscription = source.subscribe(sampleSubscriber);
subscription.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(sampleSubscriber, this.notifier));
return subscription;
}
}
class SampleSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor() {
super(...arguments);
this.hasValue = false;
}
_next(value) {
this.value = value;
this.hasValue = true;
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.emitValue();
}
notifyComplete() {
this.emitValue();
}
emitValue() {
if (this.hasValue) {
this.hasValue = false;
this.destination.next(this.value);
}
}
}
//# sourceMappingURL=sample.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/sampleTime.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/sampleTime.js ***!
\*********************************************************************/
/*! exports provided: sampleTime */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sampleTime", function() { return sampleTime; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
function sampleTime(period, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]) {
return (source) => source.lift(new SampleTimeOperator(period, scheduler));
}
class SampleTimeOperator {
constructor(period, scheduler) {
this.period = period;
this.scheduler = scheduler;
}
call(subscriber, source) {
return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler));
}
}
class SampleTimeSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, period, scheduler) {
super(destination);
this.period = period;
this.scheduler = scheduler;
this.hasValue = false;
this.add(scheduler.schedule(dispatchNotification, period, { subscriber: this, period }));
}
_next(value) {
this.lastValue = value;
this.hasValue = true;
}
notifyNext() {
if (this.hasValue) {
this.hasValue = false;
this.destination.next(this.lastValue);
}
}
}
function dispatchNotification(state) {
let { subscriber, period } = state;
subscriber.notifyNext();
this.schedule(state, period);
}
//# sourceMappingURL=sampleTime.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/scan.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/scan.js ***!
\***************************************************************/
/*! exports provided: scan */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scan", function() { return scan; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function scan(accumulator, seed) {
let hasSeed = false;
if (arguments.length >= 2) {
hasSeed = true;
}
return function scanOperatorFunction(source) {
return source.lift(new ScanOperator(accumulator, seed, hasSeed));
};
}
class ScanOperator {
constructor(accumulator, seed, hasSeed = false) {
this.accumulator = accumulator;
this.seed = seed;
this.hasSeed = hasSeed;
}
call(subscriber, source) {
return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
}
}
class ScanSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, accumulator, _seed, hasSeed) {
super(destination);
this.accumulator = accumulator;
this._seed = _seed;
this.hasSeed = hasSeed;
this.index = 0;
}
get seed() {
return this._seed;
}
set seed(value) {
this.hasSeed = true;
this._seed = value;
}
_next(value) {
if (!this.hasSeed) {
this.seed = value;
this.destination.next(value);
}
else {
return this._tryNext(value);
}
}
_tryNext(value) {
const index = this.index++;
let result;
try {
result = this.accumulator(this.seed, value, index);
}
catch (err) {
this.destination.error(err);
}
this.seed = result;
this.destination.next(result);
}
}
//# sourceMappingURL=scan.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/sequenceEqual.js":
/*!************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/sequenceEqual.js ***!
\************************************************************************/
/*! exports provided: sequenceEqual, SequenceEqualOperator, SequenceEqualSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sequenceEqual", function() { return sequenceEqual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SequenceEqualOperator", function() { return SequenceEqualOperator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SequenceEqualSubscriber", function() { return SequenceEqualSubscriber; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function sequenceEqual(compareTo, comparator) {
return (source) => source.lift(new SequenceEqualOperator(compareTo, comparator));
}
class SequenceEqualOperator {
constructor(compareTo, comparator) {
this.compareTo = compareTo;
this.comparator = comparator;
}
call(subscriber, source) {
return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparator));
}
}
class SequenceEqualSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, compareTo, comparator) {
super(destination);
this.compareTo = compareTo;
this.comparator = comparator;
this._a = [];
this._b = [];
this._oneComplete = false;
this.destination.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, this)));
}
_next(value) {
if (this._oneComplete && this._b.length === 0) {
this.emit(false);
}
else {
this._a.push(value);
this.checkValues();
}
}
_complete() {
if (this._oneComplete) {
this.emit(this._a.length === 0 && this._b.length === 0);
}
else {
this._oneComplete = true;
}
this.unsubscribe();
}
checkValues() {
const { _a, _b, comparator } = this;
while (_a.length > 0 && _b.length > 0) {
let a = _a.shift();
let b = _b.shift();
let areEqual = false;
try {
areEqual = comparator ? comparator(a, b) : a === b;
}
catch (e) {
this.destination.error(e);
}
if (!areEqual) {
this.emit(false);
}
}
}
emit(value) {
const { destination } = this;
destination.next(value);
destination.complete();
}
nextB(value) {
if (this._oneComplete && this._a.length === 0) {
this.emit(false);
}
else {
this._b.push(value);
this.checkValues();
}
}
completeB() {
if (this._oneComplete) {
this.emit(this._a.length === 0 && this._b.length === 0);
}
else {
this._oneComplete = true;
}
}
}
class SequenceEqualCompareToSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, parent) {
super(destination);
this.parent = parent;
}
_next(value) {
this.parent.nextB(value);
}
_error(err) {
this.parent.error(err);
this.unsubscribe();
}
_complete() {
this.parent.completeB();
this.unsubscribe();
}
}
//# sourceMappingURL=sequenceEqual.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/share.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/share.js ***!
\****************************************************************/
/*! exports provided: share */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "share", function() { return share; });
/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./multicast */ "./node_modules/rxjs/_esm2015/internal/operators/multicast.js");
/* harmony import */ var _refCount__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./refCount */ "./node_modules/rxjs/_esm2015/internal/operators/refCount.js");
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
function shareSubjectFactory() {
return new _Subject__WEBPACK_IMPORTED_MODULE_2__["Subject"]();
}
function share() {
return (source) => Object(_refCount__WEBPACK_IMPORTED_MODULE_1__["refCount"])()(Object(_multicast__WEBPACK_IMPORTED_MODULE_0__["multicast"])(shareSubjectFactory)(source));
}
//# sourceMappingURL=share.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/shareReplay.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/shareReplay.js ***!
\**********************************************************************/
/*! exports provided: shareReplay */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shareReplay", function() { return shareReplay; });
/* harmony import */ var _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../ReplaySubject */ "./node_modules/rxjs/_esm2015/internal/ReplaySubject.js");
function shareReplay(configOrBufferSize, windowTime, scheduler) {
let config;
if (configOrBufferSize && typeof configOrBufferSize === 'object') {
config = configOrBufferSize;
}
else {
config = {
bufferSize: configOrBufferSize,
windowTime,
refCount: false,
scheduler
};
}
return (source) => source.lift(shareReplayOperator(config));
}
function shareReplayOperator({ bufferSize = Number.POSITIVE_INFINITY, windowTime = Number.POSITIVE_INFINITY, refCount: useRefCount, scheduler }) {
let subject;
let refCount = 0;
let subscription;
let hasError = false;
let isComplete = false;
return function shareReplayOperation(source) {
refCount++;
if (!subject || hasError) {
hasError = false;
subject = new _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__["ReplaySubject"](bufferSize, windowTime, scheduler);
subscription = source.subscribe({
next(value) { subject.next(value); },
error(err) {
hasError = true;
subject.error(err);
},
complete() {
isComplete = true;
subscription = undefined;
subject.complete();
},
});
}
const innerSub = subject.subscribe(this);
this.add(() => {
refCount--;
innerSub.unsubscribe();
if (subscription && !isComplete && useRefCount && refCount === 0) {
subscription.unsubscribe();
subscription = undefined;
subject = undefined;
}
});
};
}
//# sourceMappingURL=shareReplay.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/single.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/single.js ***!
\*****************************************************************/
/*! exports provided: single */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "single", function() { return single; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/EmptyError */ "./node_modules/rxjs/_esm2015/internal/util/EmptyError.js");
function single(predicate) {
return (source) => source.lift(new SingleOperator(predicate, source));
}
class SingleOperator {
constructor(predicate, source) {
this.predicate = predicate;
this.source = source;
}
call(subscriber, source) {
return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source));
}
}
class SingleSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, predicate, source) {
super(destination);
this.predicate = predicate;
this.source = source;
this.seenValue = false;
this.index = 0;
}
applySingleValue(value) {
if (this.seenValue) {
this.destination.error('Sequence contains more than one element');
}
else {
this.seenValue = true;
this.singleValue = value;
}
}
_next(value) {
const index = this.index++;
if (this.predicate) {
this.tryNext(value, index);
}
else {
this.applySingleValue(value);
}
}
tryNext(value, index) {
try {
if (this.predicate(value, index, this.source)) {
this.applySingleValue(value);
}
}
catch (err) {
this.destination.error(err);
}
}
_complete() {
const destination = this.destination;
if (this.index > 0) {
destination.next(this.seenValue ? this.singleValue : undefined);
destination.complete();
}
else {
destination.error(new _util_EmptyError__WEBPACK_IMPORTED_MODULE_1__["EmptyError"]);
}
}
}
//# sourceMappingURL=single.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/skip.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/skip.js ***!
\***************************************************************/
/*! exports provided: skip */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skip", function() { return skip; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function skip(count) {
return (source) => source.lift(new SkipOperator(count));
}
class SkipOperator {
constructor(total) {
this.total = total;
}
call(subscriber, source) {
return source.subscribe(new SkipSubscriber(subscriber, this.total));
}
}
class SkipSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, total) {
super(destination);
this.total = total;
this.count = 0;
}
_next(x) {
if (++this.count > this.total) {
this.destination.next(x);
}
}
}
//# sourceMappingURL=skip.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/skipLast.js":
/*!*******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/skipLast.js ***!
\*******************************************************************/
/*! exports provided: skipLast */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skipLast", function() { return skipLast; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/ArgumentOutOfRangeError */ "./node_modules/rxjs/_esm2015/internal/util/ArgumentOutOfRangeError.js");
function skipLast(count) {
return (source) => source.lift(new SkipLastOperator(count));
}
class SkipLastOperator {
constructor(_skipCount) {
this._skipCount = _skipCount;
if (this._skipCount < 0) {
throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_1__["ArgumentOutOfRangeError"];
}
}
call(subscriber, source) {
if (this._skipCount === 0) {
return source.subscribe(new _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"](subscriber));
}
else {
return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount));
}
}
}
class SkipLastSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, _skipCount) {
super(destination);
this._skipCount = _skipCount;
this._count = 0;
this._ring = new Array(_skipCount);
}
_next(value) {
const skipCount = this._skipCount;
const count = this._count++;
if (count < skipCount) {
this._ring[count] = value;
}
else {
const currentIndex = count % skipCount;
const ring = this._ring;
const oldValue = ring[currentIndex];
ring[currentIndex] = value;
this.destination.next(oldValue);
}
}
}
//# sourceMappingURL=skipLast.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/skipUntil.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/skipUntil.js ***!
\********************************************************************/
/*! exports provided: skipUntil */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skipUntil", function() { return skipUntil; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../InnerSubscriber */ "./node_modules/rxjs/_esm2015/internal/InnerSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function skipUntil(notifier) {
return (source) => source.lift(new SkipUntilOperator(notifier));
}
class SkipUntilOperator {
constructor(notifier) {
this.notifier = notifier;
}
call(destination, source) {
return source.subscribe(new SkipUntilSubscriber(destination, this.notifier));
}
}
class SkipUntilSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, notifier) {
super(destination);
this.hasValue = false;
const innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_1__["InnerSubscriber"](this, undefined, undefined);
this.add(innerSubscriber);
this.innerSubscription = innerSubscriber;
const innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, notifier, undefined, undefined, innerSubscriber);
if (innerSubscription !== innerSubscriber) {
this.add(innerSubscription);
this.innerSubscription = innerSubscription;
}
}
_next(value) {
if (this.hasValue) {
super._next(value);
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.hasValue = true;
if (this.innerSubscription) {
this.innerSubscription.unsubscribe();
}
}
notifyComplete() {
}
}
//# sourceMappingURL=skipUntil.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/skipWhile.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/skipWhile.js ***!
\********************************************************************/
/*! exports provided: skipWhile */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skipWhile", function() { return skipWhile; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function skipWhile(predicate) {
return (source) => source.lift(new SkipWhileOperator(predicate));
}
class SkipWhileOperator {
constructor(predicate) {
this.predicate = predicate;
}
call(subscriber, source) {
return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
}
}
class SkipWhileSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, predicate) {
super(destination);
this.predicate = predicate;
this.skipping = true;
this.index = 0;
}
_next(value) {
const destination = this.destination;
if (this.skipping) {
this.tryCallPredicate(value);
}
if (!this.skipping) {
destination.next(value);
}
}
tryCallPredicate(value) {
try {
const result = this.predicate(value, this.index++);
this.skipping = Boolean(result);
}
catch (err) {
this.destination.error(err);
}
}
}
//# sourceMappingURL=skipWhile.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/startWith.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/startWith.js ***!
\********************************************************************/
/*! exports provided: startWith */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startWith", function() { return startWith; });
/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/concat */ "./node_modules/rxjs/_esm2015/internal/observable/concat.js");
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js");
function startWith(...array) {
const scheduler = array[array.length - 1];
if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__["isScheduler"])(scheduler)) {
array.pop();
return (source) => Object(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"])(array, source, scheduler);
}
else {
return (source) => Object(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"])(array, source);
}
}
//# sourceMappingURL=startWith.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/subscribeOn.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/subscribeOn.js ***!
\**********************************************************************/
/*! exports provided: subscribeOn */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeOn", function() { return subscribeOn; });
/* harmony import */ var _observable_SubscribeOnObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/SubscribeOnObservable */ "./node_modules/rxjs/_esm2015/internal/observable/SubscribeOnObservable.js");
function subscribeOn(scheduler, delay = 0) {
return function subscribeOnOperatorFunction(source) {
return source.lift(new SubscribeOnOperator(scheduler, delay));
};
}
class SubscribeOnOperator {
constructor(scheduler, delay) {
this.scheduler = scheduler;
this.delay = delay;
}
call(subscriber, source) {
return new _observable_SubscribeOnObservable__WEBPACK_IMPORTED_MODULE_0__["SubscribeOnObservable"](source, this.delay, this.scheduler).subscribe(subscriber);
}
}
//# sourceMappingURL=subscribeOn.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/switchAll.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/switchAll.js ***!
\********************************************************************/
/*! exports provided: switchAll */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "switchAll", function() { return switchAll; });
/* harmony import */ var _switchMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./switchMap */ "./node_modules/rxjs/_esm2015/internal/operators/switchMap.js");
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/identity */ "./node_modules/rxjs/_esm2015/internal/util/identity.js");
function switchAll() {
return Object(_switchMap__WEBPACK_IMPORTED_MODULE_0__["switchMap"])(_util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"]);
}
//# sourceMappingURL=switchAll.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/switchMap.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/switchMap.js ***!
\********************************************************************/
/*! exports provided: switchMap */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "switchMap", function() { return switchMap; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../InnerSubscriber */ "./node_modules/rxjs/_esm2015/internal/InnerSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../observable/from */ "./node_modules/rxjs/_esm2015/internal/observable/from.js");
function switchMap(project, resultSelector) {
if (typeof resultSelector === 'function') {
return (source) => source.pipe(switchMap((a, i) => Object(_observable_from__WEBPACK_IMPORTED_MODULE_4__["from"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_3__["map"])((b, ii) => resultSelector(a, b, i, ii)))));
}
return (source) => source.lift(new SwitchMapOperator(project));
}
class SwitchMapOperator {
constructor(project) {
this.project = project;
}
call(subscriber, source) {
return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));
}
}
class SwitchMapSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, project) {
super(destination);
this.project = project;
this.index = 0;
}
_next(value) {
let result;
const index = this.index++;
try {
result = this.project(value, index);
}
catch (error) {
this.destination.error(error);
return;
}
this._innerSub(result, value, index);
}
_innerSub(result, value, index) {
const innerSubscription = this.innerSubscription;
if (innerSubscription) {
innerSubscription.unsubscribe();
}
const innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_1__["InnerSubscriber"](this, value, index);
const destination = this.destination;
destination.add(innerSubscriber);
this.innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, result, undefined, undefined, innerSubscriber);
if (this.innerSubscription !== innerSubscriber) {
destination.add(this.innerSubscription);
}
}
_complete() {
const { innerSubscription } = this;
if (!innerSubscription || innerSubscription.closed) {
super._complete();
}
this.unsubscribe();
}
_unsubscribe() {
this.innerSubscription = null;
}
notifyComplete(innerSub) {
const destination = this.destination;
destination.remove(innerSub);
this.innerSubscription = null;
if (this.isStopped) {
super._complete();
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.destination.next(innerValue);
}
}
//# sourceMappingURL=switchMap.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/switchMapTo.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/switchMapTo.js ***!
\**********************************************************************/
/*! exports provided: switchMapTo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "switchMapTo", function() { return switchMapTo; });
/* harmony import */ var _switchMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./switchMap */ "./node_modules/rxjs/_esm2015/internal/operators/switchMap.js");
function switchMapTo(innerObservable, resultSelector) {
return resultSelector ? Object(_switchMap__WEBPACK_IMPORTED_MODULE_0__["switchMap"])(() => innerObservable, resultSelector) : Object(_switchMap__WEBPACK_IMPORTED_MODULE_0__["switchMap"])(() => innerObservable);
}
//# sourceMappingURL=switchMapTo.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/take.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/take.js ***!
\***************************************************************/
/*! exports provided: take */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "take", function() { return take; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/ArgumentOutOfRangeError */ "./node_modules/rxjs/_esm2015/internal/util/ArgumentOutOfRangeError.js");
/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../observable/empty */ "./node_modules/rxjs/_esm2015/internal/observable/empty.js");
function take(count) {
return (source) => {
if (count === 0) {
return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_2__["empty"])();
}
else {
return source.lift(new TakeOperator(count));
}
};
}
class TakeOperator {
constructor(total) {
this.total = total;
if (this.total < 0) {
throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_1__["ArgumentOutOfRangeError"];
}
}
call(subscriber, source) {
return source.subscribe(new TakeSubscriber(subscriber, this.total));
}
}
class TakeSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, total) {
super(destination);
this.total = total;
this.count = 0;
}
_next(value) {
const total = this.total;
const count = ++this.count;
if (count <= total) {
this.destination.next(value);
if (count === total) {
this.destination.complete();
this.unsubscribe();
}
}
}
}
//# sourceMappingURL=take.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/takeLast.js":
/*!*******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/takeLast.js ***!
\*******************************************************************/
/*! exports provided: takeLast */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeLast", function() { return takeLast; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/ArgumentOutOfRangeError */ "./node_modules/rxjs/_esm2015/internal/util/ArgumentOutOfRangeError.js");
/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../observable/empty */ "./node_modules/rxjs/_esm2015/internal/observable/empty.js");
function takeLast(count) {
return function takeLastOperatorFunction(source) {
if (count === 0) {
return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_2__["empty"])();
}
else {
return source.lift(new TakeLastOperator(count));
}
};
}
class TakeLastOperator {
constructor(total) {
this.total = total;
if (this.total < 0) {
throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_1__["ArgumentOutOfRangeError"];
}
}
call(subscriber, source) {
return source.subscribe(new TakeLastSubscriber(subscriber, this.total));
}
}
class TakeLastSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, total) {
super(destination);
this.total = total;
this.ring = new Array();
this.count = 0;
}
_next(value) {
const ring = this.ring;
const total = this.total;
const count = this.count++;
if (ring.length < total) {
ring.push(value);
}
else {
const index = count % total;
ring[index] = value;
}
}
_complete() {
const destination = this.destination;
let count = this.count;
if (count > 0) {
const total = this.count >= this.total ? this.total : this.count;
const ring = this.ring;
for (let i = 0; i < total; i++) {
const idx = (count++) % total;
destination.next(ring[idx]);
}
}
destination.complete();
}
}
//# sourceMappingURL=takeLast.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/takeUntil.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/takeUntil.js ***!
\********************************************************************/
/*! exports provided: takeUntil */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeUntil", function() { return takeUntil; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function takeUntil(notifier) {
return (source) => source.lift(new TakeUntilOperator(notifier));
}
class TakeUntilOperator {
constructor(notifier) {
this.notifier = notifier;
}
call(subscriber, source) {
const takeUntilSubscriber = new TakeUntilSubscriber(subscriber);
const notifierSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(takeUntilSubscriber, this.notifier);
if (notifierSubscription && !takeUntilSubscriber.seenValue) {
takeUntilSubscriber.add(notifierSubscription);
return source.subscribe(takeUntilSubscriber);
}
return takeUntilSubscriber;
}
}
class TakeUntilSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination) {
super(destination);
this.seenValue = false;
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.seenValue = true;
this.complete();
}
notifyComplete() {
}
}
//# sourceMappingURL=takeUntil.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/takeWhile.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/takeWhile.js ***!
\********************************************************************/
/*! exports provided: takeWhile */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeWhile", function() { return takeWhile; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function takeWhile(predicate, inclusive = false) {
return (source) => source.lift(new TakeWhileOperator(predicate, inclusive));
}
class TakeWhileOperator {
constructor(predicate, inclusive) {
this.predicate = predicate;
this.inclusive = inclusive;
}
call(subscriber, source) {
return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate, this.inclusive));
}
}
class TakeWhileSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, predicate, inclusive) {
super(destination);
this.predicate = predicate;
this.inclusive = inclusive;
this.index = 0;
}
_next(value) {
const destination = this.destination;
let result;
try {
result = this.predicate(value, this.index++);
}
catch (err) {
destination.error(err);
return;
}
this.nextOrComplete(value, result);
}
nextOrComplete(value, predicateResult) {
const destination = this.destination;
if (Boolean(predicateResult)) {
destination.next(value);
}
else {
if (this.inclusive) {
destination.next(value);
}
destination.complete();
}
}
}
//# sourceMappingURL=takeWhile.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/tap.js":
/*!**************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/tap.js ***!
\**************************************************************/
/*! exports provided: tap */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tap", function() { return tap; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _util_noop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/noop */ "./node_modules/rxjs/_esm2015/internal/util/noop.js");
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isFunction */ "./node_modules/rxjs/_esm2015/internal/util/isFunction.js");
function tap(nextOrObserver, error, complete) {
return function tapOperatorFunction(source) {
return source.lift(new DoOperator(nextOrObserver, error, complete));
};
}
class DoOperator {
constructor(nextOrObserver, error, complete) {
this.nextOrObserver = nextOrObserver;
this.error = error;
this.complete = complete;
}
call(subscriber, source) {
return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
}
}
class TapSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, observerOrNext, error, complete) {
super(destination);
this._tapNext = _util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"];
this._tapError = _util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"];
this._tapComplete = _util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"];
this._tapError = error || _util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"];
this._tapComplete = complete || _util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"];
if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(observerOrNext)) {
this._context = this;
this._tapNext = observerOrNext;
}
else if (observerOrNext) {
this._context = observerOrNext;
this._tapNext = observerOrNext.next || _util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"];
this._tapError = observerOrNext.error || _util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"];
this._tapComplete = observerOrNext.complete || _util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"];
}
}
_next(value) {
try {
this._tapNext.call(this._context, value);
}
catch (err) {
this.destination.error(err);
return;
}
this.destination.next(value);
}
_error(err) {
try {
this._tapError.call(this._context, err);
}
catch (err) {
this.destination.error(err);
return;
}
this.destination.error(err);
}
_complete() {
try {
this._tapComplete.call(this._context);
}
catch (err) {
this.destination.error(err);
return;
}
return this.destination.complete();
}
}
//# sourceMappingURL=tap.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/throttle.js":
/*!*******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/throttle.js ***!
\*******************************************************************/
/*! exports provided: defaultThrottleConfig, throttle */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultThrottleConfig", function() { return defaultThrottleConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return throttle; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
const defaultThrottleConfig = {
leading: true,
trailing: false
};
function throttle(durationSelector, config = defaultThrottleConfig) {
return (source) => source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing));
}
class ThrottleOperator {
constructor(durationSelector, leading, trailing) {
this.durationSelector = durationSelector;
this.leading = leading;
this.trailing = trailing;
}
call(subscriber, source) {
return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
}
}
class ThrottleSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, durationSelector, _leading, _trailing) {
super(destination);
this.destination = destination;
this.durationSelector = durationSelector;
this._leading = _leading;
this._trailing = _trailing;
this._hasValue = false;
}
_next(value) {
this._hasValue = true;
this._sendValue = value;
if (!this._throttled) {
if (this._leading) {
this.send();
}
else {
this.throttle(value);
}
}
}
send() {
const { _hasValue, _sendValue } = this;
if (_hasValue) {
this.destination.next(_sendValue);
this.throttle(_sendValue);
}
this._hasValue = false;
this._sendValue = null;
}
throttle(value) {
const duration = this.tryDurationSelector(value);
if (!!duration) {
this.add(this._throttled = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, duration));
}
}
tryDurationSelector(value) {
try {
return this.durationSelector(value);
}
catch (err) {
this.destination.error(err);
return null;
}
}
throttlingDone() {
const { _throttled, _trailing } = this;
if (_throttled) {
_throttled.unsubscribe();
}
this._throttled = null;
if (_trailing) {
this.send();
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.throttlingDone();
}
notifyComplete() {
this.throttlingDone();
}
}
//# sourceMappingURL=throttle.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/throttleTime.js":
/*!***********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/throttleTime.js ***!
\***********************************************************************/
/*! exports provided: throttleTime */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throttleTime", function() { return throttleTime; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _throttle__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./throttle */ "./node_modules/rxjs/_esm2015/internal/operators/throttle.js");
function throttleTime(duration, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"], config = _throttle__WEBPACK_IMPORTED_MODULE_2__["defaultThrottleConfig"]) {
return (source) => source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing));
}
class ThrottleTimeOperator {
constructor(duration, scheduler, leading, trailing) {
this.duration = duration;
this.scheduler = scheduler;
this.leading = leading;
this.trailing = trailing;
}
call(subscriber, source) {
return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
}
}
class ThrottleTimeSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, duration, scheduler, leading, trailing) {
super(destination);
this.duration = duration;
this.scheduler = scheduler;
this.leading = leading;
this.trailing = trailing;
this._hasTrailingValue = false;
this._trailingValue = null;
}
_next(value) {
if (this.throttled) {
if (this.trailing) {
this._trailingValue = value;
this._hasTrailingValue = true;
}
}
else {
this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
if (this.leading) {
this.destination.next(value);
}
else if (this.trailing) {
this._trailingValue = value;
this._hasTrailingValue = true;
}
}
}
_complete() {
if (this._hasTrailingValue) {
this.destination.next(this._trailingValue);
this.destination.complete();
}
else {
this.destination.complete();
}
}
clearThrottle() {
const throttled = this.throttled;
if (throttled) {
if (this.trailing && this._hasTrailingValue) {
this.destination.next(this._trailingValue);
this._trailingValue = null;
this._hasTrailingValue = false;
}
throttled.unsubscribe();
this.remove(throttled);
this.throttled = null;
}
}
}
function dispatchNext(arg) {
const { subscriber } = arg;
subscriber.clearThrottle();
}
//# sourceMappingURL=throttleTime.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js":
/*!***********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js ***!
\***********************************************************************/
/*! exports provided: throwIfEmpty */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throwIfEmpty", function() { return throwIfEmpty; });
/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/EmptyError */ "./node_modules/rxjs/_esm2015/internal/util/EmptyError.js");
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function throwIfEmpty(errorFactory = defaultErrorFactory) {
return (source) => {
return source.lift(new ThrowIfEmptyOperator(errorFactory));
};
}
class ThrowIfEmptyOperator {
constructor(errorFactory) {
this.errorFactory = errorFactory;
}
call(subscriber, source) {
return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory));
}
}
class ThrowIfEmptySubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"] {
constructor(destination, errorFactory) {
super(destination);
this.errorFactory = errorFactory;
this.hasValue = false;
}
_next(value) {
this.hasValue = true;
this.destination.next(value);
}
_complete() {
if (!this.hasValue) {
let err;
try {
err = this.errorFactory();
}
catch (e) {
err = e;
}
this.destination.error(err);
}
else {
return this.destination.complete();
}
}
}
function defaultErrorFactory() {
return new _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__["EmptyError"]();
}
//# sourceMappingURL=throwIfEmpty.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/timeInterval.js":
/*!***********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/timeInterval.js ***!
\***********************************************************************/
/*! exports provided: timeInterval, TimeInterval */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeInterval", function() { return timeInterval; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeInterval", function() { return TimeInterval; });
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _scan__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./scan */ "./node_modules/rxjs/_esm2015/internal/operators/scan.js");
/* harmony import */ var _observable_defer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../observable/defer */ "./node_modules/rxjs/_esm2015/internal/observable/defer.js");
/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
function timeInterval(scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]) {
return (source) => Object(_observable_defer__WEBPACK_IMPORTED_MODULE_2__["defer"])(() => {
return source.pipe(Object(_scan__WEBPACK_IMPORTED_MODULE_1__["scan"])(({ current }, value) => ({ value, current: scheduler.now(), last: current }), { current: scheduler.now(), value: undefined, last: undefined }), Object(_map__WEBPACK_IMPORTED_MODULE_3__["map"])(({ current, last, value }) => new TimeInterval(value, current - last)));
});
}
class TimeInterval {
constructor(value, interval) {
this.value = value;
this.interval = interval;
}
}
//# sourceMappingURL=timeInterval.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/timeout.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/timeout.js ***!
\******************************************************************/
/*! exports provided: timeout */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeout", function() { return timeout; });
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _util_TimeoutError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/TimeoutError */ "./node_modules/rxjs/_esm2015/internal/util/TimeoutError.js");
/* harmony import */ var _timeoutWith__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./timeoutWith */ "./node_modules/rxjs/_esm2015/internal/operators/timeoutWith.js");
/* harmony import */ var _observable_throwError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../observable/throwError */ "./node_modules/rxjs/_esm2015/internal/observable/throwError.js");
function timeout(due, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]) {
return Object(_timeoutWith__WEBPACK_IMPORTED_MODULE_2__["timeoutWith"])(due, Object(_observable_throwError__WEBPACK_IMPORTED_MODULE_3__["throwError"])(new _util_TimeoutError__WEBPACK_IMPORTED_MODULE_1__["TimeoutError"]()), scheduler);
}
//# sourceMappingURL=timeout.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/timeoutWith.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/timeoutWith.js ***!
\**********************************************************************/
/*! exports provided: timeoutWith */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeoutWith", function() { return timeoutWith; });
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _util_isDate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isDate */ "./node_modules/rxjs/_esm2015/internal/util/isDate.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function timeoutWith(due, withObservable, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]) {
return (source) => {
let absoluteTimeout = Object(_util_isDate__WEBPACK_IMPORTED_MODULE_1__["isDate"])(due);
let waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));
};
}
class TimeoutWithOperator {
constructor(waitFor, absoluteTimeout, withObservable, scheduler) {
this.waitFor = waitFor;
this.absoluteTimeout = absoluteTimeout;
this.withObservable = withObservable;
this.scheduler = scheduler;
}
call(subscriber, source) {
return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler));
}
}
class TimeoutWithSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"] {
constructor(destination, absoluteTimeout, waitFor, withObservable, scheduler) {
super(destination);
this.absoluteTimeout = absoluteTimeout;
this.waitFor = waitFor;
this.withObservable = withObservable;
this.scheduler = scheduler;
this.action = null;
this.scheduleTimeout();
}
static dispatchTimeout(subscriber) {
const { withObservable } = subscriber;
subscriber._unsubscribeAndRecycle();
subscriber.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(subscriber, withObservable));
}
scheduleTimeout() {
const { action } = this;
if (action) {
this.action = action.schedule(this, this.waitFor);
}
else {
this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this));
}
}
_next(value) {
if (!this.absoluteTimeout) {
this.scheduleTimeout();
}
super._next(value);
}
_unsubscribe() {
this.action = null;
this.scheduler = null;
this.withObservable = null;
}
}
//# sourceMappingURL=timeoutWith.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/timestamp.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/timestamp.js ***!
\********************************************************************/
/*! exports provided: timestamp, Timestamp */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timestamp", function() { return timestamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Timestamp", function() { return Timestamp; });
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
function timestamp(scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]) {
return Object(_map__WEBPACK_IMPORTED_MODULE_1__["map"])((value) => new Timestamp(value, scheduler.now()));
}
class Timestamp {
constructor(value, timestamp) {
this.value = value;
this.timestamp = timestamp;
}
}
//# sourceMappingURL=timestamp.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/toArray.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/toArray.js ***!
\******************************************************************/
/*! exports provided: toArray */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toArray", function() { return toArray; });
/* harmony import */ var _reduce__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reduce */ "./node_modules/rxjs/_esm2015/internal/operators/reduce.js");
function toArrayReducer(arr, item, index) {
if (index === 0) {
return [item];
}
arr.push(item);
return arr;
}
function toArray() {
return Object(_reduce__WEBPACK_IMPORTED_MODULE_0__["reduce"])(toArrayReducer, []);
}
//# sourceMappingURL=toArray.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/window.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/window.js ***!
\*****************************************************************/
/*! exports provided: window */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "window", function() { return window; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function window(windowBoundaries) {
return function windowOperatorFunction(source) {
return source.lift(new WindowOperator(windowBoundaries));
};
}
class WindowOperator {
constructor(windowBoundaries) {
this.windowBoundaries = windowBoundaries;
}
call(subscriber, source) {
const windowSubscriber = new WindowSubscriber(subscriber);
const sourceSubscription = source.subscribe(windowSubscriber);
if (!sourceSubscription.closed) {
windowSubscriber.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(windowSubscriber, this.windowBoundaries));
}
return sourceSubscription;
}
}
class WindowSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"] {
constructor(destination) {
super(destination);
this.window = new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"]();
destination.next(this.window);
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.openWindow();
}
notifyError(error, innerSub) {
this._error(error);
}
notifyComplete(innerSub) {
this._complete();
}
_next(value) {
this.window.next(value);
}
_error(err) {
this.window.error(err);
this.destination.error(err);
}
_complete() {
this.window.complete();
this.destination.complete();
}
_unsubscribe() {
this.window = null;
}
openWindow() {
const prevWindow = this.window;
if (prevWindow) {
prevWindow.complete();
}
const destination = this.destination;
const newWindow = this.window = new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"]();
destination.next(newWindow);
}
}
//# sourceMappingURL=window.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/windowCount.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/windowCount.js ***!
\**********************************************************************/
/*! exports provided: windowCount */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowCount", function() { return windowCount; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
function windowCount(windowSize, startWindowEvery = 0) {
return function windowCountOperatorFunction(source) {
return source.lift(new WindowCountOperator(windowSize, startWindowEvery));
};
}
class WindowCountOperator {
constructor(windowSize, startWindowEvery) {
this.windowSize = windowSize;
this.startWindowEvery = startWindowEvery;
}
call(subscriber, source) {
return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery));
}
}
class WindowCountSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"] {
constructor(destination, windowSize, startWindowEvery) {
super(destination);
this.destination = destination;
this.windowSize = windowSize;
this.startWindowEvery = startWindowEvery;
this.windows = [new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"]()];
this.count = 0;
destination.next(this.windows[0]);
}
_next(value) {
const startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize;
const destination = this.destination;
const windowSize = this.windowSize;
const windows = this.windows;
const len = windows.length;
for (let i = 0; i < len && !this.closed; i++) {
windows[i].next(value);
}
const c = this.count - windowSize + 1;
if (c >= 0 && c % startWindowEvery === 0 && !this.closed) {
windows.shift().complete();
}
if (++this.count % startWindowEvery === 0 && !this.closed) {
const window = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"]();
windows.push(window);
destination.next(window);
}
}
_error(err) {
const windows = this.windows;
if (windows) {
while (windows.length > 0 && !this.closed) {
windows.shift().error(err);
}
}
this.destination.error(err);
}
_complete() {
const windows = this.windows;
if (windows) {
while (windows.length > 0 && !this.closed) {
windows.shift().complete();
}
}
this.destination.complete();
}
_unsubscribe() {
this.count = 0;
this.windows = null;
}
}
//# sourceMappingURL=windowCount.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/windowTime.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/windowTime.js ***!
\*********************************************************************/
/*! exports provided: windowTime */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowTime", function() { return windowTime; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js");
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/isNumeric */ "./node_modules/rxjs/_esm2015/internal/util/isNumeric.js");
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js");
function windowTime(windowTimeSpan) {
let scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"];
let windowCreationInterval = null;
let maxWindowSize = Number.POSITIVE_INFINITY;
if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_4__["isScheduler"])(arguments[3])) {
scheduler = arguments[3];
}
if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_4__["isScheduler"])(arguments[2])) {
scheduler = arguments[2];
}
else if (Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_3__["isNumeric"])(arguments[2])) {
maxWindowSize = arguments[2];
}
if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_4__["isScheduler"])(arguments[1])) {
scheduler = arguments[1];
}
else if (Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_3__["isNumeric"])(arguments[1])) {
windowCreationInterval = arguments[1];
}
return function windowTimeOperatorFunction(source) {
return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler));
};
}
class WindowTimeOperator {
constructor(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
this.windowTimeSpan = windowTimeSpan;
this.windowCreationInterval = windowCreationInterval;
this.maxWindowSize = maxWindowSize;
this.scheduler = scheduler;
}
call(subscriber, source) {
return source.subscribe(new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler));
}
}
class CountedSubject extends _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"] {
constructor() {
super(...arguments);
this._numberOfNextedValues = 0;
}
next(value) {
this._numberOfNextedValues++;
super.next(value);
}
get numberOfNextedValues() {
return this._numberOfNextedValues;
}
}
class WindowTimeSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_2__["Subscriber"] {
constructor(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
super(destination);
this.destination = destination;
this.windowTimeSpan = windowTimeSpan;
this.windowCreationInterval = windowCreationInterval;
this.maxWindowSize = maxWindowSize;
this.scheduler = scheduler;
this.windows = [];
const window = this.openWindow();
if (windowCreationInterval !== null && windowCreationInterval >= 0) {
const closeState = { subscriber: this, window, context: null };
const creationState = { windowTimeSpan, windowCreationInterval, subscriber: this, scheduler };
this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState));
this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState));
}
else {
const timeSpanOnlyState = { subscriber: this, window, windowTimeSpan };
this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState));
}
}
_next(value) {
const windows = this.windows;
const len = windows.length;
for (let i = 0; i < len; i++) {
const window = windows[i];
if (!window.closed) {
window.next(value);
if (window.numberOfNextedValues >= this.maxWindowSize) {
this.closeWindow(window);
}
}
}
}
_error(err) {
const windows = this.windows;
while (windows.length > 0) {
windows.shift().error(err);
}
this.destination.error(err);
}
_complete() {
const windows = this.windows;
while (windows.length > 0) {
const window = windows.shift();
if (!window.closed) {
window.complete();
}
}
this.destination.complete();
}
openWindow() {
const window = new CountedSubject();
this.windows.push(window);
const destination = this.destination;
destination.next(window);
return window;
}
closeWindow(window) {
window.complete();
const windows = this.windows;
windows.splice(windows.indexOf(window), 1);
}
}
function dispatchWindowTimeSpanOnly(state) {
const { subscriber, windowTimeSpan, window } = state;
if (window) {
subscriber.closeWindow(window);
}
state.window = subscriber.openWindow();
this.schedule(state, windowTimeSpan);
}
function dispatchWindowCreation(state) {
const { windowTimeSpan, subscriber, scheduler, windowCreationInterval } = state;
const window = subscriber.openWindow();
const action = this;
let context = { action, subscription: null };
const timeSpanState = { subscriber, window, context };
context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState);
action.add(context.subscription);
action.schedule(state, windowCreationInterval);
}
function dispatchWindowClose(state) {
const { subscriber, window, context } = state;
if (context && context.action && context.subscription) {
context.action.remove(context.subscription);
}
subscriber.closeWindow(window);
}
//# sourceMappingURL=windowTime.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/windowToggle.js":
/*!***********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/windowToggle.js ***!
\***********************************************************************/
/*! exports provided: windowToggle */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowToggle", function() { return windowToggle; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function windowToggle(openings, closingSelector) {
return (source) => source.lift(new WindowToggleOperator(openings, closingSelector));
}
class WindowToggleOperator {
constructor(openings, closingSelector) {
this.openings = openings;
this.closingSelector = closingSelector;
}
call(subscriber, source) {
return source.subscribe(new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector));
}
}
class WindowToggleSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"] {
constructor(destination, openings, closingSelector) {
super(destination);
this.openings = openings;
this.closingSelector = closingSelector;
this.contexts = [];
this.add(this.openSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, openings, openings));
}
_next(value) {
const { contexts } = this;
if (contexts) {
const len = contexts.length;
for (let i = 0; i < len; i++) {
contexts[i].window.next(value);
}
}
}
_error(err) {
const { contexts } = this;
this.contexts = null;
if (contexts) {
const len = contexts.length;
let index = -1;
while (++index < len) {
const context = contexts[index];
context.window.error(err);
context.subscription.unsubscribe();
}
}
super._error(err);
}
_complete() {
const { contexts } = this;
this.contexts = null;
if (contexts) {
const len = contexts.length;
let index = -1;
while (++index < len) {
const context = contexts[index];
context.window.complete();
context.subscription.unsubscribe();
}
}
super._complete();
}
_unsubscribe() {
const { contexts } = this;
this.contexts = null;
if (contexts) {
const len = contexts.length;
let index = -1;
while (++index < len) {
const context = contexts[index];
context.window.unsubscribe();
context.subscription.unsubscribe();
}
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
if (outerValue === this.openings) {
let closingNotifier;
try {
const { closingSelector } = this;
closingNotifier = closingSelector(innerValue);
}
catch (e) {
return this.error(e);
}
const window = new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"]();
const subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"]();
const context = { window, subscription };
this.contexts.push(context);
const innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, closingNotifier, context);
if (innerSubscription.closed) {
this.closeWindow(this.contexts.length - 1);
}
else {
innerSubscription.context = context;
subscription.add(innerSubscription);
}
this.destination.next(window);
}
else {
this.closeWindow(this.contexts.indexOf(outerValue));
}
}
notifyError(err) {
this.error(err);
}
notifyComplete(inner) {
if (inner !== this.openSubscription) {
this.closeWindow(this.contexts.indexOf(inner.context));
}
}
closeWindow(index) {
if (index === -1) {
return;
}
const { contexts } = this;
const context = contexts[index];
const { window, subscription } = context;
contexts.splice(index, 1);
window.complete();
subscription.unsubscribe();
}
}
//# sourceMappingURL=windowToggle.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/windowWhen.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/windowWhen.js ***!
\*********************************************************************/
/*! exports provided: windowWhen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowWhen", function() { return windowWhen; });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/_esm2015/internal/Subject.js");
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function windowWhen(closingSelector) {
return function windowWhenOperatorFunction(source) {
return source.lift(new WindowOperator(closingSelector));
};
}
class WindowOperator {
constructor(closingSelector) {
this.closingSelector = closingSelector;
}
call(subscriber, source) {
return source.subscribe(new WindowSubscriber(subscriber, this.closingSelector));
}
}
class WindowSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"] {
constructor(destination, closingSelector) {
super(destination);
this.destination = destination;
this.closingSelector = closingSelector;
this.openWindow();
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.openWindow(innerSub);
}
notifyError(error, innerSub) {
this._error(error);
}
notifyComplete(innerSub) {
this.openWindow(innerSub);
}
_next(value) {
this.window.next(value);
}
_error(err) {
this.window.error(err);
this.destination.error(err);
this.unsubscribeClosingNotification();
}
_complete() {
this.window.complete();
this.destination.complete();
this.unsubscribeClosingNotification();
}
unsubscribeClosingNotification() {
if (this.closingNotification) {
this.closingNotification.unsubscribe();
}
}
openWindow(innerSub = null) {
if (innerSub) {
this.remove(innerSub);
innerSub.unsubscribe();
}
const prevWindow = this.window;
if (prevWindow) {
prevWindow.complete();
}
const window = this.window = new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"]();
this.destination.next(window);
let closingNotifier;
try {
const { closingSelector } = this;
closingNotifier = closingSelector();
}
catch (e) {
this.destination.error(e);
this.window.error(e);
return;
}
this.add(this.closingNotification = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, closingNotifier));
}
}
//# sourceMappingURL=windowWhen.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/withLatestFrom.js":
/*!*************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/withLatestFrom.js ***!
\*************************************************************************/
/*! exports provided: withLatestFrom */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withLatestFrom", function() { return withLatestFrom; });
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OuterSubscriber */ "./node_modules/rxjs/_esm2015/internal/OuterSubscriber.js");
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/subscribeToResult */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js");
function withLatestFrom(...args) {
return (source) => {
let project;
if (typeof args[args.length - 1] === 'function') {
project = args.pop();
}
const observables = args;
return source.lift(new WithLatestFromOperator(observables, project));
};
}
class WithLatestFromOperator {
constructor(observables, project) {
this.observables = observables;
this.project = project;
}
call(subscriber, source) {
return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
}
}
class WithLatestFromSubscriber extends _OuterSubscriber__WEBPACK_IMPORTED_MODULE_0__["OuterSubscriber"] {
constructor(destination, observables, project) {
super(destination);
this.observables = observables;
this.project = project;
this.toRespond = [];
const len = observables.length;
this.values = new Array(len);
for (let i = 0; i < len; i++) {
this.toRespond.push(i);
}
for (let i = 0; i < len; i++) {
let observable = observables[i];
this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, observable, observable, i));
}
}
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
this.values[outerIndex] = innerValue;
const toRespond = this.toRespond;
if (toRespond.length > 0) {
const found = toRespond.indexOf(outerIndex);
if (found !== -1) {
toRespond.splice(found, 1);
}
}
}
notifyComplete() {
}
_next(value) {
if (this.toRespond.length === 0) {
const args = [value, ...this.values];
if (this.project) {
this._tryProject(args);
}
else {
this.destination.next(args);
}
}
}
_tryProject(args) {
let result;
try {
result = this.project.apply(this, args);
}
catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
}
}
//# sourceMappingURL=withLatestFrom.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/zip.js":
/*!**************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/zip.js ***!
\**************************************************************/
/*! exports provided: zip */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return zip; });
/* harmony import */ var _observable_zip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/zip */ "./node_modules/rxjs/_esm2015/internal/observable/zip.js");
function zip(...observables) {
return function zipOperatorFunction(source) {
return source.lift.call(Object(_observable_zip__WEBPACK_IMPORTED_MODULE_0__["zip"])(source, ...observables));
};
}
//# sourceMappingURL=zip.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/operators/zipAll.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/operators/zipAll.js ***!
\*****************************************************************/
/*! exports provided: zipAll */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zipAll", function() { return zipAll; });
/* harmony import */ var _observable_zip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/zip */ "./node_modules/rxjs/_esm2015/internal/observable/zip.js");
function zipAll(project) {
return (source) => source.lift(new _observable_zip__WEBPACK_IMPORTED_MODULE_0__["ZipOperator"](project));
}
//# sourceMappingURL=zipAll.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduleArray.js":
/*!************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduled/scheduleArray.js ***!
\************************************************************************/
/*! exports provided: scheduleArray */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduleArray", function() { return scheduleArray; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
function scheduleArray(input, scheduler) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"]();
let i = 0;
sub.add(scheduler.schedule(function () {
if (i === input.length) {
subscriber.complete();
return;
}
subscriber.next(input[i++]);
if (!subscriber.closed) {
sub.add(this.schedule());
}
}));
return sub;
});
}
//# sourceMappingURL=scheduleArray.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduleIterable.js":
/*!***************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduled/scheduleIterable.js ***!
\***************************************************************************/
/*! exports provided: scheduleIterable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduleIterable", function() { return scheduleIterable; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../symbol/iterator */ "./node_modules/rxjs/_esm2015/internal/symbol/iterator.js");
function scheduleIterable(input, scheduler) {
if (!input) {
throw new Error('Iterable cannot be null');
}
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"]();
let iterator;
sub.add(() => {
if (iterator && typeof iterator.return === 'function') {
iterator.return();
}
});
sub.add(scheduler.schedule(() => {
iterator = input[_symbol_iterator__WEBPACK_IMPORTED_MODULE_2__["iterator"]]();
sub.add(scheduler.schedule(function () {
if (subscriber.closed) {
return;
}
let value;
let done;
try {
const result = iterator.next();
value = result.value;
done = result.done;
}
catch (err) {
subscriber.error(err);
return;
}
if (done) {
subscriber.complete();
}
else {
subscriber.next(value);
this.schedule();
}
}));
}));
return sub;
});
}
//# sourceMappingURL=scheduleIterable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduleObservable.js":
/*!*****************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduled/scheduleObservable.js ***!
\*****************************************************************************/
/*! exports provided: scheduleObservable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduleObservable", function() { return scheduleObservable; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../symbol/observable */ "./node_modules/rxjs/_esm2015/internal/symbol/observable.js");
function scheduleObservable(input, scheduler) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"]();
sub.add(scheduler.schedule(() => {
const observable = input[_symbol_observable__WEBPACK_IMPORTED_MODULE_2__["observable"]]();
sub.add(observable.subscribe({
next(value) { sub.add(scheduler.schedule(() => subscriber.next(value))); },
error(err) { sub.add(scheduler.schedule(() => subscriber.error(err))); },
complete() { sub.add(scheduler.schedule(() => subscriber.complete())); },
}));
}));
return sub;
});
}
//# sourceMappingURL=scheduleObservable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduled/schedulePromise.js":
/*!**************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduled/schedulePromise.js ***!
\**************************************************************************/
/*! exports provided: schedulePromise */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "schedulePromise", function() { return schedulePromise; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
function schedulePromise(input, scheduler) {
return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](subscriber => {
const sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"]();
sub.add(scheduler.schedule(() => input.then(value => {
sub.add(scheduler.schedule(() => {
subscriber.next(value);
sub.add(scheduler.schedule(() => subscriber.complete()));
}));
}, err => {
sub.add(scheduler.schedule(() => subscriber.error(err)));
})));
return sub;
});
}
//# sourceMappingURL=schedulePromise.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduled.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduled/scheduled.js ***!
\********************************************************************/
/*! exports provided: scheduled */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduled", function() { return scheduled; });
/* harmony import */ var _scheduleObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./scheduleObservable */ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduleObservable.js");
/* harmony import */ var _schedulePromise__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./schedulePromise */ "./node_modules/rxjs/_esm2015/internal/scheduled/schedulePromise.js");
/* harmony import */ var _scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./scheduleArray */ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduleArray.js");
/* harmony import */ var _scheduleIterable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./scheduleIterable */ "./node_modules/rxjs/_esm2015/internal/scheduled/scheduleIterable.js");
/* harmony import */ var _util_isInteropObservable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/isInteropObservable */ "./node_modules/rxjs/_esm2015/internal/util/isInteropObservable.js");
/* harmony import */ var _util_isPromise__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/isPromise */ "./node_modules/rxjs/_esm2015/internal/util/isPromise.js");
/* harmony import */ var _util_isArrayLike__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/isArrayLike */ "./node_modules/rxjs/_esm2015/internal/util/isArrayLike.js");
/* harmony import */ var _util_isIterable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/isIterable */ "./node_modules/rxjs/_esm2015/internal/util/isIterable.js");
function scheduled(input, scheduler) {
if (input != null) {
if (Object(_util_isInteropObservable__WEBPACK_IMPORTED_MODULE_4__["isInteropObservable"])(input)) {
return Object(_scheduleObservable__WEBPACK_IMPORTED_MODULE_0__["scheduleObservable"])(input, scheduler);
}
else if (Object(_util_isPromise__WEBPACK_IMPORTED_MODULE_5__["isPromise"])(input)) {
return Object(_schedulePromise__WEBPACK_IMPORTED_MODULE_1__["schedulePromise"])(input, scheduler);
}
else if (Object(_util_isArrayLike__WEBPACK_IMPORTED_MODULE_6__["isArrayLike"])(input)) {
return Object(_scheduleArray__WEBPACK_IMPORTED_MODULE_2__["scheduleArray"])(input, scheduler);
}
else if (Object(_util_isIterable__WEBPACK_IMPORTED_MODULE_7__["isIterable"])(input) || typeof input === 'string') {
return Object(_scheduleIterable__WEBPACK_IMPORTED_MODULE_3__["scheduleIterable"])(input, scheduler);
}
}
throw new TypeError((input !== null && typeof input || input) + ' is not observable');
}
//# sourceMappingURL=scheduled.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/Action.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/Action.js ***!
\*****************************************************************/
/*! exports provided: Action */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return Action; });
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/_esm2015/internal/Subscription.js");
class Action extends _Subscription__WEBPACK_IMPORTED_MODULE_0__["Subscription"] {
constructor(scheduler, work) {
super();
}
schedule(state, delay = 0) {
return this;
}
}
//# sourceMappingURL=Action.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/AnimationFrameAction.js":
/*!*******************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/AnimationFrameAction.js ***!
\*******************************************************************************/
/*! exports provided: AnimationFrameAction */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationFrameAction", function() { return AnimationFrameAction; });
/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AsyncAction */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncAction.js");
class AnimationFrameAction extends _AsyncAction__WEBPACK_IMPORTED_MODULE_0__["AsyncAction"] {
constructor(scheduler, work) {
super(scheduler, work);
this.scheduler = scheduler;
this.work = work;
}
requestAsyncId(scheduler, id, delay = 0) {
if (delay !== null && delay > 0) {
return super.requestAsyncId(scheduler, id, delay);
}
scheduler.actions.push(this);
return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(() => scheduler.flush(null)));
}
recycleAsyncId(scheduler, id, delay = 0) {
if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
return super.recycleAsyncId(scheduler, id, delay);
}
if (scheduler.actions.length === 0) {
cancelAnimationFrame(id);
scheduler.scheduled = undefined;
}
return undefined;
}
}
//# sourceMappingURL=AnimationFrameAction.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/AnimationFrameScheduler.js":
/*!**********************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/AnimationFrameScheduler.js ***!
\**********************************************************************************/
/*! exports provided: AnimationFrameScheduler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationFrameScheduler", function() { return AnimationFrameScheduler; });
/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AsyncScheduler */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncScheduler.js");
class AnimationFrameScheduler extends _AsyncScheduler__WEBPACK_IMPORTED_MODULE_0__["AsyncScheduler"] {
flush(action) {
this.active = true;
this.scheduled = undefined;
const { actions } = this;
let error;
let index = -1;
let count = actions.length;
action = action || actions.shift();
do {
if (error = action.execute(action.state, action.delay)) {
break;
}
} while (++index < count && (action = actions.shift()));
this.active = false;
if (error) {
while (++index < count && (action = actions.shift())) {
action.unsubscribe();
}
throw error;
}
}
}
//# sourceMappingURL=AnimationFrameScheduler.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/AsapAction.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/AsapAction.js ***!
\*********************************************************************/
/*! exports provided: AsapAction */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsapAction", function() { return AsapAction; });
/* harmony import */ var _util_Immediate__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/Immediate */ "./node_modules/rxjs/_esm2015/internal/util/Immediate.js");
/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AsyncAction */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncAction.js");
class AsapAction extends _AsyncAction__WEBPACK_IMPORTED_MODULE_1__["AsyncAction"] {
constructor(scheduler, work) {
super(scheduler, work);
this.scheduler = scheduler;
this.work = work;
}
requestAsyncId(scheduler, id, delay = 0) {
if (delay !== null && delay > 0) {
return super.requestAsyncId(scheduler, id, delay);
}
scheduler.actions.push(this);
return scheduler.scheduled || (scheduler.scheduled = _util_Immediate__WEBPACK_IMPORTED_MODULE_0__["Immediate"].setImmediate(scheduler.flush.bind(scheduler, null)));
}
recycleAsyncId(scheduler, id, delay = 0) {
if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
return super.recycleAsyncId(scheduler, id, delay);
}
if (scheduler.actions.length === 0) {
_util_Immediate__WEBPACK_IMPORTED_MODULE_0__["Immediate"].clearImmediate(id);
scheduler.scheduled = undefined;
}
return undefined;
}
}
//# sourceMappingURL=AsapAction.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/AsapScheduler.js":
/*!************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/AsapScheduler.js ***!
\************************************************************************/
/*! exports provided: AsapScheduler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsapScheduler", function() { return AsapScheduler; });
/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AsyncScheduler */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncScheduler.js");
class AsapScheduler extends _AsyncScheduler__WEBPACK_IMPORTED_MODULE_0__["AsyncScheduler"] {
flush(action) {
this.active = true;
this.scheduled = undefined;
const { actions } = this;
let error;
let index = -1;
let count = actions.length;
action = action || actions.shift();
do {
if (error = action.execute(action.state, action.delay)) {
break;
}
} while (++index < count && (action = actions.shift()));
this.active = false;
if (error) {
while (++index < count && (action = actions.shift())) {
action.unsubscribe();
}
throw error;
}
}
}
//# sourceMappingURL=AsapScheduler.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncAction.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/AsyncAction.js ***!
\**********************************************************************/
/*! exports provided: AsyncAction */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncAction", function() { return AsyncAction; });
/* harmony import */ var _Action__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Action */ "./node_modules/rxjs/_esm2015/internal/scheduler/Action.js");
class AsyncAction extends _Action__WEBPACK_IMPORTED_MODULE_0__["Action"] {
constructor(scheduler, work) {
super(scheduler, work);
this.scheduler = scheduler;
this.work = work;
this.pending = false;
}
schedule(state, delay = 0) {
if (this.closed) {
return this;
}
this.state = state;
const id = this.id;
const scheduler = this.scheduler;
if (id != null) {
this.id = this.recycleAsyncId(scheduler, id, delay);
}
this.pending = true;
this.delay = delay;
this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
return this;
}
requestAsyncId(scheduler, id, delay = 0) {
return setInterval(scheduler.flush.bind(scheduler, this), delay);
}
recycleAsyncId(scheduler, id, delay = 0) {
if (delay !== null && this.delay === delay && this.pending === false) {
return id;
}
clearInterval(id);
return undefined;
}
execute(state, delay) {
if (this.closed) {
return new Error('executing a cancelled action');
}
this.pending = false;
const error = this._execute(state, delay);
if (error) {
return error;
}
else if (this.pending === false && this.id != null) {
this.id = this.recycleAsyncId(this.scheduler, this.id, null);
}
}
_execute(state, delay) {
let errored = false;
let errorValue = undefined;
try {
this.work(state);
}
catch (e) {
errored = true;
errorValue = !!e && e || new Error(e);
}
if (errored) {
this.unsubscribe();
return errorValue;
}
}
_unsubscribe() {
const id = this.id;
const scheduler = this.scheduler;
const actions = scheduler.actions;
const index = actions.indexOf(this);
this.work = null;
this.state = null;
this.pending = false;
this.scheduler = null;
if (index !== -1) {
actions.splice(index, 1);
}
if (id != null) {
this.id = this.recycleAsyncId(scheduler, id, null);
}
this.delay = null;
}
}
//# sourceMappingURL=AsyncAction.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncScheduler.js":
/*!*************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/AsyncScheduler.js ***!
\*************************************************************************/
/*! exports provided: AsyncScheduler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncScheduler", function() { return AsyncScheduler; });
/* harmony import */ var _Scheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Scheduler */ "./node_modules/rxjs/_esm2015/internal/Scheduler.js");
class AsyncScheduler extends _Scheduler__WEBPACK_IMPORTED_MODULE_0__["Scheduler"] {
constructor(SchedulerAction, now = _Scheduler__WEBPACK_IMPORTED_MODULE_0__["Scheduler"].now) {
super(SchedulerAction, () => {
if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
return AsyncScheduler.delegate.now();
}
else {
return now();
}
});
this.actions = [];
this.active = false;
this.scheduled = undefined;
}
schedule(work, delay = 0, state) {
if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
return AsyncScheduler.delegate.schedule(work, delay, state);
}
else {
return super.schedule(work, delay, state);
}
}
flush(action) {
const { actions } = this;
if (this.active) {
actions.push(action);
return;
}
let error;
this.active = true;
do {
if (error = action.execute(action.state, action.delay)) {
break;
}
} while (action = actions.shift());
this.active = false;
if (error) {
while (action = actions.shift()) {
action.unsubscribe();
}
throw error;
}
}
}
//# sourceMappingURL=AsyncScheduler.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/QueueAction.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/QueueAction.js ***!
\**********************************************************************/
/*! exports provided: QueueAction */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueueAction", function() { return QueueAction; });
/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AsyncAction */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncAction.js");
class QueueAction extends _AsyncAction__WEBPACK_IMPORTED_MODULE_0__["AsyncAction"] {
constructor(scheduler, work) {
super(scheduler, work);
this.scheduler = scheduler;
this.work = work;
}
schedule(state, delay = 0) {
if (delay > 0) {
return super.schedule(state, delay);
}
this.delay = delay;
this.state = state;
this.scheduler.flush(this);
return this;
}
execute(state, delay) {
return (delay > 0 || this.closed) ?
super.execute(state, delay) :
this._execute(state, delay);
}
requestAsyncId(scheduler, id, delay = 0) {
if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
return super.requestAsyncId(scheduler, id, delay);
}
return scheduler.flush(this);
}
}
//# sourceMappingURL=QueueAction.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/QueueScheduler.js":
/*!*************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/QueueScheduler.js ***!
\*************************************************************************/
/*! exports provided: QueueScheduler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueueScheduler", function() { return QueueScheduler; });
/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AsyncScheduler */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncScheduler.js");
class QueueScheduler extends _AsyncScheduler__WEBPACK_IMPORTED_MODULE_0__["AsyncScheduler"] {
}
//# sourceMappingURL=QueueScheduler.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/VirtualTimeScheduler.js":
/*!*******************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/VirtualTimeScheduler.js ***!
\*******************************************************************************/
/*! exports provided: VirtualTimeScheduler, VirtualAction */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VirtualTimeScheduler", function() { return VirtualTimeScheduler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VirtualAction", function() { return VirtualAction; });
/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AsyncAction */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncAction.js");
/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AsyncScheduler */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncScheduler.js");
class VirtualTimeScheduler extends _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__["AsyncScheduler"] {
constructor(SchedulerAction = VirtualAction, maxFrames = Number.POSITIVE_INFINITY) {
super(SchedulerAction, () => this.frame);
this.maxFrames = maxFrames;
this.frame = 0;
this.index = -1;
}
flush() {
const { actions, maxFrames } = this;
let error, action;
while ((action = actions[0]) && action.delay <= maxFrames) {
actions.shift();
this.frame = action.delay;
if (error = action.execute(action.state, action.delay)) {
break;
}
}
if (error) {
while (action = actions.shift()) {
action.unsubscribe();
}
throw error;
}
}
}
VirtualTimeScheduler.frameTimeFactor = 10;
class VirtualAction extends _AsyncAction__WEBPACK_IMPORTED_MODULE_0__["AsyncAction"] {
constructor(scheduler, work, index = scheduler.index += 1) {
super(scheduler, work);
this.scheduler = scheduler;
this.work = work;
this.index = index;
this.active = true;
this.index = scheduler.index = index;
}
schedule(state, delay = 0) {
if (!this.id) {
return super.schedule(state, delay);
}
this.active = false;
const action = new VirtualAction(this.scheduler, this.work);
this.add(action);
return action.schedule(state, delay);
}
requestAsyncId(scheduler, id, delay = 0) {
this.delay = scheduler.frame + delay;
const { actions } = scheduler;
actions.push(this);
actions.sort(VirtualAction.sortActions);
return true;
}
recycleAsyncId(scheduler, id, delay = 0) {
return undefined;
}
_execute(state, delay) {
if (this.active === true) {
return super._execute(state, delay);
}
}
static sortActions(a, b) {
if (a.delay === b.delay) {
if (a.index === b.index) {
return 0;
}
else if (a.index > b.index) {
return 1;
}
else {
return -1;
}
}
else if (a.delay > b.delay) {
return 1;
}
else {
return -1;
}
}
}
//# sourceMappingURL=VirtualTimeScheduler.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/animationFrame.js":
/*!*************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/animationFrame.js ***!
\*************************************************************************/
/*! exports provided: animationFrame */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "animationFrame", function() { return animationFrame; });
/* harmony import */ var _AnimationFrameAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AnimationFrameAction */ "./node_modules/rxjs/_esm2015/internal/scheduler/AnimationFrameAction.js");
/* harmony import */ var _AnimationFrameScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AnimationFrameScheduler */ "./node_modules/rxjs/_esm2015/internal/scheduler/AnimationFrameScheduler.js");
const animationFrame = new _AnimationFrameScheduler__WEBPACK_IMPORTED_MODULE_1__["AnimationFrameScheduler"](_AnimationFrameAction__WEBPACK_IMPORTED_MODULE_0__["AnimationFrameAction"]);
//# sourceMappingURL=animationFrame.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/asap.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/asap.js ***!
\***************************************************************/
/*! exports provided: asap */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asap", function() { return asap; });
/* harmony import */ var _AsapAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AsapAction */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsapAction.js");
/* harmony import */ var _AsapScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AsapScheduler */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsapScheduler.js");
const asap = new _AsapScheduler__WEBPACK_IMPORTED_MODULE_1__["AsapScheduler"](_AsapAction__WEBPACK_IMPORTED_MODULE_0__["AsapAction"]);
//# sourceMappingURL=asap.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/async.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/async.js ***!
\****************************************************************/
/*! exports provided: async */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "async", function() { return async; });
/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AsyncAction */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncAction.js");
/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AsyncScheduler */ "./node_modules/rxjs/_esm2015/internal/scheduler/AsyncScheduler.js");
const async = new _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__["AsyncScheduler"](_AsyncAction__WEBPACK_IMPORTED_MODULE_0__["AsyncAction"]);
//# sourceMappingURL=async.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/scheduler/queue.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/scheduler/queue.js ***!
\****************************************************************/
/*! exports provided: queue */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queue", function() { return queue; });
/* harmony import */ var _QueueAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./QueueAction */ "./node_modules/rxjs/_esm2015/internal/scheduler/QueueAction.js");
/* harmony import */ var _QueueScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./QueueScheduler */ "./node_modules/rxjs/_esm2015/internal/scheduler/QueueScheduler.js");
const queue = new _QueueScheduler__WEBPACK_IMPORTED_MODULE_1__["QueueScheduler"](_QueueAction__WEBPACK_IMPORTED_MODULE_0__["QueueAction"]);
//# sourceMappingURL=queue.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/symbol/iterator.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/symbol/iterator.js ***!
\****************************************************************/
/*! exports provided: getSymbolIterator, iterator, $$iterator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSymbolIterator", function() { return getSymbolIterator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iterator", function() { return iterator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "$$iterator", function() { return $$iterator; });
function getSymbolIterator() {
if (typeof Symbol !== 'function' || !Symbol.iterator) {
return '@@iterator';
}
return Symbol.iterator;
}
const iterator = getSymbolIterator();
const $$iterator = iterator;
//# sourceMappingURL=iterator.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/symbol/observable.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/symbol/observable.js ***!
\******************************************************************/
/*! exports provided: observable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "observable", function() { return observable; });
const observable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
//# sourceMappingURL=observable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/symbol/rxSubscriber.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/symbol/rxSubscriber.js ***!
\********************************************************************/
/*! exports provided: rxSubscriber, $$rxSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rxSubscriber", function() { return rxSubscriber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "$$rxSubscriber", function() { return $$rxSubscriber; });
const rxSubscriber = (() => typeof Symbol === 'function'
? Symbol('rxSubscriber')
: '@@rxSubscriber_' + Math.random())();
const $$rxSubscriber = rxSubscriber;
//# sourceMappingURL=rxSubscriber.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/ArgumentOutOfRangeError.js":
/*!*****************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/ArgumentOutOfRangeError.js ***!
\*****************************************************************************/
/*! exports provided: ArgumentOutOfRangeError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArgumentOutOfRangeError", function() { return ArgumentOutOfRangeError; });
const ArgumentOutOfRangeErrorImpl = (() => {
function ArgumentOutOfRangeErrorImpl() {
Error.call(this);
this.message = 'argument out of range';
this.name = 'ArgumentOutOfRangeError';
return this;
}
ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);
return ArgumentOutOfRangeErrorImpl;
})();
const ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;
//# sourceMappingURL=ArgumentOutOfRangeError.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/EmptyError.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/EmptyError.js ***!
\****************************************************************/
/*! exports provided: EmptyError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmptyError", function() { return EmptyError; });
const EmptyErrorImpl = (() => {
function EmptyErrorImpl() {
Error.call(this);
this.message = 'no elements in sequence';
this.name = 'EmptyError';
return this;
}
EmptyErrorImpl.prototype = Object.create(Error.prototype);
return EmptyErrorImpl;
})();
const EmptyError = EmptyErrorImpl;
//# sourceMappingURL=EmptyError.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/Immediate.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/Immediate.js ***!
\***************************************************************/
/*! exports provided: Immediate, TestTools */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Immediate", function() { return Immediate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TestTools", function() { return TestTools; });
let nextHandle = 1;
const RESOLVED = (() => Promise.resolve())();
const activeHandles = {};
function findAndClearHandle(handle) {
if (handle in activeHandles) {
delete activeHandles[handle];
return true;
}
return false;
}
const Immediate = {
setImmediate(cb) {
const handle = nextHandle++;
activeHandles[handle] = true;
RESOLVED.then(() => findAndClearHandle(handle) && cb());
return handle;
},
clearImmediate(handle) {
findAndClearHandle(handle);
},
};
const TestTools = {
pending() {
return Object.keys(activeHandles).length;
}
};
//# sourceMappingURL=Immediate.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/ObjectUnsubscribedError.js":
/*!*****************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/ObjectUnsubscribedError.js ***!
\*****************************************************************************/
/*! exports provided: ObjectUnsubscribedError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObjectUnsubscribedError", function() { return ObjectUnsubscribedError; });
const ObjectUnsubscribedErrorImpl = (() => {
function ObjectUnsubscribedErrorImpl() {
Error.call(this);
this.message = 'object unsubscribed';
this.name = 'ObjectUnsubscribedError';
return this;
}
ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);
return ObjectUnsubscribedErrorImpl;
})();
const ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;
//# sourceMappingURL=ObjectUnsubscribedError.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/TimeoutError.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/TimeoutError.js ***!
\******************************************************************/
/*! exports provided: TimeoutError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return TimeoutError; });
const TimeoutErrorImpl = (() => {
function TimeoutErrorImpl() {
Error.call(this);
this.message = 'Timeout has occurred';
this.name = 'TimeoutError';
return this;
}
TimeoutErrorImpl.prototype = Object.create(Error.prototype);
return TimeoutErrorImpl;
})();
const TimeoutError = TimeoutErrorImpl;
//# sourceMappingURL=TimeoutError.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/UnsubscriptionError.js":
/*!*************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/UnsubscriptionError.js ***!
\*************************************************************************/
/*! exports provided: UnsubscriptionError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsubscriptionError", function() { return UnsubscriptionError; });
const UnsubscriptionErrorImpl = (() => {
function UnsubscriptionErrorImpl(errors) {
Error.call(this);
this.message = errors ?
`${errors.length} errors occurred during unsubscription:
${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\n ')}` : '';
this.name = 'UnsubscriptionError';
this.errors = errors;
return this;
}
UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);
return UnsubscriptionErrorImpl;
})();
const UnsubscriptionError = UnsubscriptionErrorImpl;
//# sourceMappingURL=UnsubscriptionError.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/canReportError.js":
/*!********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/canReportError.js ***!
\********************************************************************/
/*! exports provided: canReportError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canReportError", function() { return canReportError; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
function canReportError(observer) {
while (observer) {
const { closed, destination, isStopped } = observer;
if (closed || isStopped) {
return false;
}
else if (destination && destination instanceof _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"]) {
observer = destination;
}
else {
observer = null;
}
}
return true;
}
//# sourceMappingURL=canReportError.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/hostReportError.js":
/*!*********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/hostReportError.js ***!
\*********************************************************************/
/*! exports provided: hostReportError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hostReportError", function() { return hostReportError; });
function hostReportError(err) {
setTimeout(() => { throw err; }, 0);
}
//# sourceMappingURL=hostReportError.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/identity.js":
/*!**************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/identity.js ***!
\**************************************************************/
/*! exports provided: identity */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return identity; });
function identity(x) {
return x;
}
//# sourceMappingURL=identity.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isArray.js":
/*!*************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isArray.js ***!
\*************************************************************/
/*! exports provided: isArray */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArray", function() { return isArray; });
const isArray = (() => Array.isArray || ((x) => x && typeof x.length === 'number'))();
//# sourceMappingURL=isArray.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isArrayLike.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isArrayLike.js ***!
\*****************************************************************/
/*! exports provided: isArrayLike */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArrayLike", function() { return isArrayLike; });
const isArrayLike = ((x) => x && typeof x.length === 'number' && typeof x !== 'function');
//# sourceMappingURL=isArrayLike.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isDate.js":
/*!************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isDate.js ***!
\************************************************************/
/*! exports provided: isDate */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDate", function() { return isDate; });
function isDate(value) {
return value instanceof Date && !isNaN(+value);
}
//# sourceMappingURL=isDate.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isFunction.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isFunction.js ***!
\****************************************************************/
/*! exports provided: isFunction */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFunction", function() { return isFunction; });
function isFunction(x) {
return typeof x === 'function';
}
//# sourceMappingURL=isFunction.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isInteropObservable.js":
/*!*************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isInteropObservable.js ***!
\*************************************************************************/
/*! exports provided: isInteropObservable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isInteropObservable", function() { return isInteropObservable; });
/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../symbol/observable */ "./node_modules/rxjs/_esm2015/internal/symbol/observable.js");
function isInteropObservable(input) {
return input && typeof input[_symbol_observable__WEBPACK_IMPORTED_MODULE_0__["observable"]] === 'function';
}
//# sourceMappingURL=isInteropObservable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isIterable.js":
/*!****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isIterable.js ***!
\****************************************************************/
/*! exports provided: isIterable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isIterable", function() { return isIterable; });
/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../symbol/iterator */ "./node_modules/rxjs/_esm2015/internal/symbol/iterator.js");
function isIterable(input) {
return input && typeof input[_symbol_iterator__WEBPACK_IMPORTED_MODULE_0__["iterator"]] === 'function';
}
//# sourceMappingURL=isIterable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isNumeric.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isNumeric.js ***!
\***************************************************************/
/*! exports provided: isNumeric */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNumeric", function() { return isNumeric; });
/* harmony import */ var _isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isArray */ "./node_modules/rxjs/_esm2015/internal/util/isArray.js");
function isNumeric(val) {
return !Object(_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(val) && (val - parseFloat(val) + 1) >= 0;
}
//# sourceMappingURL=isNumeric.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isObject.js":
/*!**************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isObject.js ***!
\**************************************************************/
/*! exports provided: isObject */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return isObject; });
function isObject(x) {
return x !== null && typeof x === 'object';
}
//# sourceMappingURL=isObject.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isObservable.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isObservable.js ***!
\******************************************************************/
/*! exports provided: isObservable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObservable", function() { return isObservable; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
function isObservable(obj) {
return !!obj && (obj instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"] || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function'));
}
//# sourceMappingURL=isObservable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isPromise.js":
/*!***************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isPromise.js ***!
\***************************************************************/
/*! exports provided: isPromise */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; });
function isPromise(value) {
return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
}
//# sourceMappingURL=isPromise.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/isScheduler.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/isScheduler.js ***!
\*****************************************************************/
/*! exports provided: isScheduler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isScheduler", function() { return isScheduler; });
function isScheduler(value) {
return value && typeof value.schedule === 'function';
}
//# sourceMappingURL=isScheduler.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/noop.js":
/*!**********************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/noop.js ***!
\**********************************************************/
/*! exports provided: noop */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "noop", function() { return noop; });
function noop() { }
//# sourceMappingURL=noop.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/not.js":
/*!*********************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/not.js ***!
\*********************************************************/
/*! exports provided: not */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "not", function() { return not; });
function not(pred, thisArg) {
function notPred() {
return !(notPred.pred.apply(notPred.thisArg, arguments));
}
notPred.pred = pred;
notPred.thisArg = thisArg;
return notPred;
}
//# sourceMappingURL=not.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/pipe.js":
/*!**********************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/pipe.js ***!
\**********************************************************/
/*! exports provided: pipe, pipeFromArray */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pipe", function() { return pipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pipeFromArray", function() { return pipeFromArray; });
/* harmony import */ var _identity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./identity */ "./node_modules/rxjs/_esm2015/internal/util/identity.js");
function pipe(...fns) {
return pipeFromArray(fns);
}
function pipeFromArray(fns) {
if (fns.length === 0) {
return _identity__WEBPACK_IMPORTED_MODULE_0__["identity"];
}
if (fns.length === 1) {
return fns[0];
}
return function piped(input) {
return fns.reduce((prev, fn) => fn(prev), input);
};
}
//# sourceMappingURL=pipe.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/subscribeTo.js":
/*!*****************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/subscribeTo.js ***!
\*****************************************************************/
/*! exports provided: subscribeTo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeTo", function() { return subscribeTo; });
/* harmony import */ var _subscribeToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./subscribeToArray */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToArray.js");
/* harmony import */ var _subscribeToPromise__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./subscribeToPromise */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToPromise.js");
/* harmony import */ var _subscribeToIterable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./subscribeToIterable */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToIterable.js");
/* harmony import */ var _subscribeToObservable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./subscribeToObservable */ "./node_modules/rxjs/_esm2015/internal/util/subscribeToObservable.js");
/* harmony import */ var _isArrayLike__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./isArrayLike */ "./node_modules/rxjs/_esm2015/internal/util/isArrayLike.js");
/* harmony import */ var _isPromise__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./isPromise */ "./node_modules/rxjs/_esm2015/internal/util/isPromise.js");
/* harmony import */ var _isObject__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./isObject */ "./node_modules/rxjs/_esm2015/internal/util/isObject.js");
/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../symbol/iterator */ "./node_modules/rxjs/_esm2015/internal/symbol/iterator.js");
/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../symbol/observable */ "./node_modules/rxjs/_esm2015/internal/symbol/observable.js");
const subscribeTo = (result) => {
if (!!result && typeof result[_symbol_observable__WEBPACK_IMPORTED_MODULE_8__["observable"]] === 'function') {
return Object(_subscribeToObservable__WEBPACK_IMPORTED_MODULE_3__["subscribeToObservable"])(result);
}
else if (Object(_isArrayLike__WEBPACK_IMPORTED_MODULE_4__["isArrayLike"])(result)) {
return Object(_subscribeToArray__WEBPACK_IMPORTED_MODULE_0__["subscribeToArray"])(result);
}
else if (Object(_isPromise__WEBPACK_IMPORTED_MODULE_5__["isPromise"])(result)) {
return Object(_subscribeToPromise__WEBPACK_IMPORTED_MODULE_1__["subscribeToPromise"])(result);
}
else if (!!result && typeof result[_symbol_iterator__WEBPACK_IMPORTED_MODULE_7__["iterator"]] === 'function') {
return Object(_subscribeToIterable__WEBPACK_IMPORTED_MODULE_2__["subscribeToIterable"])(result);
}
else {
const value = Object(_isObject__WEBPACK_IMPORTED_MODULE_6__["isObject"])(result) ? 'an invalid object' : `'${result}'`;
const msg = `You provided ${value} where a stream was expected.`
+ ' You can provide an Observable, Promise, Array, or Iterable.';
throw new TypeError(msg);
}
};
//# sourceMappingURL=subscribeTo.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/subscribeToArray.js":
/*!**********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/subscribeToArray.js ***!
\**********************************************************************/
/*! exports provided: subscribeToArray */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToArray", function() { return subscribeToArray; });
const subscribeToArray = (array) => (subscriber) => {
for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) {
subscriber.next(array[i]);
}
subscriber.complete();
};
//# sourceMappingURL=subscribeToArray.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/subscribeToIterable.js":
/*!*************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/subscribeToIterable.js ***!
\*************************************************************************/
/*! exports provided: subscribeToIterable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToIterable", function() { return subscribeToIterable; });
/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../symbol/iterator */ "./node_modules/rxjs/_esm2015/internal/symbol/iterator.js");
const subscribeToIterable = (iterable) => (subscriber) => {
const iterator = iterable[_symbol_iterator__WEBPACK_IMPORTED_MODULE_0__["iterator"]]();
do {
const item = iterator.next();
if (item.done) {
subscriber.complete();
break;
}
subscriber.next(item.value);
if (subscriber.closed) {
break;
}
} while (true);
if (typeof iterator.return === 'function') {
subscriber.add(() => {
if (iterator.return) {
iterator.return();
}
});
}
return subscriber;
};
//# sourceMappingURL=subscribeToIterable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/subscribeToObservable.js":
/*!***************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/subscribeToObservable.js ***!
\***************************************************************************/
/*! exports provided: subscribeToObservable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToObservable", function() { return subscribeToObservable; });
/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../symbol/observable */ "./node_modules/rxjs/_esm2015/internal/symbol/observable.js");
const subscribeToObservable = (obj) => (subscriber) => {
const obs = obj[_symbol_observable__WEBPACK_IMPORTED_MODULE_0__["observable"]]();
if (typeof obs.subscribe !== 'function') {
throw new TypeError('Provided object does not correctly implement Symbol.observable');
}
else {
return obs.subscribe(subscriber);
}
};
//# sourceMappingURL=subscribeToObservable.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/subscribeToPromise.js":
/*!************************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/subscribeToPromise.js ***!
\************************************************************************/
/*! exports provided: subscribeToPromise */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToPromise", function() { return subscribeToPromise; });
/* harmony import */ var _hostReportError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hostReportError */ "./node_modules/rxjs/_esm2015/internal/util/hostReportError.js");
const subscribeToPromise = (promise) => (subscriber) => {
promise.then((value) => {
if (!subscriber.closed) {
subscriber.next(value);
subscriber.complete();
}
}, (err) => subscriber.error(err))
.then(null, _hostReportError__WEBPACK_IMPORTED_MODULE_0__["hostReportError"]);
return subscriber;
};
//# sourceMappingURL=subscribeToPromise.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js":
/*!***********************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js ***!
\***********************************************************************/
/*! exports provided: subscribeToResult */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToResult", function() { return subscribeToResult; });
/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../InnerSubscriber */ "./node_modules/rxjs/_esm2015/internal/InnerSubscriber.js");
/* harmony import */ var _subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./subscribeTo */ "./node_modules/rxjs/_esm2015/internal/util/subscribeTo.js");
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/_esm2015/internal/Observable.js");
function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_0__["InnerSubscriber"](outerSubscriber, outerValue, outerIndex)) {
if (innerSubscriber.closed) {
return undefined;
}
if (result instanceof _Observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]) {
return result.subscribe(innerSubscriber);
}
return Object(_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(result)(innerSubscriber);
}
//# sourceMappingURL=subscribeToResult.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/internal/util/toSubscriber.js":
/*!******************************************************************!*\
!*** ./node_modules/rxjs/_esm2015/internal/util/toSubscriber.js ***!
\******************************************************************/
/*! exports provided: toSubscriber */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toSubscriber", function() { return toSubscriber; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/_esm2015/internal/Subscriber.js");
/* harmony import */ var _symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../symbol/rxSubscriber */ "./node_modules/rxjs/_esm2015/internal/symbol/rxSubscriber.js");
/* harmony import */ var _Observer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Observer */ "./node_modules/rxjs/_esm2015/internal/Observer.js");
function toSubscriber(nextOrObserver, error, complete) {
if (nextOrObserver) {
if (nextOrObserver instanceof _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"]) {
return nextOrObserver;
}
if (nextOrObserver[_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_1__["rxSubscriber"]]) {
return nextOrObserver[_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_1__["rxSubscriber"]]();
}
}
if (!nextOrObserver && !error && !complete) {
return new _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"](_Observer__WEBPACK_IMPORTED_MODULE_2__["empty"]);
}
return new _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"](nextOrObserver, error, complete);
}
//# sourceMappingURL=toSubscriber.js.map
/***/ }),
/***/ "./node_modules/rxjs/_esm2015/operators/index.js":
/*!*******************************************************!*\
!*** ./node_modules/rxjs/_esm2015/operators/index.js ***!
\*******************************************************/
/*! exports provided: audit, auditTime, buffer, bufferCount, bufferTime, bufferToggle, bufferWhen, catchError, combineAll, combineLatest, concat, concatAll, concatMap, concatMapTo, count, debounce, debounceTime, defaultIfEmpty, delay, delayWhen, dematerialize, distinct, distinctUntilChanged, distinctUntilKeyChanged, elementAt, endWith, every, exhaust, exhaustMap, expand, filter, finalize, find, findIndex, first, groupBy, ignoreElements, isEmpty, last, map, mapTo, materialize, max, merge, mergeAll, mergeMap, flatMap, mergeMapTo, mergeScan, min, multicast, observeOn, onErrorResumeNext, pairwise, partition, pluck, publish, publishBehavior, publishLast, publishReplay, race, reduce, repeat, repeatWhen, retry, retryWhen, refCount, sample, sampleTime, scan, sequenceEqual, share, shareReplay, single, skip, skipLast, skipUntil, skipWhile, startWith, subscribeOn, switchAll, switchMap, switchMapTo, take, takeLast, takeUntil, takeWhile, tap, throttle, throttleTime, throwIfEmpty, timeInterval, timeout, timeoutWith, timestamp, toArray, window, windowCount, windowTime, windowToggle, windowWhen, withLatestFrom, zip, zipAll */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _internal_operators_audit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../internal/operators/audit */ "./node_modules/rxjs/_esm2015/internal/operators/audit.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "audit", function() { return _internal_operators_audit__WEBPACK_IMPORTED_MODULE_0__["audit"]; });
/* harmony import */ var _internal_operators_auditTime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../internal/operators/auditTime */ "./node_modules/rxjs/_esm2015/internal/operators/auditTime.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "auditTime", function() { return _internal_operators_auditTime__WEBPACK_IMPORTED_MODULE_1__["auditTime"]; });
/* harmony import */ var _internal_operators_buffer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../internal/operators/buffer */ "./node_modules/rxjs/_esm2015/internal/operators/buffer.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return _internal_operators_buffer__WEBPACK_IMPORTED_MODULE_2__["buffer"]; });
/* harmony import */ var _internal_operators_bufferCount__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../internal/operators/bufferCount */ "./node_modules/rxjs/_esm2015/internal/operators/bufferCount.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferCount", function() { return _internal_operators_bufferCount__WEBPACK_IMPORTED_MODULE_3__["bufferCount"]; });
/* harmony import */ var _internal_operators_bufferTime__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../internal/operators/bufferTime */ "./node_modules/rxjs/_esm2015/internal/operators/bufferTime.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferTime", function() { return _internal_operators_bufferTime__WEBPACK_IMPORTED_MODULE_4__["bufferTime"]; });
/* harmony import */ var _internal_operators_bufferToggle__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../internal/operators/bufferToggle */ "./node_modules/rxjs/_esm2015/internal/operators/bufferToggle.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferToggle", function() { return _internal_operators_bufferToggle__WEBPACK_IMPORTED_MODULE_5__["bufferToggle"]; });
/* harmony import */ var _internal_operators_bufferWhen__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../internal/operators/bufferWhen */ "./node_modules/rxjs/_esm2015/internal/operators/bufferWhen.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferWhen", function() { return _internal_operators_bufferWhen__WEBPACK_IMPORTED_MODULE_6__["bufferWhen"]; });
/* harmony import */ var _internal_operators_catchError__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../internal/operators/catchError */ "./node_modules/rxjs/_esm2015/internal/operators/catchError.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "catchError", function() { return _internal_operators_catchError__WEBPACK_IMPORTED_MODULE_7__["catchError"]; });
/* harmony import */ var _internal_operators_combineAll__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../internal/operators/combineAll */ "./node_modules/rxjs/_esm2015/internal/operators/combineAll.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineAll", function() { return _internal_operators_combineAll__WEBPACK_IMPORTED_MODULE_8__["combineAll"]; });
/* harmony import */ var _internal_operators_combineLatest__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../internal/operators/combineLatest */ "./node_modules/rxjs/_esm2015/internal/operators/combineLatest.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return _internal_operators_combineLatest__WEBPACK_IMPORTED_MODULE_9__["combineLatest"]; });
/* harmony import */ var _internal_operators_concat__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../internal/operators/concat */ "./node_modules/rxjs/_esm2015/internal/operators/concat.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return _internal_operators_concat__WEBPACK_IMPORTED_MODULE_10__["concat"]; });
/* harmony import */ var _internal_operators_concatAll__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../internal/operators/concatAll */ "./node_modules/rxjs/_esm2015/internal/operators/concatAll.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concatAll", function() { return _internal_operators_concatAll__WEBPACK_IMPORTED_MODULE_11__["concatAll"]; });
/* harmony import */ var _internal_operators_concatMap__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../internal/operators/concatMap */ "./node_modules/rxjs/_esm2015/internal/operators/concatMap.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concatMap", function() { return _internal_operators_concatMap__WEBPACK_IMPORTED_MODULE_12__["concatMap"]; });
/* harmony import */ var _internal_operators_concatMapTo__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../internal/operators/concatMapTo */ "./node_modules/rxjs/_esm2015/internal/operators/concatMapTo.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concatMapTo", function() { return _internal_operators_concatMapTo__WEBPACK_IMPORTED_MODULE_13__["concatMapTo"]; });
/* harmony import */ var _internal_operators_count__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../internal/operators/count */ "./node_modules/rxjs/_esm2015/internal/operators/count.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "count", function() { return _internal_operators_count__WEBPACK_IMPORTED_MODULE_14__["count"]; });
/* harmony import */ var _internal_operators_debounce__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../internal/operators/debounce */ "./node_modules/rxjs/_esm2015/internal/operators/debounce.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return _internal_operators_debounce__WEBPACK_IMPORTED_MODULE_15__["debounce"]; });
/* harmony import */ var _internal_operators_debounceTime__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../internal/operators/debounceTime */ "./node_modules/rxjs/_esm2015/internal/operators/debounceTime.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "debounceTime", function() { return _internal_operators_debounceTime__WEBPACK_IMPORTED_MODULE_16__["debounceTime"]; });
/* harmony import */ var _internal_operators_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../internal/operators/defaultIfEmpty */ "./node_modules/rxjs/_esm2015/internal/operators/defaultIfEmpty.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultIfEmpty", function() { return _internal_operators_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_17__["defaultIfEmpty"]; });
/* harmony import */ var _internal_operators_delay__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../internal/operators/delay */ "./node_modules/rxjs/_esm2015/internal/operators/delay.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "delay", function() { return _internal_operators_delay__WEBPACK_IMPORTED_MODULE_18__["delay"]; });
/* harmony import */ var _internal_operators_delayWhen__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../internal/operators/delayWhen */ "./node_modules/rxjs/_esm2015/internal/operators/delayWhen.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "delayWhen", function() { return _internal_operators_delayWhen__WEBPACK_IMPORTED_MODULE_19__["delayWhen"]; });
/* harmony import */ var _internal_operators_dematerialize__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../internal/operators/dematerialize */ "./node_modules/rxjs/_esm2015/internal/operators/dematerialize.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dematerialize", function() { return _internal_operators_dematerialize__WEBPACK_IMPORTED_MODULE_20__["dematerialize"]; });
/* harmony import */ var _internal_operators_distinct__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../internal/operators/distinct */ "./node_modules/rxjs/_esm2015/internal/operators/distinct.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "distinct", function() { return _internal_operators_distinct__WEBPACK_IMPORTED_MODULE_21__["distinct"]; });
/* harmony import */ var _internal_operators_distinctUntilChanged__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../internal/operators/distinctUntilChanged */ "./node_modules/rxjs/_esm2015/internal/operators/distinctUntilChanged.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "distinctUntilChanged", function() { return _internal_operators_distinctUntilChanged__WEBPACK_IMPORTED_MODULE_22__["distinctUntilChanged"]; });
/* harmony import */ var _internal_operators_distinctUntilKeyChanged__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../internal/operators/distinctUntilKeyChanged */ "./node_modules/rxjs/_esm2015/internal/operators/distinctUntilKeyChanged.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "distinctUntilKeyChanged", function() { return _internal_operators_distinctUntilKeyChanged__WEBPACK_IMPORTED_MODULE_23__["distinctUntilKeyChanged"]; });
/* harmony import */ var _internal_operators_elementAt__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../internal/operators/elementAt */ "./node_modules/rxjs/_esm2015/internal/operators/elementAt.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "elementAt", function() { return _internal_operators_elementAt__WEBPACK_IMPORTED_MODULE_24__["elementAt"]; });
/* harmony import */ var _internal_operators_endWith__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../internal/operators/endWith */ "./node_modules/rxjs/_esm2015/internal/operators/endWith.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endWith", function() { return _internal_operators_endWith__WEBPACK_IMPORTED_MODULE_25__["endWith"]; });
/* harmony import */ var _internal_operators_every__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../internal/operators/every */ "./node_modules/rxjs/_esm2015/internal/operators/every.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "every", function() { return _internal_operators_every__WEBPACK_IMPORTED_MODULE_26__["every"]; });
/* harmony import */ var _internal_operators_exhaust__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../internal/operators/exhaust */ "./node_modules/rxjs/_esm2015/internal/operators/exhaust.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "exhaust", function() { return _internal_operators_exhaust__WEBPACK_IMPORTED_MODULE_27__["exhaust"]; });
/* harmony import */ var _internal_operators_exhaustMap__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../internal/operators/exhaustMap */ "./node_modules/rxjs/_esm2015/internal/operators/exhaustMap.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "exhaustMap", function() { return _internal_operators_exhaustMap__WEBPACK_IMPORTED_MODULE_28__["exhaustMap"]; });
/* harmony import */ var _internal_operators_expand__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../internal/operators/expand */ "./node_modules/rxjs/_esm2015/internal/operators/expand.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "expand", function() { return _internal_operators_expand__WEBPACK_IMPORTED_MODULE_29__["expand"]; });
/* harmony import */ var _internal_operators_filter__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../internal/operators/filter */ "./node_modules/rxjs/_esm2015/internal/operators/filter.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return _internal_operators_filter__WEBPACK_IMPORTED_MODULE_30__["filter"]; });
/* harmony import */ var _internal_operators_finalize__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../internal/operators/finalize */ "./node_modules/rxjs/_esm2015/internal/operators/finalize.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "finalize", function() { return _internal_operators_finalize__WEBPACK_IMPORTED_MODULE_31__["finalize"]; });
/* harmony import */ var _internal_operators_find__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../internal/operators/find */ "./node_modules/rxjs/_esm2015/internal/operators/find.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "find", function() { return _internal_operators_find__WEBPACK_IMPORTED_MODULE_32__["find"]; });
/* harmony import */ var _internal_operators_findIndex__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ../internal/operators/findIndex */ "./node_modules/rxjs/_esm2015/internal/operators/findIndex.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findIndex", function() { return _internal_operators_findIndex__WEBPACK_IMPORTED_MODULE_33__["findIndex"]; });
/* harmony import */ var _internal_operators_first__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../internal/operators/first */ "./node_modules/rxjs/_esm2015/internal/operators/first.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "first", function() { return _internal_operators_first__WEBPACK_IMPORTED_MODULE_34__["first"]; });
/* harmony import */ var _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ../internal/operators/groupBy */ "./node_modules/rxjs/_esm2015/internal/operators/groupBy.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_35__["groupBy"]; });
/* harmony import */ var _internal_operators_ignoreElements__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ../internal/operators/ignoreElements */ "./node_modules/rxjs/_esm2015/internal/operators/ignoreElements.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ignoreElements", function() { return _internal_operators_ignoreElements__WEBPACK_IMPORTED_MODULE_36__["ignoreElements"]; });
/* harmony import */ var _internal_operators_isEmpty__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ../internal/operators/isEmpty */ "./node_modules/rxjs/_esm2015/internal/operators/isEmpty.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return _internal_operators_isEmpty__WEBPACK_IMPORTED_MODULE_37__["isEmpty"]; });
/* harmony import */ var _internal_operators_last__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ../internal/operators/last */ "./node_modules/rxjs/_esm2015/internal/operators/last.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "last", function() { return _internal_operators_last__WEBPACK_IMPORTED_MODULE_38__["last"]; });
/* harmony import */ var _internal_operators_map__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ../internal/operators/map */ "./node_modules/rxjs/_esm2015/internal/operators/map.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "map", function() { return _internal_operators_map__WEBPACK_IMPORTED_MODULE_39__["map"]; });
/* harmony import */ var _internal_operators_mapTo__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ../internal/operators/mapTo */ "./node_modules/rxjs/_esm2015/internal/operators/mapTo.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mapTo", function() { return _internal_operators_mapTo__WEBPACK_IMPORTED_MODULE_40__["mapTo"]; });
/* harmony import */ var _internal_operators_materialize__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ../internal/operators/materialize */ "./node_modules/rxjs/_esm2015/internal/operators/materialize.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "materialize", function() { return _internal_operators_materialize__WEBPACK_IMPORTED_MODULE_41__["materialize"]; });
/* harmony import */ var _internal_operators_max__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ../internal/operators/max */ "./node_modules/rxjs/_esm2015/internal/operators/max.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "max", function() { return _internal_operators_max__WEBPACK_IMPORTED_MODULE_42__["max"]; });
/* harmony import */ var _internal_operators_merge__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ../internal/operators/merge */ "./node_modules/rxjs/_esm2015/internal/operators/merge.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return _internal_operators_merge__WEBPACK_IMPORTED_MODULE_43__["merge"]; });
/* harmony import */ var _internal_operators_mergeAll__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ../internal/operators/mergeAll */ "./node_modules/rxjs/_esm2015/internal/operators/mergeAll.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeAll", function() { return _internal_operators_mergeAll__WEBPACK_IMPORTED_MODULE_44__["mergeAll"]; });
/* harmony import */ var _internal_operators_mergeMap__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ../internal/operators/mergeMap */ "./node_modules/rxjs/_esm2015/internal/operators/mergeMap.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeMap", function() { return _internal_operators_mergeMap__WEBPACK_IMPORTED_MODULE_45__["mergeMap"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "flatMap", function() { return _internal_operators_mergeMap__WEBPACK_IMPORTED_MODULE_45__["mergeMap"]; });
/* harmony import */ var _internal_operators_mergeMapTo__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ../internal/operators/mergeMapTo */ "./node_modules/rxjs/_esm2015/internal/operators/mergeMapTo.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeMapTo", function() { return _internal_operators_mergeMapTo__WEBPACK_IMPORTED_MODULE_46__["mergeMapTo"]; });
/* harmony import */ var _internal_operators_mergeScan__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ../internal/operators/mergeScan */ "./node_modules/rxjs/_esm2015/internal/operators/mergeScan.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeScan", function() { return _internal_operators_mergeScan__WEBPACK_IMPORTED_MODULE_47__["mergeScan"]; });
/* harmony import */ var _internal_operators_min__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ../internal/operators/min */ "./node_modules/rxjs/_esm2015/internal/operators/min.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "min", function() { return _internal_operators_min__WEBPACK_IMPORTED_MODULE_48__["min"]; });
/* harmony import */ var _internal_operators_multicast__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ../internal/operators/multicast */ "./node_modules/rxjs/_esm2015/internal/operators/multicast.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "multicast", function() { return _internal_operators_multicast__WEBPACK_IMPORTED_MODULE_49__["multicast"]; });
/* harmony import */ var _internal_operators_observeOn__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! ../internal/operators/observeOn */ "./node_modules/rxjs/_esm2015/internal/operators/observeOn.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "observeOn", function() { return _internal_operators_observeOn__WEBPACK_IMPORTED_MODULE_50__["observeOn"]; });
/* harmony import */ var _internal_operators_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ../internal/operators/onErrorResumeNext */ "./node_modules/rxjs/_esm2015/internal/operators/onErrorResumeNext.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return _internal_operators_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_51__["onErrorResumeNext"]; });
/* harmony import */ var _internal_operators_pairwise__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(/*! ../internal/operators/pairwise */ "./node_modules/rxjs/_esm2015/internal/operators/pairwise.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pairwise", function() { return _internal_operators_pairwise__WEBPACK_IMPORTED_MODULE_52__["pairwise"]; });
/* harmony import */ var _internal_operators_partition__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(/*! ../internal/operators/partition */ "./node_modules/rxjs/_esm2015/internal/operators/partition.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return _internal_operators_partition__WEBPACK_IMPORTED_MODULE_53__["partition"]; });
/* harmony import */ var _internal_operators_pluck__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(/*! ../internal/operators/pluck */ "./node_modules/rxjs/_esm2015/internal/operators/pluck.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pluck", function() { return _internal_operators_pluck__WEBPACK_IMPORTED_MODULE_54__["pluck"]; });
/* harmony import */ var _internal_operators_publish__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(/*! ../internal/operators/publish */ "./node_modules/rxjs/_esm2015/internal/operators/publish.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publish", function() { return _internal_operators_publish__WEBPACK_IMPORTED_MODULE_55__["publish"]; });
/* harmony import */ var _internal_operators_publishBehavior__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(/*! ../internal/operators/publishBehavior */ "./node_modules/rxjs/_esm2015/internal/operators/publishBehavior.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publishBehavior", function() { return _internal_operators_publishBehavior__WEBPACK_IMPORTED_MODULE_56__["publishBehavior"]; });
/* harmony import */ var _internal_operators_publishLast__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(/*! ../internal/operators/publishLast */ "./node_modules/rxjs/_esm2015/internal/operators/publishLast.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publishLast", function() { return _internal_operators_publishLast__WEBPACK_IMPORTED_MODULE_57__["publishLast"]; });
/* harmony import */ var _internal_operators_publishReplay__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(/*! ../internal/operators/publishReplay */ "./node_modules/rxjs/_esm2015/internal/operators/publishReplay.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publishReplay", function() { return _internal_operators_publishReplay__WEBPACK_IMPORTED_MODULE_58__["publishReplay"]; });
/* harmony import */ var _internal_operators_race__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(/*! ../internal/operators/race */ "./node_modules/rxjs/_esm2015/internal/operators/race.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "race", function() { return _internal_operators_race__WEBPACK_IMPORTED_MODULE_59__["race"]; });
/* harmony import */ var _internal_operators_reduce__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(/*! ../internal/operators/reduce */ "./node_modules/rxjs/_esm2015/internal/operators/reduce.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return _internal_operators_reduce__WEBPACK_IMPORTED_MODULE_60__["reduce"]; });
/* harmony import */ var _internal_operators_repeat__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(/*! ../internal/operators/repeat */ "./node_modules/rxjs/_esm2015/internal/operators/repeat.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "repeat", function() { return _internal_operators_repeat__WEBPACK_IMPORTED_MODULE_61__["repeat"]; });
/* harmony import */ var _internal_operators_repeatWhen__WEBPACK_IMPORTED_MODULE_62__ = __webpack_require__(/*! ../internal/operators/repeatWhen */ "./node_modules/rxjs/_esm2015/internal/operators/repeatWhen.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "repeatWhen", function() { return _internal_operators_repeatWhen__WEBPACK_IMPORTED_MODULE_62__["repeatWhen"]; });
/* harmony import */ var _internal_operators_retry__WEBPACK_IMPORTED_MODULE_63__ = __webpack_require__(/*! ../internal/operators/retry */ "./node_modules/rxjs/_esm2015/internal/operators/retry.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "retry", function() { return _internal_operators_retry__WEBPACK_IMPORTED_MODULE_63__["retry"]; });
/* harmony import */ var _internal_operators_retryWhen__WEBPACK_IMPORTED_MODULE_64__ = __webpack_require__(/*! ../internal/operators/retryWhen */ "./node_modules/rxjs/_esm2015/internal/operators/retryWhen.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "retryWhen", function() { return _internal_operators_retryWhen__WEBPACK_IMPORTED_MODULE_64__["retryWhen"]; });
/* harmony import */ var _internal_operators_refCount__WEBPACK_IMPORTED_MODULE_65__ = __webpack_require__(/*! ../internal/operators/refCount */ "./node_modules/rxjs/_esm2015/internal/operators/refCount.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "refCount", function() { return _internal_operators_refCount__WEBPACK_IMPORTED_MODULE_65__["refCount"]; });
/* harmony import */ var _internal_operators_sample__WEBPACK_IMPORTED_MODULE_66__ = __webpack_require__(/*! ../internal/operators/sample */ "./node_modules/rxjs/_esm2015/internal/operators/sample.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sample", function() { return _internal_operators_sample__WEBPACK_IMPORTED_MODULE_66__["sample"]; });
/* harmony import */ var _internal_operators_sampleTime__WEBPACK_IMPORTED_MODULE_67__ = __webpack_require__(/*! ../internal/operators/sampleTime */ "./node_modules/rxjs/_esm2015/internal/operators/sampleTime.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sampleTime", function() { return _internal_operators_sampleTime__WEBPACK_IMPORTED_MODULE_67__["sampleTime"]; });
/* harmony import */ var _internal_operators_scan__WEBPACK_IMPORTED_MODULE_68__ = __webpack_require__(/*! ../internal/operators/scan */ "./node_modules/rxjs/_esm2015/internal/operators/scan.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "scan", function() { return _internal_operators_scan__WEBPACK_IMPORTED_MODULE_68__["scan"]; });
/* harmony import */ var _internal_operators_sequenceEqual__WEBPACK_IMPORTED_MODULE_69__ = __webpack_require__(/*! ../internal/operators/sequenceEqual */ "./node_modules/rxjs/_esm2015/internal/operators/sequenceEqual.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sequenceEqual", function() { return _internal_operators_sequenceEqual__WEBPACK_IMPORTED_MODULE_69__["sequenceEqual"]; });
/* harmony import */ var _internal_operators_share__WEBPACK_IMPORTED_MODULE_70__ = __webpack_require__(/*! ../internal/operators/share */ "./node_modules/rxjs/_esm2015/internal/operators/share.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "share", function() { return _internal_operators_share__WEBPACK_IMPORTED_MODULE_70__["share"]; });
/* harmony import */ var _internal_operators_shareReplay__WEBPACK_IMPORTED_MODULE_71__ = __webpack_require__(/*! ../internal/operators/shareReplay */ "./node_modules/rxjs/_esm2015/internal/operators/shareReplay.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "shareReplay", function() { return _internal_operators_shareReplay__WEBPACK_IMPORTED_MODULE_71__["shareReplay"]; });
/* harmony import */ var _internal_operators_single__WEBPACK_IMPORTED_MODULE_72__ = __webpack_require__(/*! ../internal/operators/single */ "./node_modules/rxjs/_esm2015/internal/operators/single.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "single", function() { return _internal_operators_single__WEBPACK_IMPORTED_MODULE_72__["single"]; });
/* harmony import */ var _internal_operators_skip__WEBPACK_IMPORTED_MODULE_73__ = __webpack_require__(/*! ../internal/operators/skip */ "./node_modules/rxjs/_esm2015/internal/operators/skip.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skip", function() { return _internal_operators_skip__WEBPACK_IMPORTED_MODULE_73__["skip"]; });
/* harmony import */ var _internal_operators_skipLast__WEBPACK_IMPORTED_MODULE_74__ = __webpack_require__(/*! ../internal/operators/skipLast */ "./node_modules/rxjs/_esm2015/internal/operators/skipLast.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skipLast", function() { return _internal_operators_skipLast__WEBPACK_IMPORTED_MODULE_74__["skipLast"]; });
/* harmony import */ var _internal_operators_skipUntil__WEBPACK_IMPORTED_MODULE_75__ = __webpack_require__(/*! ../internal/operators/skipUntil */ "./node_modules/rxjs/_esm2015/internal/operators/skipUntil.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skipUntil", function() { return _internal_operators_skipUntil__WEBPACK_IMPORTED_MODULE_75__["skipUntil"]; });
/* harmony import */ var _internal_operators_skipWhile__WEBPACK_IMPORTED_MODULE_76__ = __webpack_require__(/*! ../internal/operators/skipWhile */ "./node_modules/rxjs/_esm2015/internal/operators/skipWhile.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skipWhile", function() { return _internal_operators_skipWhile__WEBPACK_IMPORTED_MODULE_76__["skipWhile"]; });
/* harmony import */ var _internal_operators_startWith__WEBPACK_IMPORTED_MODULE_77__ = __webpack_require__(/*! ../internal/operators/startWith */ "./node_modules/rxjs/_esm2015/internal/operators/startWith.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startWith", function() { return _internal_operators_startWith__WEBPACK_IMPORTED_MODULE_77__["startWith"]; });
/* harmony import */ var _internal_operators_subscribeOn__WEBPACK_IMPORTED_MODULE_78__ = __webpack_require__(/*! ../internal/operators/subscribeOn */ "./node_modules/rxjs/_esm2015/internal/operators/subscribeOn.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subscribeOn", function() { return _internal_operators_subscribeOn__WEBPACK_IMPORTED_MODULE_78__["subscribeOn"]; });
/* harmony import */ var _internal_operators_switchAll__WEBPACK_IMPORTED_MODULE_79__ = __webpack_require__(/*! ../internal/operators/switchAll */ "./node_modules/rxjs/_esm2015/internal/operators/switchAll.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "switchAll", function() { return _internal_operators_switchAll__WEBPACK_IMPORTED_MODULE_79__["switchAll"]; });
/* harmony import */ var _internal_operators_switchMap__WEBPACK_IMPORTED_MODULE_80__ = __webpack_require__(/*! ../internal/operators/switchMap */ "./node_modules/rxjs/_esm2015/internal/operators/switchMap.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "switchMap", function() { return _internal_operators_switchMap__WEBPACK_IMPORTED_MODULE_80__["switchMap"]; });
/* harmony import */ var _internal_operators_switchMapTo__WEBPACK_IMPORTED_MODULE_81__ = __webpack_require__(/*! ../internal/operators/switchMapTo */ "./node_modules/rxjs/_esm2015/internal/operators/switchMapTo.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "switchMapTo", function() { return _internal_operators_switchMapTo__WEBPACK_IMPORTED_MODULE_81__["switchMapTo"]; });
/* harmony import */ var _internal_operators_take__WEBPACK_IMPORTED_MODULE_82__ = __webpack_require__(/*! ../internal/operators/take */ "./node_modules/rxjs/_esm2015/internal/operators/take.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "take", function() { return _internal_operators_take__WEBPACK_IMPORTED_MODULE_82__["take"]; });
/* harmony import */ var _internal_operators_takeLast__WEBPACK_IMPORTED_MODULE_83__ = __webpack_require__(/*! ../internal/operators/takeLast */ "./node_modules/rxjs/_esm2015/internal/operators/takeLast.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "takeLast", function() { return _internal_operators_takeLast__WEBPACK_IMPORTED_MODULE_83__["takeLast"]; });
/* harmony import */ var _internal_operators_takeUntil__WEBPACK_IMPORTED_MODULE_84__ = __webpack_require__(/*! ../internal/operators/takeUntil */ "./node_modules/rxjs/_esm2015/internal/operators/takeUntil.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "takeUntil", function() { return _internal_operators_takeUntil__WEBPACK_IMPORTED_MODULE_84__["takeUntil"]; });
/* harmony import */ var _internal_operators_takeWhile__WEBPACK_IMPORTED_MODULE_85__ = __webpack_require__(/*! ../internal/operators/takeWhile */ "./node_modules/rxjs/_esm2015/internal/operators/takeWhile.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "takeWhile", function() { return _internal_operators_takeWhile__WEBPACK_IMPORTED_MODULE_85__["takeWhile"]; });
/* harmony import */ var _internal_operators_tap__WEBPACK_IMPORTED_MODULE_86__ = __webpack_require__(/*! ../internal/operators/tap */ "./node_modules/rxjs/_esm2015/internal/operators/tap.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "tap", function() { return _internal_operators_tap__WEBPACK_IMPORTED_MODULE_86__["tap"]; });
/* harmony import */ var _internal_operators_throttle__WEBPACK_IMPORTED_MODULE_87__ = __webpack_require__(/*! ../internal/operators/throttle */ "./node_modules/rxjs/_esm2015/internal/operators/throttle.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return _internal_operators_throttle__WEBPACK_IMPORTED_MODULE_87__["throttle"]; });
/* harmony import */ var _internal_operators_throttleTime__WEBPACK_IMPORTED_MODULE_88__ = __webpack_require__(/*! ../internal/operators/throttleTime */ "./node_modules/rxjs/_esm2015/internal/operators/throttleTime.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throttleTime", function() { return _internal_operators_throttleTime__WEBPACK_IMPORTED_MODULE_88__["throttleTime"]; });
/* harmony import */ var _internal_operators_throwIfEmpty__WEBPACK_IMPORTED_MODULE_89__ = __webpack_require__(/*! ../internal/operators/throwIfEmpty */ "./node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throwIfEmpty", function() { return _internal_operators_throwIfEmpty__WEBPACK_IMPORTED_MODULE_89__["throwIfEmpty"]; });
/* harmony import */ var _internal_operators_timeInterval__WEBPACK_IMPORTED_MODULE_90__ = __webpack_require__(/*! ../internal/operators/timeInterval */ "./node_modules/rxjs/_esm2015/internal/operators/timeInterval.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timeInterval", function() { return _internal_operators_timeInterval__WEBPACK_IMPORTED_MODULE_90__["timeInterval"]; });
/* harmony import */ var _internal_operators_timeout__WEBPACK_IMPORTED_MODULE_91__ = __webpack_require__(/*! ../internal/operators/timeout */ "./node_modules/rxjs/_esm2015/internal/operators/timeout.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timeout", function() { return _internal_operators_timeout__WEBPACK_IMPORTED_MODULE_91__["timeout"]; });
/* harmony import */ var _internal_operators_timeoutWith__WEBPACK_IMPORTED_MODULE_92__ = __webpack_require__(/*! ../internal/operators/timeoutWith */ "./node_modules/rxjs/_esm2015/internal/operators/timeoutWith.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timeoutWith", function() { return _internal_operators_timeoutWith__WEBPACK_IMPORTED_MODULE_92__["timeoutWith"]; });
/* harmony import */ var _internal_operators_timestamp__WEBPACK_IMPORTED_MODULE_93__ = __webpack_require__(/*! ../internal/operators/timestamp */ "./node_modules/rxjs/_esm2015/internal/operators/timestamp.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timestamp", function() { return _internal_operators_timestamp__WEBPACK_IMPORTED_MODULE_93__["timestamp"]; });
/* harmony import */ var _internal_operators_toArray__WEBPACK_IMPORTED_MODULE_94__ = __webpack_require__(/*! ../internal/operators/toArray */ "./node_modules/rxjs/_esm2015/internal/operators/toArray.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toArray", function() { return _internal_operators_toArray__WEBPACK_IMPORTED_MODULE_94__["toArray"]; });
/* harmony import */ var _internal_operators_window__WEBPACK_IMPORTED_MODULE_95__ = __webpack_require__(/*! ../internal/operators/window */ "./node_modules/rxjs/_esm2015/internal/operators/window.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "window", function() { return _internal_operators_window__WEBPACK_IMPORTED_MODULE_95__["window"]; });
/* harmony import */ var _internal_operators_windowCount__WEBPACK_IMPORTED_MODULE_96__ = __webpack_require__(/*! ../internal/operators/windowCount */ "./node_modules/rxjs/_esm2015/internal/operators/windowCount.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowCount", function() { return _internal_operators_windowCount__WEBPACK_IMPORTED_MODULE_96__["windowCount"]; });
/* harmony import */ var _internal_operators_windowTime__WEBPACK_IMPORTED_MODULE_97__ = __webpack_require__(/*! ../internal/operators/windowTime */ "./node_modules/rxjs/_esm2015/internal/operators/windowTime.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowTime", function() { return _internal_operators_windowTime__WEBPACK_IMPORTED_MODULE_97__["windowTime"]; });
/* harmony import */ var _internal_operators_windowToggle__WEBPACK_IMPORTED_MODULE_98__ = __webpack_require__(/*! ../internal/operators/windowToggle */ "./node_modules/rxjs/_esm2015/internal/operators/windowToggle.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowToggle", function() { return _internal_operators_windowToggle__WEBPACK_IMPORTED_MODULE_98__["windowToggle"]; });
/* harmony import */ var _internal_operators_windowWhen__WEBPACK_IMPORTED_MODULE_99__ = __webpack_require__(/*! ../internal/operators/windowWhen */ "./node_modules/rxjs/_esm2015/internal/operators/windowWhen.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowWhen", function() { return _internal_operators_windowWhen__WEBPACK_IMPORTED_MODULE_99__["windowWhen"]; });
/* harmony import */ var _internal_operators_withLatestFrom__WEBPACK_IMPORTED_MODULE_100__ = __webpack_require__(/*! ../internal/operators/withLatestFrom */ "./node_modules/rxjs/_esm2015/internal/operators/withLatestFrom.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "withLatestFrom", function() { return _internal_operators_withLatestFrom__WEBPACK_IMPORTED_MODULE_100__["withLatestFrom"]; });
/* harmony import */ var _internal_operators_zip__WEBPACK_IMPORTED_MODULE_101__ = __webpack_require__(/*! ../internal/operators/zip */ "./node_modules/rxjs/_esm2015/internal/operators/zip.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return _internal_operators_zip__WEBPACK_IMPORTED_MODULE_101__["zip"]; });
/* harmony import */ var _internal_operators_zipAll__WEBPACK_IMPORTED_MODULE_102__ = __webpack_require__(/*! ../internal/operators/zipAll */ "./node_modules/rxjs/_esm2015/internal/operators/zipAll.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zipAll", function() { return _internal_operators_zipAll__WEBPACK_IMPORTED_MODULE_102__["zipAll"]; });
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/three/build/three.module.js":
/*!**************************************************!*\
!*** ./node_modules/three/build/three.module.js ***!
\**************************************************/
/*! exports provided: ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, ClosedSplineCurve3, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, CubeGeometry, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DirectionalLightShadow, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, Face3, Face4, FaceColors, FileLoader, FlatShading, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FrontFaceDirectionCCW, FrontFaceDirectionCW, FrontSide, Frustum, GammaEncoding, Geometry, GeometryUtils, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightShadow, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LogLuvEncoding, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, Math, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColors, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, ParametricBufferGeometry, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDEncoding, RGBEEncoding, RGBEFormat, RGBFormat, RGBIntegerFormat, RGBM16Encoding, RGBM7Encoding, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, SRGB8_ALPHA8_ASTC_10x10_Format, SRGB8_ALPHA8_ASTC_10x5_Format, SRGB8_ALPHA8_ASTC_10x6_Format, SRGB8_ALPHA8_ASTC_10x8_Format, SRGB8_ALPHA8_ASTC_12x10_Format, SRGB8_ALPHA8_ASTC_12x12_Format, SRGB8_ALPHA8_ASTC_4x4_Format, SRGB8_ALPHA8_ASTC_5x4_Format, SRGB8_ALPHA8_ASTC_5x5_Format, SRGB8_ALPHA8_ASTC_6x5_Format, SRGB8_ALPHA8_ASTC_6x6_Format, SRGB8_ALPHA8_ASTC_8x5_Format, SRGB8_ALPHA8_ASTC_8x6_Format, SRGB8_ALPHA8_ASTC_8x8_Format, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SphericalReflectionMapping, Spline, SplineCurve, SplineCurve3, SpotLight, SpotLightHelper, SpotLightShadow, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, TextBufferGeometry, TextGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uncharted2ToneMapping, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGLCubeRenderTarget, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ACESFilmicToneMapping", function() { return ACESFilmicToneMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddEquation", function() { return AddEquation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddOperation", function() { return AddOperation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdditiveAnimationBlendMode", function() { return AdditiveAnimationBlendMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdditiveBlending", function() { return AdditiveBlending; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlphaFormat", function() { return AlphaFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlwaysDepth", function() { return AlwaysDepth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlwaysStencilFunc", function() { return AlwaysStencilFunc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AmbientLight", function() { return AmbientLight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AmbientLightProbe", function() { return AmbientLightProbe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationClip", function() { return AnimationClip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationLoader", function() { return AnimationLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationMixer", function() { return AnimationMixer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationObjectGroup", function() { return AnimationObjectGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationUtils", function() { return AnimationUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcCurve", function() { return ArcCurve; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrayCamera", function() { return ArrayCamera; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrowHelper", function() { return ArrowHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Audio", function() { return Audio; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AudioAnalyser", function() { return AudioAnalyser; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AudioContext", function() { return AudioContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AudioListener", function() { return AudioListener; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AudioLoader", function() { return AudioLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxesHelper", function() { return AxesHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxisHelper", function() { return AxisHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BackSide", function() { return BackSide; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BasicDepthPacking", function() { return BasicDepthPacking; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BasicShadowMap", function() { return BasicShadowMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BinaryTextureLoader", function() { return BinaryTextureLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bone", function() { return Bone; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BooleanKeyframeTrack", function() { return BooleanKeyframeTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxHelper", function() { return BoundingBoxHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Box2", function() { return Box2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Box3", function() { return Box3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Box3Helper", function() { return Box3Helper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoxBufferGeometry", function() { return BoxBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoxGeometry", function() { return BoxGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoxHelper", function() { return BoxHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferAttribute", function() { return BufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferGeometry", function() { return BufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferGeometryLoader", function() { return BufferGeometryLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ByteType", function() { return ByteType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Cache", function() { return Cache; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return Camera; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CameraHelper", function() { return CameraHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CanvasRenderer", function() { return CanvasRenderer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CanvasTexture", function() { return CanvasTexture; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CatmullRomCurve3", function() { return CatmullRomCurve3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CineonToneMapping", function() { return CineonToneMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CircleBufferGeometry", function() { return CircleBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CircleGeometry", function() { return CircleGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClampToEdgeWrapping", function() { return ClampToEdgeWrapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Clock", function() { return Clock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClosedSplineCurve3", function() { return ClosedSplineCurve3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorKeyframeTrack", function() { return ColorKeyframeTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompressedTexture", function() { return CompressedTexture; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompressedTextureLoader", function() { return CompressedTextureLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConeBufferGeometry", function() { return ConeBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConeGeometry", function() { return ConeGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeCamera", function() { return CubeCamera; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeGeometry", function() { return BoxGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeReflectionMapping", function() { return CubeReflectionMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeRefractionMapping", function() { return CubeRefractionMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeTexture", function() { return CubeTexture; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeTextureLoader", function() { return CubeTextureLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeUVReflectionMapping", function() { return CubeUVReflectionMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeUVRefractionMapping", function() { return CubeUVRefractionMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubicBezierCurve", function() { return CubicBezierCurve; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubicBezierCurve3", function() { return CubicBezierCurve3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubicInterpolant", function() { return CubicInterpolant; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CullFaceBack", function() { return CullFaceBack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CullFaceFront", function() { return CullFaceFront; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CullFaceFrontBack", function() { return CullFaceFrontBack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CullFaceNone", function() { return CullFaceNone; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Curve", function() { return Curve; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CurvePath", function() { return CurvePath; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CustomBlending", function() { return CustomBlending; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CylinderBufferGeometry", function() { return CylinderBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CylinderGeometry", function() { return CylinderGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Cylindrical", function() { return Cylindrical; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataTexture", function() { return DataTexture; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataTexture2DArray", function() { return DataTexture2DArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataTexture3D", function() { return DataTexture3D; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataTextureLoader", function() { return DataTextureLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DecrementStencilOp", function() { return DecrementStencilOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DecrementWrapStencilOp", function() { return DecrementWrapStencilOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultLoadingManager", function() { return DefaultLoadingManager; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DepthFormat", function() { return DepthFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DepthStencilFormat", function() { return DepthStencilFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DepthTexture", function() { return DepthTexture; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DirectionalLight", function() { return DirectionalLight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DirectionalLightHelper", function() { return DirectionalLightHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DirectionalLightShadow", function() { return DirectionalLightShadow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiscreteInterpolant", function() { return DiscreteInterpolant; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DodecahedronBufferGeometry", function() { return DodecahedronBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DodecahedronGeometry", function() { return DodecahedronGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DoubleSide", function() { return DoubleSide; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DstAlphaFactor", function() { return DstAlphaFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DstColorFactor", function() { return DstColorFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DynamicBufferAttribute", function() { return DynamicBufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DynamicCopyUsage", function() { return DynamicCopyUsage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DynamicDrawUsage", function() { return DynamicDrawUsage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DynamicReadUsage", function() { return DynamicReadUsage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EdgesGeometry", function() { return EdgesGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EdgesHelper", function() { return EdgesHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EllipseCurve", function() { return EllipseCurve; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EqualDepth", function() { return EqualDepth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EqualStencilFunc", function() { return EqualStencilFunc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EquirectangularReflectionMapping", function() { return EquirectangularReflectionMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EquirectangularRefractionMapping", function() { return EquirectangularRefractionMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Euler", function() { return Euler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EventDispatcher", function() { return EventDispatcher; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExtrudeBufferGeometry", function() { return ExtrudeBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExtrudeGeometry", function() { return ExtrudeGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Face3", function() { return Face3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Face4", function() { return Face4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FaceColors", function() { return FaceColors; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FileLoader", function() { return FileLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlatShading", function() { return FlatShading; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Float32Attribute", function() { return Float32Attribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Float32BufferAttribute", function() { return Float32BufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Float64Attribute", function() { return Float64Attribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Float64BufferAttribute", function() { return Float64BufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FloatType", function() { return FloatType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Fog", function() { return Fog; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FogExp2", function() { return FogExp2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Font", function() { return Font; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FontLoader", function() { return FontLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FrontFaceDirectionCCW", function() { return FrontFaceDirectionCCW; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FrontFaceDirectionCW", function() { return FrontFaceDirectionCW; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FrontSide", function() { return FrontSide; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Frustum", function() { return Frustum; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GammaEncoding", function() { return GammaEncoding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Geometry", function() { return Geometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GeometryUtils", function() { return GeometryUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GreaterDepth", function() { return GreaterDepth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GreaterEqualDepth", function() { return GreaterEqualDepth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GreaterEqualStencilFunc", function() { return GreaterEqualStencilFunc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GreaterStencilFunc", function() { return GreaterStencilFunc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GridHelper", function() { return GridHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Group", function() { return Group; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HalfFloatType", function() { return HalfFloatType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HemisphereLight", function() { return HemisphereLight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HemisphereLightHelper", function() { return HemisphereLightHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HemisphereLightProbe", function() { return HemisphereLightProbe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IcosahedronBufferGeometry", function() { return IcosahedronBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IcosahedronGeometry", function() { return IcosahedronGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImageBitmapLoader", function() { return ImageBitmapLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImageLoader", function() { return ImageLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImageUtils", function() { return ImageUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImmediateRenderObject", function() { return ImmediateRenderObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncrementStencilOp", function() { return IncrementStencilOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncrementWrapStencilOp", function() { return IncrementWrapStencilOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InstancedBufferAttribute", function() { return InstancedBufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InstancedBufferGeometry", function() { return InstancedBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InstancedInterleavedBuffer", function() { return InstancedInterleavedBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InstancedMesh", function() { return InstancedMesh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Int16Attribute", function() { return Int16Attribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Int16BufferAttribute", function() { return Int16BufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Int32Attribute", function() { return Int32Attribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Int32BufferAttribute", function() { return Int32BufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Int8Attribute", function() { return Int8Attribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Int8BufferAttribute", function() { return Int8BufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IntType", function() { return IntType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InterleavedBuffer", function() { return InterleavedBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InterleavedBufferAttribute", function() { return InterleavedBufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Interpolant", function() { return Interpolant; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InterpolateDiscrete", function() { return InterpolateDiscrete; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InterpolateLinear", function() { return InterpolateLinear; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InterpolateSmooth", function() { return InterpolateSmooth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InvertStencilOp", function() { return InvertStencilOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONLoader", function() { return JSONLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeepStencilOp", function() { return KeepStencilOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyframeTrack", function() { return KeyframeTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LOD", function() { return LOD; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LatheBufferGeometry", function() { return LatheBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LatheGeometry", function() { return LatheGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Layers", function() { return Layers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LensFlare", function() { return LensFlare; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LessDepth", function() { return LessDepth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LessEqualDepth", function() { return LessEqualDepth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LessEqualStencilFunc", function() { return LessEqualStencilFunc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LessStencilFunc", function() { return LessStencilFunc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Light", function() { return Light; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LightProbe", function() { return LightProbe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LightShadow", function() { return LightShadow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Line", function() { return Line; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Line3", function() { return Line3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LineBasicMaterial", function() { return LineBasicMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LineCurve", function() { return LineCurve; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LineCurve3", function() { return LineCurve3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LineDashedMaterial", function() { return LineDashedMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LineLoop", function() { return LineLoop; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinePieces", function() { return LinePieces; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LineSegments", function() { return LineSegments; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LineStrip", function() { return LineStrip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinearEncoding", function() { return LinearEncoding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinearFilter", function() { return LinearFilter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinearInterpolant", function() { return LinearInterpolant; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinearMipMapLinearFilter", function() { return LinearMipMapLinearFilter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinearMipMapNearestFilter", function() { return LinearMipMapNearestFilter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinearMipmapLinearFilter", function() { return LinearMipmapLinearFilter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinearMipmapNearestFilter", function() { return LinearMipmapNearestFilter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinearToneMapping", function() { return LinearToneMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Loader", function() { return Loader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoaderUtils", function() { return LoaderUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadingManager", function() { return LoadingManager; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogLuvEncoding", function() { return LogLuvEncoding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoopOnce", function() { return LoopOnce; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoopPingPong", function() { return LoopPingPong; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoopRepeat", function() { return LoopRepeat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LuminanceAlphaFormat", function() { return LuminanceAlphaFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LuminanceFormat", function() { return LuminanceFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MOUSE", function() { return MOUSE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Material", function() { return Material; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MaterialLoader", function() { return MaterialLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Math", function() { return MathUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MathUtils", function() { return MathUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Matrix3", function() { return Matrix3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Matrix4", function() { return Matrix4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MaxEquation", function() { return MaxEquation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Mesh", function() { return Mesh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshBasicMaterial", function() { return MeshBasicMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshDepthMaterial", function() { return MeshDepthMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshDistanceMaterial", function() { return MeshDistanceMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshFaceMaterial", function() { return MeshFaceMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshLambertMaterial", function() { return MeshLambertMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshMatcapMaterial", function() { return MeshMatcapMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshNormalMaterial", function() { return MeshNormalMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshPhongMaterial", function() { return MeshPhongMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshPhysicalMaterial", function() { return MeshPhysicalMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshStandardMaterial", function() { return MeshStandardMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshToonMaterial", function() { return MeshToonMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MinEquation", function() { return MinEquation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MirroredRepeatWrapping", function() { return MirroredRepeatWrapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MixOperation", function() { return MixOperation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiMaterial", function() { return MultiMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiplyBlending", function() { return MultiplyBlending; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiplyOperation", function() { return MultiplyOperation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NearestFilter", function() { return NearestFilter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NearestMipMapLinearFilter", function() { return NearestMipMapLinearFilter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NearestMipMapNearestFilter", function() { return NearestMipMapNearestFilter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NearestMipmapLinearFilter", function() { return NearestMipmapLinearFilter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NearestMipmapNearestFilter", function() { return NearestMipmapNearestFilter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NeverDepth", function() { return NeverDepth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NeverStencilFunc", function() { return NeverStencilFunc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NoBlending", function() { return NoBlending; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NoColors", function() { return NoColors; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NoToneMapping", function() { return NoToneMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NormalAnimationBlendMode", function() { return NormalAnimationBlendMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NormalBlending", function() { return NormalBlending; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotEqualDepth", function() { return NotEqualDepth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotEqualStencilFunc", function() { return NotEqualStencilFunc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NumberKeyframeTrack", function() { return NumberKeyframeTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Object3D", function() { return Object3D; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObjectLoader", function() { return ObjectLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObjectSpaceNormalMap", function() { return ObjectSpaceNormalMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OctahedronBufferGeometry", function() { return OctahedronBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OctahedronGeometry", function() { return OctahedronGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OneFactor", function() { return OneFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OneMinusDstAlphaFactor", function() { return OneMinusDstAlphaFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OneMinusDstColorFactor", function() { return OneMinusDstColorFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OneMinusSrcAlphaFactor", function() { return OneMinusSrcAlphaFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OneMinusSrcColorFactor", function() { return OneMinusSrcColorFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrthographicCamera", function() { return OrthographicCamera; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PCFShadowMap", function() { return PCFShadowMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PCFSoftShadowMap", function() { return PCFSoftShadowMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PMREMGenerator", function() { return PMREMGenerator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParametricBufferGeometry", function() { return ParametricBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParametricGeometry", function() { return ParametricGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Particle", function() { return Particle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParticleBasicMaterial", function() { return ParticleBasicMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParticleSystem", function() { return ParticleSystem; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParticleSystemMaterial", function() { return ParticleSystemMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Path", function() { return Path; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PerspectiveCamera", function() { return PerspectiveCamera; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Plane", function() { return Plane; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaneBufferGeometry", function() { return PlaneBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaneGeometry", function() { return PlaneGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaneHelper", function() { return PlaneHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointCloud", function() { return PointCloud; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointCloudMaterial", function() { return PointCloudMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointLight", function() { return PointLight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointLightHelper", function() { return PointLightHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Points", function() { return Points; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointsMaterial", function() { return PointsMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PolarGridHelper", function() { return PolarGridHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PolyhedronBufferGeometry", function() { return PolyhedronBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PolyhedronGeometry", function() { return PolyhedronGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PositionalAudio", function() { return PositionalAudio; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PropertyBinding", function() { return PropertyBinding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PropertyMixer", function() { return PropertyMixer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuadraticBezierCurve", function() { return QuadraticBezierCurve; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuadraticBezierCurve3", function() { return QuadraticBezierCurve3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Quaternion", function() { return Quaternion; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuaternionKeyframeTrack", function() { return QuaternionKeyframeTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuaternionLinearInterpolant", function() { return QuaternionLinearInterpolant; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "REVISION", function() { return REVISION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBADepthPacking", function() { return RGBADepthPacking; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBAFormat", function() { return RGBAFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBAIntegerFormat", function() { return RGBAIntegerFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_10x10_Format", function() { return RGBA_ASTC_10x10_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_10x5_Format", function() { return RGBA_ASTC_10x5_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_10x6_Format", function() { return RGBA_ASTC_10x6_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_10x8_Format", function() { return RGBA_ASTC_10x8_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_12x10_Format", function() { return RGBA_ASTC_12x10_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_12x12_Format", function() { return RGBA_ASTC_12x12_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_4x4_Format", function() { return RGBA_ASTC_4x4_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_5x4_Format", function() { return RGBA_ASTC_5x4_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_5x5_Format", function() { return RGBA_ASTC_5x5_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_6x5_Format", function() { return RGBA_ASTC_6x5_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_6x6_Format", function() { return RGBA_ASTC_6x6_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_8x5_Format", function() { return RGBA_ASTC_8x5_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_8x6_Format", function() { return RGBA_ASTC_8x6_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ASTC_8x8_Format", function() { return RGBA_ASTC_8x8_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_BPTC_Format", function() { return RGBA_BPTC_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_ETC2_EAC_Format", function() { return RGBA_ETC2_EAC_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_PVRTC_2BPPV1_Format", function() { return RGBA_PVRTC_2BPPV1_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_PVRTC_4BPPV1_Format", function() { return RGBA_PVRTC_4BPPV1_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_S3TC_DXT1_Format", function() { return RGBA_S3TC_DXT1_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_S3TC_DXT3_Format", function() { return RGBA_S3TC_DXT3_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBA_S3TC_DXT5_Format", function() { return RGBA_S3TC_DXT5_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBDEncoding", function() { return RGBDEncoding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBEEncoding", function() { return RGBEEncoding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBEFormat", function() { return RGBEFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBFormat", function() { return RGBFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBIntegerFormat", function() { return RGBIntegerFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBM16Encoding", function() { return RGBM16Encoding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBM7Encoding", function() { return RGBM7Encoding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGB_ETC1_Format", function() { return RGB_ETC1_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGB_ETC2_Format", function() { return RGB_ETC2_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGB_PVRTC_2BPPV1_Format", function() { return RGB_PVRTC_2BPPV1_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGB_PVRTC_4BPPV1_Format", function() { return RGB_PVRTC_4BPPV1_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGB_S3TC_DXT1_Format", function() { return RGB_S3TC_DXT1_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGFormat", function() { return RGFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGIntegerFormat", function() { return RGIntegerFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RawShaderMaterial", function() { return RawShaderMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return Ray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Raycaster", function() { return Raycaster; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RectAreaLight", function() { return RectAreaLight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RedFormat", function() { return RedFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RedIntegerFormat", function() { return RedIntegerFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReinhardToneMapping", function() { return ReinhardToneMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepeatWrapping", function() { return RepeatWrapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReplaceStencilOp", function() { return ReplaceStencilOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReverseSubtractEquation", function() { return ReverseSubtractEquation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RingBufferGeometry", function() { return RingBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RingGeometry", function() { return RingGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_10x10_Format", function() { return SRGB8_ALPHA8_ASTC_10x10_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_10x5_Format", function() { return SRGB8_ALPHA8_ASTC_10x5_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_10x6_Format", function() { return SRGB8_ALPHA8_ASTC_10x6_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_10x8_Format", function() { return SRGB8_ALPHA8_ASTC_10x8_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_12x10_Format", function() { return SRGB8_ALPHA8_ASTC_12x10_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_12x12_Format", function() { return SRGB8_ALPHA8_ASTC_12x12_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_4x4_Format", function() { return SRGB8_ALPHA8_ASTC_4x4_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_5x4_Format", function() { return SRGB8_ALPHA8_ASTC_5x4_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_5x5_Format", function() { return SRGB8_ALPHA8_ASTC_5x5_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_6x5_Format", function() { return SRGB8_ALPHA8_ASTC_6x5_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_6x6_Format", function() { return SRGB8_ALPHA8_ASTC_6x6_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_8x5_Format", function() { return SRGB8_ALPHA8_ASTC_8x5_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_8x6_Format", function() { return SRGB8_ALPHA8_ASTC_8x6_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SRGB8_ALPHA8_ASTC_8x8_Format", function() { return SRGB8_ALPHA8_ASTC_8x8_Format; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Scene", function() { return Scene; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneUtils", function() { return SceneUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderChunk", function() { return ShaderChunk; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderLib", function() { return ShaderLib; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderMaterial", function() { return ShaderMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShadowMaterial", function() { return ShadowMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Shape", function() { return Shape; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShapeBufferGeometry", function() { return ShapeBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShapeGeometry", function() { return ShapeGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShapePath", function() { return ShapePath; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShapeUtils", function() { return ShapeUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShortType", function() { return ShortType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Skeleton", function() { return Skeleton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SkeletonHelper", function() { return SkeletonHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SkinnedMesh", function() { return SkinnedMesh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SmoothShading", function() { return SmoothShading; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Sphere", function() { return Sphere; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SphereBufferGeometry", function() { return SphereBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SphereGeometry", function() { return SphereGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Spherical", function() { return Spherical; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SphericalHarmonics3", function() { return SphericalHarmonics3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SphericalReflectionMapping", function() { return SphericalReflectionMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Spline", function() { return Spline; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SplineCurve", function() { return SplineCurve; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SplineCurve3", function() { return SplineCurve3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpotLight", function() { return SpotLight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpotLightHelper", function() { return SpotLightHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpotLightShadow", function() { return SpotLightShadow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Sprite", function() { return Sprite; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpriteMaterial", function() { return SpriteMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SrcAlphaFactor", function() { return SrcAlphaFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SrcAlphaSaturateFactor", function() { return SrcAlphaSaturateFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SrcColorFactor", function() { return SrcColorFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StaticCopyUsage", function() { return StaticCopyUsage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StaticDrawUsage", function() { return StaticDrawUsage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StaticReadUsage", function() { return StaticReadUsage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoCamera", function() { return StereoCamera; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StreamCopyUsage", function() { return StreamCopyUsage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StreamDrawUsage", function() { return StreamDrawUsage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StreamReadUsage", function() { return StreamReadUsage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringKeyframeTrack", function() { return StringKeyframeTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubtractEquation", function() { return SubtractEquation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubtractiveBlending", function() { return SubtractiveBlending; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TOUCH", function() { return TOUCH; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TangentSpaceNormalMap", function() { return TangentSpaceNormalMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TetrahedronBufferGeometry", function() { return TetrahedronBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TetrahedronGeometry", function() { return TetrahedronGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextBufferGeometry", function() { return TextBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextGeometry", function() { return TextGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return Texture; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextureLoader", function() { return TextureLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TorusBufferGeometry", function() { return TorusBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TorusGeometry", function() { return TorusGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TorusKnotBufferGeometry", function() { return TorusKnotBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TorusKnotGeometry", function() { return TorusKnotGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Triangle", function() { return Triangle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TriangleFanDrawMode", function() { return TriangleFanDrawMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TriangleStripDrawMode", function() { return TriangleStripDrawMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TrianglesDrawMode", function() { return TrianglesDrawMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TubeBufferGeometry", function() { return TubeBufferGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TubeGeometry", function() { return TubeGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UVMapping", function() { return UVMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Uint16Attribute", function() { return Uint16Attribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Uint16BufferAttribute", function() { return Uint16BufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Uint32Attribute", function() { return Uint32Attribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Uint32BufferAttribute", function() { return Uint32BufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Uint8Attribute", function() { return Uint8Attribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Uint8BufferAttribute", function() { return Uint8BufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Uint8ClampedAttribute", function() { return Uint8ClampedAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Uint8ClampedBufferAttribute", function() { return Uint8ClampedBufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Uncharted2ToneMapping", function() { return Uncharted2ToneMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Uniform", function() { return Uniform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UniformsLib", function() { return UniformsLib; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UniformsUtils", function() { return UniformsUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsignedByteType", function() { return UnsignedByteType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsignedInt248Type", function() { return UnsignedInt248Type; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsignedIntType", function() { return UnsignedIntType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsignedShort4444Type", function() { return UnsignedShort4444Type; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsignedShort5551Type", function() { return UnsignedShort5551Type; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsignedShort565Type", function() { return UnsignedShort565Type; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsignedShortType", function() { return UnsignedShortType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VSMShadowMap", function() { return VSMShadowMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Vector2", function() { return Vector2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Vector3", function() { return Vector3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Vector4", function() { return Vector4; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VectorKeyframeTrack", function() { return VectorKeyframeTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Vertex", function() { return Vertex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VertexColors", function() { return VertexColors; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VideoTexture", function() { return VideoTexture; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGLCubeRenderTarget", function() { return WebGLCubeRenderTarget; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGLMultisampleRenderTarget", function() { return WebGLMultisampleRenderTarget; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGLRenderTarget", function() { return WebGLRenderTarget; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGLRenderTargetCube", function() { return WebGLRenderTargetCube; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGLRenderer", function() { return WebGLRenderer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGLUtils", function() { return WebGLUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WireframeGeometry", function() { return WireframeGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WireframeHelper", function() { return WireframeHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WrapAroundEnding", function() { return WrapAroundEnding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "XHRLoader", function() { return XHRLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZeroCurvatureEnding", function() { return ZeroCurvatureEnding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZeroFactor", function() { return ZeroFactor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZeroSlopeEnding", function() { return ZeroSlopeEnding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZeroStencilOp", function() { return ZeroStencilOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sRGBEncoding", function() { return sRGBEncoding; });
// Polyfills
if ( Number.EPSILON === undefined ) {
Number.EPSILON = Math.pow( 2, - 52 );
}
if ( Number.isInteger === undefined ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Number.isInteger = function ( value ) {
return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
};
}
//
if ( Math.sign === undefined ) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
Math.sign = function ( x ) {
return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
};
}
if ( 'name' in Function.prototype === false ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
Object.defineProperty( Function.prototype, 'name', {
get: function () {
return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
}
} );
}
if ( Object.assign === undefined ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Object.assign = function ( target ) {
if ( target === undefined || target === null ) {
throw new TypeError( 'Cannot convert undefined or null to object' );
}
var output = Object( target );
for ( var index = 1; index < arguments.length; index ++ ) {
var source = arguments[ index ];
if ( source !== undefined && source !== null ) {
for ( var nextKey in source ) {
if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
output[ nextKey ] = source[ nextKey ];
}
}
}
}
return output;
};
}
var REVISION = '116';
var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
var TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
var CullFaceNone = 0;
var CullFaceBack = 1;
var CullFaceFront = 2;
var CullFaceFrontBack = 3;
var FrontFaceDirectionCW = 0;
var FrontFaceDirectionCCW = 1;
var BasicShadowMap = 0;
var PCFShadowMap = 1;
var PCFSoftShadowMap = 2;
var VSMShadowMap = 3;
var FrontSide = 0;
var BackSide = 1;
var DoubleSide = 2;
var FlatShading = 1;
var SmoothShading = 2;
var NoBlending = 0;
var NormalBlending = 1;
var AdditiveBlending = 2;
var SubtractiveBlending = 3;
var MultiplyBlending = 4;
var CustomBlending = 5;
var AddEquation = 100;
var SubtractEquation = 101;
var ReverseSubtractEquation = 102;
var MinEquation = 103;
var MaxEquation = 104;
var ZeroFactor = 200;
var OneFactor = 201;
var SrcColorFactor = 202;
var OneMinusSrcColorFactor = 203;
var SrcAlphaFactor = 204;
var OneMinusSrcAlphaFactor = 205;
var DstAlphaFactor = 206;
var OneMinusDstAlphaFactor = 207;
var DstColorFactor = 208;
var OneMinusDstColorFactor = 209;
var SrcAlphaSaturateFactor = 210;
var NeverDepth = 0;
var AlwaysDepth = 1;
var LessDepth = 2;
var LessEqualDepth = 3;
var EqualDepth = 4;
var GreaterEqualDepth = 5;
var GreaterDepth = 6;
var NotEqualDepth = 7;
var MultiplyOperation = 0;
var MixOperation = 1;
var AddOperation = 2;
var NoToneMapping = 0;
var LinearToneMapping = 1;
var ReinhardToneMapping = 2;
var Uncharted2ToneMapping = 3;
var CineonToneMapping = 4;
var ACESFilmicToneMapping = 5;
var UVMapping = 300;
var CubeReflectionMapping = 301;
var CubeRefractionMapping = 302;
var EquirectangularReflectionMapping = 303;
var EquirectangularRefractionMapping = 304;
var SphericalReflectionMapping = 305;
var CubeUVReflectionMapping = 306;
var CubeUVRefractionMapping = 307;
var RepeatWrapping = 1000;
var ClampToEdgeWrapping = 1001;
var MirroredRepeatWrapping = 1002;
var NearestFilter = 1003;
var NearestMipmapNearestFilter = 1004;
var NearestMipMapNearestFilter = 1004;
var NearestMipmapLinearFilter = 1005;
var NearestMipMapLinearFilter = 1005;
var LinearFilter = 1006;
var LinearMipmapNearestFilter = 1007;
var LinearMipMapNearestFilter = 1007;
var LinearMipmapLinearFilter = 1008;
var LinearMipMapLinearFilter = 1008;
var UnsignedByteType = 1009;
var ByteType = 1010;
var ShortType = 1011;
var UnsignedShortType = 1012;
var IntType = 1013;
var UnsignedIntType = 1014;
var FloatType = 1015;
var HalfFloatType = 1016;
var UnsignedShort4444Type = 1017;
var UnsignedShort5551Type = 1018;
var UnsignedShort565Type = 1019;
var UnsignedInt248Type = 1020;
var AlphaFormat = 1021;
var RGBFormat = 1022;
var RGBAFormat = 1023;
var LuminanceFormat = 1024;
var LuminanceAlphaFormat = 1025;
var RGBEFormat = RGBAFormat;
var DepthFormat = 1026;
var DepthStencilFormat = 1027;
var RedFormat = 1028;
var RedIntegerFormat = 1029;
var RGFormat = 1030;
var RGIntegerFormat = 1031;
var RGBIntegerFormat = 1032;
var RGBAIntegerFormat = 1033;
var RGB_S3TC_DXT1_Format = 33776;
var RGBA_S3TC_DXT1_Format = 33777;
var RGBA_S3TC_DXT3_Format = 33778;
var RGBA_S3TC_DXT5_Format = 33779;
var RGB_PVRTC_4BPPV1_Format = 35840;
var RGB_PVRTC_2BPPV1_Format = 35841;
var RGBA_PVRTC_4BPPV1_Format = 35842;
var RGBA_PVRTC_2BPPV1_Format = 35843;
var RGB_ETC1_Format = 36196;
var RGB_ETC2_Format = 37492;
var RGBA_ETC2_EAC_Format = 37496;
var RGBA_ASTC_4x4_Format = 37808;
var RGBA_ASTC_5x4_Format = 37809;
var RGBA_ASTC_5x5_Format = 37810;
var RGBA_ASTC_6x5_Format = 37811;
var RGBA_ASTC_6x6_Format = 37812;
var RGBA_ASTC_8x5_Format = 37813;
var RGBA_ASTC_8x6_Format = 37814;
var RGBA_ASTC_8x8_Format = 37815;
var RGBA_ASTC_10x5_Format = 37816;
var RGBA_ASTC_10x6_Format = 37817;
var RGBA_ASTC_10x8_Format = 37818;
var RGBA_ASTC_10x10_Format = 37819;
var RGBA_ASTC_12x10_Format = 37820;
var RGBA_ASTC_12x12_Format = 37821;
var RGBA_BPTC_Format = 36492;
var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
var LoopOnce = 2200;
var LoopRepeat = 2201;
var LoopPingPong = 2202;
var InterpolateDiscrete = 2300;
var InterpolateLinear = 2301;
var InterpolateSmooth = 2302;
var ZeroCurvatureEnding = 2400;
var ZeroSlopeEnding = 2401;
var WrapAroundEnding = 2402;
var NormalAnimationBlendMode = 2500;
var AdditiveAnimationBlendMode = 2501;
var TrianglesDrawMode = 0;
var TriangleStripDrawMode = 1;
var TriangleFanDrawMode = 2;
var LinearEncoding = 3000;
var sRGBEncoding = 3001;
var GammaEncoding = 3007;
var RGBEEncoding = 3002;
var LogLuvEncoding = 3003;
var RGBM7Encoding = 3004;
var RGBM16Encoding = 3005;
var RGBDEncoding = 3006;
var BasicDepthPacking = 3200;
var RGBADepthPacking = 3201;
var TangentSpaceNormalMap = 0;
var ObjectSpaceNormalMap = 1;
var ZeroStencilOp = 0;
var KeepStencilOp = 7680;
var ReplaceStencilOp = 7681;
var IncrementStencilOp = 7682;
var DecrementStencilOp = 7683;
var IncrementWrapStencilOp = 34055;
var DecrementWrapStencilOp = 34056;
var InvertStencilOp = 5386;
var NeverStencilFunc = 512;
var LessStencilFunc = 513;
var EqualStencilFunc = 514;
var LessEqualStencilFunc = 515;
var GreaterStencilFunc = 516;
var NotEqualStencilFunc = 517;
var GreaterEqualStencilFunc = 518;
var AlwaysStencilFunc = 519;
var StaticDrawUsage = 35044;
var DynamicDrawUsage = 35048;
var StreamDrawUsage = 35040;
var StaticReadUsage = 35045;
var DynamicReadUsage = 35049;
var StreamReadUsage = 35041;
var StaticCopyUsage = 35046;
var DynamicCopyUsage = 35050;
var StreamCopyUsage = 35042;
/**
* https://github.com/mrdoob/eventdispatcher.js/
*/
function EventDispatcher() {}
Object.assign( EventDispatcher.prototype, {
addEventListener: function ( type, listener ) {
if ( this._listeners === undefined ) this._listeners = {};
var listeners = this._listeners;
if ( listeners[ type ] === undefined ) {
listeners[ type ] = [];
}
if ( listeners[ type ].indexOf( listener ) === - 1 ) {
listeners[ type ].push( listener );
}
},
hasEventListener: function ( type, listener ) {
if ( this._listeners === undefined ) return false;
var listeners = this._listeners;
return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
},
removeEventListener: function ( type, listener ) {
if ( this._listeners === undefined ) return;
var listeners = this._listeners;
var listenerArray = listeners[ type ];
if ( listenerArray !== undefined ) {
var index = listenerArray.indexOf( listener );
if ( index !== - 1 ) {
listenerArray.splice( index, 1 );
}
}
},
dispatchEvent: function ( event ) {
if ( this._listeners === undefined ) return;
var listeners = this._listeners;
var listenerArray = listeners[ event.type ];
if ( listenerArray !== undefined ) {
event.target = this;
// Make a copy, in case listeners are removed while iterating.
var array = listenerArray.slice( 0 );
for ( var i = 0, l = array.length; i < l; i ++ ) {
array[ i ].call( this, event );
}
}
}
} );
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
* @author thezwap
*/
var _lut = [];
for ( var i = 0; i < 256; i ++ ) {
_lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
}
var MathUtils = {
DEG2RAD: Math.PI / 180,
RAD2DEG: 180 / Math.PI,
generateUUID: function () {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
var d0 = Math.random() * 0xffffffff | 0;
var d1 = Math.random() * 0xffffffff | 0;
var d2 = Math.random() * 0xffffffff | 0;
var d3 = Math.random() * 0xffffffff | 0;
var uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
_lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
_lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
_lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
// .toUpperCase() here flattens concatenated strings to save heap memory space.
return uuid.toUpperCase();
},
clamp: function ( value, min, max ) {
return Math.max( min, Math.min( max, value ) );
},
// compute euclidian modulo of m % n
// https://en.wikipedia.org/wiki/Modulo_operation
euclideanModulo: function ( n, m ) {
return ( ( n % m ) + m ) % m;
},
// Linear mapping from range <a1, a2> to range <b1, b2>
mapLinear: function ( x, a1, a2, b1, b2 ) {
return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
},
// https://en.wikipedia.org/wiki/Linear_interpolation
lerp: function ( x, y, t ) {
return ( 1 - t ) * x + t * y;
},
// http://en.wikipedia.org/wiki/Smoothstep
smoothstep: function ( x, min, max ) {
if ( x <= min ) return 0;
if ( x >= max ) return 1;
x = ( x - min ) / ( max - min );
return x * x * ( 3 - 2 * x );
},
smootherstep: function ( x, min, max ) {
if ( x <= min ) return 0;
if ( x >= max ) return 1;
x = ( x - min ) / ( max - min );
return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
},
// Random integer from <low, high> interval
randInt: function ( low, high ) {
return low + Math.floor( Math.random() * ( high - low + 1 ) );
},
// Random float from <low, high> interval
randFloat: function ( low, high ) {
return low + Math.random() * ( high - low );
},
// Random float from <-range/2, range/2> interval
randFloatSpread: function ( range ) {
return range * ( 0.5 - Math.random() );
},
degToRad: function ( degrees ) {
return degrees * MathUtils.DEG2RAD;
},
radToDeg: function ( radians ) {
return radians * MathUtils.RAD2DEG;
},
isPowerOfTwo: function ( value ) {
return ( value & ( value - 1 ) ) === 0 && value !== 0;
},
ceilPowerOfTwo: function ( value ) {
return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
},
floorPowerOfTwo: function ( value ) {
return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
},
setQuaternionFromProperEuler: function ( q, a, b, c, order ) {
// Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
// rotations are applied to the axes in the order specified by 'order'
// rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
// angles are in radians
var cos = Math.cos;
var sin = Math.sin;
var c2 = cos( b / 2 );
var s2 = sin( b / 2 );
var c13 = cos( ( a + c ) / 2 );
var s13 = sin( ( a + c ) / 2 );
var c1_3 = cos( ( a - c ) / 2 );
var s1_3 = sin( ( a - c ) / 2 );
var c3_1 = cos( ( c - a ) / 2 );
var s3_1 = sin( ( c - a ) / 2 );
switch ( order ) {
case 'XYX':
q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
break;
case 'YZY':
q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
break;
case 'ZXZ':
q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
break;
case 'XZX':
q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
break;
case 'YXY':
q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
break;
case 'ZYZ':
q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
break;
default:
console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
}
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author philogb / http://blog.thejit.org/
* @author egraether / http://egraether.com/
* @author zz85 / http://www.lab4games.net/zz85/blog
*/
function Vector2( x, y ) {
this.x = x || 0;
this.y = y || 0;
}
Object.defineProperties( Vector2.prototype, {
"width": {
get: function () {
return this.x;
},
set: function ( value ) {
this.x = value;
}
},
"height": {
get: function () {
return this.y;
},
set: function ( value ) {
this.y = value;
}
}
} );
Object.assign( Vector2.prototype, {
isVector2: true,
set: function ( x, y ) {
this.x = x;
this.y = y;
return this;
},
setScalar: function ( scalar ) {
this.x = scalar;
this.y = scalar;
return this;
},
setX: function ( x ) {
this.x = x;
return this;
},
setY: function ( y ) {
this.y = y;
return this;
},
setComponent: function ( index, value ) {
switch ( index ) {
case 0: this.x = value; break;
case 1: this.y = value; break;
default: throw new Error( 'index is out of range: ' + index );
}
return this;
},
getComponent: function ( index ) {
switch ( index ) {
case 0: return this.x;
case 1: return this.y;
default: throw new Error( 'index is out of range: ' + index );
}
},
clone: function () {
return new this.constructor( this.x, this.y );
},
copy: function ( v ) {
this.x = v.x;
this.y = v.y;
return this;
},
add: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
return this.addVectors( v, w );
}
this.x += v.x;
this.y += v.y;
return this;
},
addScalar: function ( s ) {
this.x += s;
this.y += s;
return this;
},
addVectors: function ( a, b ) {
this.x = a.x + b.x;
this.y = a.y + b.y;
return this;
},
addScaledVector: function ( v, s ) {
this.x += v.x * s;
this.y += v.y * s;
return this;
},
sub: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
return this.subVectors( v, w );
}
this.x -= v.x;
this.y -= v.y;
return this;
},
subScalar: function ( s ) {
this.x -= s;
this.y -= s;
return this;
},
subVectors: function ( a, b ) {
this.x = a.x - b.x;
this.y = a.y - b.y;
return this;
},
multiply: function ( v ) {
this.x *= v.x;
this.y *= v.y;
return this;
},
multiplyScalar: function ( scalar ) {
this.x *= scalar;
this.y *= scalar;
return this;
},
divide: function ( v ) {
this.x /= v.x;
this.y /= v.y;
return this;
},
divideScalar: function ( scalar ) {
return this.multiplyScalar( 1 / scalar );
},
applyMatrix3: function ( m ) {
var x = this.x, y = this.y;
var e = m.elements;
this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
return this;
},
min: function ( v ) {
this.x = Math.min( this.x, v.x );
this.y = Math.min( this.y, v.y );
return this;
},
max: function ( v ) {
this.x = Math.max( this.x, v.x );
this.y = Math.max( this.y, v.y );
return this;
},
clamp: function ( min, max ) {
// assumes min < max, componentwise
this.x = Math.max( min.x, Math.min( max.x, this.x ) );
this.y = Math.max( min.y, Math.min( max.y, this.y ) );
return this;
},
clampScalar: function ( minVal, maxVal ) {
this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
return this;
},
clampLength: function ( min, max ) {
var length = this.length();
return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
},
floor: function () {
this.x = Math.floor( this.x );
this.y = Math.floor( this.y );
return this;
},
ceil: function () {
this.x = Math.ceil( this.x );
this.y = Math.ceil( this.y );
return this;
},
round: function () {
this.x = Math.round( this.x );
this.y = Math.round( this.y );
return this;
},
roundToZero: function () {
this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
return this;
},
negate: function () {
this.x = - this.x;
this.y = - this.y;
return this;
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y;
},
cross: function ( v ) {
return this.x * v.y - this.y * v.x;
},
lengthSq: function () {
return this.x * this.x + this.y * this.y;
},
length: function () {
return Math.sqrt( this.x * this.x + this.y * this.y );
},
manhattanLength: function () {
return Math.abs( this.x ) + Math.abs( this.y );
},
normalize: function () {
return this.divideScalar( this.length() || 1 );
},
angle: function () {
// computes the angle in radians with respect to the positive x-axis
var angle = Math.atan2( - this.y, - this.x ) + Math.PI;
return angle;
},
distanceTo: function ( v ) {
return Math.sqrt( this.distanceToSquared( v ) );
},
distanceToSquared: function ( v ) {
var dx = this.x - v.x, dy = this.y - v.y;
return dx * dx + dy * dy;
},
manhattanDistanceTo: function ( v ) {
return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
},
setLength: function ( length ) {
return this.normalize().multiplyScalar( length );
},
lerp: function ( v, alpha ) {
this.x += ( v.x - this.x ) * alpha;
this.y += ( v.y - this.y ) * alpha;
return this;
},
lerpVectors: function ( v1, v2, alpha ) {
return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
},
equals: function ( v ) {
return ( ( v.x === this.x ) && ( v.y === this.y ) );
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
this.x = array[ offset ];
this.y = array[ offset + 1 ];
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this.x;
array[ offset + 1 ] = this.y;
return array;
},
fromBufferAttribute: function ( attribute, index, offset ) {
if ( offset !== undefined ) {
console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
}
this.x = attribute.getX( index );
this.y = attribute.getY( index );
return this;
},
rotateAround: function ( center, angle ) {
var c = Math.cos( angle ), s = Math.sin( angle );
var x = this.x - center.x;
var y = this.y - center.y;
this.x = x * c - y * s + center.x;
this.y = x * s + y * c + center.y;
return this;
},
random: function () {
this.x = Math.random();
this.y = Math.random();
return this;
}
} );
/**
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author bhouston / http://clara.io
* @author tschw
*/
function Matrix3() {
this.elements = [
1, 0, 0,
0, 1, 0,
0, 0, 1
];
if ( arguments.length > 0 ) {
console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
}
}
Object.assign( Matrix3.prototype, {
isMatrix3: true,
set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
var te = this.elements;
te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
return this;
},
identity: function () {
this.set(
1, 0, 0,
0, 1, 0,
0, 0, 1
);
return this;
},
clone: function () {
return new this.constructor().fromArray( this.elements );
},
copy: function ( m ) {
var te = this.elements;
var me = m.elements;
te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
return this;
},
extractBasis: function ( xAxis, yAxis, zAxis ) {
xAxis.setFromMatrix3Column( this, 0 );
yAxis.setFromMatrix3Column( this, 1 );
zAxis.setFromMatrix3Column( this, 2 );
return this;
},
setFromMatrix4: function ( m ) {
var me = m.elements;
this.set(
me[ 0 ], me[ 4 ], me[ 8 ],
me[ 1 ], me[ 5 ], me[ 9 ],
me[ 2 ], me[ 6 ], me[ 10 ]
);
return this;
},
multiply: function ( m ) {
return this.multiplyMatrices( this, m );
},
premultiply: function ( m ) {
return this.multiplyMatrices( m, this );
},
multiplyMatrices: function ( a, b ) {
var ae = a.elements;
var be = b.elements;
var te = this.elements;
var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
return this;
},
multiplyScalar: function ( s ) {
var te = this.elements;
te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
return this;
},
determinant: function () {
var te = this.elements;
var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
},
getInverse: function ( matrix, throwOnDegenerate ) {
if ( throwOnDegenerate !== undefined ) {
console.warn( "THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate." );
}
var me = matrix.elements,
te = this.elements,
n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
t11 = n33 * n22 - n32 * n23,
t12 = n32 * n13 - n33 * n12,
t13 = n23 * n12 - n22 * n13,
det = n11 * t11 + n21 * t12 + n31 * t13;
if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
var detInv = 1 / det;
te[ 0 ] = t11 * detInv;
te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
te[ 3 ] = t12 * detInv;
te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
te[ 6 ] = t13 * detInv;
te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
return this;
},
transpose: function () {
var tmp, m = this.elements;
tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
return this;
},
getNormalMatrix: function ( matrix4 ) {
return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
},
transposeIntoArray: function ( r ) {
var m = this.elements;
r[ 0 ] = m[ 0 ];
r[ 1 ] = m[ 3 ];
r[ 2 ] = m[ 6 ];
r[ 3 ] = m[ 1 ];
r[ 4 ] = m[ 4 ];
r[ 5 ] = m[ 7 ];
r[ 6 ] = m[ 2 ];
r[ 7 ] = m[ 5 ];
r[ 8 ] = m[ 8 ];
return this;
},
setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
var c = Math.cos( rotation );
var s = Math.sin( rotation );
this.set(
sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
- sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
0, 0, 1
);
},
scale: function ( sx, sy ) {
var te = this.elements;
te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
return this;
},
rotate: function ( theta ) {
var c = Math.cos( theta );
var s = Math.sin( theta );
var te = this.elements;
var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
te[ 0 ] = c * a11 + s * a21;
te[ 3 ] = c * a12 + s * a22;
te[ 6 ] = c * a13 + s * a23;
te[ 1 ] = - s * a11 + c * a21;
te[ 4 ] = - s * a12 + c * a22;
te[ 7 ] = - s * a13 + c * a23;
return this;
},
translate: function ( tx, ty ) {
var te = this.elements;
te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
return this;
},
equals: function ( matrix ) {
var te = this.elements;
var me = matrix.elements;
for ( var i = 0; i < 9; i ++ ) {
if ( te[ i ] !== me[ i ] ) return false;
}
return true;
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
for ( var i = 0; i < 9; i ++ ) {
this.elements[ i ] = array[ i + offset ];
}
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
var te = this.elements;
array[ offset ] = te[ 0 ];
array[ offset + 1 ] = te[ 1 ];
array[ offset + 2 ] = te[ 2 ];
array[ offset + 3 ] = te[ 3 ];
array[ offset + 4 ] = te[ 4 ];
array[ offset + 5 ] = te[ 5 ];
array[ offset + 6 ] = te[ 6 ];
array[ offset + 7 ] = te[ 7 ];
array[ offset + 8 ] = te[ 8 ];
return array;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author szimek / https://github.com/szimek/
*/
var _canvas;
var ImageUtils = {
getDataURL: function ( image ) {
var canvas;
if ( typeof HTMLCanvasElement == 'undefined' ) {
return image.src;
} else if ( image instanceof HTMLCanvasElement ) {
canvas = image;
} else {
if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
_canvas.width = image.width;
_canvas.height = image.height;
var context = _canvas.getContext( '2d' );
if ( image instanceof ImageData ) {
context.putImageData( image, 0, 0 );
} else {
context.drawImage( image, 0, 0, image.width, image.height );
}
canvas = _canvas;
}
if ( canvas.width > 2048 || canvas.height > 2048 ) {
return canvas.toDataURL( 'image/jpeg', 0.6 );
} else {
return canvas.toDataURL( 'image/png' );
}
}
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author szimek / https://github.com/szimek/
*/
var textureId = 0;
function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
Object.defineProperty( this, 'id', { value: textureId ++ } );
this.uuid = MathUtils.generateUUID();
this.name = '';
this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
this.mipmaps = [];
this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
this.format = format !== undefined ? format : RGBAFormat;
this.internalFormat = null;
this.type = type !== undefined ? type : UnsignedByteType;
this.offset = new Vector2( 0, 0 );
this.repeat = new Vector2( 1, 1 );
this.center = new Vector2( 0, 0 );
this.rotation = 0;
this.matrixAutoUpdate = true;
this.matrix = new Matrix3();
this.generateMipmaps = true;
this.premultiplyAlpha = false;
this.flipY = true;
this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
// Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
//
// Also changing the encoding after already used by a Material will not automatically make the Material
// update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
this.encoding = encoding !== undefined ? encoding : LinearEncoding;
this.version = 0;
this.onUpdate = null;
}
Texture.DEFAULT_IMAGE = undefined;
Texture.DEFAULT_MAPPING = UVMapping;
Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
constructor: Texture,
isTexture: true,
updateMatrix: function () {
this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( source ) {
this.name = source.name;
this.image = source.image;
this.mipmaps = source.mipmaps.slice( 0 );
this.mapping = source.mapping;
this.wrapS = source.wrapS;
this.wrapT = source.wrapT;
this.magFilter = source.magFilter;
this.minFilter = source.minFilter;
this.anisotropy = source.anisotropy;
this.format = source.format;
this.internalFormat = source.internalFormat;
this.type = source.type;
this.offset.copy( source.offset );
this.repeat.copy( source.repeat );
this.center.copy( source.center );
this.rotation = source.rotation;
this.matrixAutoUpdate = source.matrixAutoUpdate;
this.matrix.copy( source.matrix );
this.generateMipmaps = source.generateMipmaps;
this.premultiplyAlpha = source.premultiplyAlpha;
this.flipY = source.flipY;
this.unpackAlignment = source.unpackAlignment;
this.encoding = source.encoding;
return this;
},
toJSON: function ( meta ) {
var isRootObject = ( meta === undefined || typeof meta === 'string' );
if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
return meta.textures[ this.uuid ];
}
var output = {
metadata: {
version: 4.5,
type: 'Texture',
generator: 'Texture.toJSON'
},
uuid: this.uuid,
name: this.name,
mapping: this.mapping,
repeat: [ this.repeat.x, this.repeat.y ],
offset: [ this.offset.x, this.offset.y ],
center: [ this.center.x, this.center.y ],
rotation: this.rotation,
wrap: [ this.wrapS, this.wrapT ],
format: this.format,
type: this.type,
encoding: this.encoding,
minFilter: this.minFilter,
magFilter: this.magFilter,
anisotropy: this.anisotropy,
flipY: this.flipY,
premultiplyAlpha: this.premultiplyAlpha,
unpackAlignment: this.unpackAlignment
};
if ( this.image !== undefined ) {
// TODO: Move to THREE.Image
var image = this.image;
if ( image.uuid === undefined ) {
image.uuid = MathUtils.generateUUID(); // UGH
}
if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
var url;
if ( Array.isArray( image ) ) {
// process array of images e.g. CubeTexture
url = [];
for ( var i = 0, l = image.length; i < l; i ++ ) {
url.push( ImageUtils.getDataURL( image[ i ] ) );
}
} else {
// process single image
url = ImageUtils.getDataURL( image );
}
meta.images[ image.uuid ] = {
uuid: image.uuid,
url: url
};
}
output.image = image.uuid;
}
if ( ! isRootObject ) {
meta.textures[ this.uuid ] = output;
}
return output;
},
dispose: function () {
this.dispatchEvent( { type: 'dispose' } );
},
transformUv: function ( uv ) {
if ( this.mapping !== UVMapping ) return uv;
uv.applyMatrix3( this.matrix );
if ( uv.x < 0 || uv.x > 1 ) {
switch ( this.wrapS ) {
case RepeatWrapping:
uv.x = uv.x - Math.floor( uv.x );
break;
case ClampToEdgeWrapping:
uv.x = uv.x < 0 ? 0 : 1;
break;
case MirroredRepeatWrapping:
if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
uv.x = Math.ceil( uv.x ) - uv.x;
} else {
uv.x = uv.x - Math.floor( uv.x );
}
break;
}
}
if ( uv.y < 0 || uv.y > 1 ) {
switch ( this.wrapT ) {
case RepeatWrapping:
uv.y = uv.y - Math.floor( uv.y );
break;
case ClampToEdgeWrapping:
uv.y = uv.y < 0 ? 0 : 1;
break;
case MirroredRepeatWrapping:
if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
uv.y = Math.ceil( uv.y ) - uv.y;
} else {
uv.y = uv.y - Math.floor( uv.y );
}
break;
}
}
if ( this.flipY ) {
uv.y = 1 - uv.y;
}
return uv;
}
} );
Object.defineProperty( Texture.prototype, "needsUpdate", {
set: function ( value ) {
if ( value === true ) this.version ++;
}
} );
/**
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author philogb / http://blog.thejit.org/
* @author mikael emtinger / http://gomo.se/
* @author egraether / http://egraether.com/
* @author WestLangley / http://github.com/WestLangley
*/
function Vector4( x, y, z, w ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.w = ( w !== undefined ) ? w : 1;
}
Object.defineProperties( Vector4.prototype, {
"width": {
get: function () {
return this.z;
},
set: function ( value ) {
this.z = value;
}
},
"height": {
get: function () {
return this.w;
},
set: function ( value ) {
this.w = value;
}
}
} );
Object.assign( Vector4.prototype, {
isVector4: true,
set: function ( x, y, z, w ) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
},
setScalar: function ( scalar ) {
this.x = scalar;
this.y = scalar;
this.z = scalar;
this.w = scalar;
return this;
},
setX: function ( x ) {
this.x = x;
return this;
},
setY: function ( y ) {
this.y = y;
return this;
},
setZ: function ( z ) {
this.z = z;
return this;
},
setW: function ( w ) {
this.w = w;
return this;
},
setComponent: function ( index, value ) {
switch ( index ) {
case 0: this.x = value; break;
case 1: this.y = value; break;
case 2: this.z = value; break;
case 3: this.w = value; break;
default: throw new Error( 'index is out of range: ' + index );
}
return this;
},
getComponent: function ( index ) {
switch ( index ) {
case 0: return this.x;
case 1: return this.y;
case 2: return this.z;
case 3: return this.w;
default: throw new Error( 'index is out of range: ' + index );
}
},
clone: function () {
return new this.constructor( this.x, this.y, this.z, this.w );
},
copy: function ( v ) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
this.w = ( v.w !== undefined ) ? v.w : 1;
return this;
},
add: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
return this.addVectors( v, w );
}
this.x += v.x;
this.y += v.y;
this.z += v.z;
this.w += v.w;
return this;
},
addScalar: function ( s ) {
this.x += s;
this.y += s;
this.z += s;
this.w += s;
return this;
},
addVectors: function ( a, b ) {
this.x = a.x + b.x;
this.y = a.y + b.y;
this.z = a.z + b.z;
this.w = a.w + b.w;
return this;
},
addScaledVector: function ( v, s ) {
this.x += v.x * s;
this.y += v.y * s;
this.z += v.z * s;
this.w += v.w * s;
return this;
},
sub: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
return this.subVectors( v, w );
}
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
this.w -= v.w;
return this;
},
subScalar: function ( s ) {
this.x -= s;
this.y -= s;
this.z -= s;
this.w -= s;
return this;
},
subVectors: function ( a, b ) {
this.x = a.x - b.x;
this.y = a.y - b.y;
this.z = a.z - b.z;
this.w = a.w - b.w;
return this;
},
multiplyScalar: function ( scalar ) {
this.x *= scalar;
this.y *= scalar;
this.z *= scalar;
this.w *= scalar;
return this;
},
applyMatrix4: function ( m ) {
var x = this.x, y = this.y, z = this.z, w = this.w;
var e = m.elements;
this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
return this;
},
divideScalar: function ( scalar ) {
return this.multiplyScalar( 1 / scalar );
},
setAxisAngleFromQuaternion: function ( q ) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
// q is assumed to be normalized
this.w = 2 * Math.acos( q.w );
var s = Math.sqrt( 1 - q.w * q.w );
if ( s < 0.0001 ) {
this.x = 1;
this.y = 0;
this.z = 0;
} else {
this.x = q.x / s;
this.y = q.y / s;
this.z = q.z / s;
}
return this;
},
setAxisAngleFromRotationMatrix: function ( m ) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var angle, x, y, z, // variables for result
epsilon = 0.01, // margin to allow for rounding errors
epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
te = m.elements,
m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
( Math.abs( m13 - m31 ) < epsilon ) &&
( Math.abs( m23 - m32 ) < epsilon ) ) {
// singularity found
// first check for identity matrix which must have +1 for all terms
// in leading diagonal and zero in other terms
if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
( Math.abs( m13 + m31 ) < epsilon2 ) &&
( Math.abs( m23 + m32 ) < epsilon2 ) &&
( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
// this singularity is identity matrix so angle = 0
this.set( 1, 0, 0, 0 );
return this; // zero angle, arbitrary axis
}
// otherwise this singularity is angle = 180
angle = Math.PI;
var xx = ( m11 + 1 ) / 2;
var yy = ( m22 + 1 ) / 2;
var zz = ( m33 + 1 ) / 2;
var xy = ( m12 + m21 ) / 4;
var xz = ( m13 + m31 ) / 4;
var yz = ( m23 + m32 ) / 4;
if ( ( xx > yy ) && ( xx > zz ) ) {
// m11 is the largest diagonal term
if ( xx < epsilon ) {
x = 0;
y = 0.707106781;
z = 0.707106781;
} else {
x = Math.sqrt( xx );
y = xy / x;
z = xz / x;
}
} else if ( yy > zz ) {
// m22 is the largest diagonal term
if ( yy < epsilon ) {
x = 0.707106781;
y = 0;
z = 0.707106781;
} else {
y = Math.sqrt( yy );
x = xy / y;
z = yz / y;
}
} else {
// m33 is the largest diagonal term so base result on this
if ( zz < epsilon ) {
x = 0.707106781;
y = 0.707106781;
z = 0;
} else {
z = Math.sqrt( zz );
x = xz / z;
y = yz / z;
}
}
this.set( x, y, z, angle );
return this; // return 180 deg rotation
}
// as we have reached here there are no singularities so we can handle normally
var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
( m13 - m31 ) * ( m13 - m31 ) +
( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
if ( Math.abs( s ) < 0.001 ) s = 1;
// prevent divide by zero, should not happen if matrix is orthogonal and should be
// caught by singularity test above, but I've left it in just in case
this.x = ( m32 - m23 ) / s;
this.y = ( m13 - m31 ) / s;
this.z = ( m21 - m12 ) / s;
this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
return this;
},
min: function ( v ) {
this.x = Math.min( this.x, v.x );
this.y = Math.min( this.y, v.y );
this.z = Math.min( this.z, v.z );
this.w = Math.min( this.w, v.w );
return this;
},
max: function ( v ) {
this.x = Math.max( this.x, v.x );
this.y = Math.max( this.y, v.y );
this.z = Math.max( this.z, v.z );
this.w = Math.max( this.w, v.w );
return this;
},
clamp: function ( min, max ) {
// assumes min < max, componentwise
this.x = Math.max( min.x, Math.min( max.x, this.x ) );
this.y = Math.max( min.y, Math.min( max.y, this.y ) );
this.z = Math.max( min.z, Math.min( max.z, this.z ) );
this.w = Math.max( min.w, Math.min( max.w, this.w ) );
return this;
},
clampScalar: function ( minVal, maxVal ) {
this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
return this;
},
clampLength: function ( min, max ) {
var length = this.length();
return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
},
floor: function () {
this.x = Math.floor( this.x );
this.y = Math.floor( this.y );
this.z = Math.floor( this.z );
this.w = Math.floor( this.w );
return this;
},
ceil: function () {
this.x = Math.ceil( this.x );
this.y = Math.ceil( this.y );
this.z = Math.ceil( this.z );
this.w = Math.ceil( this.w );
return this;
},
round: function () {
this.x = Math.round( this.x );
this.y = Math.round( this.y );
this.z = Math.round( this.z );
this.w = Math.round( this.w );
return this;
},
roundToZero: function () {
this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
return this;
},
negate: function () {
this.x = - this.x;
this.y = - this.y;
this.z = - this.z;
this.w = - this.w;
return this;
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
},
lengthSq: function () {
return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
},
length: function () {
return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
},
manhattanLength: function () {
return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
},
normalize: function () {
return this.divideScalar( this.length() || 1 );
},
setLength: function ( length ) {
return this.normalize().multiplyScalar( length );
},
lerp: function ( v, alpha ) {
this.x += ( v.x - this.x ) * alpha;
this.y += ( v.y - this.y ) * alpha;
this.z += ( v.z - this.z ) * alpha;
this.w += ( v.w - this.w ) * alpha;
return this;
},
lerpVectors: function ( v1, v2, alpha ) {
return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
},
equals: function ( v ) {
return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
this.x = array[ offset ];
this.y = array[ offset + 1 ];
this.z = array[ offset + 2 ];
this.w = array[ offset + 3 ];
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this.x;
array[ offset + 1 ] = this.y;
array[ offset + 2 ] = this.z;
array[ offset + 3 ] = this.w;
return array;
},
fromBufferAttribute: function ( attribute, index, offset ) {
if ( offset !== undefined ) {
console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
}
this.x = attribute.getX( index );
this.y = attribute.getY( index );
this.z = attribute.getZ( index );
this.w = attribute.getW( index );
return this;
},
random: function () {
this.x = Math.random();
this.y = Math.random();
this.z = Math.random();
this.w = Math.random();
return this;
}
} );
/**
* @author szimek / https://github.com/szimek/
* @author alteredq / http://alteredqualia.com/
* @author Marius Kintel / https://github.com/kintel
*/
/*
In options, we can specify:
* Texture parameters for an auto-generated target texture
* depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
*/
function WebGLRenderTarget( width, height, options ) {
this.width = width;
this.height = height;
this.scissor = new Vector4( 0, 0, width, height );
this.scissorTest = false;
this.viewport = new Vector4( 0, 0, width, height );
options = options || {};
this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
this.texture.image = {};
this.texture.image.width = width;
this.texture.image.height = height;
this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
}
WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
constructor: WebGLRenderTarget,
isWebGLRenderTarget: true,
setSize: function ( width, height ) {
if ( this.width !== width || this.height !== height ) {
this.width = width;
this.height = height;
this.texture.image.width = width;
this.texture.image.height = height;
this.dispose();
}
this.viewport.set( 0, 0, width, height );
this.scissor.set( 0, 0, width, height );
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( source ) {
this.width = source.width;
this.height = source.height;
this.viewport.copy( source.viewport );
this.texture = source.texture.clone();
this.depthBuffer = source.depthBuffer;
this.stencilBuffer = source.stencilBuffer;
this.depthTexture = source.depthTexture;
return this;
},
dispose: function () {
this.dispatchEvent( { type: 'dispose' } );
}
} );
/**
* @author Mugen87 / https://github.com/Mugen87
* @author Matt DesLauriers / @mattdesl
*/
function WebGLMultisampleRenderTarget( width, height, options ) {
WebGLRenderTarget.call( this, width, height, options );
this.samples = 4;
}
WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
constructor: WebGLMultisampleRenderTarget,
isWebGLMultisampleRenderTarget: true,
copy: function ( source ) {
WebGLRenderTarget.prototype.copy.call( this, source );
this.samples = source.samples;
return this;
}
} );
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author bhouston / http://clara.io
*/
function Quaternion( x, y, z, w ) {
this._x = x || 0;
this._y = y || 0;
this._z = z || 0;
this._w = ( w !== undefined ) ? w : 1;
}
Object.assign( Quaternion, {
slerp: function ( qa, qb, qm, t ) {
return qm.copy( qa ).slerp( qb, t );
},
slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
// fuzz-free, array-based Quaternion SLERP operation
var x0 = src0[ srcOffset0 + 0 ],
y0 = src0[ srcOffset0 + 1 ],
z0 = src0[ srcOffset0 + 2 ],
w0 = src0[ srcOffset0 + 3 ],
x1 = src1[ srcOffset1 + 0 ],
y1 = src1[ srcOffset1 + 1 ],
z1 = src1[ srcOffset1 + 2 ],
w1 = src1[ srcOffset1 + 3 ];
if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
var s = 1 - t,
cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
dir = ( cos >= 0 ? 1 : - 1 ),
sqrSin = 1 - cos * cos;
// Skip the Slerp for tiny steps to avoid numeric problems:
if ( sqrSin > Number.EPSILON ) {
var sin = Math.sqrt( sqrSin ),
len = Math.atan2( sin, cos * dir );
s = Math.sin( s * len ) / sin;
t = Math.sin( t * len ) / sin;
}
var tDir = t * dir;
x0 = x0 * s + x1 * tDir;
y0 = y0 * s + y1 * tDir;
z0 = z0 * s + z1 * tDir;
w0 = w0 * s + w1 * tDir;
// Normalize in case we just did a lerp:
if ( s === 1 - t ) {
var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
x0 *= f;
y0 *= f;
z0 *= f;
w0 *= f;
}
}
dst[ dstOffset ] = x0;
dst[ dstOffset + 1 ] = y0;
dst[ dstOffset + 2 ] = z0;
dst[ dstOffset + 3 ] = w0;
},
multiplyQuaternionsFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
var x0 = src0[ srcOffset0 ];
var y0 = src0[ srcOffset0 + 1 ];
var z0 = src0[ srcOffset0 + 2 ];
var w0 = src0[ srcOffset0 + 3 ];
var x1 = src1[ srcOffset1 ];
var y1 = src1[ srcOffset1 + 1 ];
var z1 = src1[ srcOffset1 + 2 ];
var w1 = src1[ srcOffset1 + 3 ];
dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
return dst;
}
} );
Object.defineProperties( Quaternion.prototype, {
x: {
get: function () {
return this._x;
},
set: function ( value ) {
this._x = value;
this._onChangeCallback();
}
},
y: {
get: function () {
return this._y;
},
set: function ( value ) {
this._y = value;
this._onChangeCallback();
}
},
z: {
get: function () {
return this._z;
},
set: function ( value ) {
this._z = value;
this._onChangeCallback();
}
},
w: {
get: function () {
return this._w;
},
set: function ( value ) {
this._w = value;
this._onChangeCallback();
}
}
} );
Object.assign( Quaternion.prototype, {
isQuaternion: true,
set: function ( x, y, z, w ) {
this._x = x;
this._y = y;
this._z = z;
this._w = w;
this._onChangeCallback();
return this;
},
clone: function () {
return new this.constructor( this._x, this._y, this._z, this._w );
},
copy: function ( quaternion ) {
this._x = quaternion.x;
this._y = quaternion.y;
this._z = quaternion.z;
this._w = quaternion.w;
this._onChangeCallback();
return this;
},
setFromEuler: function ( euler, update ) {
if ( ! ( euler && euler.isEuler ) ) {
throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
}
var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
// http://www.mathworks.com/matlabcentral/fileexchange/
// 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
// content/SpinCalc.m
var cos = Math.cos;
var sin = Math.sin;
var c1 = cos( x / 2 );
var c2 = cos( y / 2 );
var c3 = cos( z / 2 );
var s1 = sin( x / 2 );
var s2 = sin( y / 2 );
var s3 = sin( z / 2 );
switch ( order ) {
case 'XYZ':
this._x = s1 * c2 * c3 + c1 * s2 * s3;
this._y = c1 * s2 * c3 - s1 * c2 * s3;
this._z = c1 * c2 * s3 + s1 * s2 * c3;
this._w = c1 * c2 * c3 - s1 * s2 * s3;
break;
case 'YXZ':
this._x = s1 * c2 * c3 + c1 * s2 * s3;
this._y = c1 * s2 * c3 - s1 * c2 * s3;
this._z = c1 * c2 * s3 - s1 * s2 * c3;
this._w = c1 * c2 * c3 + s1 * s2 * s3;
break;
case 'ZXY':
this._x = s1 * c2 * c3 - c1 * s2 * s3;
this._y = c1 * s2 * c3 + s1 * c2 * s3;
this._z = c1 * c2 * s3 + s1 * s2 * c3;
this._w = c1 * c2 * c3 - s1 * s2 * s3;
break;
case 'ZYX':
this._x = s1 * c2 * c3 - c1 * s2 * s3;
this._y = c1 * s2 * c3 + s1 * c2 * s3;
this._z = c1 * c2 * s3 - s1 * s2 * c3;
this._w = c1 * c2 * c3 + s1 * s2 * s3;
break;
case 'YZX':
this._x = s1 * c2 * c3 + c1 * s2 * s3;
this._y = c1 * s2 * c3 + s1 * c2 * s3;
this._z = c1 * c2 * s3 - s1 * s2 * c3;
this._w = c1 * c2 * c3 - s1 * s2 * s3;
break;
case 'XZY':
this._x = s1 * c2 * c3 - c1 * s2 * s3;
this._y = c1 * s2 * c3 - s1 * c2 * s3;
this._z = c1 * c2 * s3 + s1 * s2 * c3;
this._w = c1 * c2 * c3 + s1 * s2 * s3;
break;
default:
console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
}
if ( update !== false ) this._onChangeCallback();
return this;
},
setFromAxisAngle: function ( axis, angle ) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
// assumes axis is normalized
var halfAngle = angle / 2, s = Math.sin( halfAngle );
this._x = axis.x * s;
this._y = axis.y * s;
this._z = axis.z * s;
this._w = Math.cos( halfAngle );
this._onChangeCallback();
return this;
},
setFromRotationMatrix: function ( m ) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var te = m.elements,
m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
trace = m11 + m22 + m33,
s;
if ( trace > 0 ) {
s = 0.5 / Math.sqrt( trace + 1.0 );
this._w = 0.25 / s;
this._x = ( m32 - m23 ) * s;
this._y = ( m13 - m31 ) * s;
this._z = ( m21 - m12 ) * s;
} else if ( m11 > m22 && m11 > m33 ) {
s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
this._w = ( m32 - m23 ) / s;
this._x = 0.25 * s;
this._y = ( m12 + m21 ) / s;
this._z = ( m13 + m31 ) / s;
} else if ( m22 > m33 ) {
s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
this._w = ( m13 - m31 ) / s;
this._x = ( m12 + m21 ) / s;
this._y = 0.25 * s;
this._z = ( m23 + m32 ) / s;
} else {
s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
this._w = ( m21 - m12 ) / s;
this._x = ( m13 + m31 ) / s;
this._y = ( m23 + m32 ) / s;
this._z = 0.25 * s;
}
this._onChangeCallback();
return this;
},
setFromUnitVectors: function ( vFrom, vTo ) {
// assumes direction vectors vFrom and vTo are normalized
var EPS = 0.000001;
var r = vFrom.dot( vTo ) + 1;
if ( r < EPS ) {
r = 0;
if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
this._x = - vFrom.y;
this._y = vFrom.x;
this._z = 0;
this._w = r;
} else {
this._x = 0;
this._y = - vFrom.z;
this._z = vFrom.y;
this._w = r;
}
} else {
// crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
this._w = r;
}
return this.normalize();
},
angleTo: function ( q ) {
return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );
},
rotateTowards: function ( q, step ) {
var angle = this.angleTo( q );
if ( angle === 0 ) return this;
var t = Math.min( 1, step / angle );
this.slerp( q, t );
return this;
},
inverse: function () {
// quaternion is assumed to have unit length
return this.conjugate();
},
conjugate: function () {
this._x *= - 1;
this._y *= - 1;
this._z *= - 1;
this._onChangeCallback();
return this;
},
dot: function ( v ) {
return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
},
lengthSq: function () {
return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
},
length: function () {
return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
},
normalize: function () {
var l = this.length();
if ( l === 0 ) {
this._x = 0;
this._y = 0;
this._z = 0;
this._w = 1;
} else {
l = 1 / l;
this._x = this._x * l;
this._y = this._y * l;
this._z = this._z * l;
this._w = this._w * l;
}
this._onChangeCallback();
return this;
},
multiply: function ( q, p ) {
if ( p !== undefined ) {
console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
return this.multiplyQuaternions( q, p );
}
return this.multiplyQuaternions( this, q );
},
premultiply: function ( q ) {
return this.multiplyQuaternions( q, this );
},
multiplyQuaternions: function ( a, b ) {
// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
this._onChangeCallback();
return this;
},
slerp: function ( qb, t ) {
if ( t === 0 ) return this;
if ( t === 1 ) return this.copy( qb );
var x = this._x, y = this._y, z = this._z, w = this._w;
// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
if ( cosHalfTheta < 0 ) {
this._w = - qb._w;
this._x = - qb._x;
this._y = - qb._y;
this._z = - qb._z;
cosHalfTheta = - cosHalfTheta;
} else {
this.copy( qb );
}
if ( cosHalfTheta >= 1.0 ) {
this._w = w;
this._x = x;
this._y = y;
this._z = z;
return this;
}
var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
if ( sqrSinHalfTheta <= Number.EPSILON ) {
var s = 1 - t;
this._w = s * w + t * this._w;
this._x = s * x + t * this._x;
this._y = s * y + t * this._y;
this._z = s * z + t * this._z;
this.normalize();
this._onChangeCallback();
return this;
}
var sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
this._w = ( w * ratioA + this._w * ratioB );
this._x = ( x * ratioA + this._x * ratioB );
this._y = ( y * ratioA + this._y * ratioB );
this._z = ( z * ratioA + this._z * ratioB );
this._onChangeCallback();
return this;
},
equals: function ( quaternion ) {
return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
this._x = array[ offset ];
this._y = array[ offset + 1 ];
this._z = array[ offset + 2 ];
this._w = array[ offset + 3 ];
this._onChangeCallback();
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this._x;
array[ offset + 1 ] = this._y;
array[ offset + 2 ] = this._z;
array[ offset + 3 ] = this._w;
return array;
},
fromBufferAttribute: function ( attribute, index ) {
this._x = attribute.getX( index );
this._y = attribute.getY( index );
this._z = attribute.getZ( index );
this._w = attribute.getW( index );
return this;
},
_onChange: function ( callback ) {
this._onChangeCallback = callback;
return this;
},
_onChangeCallback: function () {}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author kile / http://kile.stravaganza.org/
* @author philogb / http://blog.thejit.org/
* @author mikael emtinger / http://gomo.se/
* @author egraether / http://egraether.com/
* @author WestLangley / http://github.com/WestLangley
*/
var _vector = new Vector3();
var _quaternion = new Quaternion();
function Vector3( x, y, z ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
}
Object.assign( Vector3.prototype, {
isVector3: true,
set: function ( x, y, z ) {
this.x = x;
this.y = y;
this.z = z;
return this;
},
setScalar: function ( scalar ) {
this.x = scalar;
this.y = scalar;
this.z = scalar;
return this;
},
setX: function ( x ) {
this.x = x;
return this;
},
setY: function ( y ) {
this.y = y;
return this;
},
setZ: function ( z ) {
this.z = z;
return this;
},
setComponent: function ( index, value ) {
switch ( index ) {
case 0: this.x = value; break;
case 1: this.y = value; break;
case 2: this.z = value; break;
default: throw new Error( 'index is out of range: ' + index );
}
return this;
},
getComponent: function ( index ) {
switch ( index ) {
case 0: return this.x;
case 1: return this.y;
case 2: return this.z;
default: throw new Error( 'index is out of range: ' + index );
}
},
clone: function () {
return new this.constructor( this.x, this.y, this.z );
},
copy: function ( v ) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
return this;
},
add: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
return this.addVectors( v, w );
}
this.x += v.x;
this.y += v.y;
this.z += v.z;
return this;
},
addScalar: function ( s ) {
this.x += s;
this.y += s;
this.z += s;
return this;
},
addVectors: function ( a, b ) {
this.x = a.x + b.x;
this.y = a.y + b.y;
this.z = a.z + b.z;
return this;
},
addScaledVector: function ( v, s ) {
this.x += v.x * s;
this.y += v.y * s;
this.z += v.z * s;
return this;
},
sub: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
return this.subVectors( v, w );
}
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
return this;
},
subScalar: function ( s ) {
this.x -= s;
this.y -= s;
this.z -= s;
return this;
},
subVectors: function ( a, b ) {
this.x = a.x - b.x;
this.y = a.y - b.y;
this.z = a.z - b.z;
return this;
},
multiply: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
return this.multiplyVectors( v, w );
}
this.x *= v.x;
this.y *= v.y;
this.z *= v.z;
return this;
},
multiplyScalar: function ( scalar ) {
this.x *= scalar;
this.y *= scalar;
this.z *= scalar;
return this;
},
multiplyVectors: function ( a, b ) {
this.x = a.x * b.x;
this.y = a.y * b.y;
this.z = a.z * b.z;
return this;
},
applyEuler: function ( euler ) {
if ( ! ( euler && euler.isEuler ) ) {
console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
}
return this.applyQuaternion( _quaternion.setFromEuler( euler ) );
},
applyAxisAngle: function ( axis, angle ) {
return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );
},
applyMatrix3: function ( m ) {
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
return this;
},
applyNormalMatrix: function ( m ) {
return this.applyMatrix3( m ).normalize();
},
applyMatrix4: function ( m ) {
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
return this;
},
applyQuaternion: function ( q ) {
var x = this.x, y = this.y, z = this.z;
var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
// calculate quat * vector
var ix = qw * x + qy * z - qz * y;
var iy = qw * y + qz * x - qx * z;
var iz = qw * z + qx * y - qy * x;
var iw = - qx * x - qy * y - qz * z;
// calculate result * inverse quat
this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
return this;
},
project: function ( camera ) {
return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
},
unproject: function ( camera ) {
return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
},
transformDirection: function ( m ) {
// input: THREE.Matrix4 affine matrix
// vector interpreted as a direction
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
return this.normalize();
},
divide: function ( v ) {
this.x /= v.x;
this.y /= v.y;
this.z /= v.z;
return this;
},
divideScalar: function ( scalar ) {
return this.multiplyScalar( 1 / scalar );
},
min: function ( v ) {
this.x = Math.min( this.x, v.x );
this.y = Math.min( this.y, v.y );
this.z = Math.min( this.z, v.z );
return this;
},
max: function ( v ) {
this.x = Math.max( this.x, v.x );
this.y = Math.max( this.y, v.y );
this.z = Math.max( this.z, v.z );
return this;
},
clamp: function ( min, max ) {
// assumes min < max, componentwise
this.x = Math.max( min.x, Math.min( max.x, this.x ) );
this.y = Math.max( min.y, Math.min( max.y, this.y ) );
this.z = Math.max( min.z, Math.min( max.z, this.z ) );
return this;
},
clampScalar: function ( minVal, maxVal ) {
this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
return this;
},
clampLength: function ( min, max ) {
var length = this.length();
return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
},
floor: function () {
this.x = Math.floor( this.x );
this.y = Math.floor( this.y );
this.z = Math.floor( this.z );
return this;
},
ceil: function () {
this.x = Math.ceil( this.x );
this.y = Math.ceil( this.y );
this.z = Math.ceil( this.z );
return this;
},
round: function () {
this.x = Math.round( this.x );
this.y = Math.round( this.y );
this.z = Math.round( this.z );
return this;
},
roundToZero: function () {
this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
return this;
},
negate: function () {
this.x = - this.x;
this.y = - this.y;
this.z = - this.z;
return this;
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y + this.z * v.z;
},
// TODO lengthSquared?
lengthSq: function () {
return this.x * this.x + this.y * this.y + this.z * this.z;
},
length: function () {
return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
},
manhattanLength: function () {
return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
},
normalize: function () {
return this.divideScalar( this.length() || 1 );
},
setLength: function ( length ) {
return this.normalize().multiplyScalar( length );
},
lerp: function ( v, alpha ) {
this.x += ( v.x - this.x ) * alpha;
this.y += ( v.y - this.y ) * alpha;
this.z += ( v.z - this.z ) * alpha;
return this;
},
lerpVectors: function ( v1, v2, alpha ) {
return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
},
cross: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
return this.crossVectors( v, w );
}
return this.crossVectors( this, v );
},
crossVectors: function ( a, b ) {
var ax = a.x, ay = a.y, az = a.z;
var bx = b.x, by = b.y, bz = b.z;
this.x = ay * bz - az * by;
this.y = az * bx - ax * bz;
this.z = ax * by - ay * bx;
return this;
},
projectOnVector: function ( v ) {
var denominator = v.lengthSq();
if ( denominator === 0 ) return this.set( 0, 0, 0 );
var scalar = v.dot( this ) / denominator;
return this.copy( v ).multiplyScalar( scalar );
},
projectOnPlane: function ( planeNormal ) {
_vector.copy( this ).projectOnVector( planeNormal );
return this.sub( _vector );
},
reflect: function ( normal ) {
// reflect incident vector off plane orthogonal to normal
// normal is assumed to have unit length
return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
},
angleTo: function ( v ) {
var denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
if ( denominator === 0 ) return Math.PI / 2;
var theta = this.dot( v ) / denominator;
// clamp, to handle numerical problems
return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );
},
distanceTo: function ( v ) {
return Math.sqrt( this.distanceToSquared( v ) );
},
distanceToSquared: function ( v ) {
var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
return dx * dx + dy * dy + dz * dz;
},
manhattanDistanceTo: function ( v ) {
return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
},
setFromSpherical: function ( s ) {
return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
},
setFromSphericalCoords: function ( radius, phi, theta ) {
var sinPhiRadius = Math.sin( phi ) * radius;
this.x = sinPhiRadius * Math.sin( theta );
this.y = Math.cos( phi ) * radius;
this.z = sinPhiRadius * Math.cos( theta );
return this;
},
setFromCylindrical: function ( c ) {
return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
},
setFromCylindricalCoords: function ( radius, theta, y ) {
this.x = radius * Math.sin( theta );
this.y = y;
this.z = radius * Math.cos( theta );
return this;
},
setFromMatrixPosition: function ( m ) {
var e = m.elements;
this.x = e[ 12 ];
this.y = e[ 13 ];
this.z = e[ 14 ];
return this;
},
setFromMatrixScale: function ( m ) {
var sx = this.setFromMatrixColumn( m, 0 ).length();
var sy = this.setFromMatrixColumn( m, 1 ).length();
var sz = this.setFromMatrixColumn( m, 2 ).length();
this.x = sx;
this.y = sy;
this.z = sz;
return this;
},
setFromMatrixColumn: function ( m, index ) {
return this.fromArray( m.elements, index * 4 );
},
setFromMatrix3Column: function ( m, index ) {
return this.fromArray( m.elements, index * 3 );
},
equals: function ( v ) {
return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
this.x = array[ offset ];
this.y = array[ offset + 1 ];
this.z = array[ offset + 2 ];
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this.x;
array[ offset + 1 ] = this.y;
array[ offset + 2 ] = this.z;
return array;
},
fromBufferAttribute: function ( attribute, index, offset ) {
if ( offset !== undefined ) {
console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
}
this.x = attribute.getX( index );
this.y = attribute.getY( index );
this.z = attribute.getZ( index );
return this;
},
random: function () {
this.x = Math.random();
this.y = Math.random();
this.z = Math.random();
return this;
}
} );
var _v1 = new Vector3();
var _m1 = new Matrix4();
var _zero = new Vector3( 0, 0, 0 );
var _one = new Vector3( 1, 1, 1 );
var _x = new Vector3();
var _y = new Vector3();
var _z = new Vector3();
/**
* @author mrdoob / http://mrdoob.com/
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author philogb / http://blog.thejit.org/
* @author jordi_ros / http://plattsoft.com
* @author D1plo1d / http://github.com/D1plo1d
* @author alteredq / http://alteredqualia.com/
* @author mikael emtinger / http://gomo.se/
* @author timknip / http://www.floorplanner.com/
* @author bhouston / http://clara.io
* @author WestLangley / http://github.com/WestLangley
*/
function Matrix4() {
this.elements = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
if ( arguments.length > 0 ) {
console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
}
}
Object.assign( Matrix4.prototype, {
isMatrix4: true,
set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
var te = this.elements;
te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
return this;
},
identity: function () {
this.set(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
return this;
},
clone: function () {
return new Matrix4().fromArray( this.elements );
},
copy: function ( m ) {
var te = this.elements;
var me = m.elements;
te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
return this;
},
copyPosition: function ( m ) {
var te = this.elements, me = m.elements;
te[ 12 ] = me[ 12 ];
te[ 13 ] = me[ 13 ];
te[ 14 ] = me[ 14 ];
return this;
},
extractBasis: function ( xAxis, yAxis, zAxis ) {
xAxis.setFromMatrixColumn( this, 0 );
yAxis.setFromMatrixColumn( this, 1 );
zAxis.setFromMatrixColumn( this, 2 );
return this;
},
makeBasis: function ( xAxis, yAxis, zAxis ) {
this.set(
xAxis.x, yAxis.x, zAxis.x, 0,
xAxis.y, yAxis.y, zAxis.y, 0,
xAxis.z, yAxis.z, zAxis.z, 0,
0, 0, 0, 1
);
return this;
},
extractRotation: function ( m ) {
// this method does not support reflection matrices
var te = this.elements;
var me = m.elements;
var scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length();
var scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length();
var scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length();
te[ 0 ] = me[ 0 ] * scaleX;
te[ 1 ] = me[ 1 ] * scaleX;
te[ 2 ] = me[ 2 ] * scaleX;
te[ 3 ] = 0;
te[ 4 ] = me[ 4 ] * scaleY;
te[ 5 ] = me[ 5 ] * scaleY;
te[ 6 ] = me[ 6 ] * scaleY;
te[ 7 ] = 0;
te[ 8 ] = me[ 8 ] * scaleZ;
te[ 9 ] = me[ 9 ] * scaleZ;
te[ 10 ] = me[ 10 ] * scaleZ;
te[ 11 ] = 0;
te[ 12 ] = 0;
te[ 13 ] = 0;
te[ 14 ] = 0;
te[ 15 ] = 1;
return this;
},
makeRotationFromEuler: function ( euler ) {
if ( ! ( euler && euler.isEuler ) ) {
console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
}
var te = this.elements;
var x = euler.x, y = euler.y, z = euler.z;
var a = Math.cos( x ), b = Math.sin( x );
var c = Math.cos( y ), d = Math.sin( y );
var e = Math.cos( z ), f = Math.sin( z );
if ( euler.order === 'XYZ' ) {
var ae = a * e, af = a * f, be = b * e, bf = b * f;
te[ 0 ] = c * e;
te[ 4 ] = - c * f;
te[ 8 ] = d;
te[ 1 ] = af + be * d;
te[ 5 ] = ae - bf * d;
te[ 9 ] = - b * c;
te[ 2 ] = bf - ae * d;
te[ 6 ] = be + af * d;
te[ 10 ] = a * c;
} else if ( euler.order === 'YXZ' ) {
var ce = c * e, cf = c * f, de = d * e, df = d * f;
te[ 0 ] = ce + df * b;
te[ 4 ] = de * b - cf;
te[ 8 ] = a * d;
te[ 1 ] = a * f;
te[ 5 ] = a * e;
te[ 9 ] = - b;
te[ 2 ] = cf * b - de;
te[ 6 ] = df + ce * b;
te[ 10 ] = a * c;
} else if ( euler.order === 'ZXY' ) {
var ce = c * e, cf = c * f, de = d * e, df = d * f;
te[ 0 ] = ce - df * b;
te[ 4 ] = - a * f;
te[ 8 ] = de + cf * b;
te[ 1 ] = cf + de * b;
te[ 5 ] = a * e;
te[ 9 ] = df - ce * b;
te[ 2 ] = - a * d;
te[ 6 ] = b;
te[ 10 ] = a * c;
} else if ( euler.order === 'ZYX' ) {
var ae = a * e, af = a * f, be = b * e, bf = b * f;
te[ 0 ] = c * e;
te[ 4 ] = be * d - af;
te[ 8 ] = ae * d + bf;
te[ 1 ] = c * f;
te[ 5 ] = bf * d + ae;
te[ 9 ] = af * d - be;
te[ 2 ] = - d;
te[ 6 ] = b * c;
te[ 10 ] = a * c;
} else if ( euler.order === 'YZX' ) {
var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
te[ 0 ] = c * e;
te[ 4 ] = bd - ac * f;
te[ 8 ] = bc * f + ad;
te[ 1 ] = f;
te[ 5 ] = a * e;
te[ 9 ] = - b * e;
te[ 2 ] = - d * e;
te[ 6 ] = ad * f + bc;
te[ 10 ] = ac - bd * f;
} else if ( euler.order === 'XZY' ) {
var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
te[ 0 ] = c * e;
te[ 4 ] = - f;
te[ 8 ] = d * e;
te[ 1 ] = ac * f + bd;
te[ 5 ] = a * e;
te[ 9 ] = ad * f - bc;
te[ 2 ] = bc * f - ad;
te[ 6 ] = b * e;
te[ 10 ] = bd * f + ac;
}
// bottom row
te[ 3 ] = 0;
te[ 7 ] = 0;
te[ 11 ] = 0;
// last column
te[ 12 ] = 0;
te[ 13 ] = 0;
te[ 14 ] = 0;
te[ 15 ] = 1;
return this;
},
makeRotationFromQuaternion: function ( q ) {
return this.compose( _zero, q, _one );
},
lookAt: function ( eye, target, up ) {
var te = this.elements;
_z.subVectors( eye, target );
if ( _z.lengthSq() === 0 ) {
// eye and target are in the same position
_z.z = 1;
}
_z.normalize();
_x.crossVectors( up, _z );
if ( _x.lengthSq() === 0 ) {
// up and z are parallel
if ( Math.abs( up.z ) === 1 ) {
_z.x += 0.0001;
} else {
_z.z += 0.0001;
}
_z.normalize();
_x.crossVectors( up, _z );
}
_x.normalize();
_y.crossVectors( _z, _x );
te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
return this;
},
multiply: function ( m, n ) {
if ( n !== undefined ) {
console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
return this.multiplyMatrices( m, n );
}
return this.multiplyMatrices( this, m );
},
premultiply: function ( m ) {
return this.multiplyMatrices( m, this );
},
multiplyMatrices: function ( a, b ) {
var ae = a.elements;
var be = b.elements;
var te = this.elements;
var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
return this;
},
multiplyScalar: function ( s ) {
var te = this.elements;
te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
return this;
},
determinant: function () {
var te = this.elements;
var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
//TODO: make this more efficient
//( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
return (
n41 * (
+ n14 * n23 * n32
- n13 * n24 * n32
- n14 * n22 * n33
+ n12 * n24 * n33
+ n13 * n22 * n34
- n12 * n23 * n34
) +
n42 * (
+ n11 * n23 * n34
- n11 * n24 * n33
+ n14 * n21 * n33
- n13 * n21 * n34
+ n13 * n24 * n31
- n14 * n23 * n31
) +
n43 * (
+ n11 * n24 * n32
- n11 * n22 * n34
- n14 * n21 * n32
+ n12 * n21 * n34
+ n14 * n22 * n31
- n12 * n24 * n31
) +
n44 * (
- n13 * n22 * n31
- n11 * n23 * n32
+ n11 * n22 * n33
+ n13 * n21 * n32
- n12 * n21 * n33
+ n12 * n23 * n31
)
);
},
transpose: function () {
var te = this.elements;
var tmp;
tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
return this;
},
setPosition: function ( x, y, z ) {
var te = this.elements;
if ( x.isVector3 ) {
te[ 12 ] = x.x;
te[ 13 ] = x.y;
te[ 14 ] = x.z;
} else {
te[ 12 ] = x;
te[ 13 ] = y;
te[ 14 ] = z;
}
return this;
},
getInverse: function ( m, throwOnDegenerate ) {
if ( throwOnDegenerate !== undefined ) {
console.warn( "THREE.Matrix4: .getInverse() can no longer be configured to throw on degenerate." );
}
// based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
var te = this.elements,
me = m.elements,
n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
var detInv = 1 / det;
te[ 0 ] = t11 * detInv;
te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
te[ 4 ] = t12 * detInv;
te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
te[ 8 ] = t13 * detInv;
te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
te[ 12 ] = t14 * detInv;
te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
return this;
},
scale: function ( v ) {
var te = this.elements;
var x = v.x, y = v.y, z = v.z;
te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
return this;
},
getMaxScaleOnAxis: function () {
var te = this.elements;
var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
},
makeTranslation: function ( x, y, z ) {
this.set(
1, 0, 0, x,
0, 1, 0, y,
0, 0, 1, z,
0, 0, 0, 1
);
return this;
},
makeRotationX: function ( theta ) {
var c = Math.cos( theta ), s = Math.sin( theta );
this.set(
1, 0, 0, 0,
0, c, - s, 0,
0, s, c, 0,
0, 0, 0, 1
);
return this;
},
makeRotationY: function ( theta ) {
var c = Math.cos( theta ), s = Math.sin( theta );
this.set(
c, 0, s, 0,
0, 1, 0, 0,
- s, 0, c, 0,
0, 0, 0, 1
);
return this;
},
makeRotationZ: function ( theta ) {
var c = Math.cos( theta ), s = Math.sin( theta );
this.set(
c, - s, 0, 0,
s, c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
return this;
},
makeRotationAxis: function ( axis, angle ) {
// Based on http://www.gamedev.net/reference/articles/article1199.asp
var c = Math.cos( angle );
var s = Math.sin( angle );
var t = 1 - c;
var x = axis.x, y = axis.y, z = axis.z;
var tx = t * x, ty = t * y;
this.set(
tx * x + c, tx * y - s * z, tx * z + s * y, 0,
tx * y + s * z, ty * y + c, ty * z - s * x, 0,
tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
0, 0, 0, 1
);
return this;
},
makeScale: function ( x, y, z ) {
this.set(
x, 0, 0, 0,
0, y, 0, 0,
0, 0, z, 0,
0, 0, 0, 1
);
return this;
},
makeShear: function ( x, y, z ) {
this.set(
1, y, z, 0,
x, 1, z, 0,
x, y, 1, 0,
0, 0, 0, 1
);
return this;
},
compose: function ( position, quaternion, scale ) {
var te = this.elements;
var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
var x2 = x + x, y2 = y + y, z2 = z + z;
var xx = x * x2, xy = x * y2, xz = x * z2;
var yy = y * y2, yz = y * z2, zz = z * z2;
var wx = w * x2, wy = w * y2, wz = w * z2;
var sx = scale.x, sy = scale.y, sz = scale.z;
te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
te[ 1 ] = ( xy + wz ) * sx;
te[ 2 ] = ( xz - wy ) * sx;
te[ 3 ] = 0;
te[ 4 ] = ( xy - wz ) * sy;
te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
te[ 6 ] = ( yz + wx ) * sy;
te[ 7 ] = 0;
te[ 8 ] = ( xz + wy ) * sz;
te[ 9 ] = ( yz - wx ) * sz;
te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
te[ 11 ] = 0;
te[ 12 ] = position.x;
te[ 13 ] = position.y;
te[ 14 ] = position.z;
te[ 15 ] = 1;
return this;
},
decompose: function ( position, quaternion, scale ) {
var te = this.elements;
var sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
var sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
var sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
// if determine is negative, we need to invert one scale
var det = this.determinant();
if ( det < 0 ) sx = - sx;
position.x = te[ 12 ];
position.y = te[ 13 ];
position.z = te[ 14 ];
// scale the rotation part
_m1.copy( this );
var invSX = 1 / sx;
var invSY = 1 / sy;
var invSZ = 1 / sz;
_m1.elements[ 0 ] *= invSX;
_m1.elements[ 1 ] *= invSX;
_m1.elements[ 2 ] *= invSX;
_m1.elements[ 4 ] *= invSY;
_m1.elements[ 5 ] *= invSY;
_m1.elements[ 6 ] *= invSY;
_m1.elements[ 8 ] *= invSZ;
_m1.elements[ 9 ] *= invSZ;
_m1.elements[ 10 ] *= invSZ;
quaternion.setFromRotationMatrix( _m1 );
scale.x = sx;
scale.y = sy;
scale.z = sz;
return this;
},
makePerspective: function ( left, right, top, bottom, near, far ) {
if ( far === undefined ) {
console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
}
var te = this.elements;
var x = 2 * near / ( right - left );
var y = 2 * near / ( top - bottom );
var a = ( right + left ) / ( right - left );
var b = ( top + bottom ) / ( top - bottom );
var c = - ( far + near ) / ( far - near );
var d = - 2 * far * near / ( far - near );
te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
return this;
},
makeOrthographic: function ( left, right, top, bottom, near, far ) {
var te = this.elements;
var w = 1.0 / ( right - left );
var h = 1.0 / ( top - bottom );
var p = 1.0 / ( far - near );
var x = ( right + left ) * w;
var y = ( top + bottom ) * h;
var z = ( far + near ) * p;
te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
return this;
},
equals: function ( matrix ) {
var te = this.elements;
var me = matrix.elements;
for ( var i = 0; i < 16; i ++ ) {
if ( te[ i ] !== me[ i ] ) return false;
}
return true;
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
for ( var i = 0; i < 16; i ++ ) {
this.elements[ i ] = array[ i + offset ];
}
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
var te = this.elements;
array[ offset ] = te[ 0 ];
array[ offset + 1 ] = te[ 1 ];
array[ offset + 2 ] = te[ 2 ];
array[ offset + 3 ] = te[ 3 ];
array[ offset + 4 ] = te[ 4 ];
array[ offset + 5 ] = te[ 5 ];
array[ offset + 6 ] = te[ 6 ];
array[ offset + 7 ] = te[ 7 ];
array[ offset + 8 ] = te[ 8 ];
array[ offset + 9 ] = te[ 9 ];
array[ offset + 10 ] = te[ 10 ];
array[ offset + 11 ] = te[ 11 ];
array[ offset + 12 ] = te[ 12 ];
array[ offset + 13 ] = te[ 13 ];
array[ offset + 14 ] = te[ 14 ];
array[ offset + 15 ] = te[ 15 ];
return array;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
* @author bhouston / http://clara.io
*/
var _matrix = new Matrix4();
var _quaternion$1 = new Quaternion();
function Euler( x, y, z, order ) {
this._x = x || 0;
this._y = y || 0;
this._z = z || 0;
this._order = order || Euler.DefaultOrder;
}
Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
Euler.DefaultOrder = 'XYZ';
Object.defineProperties( Euler.prototype, {
x: {
get: function () {
return this._x;
},
set: function ( value ) {
this._x = value;
this._onChangeCallback();
}
},
y: {
get: function () {
return this._y;
},
set: function ( value ) {
this._y = value;
this._onChangeCallback();
}
},
z: {
get: function () {
return this._z;
},
set: function ( value ) {
this._z = value;
this._onChangeCallback();
}
},
order: {
get: function () {
return this._order;
},
set: function ( value ) {
this._order = value;
this._onChangeCallback();
}
}
} );
Object.assign( Euler.prototype, {
isEuler: true,
set: function ( x, y, z, order ) {
this._x = x;
this._y = y;
this._z = z;
this._order = order || this._order;
this._onChangeCallback();
return this;
},
clone: function () {
return new this.constructor( this._x, this._y, this._z, this._order );
},
copy: function ( euler ) {
this._x = euler._x;
this._y = euler._y;
this._z = euler._z;
this._order = euler._order;
this._onChangeCallback();
return this;
},
setFromRotationMatrix: function ( m, order, update ) {
var clamp = MathUtils.clamp;
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var te = m.elements;
var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
order = order || this._order;
switch ( order ) {
case 'XYZ':
this._y = Math.asin( clamp( m13, - 1, 1 ) );
if ( Math.abs( m13 ) < 0.9999999 ) {
this._x = Math.atan2( - m23, m33 );
this._z = Math.atan2( - m12, m11 );
} else {
this._x = Math.atan2( m32, m22 );
this._z = 0;
}
break;
case 'YXZ':
this._x = Math.asin( - clamp( m23, - 1, 1 ) );
if ( Math.abs( m23 ) < 0.9999999 ) {
this._y = Math.atan2( m13, m33 );
this._z = Math.atan2( m21, m22 );
} else {
this._y = Math.atan2( - m31, m11 );
this._z = 0;
}
break;
case 'ZXY':
this._x = Math.asin( clamp( m32, - 1, 1 ) );
if ( Math.abs( m32 ) < 0.9999999 ) {
this._y = Math.atan2( - m31, m33 );
this._z = Math.atan2( - m12, m22 );
} else {
this._y = 0;
this._z = Math.atan2( m21, m11 );
}
break;
case 'ZYX':
this._y = Math.asin( - clamp( m31, - 1, 1 ) );
if ( Math.abs( m31 ) < 0.9999999 ) {
this._x = Math.atan2( m32, m33 );
this._z = Math.atan2( m21, m11 );
} else {
this._x = 0;
this._z = Math.atan2( - m12, m22 );
}
break;
case 'YZX':
this._z = Math.asin( clamp( m21, - 1, 1 ) );
if ( Math.abs( m21 ) < 0.9999999 ) {
this._x = Math.atan2( - m23, m22 );
this._y = Math.atan2( - m31, m11 );
} else {
this._x = 0;
this._y = Math.atan2( m13, m33 );
}
break;
case 'XZY':
this._z = Math.asin( - clamp( m12, - 1, 1 ) );
if ( Math.abs( m12 ) < 0.9999999 ) {
this._x = Math.atan2( m32, m22 );
this._y = Math.atan2( m13, m11 );
} else {
this._x = Math.atan2( - m23, m33 );
this._y = 0;
}
break;
default:
console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
}
this._order = order;
if ( update !== false ) this._onChangeCallback();
return this;
},
setFromQuaternion: function ( q, order, update ) {
_matrix.makeRotationFromQuaternion( q );
return this.setFromRotationMatrix( _matrix, order, update );
},
setFromVector3: function ( v, order ) {
return this.set( v.x, v.y, v.z, order || this._order );
},
reorder: function ( newOrder ) {
// WARNING: this discards revolution information -bhouston
_quaternion$1.setFromEuler( this );
return this.setFromQuaternion( _quaternion$1, newOrder );
},
equals: function ( euler ) {
return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
},
fromArray: function ( array ) {
this._x = array[ 0 ];
this._y = array[ 1 ];
this._z = array[ 2 ];
if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
this._onChangeCallback();
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this._x;
array[ offset + 1 ] = this._y;
array[ offset + 2 ] = this._z;
array[ offset + 3 ] = this._order;
return array;
},
toVector3: function ( optionalResult ) {
if ( optionalResult ) {
return optionalResult.set( this._x, this._y, this._z );
} else {
return new Vector3( this._x, this._y, this._z );
}
},
_onChange: function ( callback ) {
this._onChangeCallback = callback;
return this;
},
_onChangeCallback: function () {}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function Layers() {
this.mask = 1 | 0;
}
Object.assign( Layers.prototype, {
set: function ( channel ) {
this.mask = 1 << channel | 0;
},
enable: function ( channel ) {
this.mask |= 1 << channel | 0;
},
enableAll: function () {
this.mask = 0xffffffff | 0;
},
toggle: function ( channel ) {
this.mask ^= 1 << channel | 0;
},
disable: function ( channel ) {
this.mask &= ~ ( 1 << channel | 0 );
},
disableAll: function () {
this.mask = 0;
},
test: function ( layers ) {
return ( this.mask & layers.mask ) !== 0;
}
} );
var _object3DId = 0;
var _v1$1 = new Vector3();
var _q1 = new Quaternion();
var _m1$1 = new Matrix4();
var _target = new Vector3();
var _position = new Vector3();
var _scale = new Vector3();
var _quaternion$2 = new Quaternion();
var _xAxis = new Vector3( 1, 0, 0 );
var _yAxis = new Vector3( 0, 1, 0 );
var _zAxis = new Vector3( 0, 0, 1 );
var _addedEvent = { type: 'added' };
var _removedEvent = { type: 'removed' };
/**
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author elephantatwork / www.elephantatwork.ch
*/
function Object3D() {
Object.defineProperty( this, 'id', { value: _object3DId ++ } );
this.uuid = MathUtils.generateUUID();
this.name = '';
this.type = 'Object3D';
this.parent = null;
this.children = [];
this.up = Object3D.DefaultUp.clone();
var position = new Vector3();
var rotation = new Euler();
var quaternion = new Quaternion();
var scale = new Vector3( 1, 1, 1 );
function onRotationChange() {
quaternion.setFromEuler( rotation, false );
}
function onQuaternionChange() {
rotation.setFromQuaternion( quaternion, undefined, false );
}
rotation._onChange( onRotationChange );
quaternion._onChange( onQuaternionChange );
Object.defineProperties( this, {
position: {
configurable: true,
enumerable: true,
value: position
},
rotation: {
configurable: true,
enumerable: true,
value: rotation
},
quaternion: {
configurable: true,
enumerable: true,
value: quaternion
},
scale: {
configurable: true,
enumerable: true,
value: scale
},
modelViewMatrix: {
value: new Matrix4()
},
normalMatrix: {
value: new Matrix3()
}
} );
this.matrix = new Matrix4();
this.matrixWorld = new Matrix4();
this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
this.matrixWorldNeedsUpdate = false;
this.layers = new Layers();
this.visible = true;
this.castShadow = false;
this.receiveShadow = false;
this.frustumCulled = true;
this.renderOrder = 0;
this.userData = {};
}
Object3D.DefaultUp = new Vector3( 0, 1, 0 );
Object3D.DefaultMatrixAutoUpdate = true;
Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
constructor: Object3D,
isObject3D: true,
onBeforeRender: function () {},
onAfterRender: function () {},
applyMatrix4: function ( matrix ) {
if ( this.matrixAutoUpdate ) this.updateMatrix();
this.matrix.premultiply( matrix );
this.matrix.decompose( this.position, this.quaternion, this.scale );
},
applyQuaternion: function ( q ) {
this.quaternion.premultiply( q );
return this;
},
setRotationFromAxisAngle: function ( axis, angle ) {
// assumes axis is normalized
this.quaternion.setFromAxisAngle( axis, angle );
},
setRotationFromEuler: function ( euler ) {
this.quaternion.setFromEuler( euler, true );
},
setRotationFromMatrix: function ( m ) {
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
this.quaternion.setFromRotationMatrix( m );
},
setRotationFromQuaternion: function ( q ) {
// assumes q is normalized
this.quaternion.copy( q );
},
rotateOnAxis: function ( axis, angle ) {
// rotate object on axis in object space
// axis is assumed to be normalized
_q1.setFromAxisAngle( axis, angle );
this.quaternion.multiply( _q1 );
return this;
},
rotateOnWorldAxis: function ( axis, angle ) {
// rotate object on axis in world space
// axis is assumed to be normalized
// method assumes no rotated parent
_q1.setFromAxisAngle( axis, angle );
this.quaternion.premultiply( _q1 );
return this;
},
rotateX: function ( angle ) {
return this.rotateOnAxis( _xAxis, angle );
},
rotateY: function ( angle ) {
return this.rotateOnAxis( _yAxis, angle );
},
rotateZ: function ( angle ) {
return this.rotateOnAxis( _zAxis, angle );
},
translateOnAxis: function ( axis, distance ) {
// translate object by distance along axis in object space
// axis is assumed to be normalized
_v1$1.copy( axis ).applyQuaternion( this.quaternion );
this.position.add( _v1$1.multiplyScalar( distance ) );
return this;
},
translateX: function ( distance ) {
return this.translateOnAxis( _xAxis, distance );
},
translateY: function ( distance ) {
return this.translateOnAxis( _yAxis, distance );
},
translateZ: function ( distance ) {
return this.translateOnAxis( _zAxis, distance );
},
localToWorld: function ( vector ) {
return vector.applyMatrix4( this.matrixWorld );
},
worldToLocal: function ( vector ) {
return vector.applyMatrix4( _m1$1.getInverse( this.matrixWorld ) );
},
lookAt: function ( x, y, z ) {
// This method does not support objects having non-uniformly-scaled parent(s)
if ( x.isVector3 ) {
_target.copy( x );
} else {
_target.set( x, y, z );
}
var parent = this.parent;
this.updateWorldMatrix( true, false );
_position.setFromMatrixPosition( this.matrixWorld );
if ( this.isCamera || this.isLight ) {
_m1$1.lookAt( _position, _target, this.up );
} else {
_m1$1.lookAt( _target, _position, this.up );
}
this.quaternion.setFromRotationMatrix( _m1$1 );
if ( parent ) {
_m1$1.extractRotation( parent.matrixWorld );
_q1.setFromRotationMatrix( _m1$1 );
this.quaternion.premultiply( _q1.inverse() );
}
},
add: function ( object ) {
if ( arguments.length > 1 ) {
for ( var i = 0; i < arguments.length; i ++ ) {
this.add( arguments[ i ] );
}
return this;
}
if ( object === this ) {
console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
return this;
}
if ( ( object && object.isObject3D ) ) {
if ( object.parent !== null ) {
object.parent.remove( object );
}
object.parent = this;
this.children.push( object );
object.dispatchEvent( _addedEvent );
} else {
console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
}
return this;
},
remove: function ( object ) {
if ( arguments.length > 1 ) {
for ( var i = 0; i < arguments.length; i ++ ) {
this.remove( arguments[ i ] );
}
return this;
}
var index = this.children.indexOf( object );
if ( index !== - 1 ) {
object.parent = null;
this.children.splice( index, 1 );
object.dispatchEvent( _removedEvent );
}
return this;
},
attach: function ( object ) {
// adds object as a child of this, while maintaining the object's world transform
this.updateWorldMatrix( true, false );
_m1$1.getInverse( this.matrixWorld );
if ( object.parent !== null ) {
object.parent.updateWorldMatrix( true, false );
_m1$1.multiply( object.parent.matrixWorld );
}
object.applyMatrix4( _m1$1 );
object.updateWorldMatrix( false, false );
this.add( object );
return this;
},
getObjectById: function ( id ) {
return this.getObjectByProperty( 'id', id );
},
getObjectByName: function ( name ) {
return this.getObjectByProperty( 'name', name );
},
getObjectByProperty: function ( name, value ) {
if ( this[ name ] === value ) return this;
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
var child = this.children[ i ];
var object = child.getObjectByProperty( name, value );
if ( object !== undefined ) {
return object;
}
}
return undefined;
},
getWorldPosition: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
target = new Vector3();
}
this.updateMatrixWorld( true );
return target.setFromMatrixPosition( this.matrixWorld );
},
getWorldQuaternion: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
target = new Quaternion();
}
this.updateMatrixWorld( true );
this.matrixWorld.decompose( _position, target, _scale );
return target;
},
getWorldScale: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
target = new Vector3();
}
this.updateMatrixWorld( true );
this.matrixWorld.decompose( _position, _quaternion$2, target );
return target;
},
getWorldDirection: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
target = new Vector3();
}
this.updateMatrixWorld( true );
var e = this.matrixWorld.elements;
return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
},
raycast: function () {},
traverse: function ( callback ) {
callback( this );
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].traverse( callback );
}
},
traverseVisible: function ( callback ) {
if ( this.visible === false ) return;
callback( this );
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].traverseVisible( callback );
}
},
traverseAncestors: function ( callback ) {
var parent = this.parent;
if ( parent !== null ) {
callback( parent );
parent.traverseAncestors( callback );
}
},
updateMatrix: function () {
this.matrix.compose( this.position, this.quaternion, this.scale );
this.matrixWorldNeedsUpdate = true;
},
updateMatrixWorld: function ( force ) {
if ( this.matrixAutoUpdate ) this.updateMatrix();
if ( this.matrixWorldNeedsUpdate || force ) {
if ( this.parent === null ) {
this.matrixWorld.copy( this.matrix );
} else {
this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
}
this.matrixWorldNeedsUpdate = false;
force = true;
}
// update children
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].updateMatrixWorld( force );
}
},
updateWorldMatrix: function ( updateParents, updateChildren ) {
var parent = this.parent;
if ( updateParents === true && parent !== null ) {
parent.updateWorldMatrix( true, false );
}
if ( this.matrixAutoUpdate ) this.updateMatrix();
if ( this.parent === null ) {
this.matrixWorld.copy( this.matrix );
} else {
this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
}
// update children
if ( updateChildren === true ) {
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].updateWorldMatrix( false, true );
}
}
},
toJSON: function ( meta ) {
// meta is a string when called from JSON.stringify
var isRootObject = ( meta === undefined || typeof meta === 'string' );
var output = {};
// meta is a hash used to collect geometries, materials.
// not providing it implies that this is the root object
// being serialized.
if ( isRootObject ) {
// initialize meta obj
meta = {
geometries: {},
materials: {},
textures: {},
images: {},
shapes: {}
};
output.metadata = {
version: 4.5,
type: 'Object',
generator: 'Object3D.toJSON'
};
}
// standard Object3D serialization
var object = {};
object.uuid = this.uuid;
object.type = this.type;
if ( this.name !== '' ) object.name = this.name;
if ( this.castShadow === true ) object.castShadow = true;
if ( this.receiveShadow === true ) object.receiveShadow = true;
if ( this.visible === false ) object.visible = false;
if ( this.frustumCulled === false ) object.frustumCulled = false;
if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
object.layers = this.layers.mask;
object.matrix = this.matrix.toArray();
if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
// object specific properties
if ( this.isInstancedMesh ) {
object.type = 'InstancedMesh';
object.count = this.count;
object.instanceMatrix = this.instanceMatrix.toJSON();
}
//
function serialize( library, element ) {
if ( library[ element.uuid ] === undefined ) {
library[ element.uuid ] = element.toJSON( meta );
}
return element.uuid;
}
if ( this.isMesh || this.isLine || this.isPoints ) {
object.geometry = serialize( meta.geometries, this.geometry );
var parameters = this.geometry.parameters;
if ( parameters !== undefined && parameters.shapes !== undefined ) {
var shapes = parameters.shapes;
if ( Array.isArray( shapes ) ) {
for ( var i = 0, l = shapes.length; i < l; i ++ ) {
var shape = shapes[ i ];
serialize( meta.shapes, shape );
}
} else {
serialize( meta.shapes, shapes );
}
}
}
if ( this.material !== undefined ) {
if ( Array.isArray( this.material ) ) {
var uuids = [];
for ( var i = 0, l = this.material.length; i < l; i ++ ) {
uuids.push( serialize( meta.materials, this.material[ i ] ) );
}
object.material = uuids;
} else {
object.material = serialize( meta.materials, this.material );
}
}
//
if ( this.children.length > 0 ) {
object.children = [];
for ( var i = 0; i < this.children.length; i ++ ) {
object.children.push( this.children[ i ].toJSON( meta ).object );
}
}
if ( isRootObject ) {
var geometries = extractFromCache( meta.geometries );
var materials = extractFromCache( meta.materials );
var textures = extractFromCache( meta.textures );
var images = extractFromCache( meta.images );
var shapes = extractFromCache( meta.shapes );
if ( geometries.length > 0 ) output.geometries = geometries;
if ( materials.length > 0 ) output.materials = materials;
if ( textures.length > 0 ) output.textures = textures;
if ( images.length > 0 ) output.images = images;
if ( shapes.length > 0 ) output.shapes = shapes;
}
output.object = object;
return output;
// extract data from the cache hash
// remove metadata on each item
// and return as array
function extractFromCache( cache ) {
var values = [];
for ( var key in cache ) {
var data = cache[ key ];
delete data.metadata;
values.push( data );
}
return values;
}
},
clone: function ( recursive ) {
return new this.constructor().copy( this, recursive );
},
copy: function ( source, recursive ) {
if ( recursive === undefined ) recursive = true;
this.name = source.name;
this.up.copy( source.up );
this.position.copy( source.position );
this.quaternion.copy( source.quaternion );
this.scale.copy( source.scale );
this.matrix.copy( source.matrix );
this.matrixWorld.copy( source.matrixWorld );
this.matrixAutoUpdate = source.matrixAutoUpdate;
this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
this.layers.mask = source.layers.mask;
this.visible = source.visible;
this.castShadow = source.castShadow;
this.receiveShadow = source.receiveShadow;
this.frustumCulled = source.frustumCulled;
this.renderOrder = source.renderOrder;
this.userData = JSON.parse( JSON.stringify( source.userData ) );
if ( recursive === true ) {
for ( var i = 0; i < source.children.length; i ++ ) {
var child = source.children[ i ];
this.add( child.clone() );
}
}
return this;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function Scene() {
Object3D.call( this );
this.type = 'Scene';
this.background = null;
this.environment = null;
this.fog = null;
this.overrideMaterial = null;
this.autoUpdate = true; // checked by the renderer
if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
}
}
Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Scene,
isScene: true,
copy: function ( source, recursive ) {
Object3D.prototype.copy.call( this, source, recursive );
if ( source.background !== null ) this.background = source.background.clone();
if ( source.environment !== null ) this.environment = source.environment.clone();
if ( source.fog !== null ) this.fog = source.fog.clone();
if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
this.autoUpdate = source.autoUpdate;
this.matrixAutoUpdate = source.matrixAutoUpdate;
return this;
},
toJSON: function ( meta ) {
var data = Object3D.prototype.toJSON.call( this, meta );
if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta );
if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
return data;
},
dispose: function () {
this.dispatchEvent( { type: 'dispose' } );
}
} );
var _points = [
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3()
];
var _vector$1 = new Vector3();
var _box = new Box3();
// triangle centered vertices
var _v0 = new Vector3();
var _v1$2 = new Vector3();
var _v2 = new Vector3();
// triangle edge vectors
var _f0 = new Vector3();
var _f1 = new Vector3();
var _f2 = new Vector3();
var _center = new Vector3();
var _extents = new Vector3();
var _triangleNormal = new Vector3();
var _testAxis = new Vector3();
/**
* @author bhouston / http://clara.io
* @author WestLangley / http://github.com/WestLangley
*/
function Box3( min, max ) {
this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
}
Object.assign( Box3.prototype, {
isBox3: true,
set: function ( min, max ) {
this.min.copy( min );
this.max.copy( max );
return this;
},
setFromArray: function ( array ) {
var minX = + Infinity;
var minY = + Infinity;
var minZ = + Infinity;
var maxX = - Infinity;
var maxY = - Infinity;
var maxZ = - Infinity;
for ( var i = 0, l = array.length; i < l; i += 3 ) {
var x = array[ i ];
var y = array[ i + 1 ];
var z = array[ i + 2 ];
if ( x < minX ) minX = x;
if ( y < minY ) minY = y;
if ( z < minZ ) minZ = z;
if ( x > maxX ) maxX = x;
if ( y > maxY ) maxY = y;
if ( z > maxZ ) maxZ = z;
}
this.min.set( minX, minY, minZ );
this.max.set( maxX, maxY, maxZ );
return this;
},
setFromBufferAttribute: function ( attribute ) {
var minX = + Infinity;
var minY = + Infinity;
var minZ = + Infinity;
var maxX = - Infinity;
var maxY = - Infinity;
var maxZ = - Infinity;
for ( var i = 0, l = attribute.count; i < l; i ++ ) {
var x = attribute.getX( i );
var y = attribute.getY( i );
var z = attribute.getZ( i );
if ( x < minX ) minX = x;
if ( y < minY ) minY = y;
if ( z < minZ ) minZ = z;
if ( x > maxX ) maxX = x;
if ( y > maxY ) maxY = y;
if ( z > maxZ ) maxZ = z;
}
this.min.set( minX, minY, minZ );
this.max.set( maxX, maxY, maxZ );
return this;
},
setFromPoints: function ( points ) {
this.makeEmpty();
for ( var i = 0, il = points.length; i < il; i ++ ) {
this.expandByPoint( points[ i ] );
}
return this;
},
setFromCenterAndSize: function ( center, size ) {
var halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );
this.min.copy( center ).sub( halfSize );
this.max.copy( center ).add( halfSize );
return this;
},
setFromObject: function ( object ) {
this.makeEmpty();
return this.expandByObject( object );
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( box ) {
this.min.copy( box.min );
this.max.copy( box.max );
return this;
},
makeEmpty: function () {
this.min.x = this.min.y = this.min.z = + Infinity;
this.max.x = this.max.y = this.max.z = - Infinity;
return this;
},
isEmpty: function () {
// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
},
getCenter: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Box3: .getCenter() target is now required' );
target = new Vector3();
}
return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
},
getSize: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Box3: .getSize() target is now required' );
target = new Vector3();
}
return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
},
expandByPoint: function ( point ) {
this.min.min( point );
this.max.max( point );
return this;
},
expandByVector: function ( vector ) {
this.min.sub( vector );
this.max.add( vector );
return this;
},
expandByScalar: function ( scalar ) {
this.min.addScalar( - scalar );
this.max.addScalar( scalar );
return this;
},
expandByObject: function ( object ) {
// Computes the world-axis-aligned bounding box of an object (including its children),
// accounting for both the object's, and children's, world transforms
object.updateWorldMatrix( false, false );
var geometry = object.geometry;
if ( geometry !== undefined ) {
if ( geometry.boundingBox === null ) {
geometry.computeBoundingBox();
}
_box.copy( geometry.boundingBox );
_box.applyMatrix4( object.matrixWorld );
this.union( _box );
}
var children = object.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
this.expandByObject( children[ i ] );
}
return this;
},
containsPoint: function ( point ) {
return point.x < this.min.x || point.x > this.max.x ||
point.y < this.min.y || point.y > this.max.y ||
point.z < this.min.z || point.z > this.max.z ? false : true;
},
containsBox: function ( box ) {
return this.min.x <= box.min.x && box.max.x <= this.max.x &&
this.min.y <= box.min.y && box.max.y <= this.max.y &&
this.min.z <= box.min.z && box.max.z <= this.max.z;
},
getParameter: function ( point, target ) {
// This can potentially have a divide by zero if the box
// has a size dimension of 0.
if ( target === undefined ) {
console.warn( 'THREE.Box3: .getParameter() target is now required' );
target = new Vector3();
}
return target.set(
( point.x - this.min.x ) / ( this.max.x - this.min.x ),
( point.y - this.min.y ) / ( this.max.y - this.min.y ),
( point.z - this.min.z ) / ( this.max.z - this.min.z )
);
},
intersectsBox: function ( box ) {
// using 6 splitting planes to rule out intersections.
return box.max.x < this.min.x || box.min.x > this.max.x ||
box.max.y < this.min.y || box.min.y > this.max.y ||
box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
},
intersectsSphere: function ( sphere ) {
// Find the point on the AABB closest to the sphere center.
this.clampPoint( sphere.center, _vector$1 );
// If that point is inside the sphere, the AABB and sphere intersect.
return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
},
intersectsPlane: function ( plane ) {
// We compute the minimum and maximum dot product values. If those values
// are on the same side (back or front) of the plane, then there is no intersection.
var min, max;
if ( plane.normal.x > 0 ) {
min = plane.normal.x * this.min.x;
max = plane.normal.x * this.max.x;
} else {
min = plane.normal.x * this.max.x;
max = plane.normal.x * this.min.x;
}
if ( plane.normal.y > 0 ) {
min += plane.normal.y * this.min.y;
max += plane.normal.y * this.max.y;
} else {
min += plane.normal.y * this.max.y;
max += plane.normal.y * this.min.y;
}
if ( plane.normal.z > 0 ) {
min += plane.normal.z * this.min.z;
max += plane.normal.z * this.max.z;
} else {
min += plane.normal.z * this.max.z;
max += plane.normal.z * this.min.z;
}
return ( min <= - plane.constant && max >= - plane.constant );
},
intersectsTriangle: function ( triangle ) {
if ( this.isEmpty() ) {
return false;
}
// compute box center and extents
this.getCenter( _center );
_extents.subVectors( this.max, _center );
// translate triangle to aabb origin
_v0.subVectors( triangle.a, _center );
_v1$2.subVectors( triangle.b, _center );
_v2.subVectors( triangle.c, _center );
// compute edge vectors for triangle
_f0.subVectors( _v1$2, _v0 );
_f1.subVectors( _v2, _v1$2 );
_f2.subVectors( _v0, _v2 );
// test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
// make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
// axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
var axes = [
0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
_f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
- _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
];
if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {
return false;
}
// test 3 face normals from the aabb
axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {
return false;
}
// finally testing the face normal of the triangle
// use already existing triangle edge vectors here
_triangleNormal.crossVectors( _f0, _f1 );
axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
return satForAxes( axes, _v0, _v1$2, _v2, _extents );
},
clampPoint: function ( point, target ) {
if ( target === undefined ) {
console.warn( 'THREE.Box3: .clampPoint() target is now required' );
target = new Vector3();
}
return target.copy( point ).clamp( this.min, this.max );
},
distanceToPoint: function ( point ) {
var clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );
return clampedPoint.sub( point ).length();
},
getBoundingSphere: function ( target ) {
if ( target === undefined ) {
console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
//target = new Sphere(); // removed to avoid cyclic dependency
}
this.getCenter( target.center );
target.radius = this.getSize( _vector$1 ).length() * 0.5;
return target;
},
intersect: function ( box ) {
this.min.max( box.min );
this.max.min( box.max );
// ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
if ( this.isEmpty() ) this.makeEmpty();
return this;
},
union: function ( box ) {
this.min.min( box.min );
this.max.max( box.max );
return this;
},
applyMatrix4: function ( matrix ) {
// transform of empty box is an empty box.
if ( this.isEmpty() ) return this;
// NOTE: I am using a binary pattern to specify all 2^3 combinations below
_points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
_points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
_points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
_points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
_points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
_points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
_points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
_points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
this.setFromPoints( _points );
return this;
},
translate: function ( offset ) {
this.min.add( offset );
this.max.add( offset );
return this;
},
equals: function ( box ) {
return box.min.equals( this.min ) && box.max.equals( this.max );
}
} );
function satForAxes( axes, v0, v1, v2, extents ) {
var i, j;
for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) {
_testAxis.fromArray( axes, i );
// project the aabb onto the seperating axis
var r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
// project all 3 vertices of the triangle onto the seperating axis
var p0 = v0.dot( _testAxis );
var p1 = v1.dot( _testAxis );
var p2 = v2.dot( _testAxis );
// actual test, basically see if either of the most extreme of the triangle points intersects r
if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
// points of the projected triangle are outside the projected half-length of the aabb
// the axis is seperating and we can exit
return false;
}
}
return true;
}
var _box$1 = new Box3();
/**
* @author bhouston / http://clara.io
* @author mrdoob / http://mrdoob.com/
*/
function Sphere( center, radius ) {
this.center = ( center !== undefined ) ? center : new Vector3();
this.radius = ( radius !== undefined ) ? radius : - 1;
}
Object.assign( Sphere.prototype, {
set: function ( center, radius ) {
this.center.copy( center );
this.radius = radius;
return this;
},
setFromPoints: function ( points, optionalCenter ) {
var center = this.center;
if ( optionalCenter !== undefined ) {
center.copy( optionalCenter );
} else {
_box$1.setFromPoints( points ).getCenter( center );
}
var maxRadiusSq = 0;
for ( var i = 0, il = points.length; i < il; i ++ ) {
maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
}
this.radius = Math.sqrt( maxRadiusSq );
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( sphere ) {
this.center.copy( sphere.center );
this.radius = sphere.radius;
return this;
},
isEmpty: function () {
return ( this.radius < 0 );
},
makeEmpty: function () {
this.center.set( 0, 0, 0 );
this.radius = - 1;
return this;
},
containsPoint: function ( point ) {
return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
},
distanceToPoint: function ( point ) {
return ( point.distanceTo( this.center ) - this.radius );
},
intersectsSphere: function ( sphere ) {
var radiusSum = this.radius + sphere.radius;
return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
},
intersectsBox: function ( box ) {
return box.intersectsSphere( this );
},
intersectsPlane: function ( plane ) {
return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
},
clampPoint: function ( point, target ) {
var deltaLengthSq = this.center.distanceToSquared( point );
if ( target === undefined ) {
console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
target = new Vector3();
}
target.copy( point );
if ( deltaLengthSq > ( this.radius * this.radius ) ) {
target.sub( this.center ).normalize();
target.multiplyScalar( this.radius ).add( this.center );
}
return target;
},
getBoundingBox: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
target = new Box3();
}
if ( this.isEmpty() ) {
// Empty sphere produces empty bounding box
target.makeEmpty();
return target;
}
target.set( this.center, this.center );
target.expandByScalar( this.radius );
return target;
},
applyMatrix4: function ( matrix ) {
this.center.applyMatrix4( matrix );
this.radius = this.radius * matrix.getMaxScaleOnAxis();
return this;
},
translate: function ( offset ) {
this.center.add( offset );
return this;
},
equals: function ( sphere ) {
return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
}
} );
var _vector$2 = new Vector3();
var _segCenter = new Vector3();
var _segDir = new Vector3();
var _diff = new Vector3();
var _edge1 = new Vector3();
var _edge2 = new Vector3();
var _normal = new Vector3();
/**
* @author bhouston / http://clara.io
*/
function Ray( origin, direction ) {
this.origin = ( origin !== undefined ) ? origin : new Vector3();
this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 );
}
Object.assign( Ray.prototype, {
set: function ( origin, direction ) {
this.origin.copy( origin );
this.direction.copy( direction );
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( ray ) {
this.origin.copy( ray.origin );
this.direction.copy( ray.direction );
return this;
},
at: function ( t, target ) {
if ( target === undefined ) {
console.warn( 'THREE.Ray: .at() target is now required' );
target = new Vector3();
}
return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
},
lookAt: function ( v ) {
this.direction.copy( v ).sub( this.origin ).normalize();
return this;
},
recast: function ( t ) {
this.origin.copy( this.at( t, _vector$2 ) );
return this;
},
closestPointToPoint: function ( point, target ) {
if ( target === undefined ) {
console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
target = new Vector3();
}
target.subVectors( point, this.origin );
var directionDistance = target.dot( this.direction );
if ( directionDistance < 0 ) {
return target.copy( this.origin );
}
return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
},
distanceToPoint: function ( point ) {
return Math.sqrt( this.distanceSqToPoint( point ) );
},
distanceSqToPoint: function ( point ) {
var directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );
// point behind the ray
if ( directionDistance < 0 ) {
return this.origin.distanceToSquared( point );
}
_vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
return _vector$2.distanceToSquared( point );
},
distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
// It returns the min distance between the ray and the segment
// defined by v0 and v1
// It can also set two optional targets :
// - The closest point on the ray
// - The closest point on the segment
_segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
_segDir.copy( v1 ).sub( v0 ).normalize();
_diff.copy( this.origin ).sub( _segCenter );
var segExtent = v0.distanceTo( v1 ) * 0.5;
var a01 = - this.direction.dot( _segDir );
var b0 = _diff.dot( this.direction );
var b1 = - _diff.dot( _segDir );
var c = _diff.lengthSq();
var det = Math.abs( 1 - a01 * a01 );
var s0, s1, sqrDist, extDet;
if ( det > 0 ) {
// The ray and segment are not parallel.
s0 = a01 * b1 - b0;
s1 = a01 * b0 - b1;
extDet = segExtent * det;
if ( s0 >= 0 ) {
if ( s1 >= - extDet ) {
if ( s1 <= extDet ) {
// region 0
// Minimum at interior points of ray and segment.
var invDet = 1 / det;
s0 *= invDet;
s1 *= invDet;
sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
} else {
// region 1
s1 = segExtent;
s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
}
} else {
// region 5
s1 = - segExtent;
s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
}
} else {
if ( s1 <= - extDet ) {
// region 4
s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
} else if ( s1 <= extDet ) {
// region 3
s0 = 0;
s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
sqrDist = s1 * ( s1 + 2 * b1 ) + c;
} else {
// region 2
s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
}
}
} else {
// Ray and segment are parallel.
s1 = ( a01 > 0 ) ? - segExtent : segExtent;
s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
}
if ( optionalPointOnRay ) {
optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
}
if ( optionalPointOnSegment ) {
optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
}
return sqrDist;
},
intersectSphere: function ( sphere, target ) {
_vector$2.subVectors( sphere.center, this.origin );
var tca = _vector$2.dot( this.direction );
var d2 = _vector$2.dot( _vector$2 ) - tca * tca;
var radius2 = sphere.radius * sphere.radius;
if ( d2 > radius2 ) return null;
var thc = Math.sqrt( radius2 - d2 );
// t0 = first intersect point - entrance on front of sphere
var t0 = tca - thc;
// t1 = second intersect point - exit point on back of sphere
var t1 = tca + thc;
// test to see if both t0 and t1 are behind the ray - if so, return null
if ( t0 < 0 && t1 < 0 ) return null;
// test to see if t0 is behind the ray:
// if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
// in order to always return an intersect point that is in front of the ray.
if ( t0 < 0 ) return this.at( t1, target );
// else t0 is in front of the ray, so return the first collision point scaled by t0
return this.at( t0, target );
},
intersectsSphere: function ( sphere ) {
return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
},
distanceToPlane: function ( plane ) {
var denominator = plane.normal.dot( this.direction );
if ( denominator === 0 ) {
// line is coplanar, return origin
if ( plane.distanceToPoint( this.origin ) === 0 ) {
return 0;
}
// Null is preferable to undefined since undefined means.... it is undefined
return null;
}
var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
// Return if the ray never intersects the plane
return t >= 0 ? t : null;
},
intersectPlane: function ( plane, target ) {
var t = this.distanceToPlane( plane );
if ( t === null ) {
return null;
}
return this.at( t, target );
},
intersectsPlane: function ( plane ) {
// check if the ray lies on the plane first
var distToPoint = plane.distanceToPoint( this.origin );
if ( distToPoint === 0 ) {
return true;
}
var denominator = plane.normal.dot( this.direction );
if ( denominator * distToPoint < 0 ) {
return true;
}
// ray origin is behind the plane (and is pointing behind it)
return false;
},
intersectBox: function ( box, target ) {
var tmin, tmax, tymin, tymax, tzmin, tzmax;
var invdirx = 1 / this.direction.x,
invdiry = 1 / this.direction.y,
invdirz = 1 / this.direction.z;
var origin = this.origin;
if ( invdirx >= 0 ) {
tmin = ( box.min.x - origin.x ) * invdirx;
tmax = ( box.max.x - origin.x ) * invdirx;
} else {
tmin = ( box.max.x - origin.x ) * invdirx;
tmax = ( box.min.x - origin.x ) * invdirx;
}
if ( invdiry >= 0 ) {
tymin = ( box.min.y - origin.y ) * invdiry;
tymax = ( box.max.y - origin.y ) * invdiry;
} else {
tymin = ( box.max.y - origin.y ) * invdiry;
tymax = ( box.min.y - origin.y ) * invdiry;
}
if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
// These lines also handle the case where tmin or tmax is NaN
// (result of 0 * Infinity). x !== x returns true if x is NaN
if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
if ( invdirz >= 0 ) {
tzmin = ( box.min.z - origin.z ) * invdirz;
tzmax = ( box.max.z - origin.z ) * invdirz;
} else {
tzmin = ( box.max.z - origin.z ) * invdirz;
tzmax = ( box.min.z - origin.z ) * invdirz;
}
if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
//return point closest to the ray (positive side)
if ( tmax < 0 ) return null;
return this.at( tmin >= 0 ? tmin : tmax, target );
},
intersectsBox: function ( box ) {
return this.intersectBox( box, _vector$2 ) !== null;
},
intersectTriangle: function ( a, b, c, backfaceCulling, target ) {
// Compute the offset origin, edges, and normal.
// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
_edge1.subVectors( b, a );
_edge2.subVectors( c, a );
_normal.crossVectors( _edge1, _edge2 );
// Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
// E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
// |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
// |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
// |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
var DdN = this.direction.dot( _normal );
var sign;
if ( DdN > 0 ) {
if ( backfaceCulling ) return null;
sign = 1;
} else if ( DdN < 0 ) {
sign = - 1;
DdN = - DdN;
} else {
return null;
}
_diff.subVectors( this.origin, a );
var DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
// b1 < 0, no intersection
if ( DdQxE2 < 0 ) {
return null;
}
var DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
// b2 < 0, no intersection
if ( DdE1xQ < 0 ) {
return null;
}
// b1+b2 > 1, no intersection
if ( DdQxE2 + DdE1xQ > DdN ) {
return null;
}
// Line intersects triangle, check if ray does.
var QdN = - sign * _diff.dot( _normal );
// t < 0, no intersection
if ( QdN < 0 ) {
return null;
}
// Ray intersects triangle.
return this.at( QdN / DdN, target );
},
applyMatrix4: function ( matrix4 ) {
this.origin.applyMatrix4( matrix4 );
this.direction.transformDirection( matrix4 );
return this;
},
equals: function ( ray ) {
return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
}
} );
/**
* @author bhouston / http://clara.io
*/
var _vector1 = new Vector3();
var _vector2 = new Vector3();
var _normalMatrix = new Matrix3();
function Plane( normal, constant ) {
// normal is assumed to be normalized
this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
this.constant = ( constant !== undefined ) ? constant : 0;
}
Object.assign( Plane.prototype, {
isPlane: true,
set: function ( normal, constant ) {
this.normal.copy( normal );
this.constant = constant;
return this;
},
setComponents: function ( x, y, z, w ) {
this.normal.set( x, y, z );
this.constant = w;
return this;
},
setFromNormalAndCoplanarPoint: function ( normal, point ) {
this.normal.copy( normal );
this.constant = - point.dot( this.normal );
return this;
},
setFromCoplanarPoints: function ( a, b, c ) {
var normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
// Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
this.setFromNormalAndCoplanarPoint( normal, a );
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( plane ) {
this.normal.copy( plane.normal );
this.constant = plane.constant;
return this;
},
normalize: function () {
// Note: will lead to a divide by zero if the plane is invalid.
var inverseNormalLength = 1.0 / this.normal.length();
this.normal.multiplyScalar( inverseNormalLength );
this.constant *= inverseNormalLength;
return this;
},
negate: function () {
this.constant *= - 1;
this.normal.negate();
return this;
},
distanceToPoint: function ( point ) {
return this.normal.dot( point ) + this.constant;
},
distanceToSphere: function ( sphere ) {
return this.distanceToPoint( sphere.center ) - sphere.radius;
},
projectPoint: function ( point, target ) {
if ( target === undefined ) {
console.warn( 'THREE.Plane: .projectPoint() target is now required' );
target = new Vector3();
}
return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
},
intersectLine: function ( line, target ) {
if ( target === undefined ) {
console.warn( 'THREE.Plane: .intersectLine() target is now required' );
target = new Vector3();
}
var direction = line.delta( _vector1 );
var denominator = this.normal.dot( direction );
if ( denominator === 0 ) {
// line is coplanar, return origin
if ( this.distanceToPoint( line.start ) === 0 ) {
return target.copy( line.start );
}
// Unsure if this is the correct method to handle this case.
return undefined;
}
var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
if ( t < 0 || t > 1 ) {
return undefined;
}
return target.copy( direction ).multiplyScalar( t ).add( line.start );
},
intersectsLine: function ( line ) {
// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
var startSign = this.distanceToPoint( line.start );
var endSign = this.distanceToPoint( line.end );
return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
},
intersectsBox: function ( box ) {
return box.intersectsPlane( this );
},
intersectsSphere: function ( sphere ) {
return sphere.intersectsPlane( this );
},
coplanarPoint: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
target = new Vector3();
}
return target.copy( this.normal ).multiplyScalar( - this.constant );
},
applyMatrix4: function ( matrix, optionalNormalMatrix ) {
var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
var referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
this.constant = - referencePoint.dot( normal );
return this;
},
translate: function ( offset ) {
this.constant -= offset.dot( this.normal );
return this;
},
equals: function ( plane ) {
return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
}
} );
/**
* @author bhouston / http://clara.io
* @author mrdoob / http://mrdoob.com/
*/
var _v0$1 = new Vector3();
var _v1$3 = new Vector3();
var _v2$1 = new Vector3();
var _v3 = new Vector3();
var _vab = new Vector3();
var _vac = new Vector3();
var _vbc = new Vector3();
var _vap = new Vector3();
var _vbp = new Vector3();
var _vcp = new Vector3();
function Triangle( a, b, c ) {
this.a = ( a !== undefined ) ? a : new Vector3();
this.b = ( b !== undefined ) ? b : new Vector3();
this.c = ( c !== undefined ) ? c : new Vector3();
}
Object.assign( Triangle, {
getNormal: function ( a, b, c, target ) {
if ( target === undefined ) {
console.warn( 'THREE.Triangle: .getNormal() target is now required' );
target = new Vector3();
}
target.subVectors( c, b );
_v0$1.subVectors( a, b );
target.cross( _v0$1 );
var targetLengthSq = target.lengthSq();
if ( targetLengthSq > 0 ) {
return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
}
return target.set( 0, 0, 0 );
},
// static/instance method to calculate barycentric coordinates
// based on: http://www.blackpawn.com/texts/pointinpoly/default.html
getBarycoord: function ( point, a, b, c, target ) {
_v0$1.subVectors( c, a );
_v1$3.subVectors( b, a );
_v2$1.subVectors( point, a );
var dot00 = _v0$1.dot( _v0$1 );
var dot01 = _v0$1.dot( _v1$3 );
var dot02 = _v0$1.dot( _v2$1 );
var dot11 = _v1$3.dot( _v1$3 );
var dot12 = _v1$3.dot( _v2$1 );
var denom = ( dot00 * dot11 - dot01 * dot01 );
if ( target === undefined ) {
console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
target = new Vector3();
}
// collinear or singular triangle
if ( denom === 0 ) {
// arbitrary location outside of triangle?
// not sure if this is the best idea, maybe should be returning undefined
return target.set( - 2, - 1, - 1 );
}
var invDenom = 1 / denom;
var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
// barycentric coordinates must always sum to 1
return target.set( 1 - u - v, v, u );
},
containsPoint: function ( point, a, b, c ) {
Triangle.getBarycoord( point, a, b, c, _v3 );
return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );
},
getUV: function ( point, p1, p2, p3, uv1, uv2, uv3, target ) {
this.getBarycoord( point, p1, p2, p3, _v3 );
target.set( 0, 0 );
target.addScaledVector( uv1, _v3.x );
target.addScaledVector( uv2, _v3.y );
target.addScaledVector( uv3, _v3.z );
return target;
},
isFrontFacing: function ( a, b, c, direction ) {
_v0$1.subVectors( c, b );
_v1$3.subVectors( a, b );
// strictly front facing
return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
}
} );
Object.assign( Triangle.prototype, {
set: function ( a, b, c ) {
this.a.copy( a );
this.b.copy( b );
this.c.copy( c );
return this;
},
setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
this.a.copy( points[ i0 ] );
this.b.copy( points[ i1 ] );
this.c.copy( points[ i2 ] );
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( triangle ) {
this.a.copy( triangle.a );
this.b.copy( triangle.b );
this.c.copy( triangle.c );
return this;
},
getArea: function () {
_v0$1.subVectors( this.c, this.b );
_v1$3.subVectors( this.a, this.b );
return _v0$1.cross( _v1$3 ).length() * 0.5;
},
getMidpoint: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
target = new Vector3();
}
return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
},
getNormal: function ( target ) {
return Triangle.getNormal( this.a, this.b, this.c, target );
},
getPlane: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Triangle: .getPlane() target is now required' );
target = new Plane();
}
return target.setFromCoplanarPoints( this.a, this.b, this.c );
},
getBarycoord: function ( point, target ) {
return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
},
getUV: function ( point, uv1, uv2, uv3, target ) {
return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
},
containsPoint: function ( point ) {
return Triangle.containsPoint( point, this.a, this.b, this.c );
},
isFrontFacing: function ( direction ) {
return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
},
intersectsBox: function ( box ) {
return box.intersectsTriangle( this );
},
closestPointToPoint: function ( p, target ) {
if ( target === undefined ) {
console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
target = new Vector3();
}
var a = this.a, b = this.b, c = this.c;
var v, w;
// algorithm thanks to Real-Time Collision Detection by Christer Ericson,
// published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
// under the accompanying license; see chapter 5.1.5 for detailed explanation.
// basically, we're distinguishing which of the voronoi regions of the triangle
// the point lies in with the minimum amount of redundant computation.
_vab.subVectors( b, a );
_vac.subVectors( c, a );
_vap.subVectors( p, a );
var d1 = _vab.dot( _vap );
var d2 = _vac.dot( _vap );
if ( d1 <= 0 && d2 <= 0 ) {
// vertex region of A; barycentric coords (1, 0, 0)
return target.copy( a );
}
_vbp.subVectors( p, b );
var d3 = _vab.dot( _vbp );
var d4 = _vac.dot( _vbp );
if ( d3 >= 0 && d4 <= d3 ) {
// vertex region of B; barycentric coords (0, 1, 0)
return target.copy( b );
}
var vc = d1 * d4 - d3 * d2;
if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
v = d1 / ( d1 - d3 );
// edge region of AB; barycentric coords (1-v, v, 0)
return target.copy( a ).addScaledVector( _vab, v );
}
_vcp.subVectors( p, c );
var d5 = _vab.dot( _vcp );
var d6 = _vac.dot( _vcp );
if ( d6 >= 0 && d5 <= d6 ) {
// vertex region of C; barycentric coords (0, 0, 1)
return target.copy( c );
}
var vb = d5 * d2 - d1 * d6;
if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
w = d2 / ( d2 - d6 );
// edge region of AC; barycentric coords (1-w, 0, w)
return target.copy( a ).addScaledVector( _vac, w );
}
var va = d3 * d6 - d5 * d4;
if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
_vbc.subVectors( c, b );
w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
// edge region of BC; barycentric coords (0, 1-w, w)
return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
}
// face region
var denom = 1 / ( va + vb + vc );
// u = va * denom
v = vb * denom;
w = vc * denom;
return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
},
equals: function ( triangle ) {
return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
var _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
var _hslA = { h: 0, s: 0, l: 0 };
var _hslB = { h: 0, s: 0, l: 0 };
function Color( r, g, b ) {
if ( g === undefined && b === undefined ) {
// r is THREE.Color, hex or string
return this.set( r );
}
return this.setRGB( r, g, b );
}
function hue2rgb( p, q, t ) {
if ( t < 0 ) t += 1;
if ( t > 1 ) t -= 1;
if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
if ( t < 1 / 2 ) return q;
if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
return p;
}
function SRGBToLinear( c ) {
return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
}
function LinearToSRGB( c ) {
return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
}
Object.assign( Color.prototype, {
isColor: true,
r: 1, g: 1, b: 1,
set: function ( value ) {
if ( value && value.isColor ) {
this.copy( value );
} else if ( typeof value === 'number' ) {
this.setHex( value );
} else if ( typeof value === 'string' ) {
this.setStyle( value );
}
return this;
},
setScalar: function ( scalar ) {
this.r = scalar;
this.g = scalar;
this.b = scalar;
return this;
},
setHex: function ( hex ) {
hex = Math.floor( hex );
this.r = ( hex >> 16 & 255 ) / 255;
this.g = ( hex >> 8 & 255 ) / 255;
this.b = ( hex & 255 ) / 255;
return this;
},
setRGB: function ( r, g, b ) {
this.r = r;
this.g = g;
this.b = b;
return this;
},
setHSL: function ( h, s, l ) {
// h,s,l ranges are in 0.0 - 1.0
h = MathUtils.euclideanModulo( h, 1 );
s = MathUtils.clamp( s, 0, 1 );
l = MathUtils.clamp( l, 0, 1 );
if ( s === 0 ) {
this.r = this.g = this.b = l;
} else {
var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
var q = ( 2 * l ) - p;
this.r = hue2rgb( q, p, h + 1 / 3 );
this.g = hue2rgb( q, p, h );
this.b = hue2rgb( q, p, h - 1 / 3 );
}
return this;
},
setStyle: function ( style ) {
function handleAlpha( string ) {
if ( string === undefined ) return;
if ( parseFloat( string ) < 1 ) {
console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
}
}
var m;
if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
// rgb / hsl
var color;
var name = m[ 1 ];
var components = m[ 2 ];
switch ( name ) {
case 'rgb':
case 'rgba':
if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
// rgb(255,0,0) rgba(255,0,0,0.5)
this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
handleAlpha( color[ 5 ] );
return this;
}
if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
// rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
handleAlpha( color[ 5 ] );
return this;
}
break;
case 'hsl':
case 'hsla':
if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
// hsl(120,50%,50%) hsla(120,50%,50%,0.5)
var h = parseFloat( color[ 1 ] ) / 360;
var s = parseInt( color[ 2 ], 10 ) / 100;
var l = parseInt( color[ 3 ], 10 ) / 100;
handleAlpha( color[ 5 ] );
return this.setHSL( h, s, l );
}
break;
}
} else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
// hex color
var hex = m[ 1 ];
var size = hex.length;
if ( size === 3 ) {
// #ff0
this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
return this;
} else if ( size === 6 ) {
// #ff0000
this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
return this;
}
}
if ( style && style.length > 0 ) {
return this.setColorName( style );
}
return this;
},
setColorName: function ( style ) {
// color keywords
var hex = _colorKeywords[ style ];
if ( hex !== undefined ) {
// red
this.setHex( hex );
} else {
// unknown color
console.warn( 'THREE.Color: Unknown color ' + style );
}
return this;
},
clone: function () {
return new this.constructor( this.r, this.g, this.b );
},
copy: function ( color ) {
this.r = color.r;
this.g = color.g;
this.b = color.b;
return this;
},
copyGammaToLinear: function ( color, gammaFactor ) {
if ( gammaFactor === undefined ) gammaFactor = 2.0;
this.r = Math.pow( color.r, gammaFactor );
this.g = Math.pow( color.g, gammaFactor );
this.b = Math.pow( color.b, gammaFactor );
return this;
},
copyLinearToGamma: function ( color, gammaFactor ) {
if ( gammaFactor === undefined ) gammaFactor = 2.0;
var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
this.r = Math.pow( color.r, safeInverse );
this.g = Math.pow( color.g, safeInverse );
this.b = Math.pow( color.b, safeInverse );
return this;
},
convertGammaToLinear: function ( gammaFactor ) {
this.copyGammaToLinear( this, gammaFactor );
return this;
},
convertLinearToGamma: function ( gammaFactor ) {
this.copyLinearToGamma( this, gammaFactor );
return this;
},
copySRGBToLinear: function ( color ) {
this.r = SRGBToLinear( color.r );
this.g = SRGBToLinear( color.g );
this.b = SRGBToLinear( color.b );
return this;
},
copyLinearToSRGB: function ( color ) {
this.r = LinearToSRGB( color.r );
this.g = LinearToSRGB( color.g );
this.b = LinearToSRGB( color.b );
return this;
},
convertSRGBToLinear: function () {
this.copySRGBToLinear( this );
return this;
},
convertLinearToSRGB: function () {
this.copyLinearToSRGB( this );
return this;
},
getHex: function () {
return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
},
getHexString: function () {
return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
},
getHSL: function ( target ) {
// h,s,l ranges are in 0.0 - 1.0
if ( target === undefined ) {
console.warn( 'THREE.Color: .getHSL() target is now required' );
target = { h: 0, s: 0, l: 0 };
}
var r = this.r, g = this.g, b = this.b;
var max = Math.max( r, g, b );
var min = Math.min( r, g, b );
var hue, saturation;
var lightness = ( min + max ) / 2.0;
if ( min === max ) {
hue = 0;
saturation = 0;
} else {
var delta = max - min;
saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
switch ( max ) {
case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
case g: hue = ( b - r ) / delta + 2; break;
case b: hue = ( r - g ) / delta + 4; break;
}
hue /= 6;
}
target.h = hue;
target.s = saturation;
target.l = lightness;
return target;
},
getStyle: function () {
return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
},
offsetHSL: function ( h, s, l ) {
this.getHSL( _hslA );
_hslA.h += h; _hslA.s += s; _hslA.l += l;
this.setHSL( _hslA.h, _hslA.s, _hslA.l );
return this;
},
add: function ( color ) {
this.r += color.r;
this.g += color.g;
this.b += color.b;
return this;
},
addColors: function ( color1, color2 ) {
this.r = color1.r + color2.r;
this.g = color1.g + color2.g;
this.b = color1.b + color2.b;
return this;
},
addScalar: function ( s ) {
this.r += s;
this.g += s;
this.b += s;
return this;
},
sub: function ( color ) {
this.r = Math.max( 0, this.r - color.r );
this.g = Math.max( 0, this.g - color.g );
this.b = Math.max( 0, this.b - color.b );
return this;
},
multiply: function ( color ) {
this.r *= color.r;
this.g *= color.g;
this.b *= color.b;
return this;
},
multiplyScalar: function ( s ) {
this.r *= s;
this.g *= s;
this.b *= s;
return this;
},
lerp: function ( color, alpha ) {
this.r += ( color.r - this.r ) * alpha;
this.g += ( color.g - this.g ) * alpha;
this.b += ( color.b - this.b ) * alpha;
return this;
},
lerpHSL: function ( color, alpha ) {
this.getHSL( _hslA );
color.getHSL( _hslB );
var h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
var s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
var l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );
this.setHSL( h, s, l );
return this;
},
equals: function ( c ) {
return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
this.r = array[ offset ];
this.g = array[ offset + 1 ];
this.b = array[ offset + 2 ];
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this.r;
array[ offset + 1 ] = this.g;
array[ offset + 2 ] = this.b;
return array;
},
toJSON: function () {
return this.getHex();
}
} );
Color.NAMES = _colorKeywords;
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
function Face3( a, b, c, normal, color, materialIndex ) {
this.a = a;
this.b = b;
this.c = c;
this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
this.vertexNormals = Array.isArray( normal ) ? normal : [];
this.color = ( color && color.isColor ) ? color : new Color();
this.vertexColors = Array.isArray( color ) ? color : [];
this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
}
Object.assign( Face3.prototype, {
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( source ) {
this.a = source.a;
this.b = source.b;
this.c = source.c;
this.normal.copy( source.normal );
this.color.copy( source.color );
this.materialIndex = source.materialIndex;
for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
}
for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
this.vertexColors[ i ] = source.vertexColors[ i ].clone();
}
return this;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
var materialId = 0;
function Material() {
Object.defineProperty( this, 'id', { value: materialId ++ } );
this.uuid = MathUtils.generateUUID();
this.name = '';
this.type = 'Material';
this.fog = true;
this.blending = NormalBlending;
this.side = FrontSide;
this.flatShading = false;
this.vertexColors = false;
this.opacity = 1;
this.transparent = false;
this.blendSrc = SrcAlphaFactor;
this.blendDst = OneMinusSrcAlphaFactor;
this.blendEquation = AddEquation;
this.blendSrcAlpha = null;
this.blendDstAlpha = null;
this.blendEquationAlpha = null;
this.depthFunc = LessEqualDepth;
this.depthTest = true;
this.depthWrite = true;
this.stencilWriteMask = 0xff;
this.stencilFunc = AlwaysStencilFunc;
this.stencilRef = 0;
this.stencilFuncMask = 0xff;
this.stencilFail = KeepStencilOp;
this.stencilZFail = KeepStencilOp;
this.stencilZPass = KeepStencilOp;
this.stencilWrite = false;
this.clippingPlanes = null;
this.clipIntersection = false;
this.clipShadows = false;
this.shadowSide = null;
this.colorWrite = true;
this.precision = null; // override the renderer's default precision for this material
this.polygonOffset = false;
this.polygonOffsetFactor = 0;
this.polygonOffsetUnits = 0;
this.dithering = false;
this.alphaTest = 0;
this.premultipliedAlpha = false;
this.visible = true;
this.toneMapped = true;
this.userData = {};
this.version = 0;
}
Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
constructor: Material,
isMaterial: true,
onBeforeCompile: function () {},
setValues: function ( values ) {
if ( values === undefined ) return;
for ( var key in values ) {
var newValue = values[ key ];
if ( newValue === undefined ) {
console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
continue;
}
// for backward compatability if shading is set in the constructor
if ( key === 'shading' ) {
console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
this.flatShading = ( newValue === FlatShading ) ? true : false;
continue;
}
var currentValue = this[ key ];
if ( currentValue === undefined ) {
console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
continue;
}
if ( currentValue && currentValue.isColor ) {
currentValue.set( newValue );
} else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
currentValue.copy( newValue );
} else {
this[ key ] = newValue;
}
}
},
toJSON: function ( meta ) {
var isRoot = ( meta === undefined || typeof meta === 'string' );
if ( isRoot ) {
meta = {
textures: {},
images: {}
};
}
var data = {
metadata: {
version: 4.5,
type: 'Material',
generator: 'Material.toJSON'
}
};
// standard Material serialization
data.uuid = this.uuid;
data.type = this.type;
if ( this.name !== '' ) data.name = this.name;
if ( this.color && this.color.isColor ) data.color = this.color.getHex();
if ( this.roughness !== undefined ) data.roughness = this.roughness;
if ( this.metalness !== undefined ) data.metalness = this.metalness;
if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex();
if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
if ( this.shininess !== undefined ) data.shininess = this.shininess;
if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
}
if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
}
if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
}
if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
if ( this.aoMap && this.aoMap.isTexture ) {
data.aoMap = this.aoMap.toJSON( meta ).uuid;
data.aoMapIntensity = this.aoMapIntensity;
}
if ( this.bumpMap && this.bumpMap.isTexture ) {
data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
data.bumpScale = this.bumpScale;
}
if ( this.normalMap && this.normalMap.isTexture ) {
data.normalMap = this.normalMap.toJSON( meta ).uuid;
data.normalMapType = this.normalMapType;
data.normalScale = this.normalScale.toArray();
}
if ( this.displacementMap && this.displacementMap.isTexture ) {
data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
data.displacementScale = this.displacementScale;
data.displacementBias = this.displacementBias;
}
if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
if ( this.envMap && this.envMap.isTexture ) {
data.envMap = this.envMap.toJSON( meta ).uuid;
data.reflectivity = this.reflectivity; // Scale behind envMap
data.refractionRatio = this.refractionRatio;
if ( this.combine !== undefined ) data.combine = this.combine;
if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
}
if ( this.gradientMap && this.gradientMap.isTexture ) {
data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
}
if ( this.size !== undefined ) data.size = this.size;
if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
if ( this.blending !== NormalBlending ) data.blending = this.blending;
if ( this.flatShading === true ) data.flatShading = this.flatShading;
if ( this.side !== FrontSide ) data.side = this.side;
if ( this.vertexColors ) data.vertexColors = true;
if ( this.opacity < 1 ) data.opacity = this.opacity;
if ( this.transparent === true ) data.transparent = this.transparent;
data.depthFunc = this.depthFunc;
data.depthTest = this.depthTest;
data.depthWrite = this.depthWrite;
data.stencilWrite = this.stencilWrite;
data.stencilWriteMask = this.stencilWriteMask;
data.stencilFunc = this.stencilFunc;
data.stencilRef = this.stencilRef;
data.stencilFuncMask = this.stencilFuncMask;
data.stencilFail = this.stencilFail;
data.stencilZFail = this.stencilZFail;
data.stencilZPass = this.stencilZPass;
// rotation (SpriteMaterial)
if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
if ( this.polygonOffset === true ) data.polygonOffset = true;
if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
if ( this.scale !== undefined ) data.scale = this.scale;
if ( this.dithering === true ) data.dithering = true;
if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
if ( this.wireframe === true ) data.wireframe = this.wireframe;
if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
if ( this.morphTargets === true ) data.morphTargets = true;
if ( this.morphNormals === true ) data.morphNormals = true;
if ( this.skinning === true ) data.skinning = true;
if ( this.visible === false ) data.visible = false;
if ( this.toneMapped === false ) data.toneMapped = false;
if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
// TODO: Copied from Object3D.toJSON
function extractFromCache( cache ) {
var values = [];
for ( var key in cache ) {
var data = cache[ key ];
delete data.metadata;
values.push( data );
}
return values;
}
if ( isRoot ) {
var textures = extractFromCache( meta.textures );
var images = extractFromCache( meta.images );
if ( textures.length > 0 ) data.textures = textures;
if ( images.length > 0 ) data.images = images;
}
return data;
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( source ) {
this.name = source.name;
this.fog = source.fog;
this.blending = source.blending;
this.side = source.side;
this.flatShading = source.flatShading;
this.vertexColors = source.vertexColors;
this.opacity = source.opacity;
this.transparent = source.transparent;
this.blendSrc = source.blendSrc;
this.blendDst = source.blendDst;
this.blendEquation = source.blendEquation;
this.blendSrcAlpha = source.blendSrcAlpha;
this.blendDstAlpha = source.blendDstAlpha;
this.blendEquationAlpha = source.blendEquationAlpha;
this.depthFunc = source.depthFunc;
this.depthTest = source.depthTest;
this.depthWrite = source.depthWrite;
this.stencilWriteMask = source.stencilWriteMask;
this.stencilFunc = source.stencilFunc;
this.stencilRef = source.stencilRef;
this.stencilFuncMask = source.stencilFuncMask;
this.stencilFail = source.stencilFail;
this.stencilZFail = source.stencilZFail;
this.stencilZPass = source.stencilZPass;
this.stencilWrite = source.stencilWrite;
var srcPlanes = source.clippingPlanes,
dstPlanes = null;
if ( srcPlanes !== null ) {
var n = srcPlanes.length;
dstPlanes = new Array( n );
for ( var i = 0; i !== n; ++ i )
dstPlanes[ i ] = srcPlanes[ i ].clone();
}
this.clippingPlanes = dstPlanes;
this.clipIntersection = source.clipIntersection;
this.clipShadows = source.clipShadows;
this.shadowSide = source.shadowSide;
this.colorWrite = source.colorWrite;
this.precision = source.precision;
this.polygonOffset = source.polygonOffset;
this.polygonOffsetFactor = source.polygonOffsetFactor;
this.polygonOffsetUnits = source.polygonOffsetUnits;
this.dithering = source.dithering;
this.alphaTest = source.alphaTest;
this.premultipliedAlpha = source.premultipliedAlpha;
this.visible = source.visible;
this.toneMapped = source.toneMapped;
this.userData = JSON.parse( JSON.stringify( source.userData ) );
return this;
},
dispose: function () {
this.dispatchEvent( { type: 'dispose' } );
}
} );
Object.defineProperty( Material.prototype, 'needsUpdate', {
set: function ( value ) {
if ( value === true ) this.version ++;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* opacity: <float>,
* map: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
* lightMapIntensity: <float>
*
* aoMap: new THREE.Texture( <Image> ),
* aoMapIntensity: <float>
*
* specularMap: new THREE.Texture( <Image> ),
*
* alphaMap: new THREE.Texture( <Image> ),
*
* envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
* combine: THREE.Multiply,
* reflectivity: <float>,
* refractionRatio: <float>,
*
* depthTest: <bool>,
* depthWrite: <bool>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* skinning: <bool>,
* morphTargets: <bool>
* }
*/
function MeshBasicMaterial( parameters ) {
Material.call( this );
this.type = 'MeshBasicMaterial';
this.color = new Color( 0xffffff ); // emissive
this.map = null;
this.lightMap = null;
this.lightMapIntensity = 1.0;
this.aoMap = null;
this.aoMapIntensity = 1.0;
this.specularMap = null;
this.alphaMap = null;
this.envMap = null;
this.combine = MultiplyOperation;
this.reflectivity = 1;
this.refractionRatio = 0.98;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.wireframeLinecap = 'round';
this.wireframeLinejoin = 'round';
this.skinning = false;
this.morphTargets = false;
this.setValues( parameters );
}
MeshBasicMaterial.prototype = Object.create( Material.prototype );
MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
MeshBasicMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.color.copy( source.color );
this.map = source.map;
this.lightMap = source.lightMap;
this.lightMapIntensity = source.lightMapIntensity;
this.aoMap = source.aoMap;
this.aoMapIntensity = source.aoMapIntensity;
this.specularMap = source.specularMap;
this.alphaMap = source.alphaMap;
this.envMap = source.envMap;
this.combine = source.combine;
this.reflectivity = source.reflectivity;
this.refractionRatio = source.refractionRatio;
this.wireframe = source.wireframe;
this.wireframeLinewidth = source.wireframeLinewidth;
this.wireframeLinecap = source.wireframeLinecap;
this.wireframeLinejoin = source.wireframeLinejoin;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
return this;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
var _vector$3 = new Vector3();
function BufferAttribute( array, itemSize, normalized ) {
if ( Array.isArray( array ) ) {
throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
}
this.name = '';
this.array = array;
this.itemSize = itemSize;
this.count = array !== undefined ? array.length / itemSize : 0;
this.normalized = normalized === true;
this.usage = StaticDrawUsage;
this.updateRange = { offset: 0, count: - 1 };
this.version = 0;
}
Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
set: function ( value ) {
if ( value === true ) this.version ++;
}
} );
Object.assign( BufferAttribute.prototype, {
isBufferAttribute: true,
onUploadCallback: function () {},
setUsage: function ( value ) {
this.usage = value;
return this;
},
copy: function ( source ) {
this.name = source.name;
this.array = new source.array.constructor( source.array );
this.itemSize = source.itemSize;
this.count = source.count;
this.normalized = source.normalized;
this.usage = source.usage;
return this;
},
copyAt: function ( index1, attribute, index2 ) {
index1 *= this.itemSize;
index2 *= attribute.itemSize;
for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
this.array[ index1 + i ] = attribute.array[ index2 + i ];
}
return this;
},
copyArray: function ( array ) {
this.array.set( array );
return this;
},
copyColorsArray: function ( colors ) {
var array = this.array, offset = 0;
for ( var i = 0, l = colors.length; i < l; i ++ ) {
var color = colors[ i ];
if ( color === undefined ) {
console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
color = new Color();
}
array[ offset ++ ] = color.r;
array[ offset ++ ] = color.g;
array[ offset ++ ] = color.b;
}
return this;
},
copyVector2sArray: function ( vectors ) {
var array = this.array, offset = 0;
for ( var i = 0, l = vectors.length; i < l; i ++ ) {
var vector = vectors[ i ];
if ( vector === undefined ) {
console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
vector = new Vector2();
}
array[ offset ++ ] = vector.x;
array[ offset ++ ] = vector.y;
}
return this;
},
copyVector3sArray: function ( vectors ) {
var array = this.array, offset = 0;
for ( var i = 0, l = vectors.length; i < l; i ++ ) {
var vector = vectors[ i ];
if ( vector === undefined ) {
console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
vector = new Vector3();
}
array[ offset ++ ] = vector.x;
array[ offset ++ ] = vector.y;
array[ offset ++ ] = vector.z;
}
return this;
},
copyVector4sArray: function ( vectors ) {
var array = this.array, offset = 0;
for ( var i = 0, l = vectors.length; i < l; i ++ ) {
var vector = vectors[ i ];
if ( vector === undefined ) {
console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
vector = new Vector4();
}
array[ offset ++ ] = vector.x;
array[ offset ++ ] = vector.y;
array[ offset ++ ] = vector.z;
array[ offset ++ ] = vector.w;
}
return this;
},
applyMatrix3: function ( m ) {
for ( var i = 0, l = this.count; i < l; i ++ ) {
_vector$3.x = this.getX( i );
_vector$3.y = this.getY( i );
_vector$3.z = this.getZ( i );
_vector$3.applyMatrix3( m );
this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
}
return this;
},
applyMatrix4: function ( m ) {
for ( var i = 0, l = this.count; i < l; i ++ ) {
_vector$3.x = this.getX( i );
_vector$3.y = this.getY( i );
_vector$3.z = this.getZ( i );
_vector$3.applyMatrix4( m );
this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
}
return this;
},
applyNormalMatrix: function ( m ) {
for ( var i = 0, l = this.count; i < l; i ++ ) {
_vector$3.x = this.getX( i );
_vector$3.y = this.getY( i );
_vector$3.z = this.getZ( i );
_vector$3.applyNormalMatrix( m );
this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
}
return this;
},
transformDirection: function ( m ) {
for ( var i = 0, l = this.count; i < l; i ++ ) {
_vector$3.x = this.getX( i );
_vector$3.y = this.getY( i );
_vector$3.z = this.getZ( i );
_vector$3.transformDirection( m );
this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
}
return this;
},
set: function ( value, offset ) {
if ( offset === undefined ) offset = 0;
this.array.set( value, offset );
return this;
},
getX: function ( index ) {
return this.array[ index * this.itemSize ];
},
setX: function ( index, x ) {
this.array[ index * this.itemSize ] = x;
return this;
},
getY: function ( index ) {
return this.array[ index * this.itemSize + 1 ];
},
setY: function ( index, y ) {
this.array[ index * this.itemSize + 1 ] = y;
return this;
},
getZ: function ( index ) {
return this.array[ index * this.itemSize + 2 ];
},
setZ: function ( index, z ) {
this.array[ index * this.itemSize + 2 ] = z;
return this;
},
getW: function ( index ) {
return this.array[ index * this.itemSize + 3 ];
},
setW: function ( index, w ) {
this.array[ index * this.itemSize + 3 ] = w;
return this;
},
setXY: function ( index, x, y ) {
index *= this.itemSize;
this.array[ index + 0 ] = x;
this.array[ index + 1 ] = y;
return this;
},
setXYZ: function ( index, x, y, z ) {
index *= this.itemSize;
this.array[ index + 0 ] = x;
this.array[ index + 1 ] = y;
this.array[ index + 2 ] = z;
return this;
},
setXYZW: function ( index, x, y, z, w ) {
index *= this.itemSize;
this.array[ index + 0 ] = x;
this.array[ index + 1 ] = y;
this.array[ index + 2 ] = z;
this.array[ index + 3 ] = w;
return this;
},
onUpload: function ( callback ) {
this.onUploadCallback = callback;
return this;
},
clone: function () {
return new this.constructor( this.array, this.itemSize ).copy( this );
},
toJSON: function () {
return {
itemSize: this.itemSize,
type: this.array.constructor.name,
array: Array.prototype.slice.call( this.array ),
normalized: this.normalized
};
}
} );
//
function Int8BufferAttribute( array, itemSize, normalized ) {
BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
}
Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
function Uint8BufferAttribute( array, itemSize, normalized ) {
BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
}
Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
}
Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
function Int16BufferAttribute( array, itemSize, normalized ) {
BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
}
Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
function Uint16BufferAttribute( array, itemSize, normalized ) {
BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
}
Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
function Int32BufferAttribute( array, itemSize, normalized ) {
BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
}
Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
function Uint32BufferAttribute( array, itemSize, normalized ) {
BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
}
Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
function Float32BufferAttribute( array, itemSize, normalized ) {
BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
}
Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
function Float64BufferAttribute( array, itemSize, normalized ) {
BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
}
Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
/**
* @author mrdoob / http://mrdoob.com/
*/
function DirectGeometry() {
this.vertices = [];
this.normals = [];
this.colors = [];
this.uvs = [];
this.uvs2 = [];
this.groups = [];
this.morphTargets = {};
this.skinWeights = [];
this.skinIndices = [];
// this.lineDistances = [];
this.boundingBox = null;
this.boundingSphere = null;
// update flags
this.verticesNeedUpdate = false;
this.normalsNeedUpdate = false;
this.colorsNeedUpdate = false;
this.uvsNeedUpdate = false;
this.groupsNeedUpdate = false;
}
Object.assign( DirectGeometry.prototype, {
computeGroups: function ( geometry ) {
var group;
var groups = [];
var materialIndex = undefined;
var faces = geometry.faces;
for ( var i = 0; i < faces.length; i ++ ) {
var face = faces[ i ];
// materials
if ( face.materialIndex !== materialIndex ) {
materialIndex = face.materialIndex;
if ( group !== undefined ) {
group.count = ( i * 3 ) - group.start;
groups.push( group );
}
group = {
start: i * 3,
materialIndex: materialIndex
};
}
}
if ( group !== undefined ) {
group.count = ( i * 3 ) - group.start;
groups.push( group );
}
this.groups = groups;
},
fromGeometry: function ( geometry ) {
var faces = geometry.faces;
var vertices = geometry.vertices;
var faceVertexUvs = geometry.faceVertexUvs;
var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
// morphs
var morphTargets = geometry.morphTargets;
var morphTargetsLength = morphTargets.length;
var morphTargetsPosition;
if ( morphTargetsLength > 0 ) {
morphTargetsPosition = [];
for ( var i = 0; i < morphTargetsLength; i ++ ) {
morphTargetsPosition[ i ] = {
name: morphTargets[ i ].name,
data: []
};
}
this.morphTargets.position = morphTargetsPosition;
}
var morphNormals = geometry.morphNormals;
var morphNormalsLength = morphNormals.length;
var morphTargetsNormal;
if ( morphNormalsLength > 0 ) {
morphTargetsNormal = [];
for ( var i = 0; i < morphNormalsLength; i ++ ) {
morphTargetsNormal[ i ] = {
name: morphNormals[ i ].name,
data: []
};
}
this.morphTargets.normal = morphTargetsNormal;
}
// skins
var skinIndices = geometry.skinIndices;
var skinWeights = geometry.skinWeights;
var hasSkinIndices = skinIndices.length === vertices.length;
var hasSkinWeights = skinWeights.length === vertices.length;
//
if ( vertices.length > 0 && faces.length === 0 ) {
console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
}
for ( var i = 0; i < faces.length; i ++ ) {
var face = faces[ i ];
this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
var vertexNormals = face.vertexNormals;
if ( vertexNormals.length === 3 ) {
this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
} else {
var normal = face.normal;
this.normals.push( normal, normal, normal );
}
var vertexColors = face.vertexColors;
if ( vertexColors.length === 3 ) {
this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
} else {
var color = face.color;
this.colors.push( color, color, color );
}
if ( hasFaceVertexUv === true ) {
var vertexUvs = faceVertexUvs[ 0 ][ i ];
if ( vertexUvs !== undefined ) {
this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
} else {
console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
}
}
if ( hasFaceVertexUv2 === true ) {
var vertexUvs = faceVertexUvs[ 1 ][ i ];
if ( vertexUvs !== undefined ) {
this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
} else {
console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
}
}
// morphs
for ( var j = 0; j < morphTargetsLength; j ++ ) {
var morphTarget = morphTargets[ j ].vertices;
morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
}
for ( var j = 0; j < morphNormalsLength; j ++ ) {
var morphNormal = morphNormals[ j ].vertexNormals[ i ];
morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
}
// skins
if ( hasSkinIndices ) {
this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
}
if ( hasSkinWeights ) {
this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
}
}
this.computeGroups( geometry );
this.verticesNeedUpdate = geometry.verticesNeedUpdate;
this.normalsNeedUpdate = geometry.normalsNeedUpdate;
this.colorsNeedUpdate = geometry.colorsNeedUpdate;
this.uvsNeedUpdate = geometry.uvsNeedUpdate;
this.groupsNeedUpdate = geometry.groupsNeedUpdate;
if ( geometry.boundingSphere !== null ) {
this.boundingSphere = geometry.boundingSphere.clone();
}
if ( geometry.boundingBox !== null ) {
this.boundingBox = geometry.boundingBox.clone();
}
return this;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function arrayMax( array ) {
if ( array.length === 0 ) return - Infinity;
var max = array[ 0 ];
for ( var i = 1, l = array.length; i < l; ++ i ) {
if ( array[ i ] > max ) max = array[ i ];
}
return max;
}
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
var _m1$2 = new Matrix4();
var _obj = new Object3D();
var _offset = new Vector3();
var _box$2 = new Box3();
var _boxMorphTargets = new Box3();
var _vector$4 = new Vector3();
function BufferGeometry() {
Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );
this.uuid = MathUtils.generateUUID();
this.name = '';
this.type = 'BufferGeometry';
this.index = null;
this.attributes = {};
this.morphAttributes = {};
this.morphTargetsRelative = false;
this.groups = [];
this.boundingBox = null;
this.boundingSphere = null;
this.drawRange = { start: 0, count: Infinity };
this.userData = {};
}
BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
constructor: BufferGeometry,
isBufferGeometry: true,
getIndex: function () {
return this.index;
},
setIndex: function ( index ) {
if ( Array.isArray( index ) ) {
this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
} else {
this.index = index;
}
},
getAttribute: function ( name ) {
return this.attributes[ name ];
},
setAttribute: function ( name, attribute ) {
this.attributes[ name ] = attribute;
return this;
},
deleteAttribute: function ( name ) {
delete this.attributes[ name ];
return this;
},
addGroup: function ( start, count, materialIndex ) {
this.groups.push( {
start: start,
count: count,
materialIndex: materialIndex !== undefined ? materialIndex : 0
} );
},
clearGroups: function () {
this.groups = [];
},
setDrawRange: function ( start, count ) {
this.drawRange.start = start;
this.drawRange.count = count;
},
applyMatrix4: function ( matrix ) {
var position = this.attributes.position;
if ( position !== undefined ) {
position.applyMatrix4( matrix );
position.needsUpdate = true;
}
var normal = this.attributes.normal;
if ( normal !== undefined ) {
var normalMatrix = new Matrix3().getNormalMatrix( matrix );
normal.applyNormalMatrix( normalMatrix );
normal.needsUpdate = true;
}
var tangent = this.attributes.tangent;
if ( tangent !== undefined ) {
tangent.transformDirection( matrix );
tangent.needsUpdate = true;
}
if ( this.boundingBox !== null ) {
this.computeBoundingBox();
}
if ( this.boundingSphere !== null ) {
this.computeBoundingSphere();
}
return this;
},
rotateX: function ( angle ) {
// rotate geometry around world x-axis
_m1$2.makeRotationX( angle );
this.applyMatrix4( _m1$2 );
return this;
},
rotateY: function ( angle ) {
// rotate geometry around world y-axis
_m1$2.makeRotationY( angle );
this.applyMatrix4( _m1$2 );
return this;
},
rotateZ: function ( angle ) {
// rotate geometry around world z-axis
_m1$2.makeRotationZ( angle );
this.applyMatrix4( _m1$2 );
return this;
},
translate: function ( x, y, z ) {
// translate geometry
_m1$2.makeTranslation( x, y, z );
this.applyMatrix4( _m1$2 );
return this;
},
scale: function ( x, y, z ) {
// scale geometry
_m1$2.makeScale( x, y, z );
this.applyMatrix4( _m1$2 );
return this;
},
lookAt: function ( vector ) {
_obj.lookAt( vector );
_obj.updateMatrix();
this.applyMatrix4( _obj.matrix );
return this;
},
center: function () {
this.computeBoundingBox();
this.boundingBox.getCenter( _offset ).negate();
this.translate( _offset.x, _offset.y, _offset.z );
return this;
},
setFromObject: function ( object ) {
// console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
var geometry = object.geometry;
if ( object.isPoints || object.isLine ) {
var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
}
if ( geometry.boundingSphere !== null ) {
this.boundingSphere = geometry.boundingSphere.clone();
}
if ( geometry.boundingBox !== null ) {
this.boundingBox = geometry.boundingBox.clone();
}
} else if ( object.isMesh ) {
if ( geometry && geometry.isGeometry ) {
this.fromGeometry( geometry );
}
}
return this;
},
setFromPoints: function ( points ) {
var position = [];
for ( var i = 0, l = points.length; i < l; i ++ ) {
var point = points[ i ];
position.push( point.x, point.y, point.z || 0 );
}
this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
return this;
},
updateFromObject: function ( object ) {
var geometry = object.geometry;
if ( object.isMesh ) {
var direct = geometry.__directGeometry;
if ( geometry.elementsNeedUpdate === true ) {
direct = undefined;
geometry.elementsNeedUpdate = false;
}
if ( direct === undefined ) {
return this.fromGeometry( geometry );
}
direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
geometry.verticesNeedUpdate = false;
geometry.normalsNeedUpdate = false;
geometry.colorsNeedUpdate = false;
geometry.uvsNeedUpdate = false;
geometry.groupsNeedUpdate = false;
geometry = direct;
}
var attribute;
if ( geometry.verticesNeedUpdate === true ) {
attribute = this.attributes.position;
if ( attribute !== undefined ) {
attribute.copyVector3sArray( geometry.vertices );
attribute.needsUpdate = true;
}
geometry.verticesNeedUpdate = false;
}
if ( geometry.normalsNeedUpdate === true ) {
attribute = this.attributes.normal;
if ( attribute !== undefined ) {
attribute.copyVector3sArray( geometry.normals );
attribute.needsUpdate = true;
}
geometry.normalsNeedUpdate = false;
}
if ( geometry.colorsNeedUpdate === true ) {
attribute = this.attributes.color;
if ( attribute !== undefined ) {
attribute.copyColorsArray( geometry.colors );
attribute.needsUpdate = true;
}
geometry.colorsNeedUpdate = false;
}
if ( geometry.uvsNeedUpdate ) {
attribute = this.attributes.uv;
if ( attribute !== undefined ) {
attribute.copyVector2sArray( geometry.uvs );
attribute.needsUpdate = true;
}
geometry.uvsNeedUpdate = false;
}
if ( geometry.lineDistancesNeedUpdate ) {
attribute = this.attributes.lineDistance;
if ( attribute !== undefined ) {
attribute.copyArray( geometry.lineDistances );
attribute.needsUpdate = true;
}
geometry.lineDistancesNeedUpdate = false;
}
if ( geometry.groupsNeedUpdate ) {
geometry.computeGroups( object.geometry );
this.groups = geometry.groups;
geometry.groupsNeedUpdate = false;
}
return this;
},
fromGeometry: function ( geometry ) {
geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
return this.fromDirectGeometry( geometry.__directGeometry );
},
fromDirectGeometry: function ( geometry ) {
var positions = new Float32Array( geometry.vertices.length * 3 );
this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
if ( geometry.normals.length > 0 ) {
var normals = new Float32Array( geometry.normals.length * 3 );
this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
}
if ( geometry.colors.length > 0 ) {
var colors = new Float32Array( geometry.colors.length * 3 );
this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
}
if ( geometry.uvs.length > 0 ) {
var uvs = new Float32Array( geometry.uvs.length * 2 );
this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
}
if ( geometry.uvs2.length > 0 ) {
var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
}
// groups
this.groups = geometry.groups;
// morphs
for ( var name in geometry.morphTargets ) {
var array = [];
var morphTargets = geometry.morphTargets[ name ];
for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
var morphTarget = morphTargets[ i ];
var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
attribute.name = morphTarget.name;
array.push( attribute.copyVector3sArray( morphTarget.data ) );
}
this.morphAttributes[ name ] = array;
}
// skinning
if ( geometry.skinIndices.length > 0 ) {
var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
}
if ( geometry.skinWeights.length > 0 ) {
var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
}
//
if ( geometry.boundingSphere !== null ) {
this.boundingSphere = geometry.boundingSphere.clone();
}
if ( geometry.boundingBox !== null ) {
this.boundingBox = geometry.boundingBox.clone();
}
return this;
},
computeBoundingBox: function () {
if ( this.boundingBox === null ) {
this.boundingBox = new Box3();
}
var position = this.attributes.position;
var morphAttributesPosition = this.morphAttributes.position;
if ( position !== undefined ) {
this.boundingBox.setFromBufferAttribute( position );
// process morph attributes if present
if ( morphAttributesPosition ) {
for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
var morphAttribute = morphAttributesPosition[ i ];
_box$2.setFromBufferAttribute( morphAttribute );
if ( this.morphTargetsRelative ) {
_vector$4.addVectors( this.boundingBox.min, _box$2.min );
this.boundingBox.expandByPoint( _vector$4 );
_vector$4.addVectors( this.boundingBox.max, _box$2.max );
this.boundingBox.expandByPoint( _vector$4 );
} else {
this.boundingBox.expandByPoint( _box$2.min );
this.boundingBox.expandByPoint( _box$2.max );
}
}
}
} else {
this.boundingBox.makeEmpty();
}
if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
}
},
computeBoundingSphere: function () {
if ( this.boundingSphere === null ) {
this.boundingSphere = new Sphere();
}
var position = this.attributes.position;
var morphAttributesPosition = this.morphAttributes.position;
if ( position ) {
// first, find the center of the bounding sphere
var center = this.boundingSphere.center;
_box$2.setFromBufferAttribute( position );
// process morph attributes if present
if ( morphAttributesPosition ) {
for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
var morphAttribute = morphAttributesPosition[ i ];
_boxMorphTargets.setFromBufferAttribute( morphAttribute );
if ( this.morphTargetsRelative ) {
_vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
_box$2.expandByPoint( _vector$4 );
_vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
_box$2.expandByPoint( _vector$4 );
} else {
_box$2.expandByPoint( _boxMorphTargets.min );
_box$2.expandByPoint( _boxMorphTargets.max );
}
}
}
_box$2.getCenter( center );
// second, try to find a boundingSphere with a radius smaller than the
// boundingSphere of the boundingBox: sqrt(3) smaller in the best case
var maxRadiusSq = 0;
for ( var i = 0, il = position.count; i < il; i ++ ) {
_vector$4.fromBufferAttribute( position, i );
maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
}
// process morph attributes if present
if ( morphAttributesPosition ) {
for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
var morphAttribute = morphAttributesPosition[ i ];
var morphTargetsRelative = this.morphTargetsRelative;
for ( var j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
_vector$4.fromBufferAttribute( morphAttribute, j );
if ( morphTargetsRelative ) {
_offset.fromBufferAttribute( position, j );
_vector$4.add( _offset );
}
maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
}
}
}
this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
if ( isNaN( this.boundingSphere.radius ) ) {
console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
}
}
},
computeFaceNormals: function () {
// backwards compatibility
},
computeVertexNormals: function () {
var index = this.index;
var attributes = this.attributes;
if ( attributes.position ) {
var positions = attributes.position.array;
if ( attributes.normal === undefined ) {
this.setAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
} else {
// reset existing normals to zero
var array = attributes.normal.array;
for ( var i = 0, il = array.length; i < il; i ++ ) {
array[ i ] = 0;
}
}
var normals = attributes.normal.array;
var vA, vB, vC;
var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
var cb = new Vector3(), ab = new Vector3();
// indexed elements
if ( index ) {
var indices = index.array;
for ( var i = 0, il = index.count; i < il; i += 3 ) {
vA = indices[ i + 0 ] * 3;
vB = indices[ i + 1 ] * 3;
vC = indices[ i + 2 ] * 3;
pA.fromArray( positions, vA );
pB.fromArray( positions, vB );
pC.fromArray( positions, vC );
cb.subVectors( pC, pB );
ab.subVectors( pA, pB );
cb.cross( ab );
normals[ vA ] += cb.x;
normals[ vA + 1 ] += cb.y;
normals[ vA + 2 ] += cb.z;
normals[ vB ] += cb.x;
normals[ vB + 1 ] += cb.y;
normals[ vB + 2 ] += cb.z;
normals[ vC ] += cb.x;
normals[ vC + 1 ] += cb.y;
normals[ vC + 2 ] += cb.z;
}
} else {
// non-indexed elements (unconnected triangle soup)
for ( var i = 0, il = positions.length; i < il; i += 9 ) {
pA.fromArray( positions, i );
pB.fromArray( positions, i + 3 );
pC.fromArray( positions, i + 6 );
cb.subVectors( pC, pB );
ab.subVectors( pA, pB );
cb.cross( ab );
normals[ i ] = cb.x;
normals[ i + 1 ] = cb.y;
normals[ i + 2 ] = cb.z;
normals[ i + 3 ] = cb.x;
normals[ i + 4 ] = cb.y;
normals[ i + 5 ] = cb.z;
normals[ i + 6 ] = cb.x;
normals[ i + 7 ] = cb.y;
normals[ i + 8 ] = cb.z;
}
}
this.normalizeNormals();
attributes.normal.needsUpdate = true;
}
},
merge: function ( geometry, offset ) {
if ( ! ( geometry && geometry.isBufferGeometry ) ) {
console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
return;
}
if ( offset === undefined ) {
offset = 0;
console.warn(
'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
+ 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
);
}
var attributes = this.attributes;
for ( var key in attributes ) {
if ( geometry.attributes[ key ] === undefined ) continue;
var attribute1 = attributes[ key ];
var attributeArray1 = attribute1.array;
var attribute2 = geometry.attributes[ key ];
var attributeArray2 = attribute2.array;
var attributeOffset = attribute2.itemSize * offset;
var length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
for ( var i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
attributeArray1[ j ] = attributeArray2[ i ];
}
}
return this;
},
normalizeNormals: function () {
var normals = this.attributes.normal;
for ( var i = 0, il = normals.count; i < il; i ++ ) {
_vector$4.x = normals.getX( i );
_vector$4.y = normals.getY( i );
_vector$4.z = normals.getZ( i );
_vector$4.normalize();
normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );
}
},
toNonIndexed: function () {
function convertBufferAttribute( attribute, indices ) {
var array = attribute.array;
var itemSize = attribute.itemSize;
var array2 = new array.constructor( indices.length * itemSize );
var index = 0, index2 = 0;
for ( var i = 0, l = indices.length; i < l; i ++ ) {
index = indices[ i ] * itemSize;
for ( var j = 0; j < itemSize; j ++ ) {
array2[ index2 ++ ] = array[ index ++ ];
}
}
return new BufferAttribute( array2, itemSize );
}
//
if ( this.index === null ) {
console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
return this;
}
var geometry2 = new BufferGeometry();
var indices = this.index.array;
var attributes = this.attributes;
// attributes
for ( var name in attributes ) {
var attribute = attributes[ name ];
var newAttribute = convertBufferAttribute( attribute, indices );
geometry2.setAttribute( name, newAttribute );
}
// morph attributes
var morphAttributes = this.morphAttributes;
for ( name in morphAttributes ) {
var morphArray = [];
var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {
var attribute = morphAttribute[ i ];
var newAttribute = convertBufferAttribute( attribute, indices );
morphArray.push( newAttribute );
}
geometry2.morphAttributes[ name ] = morphArray;
}
geometry2.morphTargetsRelative = this.morphTargetsRelative;
// groups
var groups = this.groups;
for ( var i = 0, l = groups.length; i < l; i ++ ) {
var group = groups[ i ];
geometry2.addGroup( group.start, group.count, group.materialIndex );
}
return geometry2;
},
toJSON: function () {
var data = {
metadata: {
version: 4.5,
type: 'BufferGeometry',
generator: 'BufferGeometry.toJSON'
}
};
// standard BufferGeometry serialization
data.uuid = this.uuid;
data.type = this.type;
if ( this.name !== '' ) data.name = this.name;
if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
if ( this.parameters !== undefined ) {
var parameters = this.parameters;
for ( var key in parameters ) {
if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
}
return data;
}
data.data = { attributes: {} };
var index = this.index;
if ( index !== null ) {
data.data.index = {
type: index.array.constructor.name,
array: Array.prototype.slice.call( index.array )
};
}
var attributes = this.attributes;
for ( var key in attributes ) {
var attribute = attributes[ key ];
var attributeData = attribute.toJSON();
if ( attribute.name !== '' ) attributeData.name = attribute.name;
data.data.attributes[ key ] = attributeData;
}
var morphAttributes = {};
var hasMorphAttributes = false;
for ( var key in this.morphAttributes ) {
var attributeArray = this.morphAttributes[ key ];
var array = [];
for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
var attribute = attributeArray[ i ];
var attributeData = attribute.toJSON();
if ( attribute.name !== '' ) attributeData.name = attribute.name;
array.push( attributeData );
}
if ( array.length > 0 ) {
morphAttributes[ key ] = array;
hasMorphAttributes = true;
}
}
if ( hasMorphAttributes ) {
data.data.morphAttributes = morphAttributes;
data.data.morphTargetsRelative = this.morphTargetsRelative;
}
var groups = this.groups;
if ( groups.length > 0 ) {
data.data.groups = JSON.parse( JSON.stringify( groups ) );
}
var boundingSphere = this.boundingSphere;
if ( boundingSphere !== null ) {
data.data.boundingSphere = {
center: boundingSphere.center.toArray(),
radius: boundingSphere.radius
};
}
return data;
},
clone: function () {
/*
// Handle primitives
var parameters = this.parameters;
if ( parameters !== undefined ) {
var values = [];
for ( var key in parameters ) {
values.push( parameters[ key ] );
}
var geometry = Object.create( this.constructor.prototype );
this.constructor.apply( geometry, values );
return geometry;
}
return new this.constructor().copy( this );
*/
return new BufferGeometry().copy( this );
},
copy: function ( source ) {
var name, i, l;
// reset
this.index = null;
this.attributes = {};
this.morphAttributes = {};
this.groups = [];
this.boundingBox = null;
this.boundingSphere = null;
// name
this.name = source.name;
// index
var index = source.index;
if ( index !== null ) {
this.setIndex( index.clone() );
}
// attributes
var attributes = source.attributes;
for ( name in attributes ) {
var attribute = attributes[ name ];
this.setAttribute( name, attribute.clone() );
}
// morph attributes
var morphAttributes = source.morphAttributes;
for ( name in morphAttributes ) {
var array = [];
var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
array.push( morphAttribute[ i ].clone() );
}
this.morphAttributes[ name ] = array;
}
this.morphTargetsRelative = source.morphTargetsRelative;
// groups
var groups = source.groups;
for ( i = 0, l = groups.length; i < l; i ++ ) {
var group = groups[ i ];
this.addGroup( group.start, group.count, group.materialIndex );
}
// bounding box
var boundingBox = source.boundingBox;
if ( boundingBox !== null ) {
this.boundingBox = boundingBox.clone();
}
// bounding sphere
var boundingSphere = source.boundingSphere;
if ( boundingSphere !== null ) {
this.boundingSphere = boundingSphere.clone();
}
// draw range
this.drawRange.start = source.drawRange.start;
this.drawRange.count = source.drawRange.count;
// user data
this.userData = source.userData;
return this;
},
dispose: function () {
this.dispatchEvent( { type: 'dispose' } );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author mikael emtinger / http://gomo.se/
* @author jonobr1 / http://jonobr1.com/
*/
var _inverseMatrix = new Matrix4();
var _ray = new Ray();
var _sphere = new Sphere();
var _vA = new Vector3();
var _vB = new Vector3();
var _vC = new Vector3();
var _tempA = new Vector3();
var _tempB = new Vector3();
var _tempC = new Vector3();
var _morphA = new Vector3();
var _morphB = new Vector3();
var _morphC = new Vector3();
var _uvA = new Vector2();
var _uvB = new Vector2();
var _uvC = new Vector2();
var _intersectionPoint = new Vector3();
var _intersectionPointWorld = new Vector3();
function Mesh( geometry, material ) {
Object3D.call( this );
this.type = 'Mesh';
this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
this.material = material !== undefined ? material : new MeshBasicMaterial();
this.updateMorphTargets();
}
Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Mesh,
isMesh: true,
copy: function ( source ) {
Object3D.prototype.copy.call( this, source );
if ( source.morphTargetInfluences !== undefined ) {
this.morphTargetInfluences = source.morphTargetInfluences.slice();
}
if ( source.morphTargetDictionary !== undefined ) {
this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
}
return this;
},
updateMorphTargets: function () {
var geometry = this.geometry;
var m, ml, name;
if ( geometry.isBufferGeometry ) {
var morphAttributes = geometry.morphAttributes;
var keys = Object.keys( morphAttributes );
if ( keys.length > 0 ) {
var morphAttribute = morphAttributes[ keys[ 0 ] ];
if ( morphAttribute !== undefined ) {
this.morphTargetInfluences = [];
this.morphTargetDictionary = {};
for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
name = morphAttribute[ m ].name || String( m );
this.morphTargetInfluences.push( 0 );
this.morphTargetDictionary[ name ] = m;
}
}
}
} else {
var morphTargets = geometry.morphTargets;
if ( morphTargets !== undefined && morphTargets.length > 0 ) {
console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
}
}
},
raycast: function ( raycaster, intersects ) {
var geometry = this.geometry;
var material = this.material;
var matrixWorld = this.matrixWorld;
if ( material === undefined ) return;
// Checking boundingSphere distance to ray
if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
_sphere.copy( geometry.boundingSphere );
_sphere.applyMatrix4( matrixWorld );
if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
//
_inverseMatrix.getInverse( matrixWorld );
_ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
// Check boundingBox before continuing
if ( geometry.boundingBox !== null ) {
if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return;
}
var intersection;
if ( geometry.isBufferGeometry ) {
var a, b, c;
var index = geometry.index;
var position = geometry.attributes.position;
var morphPosition = geometry.morphAttributes.position;
var morphTargetsRelative = geometry.morphTargetsRelative;
var uv = geometry.attributes.uv;
var uv2 = geometry.attributes.uv2;
var groups = geometry.groups;
var drawRange = geometry.drawRange;
var i, j, il, jl;
var group, groupMaterial;
var start, end;
if ( index !== null ) {
// indexed buffer geometry
if ( Array.isArray( material ) ) {
for ( i = 0, il = groups.length; i < il; i ++ ) {
group = groups[ i ];
groupMaterial = material[ group.materialIndex ];
start = Math.max( group.start, drawRange.start );
end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
for ( j = start, jl = end; j < jl; j += 3 ) {
a = index.getX( j );
b = index.getX( j + 1 );
c = index.getX( j + 2 );
intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
if ( intersection ) {
intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
intersection.face.materialIndex = group.materialIndex;
intersects.push( intersection );
}
}
}
} else {
start = Math.max( 0, drawRange.start );
end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
for ( i = start, il = end; i < il; i += 3 ) {
a = index.getX( i );
b = index.getX( i + 1 );
c = index.getX( i + 2 );
intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
if ( intersection ) {
intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
intersects.push( intersection );
}
}
}
} else if ( position !== undefined ) {
// non-indexed buffer geometry
if ( Array.isArray( material ) ) {
for ( i = 0, il = groups.length; i < il; i ++ ) {
group = groups[ i ];
groupMaterial = material[ group.materialIndex ];
start = Math.max( group.start, drawRange.start );
end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
for ( j = start, jl = end; j < jl; j += 3 ) {
a = j;
b = j + 1;
c = j + 2;
intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
if ( intersection ) {
intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
intersection.face.materialIndex = group.materialIndex;
intersects.push( intersection );
}
}
}
} else {
start = Math.max( 0, drawRange.start );
end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
for ( i = start, il = end; i < il; i += 3 ) {
a = i;
b = i + 1;
c = i + 2;
intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
if ( intersection ) {
intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
intersects.push( intersection );
}
}
}
}
} else if ( geometry.isGeometry ) {
var fvA, fvB, fvC;
var isMultiMaterial = Array.isArray( material );
var vertices = geometry.vertices;
var faces = geometry.faces;
var uvs;
var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
var face = faces[ f ];
var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
if ( faceMaterial === undefined ) continue;
fvA = vertices[ face.a ];
fvB = vertices[ face.b ];
fvC = vertices[ face.c ];
intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );
if ( intersection ) {
if ( uvs && uvs[ f ] ) {
var uvs_f = uvs[ f ];
_uvA.copy( uvs_f[ 0 ] );
_uvB.copy( uvs_f[ 1 ] );
_uvC.copy( uvs_f[ 2 ] );
intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() );
}
intersection.face = face;
intersection.faceIndex = f;
intersects.push( intersection );
}
}
}
},
clone: function () {
return new this.constructor( this.geometry, this.material ).copy( this );
}
} );
function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
var intersect;
if ( material.side === BackSide ) {
intersect = ray.intersectTriangle( pC, pB, pA, true, point );
} else {
intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
}
if ( intersect === null ) return null;
_intersectionPointWorld.copy( point );
_intersectionPointWorld.applyMatrix4( object.matrixWorld );
var distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
if ( distance < raycaster.near || distance > raycaster.far ) return null;
return {
distance: distance,
point: _intersectionPointWorld.clone(),
object: object
};
}
function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
_vA.fromBufferAttribute( position, a );
_vB.fromBufferAttribute( position, b );
_vC.fromBufferAttribute( position, c );
var morphInfluences = object.morphTargetInfluences;
if ( material.morphTargets && morphPosition && morphInfluences ) {
_morphA.set( 0, 0, 0 );
_morphB.set( 0, 0, 0 );
_morphC.set( 0, 0, 0 );
for ( var i = 0, il = morphPosition.length; i < il; i ++ ) {
var influence = morphInfluences[ i ];
var morphAttribute = morphPosition[ i ];
if ( influence === 0 ) continue;
_tempA.fromBufferAttribute( morphAttribute, a );
_tempB.fromBufferAttribute( morphAttribute, b );
_tempC.fromBufferAttribute( morphAttribute, c );
if ( morphTargetsRelative ) {
_morphA.addScaledVector( _tempA, influence );
_morphB.addScaledVector( _tempB, influence );
_morphC.addScaledVector( _tempC, influence );
} else {
_morphA.addScaledVector( _tempA.sub( _vA ), influence );
_morphB.addScaledVector( _tempB.sub( _vB ), influence );
_morphC.addScaledVector( _tempC.sub( _vC ), influence );
}
}
_vA.add( _morphA );
_vB.add( _morphB );
_vC.add( _morphC );
}
if ( object.isSkinnedMesh ) {
object.boneTransform( a, _vA );
object.boneTransform( b, _vB );
object.boneTransform( c, _vC );
}
var intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
if ( intersection ) {
if ( uv ) {
_uvA.fromBufferAttribute( uv, a );
_uvB.fromBufferAttribute( uv, b );
_uvC.fromBufferAttribute( uv, c );
intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
}
if ( uv2 ) {
_uvA.fromBufferAttribute( uv2, a );
_uvB.fromBufferAttribute( uv2, b );
_uvC.fromBufferAttribute( uv2, c );
intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
}
var face = new Face3( a, b, c );
Triangle.getNormal( _vA, _vB, _vC, face.normal );
intersection.face = face;
}
return intersection;
}
/**
* @author mrdoob / http://mrdoob.com/
* @author kile / http://kile.stravaganza.org/
* @author alteredq / http://alteredqualia.com/
* @author mikael emtinger / http://gomo.se/
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author bhouston / http://clara.io
*/
var _geometryId = 0; // Geometry uses even numbers as Id
var _m1$3 = new Matrix4();
var _obj$1 = new Object3D();
var _offset$1 = new Vector3();
function Geometry() {
Object.defineProperty( this, 'id', { value: _geometryId += 2 } );
this.uuid = MathUtils.generateUUID();
this.name = '';
this.type = 'Geometry';
this.vertices = [];
this.colors = [];
this.faces = [];
this.faceVertexUvs = [[]];
this.morphTargets = [];
this.morphNormals = [];
this.skinWeights = [];
this.skinIndices = [];
this.lineDistances = [];
this.boundingBox = null;
this.boundingSphere = null;
// update flags
this.elementsNeedUpdate = false;
this.verticesNeedUpdate = false;
this.uvsNeedUpdate = false;
this.normalsNeedUpdate = false;
this.colorsNeedUpdate = false;
this.lineDistancesNeedUpdate = false;
this.groupsNeedUpdate = false;
}
Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
constructor: Geometry,
isGeometry: true,
applyMatrix4: function ( matrix ) {
var normalMatrix = new Matrix3().getNormalMatrix( matrix );
for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
var vertex = this.vertices[ i ];
vertex.applyMatrix4( matrix );
}
for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
var face = this.faces[ i ];
face.normal.applyMatrix3( normalMatrix ).normalize();
for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
}
}
if ( this.boundingBox !== null ) {
this.computeBoundingBox();
}
if ( this.boundingSphere !== null ) {
this.computeBoundingSphere();
}
this.verticesNeedUpdate = true;
this.normalsNeedUpdate = true;
return this;
},
rotateX: function ( angle ) {
// rotate geometry around world x-axis
_m1$3.makeRotationX( angle );
this.applyMatrix4( _m1$3 );
return this;
},
rotateY: function ( angle ) {
// rotate geometry around world y-axis
_m1$3.makeRotationY( angle );
this.applyMatrix4( _m1$3 );
return this;
},
rotateZ: function ( angle ) {
// rotate geometry around world z-axis
_m1$3.makeRotationZ( angle );
this.applyMatrix4( _m1$3 );
return this;
},
translate: function ( x, y, z ) {
// translate geometry
_m1$3.makeTranslation( x, y, z );
this.applyMatrix4( _m1$3 );
return this;
},
scale: function ( x, y, z ) {
// scale geometry
_m1$3.makeScale( x, y, z );
this.applyMatrix4( _m1$3 );
return this;
},
lookAt: function ( vector ) {
_obj$1.lookAt( vector );
_obj$1.updateMatrix();
this.applyMatrix4( _obj$1.matrix );
return this;
},
fromBufferGeometry: function ( geometry ) {
var scope = this;
var indices = geometry.index !== null ? geometry.index.array : undefined;
var attributes = geometry.attributes;
if ( attributes.position === undefined ) {
console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' );
return this;
}
var positions = attributes.position.array;
var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
var colors = attributes.color !== undefined ? attributes.color.array : undefined;
var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
for ( var i = 0; i < positions.length; i += 3 ) {
scope.vertices.push( new Vector3().fromArray( positions, i ) );
if ( colors !== undefined ) {
scope.colors.push( new Color().fromArray( colors, i ) );
}
}
function addFace( a, b, c, materialIndex ) {
var vertexColors = ( colors === undefined ) ? [] : [
scope.colors[ a ].clone(),
scope.colors[ b ].clone(),
scope.colors[ c ].clone() ];
var vertexNormals = ( normals === undefined ) ? [] : [
new Vector3().fromArray( normals, a * 3 ),
new Vector3().fromArray( normals, b * 3 ),
new Vector3().fromArray( normals, c * 3 )
];
var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
scope.faces.push( face );
if ( uvs !== undefined ) {
scope.faceVertexUvs[ 0 ].push( [
new Vector2().fromArray( uvs, a * 2 ),
new Vector2().fromArray( uvs, b * 2 ),
new Vector2().fromArray( uvs, c * 2 )
] );
}
if ( uvs2 !== undefined ) {
scope.faceVertexUvs[ 1 ].push( [
new Vector2().fromArray( uvs2, a * 2 ),
new Vector2().fromArray( uvs2, b * 2 ),
new Vector2().fromArray( uvs2, c * 2 )
] );
}
}
var groups = geometry.groups;
if ( groups.length > 0 ) {
for ( var i = 0; i < groups.length; i ++ ) {
var group = groups[ i ];
var start = group.start;
var count = group.count;
for ( var j = start, jl = start + count; j < jl; j += 3 ) {
if ( indices !== undefined ) {
addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
} else {
addFace( j, j + 1, j + 2, group.materialIndex );
}
}
}
} else {
if ( indices !== undefined ) {
for ( var i = 0; i < indices.length; i += 3 ) {
addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
}
} else {
for ( var i = 0; i < positions.length / 3; i += 3 ) {
addFace( i, i + 1, i + 2 );
}
}
}
this.computeFaceNormals();
if ( geometry.boundingBox !== null ) {
this.boundingBox = geometry.boundingBox.clone();
}
if ( geometry.boundingSphere !== null ) {
this.boundingSphere = geometry.boundingSphere.clone();
}
return this;
},
center: function () {
this.computeBoundingBox();
this.boundingBox.getCenter( _offset$1 ).negate();
this.translate( _offset$1.x, _offset$1.y, _offset$1.z );
return this;
},
normalize: function () {
this.computeBoundingSphere();
var center = this.boundingSphere.center;
var radius = this.boundingSphere.radius;
var s = radius === 0 ? 1 : 1.0 / radius;
var matrix = new Matrix4();
matrix.set(
s, 0, 0, - s * center.x,
0, s, 0, - s * center.y,
0, 0, s, - s * center.z,
0, 0, 0, 1
);
this.applyMatrix4( matrix );
return this;
},
computeFaceNormals: function () {
var cb = new Vector3(), ab = new Vector3();
for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
var face = this.faces[ f ];
var vA = this.vertices[ face.a ];
var vB = this.vertices[ face.b ];
var vC = this.vertices[ face.c ];
cb.subVectors( vC, vB );
ab.subVectors( vA, vB );
cb.cross( ab );
cb.normalize();
face.normal.copy( cb );
}
},
computeVertexNormals: function ( areaWeighted ) {
if ( areaWeighted === undefined ) areaWeighted = true;
var v, vl, f, fl, face, vertices;
vertices = new Array( this.vertices.length );
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
vertices[ v ] = new Vector3();
}
if ( areaWeighted ) {
// vertex normals weighted by triangle areas
// http://www.iquilezles.org/www/articles/normals/normals.htm
var vA, vB, vC;
var cb = new Vector3(), ab = new Vector3();
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
vA = this.vertices[ face.a ];
vB = this.vertices[ face.b ];
vC = this.vertices[ face.c ];
cb.subVectors( vC, vB );
ab.subVectors( vA, vB );
cb.cross( ab );
vertices[ face.a ].add( cb );
vertices[ face.b ].add( cb );
vertices[ face.c ].add( cb );
}
} else {
this.computeFaceNormals();
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
vertices[ face.a ].add( face.normal );
vertices[ face.b ].add( face.normal );
vertices[ face.c ].add( face.normal );
}
}
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
vertices[ v ].normalize();
}
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
var vertexNormals = face.vertexNormals;
if ( vertexNormals.length === 3 ) {
vertexNormals[ 0 ].copy( vertices[ face.a ] );
vertexNormals[ 1 ].copy( vertices[ face.b ] );
vertexNormals[ 2 ].copy( vertices[ face.c ] );
} else {
vertexNormals[ 0 ] = vertices[ face.a ].clone();
vertexNormals[ 1 ] = vertices[ face.b ].clone();
vertexNormals[ 2 ] = vertices[ face.c ].clone();
}
}
if ( this.faces.length > 0 ) {
this.normalsNeedUpdate = true;
}
},
computeFlatVertexNormals: function () {
var f, fl, face;
this.computeFaceNormals();
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
var vertexNormals = face.vertexNormals;
if ( vertexNormals.length === 3 ) {
vertexNormals[ 0 ].copy( face.normal );
vertexNormals[ 1 ].copy( face.normal );
vertexNormals[ 2 ].copy( face.normal );
} else {
vertexNormals[ 0 ] = face.normal.clone();
vertexNormals[ 1 ] = face.normal.clone();
vertexNormals[ 2 ] = face.normal.clone();
}
}
if ( this.faces.length > 0 ) {
this.normalsNeedUpdate = true;
}
},
computeMorphNormals: function () {
var i, il, f, fl, face;
// save original normals
// - create temp variables on first access
// otherwise just copy (for faster repeated calls)
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
if ( ! face.__originalFaceNormal ) {
face.__originalFaceNormal = face.normal.clone();
} else {
face.__originalFaceNormal.copy( face.normal );
}
if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
if ( ! face.__originalVertexNormals[ i ] ) {
face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
} else {
face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
}
}
}
// use temp geometry to compute face and vertex normals for each morph
var tmpGeo = new Geometry();
tmpGeo.faces = this.faces;
for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
// create on first access
if ( ! this.morphNormals[ i ] ) {
this.morphNormals[ i ] = {};
this.morphNormals[ i ].faceNormals = [];
this.morphNormals[ i ].vertexNormals = [];
var dstNormalsFace = this.morphNormals[ i ].faceNormals;
var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
var faceNormal, vertexNormals;
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
faceNormal = new Vector3();
vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
dstNormalsFace.push( faceNormal );
dstNormalsVertex.push( vertexNormals );
}
}
var morphNormals = this.morphNormals[ i ];
// set vertices to morph target
tmpGeo.vertices = this.morphTargets[ i ].vertices;
// compute morph normals
tmpGeo.computeFaceNormals();
tmpGeo.computeVertexNormals();
// store morph normals
var faceNormal, vertexNormals;
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
faceNormal = morphNormals.faceNormals[ f ];
vertexNormals = morphNormals.vertexNormals[ f ];
faceNormal.copy( face.normal );
vertexNormals.a.copy( face.vertexNormals[ 0 ] );
vertexNormals.b.copy( face.vertexNormals[ 1 ] );
vertexNormals.c.copy( face.vertexNormals[ 2 ] );
}
}
// restore original normals
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
face.normal = face.__originalFaceNormal;
face.vertexNormals = face.__originalVertexNormals;
}
},
computeBoundingBox: function () {
if ( this.boundingBox === null ) {
this.boundingBox = new Box3();
}
this.boundingBox.setFromPoints( this.vertices );
},
computeBoundingSphere: function () {
if ( this.boundingSphere === null ) {
this.boundingSphere = new Sphere();
}
this.boundingSphere.setFromPoints( this.vertices );
},
merge: function ( geometry, matrix, materialIndexOffset ) {
if ( ! ( geometry && geometry.isGeometry ) ) {
console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
return;
}
var normalMatrix,
vertexOffset = this.vertices.length,
vertices1 = this.vertices,
vertices2 = geometry.vertices,
faces1 = this.faces,
faces2 = geometry.faces,
colors1 = this.colors,
colors2 = geometry.colors;
if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
if ( matrix !== undefined ) {
normalMatrix = new Matrix3().getNormalMatrix( matrix );
}
// vertices
for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
var vertex = vertices2[ i ];
var vertexCopy = vertex.clone();
if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
vertices1.push( vertexCopy );
}
// colors
for ( var i = 0, il = colors2.length; i < il; i ++ ) {
colors1.push( colors2[ i ].clone() );
}
// faces
for ( i = 0, il = faces2.length; i < il; i ++ ) {
var face = faces2[ i ], faceCopy, normal, color,
faceVertexNormals = face.vertexNormals,
faceVertexColors = face.vertexColors;
faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
faceCopy.normal.copy( face.normal );
if ( normalMatrix !== undefined ) {
faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
}
for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
normal = faceVertexNormals[ j ].clone();
if ( normalMatrix !== undefined ) {
normal.applyMatrix3( normalMatrix ).normalize();
}
faceCopy.vertexNormals.push( normal );
}
faceCopy.color.copy( face.color );
for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
color = faceVertexColors[ j ];
faceCopy.vertexColors.push( color.clone() );
}
faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
faces1.push( faceCopy );
}
// uvs
for ( var i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
var faceVertexUvs2 = geometry.faceVertexUvs[ i ];
if ( this.faceVertexUvs[ i ] === undefined ) this.faceVertexUvs[ i ] = [];
for ( var j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) {
var uvs2 = faceVertexUvs2[ j ], uvsCopy = [];
for ( var k = 0, kl = uvs2.length; k < kl; k ++ ) {
uvsCopy.push( uvs2[ k ].clone() );
}
this.faceVertexUvs[ i ].push( uvsCopy );
}
}
},
mergeMesh: function ( mesh ) {
if ( ! ( mesh && mesh.isMesh ) ) {
console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
return;
}
if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
this.merge( mesh.geometry, mesh.matrix );
},
/*
* Checks for duplicate vertices with hashmap.
* Duplicated vertices are removed
* and faces' vertices are updated.
*/
mergeVertices: function () {
var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
var unique = [], changes = [];
var v, key;
var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
var precision = Math.pow( 10, precisionPoints );
var i, il, face;
var indices, j, jl;
for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
v = this.vertices[ i ];
key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
if ( verticesMap[ key ] === undefined ) {
verticesMap[ key ] = i;
unique.push( this.vertices[ i ] );
changes[ i ] = unique.length - 1;
} else {
//console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
changes[ i ] = changes[ verticesMap[ key ] ];
}
}
// if faces are completely degenerate after merging vertices, we
// have to remove them from the geometry.
var faceIndicesToRemove = [];
for ( i = 0, il = this.faces.length; i < il; i ++ ) {
face = this.faces[ i ];
face.a = changes[ face.a ];
face.b = changes[ face.b ];
face.c = changes[ face.c ];
indices = [ face.a, face.b, face.c ];
// if any duplicate vertices are found in a Face3
// we have to remove the face as nothing can be saved
for ( var n = 0; n < 3; n ++ ) {
if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
faceIndicesToRemove.push( i );
break;
}
}
}
for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
var idx = faceIndicesToRemove[ i ];
this.faces.splice( idx, 1 );
for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
this.faceVertexUvs[ j ].splice( idx, 1 );
}
}
// Use unique set of vertices
var diff = this.vertices.length - unique.length;
this.vertices = unique;
return diff;
},
setFromPoints: function ( points ) {
this.vertices = [];
for ( var i = 0, l = points.length; i < l; i ++ ) {
var point = points[ i ];
this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
}
return this;
},
sortFacesByMaterialIndex: function () {
var faces = this.faces;
var length = faces.length;
// tag faces
for ( var i = 0; i < length; i ++ ) {
faces[ i ]._id = i;
}
// sort faces
function materialIndexSort( a, b ) {
return a.materialIndex - b.materialIndex;
}
faces.sort( materialIndexSort );
// sort uvs
var uvs1 = this.faceVertexUvs[ 0 ];
var uvs2 = this.faceVertexUvs[ 1 ];
var newUvs1, newUvs2;
if ( uvs1 && uvs1.length === length ) newUvs1 = [];
if ( uvs2 && uvs2.length === length ) newUvs2 = [];
for ( var i = 0; i < length; i ++ ) {
var id = faces[ i ]._id;
if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
}
if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
},
toJSON: function () {
var data = {
metadata: {
version: 4.5,
type: 'Geometry',
generator: 'Geometry.toJSON'
}
};
// standard Geometry serialization
data.uuid = this.uuid;
data.type = this.type;
if ( this.name !== '' ) data.name = this.name;
if ( this.parameters !== undefined ) {
var parameters = this.parameters;
for ( var key in parameters ) {
if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
}
return data;
}
var vertices = [];
for ( var i = 0; i < this.vertices.length; i ++ ) {
var vertex = this.vertices[ i ];
vertices.push( vertex.x, vertex.y, vertex.z );
}
var faces = [];
var normals = [];
var normalsHash = {};
var colors = [];
var colorsHash = {};
var uvs = [];
var uvsHash = {};
for ( var i = 0; i < this.faces.length; i ++ ) {
var face = this.faces[ i ];
var hasMaterial = true;
var hasFaceUv = false; // deprecated
var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
var hasFaceNormal = face.normal.length() > 0;
var hasFaceVertexNormal = face.vertexNormals.length > 0;
var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
var hasFaceVertexColor = face.vertexColors.length > 0;
var faceType = 0;
faceType = setBit( faceType, 0, 0 ); // isQuad
faceType = setBit( faceType, 1, hasMaterial );
faceType = setBit( faceType, 2, hasFaceUv );
faceType = setBit( faceType, 3, hasFaceVertexUv );
faceType = setBit( faceType, 4, hasFaceNormal );
faceType = setBit( faceType, 5, hasFaceVertexNormal );
faceType = setBit( faceType, 6, hasFaceColor );
faceType = setBit( faceType, 7, hasFaceVertexColor );
faces.push( faceType );
faces.push( face.a, face.b, face.c );
faces.push( face.materialIndex );
if ( hasFaceVertexUv ) {
var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
faces.push(
getUvIndex( faceVertexUvs[ 0 ] ),
getUvIndex( faceVertexUvs[ 1 ] ),
getUvIndex( faceVertexUvs[ 2 ] )
);
}
if ( hasFaceNormal ) {
faces.push( getNormalIndex( face.normal ) );
}
if ( hasFaceVertexNormal ) {
var vertexNormals = face.vertexNormals;
faces.push(
getNormalIndex( vertexNormals[ 0 ] ),
getNormalIndex( vertexNormals[ 1 ] ),
getNormalIndex( vertexNormals[ 2 ] )
);
}
if ( hasFaceColor ) {
faces.push( getColorIndex( face.color ) );
}
if ( hasFaceVertexColor ) {
var vertexColors = face.vertexColors;
faces.push(
getColorIndex( vertexColors[ 0 ] ),
getColorIndex( vertexColors[ 1 ] ),
getColorIndex( vertexColors[ 2 ] )
);
}
}
function setBit( value, position, enabled ) {
return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
}
function getNormalIndex( normal ) {
var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
if ( normalsHash[ hash ] !== undefined ) {
return normalsHash[ hash ];
}
normalsHash[ hash ] = normals.length / 3;
normals.push( normal.x, normal.y, normal.z );
return normalsHash[ hash ];
}
function getColorIndex( color ) {
var hash = color.r.toString() + color.g.toString() + color.b.toString();
if ( colorsHash[ hash ] !== undefined ) {
return colorsHash[ hash ];
}
colorsHash[ hash ] = colors.length;
colors.push( color.getHex() );
return colorsHash[ hash ];
}
function getUvIndex( uv ) {
var hash = uv.x.toString() + uv.y.toString();
if ( uvsHash[ hash ] !== undefined ) {
return uvsHash[ hash ];
}
uvsHash[ hash ] = uvs.length / 2;
uvs.push( uv.x, uv.y );
return uvsHash[ hash ];
}
data.data = {};
data.data.vertices = vertices;
data.data.normals = normals;
if ( colors.length > 0 ) data.data.colors = colors;
if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
data.data.faces = faces;
return data;
},
clone: function () {
/*
// Handle primitives
var parameters = this.parameters;
if ( parameters !== undefined ) {
var values = [];
for ( var key in parameters ) {
values.push( parameters[ key ] );
}
var geometry = Object.create( this.constructor.prototype );
this.constructor.apply( geometry, values );
return geometry;
}
return new this.constructor().copy( this );
*/
return new Geometry().copy( this );
},
copy: function ( source ) {
var i, il, j, jl, k, kl;
// reset
this.vertices = [];
this.colors = [];
this.faces = [];
this.faceVertexUvs = [[]];
this.morphTargets = [];
this.morphNormals = [];
this.skinWeights = [];
this.skinIndices = [];
this.lineDistances = [];
this.boundingBox = null;
this.boundingSphere = null;
// name
this.name = source.name;
// vertices
var vertices = source.vertices;
for ( i = 0, il = vertices.length; i < il; i ++ ) {
this.vertices.push( vertices[ i ].clone() );
}
// colors
var colors = source.colors;
for ( i = 0, il = colors.length; i < il; i ++ ) {
this.colors.push( colors[ i ].clone() );
}
// faces
var faces = source.faces;
for ( i = 0, il = faces.length; i < il; i ++ ) {
this.faces.push( faces[ i ].clone() );
}
// face vertex uvs
for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
var faceVertexUvs = source.faceVertexUvs[ i ];
if ( this.faceVertexUvs[ i ] === undefined ) {
this.faceVertexUvs[ i ] = [];
}
for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
var uvs = faceVertexUvs[ j ], uvsCopy = [];
for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
var uv = uvs[ k ];
uvsCopy.push( uv.clone() );
}
this.faceVertexUvs[ i ].push( uvsCopy );
}
}
// morph targets
var morphTargets = source.morphTargets;
for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
var morphTarget = {};
morphTarget.name = morphTargets[ i ].name;
// vertices
if ( morphTargets[ i ].vertices !== undefined ) {
morphTarget.vertices = [];
for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
}
}
// normals
if ( morphTargets[ i ].normals !== undefined ) {
morphTarget.normals = [];
for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
}
}
this.morphTargets.push( morphTarget );
}
// morph normals
var morphNormals = source.morphNormals;
for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
var morphNormal = {};
// vertex normals
if ( morphNormals[ i ].vertexNormals !== undefined ) {
morphNormal.vertexNormals = [];
for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
var destVertexNormal = {};
destVertexNormal.a = srcVertexNormal.a.clone();
destVertexNormal.b = srcVertexNormal.b.clone();
destVertexNormal.c = srcVertexNormal.c.clone();
morphNormal.vertexNormals.push( destVertexNormal );
}
}
// face normals
if ( morphNormals[ i ].faceNormals !== undefined ) {
morphNormal.faceNormals = [];
for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
}
}
this.morphNormals.push( morphNormal );
}
// skin weights
var skinWeights = source.skinWeights;
for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
this.skinWeights.push( skinWeights[ i ].clone() );
}
// skin indices
var skinIndices = source.skinIndices;
for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
this.skinIndices.push( skinIndices[ i ].clone() );
}
// line distances
var lineDistances = source.lineDistances;
for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
this.lineDistances.push( lineDistances[ i ] );
}
// bounding box
var boundingBox = source.boundingBox;
if ( boundingBox !== null ) {
this.boundingBox = boundingBox.clone();
}
// bounding sphere
var boundingSphere = source.boundingSphere;
if ( boundingSphere !== null ) {
this.boundingSphere = boundingSphere.clone();
}
// update flags
this.elementsNeedUpdate = source.elementsNeedUpdate;
this.verticesNeedUpdate = source.verticesNeedUpdate;
this.uvsNeedUpdate = source.uvsNeedUpdate;
this.normalsNeedUpdate = source.normalsNeedUpdate;
this.colorsNeedUpdate = source.colorsNeedUpdate;
this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
this.groupsNeedUpdate = source.groupsNeedUpdate;
return this;
},
dispose: function () {
this.dispatchEvent( { type: 'dispose' } );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / https://github.com/Mugen87
*/
// BoxGeometry
class BoxGeometry extends Geometry {
constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
super();
this.type = 'BoxGeometry';
this.parameters = {
width: width,
height: height,
depth: depth,
widthSegments: widthSegments,
heightSegments: heightSegments,
depthSegments: depthSegments
};
this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
this.mergeVertices();
}
}
// BoxBufferGeometry
class BoxBufferGeometry extends BufferGeometry {
constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
super();
this.type = 'BoxBufferGeometry';
this.parameters = {
width: width,
height: height,
depth: depth,
widthSegments: widthSegments,
heightSegments: heightSegments,
depthSegments: depthSegments
};
var scope = this;
width = width || 1;
height = height || 1;
depth = depth || 1;
// segments
widthSegments = Math.floor( widthSegments ) || 1;
heightSegments = Math.floor( heightSegments ) || 1;
depthSegments = Math.floor( depthSegments ) || 1;
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
// helper variables
var numberOfVertices = 0;
var groupStart = 0;
// build each side of the box geometry
buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
var segmentWidth = width / gridX;
var segmentHeight = height / gridY;
var widthHalf = width / 2;
var heightHalf = height / 2;
var depthHalf = depth / 2;
var gridX1 = gridX + 1;
var gridY1 = gridY + 1;
var vertexCounter = 0;
var groupCount = 0;
var ix, iy;
var vector = new Vector3();
// generate vertices, normals and uvs
for ( iy = 0; iy < gridY1; iy ++ ) {
var y = iy * segmentHeight - heightHalf;
for ( ix = 0; ix < gridX1; ix ++ ) {
var x = ix * segmentWidth - widthHalf;
// set values to correct vector component
vector[ u ] = x * udir;
vector[ v ] = y * vdir;
vector[ w ] = depthHalf;
// now apply vector to vertex buffer
vertices.push( vector.x, vector.y, vector.z );
// set values to correct vector component
vector[ u ] = 0;
vector[ v ] = 0;
vector[ w ] = depth > 0 ? 1 : - 1;
// now apply vector to normal buffer
normals.push( vector.x, vector.y, vector.z );
// uvs
uvs.push( ix / gridX );
uvs.push( 1 - ( iy / gridY ) );
// counters
vertexCounter += 1;
}
}
// indices
// 1. you need three indices to draw a single face
// 2. a single segment consists of two faces
// 3. so we need to generate six (2*3) indices per segment
for ( iy = 0; iy < gridY; iy ++ ) {
for ( ix = 0; ix < gridX; ix ++ ) {
var a = numberOfVertices + ix + gridX1 * iy;
var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
// faces
indices.push( a, b, d );
indices.push( b, c, d );
// increase counter
groupCount += 6;
}
}
// add a group to the geometry. this will ensure multi material support
scope.addGroup( groupStart, groupCount, materialIndex );
// calculate new start value for groups
groupStart += groupCount;
// update total number of vertices
numberOfVertices += vertexCounter;
}
}
}
/**
* Uniform Utilities
*/
function cloneUniforms( src ) {
var dst = {};
for ( var u in src ) {
dst[ u ] = {};
for ( var p in src[ u ] ) {
var property = src[ u ][ p ];
if ( property && ( property.isColor ||
property.isMatrix3 || property.isMatrix4 ||
property.isVector2 || property.isVector3 || property.isVector4 ||
property.isTexture ) ) {
dst[ u ][ p ] = property.clone();
} else if ( Array.isArray( property ) ) {
dst[ u ][ p ] = property.slice();
} else {
dst[ u ][ p ] = property;
}
}
}
return dst;
}
function mergeUniforms( uniforms ) {
var merged = {};
for ( var u = 0; u < uniforms.length; u ++ ) {
var tmp = cloneUniforms( uniforms[ u ] );
for ( var p in tmp ) {
merged[ p ] = tmp[ p ];
}
}
return merged;
}
// Legacy
var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
/**
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* defines: { "label" : "value" },
* uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
*
* fragmentShader: <string>,
* vertexShader: <string>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* lights: <bool>,
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>
* }
*/
function ShaderMaterial( parameters ) {
Material.call( this );
this.type = 'ShaderMaterial';
this.defines = {};
this.uniforms = {};
this.vertexShader = default_vertex;
this.fragmentShader = default_fragment;
this.linewidth = 1;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.fog = false; // set to use scene fog
this.lights = false; // set to use scene lights
this.clipping = false; // set to use user-defined clipping planes
this.skinning = false; // set to use skinning attribute streams
this.morphTargets = false; // set to use morph targets
this.morphNormals = false; // set to use morph normals
this.extensions = {
derivatives: false, // set to use derivatives
fragDepth: false, // set to use fragment depth values
drawBuffers: false, // set to use draw buffers
shaderTextureLOD: false // set to use shader texture LOD
};
// When rendered geometry doesn't include these attributes but the material does,
// use these default values in WebGL. This avoids errors when buffer data is missing.
this.defaultAttributeValues = {
'color': [ 1, 1, 1 ],
'uv': [ 0, 0 ],
'uv2': [ 0, 0 ]
};
this.index0AttributeName = undefined;
this.uniformsNeedUpdate = false;
if ( parameters !== undefined ) {
if ( parameters.attributes !== undefined ) {
console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
}
this.setValues( parameters );
}
}
ShaderMaterial.prototype = Object.create( Material.prototype );
ShaderMaterial.prototype.constructor = ShaderMaterial;
ShaderMaterial.prototype.isShaderMaterial = true;
ShaderMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.fragmentShader = source.fragmentShader;
this.vertexShader = source.vertexShader;
this.uniforms = cloneUniforms( source.uniforms );
this.defines = Object.assign( {}, source.defines );
this.wireframe = source.wireframe;
this.wireframeLinewidth = source.wireframeLinewidth;
this.lights = source.lights;
this.clipping = source.clipping;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
this.morphNormals = source.morphNormals;
this.extensions = source.extensions;
return this;
};
ShaderMaterial.prototype.toJSON = function ( meta ) {
var data = Material.prototype.toJSON.call( this, meta );
data.uniforms = {};
for ( var name in this.uniforms ) {
var uniform = this.uniforms[ name ];
var value = uniform.value;
if ( value && value.isTexture ) {
data.uniforms[ name ] = {
type: 't',
value: value.toJSON( meta ).uuid
};
} else if ( value && value.isColor ) {
data.uniforms[ name ] = {
type: 'c',
value: value.getHex()
};
} else if ( value && value.isVector2 ) {
data.uniforms[ name ] = {
type: 'v2',
value: value.toArray()
};
} else if ( value && value.isVector3 ) {
data.uniforms[ name ] = {
type: 'v3',
value: value.toArray()
};
} else if ( value && value.isVector4 ) {
data.uniforms[ name ] = {
type: 'v4',
value: value.toArray()
};
} else if ( value && value.isMatrix3 ) {
data.uniforms[ name ] = {
type: 'm3',
value: value.toArray()
};
} else if ( value && value.isMatrix4 ) {
data.uniforms[ name ] = {
type: 'm4',
value: value.toArray()
};
} else {
data.uniforms[ name ] = {
value: value
};
// note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
}
}
if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
data.vertexShader = this.vertexShader;
data.fragmentShader = this.fragmentShader;
var extensions = {};
for ( var key in this.extensions ) {
if ( this.extensions[ key ] === true ) extensions[ key ] = true;
}
if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
return data;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
* @author WestLangley / http://github.com/WestLangley
*/
function Camera() {
Object3D.call( this );
this.type = 'Camera';
this.matrixWorldInverse = new Matrix4();
this.projectionMatrix = new Matrix4();
this.projectionMatrixInverse = new Matrix4();
}
Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Camera,
isCamera: true,
copy: function ( source, recursive ) {
Object3D.prototype.copy.call( this, source, recursive );
this.matrixWorldInverse.copy( source.matrixWorldInverse );
this.projectionMatrix.copy( source.projectionMatrix );
this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
return this;
},
getWorldDirection: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
target = new Vector3();
}
this.updateMatrixWorld( true );
var e = this.matrixWorld.elements;
return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
},
updateMatrixWorld: function ( force ) {
Object3D.prototype.updateMatrixWorld.call( this, force );
this.matrixWorldInverse.getInverse( this.matrixWorld );
},
updateWorldMatrix: function ( updateParents, updateChildren ) {
Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );
this.matrixWorldInverse.getInverse( this.matrixWorld );
},
clone: function () {
return new this.constructor().copy( this );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author greggman / http://games.greggman.com/
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author tschw
*/
function PerspectiveCamera( fov, aspect, near, far ) {
Camera.call( this );
this.type = 'PerspectiveCamera';
this.fov = fov !== undefined ? fov : 50;
this.zoom = 1;
this.near = near !== undefined ? near : 0.1;
this.far = far !== undefined ? far : 2000;
this.focus = 10;
this.aspect = aspect !== undefined ? aspect : 1;
this.view = null;
this.filmGauge = 35; // width of the film (default in millimeters)
this.filmOffset = 0; // horizontal film offset (same unit as gauge)
this.updateProjectionMatrix();
}
PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
constructor: PerspectiveCamera,
isPerspectiveCamera: true,
copy: function ( source, recursive ) {
Camera.prototype.copy.call( this, source, recursive );
this.fov = source.fov;
this.zoom = source.zoom;
this.near = source.near;
this.far = source.far;
this.focus = source.focus;
this.aspect = source.aspect;
this.view = source.view === null ? null : Object.assign( {}, source.view );
this.filmGauge = source.filmGauge;
this.filmOffset = source.filmOffset;
return this;
},
/**
* Sets the FOV by focal length in respect to the current .filmGauge.
*
* The default film gauge is 35, so that the focal length can be specified for
* a 35mm (full frame) camera.
*
* Values for focal length and film gauge must have the same unit.
*/
setFocalLength: function ( focalLength ) {
// see http://www.bobatkins.com/photography/technical/field_of_view.html
var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
this.updateProjectionMatrix();
},
/**
* Calculates the focal length from the current .fov and .filmGauge.
*/
getFocalLength: function () {
var vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );
return 0.5 * this.getFilmHeight() / vExtentSlope;
},
getEffectiveFOV: function () {
return MathUtils.RAD2DEG * 2 * Math.atan(
Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );
},
getFilmWidth: function () {
// film not completely covered in portrait format (aspect < 1)
return this.filmGauge * Math.min( this.aspect, 1 );
},
getFilmHeight: function () {
// film not completely covered in landscape format (aspect > 1)
return this.filmGauge / Math.max( this.aspect, 1 );
},
/**
* Sets an offset in a larger frustum. This is useful for multi-window or
* multi-monitor/multi-machine setups.
*
* For example, if you have 3x2 monitors and each monitor is 1920x1080 and
* the monitors are in grid like this
*
* +---+---+---+
* | A | B | C |
* +---+---+---+
* | D | E | F |
* +---+---+---+
*
* then for each monitor you would call it like this
*
* var w = 1920;
* var h = 1080;
* var fullWidth = w * 3;
* var fullHeight = h * 2;
*
* --A--
* camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
* --B--
* camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
* --C--
* camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
* --D--
* camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
* --E--
* camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
* --F--
* camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
*
* Note there is no reason monitors have to be the same size or in a grid.
*/
setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
this.aspect = fullWidth / fullHeight;
if ( this.view === null ) {
this.view = {
enabled: true,
fullWidth: 1,
fullHeight: 1,
offsetX: 0,
offsetY: 0,
width: 1,
height: 1
};
}
this.view.enabled = true;
this.view.fullWidth = fullWidth;
this.view.fullHeight = fullHeight;
this.view.offsetX = x;
this.view.offsetY = y;
this.view.width = width;
this.view.height = height;
this.updateProjectionMatrix();
},
clearViewOffset: function () {
if ( this.view !== null ) {
this.view.enabled = false;
}
this.updateProjectionMatrix();
},
updateProjectionMatrix: function () {
var near = this.near,
top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom,
height = 2 * top,
width = this.aspect * height,
left = - 0.5 * width,
view = this.view;
if ( this.view !== null && this.view.enabled ) {
var fullWidth = view.fullWidth,
fullHeight = view.fullHeight;
left += view.offsetX * width / fullWidth;
top -= view.offsetY * height / fullHeight;
width *= view.width / fullWidth;
height *= view.height / fullHeight;
}
var skew = this.filmOffset;
if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
this.projectionMatrixInverse.getInverse( this.projectionMatrix );
},
toJSON: function ( meta ) {
var data = Object3D.prototype.toJSON.call( this, meta );
data.object.fov = this.fov;
data.object.zoom = this.zoom;
data.object.near = this.near;
data.object.far = this.far;
data.object.focus = this.focus;
data.object.aspect = this.aspect;
if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
data.object.filmGauge = this.filmGauge;
data.object.filmOffset = this.filmOffset;
return data;
}
} );
/**
* Camera for rendering cube maps
* - renders scene into axis-aligned cube
*
* @author alteredq / http://alteredqualia.com/
*/
var fov = 90, aspect = 1;
function CubeCamera( near, far, cubeResolution, options ) {
Object3D.call( this );
this.type = 'CubeCamera';
var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
cameraPX.up.set( 0, - 1, 0 );
cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
this.add( cameraPX );
var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
cameraNX.up.set( 0, - 1, 0 );
cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
this.add( cameraNX );
var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
cameraPY.up.set( 0, 0, 1 );
cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
this.add( cameraPY );
var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
cameraNY.up.set( 0, 0, - 1 );
cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
this.add( cameraNY );
var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
cameraPZ.up.set( 0, - 1, 0 );
cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
this.add( cameraPZ );
var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
cameraNZ.up.set( 0, - 1, 0 );
cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
this.add( cameraNZ );
options = options || { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
this.renderTarget = new WebGLCubeRenderTarget( cubeResolution, options );
this.renderTarget.texture.name = "CubeCamera";
this.update = function ( renderer, scene ) {
if ( this.parent === null ) this.updateMatrixWorld();
var currentRenderTarget = renderer.getRenderTarget();
var renderTarget = this.renderTarget;
var generateMipmaps = renderTarget.texture.generateMipmaps;
renderTarget.texture.generateMipmaps = false;
renderer.setRenderTarget( renderTarget, 0 );
renderer.render( scene, cameraPX );
renderer.setRenderTarget( renderTarget, 1 );
renderer.render( scene, cameraNX );
renderer.setRenderTarget( renderTarget, 2 );
renderer.render( scene, cameraPY );
renderer.setRenderTarget( renderTarget, 3 );
renderer.render( scene, cameraNY );
renderer.setRenderTarget( renderTarget, 4 );
renderer.render( scene, cameraPZ );
renderTarget.texture.generateMipmaps = generateMipmaps;
renderer.setRenderTarget( renderTarget, 5 );
renderer.render( scene, cameraNZ );
renderer.setRenderTarget( currentRenderTarget );
};
this.clear = function ( renderer, color, depth, stencil ) {
var currentRenderTarget = renderer.getRenderTarget();
var renderTarget = this.renderTarget;
for ( var i = 0; i < 6; i ++ ) {
renderer.setRenderTarget( renderTarget, i );
renderer.clear( color, depth, stencil );
}
renderer.setRenderTarget( currentRenderTarget );
};
}
CubeCamera.prototype = Object.create( Object3D.prototype );
CubeCamera.prototype.constructor = CubeCamera;
/**
* @author alteredq / http://alteredqualia.com
* @author WestLangley / http://github.com/WestLangley
*/
function WebGLCubeRenderTarget( size, options, dummy ) {
if ( Number.isInteger( options ) ) {
console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
options = dummy;
}
WebGLRenderTarget.call( this, size, size, options );
}
WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {
this.texture.type = texture.type;
this.texture.format = texture.format;
this.texture.encoding = texture.encoding;
var scene = new Scene();
var shader = {
uniforms: {
tEquirect: { value: null },
},
vertexShader: [
"varying vec3 vWorldDirection;",
"vec3 transformDirection( in vec3 dir, in mat4 matrix ) {",
" return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );",
"}",
"void main() {",
" vWorldDirection = transformDirection( position, modelMatrix );",
" #include <begin_vertex>",
" #include <project_vertex>",
"}"
].join( '\n' ),
fragmentShader: [
"uniform sampler2D tEquirect;",
"varying vec3 vWorldDirection;",
"#define RECIPROCAL_PI 0.31830988618",
"#define RECIPROCAL_PI2 0.15915494",
"void main() {",
" vec3 direction = normalize( vWorldDirection );",
" vec2 sampleUV;",
" sampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;",
" sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
" gl_FragColor = texture2D( tEquirect, sampleUV );",
"}"
].join( '\n' ),
};
var material = new ShaderMaterial( {
type: 'CubemapFromEquirect',
uniforms: cloneUniforms( shader.uniforms ),
vertexShader: shader.vertexShader,
fragmentShader: shader.fragmentShader,
side: BackSide,
blending: NoBlending
} );
material.uniforms.tEquirect.value = texture;
var mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material );
scene.add( mesh );
var camera = new CubeCamera( 1, 10, 1 );
camera.renderTarget = this;
camera.renderTarget.texture.name = 'CubeCameraTexture';
camera.update( renderer, scene );
mesh.geometry.dispose();
mesh.material.dispose();
return this;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
this.image = { data: data || null, width: width || 1, height: height || 1 };
this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
this.generateMipmaps = false;
this.flipY = false;
this.unpackAlignment = 1;
this.needsUpdate = true;
}
DataTexture.prototype = Object.create( Texture.prototype );
DataTexture.prototype.constructor = DataTexture;
DataTexture.prototype.isDataTexture = true;
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author bhouston / http://clara.io
*/
var _sphere$1 = new Sphere();
var _vector$5 = new Vector3();
function Frustum( p0, p1, p2, p3, p4, p5 ) {
this.planes = [
( p0 !== undefined ) ? p0 : new Plane(),
( p1 !== undefined ) ? p1 : new Plane(),
( p2 !== undefined ) ? p2 : new Plane(),
( p3 !== undefined ) ? p3 : new Plane(),
( p4 !== undefined ) ? p4 : new Plane(),
( p5 !== undefined ) ? p5 : new Plane()
];
}
Object.assign( Frustum.prototype, {
set: function ( p0, p1, p2, p3, p4, p5 ) {
var planes = this.planes;
planes[ 0 ].copy( p0 );
planes[ 1 ].copy( p1 );
planes[ 2 ].copy( p2 );
planes[ 3 ].copy( p3 );
planes[ 4 ].copy( p4 );
planes[ 5 ].copy( p5 );
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( frustum ) {
var planes = this.planes;
for ( var i = 0; i < 6; i ++ ) {
planes[ i ].copy( frustum.planes[ i ] );
}
return this;
},
setFromProjectionMatrix: function ( m ) {
var planes = this.planes;
var me = m.elements;
var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
return this;
},
intersectsObject: function ( object ) {
var geometry = object.geometry;
if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
_sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
return this.intersectsSphere( _sphere$1 );
},
intersectsSprite: function ( sprite ) {
_sphere$1.center.set( 0, 0, 0 );
_sphere$1.radius = 0.7071067811865476;
_sphere$1.applyMatrix4( sprite.matrixWorld );
return this.intersectsSphere( _sphere$1 );
},
intersectsSphere: function ( sphere ) {
var planes = this.planes;
var center = sphere.center;
var negRadius = - sphere.radius;
for ( var i = 0; i < 6; i ++ ) {
var distance = planes[ i ].distanceToPoint( center );
if ( distance < negRadius ) {
return false;
}
}
return true;
},
intersectsBox: function ( box ) {
var planes = this.planes;
for ( var i = 0; i < 6; i ++ ) {
var plane = planes[ i ];
// corner at max distance
_vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
_vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
_vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
if ( plane.distanceToPoint( _vector$5 ) < 0 ) {
return false;
}
}
return true;
},
containsPoint: function ( point ) {
var planes = this.planes;
for ( var i = 0; i < 6; i ++ ) {
if ( planes[ i ].distanceToPoint( point ) < 0 ) {
return false;
}
}
return true;
}
} );
/**
* Uniforms library for shared webgl shaders
*/
var UniformsLib = {
common: {
diffuse: { value: new Color( 0xeeeeee ) },
opacity: { value: 1.0 },
map: { value: null },
uvTransform: { value: new Matrix3() },
uv2Transform: { value: new Matrix3() },
alphaMap: { value: null },
},
specularmap: {
specularMap: { value: null },
},
envmap: {
envMap: { value: null },
flipEnvMap: { value: - 1 },
reflectivity: { value: 1.0 },
refractionRatio: { value: 0.98 },
maxMipLevel: { value: 0 }
},
aomap: {
aoMap: { value: null },
aoMapIntensity: { value: 1 }
},
lightmap: {
lightMap: { value: null },
lightMapIntensity: { value: 1 }
},
emissivemap: {
emissiveMap: { value: null }
},
bumpmap: {
bumpMap: { value: null },
bumpScale: { value: 1 }
},
normalmap: {
normalMap: { value: null },
normalScale: { value: new Vector2( 1, 1 ) }
},
displacementmap: {
displacementMap: { value: null },
displacementScale: { value: 1 },
displacementBias: { value: 0 }
},
roughnessmap: {
roughnessMap: { value: null }
},
metalnessmap: {
metalnessMap: { value: null }
},
gradientmap: {
gradientMap: { value: null }
},
fog: {
fogDensity: { value: 0.00025 },
fogNear: { value: 1 },
fogFar: { value: 2000 },
fogColor: { value: new Color( 0xffffff ) }
},
lights: {
ambientLightColor: { value: [] },
lightProbe: { value: [] },
directionalLights: { value: [], properties: {
direction: {},
color: {}
} },
directionalLightShadows: { value: [], properties: {
shadowBias: {},
shadowRadius: {},
shadowMapSize: {}
} },
directionalShadowMap: { value: [] },
directionalShadowMatrix: { value: [] },
spotLights: { value: [], properties: {
color: {},
position: {},
direction: {},
distance: {},
coneCos: {},
penumbraCos: {},
decay: {}
} },
spotLightShadows: { value: [], properties: {
shadowBias: {},
shadowRadius: {},
shadowMapSize: {}
} },
spotShadowMap: { value: [] },
spotShadowMatrix: { value: [] },
pointLights: { value: [], properties: {
color: {},
position: {},
decay: {},
distance: {}
} },
pointLightShadows: { value: [], properties: {
shadowBias: {},
shadowRadius: {},
shadowMapSize: {},
shadowCameraNear: {},
shadowCameraFar: {}
} },
pointShadowMap: { value: [] },
pointShadowMatrix: { value: [] },
hemisphereLights: { value: [], properties: {
direction: {},
skyColor: {},
groundColor: {}
} },
// TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
rectAreaLights: { value: [], properties: {
color: {},
position: {},
width: {},
height: {}
} }
},
points: {
diffuse: { value: new Color( 0xeeeeee ) },
opacity: { value: 1.0 },
size: { value: 1.0 },
scale: { value: 1.0 },
map: { value: null },
alphaMap: { value: null },
uvTransform: { value: new Matrix3() }
},
sprite: {
diffuse: { value: new Color( 0xeeeeee ) },
opacity: { value: 1.0 },
center: { value: new Vector2( 0.5, 0.5 ) },
rotation: { value: 0.0 },
map: { value: null },
alphaMap: { value: null },
uvTransform: { value: new Matrix3() }
}
};
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLAnimation() {
var context = null;
var isAnimating = false;
var animationLoop = null;
function onAnimationFrame( time, frame ) {
if ( isAnimating === false ) return;
animationLoop( time, frame );
context.requestAnimationFrame( onAnimationFrame );
}
return {
start: function () {
if ( isAnimating === true ) return;
if ( animationLoop === null ) return;
context.requestAnimationFrame( onAnimationFrame );
isAnimating = true;
},
stop: function () {
isAnimating = false;
},
setAnimationLoop: function ( callback ) {
animationLoop = callback;
},
setContext: function ( value ) {
context = value;
}
};
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLAttributes( gl, capabilities ) {
var isWebGL2 = capabilities.isWebGL2;
var buffers = new WeakMap();
function createBuffer( attribute, bufferType ) {
var array = attribute.array;
var usage = attribute.usage;
var buffer = gl.createBuffer();
gl.bindBuffer( bufferType, buffer );
gl.bufferData( bufferType, array, usage );
attribute.onUploadCallback();
var type = 5126;
if ( array instanceof Float32Array ) {
type = 5126;
} else if ( array instanceof Float64Array ) {
console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
} else if ( array instanceof Uint16Array ) {
type = 5123;
} else if ( array instanceof Int16Array ) {
type = 5122;
} else if ( array instanceof Uint32Array ) {
type = 5125;
} else if ( array instanceof Int32Array ) {
type = 5124;
} else if ( array instanceof Int8Array ) {
type = 5120;
} else if ( array instanceof Uint8Array ) {
type = 5121;
}
return {
buffer: buffer,
type: type,
bytesPerElement: array.BYTES_PER_ELEMENT,
version: attribute.version
};
}
function updateBuffer( buffer, attribute, bufferType ) {
var array = attribute.array;
var updateRange = attribute.updateRange;
gl.bindBuffer( bufferType, buffer );
if ( updateRange.count === - 1 ) {
// Not using update ranges
gl.bufferSubData( bufferType, 0, array );
} else {
if ( isWebGL2 ) {
gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
array, updateRange.offset, updateRange.count );
} else {
gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
}
updateRange.count = - 1; // reset range
}
}
//
function get( attribute ) {
if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
return buffers.get( attribute );
}
function remove( attribute ) {
if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
var data = buffers.get( attribute );
if ( data ) {
gl.deleteBuffer( data.buffer );
buffers.delete( attribute );
}
}
function update( attribute, bufferType ) {
if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
var data = buffers.get( attribute );
if ( data === undefined ) {
buffers.set( attribute, createBuffer( attribute, bufferType ) );
} else if ( data.version < attribute.version ) {
updateBuffer( data.buffer, attribute, bufferType );
data.version = attribute.version;
}
}
return {
get: get,
remove: remove,
update: update
};
}
/**
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / https://github.com/Mugen87
*/
// PlaneGeometry
function PlaneGeometry( width, height, widthSegments, heightSegments ) {
Geometry.call( this );
this.type = 'PlaneGeometry';
this.parameters = {
width: width,
height: height,
widthSegments: widthSegments,
heightSegments: heightSegments
};
this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
this.mergeVertices();
}
PlaneGeometry.prototype = Object.create( Geometry.prototype );
PlaneGeometry.prototype.constructor = PlaneGeometry;
// PlaneBufferGeometry
function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
BufferGeometry.call( this );
this.type = 'PlaneBufferGeometry';
this.parameters = {
width: width,
height: height,
widthSegments: widthSegments,
heightSegments: heightSegments
};
width = width || 1;
height = height || 1;
var width_half = width / 2;
var height_half = height / 2;
var gridX = Math.floor( widthSegments ) || 1;
var gridY = Math.floor( heightSegments ) || 1;
var gridX1 = gridX + 1;
var gridY1 = gridY + 1;
var segment_width = width / gridX;
var segment_height = height / gridY;
var ix, iy;
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
// generate vertices, normals and uvs
for ( iy = 0; iy < gridY1; iy ++ ) {
var y = iy * segment_height - height_half;
for ( ix = 0; ix < gridX1; ix ++ ) {
var x = ix * segment_width - width_half;
vertices.push( x, - y, 0 );
normals.push( 0, 0, 1 );
uvs.push( ix / gridX );
uvs.push( 1 - ( iy / gridY ) );
}
}
// indices
for ( iy = 0; iy < gridY; iy ++ ) {
for ( ix = 0; ix < gridX; ix ++ ) {
var a = ix + gridX1 * iy;
var b = ix + gridX1 * ( iy + 1 );
var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
var d = ( ix + 1 ) + gridX1 * iy;
// faces
indices.push( a, b, d );
indices.push( b, c, d );
}
}
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
}
PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
var begin_vertex = "vec3 transformed = vec3( position );";
var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}";
var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_maxMipLevel 8.0\n#define cubeUV_minMipLevel 4.0\n#define cubeUV_maxTileSize 256.0\n#define cubeUV_minTileSize 16.0\nfloat getFace(vec3 direction) {\n vec3 absDirection = abs(direction);\n float face = -1.0;\n if (absDirection.x > absDirection.z) {\n if (absDirection.x > absDirection.y)\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if (absDirection.z > absDirection.y)\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n}\nvec2 getUV(vec3 direction, float face) {\n vec2 uv;\n if (face == 0.0) {\n uv = vec2(-direction.z, direction.y) / abs(direction.x);\n } else if (face == 1.0) {\n uv = vec2(direction.x, -direction.z) / abs(direction.y);\n } else if (face == 2.0) {\n uv = direction.xy / abs(direction.z);\n } else if (face == 3.0) {\n uv = vec2(direction.z, direction.y) / abs(direction.x);\n } else if (face == 4.0) {\n uv = direction.xz / abs(direction.y);\n } else {\n uv = vec2(-direction.x, direction.y) / abs(direction.z);\n }\n return 0.5 * (uv + 1.0);\n}\nvec3 bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) {\n float face = getFace(direction);\n float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0);\n mipInt = max(mipInt, cubeUV_minMipLevel);\n float faceSize = exp2(mipInt);\n float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize);\n vec2 uv = getUV(direction, face) * (faceSize - 1.0);\n vec2 f = fract(uv);\n uv += 0.5 - f;\n if (face > 2.0) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n if(mipInt < cubeUV_maxMipLevel){\n uv.y += 2.0 * cubeUV_maxTileSize;\n }\n uv.y += filterInt * 2.0 * cubeUV_minTileSize;\n uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize);\n uv *= texelSize;\n vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x += texelSize;\n vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.y += texelSize;\n vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x -= texelSize;\n vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n vec3 tm = mix(tl, tr, f.x);\n vec3 bm = mix(bl, br, f.x);\n return mix(tm, bm, f.y);\n}\n#define r0 1.0\n#define v0 0.339\n#define m0 -2.0\n#define r1 0.8\n#define v1 0.276\n#define m1 -1.0\n#define r4 0.4\n#define v4 0.046\n#define m4 2.0\n#define r5 0.305\n#define v5 0.016\n#define m5 3.0\n#define r6 0.21\n#define v6 0.0038\n#define m6 4.0\nfloat roughnessToMip(float roughness) {\n float mip = 0.0;\n if (roughness >= r1) {\n mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0;\n } else if (roughness >= r4) {\n mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1;\n } else if (roughness >= r5) {\n mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4;\n } else if (roughness >= r6) {\n mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5;\n } else {\n mip = -2.0 * log2(1.16 * roughness); }\n return mip;\n}\nvec4 textureCubeUV(sampler2D envMap, vec3 sampleDir, float roughness) {\n float mip = clamp(roughnessToMip(roughness), m0, cubeUV_maxMipLevel);\n float mipF = fract(mip);\n float mipInt = floor(mip);\n vec3 color0 = bilinearCubeUV(envMap, sampleDir, mipInt);\n if (mipF == 0.0) {\n return vec4(color0, 1.0);\n } else {\n vec3 color1 = bilinearCubeUV(envMap, sampleDir, mipInt + 1.0);\n return vec4(mix(color0, color1, mipF), 1.0);\n }\n}\n#endif";
var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\t\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) { \n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";
var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}";
var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
var shadow_vert = "#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
var ShaderChunk = {
alphamap_fragment: alphamap_fragment,
alphamap_pars_fragment: alphamap_pars_fragment,
alphatest_fragment: alphatest_fragment,
aomap_fragment: aomap_fragment,
aomap_pars_fragment: aomap_pars_fragment,
begin_vertex: begin_vertex,
beginnormal_vertex: beginnormal_vertex,
bsdfs: bsdfs,
bumpmap_pars_fragment: bumpmap_pars_fragment,
clipping_planes_fragment: clipping_planes_fragment,
clipping_planes_pars_fragment: clipping_planes_pars_fragment,
clipping_planes_pars_vertex: clipping_planes_pars_vertex,
clipping_planes_vertex: clipping_planes_vertex,
color_fragment: color_fragment,
color_pars_fragment: color_pars_fragment,
color_pars_vertex: color_pars_vertex,
color_vertex: color_vertex,
common: common,
cube_uv_reflection_fragment: cube_uv_reflection_fragment,
defaultnormal_vertex: defaultnormal_vertex,
displacementmap_pars_vertex: displacementmap_pars_vertex,
displacementmap_vertex: displacementmap_vertex,
emissivemap_fragment: emissivemap_fragment,
emissivemap_pars_fragment: emissivemap_pars_fragment,
encodings_fragment: encodings_fragment,
encodings_pars_fragment: encodings_pars_fragment,
envmap_fragment: envmap_fragment,
envmap_common_pars_fragment: envmap_common_pars_fragment,
envmap_pars_fragment: envmap_pars_fragment,
envmap_pars_vertex: envmap_pars_vertex,
envmap_physical_pars_fragment: envmap_physical_pars_fragment,
envmap_vertex: envmap_vertex,
fog_vertex: fog_vertex,
fog_pars_vertex: fog_pars_vertex,
fog_fragment: fog_fragment,
fog_pars_fragment: fog_pars_fragment,
gradientmap_pars_fragment: gradientmap_pars_fragment,
lightmap_fragment: lightmap_fragment,
lightmap_pars_fragment: lightmap_pars_fragment,
lights_lambert_vertex: lights_lambert_vertex,
lights_pars_begin: lights_pars_begin,
lights_toon_fragment: lights_toon_fragment,
lights_toon_pars_fragment: lights_toon_pars_fragment,
lights_phong_fragment: lights_phong_fragment,
lights_phong_pars_fragment: lights_phong_pars_fragment,
lights_physical_fragment: lights_physical_fragment,
lights_physical_pars_fragment: lights_physical_pars_fragment,
lights_fragment_begin: lights_fragment_begin,
lights_fragment_maps: lights_fragment_maps,
lights_fragment_end: lights_fragment_end,
logdepthbuf_fragment: logdepthbuf_fragment,
logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
logdepthbuf_vertex: logdepthbuf_vertex,
map_fragment: map_fragment,
map_pars_fragment: map_pars_fragment,
map_particle_fragment: map_particle_fragment,
map_particle_pars_fragment: map_particle_pars_fragment,
metalnessmap_fragment: metalnessmap_fragment,
metalnessmap_pars_fragment: metalnessmap_pars_fragment,
morphnormal_vertex: morphnormal_vertex,
morphtarget_pars_vertex: morphtarget_pars_vertex,
morphtarget_vertex: morphtarget_vertex,
normal_fragment_begin: normal_fragment_begin,
normal_fragment_maps: normal_fragment_maps,
normalmap_pars_fragment: normalmap_pars_fragment,
clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
clearcoat_pars_fragment: clearcoat_pars_fragment,
packing: packing,
premultiplied_alpha_fragment: premultiplied_alpha_fragment,
project_vertex: project_vertex,
dithering_fragment: dithering_fragment,
dithering_pars_fragment: dithering_pars_fragment,
roughnessmap_fragment: roughnessmap_fragment,
roughnessmap_pars_fragment: roughnessmap_pars_fragment,
shadowmap_pars_fragment: shadowmap_pars_fragment,
shadowmap_pars_vertex: shadowmap_pars_vertex,
shadowmap_vertex: shadowmap_vertex,
shadowmask_pars_fragment: shadowmask_pars_fragment,
skinbase_vertex: skinbase_vertex,
skinning_pars_vertex: skinning_pars_vertex,
skinning_vertex: skinning_vertex,
skinnormal_vertex: skinnormal_vertex,
specularmap_fragment: specularmap_fragment,
specularmap_pars_fragment: specularmap_pars_fragment,
tonemapping_fragment: tonemapping_fragment,
tonemapping_pars_fragment: tonemapping_pars_fragment,
uv_pars_fragment: uv_pars_fragment,
uv_pars_vertex: uv_pars_vertex,
uv_vertex: uv_vertex,
uv2_pars_fragment: uv2_pars_fragment,
uv2_pars_vertex: uv2_pars_vertex,
uv2_vertex: uv2_vertex,
worldpos_vertex: worldpos_vertex,
background_frag: background_frag,
background_vert: background_vert,
cube_frag: cube_frag,
cube_vert: cube_vert,
depth_frag: depth_frag,
depth_vert: depth_vert,
distanceRGBA_frag: distanceRGBA_frag,
distanceRGBA_vert: distanceRGBA_vert,
equirect_frag: equirect_frag,
equirect_vert: equirect_vert,
linedashed_frag: linedashed_frag,
linedashed_vert: linedashed_vert,
meshbasic_frag: meshbasic_frag,
meshbasic_vert: meshbasic_vert,
meshlambert_frag: meshlambert_frag,
meshlambert_vert: meshlambert_vert,
meshmatcap_frag: meshmatcap_frag,
meshmatcap_vert: meshmatcap_vert,
meshtoon_frag: meshtoon_frag,
meshtoon_vert: meshtoon_vert,
meshphong_frag: meshphong_frag,
meshphong_vert: meshphong_vert,
meshphysical_frag: meshphysical_frag,
meshphysical_vert: meshphysical_vert,
normal_frag: normal_frag,
normal_vert: normal_vert,
points_frag: points_frag,
points_vert: points_vert,
shadow_frag: shadow_frag,
shadow_vert: shadow_vert,
sprite_frag: sprite_frag,
sprite_vert: sprite_vert
};
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
*/
var ShaderLib = {
basic: {
uniforms: mergeUniforms( [
UniformsLib.common,
UniformsLib.specularmap,
UniformsLib.envmap,
UniformsLib.aomap,
UniformsLib.lightmap,
UniformsLib.fog
] ),
vertexShader: ShaderChunk.meshbasic_vert,
fragmentShader: ShaderChunk.meshbasic_frag
},
lambert: {
uniforms: mergeUniforms( [
UniformsLib.common,
UniformsLib.specularmap,
UniformsLib.envmap,
UniformsLib.aomap,
UniformsLib.lightmap,
UniformsLib.emissivemap,
UniformsLib.fog,
UniformsLib.lights,
{
emissive: { value: new Color( 0x000000 ) }
}
] ),
vertexShader: ShaderChunk.meshlambert_vert,
fragmentShader: ShaderChunk.meshlambert_frag
},
phong: {
uniforms: mergeUniforms( [
UniformsLib.common,
UniformsLib.specularmap,
UniformsLib.envmap,
UniformsLib.aomap,
UniformsLib.lightmap,
UniformsLib.emissivemap,
UniformsLib.bumpmap,
UniformsLib.normalmap,
UniformsLib.displacementmap,
UniformsLib.fog,
UniformsLib.lights,
{
emissive: { value: new Color( 0x000000 ) },
specular: { value: new Color( 0x111111 ) },
shininess: { value: 30 }
}
] ),
vertexShader: ShaderChunk.meshphong_vert,
fragmentShader: ShaderChunk.meshphong_frag
},
standard: {
uniforms: mergeUniforms( [
UniformsLib.common,
UniformsLib.envmap,
UniformsLib.aomap,
UniformsLib.lightmap,
UniformsLib.emissivemap,
UniformsLib.bumpmap,
UniformsLib.normalmap,
UniformsLib.displacementmap,
UniformsLib.roughnessmap,
UniformsLib.metalnessmap,
UniformsLib.fog,
UniformsLib.lights,
{
emissive: { value: new Color( 0x000000 ) },
roughness: { value: 1.0 },
metalness: { value: 0.0 },
envMapIntensity: { value: 1 } // temporary
}
] ),
vertexShader: ShaderChunk.meshphysical_vert,
fragmentShader: ShaderChunk.meshphysical_frag
},
toon: {
uniforms: mergeUniforms( [
UniformsLib.common,
UniformsLib.specularmap,
UniformsLib.aomap,
UniformsLib.lightmap,
UniformsLib.emissivemap,
UniformsLib.bumpmap,
UniformsLib.normalmap,
UniformsLib.displacementmap,
UniformsLib.gradientmap,
UniformsLib.fog,
UniformsLib.lights,
{
emissive: { value: new Color( 0x000000 ) },
specular: { value: new Color( 0x111111 ) },
shininess: { value: 30 }
}
] ),
vertexShader: ShaderChunk.meshtoon_vert,
fragmentShader: ShaderChunk.meshtoon_frag
},
matcap: {
uniforms: mergeUniforms( [
UniformsLib.common,
UniformsLib.bumpmap,
UniformsLib.normalmap,
UniformsLib.displacementmap,
UniformsLib.fog,
{
matcap: { value: null }
}
] ),
vertexShader: ShaderChunk.meshmatcap_vert,
fragmentShader: ShaderChunk.meshmatcap_frag
},
points: {
uniforms: mergeUniforms( [
UniformsLib.points,
UniformsLib.fog
] ),
vertexShader: ShaderChunk.points_vert,
fragmentShader: ShaderChunk.points_frag
},
dashed: {
uniforms: mergeUniforms( [
UniformsLib.common,
UniformsLib.fog,
{
scale: { value: 1 },
dashSize: { value: 1 },
totalSize: { value: 2 }
}
] ),
vertexShader: ShaderChunk.linedashed_vert,
fragmentShader: ShaderChunk.linedashed_frag
},
depth: {
uniforms: mergeUniforms( [
UniformsLib.common,
UniformsLib.displacementmap
] ),
vertexShader: ShaderChunk.depth_vert,
fragmentShader: ShaderChunk.depth_frag
},
normal: {
uniforms: mergeUniforms( [
UniformsLib.common,
UniformsLib.bumpmap,
UniformsLib.normalmap,
UniformsLib.displacementmap,
{
opacity: { value: 1.0 }
}
] ),
vertexShader: ShaderChunk.normal_vert,
fragmentShader: ShaderChunk.normal_frag
},
sprite: {
uniforms: mergeUniforms( [
UniformsLib.sprite,
UniformsLib.fog
] ),
vertexShader: ShaderChunk.sprite_vert,
fragmentShader: ShaderChunk.sprite_frag
},
background: {
uniforms: {
uvTransform: { value: new Matrix3() },
t2D: { value: null },
},
vertexShader: ShaderChunk.background_vert,
fragmentShader: ShaderChunk.background_frag
},
/* -------------------------------------------------------------------------
// Cube map shader
------------------------------------------------------------------------- */
cube: {
uniforms: mergeUniforms( [
UniformsLib.envmap,
{
opacity: { value: 1.0 }
}
] ),
vertexShader: ShaderChunk.cube_vert,
fragmentShader: ShaderChunk.cube_frag
},
equirect: {
uniforms: {
tEquirect: { value: null },
},
vertexShader: ShaderChunk.equirect_vert,
fragmentShader: ShaderChunk.equirect_frag
},
distanceRGBA: {
uniforms: mergeUniforms( [
UniformsLib.common,
UniformsLib.displacementmap,
{
referencePosition: { value: new Vector3() },
nearDistance: { value: 1 },
farDistance: { value: 1000 }
}
] ),
vertexShader: ShaderChunk.distanceRGBA_vert,
fragmentShader: ShaderChunk.distanceRGBA_frag
},
shadow: {
uniforms: mergeUniforms( [
UniformsLib.lights,
UniformsLib.fog,
{
color: { value: new Color( 0x00000 ) },
opacity: { value: 1.0 }
},
] ),
vertexShader: ShaderChunk.shadow_vert,
fragmentShader: ShaderChunk.shadow_frag
}
};
ShaderLib.physical = {
uniforms: mergeUniforms( [
ShaderLib.standard.uniforms,
{
clearcoat: { value: 0 },
clearcoatMap: { value: null },
clearcoatRoughness: { value: 0 },
clearcoatRoughnessMap: { value: null },
clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
clearcoatNormalMap: { value: null },
sheen: { value: new Color( 0x000000 ) },
transparency: { value: 0 },
}
] ),
vertexShader: ShaderChunk.meshphysical_vert,
fragmentShader: ShaderChunk.meshphysical_frag
};
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {
var clearColor = new Color( 0x000000 );
var clearAlpha = 0;
var planeMesh;
var boxMesh;
var currentBackground = null;
var currentBackgroundVersion = 0;
var currentTonemapping = null;
function render( renderList, scene, camera, forceClear ) {
var background = scene.background;
// Ignore background in AR
// TODO: Reconsider this.
var xr = renderer.xr;
var session = xr.getSession && xr.getSession();
if ( session && session.environmentBlendMode === 'additive' ) {
background = null;
}
if ( background === null ) {
setClear( clearColor, clearAlpha );
} else if ( background && background.isColor ) {
setClear( background, 1 );
forceClear = true;
}
if ( renderer.autoClear || forceClear ) {
renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
}
if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) {
if ( boxMesh === undefined ) {
boxMesh = new Mesh(
new BoxBufferGeometry( 1, 1, 1 ),
new ShaderMaterial( {
type: 'BackgroundCubeMaterial',
uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
vertexShader: ShaderLib.cube.vertexShader,
fragmentShader: ShaderLib.cube.fragmentShader,
side: BackSide,
depthTest: false,
depthWrite: false,
fog: false
} )
);
boxMesh.geometry.deleteAttribute( 'normal' );
boxMesh.geometry.deleteAttribute( 'uv' );
boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
this.matrixWorld.copyPosition( camera.matrixWorld );
};
// enable code injection for non-built-in material
Object.defineProperty( boxMesh.material, 'envMap', {
get: function () {
return this.uniforms.envMap.value;
}
} );
objects.update( boxMesh );
}
var texture = background.isWebGLCubeRenderTarget ? background.texture : background;
boxMesh.material.uniforms.envMap.value = texture;
boxMesh.material.uniforms.flipEnvMap.value = texture.isCubeTexture ? - 1 : 1;
if ( currentBackground !== background ||
currentBackgroundVersion !== texture.version ||
currentTonemapping !== renderer.toneMapping ) {
boxMesh.material.needsUpdate = true;
currentBackground = background;
currentBackgroundVersion = texture.version;
currentTonemapping = renderer.toneMapping;
}
// push to the pre-sorted opaque render list
renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
} else if ( background && background.isTexture ) {
if ( planeMesh === undefined ) {
planeMesh = new Mesh(
new PlaneBufferGeometry( 2, 2 ),
new ShaderMaterial( {
type: 'BackgroundMaterial',
uniforms: cloneUniforms( ShaderLib.background.uniforms ),
vertexShader: ShaderLib.background.vertexShader,
fragmentShader: ShaderLib.background.fragmentShader,
side: FrontSide,
depthTest: false,
depthWrite: false,
fog: false
} )
);
planeMesh.geometry.deleteAttribute( 'normal' );
// enable code injection for non-built-in material
Object.defineProperty( planeMesh.material, 'map', {
get: function () {
return this.uniforms.t2D.value;
}
} );
objects.update( planeMesh );
}
planeMesh.material.uniforms.t2D.value = background;
if ( background.matrixAutoUpdate === true ) {
background.updateMatrix();
}
planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
if ( currentBackground !== background ||
currentBackgroundVersion !== background.version ||
currentTonemapping !== renderer.toneMapping ) {
planeMesh.material.needsUpdate = true;
currentBackground = background;
currentBackgroundVersion = background.version;
currentTonemapping = renderer.toneMapping;
}
// push to the pre-sorted opaque render list
renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
}
}
function setClear( color, alpha ) {
state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
}
return {
getClearColor: function () {
return clearColor;
},
setClearColor: function ( color, alpha ) {
clearColor.set( color );
clearAlpha = alpha !== undefined ? alpha : 1;
setClear( clearColor, clearAlpha );
},
getClearAlpha: function () {
return clearAlpha;
},
setClearAlpha: function ( alpha ) {
clearAlpha = alpha;
setClear( clearColor, clearAlpha );
},
render: render
};
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
var isWebGL2 = capabilities.isWebGL2;
var mode;
function setMode( value ) {
mode = value;
}
function render( start, count ) {
gl.drawArrays( mode, start, count );
info.update( count, mode );
}
function renderInstances( geometry, start, count, primcount ) {
if ( primcount === 0 ) return;
var extension, methodName;
if ( isWebGL2 ) {
extension = gl;
methodName = 'drawArraysInstanced';
} else {
extension = extensions.get( 'ANGLE_instanced_arrays' );
methodName = 'drawArraysInstancedANGLE';
if ( extension === null ) {
console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
return;
}
}
extension[ methodName ]( mode, start, count, primcount );
info.update( count, mode, primcount );
}
//
this.setMode = setMode;
this.render = render;
this.renderInstances = renderInstances;
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLCapabilities( gl, extensions, parameters ) {
var maxAnisotropy;
function getMaxAnisotropy() {
if ( maxAnisotropy !== undefined ) return maxAnisotropy;
var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
if ( extension !== null ) {
maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
} else {
maxAnisotropy = 0;
}
return maxAnisotropy;
}
function getMaxPrecision( precision ) {
if ( precision === 'highp' ) {
if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
return 'highp';
}
precision = 'mediump';
}
if ( precision === 'mediump' ) {
if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
return 'mediump';
}
}
return 'lowp';
}
/* eslint-disable no-undef */
var isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
/* eslint-enable no-undef */
var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
var maxPrecision = getMaxPrecision( precision );
if ( maxPrecision !== precision ) {
console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
precision = maxPrecision;
}
var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
var maxTextures = gl.getParameter( 34930 );
var maxVertexTextures = gl.getParameter( 35660 );
var maxTextureSize = gl.getParameter( 3379 );
var maxCubemapSize = gl.getParameter( 34076 );
var maxAttributes = gl.getParameter( 34921 );
var maxVertexUniforms = gl.getParameter( 36347 );
var maxVaryings = gl.getParameter( 36348 );
var maxFragmentUniforms = gl.getParameter( 36349 );
var vertexTextures = maxVertexTextures > 0;
var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
var floatVertexTextures = vertexTextures && floatFragmentTextures;
var maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
return {
isWebGL2: isWebGL2,
getMaxAnisotropy: getMaxAnisotropy,
getMaxPrecision: getMaxPrecision,
precision: precision,
logarithmicDepthBuffer: logarithmicDepthBuffer,
maxTextures: maxTextures,
maxVertexTextures: maxVertexTextures,
maxTextureSize: maxTextureSize,
maxCubemapSize: maxCubemapSize,
maxAttributes: maxAttributes,
maxVertexUniforms: maxVertexUniforms,
maxVaryings: maxVaryings,
maxFragmentUniforms: maxFragmentUniforms,
vertexTextures: vertexTextures,
floatFragmentTextures: floatFragmentTextures,
floatVertexTextures: floatVertexTextures,
maxSamples: maxSamples
};
}
/**
* @author tschw
*/
function WebGLClipping() {
var scope = this,
globalState = null,
numGlobalPlanes = 0,
localClippingEnabled = false,
renderingShadows = false,
plane = new Plane(),
viewNormalMatrix = new Matrix3(),
uniform = { value: null, needsUpdate: false };
this.uniform = uniform;
this.numPlanes = 0;
this.numIntersection = 0;
this.init = function ( planes, enableLocalClipping, camera ) {
var enabled =
planes.length !== 0 ||
enableLocalClipping ||
// enable state of previous frame - the clipping code has to
// run another frame in order to reset the state:
numGlobalPlanes !== 0 ||
localClippingEnabled;
localClippingEnabled = enableLocalClipping;
globalState = projectPlanes( planes, camera, 0 );
numGlobalPlanes = planes.length;
return enabled;
};
this.beginShadows = function () {
renderingShadows = true;
projectPlanes( null );
};
this.endShadows = function () {
renderingShadows = false;
resetGlobalState();
};
this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
// there's no local clipping
if ( renderingShadows ) {
// there's no global clipping
projectPlanes( null );
} else {
resetGlobalState();
}
} else {
var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
lGlobal = nGlobal * 4,
dstArray = cache.clippingState || null;
uniform.value = dstArray; // ensure unique state
dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
for ( var i = 0; i !== lGlobal; ++ i ) {
dstArray[ i ] = globalState[ i ];
}
cache.clippingState = dstArray;
this.numIntersection = clipIntersection ? this.numPlanes : 0;
this.numPlanes += nGlobal;
}
};
function resetGlobalState() {
if ( uniform.value !== globalState ) {
uniform.value = globalState;
uniform.needsUpdate = numGlobalPlanes > 0;
}
scope.numPlanes = numGlobalPlanes;
scope.numIntersection = 0;
}
function projectPlanes( planes, camera, dstOffset, skipTransform ) {
var nPlanes = planes !== null ? planes.length : 0,
dstArray = null;
if ( nPlanes !== 0 ) {
dstArray = uniform.value;
if ( skipTransform !== true || dstArray === null ) {
var flatSize = dstOffset + nPlanes * 4,
viewMatrix = camera.matrixWorldInverse;
viewNormalMatrix.getNormalMatrix( viewMatrix );
if ( dstArray === null || dstArray.length < flatSize ) {
dstArray = new Float32Array( flatSize );
}
for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
plane.normal.toArray( dstArray, i4 );
dstArray[ i4 + 3 ] = plane.constant;
}
}
uniform.value = dstArray;
uniform.needsUpdate = true;
}
scope.numPlanes = nPlanes;
scope.numIntersection = 0;
return dstArray;
}
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLExtensions( gl ) {
var extensions = {};
return {
get: function ( name ) {
if ( extensions[ name ] !== undefined ) {
return extensions[ name ];
}
var extension;
switch ( name ) {
case 'WEBGL_depth_texture':
extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
break;
case 'EXT_texture_filter_anisotropic':
extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
break;
case 'WEBGL_compressed_texture_s3tc':
extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
break;
case 'WEBGL_compressed_texture_pvrtc':
extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
break;
default:
extension = gl.getExtension( name );
}
if ( extension === null ) {
console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
}
extensions[ name ] = extension;
return extension;
}
};
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLGeometries( gl, attributes, info ) {
var geometries = new WeakMap();
var wireframeAttributes = new WeakMap();
function onGeometryDispose( event ) {
var geometry = event.target;
var buffergeometry = geometries.get( geometry );
if ( buffergeometry.index !== null ) {
attributes.remove( buffergeometry.index );
}
for ( var name in buffergeometry.attributes ) {
attributes.remove( buffergeometry.attributes[ name ] );
}
geometry.removeEventListener( 'dispose', onGeometryDispose );
geometries.delete( geometry );
var attribute = wireframeAttributes.get( buffergeometry );
if ( attribute ) {
attributes.remove( attribute );
wireframeAttributes.delete( buffergeometry );
}
//
info.memory.geometries --;
}
function get( object, geometry ) {
var buffergeometry = geometries.get( geometry );
if ( buffergeometry ) return buffergeometry;
geometry.addEventListener( 'dispose', onGeometryDispose );
if ( geometry.isBufferGeometry ) {
buffergeometry = geometry;
} else if ( geometry.isGeometry ) {
if ( geometry._bufferGeometry === undefined ) {
geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
}
buffergeometry = geometry._bufferGeometry;
}
geometries.set( geometry, buffergeometry );
info.memory.geometries ++;
return buffergeometry;
}
function update( geometry ) {
var index = geometry.index;
var geometryAttributes = geometry.attributes;
if ( index !== null ) {
attributes.update( index, 34963 );
}
for ( var name in geometryAttributes ) {
attributes.update( geometryAttributes[ name ], 34962 );
}
// morph targets
var morphAttributes = geometry.morphAttributes;
for ( var name in morphAttributes ) {
var array = morphAttributes[ name ];
for ( var i = 0, l = array.length; i < l; i ++ ) {
attributes.update( array[ i ], 34962 );
}
}
}
function updateWireframeAttribute( geometry ) {
var indices = [];
var geometryIndex = geometry.index;
var geometryPosition = geometry.attributes.position;
var version = 0;
if ( geometryIndex !== null ) {
var array = geometryIndex.array;
version = geometryIndex.version;
for ( var i = 0, l = array.length; i < l; i += 3 ) {
var a = array[ i + 0 ];
var b = array[ i + 1 ];
var c = array[ i + 2 ];
indices.push( a, b, b, c, c, a );
}
} else {
var array = geometryPosition.array;
version = geometryPosition.version;
for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
var a = i + 0;
var b = i + 1;
var c = i + 2;
indices.push( a, b, b, c, c, a );
}
}
var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
attribute.version = version;
attributes.update( attribute, 34963 );
//
var previousAttribute = wireframeAttributes.get( geometry );
if ( previousAttribute ) attributes.remove( previousAttribute );
//
wireframeAttributes.set( geometry, attribute );
}
function getWireframeAttribute( geometry ) {
var currentAttribute = wireframeAttributes.get( geometry );
if ( currentAttribute ) {
var geometryIndex = geometry.index;
if ( geometryIndex !== null ) {
// if the attribute is obsolete, create a new one
if ( currentAttribute.version < geometryIndex.version ) {
updateWireframeAttribute( geometry );
}
}
} else {
updateWireframeAttribute( geometry );
}
return wireframeAttributes.get( geometry );
}
return {
get: get,
update: update,
getWireframeAttribute: getWireframeAttribute
};
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
var isWebGL2 = capabilities.isWebGL2;
var mode;
function setMode( value ) {
mode = value;
}
var type, bytesPerElement;
function setIndex( value ) {
type = value.type;
bytesPerElement = value.bytesPerElement;
}
function render( start, count ) {
gl.drawElements( mode, count, type, start * bytesPerElement );
info.update( count, mode );
}
function renderInstances( geometry, start, count, primcount ) {
if ( primcount === 0 ) return;
var extension, methodName;
if ( isWebGL2 ) {
extension = gl;
methodName = 'drawElementsInstanced';
} else {
extension = extensions.get( 'ANGLE_instanced_arrays' );
methodName = 'drawElementsInstancedANGLE';
if ( extension === null ) {
console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
return;
}
}
extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
info.update( count, mode, primcount );
}
//
this.setMode = setMode;
this.setIndex = setIndex;
this.render = render;
this.renderInstances = renderInstances;
}
/**
* @author Mugen87 / https://github.com/Mugen87
*/
function WebGLInfo( gl ) {
var memory = {
geometries: 0,
textures: 0
};
var render = {
frame: 0,
calls: 0,
triangles: 0,
points: 0,
lines: 0
};
function update( count, mode, instanceCount ) {
instanceCount = instanceCount || 1;
render.calls ++;
switch ( mode ) {
case 4:
render.triangles += instanceCount * ( count / 3 );
break;
case 1:
render.lines += instanceCount * ( count / 2 );
break;
case 3:
render.lines += instanceCount * ( count - 1 );
break;
case 2:
render.lines += instanceCount * count;
break;
case 0:
render.points += instanceCount * count;
break;
default:
console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
break;
}
}
function reset() {
render.frame ++;
render.calls = 0;
render.triangles = 0;
render.points = 0;
render.lines = 0;
}
return {
memory: memory,
render: render,
programs: null,
autoReset: true,
reset: reset,
update: update
};
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function absNumericalSort( a, b ) {
return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
}
function WebGLMorphtargets( gl ) {
var influencesList = {};
var morphInfluences = new Float32Array( 8 );
function update( object, geometry, material, program ) {
var objectInfluences = object.morphTargetInfluences;
// When object doesn't have morph target influences defined, we treat it as a 0-length array
// This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
var length = objectInfluences === undefined ? 0 : objectInfluences.length;
var influences = influencesList[ geometry.id ];
if ( influences === undefined ) {
// initialise list
influences = [];
for ( var i = 0; i < length; i ++ ) {
influences[ i ] = [ i, 0 ];
}
influencesList[ geometry.id ] = influences;
}
var morphTargets = material.morphTargets && geometry.morphAttributes.position;
var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
// Remove current morphAttributes
for ( var i = 0; i < length; i ++ ) {
var influence = influences[ i ];
if ( influence[ 1 ] !== 0 ) {
if ( morphTargets ) geometry.deleteAttribute( 'morphTarget' + i );
if ( morphNormals ) geometry.deleteAttribute( 'morphNormal' + i );
}
}
// Collect influences
for ( var i = 0; i < length; i ++ ) {
var influence = influences[ i ];
influence[ 0 ] = i;
influence[ 1 ] = objectInfluences[ i ];
}
influences.sort( absNumericalSort );
// Add morphAttributes
var morphInfluencesSum = 0;
for ( var i = 0; i < 8; i ++ ) {
var influence = influences[ i ];
if ( influence ) {
var index = influence[ 0 ];
var value = influence[ 1 ];
if ( value ) {
if ( morphTargets ) geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
if ( morphNormals ) geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
morphInfluences[ i ] = value;
morphInfluencesSum += value;
continue;
}
}
morphInfluences[ i ] = 0;
}
// GLSL shader uses formula baseinfluence * base + sum(target * influence)
// This allows us to switch between absolute morphs and relative morphs without changing shader code
// When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
}
return {
update: update
};
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLObjects( gl, geometries, attributes, info ) {
var updateMap = new WeakMap();
function update( object ) {
var frame = info.render.frame;
var geometry = object.geometry;
var buffergeometry = geometries.get( object, geometry );
// Update once per frame
if ( updateMap.get( buffergeometry ) !== frame ) {
if ( geometry.isGeometry ) {
buffergeometry.updateFromObject( object );
}
geometries.update( buffergeometry );
updateMap.set( buffergeometry, frame );
}
if ( object.isInstancedMesh ) {
attributes.update( object.instanceMatrix, 34962 );
}
return buffergeometry;
}
function dispose() {
updateMap = new WeakMap();
}
return {
update: update,
dispose: dispose
};
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
images = images !== undefined ? images : [];
mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
format = format !== undefined ? format : RGBFormat;
Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
this.flipY = false;
}
CubeTexture.prototype = Object.create( Texture.prototype );
CubeTexture.prototype.constructor = CubeTexture;
CubeTexture.prototype.isCubeTexture = true;
Object.defineProperty( CubeTexture.prototype, 'images', {
get: function () {
return this.image;
},
set: function ( value ) {
this.image = value;
}
} );
/**
* @author Takahiro https://github.com/takahirox
*/
function DataTexture2DArray( data, width, height, depth ) {
Texture.call( this, null );
this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };
this.magFilter = NearestFilter;
this.minFilter = NearestFilter;
this.wrapR = ClampToEdgeWrapping;
this.generateMipmaps = false;
this.flipY = false;
this.needsUpdate = true;
}
DataTexture2DArray.prototype = Object.create( Texture.prototype );
DataTexture2DArray.prototype.constructor = DataTexture2DArray;
DataTexture2DArray.prototype.isDataTexture2DArray = true;
/**
* @author Artur Trzesiok
*/
function DataTexture3D( data, width, height, depth ) {
// We're going to add .setXXX() methods for setting properties later.
// Users can still set in DataTexture3D directly.
//
// var texture = new THREE.DataTexture3D( data, width, height, depth );
// texture.anisotropy = 16;
//
// See #14839
Texture.call( this, null );
this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };
this.magFilter = NearestFilter;
this.minFilter = NearestFilter;
this.wrapR = ClampToEdgeWrapping;
this.generateMipmaps = false;
this.flipY = false;
this.needsUpdate = true;
}
DataTexture3D.prototype = Object.create( Texture.prototype );
DataTexture3D.prototype.constructor = DataTexture3D;
DataTexture3D.prototype.isDataTexture3D = true;
/**
* @author tschw
* @author Mugen87 / https://github.com/Mugen87
* @author mrdoob / http://mrdoob.com/
*
* Uniforms of a program.
* Those form a tree structure with a special top-level container for the root,
* which you get by calling 'new WebGLUniforms( gl, program )'.
*
*
* Properties of inner nodes including the top-level container:
*
* .seq - array of nested uniforms
* .map - nested uniforms by name
*
*
* Methods of all nodes except the top-level container:
*
* .setValue( gl, value, [textures] )
*
* uploads a uniform value(s)
* the 'textures' parameter is needed for sampler uniforms
*
*
* Static methods of the top-level container (textures factorizations):
*
* .upload( gl, seq, values, textures )
*
* sets uniforms in 'seq' to 'values[id].value'
*
* .seqWithValue( seq, values ) : filteredSeq
*
* filters 'seq' entries with corresponding entry in values
*
*
* Methods of the top-level container (textures factorizations):
*
* .setValue( gl, name, value, textures )
*
* sets uniform with name 'name' to 'value'
*
* .setOptional( gl, obj, prop )
*
* like .set for an optional property of the object
*
*/
var emptyTexture = new Texture();
var emptyTexture2dArray = new DataTexture2DArray();
var emptyTexture3d = new DataTexture3D();
var emptyCubeTexture = new CubeTexture();
// --- Utilities ---
// Array Caches (provide typed arrays for temporary by size)
var arrayCacheF32 = [];
var arrayCacheI32 = [];
// Float32Array caches used for uploading Matrix uniforms
var mat4array = new Float32Array( 16 );
var mat3array = new Float32Array( 9 );
var mat2array = new Float32Array( 4 );
// Flattening for arrays of vectors and matrices
function flatten( array, nBlocks, blockSize ) {
var firstElem = array[ 0 ];
if ( firstElem <= 0 || firstElem > 0 ) return array;
// unoptimized: ! isNaN( firstElem )
// see http://jacksondunstan.com/articles/983
var n = nBlocks * blockSize,
r = arrayCacheF32[ n ];
if ( r === undefined ) {
r = new Float32Array( n );
arrayCacheF32[ n ] = r;
}
if ( nBlocks !== 0 ) {
firstElem.toArray( r, 0 );
for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
offset += blockSize;
array[ i ].toArray( r, offset );
}
}
return r;
}
function arraysEqual( a, b ) {
if ( a.length !== b.length ) return false;
for ( var i = 0, l = a.length; i < l; i ++ ) {
if ( a[ i ] !== b[ i ] ) return false;
}
return true;
}
function copyArray( a, b ) {
for ( var i = 0, l = b.length; i < l; i ++ ) {
a[ i ] = b[ i ];
}
}
// Texture unit allocation
function allocTexUnits( textures, n ) {
var r = arrayCacheI32[ n ];
if ( r === undefined ) {
r = new Int32Array( n );
arrayCacheI32[ n ] = r;
}
for ( var i = 0; i !== n; ++ i )
r[ i ] = textures.allocateTextureUnit();
return r;
}
// --- Setters ---
// Note: Defining these methods externally, because they come in a bunch
// and this way their names minify.
// Single scalar
function setValueV1f( gl, v ) {
var cache = this.cache;
if ( cache[ 0 ] === v ) return;
gl.uniform1f( this.addr, v );
cache[ 0 ] = v;
}
// Single float vector (from flat array or THREE.VectorN)
function setValueV2f( gl, v ) {
var cache = this.cache;
if ( v.x !== undefined ) {
if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
gl.uniform2f( this.addr, v.x, v.y );
cache[ 0 ] = v.x;
cache[ 1 ] = v.y;
}
} else {
if ( arraysEqual( cache, v ) ) return;
gl.uniform2fv( this.addr, v );
copyArray( cache, v );
}
}
function setValueV3f( gl, v ) {
var cache = this.cache;
if ( v.x !== undefined ) {
if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
gl.uniform3f( this.addr, v.x, v.y, v.z );
cache[ 0 ] = v.x;
cache[ 1 ] = v.y;
cache[ 2 ] = v.z;
}
} else if ( v.r !== undefined ) {
if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
gl.uniform3f( this.addr, v.r, v.g, v.b );
cache[ 0 ] = v.r;
cache[ 1 ] = v.g;
cache[ 2 ] = v.b;
}
} else {
if ( arraysEqual( cache, v ) ) return;
gl.uniform3fv( this.addr, v );
copyArray( cache, v );
}
}
function setValueV4f( gl, v ) {
var cache = this.cache;
if ( v.x !== undefined ) {
if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
cache[ 0 ] = v.x;
cache[ 1 ] = v.y;
cache[ 2 ] = v.z;
cache[ 3 ] = v.w;
}
} else {
if ( arraysEqual( cache, v ) ) return;
gl.uniform4fv( this.addr, v );
copyArray( cache, v );
}
}
// Single matrix (from flat array or MatrixN)
function setValueM2( gl, v ) {
var cache = this.cache;
var elements = v.elements;
if ( elements === undefined ) {
if ( arraysEqual( cache, v ) ) return;
gl.uniformMatrix2fv( this.addr, false, v );
copyArray( cache, v );
} else {
if ( arraysEqual( cache, elements ) ) return;
mat2array.set( elements );
gl.uniformMatrix2fv( this.addr, false, mat2array );
copyArray( cache, elements );
}
}
function setValueM3( gl, v ) {
var cache = this.cache;
var elements = v.elements;
if ( elements === undefined ) {
if ( arraysEqual( cache, v ) ) return;
gl.uniformMatrix3fv( this.addr, false, v );
copyArray( cache, v );
} else {
if ( arraysEqual( cache, elements ) ) return;
mat3array.set( elements );
gl.uniformMatrix3fv( this.addr, false, mat3array );
copyArray( cache, elements );
}
}
function setValueM4( gl, v ) {
var cache = this.cache;
var elements = v.elements;
if ( elements === undefined ) {
if ( arraysEqual( cache, v ) ) return;
gl.uniformMatrix4fv( this.addr, false, v );
copyArray( cache, v );
} else {
if ( arraysEqual( cache, elements ) ) return;
mat4array.set( elements );
gl.uniformMatrix4fv( this.addr, false, mat4array );
copyArray( cache, elements );
}
}
// Single texture (2D / Cube)
function setValueT1( gl, v, textures ) {
var cache = this.cache;
var unit = textures.allocateTextureUnit();
if ( cache[ 0 ] !== unit ) {
gl.uniform1i( this.addr, unit );
cache[ 0 ] = unit;
}
textures.safeSetTexture2D( v || emptyTexture, unit );
}
function setValueT2DArray1( gl, v, textures ) {
var cache = this.cache;
var unit = textures.allocateTextureUnit();
if ( cache[ 0 ] !== unit ) {
gl.uniform1i( this.addr, unit );
cache[ 0 ] = unit;
}
textures.setTexture2DArray( v || emptyTexture2dArray, unit );
}
function setValueT3D1( gl, v, textures ) {
var cache = this.cache;
var unit = textures.allocateTextureUnit();
if ( cache[ 0 ] !== unit ) {
gl.uniform1i( this.addr, unit );
cache[ 0 ] = unit;
}
textures.setTexture3D( v || emptyTexture3d, unit );
}
function setValueT6( gl, v, textures ) {
var cache = this.cache;
var unit = textures.allocateTextureUnit();
if ( cache[ 0 ] !== unit ) {
gl.uniform1i( this.addr, unit );
cache[ 0 ] = unit;
}
textures.safeSetTextureCube( v || emptyCubeTexture, unit );
}
// Integer / Boolean vectors or arrays thereof (always flat arrays)
function setValueV1i( gl, v ) {
var cache = this.cache;
if ( cache[ 0 ] === v ) return;
gl.uniform1i( this.addr, v );
cache[ 0 ] = v;
}
function setValueV2i( gl, v ) {
var cache = this.cache;
if ( arraysEqual( cache, v ) ) return;
gl.uniform2iv( this.addr, v );
copyArray( cache, v );
}
function setValueV3i( gl, v ) {
var cache = this.cache;
if ( arraysEqual( cache, v ) ) return;
gl.uniform3iv( this.addr, v );
copyArray( cache, v );
}
function setValueV4i( gl, v ) {
var cache = this.cache;
if ( arraysEqual( cache, v ) ) return;
gl.uniform4iv( this.addr, v );
copyArray( cache, v );
}
// uint
function setValueV1ui( gl, v ) {
var cache = this.cache;
if ( cache[ 0 ] === v ) return;
gl.uniform1ui( this.addr, v );
cache[ 0 ] = v;
}
// Helper to pick the right setter for the singular case
function getSingularSetter( type ) {
switch ( type ) {
case 0x1406: return setValueV1f; // FLOAT
case 0x8b50: return setValueV2f; // _VEC2
case 0x8b51: return setValueV3f; // _VEC3
case 0x8b52: return setValueV4f; // _VEC4
case 0x8b5a: return setValueM2; // _MAT2
case 0x8b5b: return setValueM3; // _MAT3
case 0x8b5c: return setValueM4; // _MAT4
case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
case 0x1405: return setValueV1ui; // UINT
case 0x8b5e: // SAMPLER_2D
case 0x8d66: // SAMPLER_EXTERNAL_OES
case 0x8dca: // INT_SAMPLER_2D
case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
case 0x8b62: // SAMPLER_2D_SHADOW
return setValueT1;
case 0x8b5f: // SAMPLER_3D
case 0x8dcb: // INT_SAMPLER_3D
case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
return setValueT3D1;
case 0x8b60: // SAMPLER_CUBE
case 0x8dcc: // INT_SAMPLER_CUBE
case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
case 0x8dc5: // SAMPLER_CUBE_SHADOW
return setValueT6;
case 0x8dc1: // SAMPLER_2D_ARRAY
case 0x8dcf: // INT_SAMPLER_2D_ARRAY
case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
return setValueT2DArray1;
}
}
// Array of scalars
function setValueV1fArray( gl, v ) {
gl.uniform1fv( this.addr, v );
}
// Integer / Boolean vectors or arrays thereof (always flat arrays)
function setValueV1iArray( gl, v ) {
gl.uniform1iv( this.addr, v );
}
function setValueV2iArray( gl, v ) {
gl.uniform2iv( this.addr, v );
}
function setValueV3iArray( gl, v ) {
gl.uniform3iv( this.addr, v );
}
function setValueV4iArray( gl, v ) {
gl.uniform4iv( this.addr, v );
}
// Array of vectors (flat or from THREE classes)
function setValueV2fArray( gl, v ) {
var data = flatten( v, this.size, 2 );
gl.uniform2fv( this.addr, data );
}
function setValueV3fArray( gl, v ) {
var data = flatten( v, this.size, 3 );
gl.uniform3fv( this.addr, data );
}
function setValueV4fArray( gl, v ) {
var data = flatten( v, this.size, 4 );
gl.uniform4fv( this.addr, data );
}
// Array of matrices (flat or from THREE clases)
function setValueM2Array( gl, v ) {
var data = flatten( v, this.size, 4 );
gl.uniformMatrix2fv( this.addr, false, data );
}
function setValueM3Array( gl, v ) {
var data = flatten( v, this.size, 9 );
gl.uniformMatrix3fv( this.addr, false, data );
}
function setValueM4Array( gl, v ) {
var data = flatten( v, this.size, 16 );
gl.uniformMatrix4fv( this.addr, false, data );
}
// Array of textures (2D / Cube)
function setValueT1Array( gl, v, textures ) {
var n = v.length;
var units = allocTexUnits( textures, n );
gl.uniform1iv( this.addr, units );
for ( var i = 0; i !== n; ++ i ) {
textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
}
}
function setValueT6Array( gl, v, textures ) {
var n = v.length;
var units = allocTexUnits( textures, n );
gl.uniform1iv( this.addr, units );
for ( var i = 0; i !== n; ++ i ) {
textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
}
}
// Helper to pick the right setter for a pure (bottom-level) array
function getPureArraySetter( type ) {
switch ( type ) {
case 0x1406: return setValueV1fArray; // FLOAT
case 0x8b50: return setValueV2fArray; // _VEC2
case 0x8b51: return setValueV3fArray; // _VEC3
case 0x8b52: return setValueV4fArray; // _VEC4
case 0x8b5a: return setValueM2Array; // _MAT2
case 0x8b5b: return setValueM3Array; // _MAT3
case 0x8b5c: return setValueM4Array; // _MAT4
case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
case 0x8b5e: // SAMPLER_2D
case 0x8d66: // SAMPLER_EXTERNAL_OES
case 0x8dca: // INT_SAMPLER_2D
case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
case 0x8b62: // SAMPLER_2D_SHADOW
return setValueT1Array;
case 0x8b60: // SAMPLER_CUBE
case 0x8dcc: // INT_SAMPLER_CUBE
case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
case 0x8dc5: // SAMPLER_CUBE_SHADOW
return setValueT6Array;
}
}
// --- Uniform Classes ---
function SingleUniform( id, activeInfo, addr ) {
this.id = id;
this.addr = addr;
this.cache = [];
this.setValue = getSingularSetter( activeInfo.type );
// this.path = activeInfo.name; // DEBUG
}
function PureArrayUniform( id, activeInfo, addr ) {
this.id = id;
this.addr = addr;
this.cache = [];
this.size = activeInfo.size;
this.setValue = getPureArraySetter( activeInfo.type );
// this.path = activeInfo.name; // DEBUG
}
PureArrayUniform.prototype.updateCache = function ( data ) {
var cache = this.cache;
if ( data instanceof Float32Array && cache.length !== data.length ) {
this.cache = new Float32Array( data.length );
}
copyArray( cache, data );
};
function StructuredUniform( id ) {
this.id = id;
this.seq = [];
this.map = {};
}
StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
var seq = this.seq;
for ( var i = 0, n = seq.length; i !== n; ++ i ) {
var u = seq[ i ];
u.setValue( gl, value[ u.id ], textures );
}
};
// --- Top-level ---
// Parser - builds up the property tree from the path strings
var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
// extracts
// - the identifier (member name or array index)
// - followed by an optional right bracket (found when array index)
// - followed by an optional left bracket or dot (type of subscript)
//
// Note: These portions can be read in a non-overlapping fashion and
// allow straightforward parsing of the hierarchy that WebGL encodes
// in the uniform names.
function addUniform( container, uniformObject ) {
container.seq.push( uniformObject );
container.map[ uniformObject.id ] = uniformObject;
}
function parseUniform( activeInfo, addr, container ) {
var path = activeInfo.name,
pathLength = path.length;
// reset RegExp object, because of the early exit of a previous run
RePathPart.lastIndex = 0;
while ( true ) {
var match = RePathPart.exec( path ),
matchEnd = RePathPart.lastIndex,
id = match[ 1 ],
idIsIndex = match[ 2 ] === ']',
subscript = match[ 3 ];
if ( idIsIndex ) id = id | 0; // convert to integer
if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
// bare name or "pure" bottom-level array "[0]" suffix
addUniform( container, subscript === undefined ?
new SingleUniform( id, activeInfo, addr ) :
new PureArrayUniform( id, activeInfo, addr ) );
break;
} else {
// step into inner node / create it in case it doesn't exist
var map = container.map, next = map[ id ];
if ( next === undefined ) {
next = new StructuredUniform( id );
addUniform( container, next );
}
container = next;
}
}
}
// Root Container
function WebGLUniforms( gl, program ) {
this.seq = [];
this.map = {};
var n = gl.getProgramParameter( program, 35718 );
for ( var i = 0; i < n; ++ i ) {
var info = gl.getActiveUniform( program, i ),
addr = gl.getUniformLocation( program, info.name );
parseUniform( info, addr, this );
}
}
WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
var u = this.map[ name ];
if ( u !== undefined ) u.setValue( gl, value, textures );
};
WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
var v = object[ name ];
if ( v !== undefined ) this.setValue( gl, name, v );
};
// Static interface
WebGLUniforms.upload = function ( gl, seq, values, textures ) {
for ( var i = 0, n = seq.length; i !== n; ++ i ) {
var u = seq[ i ],
v = values[ u.id ];
if ( v.needsUpdate !== false ) {
// note: always updating when .needsUpdate is undefined
u.setValue( gl, v.value, textures );
}
}
};
WebGLUniforms.seqWithValue = function ( seq, values ) {
var r = [];
for ( var i = 0, n = seq.length; i !== n; ++ i ) {
var u = seq[ i ];
if ( u.id in values ) r.push( u );
}
return r;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLShader( gl, type, string ) {
var shader = gl.createShader( type );
gl.shaderSource( shader, string );
gl.compileShader( shader );
return shader;
}
/**
* @author mrdoob / http://mrdoob.com/
*/
var programIdCount = 0;
function addLineNumbers( string ) {
var lines = string.split( '\n' );
for ( var i = 0; i < lines.length; i ++ ) {
lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
}
return lines.join( '\n' );
}
function getEncodingComponents( encoding ) {
switch ( encoding ) {
case LinearEncoding:
return [ 'Linear', '( value )' ];
case sRGBEncoding:
return [ 'sRGB', '( value )' ];
case RGBEEncoding:
return [ 'RGBE', '( value )' ];
case RGBM7Encoding:
return [ 'RGBM', '( value, 7.0 )' ];
case RGBM16Encoding:
return [ 'RGBM', '( value, 16.0 )' ];
case RGBDEncoding:
return [ 'RGBD', '( value, 256.0 )' ];
case GammaEncoding:
return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
case LogLuvEncoding:
return [ 'LogLuv', '( value )' ];
default:
throw new Error( 'unsupported encoding: ' + encoding );
}
}
function getShaderErrors( gl, shader, type ) {
var status = gl.getShaderParameter( shader, 35713 );
var log = gl.getShaderInfoLog( shader ).trim();
if ( status && log === '' ) return '';
// --enable-privileged-webgl-extension
// console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
var source = gl.getShaderSource( shader );
return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
}
function getTexelDecodingFunction( functionName, encoding ) {
var components = getEncodingComponents( encoding );
return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
}
function getTexelEncodingFunction( functionName, encoding ) {
var components = getEncodingComponents( encoding );
return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
}
function getToneMappingFunction( functionName, toneMapping ) {
var toneMappingName;
switch ( toneMapping ) {
case LinearToneMapping:
toneMappingName = 'Linear';
break;
case ReinhardToneMapping:
toneMappingName = 'Reinhard';
break;
case Uncharted2ToneMapping:
toneMappingName = 'Uncharted2';
break;
case CineonToneMapping:
toneMappingName = 'OptimizedCineon';
break;
case ACESFilmicToneMapping:
toneMappingName = 'ACESFilmic';
break;
default:
throw new Error( 'unsupported toneMapping: ' + toneMapping );
}
return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
}
function generateExtensions( parameters ) {
var chunks = [
( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
];
return chunks.filter( filterEmptyLine ).join( '\n' );
}
function generateDefines( defines ) {
var chunks = [];
for ( var name in defines ) {
var value = defines[ name ];
if ( value === false ) continue;
chunks.push( '#define ' + name + ' ' + value );
}
return chunks.join( '\n' );
}
function fetchAttributeLocations( gl, program ) {
var attributes = {};
var n = gl.getProgramParameter( program, 35721 );
for ( var i = 0; i < n; i ++ ) {
var info = gl.getActiveAttrib( program, i );
var name = info.name;
// console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
attributes[ name ] = gl.getAttribLocation( program, name );
}
return attributes;
}
function filterEmptyLine( string ) {
return string !== '';
}
function replaceLightNums( string, parameters ) {
return string
.replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
.replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
.replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
.replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
.replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
.replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
.replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
.replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
}
function replaceClippingPlaneNums( string, parameters ) {
return string
.replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
.replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
}
// Resolve Includes
var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
function resolveIncludes( string ) {
return string.replace( includePattern, includeReplacer );
}
function includeReplacer( match, include ) {
var string = ShaderChunk[ include ];
if ( string === undefined ) {
throw new Error( 'Can not resolve #include <' + include + '>' );
}
return resolveIncludes( string );
}
// Unroll Loops
var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
var unrollLoopPattern = /#pragma unroll_loop_start[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}[\s]+?#pragma unroll_loop_end/g;
function unrollLoops( string ) {
return string
.replace( unrollLoopPattern, loopReplacer )
.replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
}
function deprecatedLoopReplacer( match, start, end, snippet ) {
console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
return loopReplacer( match, start, end, snippet );
}
function loopReplacer( match, start, end, snippet ) {
var string = '';
for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
string += snippet
.replace( /\[ i \]/g, '[ ' + i + ' ]' )
.replace( /UNROLLED_LOOP_INDEX/g, i );
}
return string;
}
//
function generatePrecision( parameters ) {
var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
if ( parameters.precision === "highp" ) {
precisionstring += "\n#define HIGH_PRECISION";
} else if ( parameters.precision === "mediump" ) {
precisionstring += "\n#define MEDIUM_PRECISION";
} else if ( parameters.precision === "lowp" ) {
precisionstring += "\n#define LOW_PRECISION";
}
return precisionstring;
}
function generateShadowMapTypeDefine( parameters ) {
var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
if ( parameters.shadowMapType === PCFShadowMap ) {
shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
} else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
} else if ( parameters.shadowMapType === VSMShadowMap ) {
shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
}
return shadowMapTypeDefine;
}
function generateEnvMapTypeDefine( parameters ) {
var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
if ( parameters.envMap ) {
switch ( parameters.envMapMode ) {
case CubeReflectionMapping:
case CubeRefractionMapping:
envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
break;
case CubeUVReflectionMapping:
case CubeUVRefractionMapping:
envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
break;
case EquirectangularReflectionMapping:
case EquirectangularRefractionMapping:
envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
break;
case SphericalReflectionMapping:
envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
break;
}
}
return envMapTypeDefine;
}
function generateEnvMapModeDefine( parameters ) {
var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
if ( parameters.envMap ) {
switch ( parameters.envMapMode ) {
case CubeRefractionMapping:
case EquirectangularRefractionMapping:
envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
break;
}
}
return envMapModeDefine;
}
function generateEnvMapBlendingDefine( parameters ) {
var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
if ( parameters.envMap ) {
switch ( parameters.combine ) {
case MultiplyOperation:
envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
break;
case MixOperation:
envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
break;
case AddOperation:
envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
break;
}
}
return envMapBlendingDefine;
}
function WebGLProgram( renderer, cacheKey, parameters ) {
var gl = renderer.getContext();
var defines = parameters.defines;
var vertexShader = parameters.vertexShader;
var fragmentShader = parameters.fragmentShader;
var shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
var envMapTypeDefine = generateEnvMapTypeDefine( parameters );
var envMapModeDefine = generateEnvMapModeDefine( parameters );
var envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
var customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
var customDefines = generateDefines( defines );
var program = gl.createProgram();
var prefixVertex, prefixFragment;
if ( parameters.isRawShaderMaterial ) {
prefixVertex = [
customDefines
].filter( filterEmptyLine ).join( '\n' );
if ( prefixVertex.length > 0 ) {
prefixVertex += '\n';
}
prefixFragment = [
customExtensions,
customDefines
].filter( filterEmptyLine ).join( '\n' );
if ( prefixFragment.length > 0 ) {
prefixFragment += '\n';
}
} else {
prefixVertex = [
generatePrecision( parameters ),
'#define SHADER_NAME ' + parameters.shaderName,
customDefines,
parameters.instancing ? '#define USE_INSTANCING' : '',
parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
'#define GAMMA_FACTOR ' + gammaFactorDefine,
'#define MAX_BONES ' + parameters.maxBones,
( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
parameters.map ? '#define USE_MAP' : '',
parameters.envMap ? '#define USE_ENVMAP' : '',
parameters.envMap ? '#define ' + envMapModeDefine : '',
parameters.lightMap ? '#define USE_LIGHTMAP' : '',
parameters.aoMap ? '#define USE_AOMAP' : '',
parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
parameters.bumpMap ? '#define USE_BUMPMAP' : '',
parameters.normalMap ? '#define USE_NORMALMAP' : '',
( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
parameters.specularMap ? '#define USE_SPECULARMAP' : '',
parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
parameters.vertexTangents ? '#define USE_TANGENT' : '',
parameters.vertexColors ? '#define USE_COLOR' : '',
parameters.vertexUvs ? '#define USE_UV' : '',
parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
parameters.flatShading ? '#define FLAT_SHADED' : '',
parameters.skinning ? '#define USE_SKINNING' : '',
parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
parameters.flipSided ? '#define FLIP_SIDED' : '',
parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
'uniform mat4 modelMatrix;',
'uniform mat4 modelViewMatrix;',
'uniform mat4 projectionMatrix;',
'uniform mat4 viewMatrix;',
'uniform mat3 normalMatrix;',
'uniform vec3 cameraPosition;',
'uniform bool isOrthographic;',
'#ifdef USE_INSTANCING',
' attribute mat4 instanceMatrix;',
'#endif',
'attribute vec3 position;',
'attribute vec3 normal;',
'attribute vec2 uv;',
'#ifdef USE_TANGENT',
' attribute vec4 tangent;',
'#endif',
'#ifdef USE_COLOR',
' attribute vec3 color;',
'#endif',
'#ifdef USE_MORPHTARGETS',
' attribute vec3 morphTarget0;',
' attribute vec3 morphTarget1;',
' attribute vec3 morphTarget2;',
' attribute vec3 morphTarget3;',
' #ifdef USE_MORPHNORMALS',
' attribute vec3 morphNormal0;',
' attribute vec3 morphNormal1;',
' attribute vec3 morphNormal2;',
' attribute vec3 morphNormal3;',
' #else',
' attribute vec3 morphTarget4;',
' attribute vec3 morphTarget5;',
' attribute vec3 morphTarget6;',
' attribute vec3 morphTarget7;',
' #endif',
'#endif',
'#ifdef USE_SKINNING',
' attribute vec4 skinIndex;',
' attribute vec4 skinWeight;',
'#endif',
'\n'
].filter( filterEmptyLine ).join( '\n' );
prefixFragment = [
customExtensions,
generatePrecision( parameters ),
'#define SHADER_NAME ' + parameters.shaderName,
customDefines,
parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
'#define GAMMA_FACTOR ' + gammaFactorDefine,
( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
parameters.map ? '#define USE_MAP' : '',
parameters.matcap ? '#define USE_MATCAP' : '',
parameters.envMap ? '#define USE_ENVMAP' : '',
parameters.envMap ? '#define ' + envMapTypeDefine : '',
parameters.envMap ? '#define ' + envMapModeDefine : '',
parameters.envMap ? '#define ' + envMapBlendingDefine : '',
parameters.lightMap ? '#define USE_LIGHTMAP' : '',
parameters.aoMap ? '#define USE_AOMAP' : '',
parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
parameters.bumpMap ? '#define USE_BUMPMAP' : '',
parameters.normalMap ? '#define USE_NORMALMAP' : '',
( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
parameters.specularMap ? '#define USE_SPECULARMAP' : '',
parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
parameters.sheen ? '#define USE_SHEEN' : '',
parameters.vertexTangents ? '#define USE_TANGENT' : '',
parameters.vertexColors ? '#define USE_COLOR' : '',
parameters.vertexUvs ? '#define USE_UV' : '',
parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
parameters.flatShading ? '#define FLAT_SHADED' : '',
parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
parameters.flipSided ? '#define FLIP_SIDED' : '',
parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
'uniform mat4 viewMatrix;',
'uniform vec3 cameraPosition;',
'uniform bool isOrthographic;',
( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
parameters.dithering ? '#define DITHERING' : '',
( parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding || parameters.lightMapEncoding ) ?
ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
parameters.matcapEncoding ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
parameters.lightMapEncoding ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '',
parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
'\n'
].filter( filterEmptyLine ).join( '\n' );
}
vertexShader = resolveIncludes( vertexShader );
vertexShader = replaceLightNums( vertexShader, parameters );
vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
fragmentShader = resolveIncludes( fragmentShader );
fragmentShader = replaceLightNums( fragmentShader, parameters );
fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
vertexShader = unrollLoops( vertexShader );
fragmentShader = unrollLoops( fragmentShader );
if ( parameters.isWebGL2 && ! parameters.isRawShaderMaterial ) {
var isGLSL3ShaderMaterial = false;
var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
if ( parameters.isShaderMaterial &&
vertexShader.match( versionRegex ) !== null &&
fragmentShader.match( versionRegex ) !== null ) {
isGLSL3ShaderMaterial = true;
vertexShader = vertexShader.replace( versionRegex, '' );
fragmentShader = fragmentShader.replace( versionRegex, '' );
}
// GLSL 3.0 conversion
prefixVertex = [
'#version 300 es\n',
'#define attribute in',
'#define varying out',
'#define texture2D texture'
].join( '\n' ) + '\n' + prefixVertex;
prefixFragment = [
'#version 300 es\n',
'#define varying in',
isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;',
isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor',
'#define gl_FragDepthEXT gl_FragDepth',
'#define texture2D texture',
'#define textureCube texture',
'#define texture2DProj textureProj',
'#define texture2DLodEXT textureLod',
'#define texture2DProjLodEXT textureProjLod',
'#define textureCubeLodEXT textureLod',
'#define texture2DGradEXT textureGrad',
'#define texture2DProjGradEXT textureProjGrad',
'#define textureCubeGradEXT textureGrad'
].join( '\n' ) + '\n' + prefixFragment;
}
var vertexGlsl = prefixVertex + vertexShader;
var fragmentGlsl = prefixFragment + fragmentShader;
// console.log( '*VERTEX*', vertexGlsl );
// console.log( '*FRAGMENT*', fragmentGlsl );
var glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
gl.attachShader( program, glVertexShader );
gl.attachShader( program, glFragmentShader );
// Force a particular attribute to index 0.
if ( parameters.index0AttributeName !== undefined ) {
gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
} else if ( parameters.morphTargets === true ) {
// programs with morphTargets displace position out of attribute 0
gl.bindAttribLocation( program, 0, 'position' );
}
gl.linkProgram( program );
// check for link errors
if ( renderer.debug.checkShaderErrors ) {
var programLog = gl.getProgramInfoLog( program ).trim();
var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
var runnable = true;
var haveDiagnostics = true;
if ( gl.getProgramParameter( program, 35714 ) === false ) {
runnable = false;
var vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
var fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
} else if ( programLog !== '' ) {
console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
} else if ( vertexLog === '' || fragmentLog === '' ) {
haveDiagnostics = false;
}
if ( haveDiagnostics ) {
this.diagnostics = {
runnable: runnable,
programLog: programLog,
vertexShader: {
log: vertexLog,
prefix: prefixVertex
},
fragmentShader: {
log: fragmentLog,
prefix: prefixFragment
}
};
}
}
// Clean up
// Crashes in iOS9 and iOS10. #18402
// gl.detachShader( program, glVertexShader );
// gl.detachShader( program, glFragmentShader );
gl.deleteShader( glVertexShader );
gl.deleteShader( glFragmentShader );
// set up caching for uniform locations
var cachedUniforms;
this.getUniforms = function () {
if ( cachedUniforms === undefined ) {
cachedUniforms = new WebGLUniforms( gl, program );
}
return cachedUniforms;
};
// set up caching for attribute locations
var cachedAttributes;
this.getAttributes = function () {
if ( cachedAttributes === undefined ) {
cachedAttributes = fetchAttributeLocations( gl, program );
}
return cachedAttributes;
};
// free resource
this.destroy = function () {
gl.deleteProgram( program );
this.program = undefined;
};
//
this.name = parameters.shaderName;
this.id = programIdCount ++;
this.cacheKey = cacheKey;
this.usedTimes = 1;
this.program = program;
this.vertexShader = glVertexShader;
this.fragmentShader = glFragmentShader;
return this;
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLPrograms( renderer, extensions, capabilities ) {
var programs = [];
var isWebGL2 = capabilities.isWebGL2;
var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
var floatVertexTextures = capabilities.floatVertexTextures;
var precision = capabilities.precision;
var maxVertexUniforms = capabilities.maxVertexUniforms;
var vertexTextures = capabilities.vertexTextures;
var shaderIDs = {
MeshDepthMaterial: 'depth',
MeshDistanceMaterial: 'distanceRGBA',
MeshNormalMaterial: 'normal',
MeshBasicMaterial: 'basic',
MeshLambertMaterial: 'lambert',
MeshPhongMaterial: 'phong',
MeshToonMaterial: 'toon',
MeshStandardMaterial: 'physical',
MeshPhysicalMaterial: 'physical',
MeshMatcapMaterial: 'matcap',
LineBasicMaterial: 'basic',
LineDashedMaterial: 'dashed',
PointsMaterial: 'points',
ShadowMaterial: 'shadow',
SpriteMaterial: 'sprite'
};
var parameterNames = [
"precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing",
"map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV",
"lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap",
"roughnessMap", "metalnessMap", "gradientMap",
"alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2",
"flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
"maxBones", "useVertexTexture", "morphTargets", "morphNormals",
"maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
"numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
"numDirLightShadows", "numPointLightShadows", "numSpotLightShadows",
"shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
"alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering",
"sheen"
];
function getShaderObject( material, shaderID ) {
var shaderobject;
if ( shaderID ) {
var shader = ShaderLib[ shaderID ];
shaderobject = {
name: material.type,
uniforms: UniformsUtils.clone( shader.uniforms ),
vertexShader: shader.vertexShader,
fragmentShader: shader.fragmentShader
};
} else {
shaderobject = {
name: material.type,
uniforms: material.uniforms,
vertexShader: material.vertexShader,
fragmentShader: material.fragmentShader
};
}
return shaderobject;
}
function allocateBones( object ) {
var skeleton = object.skeleton;
var bones = skeleton.bones;
if ( floatVertexTextures ) {
return 1024;
} else {
// default for when object is not specified
// ( for example when prebuilding shader to be used with multiple objects )
//
// - leave some extra space for other uniforms
// - limit here is ANGLE's 254 max uniform vectors
// (up to 54 should be safe)
var nVertexUniforms = maxVertexUniforms;
var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
var maxBones = Math.min( nVertexMatrices, bones.length );
if ( maxBones < bones.length ) {
console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
return 0;
}
return maxBones;
}
}
function getTextureEncodingFromMap( map ) {
var encoding;
if ( ! map ) {
encoding = LinearEncoding;
} else if ( map.isTexture ) {
encoding = map.encoding;
} else if ( map.isWebGLRenderTarget ) {
console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
encoding = map.texture.encoding;
}
return encoding;
}
this.getParameters = function ( material, lights, shadows, scene, nClipPlanes, nClipIntersection, object ) {
var fog = scene.fog;
var environment = material.isMeshStandardMaterial ? scene.environment : null;
var envMap = material.envMap || environment;
var shaderID = shaderIDs[ material.type ];
// heuristics to create shader parameters according to lights in the scene
// (not to blow over maxLights budget)
var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
if ( material.precision !== null ) {
precision = capabilities.getMaxPrecision( material.precision );
if ( precision !== material.precision ) {
console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
}
}
var shaderobject = getShaderObject( material, shaderID );
material.onBeforeCompile( shaderobject, renderer );
var currentRenderTarget = renderer.getRenderTarget();
var parameters = {
isWebGL2: isWebGL2,
shaderID: shaderID,
shaderName: shaderobject.name,
uniforms: shaderobject.uniforms,
vertexShader: shaderobject.vertexShader,
fragmentShader: shaderobject.fragmentShader,
defines: material.defines,
isRawShaderMaterial: material.isRawShaderMaterial,
isShaderMaterial: material.isShaderMaterial,
precision: precision,
instancing: object.isInstancedMesh === true,
supportsVertexTextures: vertexTextures,
outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
map: !! material.map,
mapEncoding: getTextureEncodingFromMap( material.map ),
matcap: !! material.matcap,
matcapEncoding: getTextureEncodingFromMap( material.matcap ),
envMap: !! envMap,
envMapMode: envMap && envMap.mapping,
envMapEncoding: getTextureEncodingFromMap( envMap ),
envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
lightMap: !! material.lightMap,
lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
aoMap: !! material.aoMap,
emissiveMap: !! material.emissiveMap,
emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
bumpMap: !! material.bumpMap,
normalMap: !! material.normalMap,
objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
clearcoatMap: !! material.clearcoatMap,
clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
clearcoatNormalMap: !! material.clearcoatNormalMap,
displacementMap: !! material.displacementMap,
roughnessMap: !! material.roughnessMap,
metalnessMap: !! material.metalnessMap,
specularMap: !! material.specularMap,
alphaMap: !! material.alphaMap,
gradientMap: !! material.gradientMap,
sheen: !! material.sheen,
combine: material.combine,
vertexTangents: ( material.normalMap && material.vertexTangents ),
vertexColors: material.vertexColors,
vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap,
uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap ) && !! material.displacementMap,
fog: !! fog,
useFog: material.fog,
fogExp2: ( fog && fog.isFogExp2 ),
flatShading: material.flatShading,
sizeAttenuation: material.sizeAttenuation,
logarithmicDepthBuffer: logarithmicDepthBuffer,
skinning: material.skinning && maxBones > 0,
maxBones: maxBones,
useVertexTexture: floatVertexTextures,
morphTargets: material.morphTargets,
morphNormals: material.morphNormals,
maxMorphTargets: renderer.maxMorphTargets,
maxMorphNormals: renderer.maxMorphNormals,
numDirLights: lights.directional.length,
numPointLights: lights.point.length,
numSpotLights: lights.spot.length,
numRectAreaLights: lights.rectArea.length,
numHemiLights: lights.hemi.length,
numDirLightShadows: lights.directionalShadowMap.length,
numPointLightShadows: lights.pointShadowMap.length,
numSpotLightShadows: lights.spotShadowMap.length,
numClippingPlanes: nClipPlanes,
numClipIntersection: nClipIntersection,
dithering: material.dithering,
shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
shadowMapType: renderer.shadowMap.type,
toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
physicallyCorrectLights: renderer.physicallyCorrectLights,
premultipliedAlpha: material.premultipliedAlpha,
alphaTest: material.alphaTest,
doubleSided: material.side === DoubleSide,
flipSided: material.side === BackSide,
depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
index0AttributeName: material.index0AttributeName,
extensionDerivatives: material.extensions && material.extensions.derivatives,
extensionFragDepth: material.extensions && material.extensions.fragDepth,
extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
rendererExtensionFragDepth: isWebGL2 || extensions.get( 'EXT_frag_depth' ) !== null,
rendererExtensionDrawBuffers: isWebGL2 || extensions.get( 'WEBGL_draw_buffers' ) !== null,
rendererExtensionShaderTextureLod: isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) !== null,
onBeforeCompile: material.onBeforeCompile
};
return parameters;
};
this.getProgramCacheKey = function ( parameters ) {
var array = [];
if ( parameters.shaderID ) {
array.push( parameters.shaderID );
} else {
array.push( parameters.fragmentShader );
array.push( parameters.vertexShader );
}
if ( parameters.defines !== undefined ) {
for ( var name in parameters.defines ) {
array.push( name );
array.push( parameters.defines[ name ] );
}
}
if ( parameters.isRawShaderMaterial === undefined ) {
for ( var i = 0; i < parameterNames.length; i ++ ) {
array.push( parameters[ parameterNames[ i ] ] );
}
array.push( renderer.outputEncoding );
array.push( renderer.gammaFactor );
}
array.push( parameters.onBeforeCompile.toString() );
return array.join();
};
this.acquireProgram = function ( parameters, cacheKey ) {
var program;
// Check if code has been already compiled
for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
var preexistingProgram = programs[ p ];
if ( preexistingProgram.cacheKey === cacheKey ) {
program = preexistingProgram;
++ program.usedTimes;
break;
}
}
if ( program === undefined ) {
program = new WebGLProgram( renderer, cacheKey, parameters );
programs.push( program );
}
return program;
};
this.releaseProgram = function ( program ) {
if ( -- program.usedTimes === 0 ) {
// Remove from unordered set
var i = programs.indexOf( program );
programs[ i ] = programs[ programs.length - 1 ];
programs.pop();
// Free WebGL resources
program.destroy();
}
};
// Exposed for resource monitoring & error feedback via renderer.info:
this.programs = programs;
}
/**
* @author fordacious / fordacious.github.io
*/
function WebGLProperties() {
var properties = new WeakMap();
function get( object ) {
var map = properties.get( object );
if ( map === undefined ) {
map = {};
properties.set( object, map );
}
return map;
}
function remove( object ) {
properties.delete( object );
}
function update( object, key, value ) {
properties.get( object )[ key ] = value;
}
function dispose() {
properties = new WeakMap();
}
return {
get: get,
remove: remove,
update: update,
dispose: dispose
};
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function painterSortStable( a, b ) {
if ( a.groupOrder !== b.groupOrder ) {
return a.groupOrder - b.groupOrder;
} else if ( a.renderOrder !== b.renderOrder ) {
return a.renderOrder - b.renderOrder;
} else if ( a.program !== b.program ) {
return a.program.id - b.program.id;
} else if ( a.material.id !== b.material.id ) {
return a.material.id - b.material.id;
} else if ( a.z !== b.z ) {
return a.z - b.z;
} else {
return a.id - b.id;
}
}
function reversePainterSortStable( a, b ) {
if ( a.groupOrder !== b.groupOrder ) {
return a.groupOrder - b.groupOrder;
} else if ( a.renderOrder !== b.renderOrder ) {
return a.renderOrder - b.renderOrder;
} else if ( a.z !== b.z ) {
return b.z - a.z;
} else {
return a.id - b.id;
}
}
function WebGLRenderList() {
var renderItems = [];
var renderItemsIndex = 0;
var opaque = [];
var transparent = [];
var defaultProgram = { id: - 1 };
function init() {
renderItemsIndex = 0;
opaque.length = 0;
transparent.length = 0;
}
function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
var renderItem = renderItems[ renderItemsIndex ];
if ( renderItem === undefined ) {
renderItem = {
id: object.id,
object: object,
geometry: geometry,
material: material,
program: material.program || defaultProgram,
groupOrder: groupOrder,
renderOrder: object.renderOrder,
z: z,
group: group
};
renderItems[ renderItemsIndex ] = renderItem;
} else {
renderItem.id = object.id;
renderItem.object = object;
renderItem.geometry = geometry;
renderItem.material = material;
renderItem.program = material.program || defaultProgram;
renderItem.groupOrder = groupOrder;
renderItem.renderOrder = object.renderOrder;
renderItem.z = z;
renderItem.group = group;
}
renderItemsIndex ++;
return renderItem;
}
function push( object, geometry, material, groupOrder, z, group ) {
var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
( material.transparent === true ? transparent : opaque ).push( renderItem );
}
function unshift( object, geometry, material, groupOrder, z, group ) {
var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
( material.transparent === true ? transparent : opaque ).unshift( renderItem );
}
function sort( customOpaqueSort, customTransparentSort ) {
if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
}
function finish() {
// Clear references from inactive renderItems in the list
for ( var i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
var renderItem = renderItems[ i ];
if ( renderItem.id === null ) break;
renderItem.id = null;
renderItem.object = null;
renderItem.geometry = null;
renderItem.material = null;
renderItem.program = null;
renderItem.group = null;
}
}
return {
opaque: opaque,
transparent: transparent,
init: init,
push: push,
unshift: unshift,
finish: finish,
sort: sort
};
}
function WebGLRenderLists() {
var lists = new WeakMap();
function onSceneDispose( event ) {
var scene = event.target;
scene.removeEventListener( 'dispose', onSceneDispose );
lists.delete( scene );
}
function get( scene, camera ) {
var cameras = lists.get( scene );
var list;
if ( cameras === undefined ) {
list = new WebGLRenderList();
lists.set( scene, new WeakMap() );
lists.get( scene ).set( camera, list );
scene.addEventListener( 'dispose', onSceneDispose );
} else {
list = cameras.get( camera );
if ( list === undefined ) {
list = new WebGLRenderList();
cameras.set( camera, list );
}
}
return list;
}
function dispose() {
lists = new WeakMap();
}
return {
get: get,
dispose: dispose
};
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function UniformsCache() {
var lights = {};
return {
get: function ( light ) {
if ( lights[ light.id ] !== undefined ) {
return lights[ light.id ];
}
var uniforms;
switch ( light.type ) {
case 'DirectionalLight':
uniforms = {
direction: new Vector3(),
color: new Color()
};
break;
case 'SpotLight':
uniforms = {
position: new Vector3(),
direction: new Vector3(),
color: new Color(),
distance: 0,
coneCos: 0,
penumbraCos: 0,
decay: 0
};
break;
case 'PointLight':
uniforms = {
position: new Vector3(),
color: new Color(),
distance: 0,
decay: 0
};
break;
case 'HemisphereLight':
uniforms = {
direction: new Vector3(),
skyColor: new Color(),
groundColor: new Color()
};
break;
case 'RectAreaLight':
uniforms = {
color: new Color(),
position: new Vector3(),
halfWidth: new Vector3(),
halfHeight: new Vector3()
};
break;
}
lights[ light.id ] = uniforms;
return uniforms;
}
};
}
function ShadowUniformsCache() {
var lights = {};
return {
get: function ( light ) {
if ( lights[ light.id ] !== undefined ) {
return lights[ light.id ];
}
var uniforms;
switch ( light.type ) {
case 'DirectionalLight':
uniforms = {
shadowBias: 0,
shadowRadius: 1,
shadowMapSize: new Vector2()
};
break;
case 'SpotLight':
uniforms = {
shadowBias: 0,
shadowRadius: 1,
shadowMapSize: new Vector2()
};
break;
case 'PointLight':
uniforms = {
shadowBias: 0,
shadowRadius: 1,
shadowMapSize: new Vector2(),
shadowCameraNear: 1,
shadowCameraFar: 1000
};
break;
// TODO (abelnation): set RectAreaLight shadow uniforms
}
lights[ light.id ] = uniforms;
return uniforms;
}
};
}
var nextVersion = 0;
function shadowCastingLightsFirst( lightA, lightB ) {
return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
}
function WebGLLights() {
var cache = new UniformsCache();
var shadowCache = ShadowUniformsCache();
var state = {
version: 0,
hash: {
directionalLength: - 1,
pointLength: - 1,
spotLength: - 1,
rectAreaLength: - 1,
hemiLength: - 1,
numDirectionalShadows: - 1,
numPointShadows: - 1,
numSpotShadows: - 1
},
ambient: [ 0, 0, 0 ],
probe: [],
directional: [],
directionalShadow: [],
directionalShadowMap: [],
directionalShadowMatrix: [],
spot: [],
spotShadow: [],
spotShadowMap: [],
spotShadowMatrix: [],
rectArea: [],
point: [],
pointShadow: [],
pointShadowMap: [],
pointShadowMatrix: [],
hemi: []
};
for ( var i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
var vector3 = new Vector3();
var matrix4 = new Matrix4();
var matrix42 = new Matrix4();
function setup( lights, shadows, camera ) {
var r = 0, g = 0, b = 0;
for ( var i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
var directionalLength = 0;
var pointLength = 0;
var spotLength = 0;
var rectAreaLength = 0;
var hemiLength = 0;
var numDirectionalShadows = 0;
var numPointShadows = 0;
var numSpotShadows = 0;
var viewMatrix = camera.matrixWorldInverse;
lights.sort( shadowCastingLightsFirst );
for ( var i = 0, l = lights.length; i < l; i ++ ) {
var light = lights[ i ];
var color = light.color;
var intensity = light.intensity;
var distance = light.distance;
var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
if ( light.isAmbientLight ) {
r += color.r * intensity;
g += color.g * intensity;
b += color.b * intensity;
} else if ( light.isLightProbe ) {
for ( var j = 0; j < 9; j ++ ) {
state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
}
} else if ( light.isDirectionalLight ) {
var uniforms = cache.get( light );
uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
uniforms.direction.setFromMatrixPosition( light.matrixWorld );
vector3.setFromMatrixPosition( light.target.matrixWorld );
uniforms.direction.sub( vector3 );
uniforms.direction.transformDirection( viewMatrix );
if ( light.castShadow ) {
var shadow = light.shadow;
var shadowUniforms = shadowCache.get( light );
shadowUniforms.shadowBias = shadow.bias;
shadowUniforms.shadowRadius = shadow.radius;
shadowUniforms.shadowMapSize = shadow.mapSize;
state.directionalShadow[ directionalLength ] = shadowUniforms;
state.directionalShadowMap[ directionalLength ] = shadowMap;
state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
numDirectionalShadows ++;
}
state.directional[ directionalLength ] = uniforms;
directionalLength ++;
} else if ( light.isSpotLight ) {
var uniforms = cache.get( light );
uniforms.position.setFromMatrixPosition( light.matrixWorld );
uniforms.position.applyMatrix4( viewMatrix );
uniforms.color.copy( color ).multiplyScalar( intensity );
uniforms.distance = distance;
uniforms.direction.setFromMatrixPosition( light.matrixWorld );
vector3.setFromMatrixPosition( light.target.matrixWorld );
uniforms.direction.sub( vector3 );
uniforms.direction.transformDirection( viewMatrix );
uniforms.coneCos = Math.cos( light.angle );
uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
uniforms.decay = light.decay;
if ( light.castShadow ) {
var shadow = light.shadow;
var shadowUniforms = shadowCache.get( light );
shadowUniforms.shadowBias = shadow.bias;
shadowUniforms.shadowRadius = shadow.radius;
shadowUniforms.shadowMapSize = shadow.mapSize;
state.spotShadow[ spotLength ] = shadowUniforms;
state.spotShadowMap[ spotLength ] = shadowMap;
state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
numSpotShadows ++;
}
state.spot[ spotLength ] = uniforms;
spotLength ++;
} else if ( light.isRectAreaLight ) {
var uniforms = cache.get( light );
// (a) intensity is the total visible light emitted
//uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
// (b) intensity is the brightness of the light
uniforms.color.copy( color ).multiplyScalar( intensity );
uniforms.position.setFromMatrixPosition( light.matrixWorld );
uniforms.position.applyMatrix4( viewMatrix );
// extract local rotation of light to derive width/height half vectors
matrix42.identity();
matrix4.copy( light.matrixWorld );
matrix4.premultiply( viewMatrix );
matrix42.extractRotation( matrix4 );
uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
uniforms.halfWidth.applyMatrix4( matrix42 );
uniforms.halfHeight.applyMatrix4( matrix42 );
// TODO (abelnation): RectAreaLight distance?
// uniforms.distance = distance;
state.rectArea[ rectAreaLength ] = uniforms;
rectAreaLength ++;
} else if ( light.isPointLight ) {
var uniforms = cache.get( light );
uniforms.position.setFromMatrixPosition( light.matrixWorld );
uniforms.position.applyMatrix4( viewMatrix );
uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
uniforms.distance = light.distance;
uniforms.decay = light.decay;
if ( light.castShadow ) {
var shadow = light.shadow;
var shadowUniforms = shadowCache.get( light );
shadowUniforms.shadowBias = shadow.bias;
shadowUniforms.shadowRadius = shadow.radius;
shadowUniforms.shadowMapSize = shadow.mapSize;
shadowUniforms.shadowCameraNear = shadow.camera.near;
shadowUniforms.shadowCameraFar = shadow.camera.far;
state.pointShadow[ pointLength ] = shadowUniforms;
state.pointShadowMap[ pointLength ] = shadowMap;
state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
numPointShadows ++;
}
state.point[ pointLength ] = uniforms;
pointLength ++;
} else if ( light.isHemisphereLight ) {
var uniforms = cache.get( light );
uniforms.direction.setFromMatrixPosition( light.matrixWorld );
uniforms.direction.transformDirection( viewMatrix );
uniforms.direction.normalize();
uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
state.hemi[ hemiLength ] = uniforms;
hemiLength ++;
}
}
state.ambient[ 0 ] = r;
state.ambient[ 1 ] = g;
state.ambient[ 2 ] = b;
var hash = state.hash;
if ( hash.directionalLength !== directionalLength ||
hash.pointLength !== pointLength ||
hash.spotLength !== spotLength ||
hash.rectAreaLength !== rectAreaLength ||
hash.hemiLength !== hemiLength ||
hash.numDirectionalShadows !== numDirectionalShadows ||
hash.numPointShadows !== numPointShadows ||
hash.numSpotShadows !== numSpotShadows ) {
state.directional.length = directionalLength;
state.spot.length = spotLength;
state.rectArea.length = rectAreaLength;
state.point.length = pointLength;
state.hemi.length = hemiLength;
state.directionalShadow.length = numDirectionalShadows;
state.directionalShadowMap.length = numDirectionalShadows;
state.pointShadow.length = numPointShadows;
state.pointShadowMap.length = numPointShadows;
state.spotShadow.length = numSpotShadows;
state.spotShadowMap.length = numSpotShadows;
state.directionalShadowMatrix.length = numDirectionalShadows;
state.pointShadowMatrix.length = numPointShadows;
state.spotShadowMatrix.length = numSpotShadows;
hash.directionalLength = directionalLength;
hash.pointLength = pointLength;
hash.spotLength = spotLength;
hash.rectAreaLength = rectAreaLength;
hash.hemiLength = hemiLength;
hash.numDirectionalShadows = numDirectionalShadows;
hash.numPointShadows = numPointShadows;
hash.numSpotShadows = numSpotShadows;
state.version = nextVersion ++;
}
}
return {
setup: setup,
state: state
};
}
/**
* @author Mugen87 / https://github.com/Mugen87
*/
function WebGLRenderState() {
var lights = new WebGLLights();
var lightsArray = [];
var shadowsArray = [];
function init() {
lightsArray.length = 0;
shadowsArray.length = 0;
}
function pushLight( light ) {
lightsArray.push( light );
}
function pushShadow( shadowLight ) {
shadowsArray.push( shadowLight );
}
function setupLights( camera ) {
lights.setup( lightsArray, shadowsArray, camera );
}
var state = {
lightsArray: lightsArray,
shadowsArray: shadowsArray,
lights: lights
};
return {
init: init,
state: state,
setupLights: setupLights,
pushLight: pushLight,
pushShadow: pushShadow
};
}
function WebGLRenderStates() {
var renderStates = new WeakMap();
function onSceneDispose( event ) {
var scene = event.target;
scene.removeEventListener( 'dispose', onSceneDispose );
renderStates.delete( scene );
}
function get( scene, camera ) {
var renderState;
if ( renderStates.has( scene ) === false ) {
renderState = new WebGLRenderState();
renderStates.set( scene, new WeakMap() );
renderStates.get( scene ).set( camera, renderState );
scene.addEventListener( 'dispose', onSceneDispose );
} else {
if ( renderStates.get( scene ).has( camera ) === false ) {
renderState = new WebGLRenderState();
renderStates.get( scene ).set( camera, renderState );
} else {
renderState = renderStates.get( scene ).get( camera );
}
}
return renderState;
}
function dispose() {
renderStates = new WeakMap();
}
return {
get: get,
dispose: dispose
};
}
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author bhouston / https://clara.io
* @author WestLangley / http://github.com/WestLangley
*
* parameters = {
*
* opacity: <float>,
*
* map: new THREE.Texture( <Image> ),
*
* alphaMap: new THREE.Texture( <Image> ),
*
* displacementMap: new THREE.Texture( <Image> ),
* displacementScale: <float>,
* displacementBias: <float>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>
* }
*/
function MeshDepthMaterial( parameters ) {
Material.call( this );
this.type = 'MeshDepthMaterial';
this.depthPacking = BasicDepthPacking;
this.skinning = false;
this.morphTargets = false;
this.map = null;
this.alphaMap = null;
this.displacementMap = null;
this.displacementScale = 1;
this.displacementBias = 0;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.fog = false;
this.setValues( parameters );
}
MeshDepthMaterial.prototype = Object.create( Material.prototype );
MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
MeshDepthMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.depthPacking = source.depthPacking;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
this.map = source.map;
this.alphaMap = source.alphaMap;
this.displacementMap = source.displacementMap;
this.displacementScale = source.displacementScale;
this.displacementBias = source.displacementBias;
this.wireframe = source.wireframe;
this.wireframeLinewidth = source.wireframeLinewidth;
return this;
};
/**
* @author WestLangley / http://github.com/WestLangley
*
* parameters = {
*
* referencePosition: <float>,
* nearDistance: <float>,
* farDistance: <float>,
*
* skinning: <bool>,
* morphTargets: <bool>,
*
* map: new THREE.Texture( <Image> ),
*
* alphaMap: new THREE.Texture( <Image> ),
*
* displacementMap: new THREE.Texture( <Image> ),
* displacementScale: <float>,
* displacementBias: <float>
*
* }
*/
function MeshDistanceMaterial( parameters ) {
Material.call( this );
this.type = 'MeshDistanceMaterial';
this.referencePosition = new Vector3();
this.nearDistance = 1;
this.farDistance = 1000;
this.skinning = false;
this.morphTargets = false;
this.map = null;
this.alphaMap = null;
this.displacementMap = null;
this.displacementScale = 1;
this.displacementBias = 0;
this.fog = false;
this.setValues( parameters );
}
MeshDistanceMaterial.prototype = Object.create( Material.prototype );
MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
MeshDistanceMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.referencePosition.copy( source.referencePosition );
this.nearDistance = source.nearDistance;
this.farDistance = source.farDistance;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
this.map = source.map;
this.alphaMap = source.alphaMap;
this.displacementMap = source.displacementMap;
this.displacementScale = source.displacementScale;
this.displacementBias = source.displacementBias;
return this;
};
var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
var _frustum = new Frustum(),
_shadowMapSize = new Vector2(),
_viewportSize = new Vector2(),
_viewport = new Vector4(),
_depthMaterials = [],
_distanceMaterials = [],
_materialCache = {};
var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
var shadowMaterialVertical = new ShaderMaterial( {
defines: {
SAMPLE_RATE: 2.0 / 8.0,
HALF_SAMPLE_RATE: 1.0 / 8.0
},
uniforms: {
shadow_pass: { value: null },
resolution: { value: new Vector2() },
radius: { value: 4.0 }
},
vertexShader: vsm_vert,
fragmentShader: vsm_frag
} );
var shadowMaterialHorizonal = shadowMaterialVertical.clone();
shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
var fullScreenTri = new BufferGeometry();
fullScreenTri.setAttribute(
"position",
new BufferAttribute(
new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
3
)
);
var fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
var scope = this;
this.enabled = false;
this.autoUpdate = true;
this.needsUpdate = false;
this.type = PCFShadowMap;
this.render = function ( lights, scene, camera ) {
if ( scope.enabled === false ) return;
if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
if ( lights.length === 0 ) return;
var currentRenderTarget = _renderer.getRenderTarget();
var activeCubeFace = _renderer.getActiveCubeFace();
var activeMipmapLevel = _renderer.getActiveMipmapLevel();
var _state = _renderer.state;
// Set GL state for depth map.
_state.setBlending( NoBlending );
_state.buffers.color.setClear( 1, 1, 1, 1 );
_state.buffers.depth.setTest( true );
_state.setScissorTest( false );
// render depth map
for ( var i = 0, il = lights.length; i < il; i ++ ) {
var light = lights[ i ];
var shadow = light.shadow;
if ( shadow === undefined ) {
console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
continue;
}
_shadowMapSize.copy( shadow.mapSize );
var shadowFrameExtents = shadow.getFrameExtents();
_shadowMapSize.multiply( shadowFrameExtents );
_viewportSize.copy( shadow.mapSize );
if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {
if ( _shadowMapSize.x > maxTextureSize ) {
_viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
_shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
shadow.mapSize.x = _viewportSize.x;
}
if ( _shadowMapSize.y > maxTextureSize ) {
_viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
_shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
shadow.mapSize.y = _viewportSize.y;
}
}
if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
shadow.map.texture.name = light.name + ".shadowMap";
shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
shadow.camera.updateProjectionMatrix();
}
if ( shadow.map === null ) {
var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
shadow.map.texture.name = light.name + ".shadowMap";
shadow.camera.updateProjectionMatrix();
}
_renderer.setRenderTarget( shadow.map );
_renderer.clear();
var viewportCount = shadow.getViewportCount();
for ( var vp = 0; vp < viewportCount; vp ++ ) {
var viewport = shadow.getViewport( vp );
_viewport.set(
_viewportSize.x * viewport.x,
_viewportSize.y * viewport.y,
_viewportSize.x * viewport.z,
_viewportSize.y * viewport.w
);
_state.viewport( _viewport );
shadow.updateMatrices( light, vp );
_frustum = shadow.getFrustum();
renderObject( scene, camera, shadow.camera, light, this.type );
}
// do blur pass for VSM
if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
VSMPass( shadow, camera );
}
}
scope.needsUpdate = false;
_renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
};
function VSMPass( shadow, camera ) {
var geometry = _objects.update( fullScreenMesh );
// vertical pass
shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
shadowMaterialVertical.uniforms.radius.value = shadow.radius;
_renderer.setRenderTarget( shadow.mapPass );
_renderer.clear();
_renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
// horizonal pass
shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
_renderer.setRenderTarget( shadow.map );
_renderer.clear();
_renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null );
}
function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {
var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
var material = _depthMaterials[ index ];
if ( material === undefined ) {
material = new MeshDepthMaterial( {
depthPacking: RGBADepthPacking,
morphTargets: useMorphing,
skinning: useSkinning
} );
_depthMaterials[ index ] = material;
}
return material;
}
function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {
var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
var material = _distanceMaterials[ index ];
if ( material === undefined ) {
material = new MeshDistanceMaterial( {
morphTargets: useMorphing,
skinning: useSkinning
} );
_distanceMaterials[ index ] = material;
}
return material;
}
function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
var result = null;
var getMaterialVariant = getDepthMaterialVariant;
var customMaterial = object.customDepthMaterial;
if ( light.isPointLight === true ) {
getMaterialVariant = getDistanceMaterialVariant;
customMaterial = object.customDistanceMaterial;
}
if ( customMaterial === undefined ) {
var useMorphing = false;
if ( material.morphTargets === true ) {
useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
}
var useSkinning = false;
if ( object.isSkinnedMesh === true ) {
if ( material.skinning === true ) {
useSkinning = true;
} else {
console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
}
}
var useInstancing = object.isInstancedMesh === true;
result = getMaterialVariant( useMorphing, useSkinning, useInstancing );
} else {
result = customMaterial;
}
if ( _renderer.localClippingEnabled &&
material.clipShadows === true &&
material.clippingPlanes.length !== 0 ) {
// in this case we need a unique material instance reflecting the
// appropriate state
var keyA = result.uuid, keyB = material.uuid;
var materialsForVariant = _materialCache[ keyA ];
if ( materialsForVariant === undefined ) {
materialsForVariant = {};
_materialCache[ keyA ] = materialsForVariant;
}
var cachedMaterial = materialsForVariant[ keyB ];
if ( cachedMaterial === undefined ) {
cachedMaterial = result.clone();
materialsForVariant[ keyB ] = cachedMaterial;
}
result = cachedMaterial;
}
result.visible = material.visible;
result.wireframe = material.wireframe;
if ( type === VSMShadowMap ) {
result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
} else {
result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
}
result.clipShadows = material.clipShadows;
result.clippingPlanes = material.clippingPlanes;
result.clipIntersection = material.clipIntersection;
result.wireframeLinewidth = material.wireframeLinewidth;
result.linewidth = material.linewidth;
if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
result.referencePosition.setFromMatrixPosition( light.matrixWorld );
result.nearDistance = shadowCameraNear;
result.farDistance = shadowCameraFar;
}
return result;
}
function renderObject( object, camera, shadowCamera, light, type ) {
if ( object.visible === false ) return;
var visible = object.layers.test( camera.layers );
if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
var geometry = _objects.update( object );
var material = object.material;
if ( Array.isArray( material ) ) {
var groups = geometry.groups;
for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
var group = groups[ k ];
var groupMaterial = material[ group.materialIndex ];
if ( groupMaterial && groupMaterial.visible ) {
var depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
_renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
}
}
} else if ( material.visible ) {
var depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
_renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
}
}
}
var children = object.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
renderObject( children[ i ], camera, shadowCamera, light, type );
}
}
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLState( gl, extensions, capabilities ) {
var isWebGL2 = capabilities.isWebGL2;
function ColorBuffer() {
var locked = false;
var color = new Vector4();
var currentColorMask = null;
var currentColorClear = new Vector4( 0, 0, 0, 0 );
return {
setMask: function ( colorMask ) {
if ( currentColorMask !== colorMask && ! locked ) {
gl.colorMask( colorMask, colorMask, colorMask, colorMask );
currentColorMask = colorMask;
}
},
setLocked: function ( lock ) {
locked = lock;
},
setClear: function ( r, g, b, a, premultipliedAlpha ) {
if ( premultipliedAlpha === true ) {
r *= a; g *= a; b *= a;
}
color.set( r, g, b, a );
if ( currentColorClear.equals( color ) === false ) {
gl.clearColor( r, g, b, a );
currentColorClear.copy( color );
}
},
reset: function () {
locked = false;
currentColorMask = null;
currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
}
};
}
function DepthBuffer() {
var locked = false;
var currentDepthMask = null;
var currentDepthFunc = null;
var currentDepthClear = null;
return {
setTest: function ( depthTest ) {
if ( depthTest ) {
enable( 2929 );
} else {
disable( 2929 );
}
},
setMask: function ( depthMask ) {
if ( currentDepthMask !== depthMask && ! locked ) {
gl.depthMask( depthMask );
currentDepthMask = depthMask;
}
},
setFunc: function ( depthFunc ) {
if ( currentDepthFunc !== depthFunc ) {
if ( depthFunc ) {
switch ( depthFunc ) {
case NeverDepth:
gl.depthFunc( 512 );
break;
case AlwaysDepth:
gl.depthFunc( 519 );
break;
case LessDepth:
gl.depthFunc( 513 );
break;
case LessEqualDepth:
gl.depthFunc( 515 );
break;
case EqualDepth:
gl.depthFunc( 514 );
break;
case GreaterEqualDepth:
gl.depthFunc( 518 );
break;
case GreaterDepth:
gl.depthFunc( 516 );
break;
case NotEqualDepth:
gl.depthFunc( 517 );
break;
default:
gl.depthFunc( 515 );
}
} else {
gl.depthFunc( 515 );
}
currentDepthFunc = depthFunc;
}
},
setLocked: function ( lock ) {
locked = lock;
},
setClear: function ( depth ) {
if ( currentDepthClear !== depth ) {
gl.clearDepth( depth );
currentDepthClear = depth;
}
},
reset: function () {
locked = false;
currentDepthMask = null;
currentDepthFunc = null;
currentDepthClear = null;
}
};
}
function StencilBuffer() {
var locked = false;
var currentStencilMask = null;
var currentStencilFunc = null;
var currentStencilRef = null;
var currentStencilFuncMask = null;
var currentStencilFail = null;
var currentStencilZFail = null;
var currentStencilZPass = null;
var currentStencilClear = null;
return {
setTest: function ( stencilTest ) {
if ( ! locked ) {
if ( stencilTest ) {
enable( 2960 );
} else {
disable( 2960 );
}
}
},
setMask: function ( stencilMask ) {
if ( currentStencilMask !== stencilMask && ! locked ) {
gl.stencilMask( stencilMask );
currentStencilMask = stencilMask;
}
},
setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
if ( currentStencilFunc !== stencilFunc ||
currentStencilRef !== stencilRef ||
currentStencilFuncMask !== stencilMask ) {
gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
currentStencilFunc = stencilFunc;
currentStencilRef = stencilRef;
currentStencilFuncMask = stencilMask;
}
},
setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
if ( currentStencilFail !== stencilFail ||
currentStencilZFail !== stencilZFail ||
currentStencilZPass !== stencilZPass ) {
gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
currentStencilFail = stencilFail;
currentStencilZFail = stencilZFail;
currentStencilZPass = stencilZPass;
}
},
setLocked: function ( lock ) {
locked = lock;
},
setClear: function ( stencil ) {
if ( currentStencilClear !== stencil ) {
gl.clearStencil( stencil );
currentStencilClear = stencil;
}
},
reset: function () {
locked = false;
currentStencilMask = null;
currentStencilFunc = null;
currentStencilRef = null;
currentStencilFuncMask = null;
currentStencilFail = null;
currentStencilZFail = null;
currentStencilZPass = null;
currentStencilClear = null;
}
};
}
//
var colorBuffer = new ColorBuffer();
var depthBuffer = new DepthBuffer();
var stencilBuffer = new StencilBuffer();
var maxVertexAttributes = gl.getParameter( 34921 );
var newAttributes = new Uint8Array( maxVertexAttributes );
var enabledAttributes = new Uint8Array( maxVertexAttributes );
var attributeDivisors = new Uint8Array( maxVertexAttributes );
var enabledCapabilities = {};
var currentProgram = null;
var currentBlendingEnabled = null;
var currentBlending = null;
var currentBlendEquation = null;
var currentBlendSrc = null;
var currentBlendDst = null;
var currentBlendEquationAlpha = null;
var currentBlendSrcAlpha = null;
var currentBlendDstAlpha = null;
var currentPremultipledAlpha = false;
var currentFlipSided = null;
var currentCullFace = null;
var currentLineWidth = null;
var currentPolygonOffsetFactor = null;
var currentPolygonOffsetUnits = null;
var maxTextures = gl.getParameter( 35661 );
var lineWidthAvailable = false;
var version = 0;
var glVersion = gl.getParameter( 7938 );
if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
lineWidthAvailable = ( version >= 1.0 );
} else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
lineWidthAvailable = ( version >= 2.0 );
}
var currentTextureSlot = null;
var currentBoundTextures = {};
var currentScissor = new Vector4();
var currentViewport = new Vector4();
function createTexture( type, target, count ) {
var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
var texture = gl.createTexture();
gl.bindTexture( type, texture );
gl.texParameteri( type, 10241, 9728 );
gl.texParameteri( type, 10240, 9728 );
for ( var i = 0; i < count; i ++ ) {
gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
}
return texture;
}
var emptyTextures = {};
emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
// init
colorBuffer.setClear( 0, 0, 0, 1 );
depthBuffer.setClear( 1 );
stencilBuffer.setClear( 0 );
enable( 2929 );
depthBuffer.setFunc( LessEqualDepth );
setFlipSided( false );
setCullFace( CullFaceBack );
enable( 2884 );
setBlending( NoBlending );
//
function initAttributes() {
for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
newAttributes[ i ] = 0;
}
}
function enableAttribute( attribute ) {
enableAttributeAndDivisor( attribute, 0 );
}
function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
newAttributes[ attribute ] = 1;
if ( enabledAttributes[ attribute ] === 0 ) {
gl.enableVertexAttribArray( attribute );
enabledAttributes[ attribute ] = 1;
}
if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
var extension = isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
extension[ isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
attributeDivisors[ attribute ] = meshPerAttribute;
}
}
function disableUnusedAttributes() {
for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
gl.disableVertexAttribArray( i );
enabledAttributes[ i ] = 0;
}
}
}
function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
if ( isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
gl.vertexAttribIPointer( index, size, type, normalized, stride, offset );
} else {
gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
}
}
function enable( id ) {
if ( enabledCapabilities[ id ] !== true ) {
gl.enable( id );
enabledCapabilities[ id ] = true;
}
}
function disable( id ) {
if ( enabledCapabilities[ id ] !== false ) {
gl.disable( id );
enabledCapabilities[ id ] = false;
}
}
function useProgram( program ) {
if ( currentProgram !== program ) {
gl.useProgram( program );
currentProgram = program;
return true;
}
return false;
}
var equationToGL = {
[ AddEquation ]: 32774,
[ SubtractEquation ]: 32778,
[ ReverseSubtractEquation ]: 32779
};
if ( isWebGL2 ) {
equationToGL[ MinEquation ] = 32775;
equationToGL[ MaxEquation ] = 32776;
} else {
var extension = extensions.get( 'EXT_blend_minmax' );
if ( extension !== null ) {
equationToGL[ MinEquation ] = extension.MIN_EXT;
equationToGL[ MaxEquation ] = extension.MAX_EXT;
}
}
var factorToGL = {
[ ZeroFactor ]: 0,
[ OneFactor ]: 1,
[ SrcColorFactor ]: 768,
[ SrcAlphaFactor ]: 770,
[ SrcAlphaSaturateFactor ]: 776,
[ DstColorFactor ]: 774,
[ DstAlphaFactor ]: 772,
[ OneMinusSrcColorFactor ]: 769,
[ OneMinusSrcAlphaFactor ]: 771,
[ OneMinusDstColorFactor ]: 775,
[ OneMinusDstAlphaFactor ]: 773
};
function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
if ( blending === NoBlending ) {
if ( currentBlendingEnabled ) {
disable( 3042 );
currentBlendingEnabled = false;
}
return;
}
if ( ! currentBlendingEnabled ) {
enable( 3042 );
currentBlendingEnabled = true;
}
if ( blending !== CustomBlending ) {
if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
gl.blendEquation( 32774 );
currentBlendEquation = AddEquation;
currentBlendEquationAlpha = AddEquation;
}
if ( premultipliedAlpha ) {
switch ( blending ) {
case NormalBlending:
gl.blendFuncSeparate( 1, 771, 1, 771 );
break;
case AdditiveBlending:
gl.blendFunc( 1, 1 );
break;
case SubtractiveBlending:
gl.blendFuncSeparate( 0, 0, 769, 771 );
break;
case MultiplyBlending:
gl.blendFuncSeparate( 0, 768, 0, 770 );
break;
default:
console.error( 'THREE.WebGLState: Invalid blending: ', blending );
break;
}
} else {
switch ( blending ) {
case NormalBlending:
gl.blendFuncSeparate( 770, 771, 1, 771 );
break;
case AdditiveBlending:
gl.blendFunc( 770, 1 );
break;
case SubtractiveBlending:
gl.blendFunc( 0, 769 );
break;
case MultiplyBlending:
gl.blendFunc( 0, 768 );
break;
default:
console.error( 'THREE.WebGLState: Invalid blending: ', blending );
break;
}
}
currentBlendSrc = null;
currentBlendDst = null;
currentBlendSrcAlpha = null;
currentBlendDstAlpha = null;
currentBlending = blending;
currentPremultipledAlpha = premultipliedAlpha;
}
return;
}
// custom blending
blendEquationAlpha = blendEquationAlpha || blendEquation;
blendSrcAlpha = blendSrcAlpha || blendSrc;
blendDstAlpha = blendDstAlpha || blendDst;
if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
currentBlendEquation = blendEquation;
currentBlendEquationAlpha = blendEquationAlpha;
}
if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
currentBlendSrc = blendSrc;
currentBlendDst = blendDst;
currentBlendSrcAlpha = blendSrcAlpha;
currentBlendDstAlpha = blendDstAlpha;
}
currentBlending = blending;
currentPremultipledAlpha = null;
}
function setMaterial( material, frontFaceCW ) {
material.side === DoubleSide
? disable( 2884 )
: enable( 2884 );
var flipSided = ( material.side === BackSide );
if ( frontFaceCW ) flipSided = ! flipSided;
setFlipSided( flipSided );
( material.blending === NormalBlending && material.transparent === false )
? setBlending( NoBlending )
: setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
depthBuffer.setFunc( material.depthFunc );
depthBuffer.setTest( material.depthTest );
depthBuffer.setMask( material.depthWrite );
colorBuffer.setMask( material.colorWrite );
var stencilWrite = material.stencilWrite;
stencilBuffer.setTest( stencilWrite );
if ( stencilWrite ) {
stencilBuffer.setMask( material.stencilWriteMask );
stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
}
setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
}
//
function setFlipSided( flipSided ) {
if ( currentFlipSided !== flipSided ) {
if ( flipSided ) {
gl.frontFace( 2304 );
} else {
gl.frontFace( 2305 );
}
currentFlipSided = flipSided;
}
}
function setCullFace( cullFace ) {
if ( cullFace !== CullFaceNone ) {
enable( 2884 );
if ( cullFace !== currentCullFace ) {
if ( cullFace === CullFaceBack ) {
gl.cullFace( 1029 );
} else if ( cullFace === CullFaceFront ) {
gl.cullFace( 1028 );
} else {
gl.cullFace( 1032 );
}
}
} else {
disable( 2884 );
}
currentCullFace = cullFace;
}
function setLineWidth( width ) {
if ( width !== currentLineWidth ) {
if ( lineWidthAvailable ) gl.lineWidth( width );
currentLineWidth = width;
}
}
function setPolygonOffset( polygonOffset, factor, units ) {
if ( polygonOffset ) {
enable( 32823 );
if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
gl.polygonOffset( factor, units );
currentPolygonOffsetFactor = factor;
currentPolygonOffsetUnits = units;
}
} else {
disable( 32823 );
}
}
function setScissorTest( scissorTest ) {
if ( scissorTest ) {
enable( 3089 );
} else {
disable( 3089 );
}
}
// texture
function activeTexture( webglSlot ) {
if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
if ( currentTextureSlot !== webglSlot ) {
gl.activeTexture( webglSlot );
currentTextureSlot = webglSlot;
}
}
function bindTexture( webglType, webglTexture ) {
if ( currentTextureSlot === null ) {
activeTexture();
}
var boundTexture = currentBoundTextures[ currentTextureSlot ];
if ( boundTexture === undefined ) {
boundTexture = { type: undefined, texture: undefined };
currentBoundTextures[ currentTextureSlot ] = boundTexture;
}
if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
boundTexture.type = webglType;
boundTexture.texture = webglTexture;
}
}
function unbindTexture() {
var boundTexture = currentBoundTextures[ currentTextureSlot ];
if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
gl.bindTexture( boundTexture.type, null );
boundTexture.type = undefined;
boundTexture.texture = undefined;
}
}
function compressedTexImage2D() {
try {
gl.compressedTexImage2D.apply( gl, arguments );
} catch ( error ) {
console.error( 'THREE.WebGLState:', error );
}
}
function texImage2D() {
try {
gl.texImage2D.apply( gl, arguments );
} catch ( error ) {
console.error( 'THREE.WebGLState:', error );
}
}
function texImage3D() {
try {
gl.texImage3D.apply( gl, arguments );
} catch ( error ) {
console.error( 'THREE.WebGLState:', error );
}
}
//
function scissor( scissor ) {
if ( currentScissor.equals( scissor ) === false ) {
gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
currentScissor.copy( scissor );
}
}
function viewport( viewport ) {
if ( currentViewport.equals( viewport ) === false ) {
gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
currentViewport.copy( viewport );
}
}
//
function reset() {
for ( var i = 0; i < enabledAttributes.length; i ++ ) {
if ( enabledAttributes[ i ] === 1 ) {
gl.disableVertexAttribArray( i );
enabledAttributes[ i ] = 0;
}
}
enabledCapabilities = {};
currentTextureSlot = null;
currentBoundTextures = {};
currentProgram = null;
currentBlending = null;
currentFlipSided = null;
currentCullFace = null;
colorBuffer.reset();
depthBuffer.reset();
stencilBuffer.reset();
}
return {
buffers: {
color: colorBuffer,
depth: depthBuffer,
stencil: stencilBuffer
},
initAttributes: initAttributes,
enableAttribute: enableAttribute,
enableAttributeAndDivisor: enableAttributeAndDivisor,
disableUnusedAttributes: disableUnusedAttributes,
vertexAttribPointer: vertexAttribPointer,
enable: enable,
disable: disable,
useProgram: useProgram,
setBlending: setBlending,
setMaterial: setMaterial,
setFlipSided: setFlipSided,
setCullFace: setCullFace,
setLineWidth: setLineWidth,
setPolygonOffset: setPolygonOffset,
setScissorTest: setScissorTest,
activeTexture: activeTexture,
bindTexture: bindTexture,
unbindTexture: unbindTexture,
compressedTexImage2D: compressedTexImage2D,
texImage2D: texImage2D,
texImage3D: texImage3D,
scissor: scissor,
viewport: viewport,
reset: reset
};
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
var isWebGL2 = capabilities.isWebGL2;
var maxTextures = capabilities.maxTextures;
var maxCubemapSize = capabilities.maxCubemapSize;
var maxTextureSize = capabilities.maxTextureSize;
var maxSamples = capabilities.maxSamples;
var _videoTextures = new WeakMap();
var _canvas;
// cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
// also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
// Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
var useOffscreenCanvas = false;
try {
useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
&& ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null;
} catch ( err ) {
// Ignore any errors
}
function createCanvas( width, height ) {
// Use OffscreenCanvas when available. Specially needed in web workers
return useOffscreenCanvas ?
new OffscreenCanvas( width, height ) :
document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
}
function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
var scale = 1;
// handle case if texture exceeds max size
if ( image.width > maxSize || image.height > maxSize ) {
scale = maxSize / Math.max( image.width, image.height );
}
// only perform resize if necessary
if ( scale < 1 || needsPowerOfTwo === true ) {
// only perform resize for certain image types
if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
var width = floor( scale * image.width );
var height = floor( scale * image.height );
if ( _canvas === undefined ) _canvas = createCanvas( width, height );
// cube textures can't reuse the same canvas
var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
canvas.width = width;
canvas.height = height;
var context = canvas.getContext( '2d' );
context.drawImage( image, 0, 0, width, height );
console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
return canvas;
} else {
if ( 'data' in image ) {
console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
}
return image;
}
}
return image;
}
function isPowerOfTwo( image ) {
return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );
}
function textureNeedsPowerOfTwo( texture ) {
if ( isWebGL2 ) return false;
return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
}
function textureNeedsGenerateMipmaps( texture, supportsMips ) {
return texture.generateMipmaps && supportsMips &&
texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
}
function generateMipmap( target, texture, width, height ) {
_gl.generateMipmap( target );
var textureProperties = properties.get( texture );
// Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
}
function getInternalFormat( internalFormatName, glFormat, glType ) {
if ( isWebGL2 === false ) return glFormat;
if ( internalFormatName !== null ) {
if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
}
var internalFormat = glFormat;
if ( glFormat === 6403 ) {
if ( glType === 5126 ) internalFormat = 33326;
if ( glType === 5131 ) internalFormat = 33325;
if ( glType === 5121 ) internalFormat = 33321;
}
if ( glFormat === 6407 ) {
if ( glType === 5126 ) internalFormat = 34837;
if ( glType === 5131 ) internalFormat = 34843;
if ( glType === 5121 ) internalFormat = 32849;
}
if ( glFormat === 6408 ) {
if ( glType === 5126 ) internalFormat = 34836;
if ( glType === 5131 ) internalFormat = 34842;
if ( glType === 5121 ) internalFormat = 32856;
}
if ( internalFormat === 33325 || internalFormat === 33326 ||
internalFormat === 34842 || internalFormat === 34836 ) {
extensions.get( 'EXT_color_buffer_float' );
}
return internalFormat;
}
// Fallback filters for non-power-of-2 textures
function filterFallback( f ) {
if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
return 9728;
}
return 9729;
}
//
function onTextureDispose( event ) {
var texture = event.target;
texture.removeEventListener( 'dispose', onTextureDispose );
deallocateTexture( texture );
if ( texture.isVideoTexture ) {
_videoTextures.delete( texture );
}
info.memory.textures --;
}
function onRenderTargetDispose( event ) {
var renderTarget = event.target;
renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
deallocateRenderTarget( renderTarget );
info.memory.textures --;
}
//
function deallocateTexture( texture ) {
var textureProperties = properties.get( texture );
if ( textureProperties.__webglInit === undefined ) return;
_gl.deleteTexture( textureProperties.__webglTexture );
properties.remove( texture );
}
function deallocateRenderTarget( renderTarget ) {
var renderTargetProperties = properties.get( renderTarget );
var textureProperties = properties.get( renderTarget.texture );
if ( ! renderTarget ) return;
if ( textureProperties.__webglTexture !== undefined ) {
_gl.deleteTexture( textureProperties.__webglTexture );
}
if ( renderTarget.depthTexture ) {
renderTarget.depthTexture.dispose();
}
if ( renderTarget.isWebGLCubeRenderTarget ) {
for ( var i = 0; i < 6; i ++ ) {
_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
}
} else {
_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
}
properties.remove( renderTarget.texture );
properties.remove( renderTarget );
}
//
var textureUnits = 0;
function resetTextureUnits() {
textureUnits = 0;
}
function allocateTextureUnit() {
var textureUnit = textureUnits;
if ( textureUnit >= maxTextures ) {
console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
}
textureUnits += 1;
return textureUnit;
}
//
function setTexture2D( texture, slot ) {
var textureProperties = properties.get( texture );
if ( texture.isVideoTexture ) updateVideoTexture( texture );
if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
var image = texture.image;
if ( image === undefined ) {
console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
} else if ( image.complete === false ) {
console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
} else {
uploadTexture( textureProperties, texture, slot );
return;
}
}
state.activeTexture( 33984 + slot );
state.bindTexture( 3553, textureProperties.__webglTexture );
}
function setTexture2DArray( texture, slot ) {
var textureProperties = properties.get( texture );
if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
uploadTexture( textureProperties, texture, slot );
return;
}
state.activeTexture( 33984 + slot );
state.bindTexture( 35866, textureProperties.__webglTexture );
}
function setTexture3D( texture, slot ) {
var textureProperties = properties.get( texture );
if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
uploadTexture( textureProperties, texture, slot );
return;
}
state.activeTexture( 33984 + slot );
state.bindTexture( 32879, textureProperties.__webglTexture );
}
function setTextureCube( texture, slot ) {
if ( texture.image.length !== 6 ) return;
var textureProperties = properties.get( texture );
if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
initTexture( textureProperties, texture );
state.activeTexture( 33984 + slot );
state.bindTexture( 34067, textureProperties.__webglTexture );
_gl.pixelStorei( 37440, texture.flipY );
var isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
var cubeImage = [];
for ( var i = 0; i < 6; i ++ ) {
if ( ! isCompressed && ! isDataTexture ) {
cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
} else {
cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
}
}
var image = cubeImage[ 0 ],
supportsMips = isPowerOfTwo( image ) || isWebGL2,
glFormat = utils.convert( texture.format ),
glType = utils.convert( texture.type ),
glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
setTextureParameters( 34067, texture, supportsMips );
var mipmaps;
if ( isCompressed ) {
for ( var i = 0; i < 6; i ++ ) {
mipmaps = cubeImage[ i ].mipmaps;
for ( var j = 0; j < mipmaps.length; j ++ ) {
var mipmap = mipmaps[ j ];
if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
if ( glFormat !== null ) {
state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
} else {
console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
}
} else {
state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
}
}
}
textureProperties.__maxMipLevel = mipmaps.length - 1;
} else {
mipmaps = texture.mipmaps;
for ( var i = 0; i < 6; i ++ ) {
if ( isDataTexture ) {
state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
for ( var j = 0; j < mipmaps.length; j ++ ) {
var mipmap = mipmaps[ j ];
var mipmapImage = mipmap.image[ i ].image;
state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
}
} else {
state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
for ( var j = 0; j < mipmaps.length; j ++ ) {
var mipmap = mipmaps[ j ];
state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
}
}
}
textureProperties.__maxMipLevel = mipmaps.length;
}
if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
// We assume images for cube map have the same size.
generateMipmap( 34067, texture, image.width, image.height );
}
textureProperties.__version = texture.version;
if ( texture.onUpdate ) texture.onUpdate( texture );
} else {
state.activeTexture( 33984 + slot );
state.bindTexture( 34067, textureProperties.__webglTexture );
}
}
function setTextureCubeDynamic( texture, slot ) {
state.activeTexture( 33984 + slot );
state.bindTexture( 34067, properties.get( texture ).__webglTexture );
}
var wrappingToGL = {
[ RepeatWrapping ]: 10497,
[ ClampToEdgeWrapping ]: 33071,
[ MirroredRepeatWrapping ]: 33648
};
var filterToGL = {
[ NearestFilter ]: 9728,
[ NearestMipmapNearestFilter ]: 9984,
[ NearestMipmapLinearFilter ]: 9986,
[ LinearFilter ]: 9729,
[ LinearMipmapNearestFilter ]: 9985,
[ LinearMipmapLinearFilter ]: 9987
};
function setTextureParameters( textureType, texture, supportsMips ) {
if ( supportsMips ) {
_gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
_gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
if ( textureType === 32879 || textureType === 35866 ) {
_gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
}
_gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
_gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
} else {
_gl.texParameteri( textureType, 10242, 33071 );
_gl.texParameteri( textureType, 10243, 33071 );
if ( textureType === 32879 || textureType === 35866 ) {
_gl.texParameteri( textureType, 32882, 33071 );
}
if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
}
_gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
_gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
}
}
var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
if ( extension ) {
if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
_gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
properties.get( texture ).__currentAnisotropy = texture.anisotropy;
}
}
}
function initTexture( textureProperties, texture ) {
if ( textureProperties.__webglInit === undefined ) {
textureProperties.__webglInit = true;
texture.addEventListener( 'dispose', onTextureDispose );
textureProperties.__webglTexture = _gl.createTexture();
info.memory.textures ++;
}
}
function uploadTexture( textureProperties, texture, slot ) {
var textureType = 3553;
if ( texture.isDataTexture2DArray ) textureType = 35866;
if ( texture.isDataTexture3D ) textureType = 32879;
initTexture( textureProperties, texture );
state.activeTexture( 33984 + slot );
state.bindTexture( textureType, textureProperties.__webglTexture );
_gl.pixelStorei( 37440, texture.flipY );
_gl.pixelStorei( 37441, texture.premultiplyAlpha );
_gl.pixelStorei( 3317, texture.unpackAlignment );
var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
var image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
var supportsMips = isPowerOfTwo( image ) || isWebGL2,
glFormat = utils.convert( texture.format ),
glType = utils.convert( texture.type ),
glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
setTextureParameters( textureType, texture, supportsMips );
var mipmap, mipmaps = texture.mipmaps;
if ( texture.isDepthTexture ) {
// populate depth texture with dummy data
glInternalFormat = 6402;
if ( isWebGL2 ) {
if ( texture.type === FloatType ) {
glInternalFormat = 36012;
} else if ( texture.type === UnsignedIntType ) {
glInternalFormat = 33190;
} else if ( texture.type === UnsignedInt248Type ) {
glInternalFormat = 35056;
} else {
glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
}
} else {
if ( texture.type === FloatType ) {
console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
}
}
// validation checks for WebGL 1
if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
// DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
texture.type = UnsignedShortType;
glType = utils.convert( texture.type );
}
}
if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
// Depth stencil textures need the DEPTH_STENCIL internal format
// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
glInternalFormat = 34041;
// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
// DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
if ( texture.type !== UnsignedInt248Type ) {
console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
texture.type = UnsignedInt248Type;
glType = utils.convert( texture.type );
}
}
//
state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
} else if ( texture.isDataTexture ) {
// use manually created mipmaps if available
// if there are no manual mipmaps
// set 0 level mipmap and then use GL to generate other mipmap levels
if ( mipmaps.length > 0 && supportsMips ) {
for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
mipmap = mipmaps[ i ];
state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
}
texture.generateMipmaps = false;
textureProperties.__maxMipLevel = mipmaps.length - 1;
} else {
state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
textureProperties.__maxMipLevel = 0;
}
} else if ( texture.isCompressedTexture ) {
for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
mipmap = mipmaps[ i ];
if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
if ( glFormat !== null ) {
state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
} else {
console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
}
} else {
state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
}
}
textureProperties.__maxMipLevel = mipmaps.length - 1;
} else if ( texture.isDataTexture2DArray ) {
state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
textureProperties.__maxMipLevel = 0;
} else if ( texture.isDataTexture3D ) {
state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
textureProperties.__maxMipLevel = 0;
} else {
// regular Texture (image, video, canvas)
// use manually created mipmaps if available
// if there are no manual mipmaps
// set 0 level mipmap and then use GL to generate other mipmap levels
if ( mipmaps.length > 0 && supportsMips ) {
for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
mipmap = mipmaps[ i ];
state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
}
texture.generateMipmaps = false;
textureProperties.__maxMipLevel = mipmaps.length - 1;
} else {
state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
textureProperties.__maxMipLevel = 0;
}
}
if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
generateMipmap( textureType, texture, image.width, image.height );
}
textureProperties.__version = texture.version;
if ( texture.onUpdate ) texture.onUpdate( texture );
}
// Render targets
// Setup storage for target texture and bind it to correct framebuffer
function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
var glFormat = utils.convert( renderTarget.texture.format );
var glType = utils.convert( renderTarget.texture.type );
var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
_gl.bindFramebuffer( 36160, framebuffer );
_gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
_gl.bindFramebuffer( 36160, null );
}
// Setup storage for internal depth/stencil buffers and bind to correct framebuffer
function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
_gl.bindRenderbuffer( 36161, renderbuffer );
if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
var glInternalFormat = 33189;
if ( isMultisample ) {
var depthTexture = renderTarget.depthTexture;
if ( depthTexture && depthTexture.isDepthTexture ) {
if ( depthTexture.type === FloatType ) {
glInternalFormat = 36012;
} else if ( depthTexture.type === UnsignedIntType ) {
glInternalFormat = 33190;
}
}
var samples = getRenderTargetSamples( renderTarget );
_gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
} else {
_gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
}
_gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
if ( isMultisample ) {
var samples = getRenderTargetSamples( renderTarget );
_gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
} else {
_gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
}
_gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
} else {
var glFormat = utils.convert( renderTarget.texture.format );
var glType = utils.convert( renderTarget.texture.type );
var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
if ( isMultisample ) {
var samples = getRenderTargetSamples( renderTarget );
_gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
} else {
_gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
}
}
_gl.bindRenderbuffer( 36161, null );
}
// Setup resources for a Depth Texture for a FBO (needs an extension)
function setupDepthTexture( framebuffer, renderTarget ) {
var isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
_gl.bindFramebuffer( 36160, framebuffer );
if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
}
// upload an empty depth texture with framebuffer size
if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
renderTarget.depthTexture.image.width !== renderTarget.width ||
renderTarget.depthTexture.image.height !== renderTarget.height ) {
renderTarget.depthTexture.image.width = renderTarget.width;
renderTarget.depthTexture.image.height = renderTarget.height;
renderTarget.depthTexture.needsUpdate = true;
}
setTexture2D( renderTarget.depthTexture, 0 );
var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
if ( renderTarget.depthTexture.format === DepthFormat ) {
_gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
} else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
_gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
} else {
throw new Error( 'Unknown depthTexture format' );
}
}
// Setup GL resources for a non-texture depth buffer
function setupDepthRenderbuffer( renderTarget ) {
var renderTargetProperties = properties.get( renderTarget );
var isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
if ( renderTarget.depthTexture ) {
if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
} else {
if ( isCube ) {
renderTargetProperties.__webglDepthbuffer = [];
for ( var i = 0; i < 6; i ++ ) {
_gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
}
} else {
_gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
}
}
_gl.bindFramebuffer( 36160, null );
}
// Set up GL resources for the render target
function setupRenderTarget( renderTarget ) {
var renderTargetProperties = properties.get( renderTarget );
var textureProperties = properties.get( renderTarget.texture );
renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
textureProperties.__webglTexture = _gl.createTexture();
info.memory.textures ++;
var isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
// Handles WebGL2 RGBFormat fallback - #18858
if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) {
renderTarget.texture.format = RGBAFormat;
console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
}
// Setup framebuffer
if ( isCube ) {
renderTargetProperties.__webglFramebuffer = [];
for ( var i = 0; i < 6; i ++ ) {
renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
}
} else {
renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
if ( isMultisample ) {
if ( isWebGL2 ) {
renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
_gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
var glFormat = utils.convert( renderTarget.texture.format );
var glType = utils.convert( renderTarget.texture.type );
var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
var samples = getRenderTargetSamples( renderTarget );
_gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
_gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
_gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
_gl.bindRenderbuffer( 36161, null );
if ( renderTarget.depthBuffer ) {
renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
}
_gl.bindFramebuffer( 36160, null );
} else {
console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
}
}
}
// Setup color buffer
if ( isCube ) {
state.bindTexture( 34067, textureProperties.__webglTexture );
setTextureParameters( 34067, renderTarget.texture, supportsMips );
for ( var i = 0; i < 6; i ++ ) {
setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
}
if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
}
state.bindTexture( 34067, null );
} else {
state.bindTexture( 3553, textureProperties.__webglTexture );
setTextureParameters( 3553, renderTarget.texture, supportsMips );
setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
}
state.bindTexture( 3553, null );
}
// Setup depth and stencil buffers
if ( renderTarget.depthBuffer ) {
setupDepthRenderbuffer( renderTarget );
}
}
function updateRenderTargetMipmap( renderTarget ) {
var texture = renderTarget.texture;
var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
var webglTexture = properties.get( texture ).__webglTexture;
state.bindTexture( target, webglTexture );
generateMipmap( target, texture, renderTarget.width, renderTarget.height );
state.bindTexture( target, null );
}
}
function updateMultisampleRenderTarget( renderTarget ) {
if ( renderTarget.isWebGLMultisampleRenderTarget ) {
if ( isWebGL2 ) {
var renderTargetProperties = properties.get( renderTarget );
_gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
_gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
var width = renderTarget.width;
var height = renderTarget.height;
var mask = 16384;
if ( renderTarget.depthBuffer ) mask |= 256;
if ( renderTarget.stencilBuffer ) mask |= 1024;
_gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
_gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905
} else {
console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
}
}
}
function getRenderTargetSamples( renderTarget ) {
return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
Math.min( maxSamples, renderTarget.samples ) : 0;
}
function updateVideoTexture( texture ) {
var frame = info.render.frame;
// Check the last frame we updated the VideoTexture
if ( _videoTextures.get( texture ) !== frame ) {
_videoTextures.set( texture, frame );
texture.update();
}
}
// backwards compatibility
var warnedTexture2D = false;
var warnedTextureCube = false;
function safeSetTexture2D( texture, slot ) {
if ( texture && texture.isWebGLRenderTarget ) {
if ( warnedTexture2D === false ) {
console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." );
warnedTexture2D = true;
}
texture = texture.texture;
}
setTexture2D( texture, slot );
}
function safeSetTextureCube( texture, slot ) {
if ( texture && texture.isWebGLCubeRenderTarget ) {
if ( warnedTextureCube === false ) {
console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
warnedTextureCube = true;
}
texture = texture.texture;
}
// currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture
// TODO: unify these code paths
if ( ( texture && texture.isCubeTexture ) ||
( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
// CompressedTexture can have Array in image :/
// this function alone should take care of cube textures
setTextureCube( texture, slot );
} else {
// assumed: texture property of THREE.WebGLCubeRenderTarget
setTextureCubeDynamic( texture, slot );
}
}
//
this.allocateTextureUnit = allocateTextureUnit;
this.resetTextureUnits = resetTextureUnits;
this.setTexture2D = setTexture2D;
this.setTexture2DArray = setTexture2DArray;
this.setTexture3D = setTexture3D;
this.setTextureCube = setTextureCube;
this.setTextureCubeDynamic = setTextureCubeDynamic;
this.setupRenderTarget = setupRenderTarget;
this.updateRenderTargetMipmap = updateRenderTargetMipmap;
this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
this.safeSetTexture2D = safeSetTexture2D;
this.safeSetTextureCube = safeSetTextureCube;
}
/**
* @author thespite / http://www.twitter.com/thespite
*/
function WebGLUtils( gl, extensions, capabilities ) {
var isWebGL2 = capabilities.isWebGL2;
function convert( p ) {
var extension;
if ( p === UnsignedByteType ) return 5121;
if ( p === UnsignedShort4444Type ) return 32819;
if ( p === UnsignedShort5551Type ) return 32820;
if ( p === UnsignedShort565Type ) return 33635;
if ( p === ByteType ) return 5120;
if ( p === ShortType ) return 5122;
if ( p === UnsignedShortType ) return 5123;
if ( p === IntType ) return 5124;
if ( p === UnsignedIntType ) return 5125;
if ( p === FloatType ) return 5126;
if ( p === HalfFloatType ) {
if ( isWebGL2 ) return 5131;
extension = extensions.get( 'OES_texture_half_float' );
if ( extension !== null ) {
return extension.HALF_FLOAT_OES;
} else {
return null;
}
}
if ( p === AlphaFormat ) return 6406;
if ( p === RGBFormat ) return 6407;
if ( p === RGBAFormat ) return 6408;
if ( p === LuminanceFormat ) return 6409;
if ( p === LuminanceAlphaFormat ) return 6410;
if ( p === DepthFormat ) return 6402;
if ( p === DepthStencilFormat ) return 34041;
if ( p === RedFormat ) return 6403;
// WebGL2 formats.
if ( p === RedIntegerFormat ) return 36244;
if ( p === RGFormat ) return 33319;
if ( p === RGIntegerFormat ) return 33320;
if ( p === RGBIntegerFormat ) return 36248;
if ( p === RGBAIntegerFormat ) return 36249;
if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
if ( extension !== null ) {
if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
} else {
return null;
}
}
if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
if ( extension !== null ) {
if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
} else {
return null;
}
}
if ( p === RGB_ETC1_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
if ( extension !== null ) {
return extension.COMPRESSED_RGB_ETC1_WEBGL;
} else {
return null;
}
}
if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_etc' );
if ( extension !== null ) {
if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
}
}
if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
extension = extensions.get( 'WEBGL_compressed_texture_astc' );
if ( extension !== null ) {
// TODO Complete?
return p;
} else {
return null;
}
}
if ( p === RGBA_BPTC_Format ) {
extension = extensions.get( 'EXT_texture_compression_bptc' );
if ( extension !== null ) {
// TODO Complete?
return p;
} else {
return null;
}
}
if ( p === UnsignedInt248Type ) {
if ( isWebGL2 ) return 34042;
extension = extensions.get( 'WEBGL_depth_texture' );
if ( extension !== null ) {
return extension.UNSIGNED_INT_24_8_WEBGL;
} else {
return null;
}
}
}
return { convert: convert };
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function ArrayCamera( array ) {
PerspectiveCamera.call( this );
this.cameras = array || [];
}
ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
constructor: ArrayCamera,
isArrayCamera: true
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function Group() {
Object3D.call( this );
this.type = 'Group';
}
Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Group,
isGroup: true
} );
/**
* @author Mugen87 / https://github.com/Mugen87
*/
function WebXRController() {
this._targetRay = null;
this._grip = null;
}
Object.assign( WebXRController.prototype, {
constructor: WebXRController,
getTargetRaySpace: function () {
if ( this._targetRay === null ) {
this._targetRay = new Group();
this._targetRay.matrixAutoUpdate = false;
this._targetRay.visible = false;
}
return this._targetRay;
},
getGripSpace: function () {
if ( this._grip === null ) {
this._grip = new Group();
this._grip.matrixAutoUpdate = false;
this._grip.visible = false;
}
return this._grip;
},
dispatchEvent: function ( event ) {
if ( this._targetRay !== null ) {
this._targetRay.dispatchEvent( event );
}
if ( this._grip !== null ) {
this._grip.dispatchEvent( event );
}
return this;
},
disconnect: function ( inputSource ) {
this.dispatchEvent( { type: 'disconnected', data: inputSource } );
if ( this._targetRay !== null ) {
this._targetRay.visible = false;
}
if ( this._grip !== null ) {
this._grip.visible = false;
}
return this;
},
update: function ( inputSource, frame, referenceSpace ) {
var inputPose = null;
var gripPose = null;
var targetRay = this._targetRay;
var grip = this._grip;
if ( inputSource ) {
if ( targetRay !== null ) {
inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
if ( inputPose !== null ) {
targetRay.matrix.fromArray( inputPose.transform.matrix );
targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
}
}
if ( grip !== null && inputSource.gripSpace ) {
gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
if ( gripPose !== null ) {
grip.matrix.fromArray( gripPose.transform.matrix );
grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
}
}
}
if ( targetRay !== null ) {
targetRay.visible = ( inputPose !== null );
}
if ( grip !== null ) {
grip.visible = ( gripPose !== null );
}
return this;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebXRManager( renderer, gl ) {
var scope = this;
var session = null;
var framebufferScaleFactor = 1.0;
var referenceSpace = null;
var referenceSpaceType = 'local-floor';
var pose = null;
var controllers = [];
var inputSourcesMap = new Map();
//
var cameraL = new PerspectiveCamera();
cameraL.layers.enable( 1 );
cameraL.viewport = new Vector4();
var cameraR = new PerspectiveCamera();
cameraR.layers.enable( 2 );
cameraR.viewport = new Vector4();
var cameras = [ cameraL, cameraR ];
var cameraVR = new ArrayCamera();
cameraVR.layers.enable( 1 );
cameraVR.layers.enable( 2 );
var _currentDepthNear = null;
var _currentDepthFar = null;
//
this.enabled = false;
this.isPresenting = false;
this.getController = function ( index ) {
var controller = controllers[ index ];
if ( controller === undefined ) {
controller = new WebXRController();
controllers[ index ] = controller;
}
return controller.getTargetRaySpace();
};
this.getControllerGrip = function ( index ) {
var controller = controllers[ index ];
if ( controller === undefined ) {
controller = new WebXRController();
controllers[ index ] = controller;
}
return controller.getGripSpace();
};
//
function onSessionEvent( event ) {
var controller = inputSourcesMap.get( event.inputSource );
if ( controller ) {
controller.dispatchEvent( { type: event.type } );
}
}
function onSessionEnd() {
inputSourcesMap.forEach( function ( controller, inputSource ) {
controller.disconnect( inputSource );
} );
inputSourcesMap.clear();
//
renderer.setFramebuffer( null );
renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
animation.stop();
scope.isPresenting = false;
scope.dispatchEvent( { type: 'sessionend' } );
}
function onRequestReferenceSpace( value ) {
referenceSpace = value;
animation.setContext( session );
animation.start();
scope.isPresenting = true;
scope.dispatchEvent( { type: 'sessionstart' } );
}
this.setFramebufferScaleFactor = function ( value ) {
framebufferScaleFactor = value;
if ( scope.isPresenting === true ) {
console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
}
};
this.setReferenceSpaceType = function ( value ) {
referenceSpaceType = value;
if ( scope.isPresenting === true ) {
console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
}
};
this.getReferenceSpace = function () {
return referenceSpace;
};
this.getSession = function () {
return session;
};
this.setSession = function ( value ) {
session = value;
if ( session !== null ) {
session.addEventListener( 'select', onSessionEvent );
session.addEventListener( 'selectstart', onSessionEvent );
session.addEventListener( 'selectend', onSessionEvent );
session.addEventListener( 'squeeze', onSessionEvent );
session.addEventListener( 'squeezestart', onSessionEvent );
session.addEventListener( 'squeezeend', onSessionEvent );
session.addEventListener( 'end', onSessionEnd );
var attributes = gl.getContextAttributes();
var layerInit = {
antialias: attributes.antialias,
alpha: attributes.alpha,
depth: attributes.depth,
stencil: attributes.stencil,
framebufferScaleFactor: framebufferScaleFactor
};
// eslint-disable-next-line no-undef
var baseLayer = new XRWebGLLayer( session, gl, layerInit );
session.updateRenderState( { baseLayer: baseLayer } );
session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );
//
session.addEventListener( 'inputsourceschange', updateInputSources );
}
};
function updateInputSources( event ) {
var inputSources = session.inputSources;
// Assign inputSources to available controllers
for ( var i = 0; i < controllers.length; i ++ ) {
inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
}
// Notify disconnected
for ( var i = 0; i < event.removed.length; i ++ ) {
var inputSource = event.removed[ i ];
var controller = inputSourcesMap.get( inputSource );
if ( controller ) {
controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
inputSourcesMap.delete( inputSource );
}
}
// Notify connected
for ( var i = 0; i < event.added.length; i ++ ) {
var inputSource = event.added[ i ];
var controller = inputSourcesMap.get( inputSource );
if ( controller ) {
controller.dispatchEvent( { type: 'connected', data: inputSource } );
}
}
}
//
var cameraLPos = new Vector3();
var cameraRPos = new Vector3();
/**
* @author jsantell / https://www.jsantell.com/
*
* Assumes 2 cameras that are parallel and share an X-axis, and that
* the cameras' projection and world matrices have already been set.
* And that near and far planes are identical for both cameras.
* Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
*/
function setProjectionFromUnion( camera, cameraL, cameraR ) {
cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
var ipd = cameraLPos.distanceTo( cameraRPos );
var projL = cameraL.projectionMatrix.elements;
var projR = cameraR.projectionMatrix.elements;
// VR systems will have identical far and near planes, and
// most likely identical top and bottom frustum extents.
// Use the left camera for these values.
var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
var left = near * leftFov;
var right = near * rightFov;
// Calculate the new camera's position offset from the
// left camera. xOffset should be roughly half `ipd`.
var zOffset = ipd / ( - leftFov + rightFov );
var xOffset = zOffset * - leftFov;
// TODO: Better way to apply this offset?
cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
camera.translateX( xOffset );
camera.translateZ( zOffset );
camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
// Find the union of the frustum values of the cameras and scale
// the values so that the near plane's position does not change in world space,
// although must now be relative to the new union camera.
var near2 = near + zOffset;
var far2 = far + zOffset;
var left2 = left - xOffset;
var right2 = right + ( ipd - xOffset );
var top2 = topFov * far / far2 * near2;
var bottom2 = bottomFov * far / far2 * near2;
camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
}
function updateCamera( camera, parent ) {
if ( parent === null ) {
camera.matrixWorld.copy( camera.matrix );
} else {
camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
}
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
}
this.getCamera = function ( camera ) {
cameraVR.near = cameraR.near = cameraL.near = camera.near;
cameraVR.far = cameraR.far = cameraL.far = camera.far;
if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
// Note that the new renderState won't apply until the next frame. See #18320
session.updateRenderState( {
depthNear: cameraVR.near,
depthFar: cameraVR.far
} );
_currentDepthNear = cameraVR.near;
_currentDepthFar = cameraVR.far;
}
var parent = camera.parent;
var cameras = cameraVR.cameras;
updateCamera( cameraVR, parent );
for ( var i = 0; i < cameras.length; i ++ ) {
updateCamera( cameras[ i ], parent );
}
// update camera and its children
camera.matrixWorld.copy( cameraVR.matrixWorld );
var children = camera.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].updateMatrixWorld( true );
}
// update projection matrix for proper view frustum culling
if ( cameras.length === 2 ) {
setProjectionFromUnion( cameraVR, cameraL, cameraR );
} else {
// assume single camera setup (AR)
cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
}
return cameraVR;
};
// Animation Loop
var onAnimationFrameCallback = null;
function onAnimationFrame( time, frame ) {
pose = frame.getViewerPose( referenceSpace );
if ( pose !== null ) {
var views = pose.views;
var baseLayer = session.renderState.baseLayer;
renderer.setFramebuffer( baseLayer.framebuffer );
var cameraVRNeedsUpdate = false;
// check if it's necessary to rebuild cameraVR's camera list
if ( views.length !== cameraVR.cameras.length ) {
cameraVR.cameras.length = 0;
cameraVRNeedsUpdate = true;
}
for ( var i = 0; i < views.length; i ++ ) {
var view = views[ i ];
var viewport = baseLayer.getViewport( view );
var camera = cameras[ i ];
camera.matrix.fromArray( view.transform.matrix );
camera.projectionMatrix.fromArray( view.projectionMatrix );
camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
if ( i === 0 ) {
cameraVR.matrix.copy( camera.matrix );
}
if ( cameraVRNeedsUpdate === true ) {
cameraVR.cameras.push( camera );
}
}
}
//
var inputSources = session.inputSources;
for ( var i = 0; i < controllers.length; i ++ ) {
var controller = controllers[ i ];
var inputSource = inputSources[ i ];
controller.update( inputSource, frame, referenceSpace );
}
if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
}
var animation = new WebGLAnimation();
animation.setAnimationLoop( onAnimationFrame );
this.setAnimationLoop = function ( callback ) {
onAnimationFrameCallback = callback;
};
this.dispose = function () {};
}
Object.assign( WebXRManager.prototype, EventDispatcher.prototype );
/**
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author szimek / https://github.com/szimek/
* @author tschw
*/
function WebGLRenderer( parameters ) {
parameters = parameters || {};
var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
_context = parameters.context !== undefined ? parameters.context : null,
_alpha = parameters.alpha !== undefined ? parameters.alpha : false,
_depth = parameters.depth !== undefined ? parameters.depth : true,
_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
_powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
_failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
var currentRenderList = null;
var currentRenderState = null;
// public properties
this.domElement = _canvas;
// Debug configuration container
this.debug = {
/**
* Enables error checking and reporting when shader programs are being compiled
* @type {boolean}
*/
checkShaderErrors: true
};
// clearing
this.autoClear = true;
this.autoClearColor = true;
this.autoClearDepth = true;
this.autoClearStencil = true;
// scene graph
this.sortObjects = true;
// user-defined clipping
this.clippingPlanes = [];
this.localClippingEnabled = false;
// physically based shading
this.gammaFactor = 2.0; // for backwards compatibility
this.outputEncoding = LinearEncoding;
// physical lights
this.physicallyCorrectLights = false;
// tone mapping
this.toneMapping = NoToneMapping;
this.toneMappingExposure = 1.0;
this.toneMappingWhitePoint = 1.0;
// morphs
this.maxMorphTargets = 8;
this.maxMorphNormals = 4;
// internal properties
var _this = this,
_isContextLost = false,
// internal state cache
_framebuffer = null,
_currentActiveCubeFace = 0,
_currentActiveMipmapLevel = 0,
_currentRenderTarget = null,
_currentFramebuffer = null,
_currentMaterialId = - 1,
// geometry and program caching
_currentGeometryProgram = {
geometry: null,
program: null,
wireframe: false
},
_currentCamera = null,
_currentArrayCamera = null,
_currentViewport = new Vector4(),
_currentScissor = new Vector4(),
_currentScissorTest = null,
//
_width = _canvas.width,
_height = _canvas.height,
_pixelRatio = 1,
_opaqueSort = null,
_transparentSort = null,
_viewport = new Vector4( 0, 0, _width, _height ),
_scissor = new Vector4( 0, 0, _width, _height ),
_scissorTest = false,
// frustum
_frustum = new Frustum(),
// clipping
_clipping = new WebGLClipping(),
_clippingEnabled = false,
_localClippingEnabled = false,
// camera matrices cache
_projScreenMatrix = new Matrix4(),
_vector3 = new Vector3();
function getTargetPixelRatio() {
return _currentRenderTarget === null ? _pixelRatio : 1;
}
// initialize
var _gl;
try {
var contextAttributes = {
alpha: _alpha,
depth: _depth,
stencil: _stencil,
antialias: _antialias,
premultipliedAlpha: _premultipliedAlpha,
preserveDrawingBuffer: _preserveDrawingBuffer,
powerPreference: _powerPreference,
failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
xrCompatible: true
};
// event listeners must be registered before WebGL context is created, see #12753
_canvas.addEventListener( 'webglcontextlost', onContextLost, false );
_canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
_gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
if ( _gl === null ) {
if ( _canvas.getContext( 'webgl' ) !== null ) {
throw new Error( 'Error creating WebGL context with your selected attributes.' );
} else {
throw new Error( 'Error creating WebGL context.' );
}
}
// Some experimental-webgl implementations do not have getShaderPrecisionFormat
if ( _gl.getShaderPrecisionFormat === undefined ) {
_gl.getShaderPrecisionFormat = function () {
return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
};
}
} catch ( error ) {
console.error( 'THREE.WebGLRenderer: ' + error.message );
throw error;
}
var extensions, capabilities, state, info;
var properties, textures, attributes, geometries, objects;
var programCache, renderLists, renderStates;
var background, morphtargets, bufferRenderer, indexedBufferRenderer;
var utils;
function initGLContext() {
extensions = new WebGLExtensions( _gl );
capabilities = new WebGLCapabilities( _gl, extensions, parameters );
if ( capabilities.isWebGL2 === false ) {
extensions.get( 'WEBGL_depth_texture' );
extensions.get( 'OES_texture_float' );
extensions.get( 'OES_texture_half_float' );
extensions.get( 'OES_texture_half_float_linear' );
extensions.get( 'OES_standard_derivatives' );
extensions.get( 'OES_element_index_uint' );
extensions.get( 'ANGLE_instanced_arrays' );
}
extensions.get( 'OES_texture_float_linear' );
utils = new WebGLUtils( _gl, extensions, capabilities );
state = new WebGLState( _gl, extensions, capabilities );
state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
info = new WebGLInfo( _gl );
properties = new WebGLProperties();
textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
attributes = new WebGLAttributes( _gl, capabilities );
geometries = new WebGLGeometries( _gl, attributes, info );
objects = new WebGLObjects( _gl, geometries, attributes, info );
morphtargets = new WebGLMorphtargets( _gl );
programCache = new WebGLPrograms( _this, extensions, capabilities );
renderLists = new WebGLRenderLists();
renderStates = new WebGLRenderStates();
background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
info.programs = programCache.programs;
_this.capabilities = capabilities;
_this.extensions = extensions;
_this.properties = properties;
_this.renderLists = renderLists;
_this.state = state;
_this.info = info;
}
initGLContext();
// xr
var xr = new WebXRManager( _this, _gl );
this.xr = xr;
// shadow map
var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
this.shadowMap = shadowMap;
// API
this.getContext = function () {
return _gl;
};
this.getContextAttributes = function () {
return _gl.getContextAttributes();
};
this.forceContextLoss = function () {
var extension = extensions.get( 'WEBGL_lose_context' );
if ( extension ) extension.loseContext();
};
this.forceContextRestore = function () {
var extension = extensions.get( 'WEBGL_lose_context' );
if ( extension ) extension.restoreContext();
};
this.getPixelRatio = function () {
return _pixelRatio;
};
this.setPixelRatio = function ( value ) {
if ( value === undefined ) return;
_pixelRatio = value;
this.setSize( _width, _height, false );
};
this.getSize = function ( target ) {
if ( target === undefined ) {
console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
target = new Vector2();
}
return target.set( _width, _height );
};
this.setSize = function ( width, height, updateStyle ) {
if ( xr.isPresenting ) {
console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
return;
}
_width = width;
_height = height;
_canvas.width = Math.floor( width * _pixelRatio );
_canvas.height = Math.floor( height * _pixelRatio );
if ( updateStyle !== false ) {
_canvas.style.width = width + 'px';
_canvas.style.height = height + 'px';
}
this.setViewport( 0, 0, width, height );
};
this.getDrawingBufferSize = function ( target ) {
if ( target === undefined ) {
console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
target = new Vector2();
}
return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
};
this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
_width = width;
_height = height;
_pixelRatio = pixelRatio;
_canvas.width = Math.floor( width * pixelRatio );
_canvas.height = Math.floor( height * pixelRatio );
this.setViewport( 0, 0, width, height );
};
this.getCurrentViewport = function ( target ) {
if ( target === undefined ) {
console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
target = new Vector4();
}
return target.copy( _currentViewport );
};
this.getViewport = function ( target ) {
return target.copy( _viewport );
};
this.setViewport = function ( x, y, width, height ) {
if ( x.isVector4 ) {
_viewport.set( x.x, x.y, x.z, x.w );
} else {
_viewport.set( x, y, width, height );
}
state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
};
this.getScissor = function ( target ) {
return target.copy( _scissor );
};
this.setScissor = function ( x, y, width, height ) {
if ( x.isVector4 ) {
_scissor.set( x.x, x.y, x.z, x.w );
} else {
_scissor.set( x, y, width, height );
}
state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
};
this.getScissorTest = function () {
return _scissorTest;
};
this.setScissorTest = function ( boolean ) {
state.setScissorTest( _scissorTest = boolean );
};
this.setOpaqueSort = function ( method ) {
_opaqueSort = method;
};
this.setTransparentSort = function ( method ) {
_transparentSort = method;
};
// Clearing
this.getClearColor = function () {
return background.getClearColor();
};
this.setClearColor = function () {
background.setClearColor.apply( background, arguments );
};
this.getClearAlpha = function () {
return background.getClearAlpha();
};
this.setClearAlpha = function () {
background.setClearAlpha.apply( background, arguments );
};
this.clear = function ( color, depth, stencil ) {
var bits = 0;
if ( color === undefined || color ) bits |= 16384;
if ( depth === undefined || depth ) bits |= 256;
if ( stencil === undefined || stencil ) bits |= 1024;
_gl.clear( bits );
};
this.clearColor = function () {
this.clear( true, false, false );
};
this.clearDepth = function () {
this.clear( false, true, false );
};
this.clearStencil = function () {
this.clear( false, false, true );
};
//
this.dispose = function () {
_canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
_canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
renderLists.dispose();
renderStates.dispose();
properties.dispose();
objects.dispose();
xr.dispose();
animation.stop();
};
// Events
function onContextLost( event ) {
event.preventDefault();
console.log( 'THREE.WebGLRenderer: Context Lost.' );
_isContextLost = true;
}
function onContextRestore( /* event */ ) {
console.log( 'THREE.WebGLRenderer: Context Restored.' );
_isContextLost = false;
initGLContext();
}
function onMaterialDispose( event ) {
var material = event.target;
material.removeEventListener( 'dispose', onMaterialDispose );
deallocateMaterial( material );
}
// Buffer deallocation
function deallocateMaterial( material ) {
releaseMaterialProgramReference( material );
properties.remove( material );
}
function releaseMaterialProgramReference( material ) {
var programInfo = properties.get( material ).program;
material.program = undefined;
if ( programInfo !== undefined ) {
programCache.releaseProgram( programInfo );
}
}
// Buffer rendering
function renderObjectImmediate( object, program ) {
object.render( function ( object ) {
_this.renderBufferImmediate( object, program );
} );
}
this.renderBufferImmediate = function ( object, program ) {
state.initAttributes();
var buffers = properties.get( object );
if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
var programAttributes = program.getAttributes();
if ( object.hasPositions ) {
_gl.bindBuffer( 34962, buffers.position );
_gl.bufferData( 34962, object.positionArray, 35048 );
state.enableAttribute( programAttributes.position );
_gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
}
if ( object.hasNormals ) {
_gl.bindBuffer( 34962, buffers.normal );
_gl.bufferData( 34962, object.normalArray, 35048 );
state.enableAttribute( programAttributes.normal );
_gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
}
if ( object.hasUvs ) {
_gl.bindBuffer( 34962, buffers.uv );
_gl.bufferData( 34962, object.uvArray, 35048 );
state.enableAttribute( programAttributes.uv );
_gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
}
if ( object.hasColors ) {
_gl.bindBuffer( 34962, buffers.color );
_gl.bufferData( 34962, object.colorArray, 35048 );
state.enableAttribute( programAttributes.color );
_gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
}
state.disableUnusedAttributes();
_gl.drawArrays( 4, 0, object.count );
object.count = 0;
};
var tempScene = new Scene();
this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
if ( scene === null ) scene = tempScene; // renderBufferDirect second parameter used to be fog (could be null)
var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
var program = setProgram( camera, scene, material, object );
state.setMaterial( material, frontFaceCW );
var updateBuffers = false;
if ( _currentGeometryProgram.geometry !== geometry.id ||
_currentGeometryProgram.program !== program.id ||
_currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {
_currentGeometryProgram.geometry = geometry.id;
_currentGeometryProgram.program = program.id;
_currentGeometryProgram.wireframe = material.wireframe === true;
updateBuffers = true;
}
if ( material.morphTargets || material.morphNormals ) {
morphtargets.update( object, geometry, material, program );
updateBuffers = true;
}
if ( object.isInstancedMesh === true ) {
updateBuffers = true;
}
//
var index = geometry.index;
var position = geometry.attributes.position;
//
if ( index === null ) {
if ( position === undefined || position.count === 0 ) return;
} else if ( index.count === 0 ) {
return;
}
//
var rangeFactor = 1;
if ( material.wireframe === true ) {
index = geometries.getWireframeAttribute( geometry );
rangeFactor = 2;
}
var attribute;
var renderer = bufferRenderer;
if ( index !== null ) {
attribute = attributes.get( index );
renderer = indexedBufferRenderer;
renderer.setIndex( attribute );
}
if ( updateBuffers ) {
setupVertexAttributes( object, geometry, material, program );
if ( index !== null ) {
_gl.bindBuffer( 34963, attribute.buffer );
}
}
//
var dataCount = ( index !== null ) ? index.count : position.count;
var rangeStart = geometry.drawRange.start * rangeFactor;
var rangeCount = geometry.drawRange.count * rangeFactor;
var groupStart = group !== null ? group.start * rangeFactor : 0;
var groupCount = group !== null ? group.count * rangeFactor : Infinity;
var drawStart = Math.max( rangeStart, groupStart );
var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
if ( drawCount === 0 ) return;
//
if ( object.isMesh ) {
if ( material.wireframe === true ) {
state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
renderer.setMode( 1 );
} else {
renderer.setMode( 4 );
}
} else if ( object.isLine ) {
var lineWidth = material.linewidth;
if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
state.setLineWidth( lineWidth * getTargetPixelRatio() );
if ( object.isLineSegments ) {
renderer.setMode( 1 );
} else if ( object.isLineLoop ) {
renderer.setMode( 2 );
} else {
renderer.setMode( 3 );
}
} else if ( object.isPoints ) {
renderer.setMode( 0 );
} else if ( object.isSprite ) {
renderer.setMode( 4 );
}
if ( object.isInstancedMesh ) {
renderer.renderInstances( geometry, drawStart, drawCount, object.count );
} else if ( geometry.isInstancedBufferGeometry ) {
renderer.renderInstances( geometry, drawStart, drawCount, geometry.maxInstancedCount );
} else {
renderer.render( drawStart, drawCount );
}
};
function setupVertexAttributes( object, geometry, material, program ) {
if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
}
state.initAttributes();
var geometryAttributes = geometry.attributes;
var programAttributes = program.getAttributes();
var materialDefaultAttributeValues = material.defaultAttributeValues;
for ( var name in programAttributes ) {
var programAttribute = programAttributes[ name ];
if ( programAttribute >= 0 ) {
var geometryAttribute = geometryAttributes[ name ];
if ( geometryAttribute !== undefined ) {
var normalized = geometryAttribute.normalized;
var size = geometryAttribute.itemSize;
var attribute = attributes.get( geometryAttribute );
// TODO Attribute may not be available on context restore
if ( attribute === undefined ) continue;
var buffer = attribute.buffer;
var type = attribute.type;
var bytesPerElement = attribute.bytesPerElement;
if ( geometryAttribute.isInterleavedBufferAttribute ) {
var data = geometryAttribute.data;
var stride = data.stride;
var offset = geometryAttribute.offset;
if ( data && data.isInstancedInterleavedBuffer ) {
state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
if ( geometry.maxInstancedCount === undefined ) {
geometry.maxInstancedCount = data.meshPerAttribute * data.count;
}
} else {
state.enableAttribute( programAttribute );
}
_gl.bindBuffer( 34962, buffer );
state.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
} else {
if ( geometryAttribute.isInstancedBufferAttribute ) {
state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
if ( geometry.maxInstancedCount === undefined ) {
geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
}
} else {
state.enableAttribute( programAttribute );
}
_gl.bindBuffer( 34962, buffer );
state.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
}
} else if ( name === 'instanceMatrix' ) {
var attribute = attributes.get( object.instanceMatrix );
// TODO Attribute may not be available on context restore
if ( attribute === undefined ) continue;
var buffer = attribute.buffer;
var type = attribute.type;
state.enableAttributeAndDivisor( programAttribute + 0, 1 );
state.enableAttributeAndDivisor( programAttribute + 1, 1 );
state.enableAttributeAndDivisor( programAttribute + 2, 1 );
state.enableAttributeAndDivisor( programAttribute + 3, 1 );
_gl.bindBuffer( 34962, buffer );
_gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
_gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
_gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
_gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
} else if ( materialDefaultAttributeValues !== undefined ) {
var value = materialDefaultAttributeValues[ name ];
if ( value !== undefined ) {
switch ( value.length ) {
case 2:
_gl.vertexAttrib2fv( programAttribute, value );
break;
case 3:
_gl.vertexAttrib3fv( programAttribute, value );
break;
case 4:
_gl.vertexAttrib4fv( programAttribute, value );
break;
default:
_gl.vertexAttrib1fv( programAttribute, value );
}
}
}
}
}
state.disableUnusedAttributes();
}
// Compile
this.compile = function ( scene, camera ) {
currentRenderState = renderStates.get( scene, camera );
currentRenderState.init();
scene.traverse( function ( object ) {
if ( object.isLight ) {
currentRenderState.pushLight( object );
if ( object.castShadow ) {
currentRenderState.pushShadow( object );
}
}
} );
currentRenderState.setupLights( camera );
var compiled = {};
scene.traverse( function ( object ) {
if ( object.material ) {
if ( Array.isArray( object.material ) ) {
for ( var i = 0; i < object.material.length; i ++ ) {
if ( object.material[ i ].uuid in compiled === false ) {
initMaterial( object.material[ i ], scene, object );
compiled[ object.material[ i ].uuid ] = true;
}
}
} else if ( object.material.uuid in compiled === false ) {
initMaterial( object.material, scene, object );
compiled[ object.material.uuid ] = true;
}
}
} );
};
// Animation Loop
var onAnimationFrameCallback = null;
function onAnimationFrame( time ) {
if ( xr.isPresenting ) return;
if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
}
var animation = new WebGLAnimation();
animation.setAnimationLoop( onAnimationFrame );
if ( typeof window !== 'undefined' ) animation.setContext( window );
this.setAnimationLoop = function ( callback ) {
onAnimationFrameCallback = callback;
xr.setAnimationLoop( callback );
animation.start();
};
// Rendering
this.render = function ( scene, camera ) {
var renderTarget, forceClear;
if ( arguments[ 2 ] !== undefined ) {
console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
renderTarget = arguments[ 2 ];
}
if ( arguments[ 3 ] !== undefined ) {
console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
forceClear = arguments[ 3 ];
}
if ( ! ( camera && camera.isCamera ) ) {
console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
return;
}
if ( _isContextLost ) return;
// reset caching for this frame
_currentGeometryProgram.geometry = null;
_currentGeometryProgram.program = null;
_currentGeometryProgram.wireframe = false;
_currentMaterialId = - 1;
_currentCamera = null;
// update scene graph
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
// update camera matrices and frustum
if ( camera.parent === null ) camera.updateMatrixWorld();
if ( xr.enabled && xr.isPresenting ) {
camera = xr.getCamera( camera );
}
//
scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
currentRenderState = renderStates.get( scene, camera );
currentRenderState.init();
_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
_frustum.setFromProjectionMatrix( _projScreenMatrix );
_localClippingEnabled = this.localClippingEnabled;
_clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
currentRenderList = renderLists.get( scene, camera );
currentRenderList.init();
projectObject( scene, camera, 0, _this.sortObjects );
currentRenderList.finish();
if ( _this.sortObjects === true ) {
currentRenderList.sort( _opaqueSort, _transparentSort );
}
//
if ( _clippingEnabled ) _clipping.beginShadows();
var shadowsArray = currentRenderState.state.shadowsArray;
shadowMap.render( shadowsArray, scene, camera );
currentRenderState.setupLights( camera );
if ( _clippingEnabled ) _clipping.endShadows();
//
if ( this.info.autoReset ) this.info.reset();
if ( renderTarget !== undefined ) {
this.setRenderTarget( renderTarget );
}
//
background.render( currentRenderList, scene, camera, forceClear );
// render scene
var opaqueObjects = currentRenderList.opaque;
var transparentObjects = currentRenderList.transparent;
if ( scene.overrideMaterial ) {
var overrideMaterial = scene.overrideMaterial;
if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
} else {
// opaque pass (front-to-back order)
if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
// transparent pass (back-to-front order)
if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
}
//
scene.onAfterRender( _this, scene, camera );
//
if ( _currentRenderTarget !== null ) {
// Generate mipmap if we're using any kind of mipmap filtering
textures.updateRenderTargetMipmap( _currentRenderTarget );
// resolve multisample renderbuffers to a single-sample texture if necessary
textures.updateMultisampleRenderTarget( _currentRenderTarget );
}
// Ensure depth buffer writing is enabled so it can be cleared on next render
state.buffers.depth.setTest( true );
state.buffers.depth.setMask( true );
state.buffers.color.setMask( true );
state.setPolygonOffset( false );
// _gl.finish();
currentRenderList = null;
currentRenderState = null;
};
function projectObject( object, camera, groupOrder, sortObjects ) {
if ( object.visible === false ) return;
var visible = object.layers.test( camera.layers );
if ( visible ) {
if ( object.isGroup ) {
groupOrder = object.renderOrder;
} else if ( object.isLOD ) {
if ( object.autoUpdate === true ) object.update( camera );
} else if ( object.isLight ) {
currentRenderState.pushLight( object );
if ( object.castShadow ) {
currentRenderState.pushShadow( object );
}
} else if ( object.isSprite ) {
if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
if ( sortObjects ) {
_vector3.setFromMatrixPosition( object.matrixWorld )
.applyMatrix4( _projScreenMatrix );
}
var geometry = objects.update( object );
var material = object.material;
if ( material.visible ) {
currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
}
}
} else if ( object.isImmediateRenderObject ) {
if ( sortObjects ) {
_vector3.setFromMatrixPosition( object.matrixWorld )
.applyMatrix4( _projScreenMatrix );
}
currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
} else if ( object.isMesh || object.isLine || object.isPoints ) {
if ( object.isSkinnedMesh ) {
// update skeleton only once in a frame
if ( object.skeleton.frame !== info.render.frame ) {
object.skeleton.update();
object.skeleton.frame = info.render.frame;
}
}
if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
if ( sortObjects ) {
_vector3.setFromMatrixPosition( object.matrixWorld )
.applyMatrix4( _projScreenMatrix );
}
var geometry = objects.update( object );
var material = object.material;
if ( Array.isArray( material ) ) {
var groups = geometry.groups;
for ( var i = 0, l = groups.length; i < l; i ++ ) {
var group = groups[ i ];
var groupMaterial = material[ group.materialIndex ];
if ( groupMaterial && groupMaterial.visible ) {
currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
}
}
} else if ( material.visible ) {
currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
}
}
}
}
var children = object.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
projectObject( children[ i ], camera, groupOrder, sortObjects );
}
}
function renderObjects( renderList, scene, camera, overrideMaterial ) {
for ( var i = 0, l = renderList.length; i < l; i ++ ) {
var renderItem = renderList[ i ];
var object = renderItem.object;
var geometry = renderItem.geometry;
var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
var group = renderItem.group;
if ( camera.isArrayCamera ) {
_currentArrayCamera = camera;
var cameras = camera.cameras;
for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
var camera2 = cameras[ j ];
if ( object.layers.test( camera2.layers ) ) {
state.viewport( _currentViewport.copy( camera2.viewport ) );
currentRenderState.setupLights( camera2 );
renderObject( object, scene, camera2, geometry, material, group );
}
}
} else {
_currentArrayCamera = null;
renderObject( object, scene, camera, geometry, material, group );
}
}
}
function renderObject( object, scene, camera, geometry, material, group ) {
object.onBeforeRender( _this, scene, camera, geometry, material, group );
currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
if ( object.isImmediateRenderObject ) {
var program = setProgram( camera, scene, material, object );
state.setMaterial( material );
_currentGeometryProgram.geometry = null;
_currentGeometryProgram.program = null;
_currentGeometryProgram.wireframe = false;
renderObjectImmediate( object, program );
} else {
_this.renderBufferDirect( camera, scene, geometry, material, object, group );
}
object.onAfterRender( _this, scene, camera, geometry, material, group );
currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
}
function initMaterial( material, scene, object ) {
var materialProperties = properties.get( material );
var lights = currentRenderState.state.lights;
var shadowsArray = currentRenderState.state.shadowsArray;
var lightsStateVersion = lights.state.version;
var parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object );
var programCacheKey = programCache.getProgramCacheKey( parameters );
var program = materialProperties.program;
var programChange = true;
if ( program === undefined ) {
// new material
material.addEventListener( 'dispose', onMaterialDispose );
} else if ( program.cacheKey !== programCacheKey ) {
// changed glsl or parameters
releaseMaterialProgramReference( material );
} else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
materialProperties.lightsStateVersion = lightsStateVersion;
programChange = false;
} else if ( parameters.shaderID !== undefined ) {
// same glsl and uniform list
return;
} else {
// only rebuild uniform list
programChange = false;
}
if ( programChange ) {
program = programCache.acquireProgram( parameters, programCacheKey );
materialProperties.program = program;
materialProperties.uniforms = parameters.uniforms;
materialProperties.outputEncoding = parameters.outputEncoding;
material.program = program;
}
var programAttributes = program.getAttributes();
if ( material.morphTargets ) {
material.numSupportedMorphTargets = 0;
for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
material.numSupportedMorphTargets ++;
}
}
}
if ( material.morphNormals ) {
material.numSupportedMorphNormals = 0;
for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
material.numSupportedMorphNormals ++;
}
}
}
var uniforms = materialProperties.uniforms;
if ( ! material.isShaderMaterial &&
! material.isRawShaderMaterial ||
material.clipping === true ) {
materialProperties.numClippingPlanes = _clipping.numPlanes;
materialProperties.numIntersection = _clipping.numIntersection;
uniforms.clippingPlanes = _clipping.uniform;
}
materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
materialProperties.fog = scene.fog;
// store the light setup it was created for
materialProperties.needsLights = materialNeedsLights( material );
materialProperties.lightsStateVersion = lightsStateVersion;
if ( materialProperties.needsLights ) {
// wire up the material to this renderer's lighting state
uniforms.ambientLightColor.value = lights.state.ambient;
uniforms.lightProbe.value = lights.state.probe;
uniforms.directionalLights.value = lights.state.directional;
uniforms.directionalLightShadows.value = lights.state.directionalShadow;
uniforms.spotLights.value = lights.state.spot;
uniforms.spotLightShadows.value = lights.state.spotShadow;
uniforms.rectAreaLights.value = lights.state.rectArea;
uniforms.pointLights.value = lights.state.point;
uniforms.pointLightShadows.value = lights.state.pointShadow;
uniforms.hemisphereLights.value = lights.state.hemi;
uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
uniforms.spotShadowMap.value = lights.state.spotShadowMap;
uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
uniforms.pointShadowMap.value = lights.state.pointShadowMap;
uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
// TODO (abelnation): add area lights shadow info to uniforms
}
var progUniforms = materialProperties.program.getUniforms(),
uniformsList =
WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
materialProperties.uniformsList = uniformsList;
}
function setProgram( camera, scene, material, object ) {
textures.resetTextureUnits();
var fog = scene.fog;
var environment = material.isMeshStandardMaterial ? scene.environment : null;
var encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
var materialProperties = properties.get( material );
var lights = currentRenderState.state.lights;
if ( _clippingEnabled ) {
if ( _localClippingEnabled || camera !== _currentCamera ) {
var useCache =
camera === _currentCamera &&
material.id === _currentMaterialId;
// we might want to call this function with some ClippingGroup
// object instead of the material, once it becomes feasible
// (#8465, #8379)
_clipping.setState(
material.clippingPlanes, material.clipIntersection, material.clipShadows,
camera, materialProperties, useCache );
}
}
if ( material.version === materialProperties.__version ) {
if ( materialProperties.program === undefined ) {
initMaterial( material, scene, object );
} else if ( material.fog && materialProperties.fog !== fog ) {
initMaterial( material, scene, object );
} else if ( materialProperties.environment !== environment ) {
initMaterial( material, scene, object );
} else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
initMaterial( material, scene, object );
} else if ( materialProperties.numClippingPlanes !== undefined &&
( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
materialProperties.numIntersection !== _clipping.numIntersection ) ) {
initMaterial( material, scene, object );
} else if ( materialProperties.outputEncoding !== encoding ) {
initMaterial( material, scene, object );
}
} else {
initMaterial( material, scene, object );
materialProperties.__version = material.version;
}
var refreshProgram = false;
var refreshMaterial = false;
var refreshLights = false;
var program = materialProperties.program,
p_uniforms = program.getUniforms(),
m_uniforms = materialProperties.uniforms;
if ( state.useProgram( program.program ) ) {
refreshProgram = true;
refreshMaterial = true;
refreshLights = true;
}
if ( material.id !== _currentMaterialId ) {
_currentMaterialId = material.id;
refreshMaterial = true;
}
if ( refreshProgram || _currentCamera !== camera ) {
p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
if ( capabilities.logarithmicDepthBuffer ) {
p_uniforms.setValue( _gl, 'logDepthBufFC',
2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
}
if ( _currentCamera !== camera ) {
_currentCamera = camera;
// lighting uniforms depend on the camera so enforce an update
// now, in case this material supports lights - or later, when
// the next material that does gets activated:
refreshMaterial = true; // set to true on material change
refreshLights = true; // remains set until update done
}
// load material specific uniforms
// (shader material also gets them for the sake of genericity)
if ( material.isShaderMaterial ||
material.isMeshPhongMaterial ||
material.isMeshToonMaterial ||
material.isMeshStandardMaterial ||
material.envMap ) {
var uCamPos = p_uniforms.map.cameraPosition;
if ( uCamPos !== undefined ) {
uCamPos.setValue( _gl,
_vector3.setFromMatrixPosition( camera.matrixWorld ) );
}
}
if ( material.isMeshPhongMaterial ||
material.isMeshToonMaterial ||
material.isMeshLambertMaterial ||
material.isMeshBasicMaterial ||
material.isMeshStandardMaterial ||
material.isShaderMaterial ) {
p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
}
if ( material.isMeshPhongMaterial ||
material.isMeshToonMaterial ||
material.isMeshLambertMaterial ||
material.isMeshBasicMaterial ||
material.isMeshStandardMaterial ||
material.isShaderMaterial ||
material.skinning ) {
p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
}
}
// skinning uniforms must be set even if material didn't change
// auto-setting of texture unit for bone texture must go before other textures
// otherwise textures used for skinning can take over texture units reserved for other material textures
if ( material.skinning ) {
p_uniforms.setOptional( _gl, object, 'bindMatrix' );
p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
var skeleton = object.skeleton;
if ( skeleton ) {
var bones = skeleton.bones;
if ( capabilities.floatVertexTextures ) {
if ( skeleton.boneTexture === undefined ) {
// layout (1 matrix = 4 pixels)
// RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
// with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
// 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
// 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
// 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
size = MathUtils.ceilPowerOfTwo( size );
size = Math.max( size, 4 );
var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
boneMatrices.set( skeleton.boneMatrices ); // copy current values
var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
skeleton.boneMatrices = boneMatrices;
skeleton.boneTexture = boneTexture;
skeleton.boneTextureSize = size;
}
p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
} else {
p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
}
}
}
if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
materialProperties.receiveShadow = object.receiveShadow;
p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
}
if ( refreshMaterial ) {
p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
if ( materialProperties.needsLights ) {
// the current material requires lighting info
// note: all lighting uniforms are always set correctly
// they simply reference the renderer's state for their
// values
//
// use the current material's .needsUpdate flags to set
// the GL state when required
markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
}
// refresh uniforms common to several materials
if ( fog && material.fog ) {
refreshUniformsFog( m_uniforms, fog );
}
if ( material.isMeshBasicMaterial ) {
refreshUniformsCommon( m_uniforms, material );
} else if ( material.isMeshLambertMaterial ) {
refreshUniformsCommon( m_uniforms, material );
refreshUniformsLambert( m_uniforms, material );
} else if ( material.isMeshToonMaterial ) {
refreshUniformsCommon( m_uniforms, material );
refreshUniformsToon( m_uniforms, material );
} else if ( material.isMeshPhongMaterial ) {
refreshUniformsCommon( m_uniforms, material );
refreshUniformsPhong( m_uniforms, material );
} else if ( material.isMeshStandardMaterial ) {
refreshUniformsCommon( m_uniforms, material, environment );
if ( material.isMeshPhysicalMaterial ) {
refreshUniformsPhysical( m_uniforms, material, environment );
} else {
refreshUniformsStandard( m_uniforms, material, environment );
}
} else if ( material.isMeshMatcapMaterial ) {
refreshUniformsCommon( m_uniforms, material );
refreshUniformsMatcap( m_uniforms, material );
} else if ( material.isMeshDepthMaterial ) {
refreshUniformsCommon( m_uniforms, material );
refreshUniformsDepth( m_uniforms, material );
} else if ( material.isMeshDistanceMaterial ) {
refreshUniformsCommon( m_uniforms, material );
refreshUniformsDistance( m_uniforms, material );
} else if ( material.isMeshNormalMaterial ) {
refreshUniformsCommon( m_uniforms, material );
refreshUniformsNormal( m_uniforms, material );
} else if ( material.isLineBasicMaterial ) {
refreshUniformsLine( m_uniforms, material );
if ( material.isLineDashedMaterial ) {
refreshUniformsDash( m_uniforms, material );
}
} else if ( material.isPointsMaterial ) {
refreshUniformsPoints( m_uniforms, material );
} else if ( material.isSpriteMaterial ) {
refreshUniformsSprites( m_uniforms, material );
} else if ( material.isShadowMaterial ) {
m_uniforms.color.value.copy( material.color );
m_uniforms.opacity.value = material.opacity;
}
// RectAreaLight Texture
// TODO (mrdoob): Find a nicer implementation
if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
if ( material.isShaderMaterial ) {
material.uniformsNeedUpdate = false; // #15581
}
}
if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
material.uniformsNeedUpdate = false;
}
if ( material.isSpriteMaterial ) {
p_uniforms.setValue( _gl, 'center', object.center );
}
// common matrices
p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
return program;
}
// Uniforms (refresh uniforms objects)
function refreshUniformsCommon( uniforms, material, environment ) {
uniforms.opacity.value = material.opacity;
if ( material.color ) {
uniforms.diffuse.value.copy( material.color );
}
if ( material.emissive ) {
uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
}
if ( material.map ) {
uniforms.map.value = material.map;
}
if ( material.alphaMap ) {
uniforms.alphaMap.value = material.alphaMap;
}
if ( material.specularMap ) {
uniforms.specularMap.value = material.specularMap;
}
var envMap = material.envMap || environment;
if ( envMap ) {
uniforms.envMap.value = envMap;
uniforms.flipEnvMap.value = envMap.isCubeTexture ? - 1 : 1;
uniforms.reflectivity.value = material.reflectivity;
uniforms.refractionRatio.value = material.refractionRatio;
uniforms.maxMipLevel.value = properties.get( envMap ).__maxMipLevel;
}
if ( material.lightMap ) {
uniforms.lightMap.value = material.lightMap;
uniforms.lightMapIntensity.value = material.lightMapIntensity;
}
if ( material.aoMap ) {
uniforms.aoMap.value = material.aoMap;
uniforms.aoMapIntensity.value = material.aoMapIntensity;
}
// uv repeat and offset setting priorities
// 1. color map
// 2. specular map
// 3. normal map
// 4. bump map
// 5. alpha map
// 6. emissive map
var uvScaleMap;
if ( material.map ) {
uvScaleMap = material.map;
} else if ( material.specularMap ) {
uvScaleMap = material.specularMap;
} else if ( material.displacementMap ) {
uvScaleMap = material.displacementMap;
} else if ( material.normalMap ) {
uvScaleMap = material.normalMap;
} else if ( material.bumpMap ) {
uvScaleMap = material.bumpMap;
} else if ( material.roughnessMap ) {
uvScaleMap = material.roughnessMap;
} else if ( material.metalnessMap ) {
uvScaleMap = material.metalnessMap;
} else if ( material.alphaMap ) {
uvScaleMap = material.alphaMap;
} else if ( material.emissiveMap ) {
uvScaleMap = material.emissiveMap;
}
if ( uvScaleMap !== undefined ) {
// backwards compatibility
if ( uvScaleMap.isWebGLRenderTarget ) {
uvScaleMap = uvScaleMap.texture;
}
if ( uvScaleMap.matrixAutoUpdate === true ) {
uvScaleMap.updateMatrix();
}
uniforms.uvTransform.value.copy( uvScaleMap.matrix );
}
// uv repeat and offset setting priorities for uv2
// 1. ao map
// 2. light map
var uv2ScaleMap;
if ( material.aoMap ) {
uv2ScaleMap = material.aoMap;
} else if ( material.lightMap ) {
uv2ScaleMap = material.lightMap;
}
if ( uv2ScaleMap !== undefined ) {
// backwards compatibility
if ( uv2ScaleMap.isWebGLRenderTarget ) {
uv2ScaleMap = uv2ScaleMap.texture;
}
if ( uv2ScaleMap.matrixAutoUpdate === true ) {
uv2ScaleMap.updateMatrix();
}
uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
}
}
function refreshUniformsLine( uniforms, material ) {
uniforms.diffuse.value.copy( material.color );
uniforms.opacity.value = material.opacity;
}
function refreshUniformsDash( uniforms, material ) {
uniforms.dashSize.value = material.dashSize;
uniforms.totalSize.value = material.dashSize + material.gapSize;
uniforms.scale.value = material.scale;
}
function refreshUniformsPoints( uniforms, material ) {
uniforms.diffuse.value.copy( material.color );
uniforms.opacity.value = material.opacity;
uniforms.size.value = material.size * _pixelRatio;
uniforms.scale.value = _height * 0.5;
if ( material.map ) {
uniforms.map.value = material.map;
}
if ( material.alphaMap ) {
uniforms.alphaMap.value = material.alphaMap;
}
// uv repeat and offset setting priorities
// 1. color map
// 2. alpha map
var uvScaleMap;
if ( material.map ) {
uvScaleMap = material.map;
} else if ( material.alphaMap ) {
uvScaleMap = material.alphaMap;
}
if ( uvScaleMap !== undefined ) {
if ( uvScaleMap.matrixAutoUpdate === true ) {
uvScaleMap.updateMatrix();
}
uniforms.uvTransform.value.copy( uvScaleMap.matrix );
}
}
function refreshUniformsSprites( uniforms, material ) {
uniforms.diffuse.value.copy( material.color );
uniforms.opacity.value = material.opacity;
uniforms.rotation.value = material.rotation;
if ( material.map ) {
uniforms.map.value = material.map;
}
if ( material.alphaMap ) {
uniforms.alphaMap.value = material.alphaMap;
}
// uv repeat and offset setting priorities
// 1. color map
// 2. alpha map
var uvScaleMap;
if ( material.map ) {
uvScaleMap = material.map;
} else if ( material.alphaMap ) {
uvScaleMap = material.alphaMap;
}
if ( uvScaleMap !== undefined ) {
if ( uvScaleMap.matrixAutoUpdate === true ) {
uvScaleMap.updateMatrix();
}
uniforms.uvTransform.value.copy( uvScaleMap.matrix );
}
}
function refreshUniformsFog( uniforms, fog ) {
uniforms.fogColor.value.copy( fog.color );
if ( fog.isFog ) {
uniforms.fogNear.value = fog.near;
uniforms.fogFar.value = fog.far;
} else if ( fog.isFogExp2 ) {
uniforms.fogDensity.value = fog.density;
}
}
function refreshUniformsLambert( uniforms, material ) {
if ( material.emissiveMap ) {
uniforms.emissiveMap.value = material.emissiveMap;
}
}
function refreshUniformsPhong( uniforms, material ) {
uniforms.specular.value.copy( material.specular );
uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
if ( material.emissiveMap ) {
uniforms.emissiveMap.value = material.emissiveMap;
}
if ( material.bumpMap ) {
uniforms.bumpMap.value = material.bumpMap;
uniforms.bumpScale.value = material.bumpScale;
if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
}
if ( material.normalMap ) {
uniforms.normalMap.value = material.normalMap;
uniforms.normalScale.value.copy( material.normalScale );
if ( material.side === BackSide ) uniforms.normalScale.value.negate();
}
if ( material.displacementMap ) {
uniforms.displacementMap.value = material.displacementMap;
uniforms.displacementScale.value = material.displacementScale;
uniforms.displacementBias.value = material.displacementBias;
}
}
function refreshUniformsToon( uniforms, material ) {
uniforms.specular.value.copy( material.specular );
uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
if ( material.gradientMap ) {
uniforms.gradientMap.value = material.gradientMap;
}
if ( material.emissiveMap ) {
uniforms.emissiveMap.value = material.emissiveMap;
}
if ( material.bumpMap ) {
uniforms.bumpMap.value = material.bumpMap;
uniforms.bumpScale.value = material.bumpScale;
if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
}
if ( material.normalMap ) {
uniforms.normalMap.value = material.normalMap;
uniforms.normalScale.value.copy( material.normalScale );
if ( material.side === BackSide ) uniforms.normalScale.value.negate();
}
if ( material.displacementMap ) {
uniforms.displacementMap.value = material.displacementMap;
uniforms.displacementScale.value = material.displacementScale;
uniforms.displacementBias.value = material.displacementBias;
}
}
function refreshUniformsStandard( uniforms, material, environment ) {
uniforms.roughness.value = material.roughness;
uniforms.metalness.value = material.metalness;
if ( material.roughnessMap ) {
uniforms.roughnessMap.value = material.roughnessMap;
}
if ( material.metalnessMap ) {
uniforms.metalnessMap.value = material.metalnessMap;
}
if ( material.emissiveMap ) {
uniforms.emissiveMap.value = material.emissiveMap;
}
if ( material.bumpMap ) {
uniforms.bumpMap.value = material.bumpMap;
uniforms.bumpScale.value = material.bumpScale;
if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
}
if ( material.normalMap ) {
uniforms.normalMap.value = material.normalMap;
uniforms.normalScale.value.copy( material.normalScale );
if ( material.side === BackSide ) uniforms.normalScale.value.negate();
}
if ( material.displacementMap ) {
uniforms.displacementMap.value = material.displacementMap;
uniforms.displacementScale.value = material.displacementScale;
uniforms.displacementBias.value = material.displacementBias;
}
if ( material.envMap || environment ) {
//uniforms.envMap.value = material.envMap; // part of uniforms common
uniforms.envMapIntensity.value = material.envMapIntensity;
}
}
function refreshUniformsPhysical( uniforms, material, environment ) {
refreshUniformsStandard( uniforms, material, environment );
uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
uniforms.clearcoat.value = material.clearcoat;
uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
if ( material.clearcoatMap ) {
uniforms.clearcoatMap.value = material.clearcoatMap;
}
if ( material.clearcoatRoughnessMap ) {
uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
}
if ( material.clearcoatNormalMap ) {
uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
if ( material.side === BackSide ) {
uniforms.clearcoatNormalScale.value.negate();
}
}
uniforms.transparency.value = material.transparency;
}
function refreshUniformsMatcap( uniforms, material ) {
if ( material.matcap ) {
uniforms.matcap.value = material.matcap;
}
if ( material.bumpMap ) {
uniforms.bumpMap.value = material.bumpMap;
uniforms.bumpScale.value = material.bumpScale;
if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
}
if ( material.normalMap ) {
uniforms.normalMap.value = material.normalMap;
uniforms.normalScale.value.copy( material.normalScale );
if ( material.side === BackSide ) uniforms.normalScale.value.negate();
}
if ( material.displacementMap ) {
uniforms.displacementMap.value = material.displacementMap;
uniforms.displacementScale.value = material.displacementScale;
uniforms.displacementBias.value = material.displacementBias;
}
}
function refreshUniformsDepth( uniforms, material ) {
if ( material.displacementMap ) {
uniforms.displacementMap.value = material.displacementMap;
uniforms.displacementScale.value = material.displacementScale;
uniforms.displacementBias.value = material.displacementBias;
}
}
function refreshUniformsDistance( uniforms, material ) {
if ( material.displacementMap ) {
uniforms.displacementMap.value = material.displacementMap;
uniforms.displacementScale.value = material.displacementScale;
uniforms.displacementBias.value = material.displacementBias;
}
uniforms.referencePosition.value.copy( material.referencePosition );
uniforms.nearDistance.value = material.nearDistance;
uniforms.farDistance.value = material.farDistance;
}
function refreshUniformsNormal( uniforms, material ) {
if ( material.bumpMap ) {
uniforms.bumpMap.value = material.bumpMap;
uniforms.bumpScale.value = material.bumpScale;
if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
}
if ( material.normalMap ) {
uniforms.normalMap.value = material.normalMap;
uniforms.normalScale.value.copy( material.normalScale );
if ( material.side === BackSide ) uniforms.normalScale.value.negate();
}
if ( material.displacementMap ) {
uniforms.displacementMap.value = material.displacementMap;
uniforms.displacementScale.value = material.displacementScale;
uniforms.displacementBias.value = material.displacementBias;
}
}
// If uniforms are marked as clean, they don't need to be loaded to the GPU.
function markUniformsLightsNeedsUpdate( uniforms, value ) {
uniforms.ambientLightColor.needsUpdate = value;
uniforms.lightProbe.needsUpdate = value;
uniforms.directionalLights.needsUpdate = value;
uniforms.directionalLightShadows.needsUpdate = value;
uniforms.pointLights.needsUpdate = value;
uniforms.pointLightShadows.needsUpdate = value;
uniforms.spotLights.needsUpdate = value;
uniforms.spotLightShadows.needsUpdate = value;
uniforms.rectAreaLights.needsUpdate = value;
uniforms.hemisphereLights.needsUpdate = value;
}
function materialNeedsLights( material ) {
return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
material.isMeshStandardMaterial || material.isShadowMaterial ||
( material.isShaderMaterial && material.lights === true );
}
//
this.setFramebuffer = function ( value ) {
if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( 36160, value );
_framebuffer = value;
};
this.getActiveCubeFace = function () {
return _currentActiveCubeFace;
};
this.getActiveMipmapLevel = function () {
return _currentActiveMipmapLevel;
};
this.getRenderTarget = function () {
return _currentRenderTarget;
};
this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) {
_currentRenderTarget = renderTarget;
_currentActiveCubeFace = activeCubeFace;
_currentActiveMipmapLevel = activeMipmapLevel;
if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
textures.setupRenderTarget( renderTarget );
}
var framebuffer = _framebuffer;
var isCube = false;
if ( renderTarget ) {
var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
if ( renderTarget.isWebGLCubeRenderTarget ) {
framebuffer = __webglFramebuffer[ activeCubeFace || 0 ];
isCube = true;
} else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
} else {
framebuffer = __webglFramebuffer;
}
_currentViewport.copy( renderTarget.viewport );
_currentScissor.copy( renderTarget.scissor );
_currentScissorTest = renderTarget.scissorTest;
} else {
_currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
_currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
_currentScissorTest = _scissorTest;
}
if ( _currentFramebuffer !== framebuffer ) {
_gl.bindFramebuffer( 36160, framebuffer );
_currentFramebuffer = framebuffer;
}
state.viewport( _currentViewport );
state.scissor( _currentScissor );
state.setScissorTest( _currentScissorTest );
if ( isCube ) {
var textureProperties = properties.get( renderTarget.texture );
_gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 );
}
};
this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
return;
}
var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
framebuffer = framebuffer[ activeCubeFaceIndex ];
}
if ( framebuffer ) {
var restore = false;
if ( framebuffer !== _currentFramebuffer ) {
_gl.bindFramebuffer( 36160, framebuffer );
restore = true;
}
try {
var texture = renderTarget.texture;
var textureFormat = texture.format;
var textureType = texture.type;
if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
return;
}
if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
return;
}
if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
// the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
_gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
}
} else {
console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
}
} finally {
if ( restore ) {
_gl.bindFramebuffer( 36160, _currentFramebuffer );
}
}
}
};
this.copyFramebufferToTexture = function ( position, texture, level ) {
if ( level === undefined ) level = 0;
var levelScale = Math.pow( 2, - level );
var width = Math.floor( texture.image.width * levelScale );
var height = Math.floor( texture.image.height * levelScale );
var glFormat = utils.convert( texture.format );
textures.setTexture2D( texture, 0 );
_gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
state.unbindTexture();
};
this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
if ( level === undefined ) level = 0;
var width = srcTexture.image.width;
var height = srcTexture.image.height;
var glFormat = utils.convert( dstTexture.format );
var glType = utils.convert( dstTexture.type );
textures.setTexture2D( dstTexture, 0 );
if ( srcTexture.isDataTexture ) {
_gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
} else {
if ( srcTexture.isCompressedTexture ) {
_gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
} else {
_gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
}
}
// Generate mipmaps only when copying level 0
if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
state.unbindTexture();
};
this.initTexture = function ( texture ) {
textures.setTexture2D( texture, 0 );
state.unbindTexture();
};
if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
}
}
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
function FogExp2( color, density ) {
this.name = '';
this.color = new Color( color );
this.density = ( density !== undefined ) ? density : 0.00025;
}
Object.assign( FogExp2.prototype, {
isFogExp2: true,
clone: function () {
return new FogExp2( this.color, this.density );
},
toJSON: function ( /* meta */ ) {
return {
type: 'FogExp2',
color: this.color.getHex(),
density: this.density
};
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
function Fog( color, near, far ) {
this.name = '';
this.color = new Color( color );
this.near = ( near !== undefined ) ? near : 1;
this.far = ( far !== undefined ) ? far : 1000;
}
Object.assign( Fog.prototype, {
isFog: true,
clone: function () {
return new Fog( this.color, this.near, this.far );
},
toJSON: function ( /* meta */ ) {
return {
type: 'Fog',
color: this.color.getHex(),
near: this.near,
far: this.far
};
}
} );
/**
* @author benaadams / https://twitter.com/ben_a_adams
*/
function InterleavedBuffer( array, stride ) {
this.array = array;
this.stride = stride;
this.count = array !== undefined ? array.length / stride : 0;
this.usage = StaticDrawUsage;
this.updateRange = { offset: 0, count: - 1 };
this.version = 0;
}
Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
set: function ( value ) {
if ( value === true ) this.version ++;
}
} );
Object.assign( InterleavedBuffer.prototype, {
isInterleavedBuffer: true,
onUploadCallback: function () {},
setUsage: function ( value ) {
this.usage = value;
return this;
},
copy: function ( source ) {
this.array = new source.array.constructor( source.array );
this.count = source.count;
this.stride = source.stride;
this.usage = source.usage;
return this;
},
copyAt: function ( index1, attribute, index2 ) {
index1 *= this.stride;
index2 *= attribute.stride;
for ( var i = 0, l = this.stride; i < l; i ++ ) {
this.array[ index1 + i ] = attribute.array[ index2 + i ];
}
return this;
},
set: function ( value, offset ) {
if ( offset === undefined ) offset = 0;
this.array.set( value, offset );
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
onUpload: function ( callback ) {
this.onUploadCallback = callback;
return this;
}
} );
/**
* @author benaadams / https://twitter.com/ben_a_adams
*/
var _vector$6 = new Vector3();
function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
this.data = interleavedBuffer;
this.itemSize = itemSize;
this.offset = offset;
this.normalized = normalized === true;
}
Object.defineProperties( InterleavedBufferAttribute.prototype, {
count: {
get: function () {
return this.data.count;
}
},
array: {
get: function () {
return this.data.array;
}
}
} );
Object.assign( InterleavedBufferAttribute.prototype, {
isInterleavedBufferAttribute: true,
applyMatrix4: function ( m ) {
for ( var i = 0, l = this.data.count; i < l; i ++ ) {
_vector$6.x = this.getX( i );
_vector$6.y = this.getY( i );
_vector$6.z = this.getZ( i );
_vector$6.applyMatrix4( m );
this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
}
return this;
},
setX: function ( index, x ) {
this.data.array[ index * this.data.stride + this.offset ] = x;
return this;
},
setY: function ( index, y ) {
this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
return this;
},
setZ: function ( index, z ) {
this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
return this;
},
setW: function ( index, w ) {
this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
return this;
},
getX: function ( index ) {
return this.data.array[ index * this.data.stride + this.offset ];
},
getY: function ( index ) {
return this.data.array[ index * this.data.stride + this.offset + 1 ];
},
getZ: function ( index ) {
return this.data.array[ index * this.data.stride + this.offset + 2 ];
},
getW: function ( index ) {
return this.data.array[ index * this.data.stride + this.offset + 3 ];
},
setXY: function ( index, x, y ) {
index = index * this.data.stride + this.offset;
this.data.array[ index + 0 ] = x;
this.data.array[ index + 1 ] = y;
return this;
},
setXYZ: function ( index, x, y, z ) {
index = index * this.data.stride + this.offset;
this.data.array[ index + 0 ] = x;
this.data.array[ index + 1 ] = y;
this.data.array[ index + 2 ] = z;
return this;
},
setXYZW: function ( index, x, y, z, w ) {
index = index * this.data.stride + this.offset;
this.data.array[ index + 0 ] = x;
this.data.array[ index + 1 ] = y;
this.data.array[ index + 2 ] = z;
this.data.array[ index + 3 ] = w;
return this;
}
} );
/**
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* map: new THREE.Texture( <Image> ),
* alphaMap: new THREE.Texture( <Image> ),
* rotation: <float>,
* sizeAttenuation: <bool>
* }
*/
function SpriteMaterial( parameters ) {
Material.call( this );
this.type = 'SpriteMaterial';
this.color = new Color( 0xffffff );
this.map = null;
this.alphaMap = null;
this.rotation = 0;
this.sizeAttenuation = true;
this.transparent = true;
this.setValues( parameters );
}
SpriteMaterial.prototype = Object.create( Material.prototype );
SpriteMaterial.prototype.constructor = SpriteMaterial;
SpriteMaterial.prototype.isSpriteMaterial = true;
SpriteMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.color.copy( source.color );
this.map = source.map;
this.alphaMap = source.alphaMap;
this.rotation = source.rotation;
this.sizeAttenuation = source.sizeAttenuation;
return this;
};
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
*/
var _geometry;
var _intersectPoint = new Vector3();
var _worldScale = new Vector3();
var _mvPosition = new Vector3();
var _alignedPosition = new Vector2();
var _rotatedPosition = new Vector2();
var _viewWorldMatrix = new Matrix4();
var _vA$1 = new Vector3();
var _vB$1 = new Vector3();
var _vC$1 = new Vector3();
var _uvA$1 = new Vector2();
var _uvB$1 = new Vector2();
var _uvC$1 = new Vector2();
function Sprite( material ) {
Object3D.call( this );
this.type = 'Sprite';
if ( _geometry === undefined ) {
_geometry = new BufferGeometry();
var float32Array = new Float32Array( [
- 0.5, - 0.5, 0, 0, 0,
0.5, - 0.5, 0, 1, 0,
0.5, 0.5, 0, 1, 1,
- 0.5, 0.5, 0, 0, 1
] );
var interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
_geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
_geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
_geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
}
this.geometry = _geometry;
this.material = ( material !== undefined ) ? material : new SpriteMaterial();
this.center = new Vector2( 0.5, 0.5 );
}
Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Sprite,
isSprite: true,
raycast: function ( raycaster, intersects ) {
if ( raycaster.camera === null ) {
console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
}
_worldScale.setFromMatrixScale( this.matrixWorld );
_viewWorldMatrix.copy( raycaster.camera.matrixWorld );
this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
_mvPosition.setFromMatrixPosition( this.modelViewMatrix );
if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
_worldScale.multiplyScalar( - _mvPosition.z );
}
var rotation = this.material.rotation;
var sin, cos;
if ( rotation !== 0 ) {
cos = Math.cos( rotation );
sin = Math.sin( rotation );
}
var center = this.center;
transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
_uvA$1.set( 0, 0 );
_uvB$1.set( 1, 0 );
_uvC$1.set( 1, 1 );
// check first triangle
var intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
if ( intersect === null ) {
// check second triangle
transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
_uvB$1.set( 0, 1 );
intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
if ( intersect === null ) {
return;
}
}
var distance = raycaster.ray.origin.distanceTo( _intersectPoint );
if ( distance < raycaster.near || distance > raycaster.far ) return;
intersects.push( {
distance: distance,
point: _intersectPoint.clone(),
uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ),
face: null,
object: this
} );
},
clone: function () {
return new this.constructor( this.material ).copy( this );
},
copy: function ( source ) {
Object3D.prototype.copy.call( this, source );
if ( source.center !== undefined ) this.center.copy( source.center );
return this;
}
} );
function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
// compute position in camera space
_alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
// to check if rotation is not zero
if ( sin !== undefined ) {
_rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
_rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
} else {
_rotatedPosition.copy( _alignedPosition );
}
vertexPosition.copy( mvPosition );
vertexPosition.x += _rotatedPosition.x;
vertexPosition.y += _rotatedPosition.y;
// transform to world space
vertexPosition.applyMatrix4( _viewWorldMatrix );
}
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
var _v1$4 = new Vector3();
var _v2$2 = new Vector3();
function LOD() {
Object3D.call( this );
this._currentLevel = 0;
this.type = 'LOD';
Object.defineProperties( this, {
levels: {
enumerable: true,
value: []
}
} );
this.autoUpdate = true;
}
LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: LOD,
isLOD: true,
copy: function ( source ) {
Object3D.prototype.copy.call( this, source, false );
var levels = source.levels;
for ( var i = 0, l = levels.length; i < l; i ++ ) {
var level = levels[ i ];
this.addLevel( level.object.clone(), level.distance );
}
this.autoUpdate = source.autoUpdate;
return this;
},
addLevel: function ( object, distance ) {
if ( distance === undefined ) distance = 0;
distance = Math.abs( distance );
var levels = this.levels;
for ( var l = 0; l < levels.length; l ++ ) {
if ( distance < levels[ l ].distance ) {
break;
}
}
levels.splice( l, 0, { distance: distance, object: object } );
this.add( object );
return this;
},
getCurrentLevel: function () {
return this._currentLevel;
},
getObjectForDistance: function ( distance ) {
var levels = this.levels;
if ( levels.length > 0 ) {
for ( var i = 1, l = levels.length; i < l; i ++ ) {
if ( distance < levels[ i ].distance ) {
break;
}
}
return levels[ i - 1 ].object;
}
return null;
},
raycast: function ( raycaster, intersects ) {
var levels = this.levels;
if ( levels.length > 0 ) {
_v1$4.setFromMatrixPosition( this.matrixWorld );
var distance = raycaster.ray.origin.distanceTo( _v1$4 );
this.getObjectForDistance( distance ).raycast( raycaster, intersects );
}
},
update: function ( camera ) {
var levels = this.levels;
if ( levels.length > 1 ) {
_v1$4.setFromMatrixPosition( camera.matrixWorld );
_v2$2.setFromMatrixPosition( this.matrixWorld );
var distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom;
levels[ 0 ].object.visible = true;
for ( var i = 1, l = levels.length; i < l; i ++ ) {
if ( distance >= levels[ i ].distance ) {
levels[ i - 1 ].object.visible = false;
levels[ i ].object.visible = true;
} else {
break;
}
}
this._currentLevel = i - 1;
for ( ; i < l; i ++ ) {
levels[ i ].object.visible = false;
}
}
},
toJSON: function ( meta ) {
var data = Object3D.prototype.toJSON.call( this, meta );
if ( this.autoUpdate === false ) data.object.autoUpdate = false;
data.object.levels = [];
var levels = this.levels;
for ( var i = 0, l = levels.length; i < l; i ++ ) {
var level = levels[ i ];
data.object.levels.push( {
object: level.object.uuid,
distance: level.distance
} );
}
return data;
}
} );
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author ikerr / http://verold.com
*/
function SkinnedMesh( geometry, material ) {
if ( geometry && geometry.isGeometry ) {
console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
}
Mesh.call( this, geometry, material );
this.type = 'SkinnedMesh';
this.bindMode = 'attached';
this.bindMatrix = new Matrix4();
this.bindMatrixInverse = new Matrix4();
}
SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
constructor: SkinnedMesh,
isSkinnedMesh: true,
bind: function ( skeleton, bindMatrix ) {
this.skeleton = skeleton;
if ( bindMatrix === undefined ) {
this.updateMatrixWorld( true );
this.skeleton.calculateInverses();
bindMatrix = this.matrixWorld;
}
this.bindMatrix.copy( bindMatrix );
this.bindMatrixInverse.getInverse( bindMatrix );
},
pose: function () {
this.skeleton.pose();
},
normalizeSkinWeights: function () {
var vector = new Vector4();
var skinWeight = this.geometry.attributes.skinWeight;
for ( var i = 0, l = skinWeight.count; i < l; i ++ ) {
vector.x = skinWeight.getX( i );
vector.y = skinWeight.getY( i );
vector.z = skinWeight.getZ( i );
vector.w = skinWeight.getW( i );
var scale = 1.0 / vector.manhattanLength();
if ( scale !== Infinity ) {
vector.multiplyScalar( scale );
} else {
vector.set( 1, 0, 0, 0 ); // do something reasonable
}
skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
}
},
updateMatrixWorld: function ( force ) {
Mesh.prototype.updateMatrixWorld.call( this, force );
if ( this.bindMode === 'attached' ) {
this.bindMatrixInverse.getInverse( this.matrixWorld );
} else if ( this.bindMode === 'detached' ) {
this.bindMatrixInverse.getInverse( this.bindMatrix );
} else {
console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
}
},
clone: function () {
return new this.constructor( this.geometry, this.material ).copy( this );
},
boneTransform: ( function () {
var basePosition = new Vector3();
var skinIndex = new Vector4();
var skinWeight = new Vector4();
var vector = new Vector3();
var matrix = new Matrix4();
return function ( index, target ) {
var skeleton = this.skeleton;
var geometry = this.geometry;
skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
target.set( 0, 0, 0 );
for ( var i = 0; i < 4; i ++ ) {
var weight = skinWeight.getComponent( i );
if ( weight !== 0 ) {
var boneIndex = skinIndex.getComponent( i );
matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
target.addScaledVector( vector.copy( basePosition ).applyMatrix4( matrix ), weight );
}
}
return target.applyMatrix4( this.bindMatrixInverse );
};
}() )
} );
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author michael guerrero / http://realitymeltdown.com
* @author ikerr / http://verold.com
*/
var _offsetMatrix = new Matrix4();
var _identityMatrix = new Matrix4();
function Skeleton( bones, boneInverses ) {
// copy the bone array
bones = bones || [];
this.bones = bones.slice( 0 );
this.boneMatrices = new Float32Array( this.bones.length * 16 );
this.frame = - 1;
// use the supplied bone inverses or calculate the inverses
if ( boneInverses === undefined ) {
this.calculateInverses();
} else {
if ( this.bones.length === boneInverses.length ) {
this.boneInverses = boneInverses.slice( 0 );
} else {
console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
this.boneInverses = [];
for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
this.boneInverses.push( new Matrix4() );
}
}
}
}
Object.assign( Skeleton.prototype, {
calculateInverses: function () {
this.boneInverses = [];
for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
var inverse = new Matrix4();
if ( this.bones[ i ] ) {
inverse.getInverse( this.bones[ i ].matrixWorld );
}
this.boneInverses.push( inverse );
}
},
pose: function () {
var bone, i, il;
// recover the bind-time world matrices
for ( i = 0, il = this.bones.length; i < il; i ++ ) {
bone = this.bones[ i ];
if ( bone ) {
bone.matrixWorld.getInverse( this.boneInverses[ i ] );
}
}
// compute the local matrices, positions, rotations and scales
for ( i = 0, il = this.bones.length; i < il; i ++ ) {
bone = this.bones[ i ];
if ( bone ) {
if ( bone.parent && bone.parent.isBone ) {
bone.matrix.getInverse( bone.parent.matrixWorld );
bone.matrix.multiply( bone.matrixWorld );
} else {
bone.matrix.copy( bone.matrixWorld );
}
bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
}
}
},
update: function () {
var bones = this.bones;
var boneInverses = this.boneInverses;
var boneMatrices = this.boneMatrices;
var boneTexture = this.boneTexture;
// flatten bone matrices to array
for ( var i = 0, il = bones.length; i < il; i ++ ) {
// compute the offset between the current and the original transform
var matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
_offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
_offsetMatrix.toArray( boneMatrices, i * 16 );
}
if ( boneTexture !== undefined ) {
boneTexture.needsUpdate = true;
}
},
clone: function () {
return new Skeleton( this.bones, this.boneInverses );
},
getBoneByName: function ( name ) {
for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
var bone = this.bones[ i ];
if ( bone.name === name ) {
return bone;
}
}
return undefined;
},
dispose: function ( ) {
if ( this.boneTexture ) {
this.boneTexture.dispose();
this.boneTexture = undefined;
}
}
} );
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author ikerr / http://verold.com
*/
function Bone() {
Object3D.call( this );
this.type = 'Bone';
}
Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Bone,
isBone: true
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
var _instanceLocalMatrix = new Matrix4();
var _instanceWorldMatrix = new Matrix4();
var _instanceIntersects = [];
var _mesh = new Mesh();
function InstancedMesh( geometry, material, count ) {
Mesh.call( this, geometry, material );
this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
this.count = count;
this.frustumCulled = false;
}
InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
constructor: InstancedMesh,
isInstancedMesh: true,
getMatrixAt: function ( index, matrix ) {
matrix.fromArray( this.instanceMatrix.array, index * 16 );
},
raycast: function ( raycaster, intersects ) {
var matrixWorld = this.matrixWorld;
var raycastTimes = this.count;
_mesh.geometry = this.geometry;
_mesh.material = this.material;
if ( _mesh.material === undefined ) return;
for ( var instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
// calculate the world matrix for each instance
this.getMatrixAt( instanceId, _instanceLocalMatrix );
_instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
// the mesh represents this single instance
_mesh.matrixWorld = _instanceWorldMatrix;
_mesh.raycast( raycaster, _instanceIntersects );
// process the result of raycast
for ( var i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
var intersect = _instanceIntersects[ i ];
intersect.instanceId = instanceId;
intersect.object = this;
intersects.push( intersect );
}
_instanceIntersects.length = 0;
}
},
setMatrixAt: function ( index, matrix ) {
matrix.toArray( this.instanceMatrix.array, index * 16 );
},
updateMorphTargets: function () {
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* opacity: <float>,
*
* linewidth: <float>,
* linecap: "round",
* linejoin: "round"
* }
*/
function LineBasicMaterial( parameters ) {
Material.call( this );
this.type = 'LineBasicMaterial';
this.color = new Color( 0xffffff );
this.linewidth = 1;
this.linecap = 'round';
this.linejoin = 'round';
this.setValues( parameters );
}
LineBasicMaterial.prototype = Object.create( Material.prototype );
LineBasicMaterial.prototype.constructor = LineBasicMaterial;
LineBasicMaterial.prototype.isLineBasicMaterial = true;
LineBasicMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.color.copy( source.color );
this.linewidth = source.linewidth;
this.linecap = source.linecap;
this.linejoin = source.linejoin;
return this;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
var _start = new Vector3();
var _end = new Vector3();
var _inverseMatrix$1 = new Matrix4();
var _ray$1 = new Ray();
var _sphere$2 = new Sphere();
function Line( geometry, material, mode ) {
if ( mode === 1 ) {
console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );
}
Object3D.call( this );
this.type = 'Line';
this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
this.material = material !== undefined ? material : new LineBasicMaterial();
}
Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Line,
isLine: true,
computeLineDistances: function () {
var geometry = this.geometry;
if ( geometry.isBufferGeometry ) {
// we assume non-indexed geometry
if ( geometry.index === null ) {
var positionAttribute = geometry.attributes.position;
var lineDistances = [ 0 ];
for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) {
_start.fromBufferAttribute( positionAttribute, i - 1 );
_end.fromBufferAttribute( positionAttribute, i );
lineDistances[ i ] = lineDistances[ i - 1 ];
lineDistances[ i ] += _start.distanceTo( _end );
}
geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
} else {
console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
}
} else if ( geometry.isGeometry ) {
var vertices = geometry.vertices;
var lineDistances = geometry.lineDistances;
lineDistances[ 0 ] = 0;
for ( var i = 1, l = vertices.length; i < l; i ++ ) {
lineDistances[ i ] = lineDistances[ i - 1 ];
lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
}
}
return this;
},
raycast: function ( raycaster, intersects ) {
var geometry = this.geometry;
var matrixWorld = this.matrixWorld;
var threshold = raycaster.params.Line.threshold;
// Checking boundingSphere distance to ray
if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
_sphere$2.copy( geometry.boundingSphere );
_sphere$2.applyMatrix4( matrixWorld );
_sphere$2.radius += threshold;
if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
//
_inverseMatrix$1.getInverse( matrixWorld );
_ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
var localThresholdSq = localThreshold * localThreshold;
var vStart = new Vector3();
var vEnd = new Vector3();
var interSegment = new Vector3();
var interRay = new Vector3();
var step = ( this && this.isLineSegments ) ? 2 : 1;
if ( geometry.isBufferGeometry ) {
var index = geometry.index;
var attributes = geometry.attributes;
var positions = attributes.position.array;
if ( index !== null ) {
var indices = index.array;
for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
var a = indices[ i ];
var b = indices[ i + 1 ];
vStart.fromArray( positions, a * 3 );
vEnd.fromArray( positions, b * 3 );
var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
if ( distSq > localThresholdSq ) continue;
interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
var distance = raycaster.ray.origin.distanceTo( interRay );
if ( distance < raycaster.near || distance > raycaster.far ) continue;
intersects.push( {
distance: distance,
// What do we want? intersection point on the ray or on the segment??
// point: raycaster.ray.at( distance ),
point: interSegment.clone().applyMatrix4( this.matrixWorld ),
index: i,
face: null,
faceIndex: null,
object: this
} );
}
} else {
for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
vStart.fromArray( positions, 3 * i );
vEnd.fromArray( positions, 3 * i + 3 );
var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
if ( distSq > localThresholdSq ) continue;
interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
var distance = raycaster.ray.origin.distanceTo( interRay );
if ( distance < raycaster.near || distance > raycaster.far ) continue;
intersects.push( {
distance: distance,
// What do we want? intersection point on the ray or on the segment??
// point: raycaster.ray.at( distance ),
point: interSegment.clone().applyMatrix4( this.matrixWorld ),
index: i,
face: null,
faceIndex: null,
object: this
} );
}
}
} else if ( geometry.isGeometry ) {
var vertices = geometry.vertices;
var nbVertices = vertices.length;
for ( var i = 0; i < nbVertices - 1; i += step ) {
var distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
if ( distSq > localThresholdSq ) continue;
interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
var distance = raycaster.ray.origin.distanceTo( interRay );
if ( distance < raycaster.near || distance > raycaster.far ) continue;
intersects.push( {
distance: distance,
// What do we want? intersection point on the ray or on the segment??
// point: raycaster.ray.at( distance ),
point: interSegment.clone().applyMatrix4( this.matrixWorld ),
index: i,
face: null,
faceIndex: null,
object: this
} );
}
}
},
clone: function () {
return new this.constructor( this.geometry, this.material ).copy( this );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
var _start$1 = new Vector3();
var _end$1 = new Vector3();
function LineSegments( geometry, material ) {
Line.call( this, geometry, material );
this.type = 'LineSegments';
}
LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
constructor: LineSegments,
isLineSegments: true,
computeLineDistances: function () {
var geometry = this.geometry;
if ( geometry.isBufferGeometry ) {
// we assume non-indexed geometry
if ( geometry.index === null ) {
var positionAttribute = geometry.attributes.position;
var lineDistances = [];
for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) {
_start$1.fromBufferAttribute( positionAttribute, i );
_end$1.fromBufferAttribute( positionAttribute, i + 1 );
lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
}
geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
} else {
console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
}
} else if ( geometry.isGeometry ) {
var vertices = geometry.vertices;
var lineDistances = geometry.lineDistances;
for ( var i = 0, l = vertices.length; i < l; i += 2 ) {
_start$1.copy( vertices[ i ] );
_end$1.copy( vertices[ i + 1 ] );
lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
}
}
return this;
}
} );
/**
* @author mgreter / http://github.com/mgreter
*/
function LineLoop( geometry, material ) {
Line.call( this, geometry, material );
this.type = 'LineLoop';
}
LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
constructor: LineLoop,
isLineLoop: true,
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* opacity: <float>,
* map: new THREE.Texture( <Image> ),
* alphaMap: new THREE.Texture( <Image> ),
*
* size: <float>,
* sizeAttenuation: <bool>
*
* morphTargets: <bool>
* }
*/
function PointsMaterial( parameters ) {
Material.call( this );
this.type = 'PointsMaterial';
this.color = new Color( 0xffffff );
this.map = null;
this.alphaMap = null;
this.size = 1;
this.sizeAttenuation = true;
this.morphTargets = false;
this.setValues( parameters );
}
PointsMaterial.prototype = Object.create( Material.prototype );
PointsMaterial.prototype.constructor = PointsMaterial;
PointsMaterial.prototype.isPointsMaterial = true;
PointsMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.color.copy( source.color );
this.map = source.map;
this.alphaMap = source.alphaMap;
this.size = source.size;
this.sizeAttenuation = source.sizeAttenuation;
this.morphTargets = source.morphTargets;
return this;
};
/**
* @author alteredq / http://alteredqualia.com/
*/
var _inverseMatrix$2 = new Matrix4();
var _ray$2 = new Ray();
var _sphere$3 = new Sphere();
var _position$1 = new Vector3();
function Points( geometry, material ) {
Object3D.call( this );
this.type = 'Points';
this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
this.material = material !== undefined ? material : new PointsMaterial();
this.updateMorphTargets();
}
Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Points,
isPoints: true,
raycast: function ( raycaster, intersects ) {
var geometry = this.geometry;
var matrixWorld = this.matrixWorld;
var threshold = raycaster.params.Points.threshold;
// Checking boundingSphere distance to ray
if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
_sphere$3.copy( geometry.boundingSphere );
_sphere$3.applyMatrix4( matrixWorld );
_sphere$3.radius += threshold;
if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
//
_inverseMatrix$2.getInverse( matrixWorld );
_ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
var localThresholdSq = localThreshold * localThreshold;
if ( geometry.isBufferGeometry ) {
var index = geometry.index;
var attributes = geometry.attributes;
var positions = attributes.position.array;
if ( index !== null ) {
var indices = index.array;
for ( var i = 0, il = indices.length; i < il; i ++ ) {
var a = indices[ i ];
_position$1.fromArray( positions, a * 3 );
testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
}
} else {
for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
_position$1.fromArray( positions, i * 3 );
testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
}
}
} else {
var vertices = geometry.vertices;
for ( var i = 0, l = vertices.length; i < l; i ++ ) {
testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this );
}
}
},
updateMorphTargets: function () {
var geometry = this.geometry;
var m, ml, name;
if ( geometry.isBufferGeometry ) {
var morphAttributes = geometry.morphAttributes;
var keys = Object.keys( morphAttributes );
if ( keys.length > 0 ) {
var morphAttribute = morphAttributes[ keys[ 0 ] ];
if ( morphAttribute !== undefined ) {
this.morphTargetInfluences = [];
this.morphTargetDictionary = {};
for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
name = morphAttribute[ m ].name || String( m );
this.morphTargetInfluences.push( 0 );
this.morphTargetDictionary[ name ] = m;
}
}
}
} else {
var morphTargets = geometry.morphTargets;
if ( morphTargets !== undefined && morphTargets.length > 0 ) {
console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
}
}
},
clone: function () {
return new this.constructor( this.geometry, this.material ).copy( this );
}
} );
function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
var rayPointDistanceSq = _ray$2.distanceSqToPoint( point );
if ( rayPointDistanceSq < localThresholdSq ) {
var intersectPoint = new Vector3();
_ray$2.closestPointToPoint( point, intersectPoint );
intersectPoint.applyMatrix4( matrixWorld );
var distance = raycaster.ray.origin.distanceTo( intersectPoint );
if ( distance < raycaster.near || distance > raycaster.far ) return;
intersects.push( {
distance: distance,
distanceToRay: Math.sqrt( rayPointDistanceSq ),
point: intersectPoint,
index: index,
face: null,
object: object
} );
}
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
this.format = format !== undefined ? format : RGBFormat;
this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
this.generateMipmaps = false;
}
VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
constructor: VideoTexture,
isVideoTexture: true,
update: function () {
var video = this.image;
if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
this.needsUpdate = true;
}
}
} );
/**
* @author alteredq / http://alteredqualia.com/
*/
function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
this.image = { width: width, height: height };
this.mipmaps = mipmaps;
// no flipping for cube textures
// (also flipping doesn't work for compressed textures )
this.flipY = false;
// can't generate mipmaps for compressed textures
// mips must be embedded in DDS files
this.generateMipmaps = false;
}
CompressedTexture.prototype = Object.create( Texture.prototype );
CompressedTexture.prototype.constructor = CompressedTexture;
CompressedTexture.prototype.isCompressedTexture = true;
/**
* @author mrdoob / http://mrdoob.com/
*/
function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
this.needsUpdate = true;
}
CanvasTexture.prototype = Object.create( Texture.prototype );
CanvasTexture.prototype.constructor = CanvasTexture;
CanvasTexture.prototype.isCanvasTexture = true;
/**
* @author Matt DesLauriers / @mattdesl
* @author atix / arthursilber.de
*/
function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
format = format !== undefined ? format : DepthFormat;
if ( format !== DepthFormat && format !== DepthStencilFormat ) {
throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
}
if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
this.image = { width: width, height: height };
this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
this.flipY = false;
this.generateMipmaps = false;
}
DepthTexture.prototype = Object.create( Texture.prototype );
DepthTexture.prototype.constructor = DepthTexture;
DepthTexture.prototype.isDepthTexture = true;
/**
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / https://github.com/Mugen87
*/
function WireframeGeometry( geometry ) {
BufferGeometry.call( this );
this.type = 'WireframeGeometry';
// buffer
var vertices = [];
// helper variables
var i, j, l, o, ol;
var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
var key, keys = [ 'a', 'b', 'c' ];
var vertex;
// different logic for Geometry and BufferGeometry
if ( geometry && geometry.isGeometry ) {
// create a data structure that contains all edges without duplicates
var faces = geometry.faces;
for ( i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
for ( j = 0; j < 3; j ++ ) {
edge1 = face[ keys[ j ] ];
edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
edge[ 1 ] = Math.max( edge1, edge2 );
key = edge[ 0 ] + ',' + edge[ 1 ];
if ( edges[ key ] === undefined ) {
edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
}
}
}
// generate vertices
for ( key in edges ) {
e = edges[ key ];
vertex = geometry.vertices[ e.index1 ];
vertices.push( vertex.x, vertex.y, vertex.z );
vertex = geometry.vertices[ e.index2 ];
vertices.push( vertex.x, vertex.y, vertex.z );
}
} else if ( geometry && geometry.isBufferGeometry ) {
var position, indices, groups;
var group, start, count;
var index1, index2;
vertex = new Vector3();
if ( geometry.index !== null ) {
// indexed BufferGeometry
position = geometry.attributes.position;
indices = geometry.index;
groups = geometry.groups;
if ( groups.length === 0 ) {
groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
}
// create a data structure that contains all eges without duplicates
for ( o = 0, ol = groups.length; o < ol; ++ o ) {
group = groups[ o ];
start = group.start;
count = group.count;
for ( i = start, l = ( start + count ); i < l; i += 3 ) {
for ( j = 0; j < 3; j ++ ) {
edge1 = indices.getX( i + j );
edge2 = indices.getX( i + ( j + 1 ) % 3 );
edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
edge[ 1 ] = Math.max( edge1, edge2 );
key = edge[ 0 ] + ',' + edge[ 1 ];
if ( edges[ key ] === undefined ) {
edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
}
}
}
}
// generate vertices
for ( key in edges ) {
e = edges[ key ];
vertex.fromBufferAttribute( position, e.index1 );
vertices.push( vertex.x, vertex.y, vertex.z );
vertex.fromBufferAttribute( position, e.index2 );
vertices.push( vertex.x, vertex.y, vertex.z );
}
} else {
// non-indexed BufferGeometry
position = geometry.attributes.position;
for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
for ( j = 0; j < 3; j ++ ) {
// three edges per triangle, an edge is represented as (index1, index2)
// e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
index1 = 3 * i + j;
vertex.fromBufferAttribute( position, index1 );
vertices.push( vertex.x, vertex.y, vertex.z );
index2 = 3 * i + ( ( j + 1 ) % 3 );
vertex.fromBufferAttribute( position, index2 );
vertices.push( vertex.x, vertex.y, vertex.z );
}
}
}
}
// build geometry
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
}
WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
WireframeGeometry.prototype.constructor = WireframeGeometry;
/**
* @author zz85 / https://github.com/zz85
* @author Mugen87 / https://github.com/Mugen87
*
* Parametric Surfaces Geometry
* based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
*/
// ParametricGeometry
function ParametricGeometry( func, slices, stacks ) {
Geometry.call( this );
this.type = 'ParametricGeometry';
this.parameters = {
func: func,
slices: slices,
stacks: stacks
};
this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
this.mergeVertices();
}
ParametricGeometry.prototype = Object.create( Geometry.prototype );
ParametricGeometry.prototype.constructor = ParametricGeometry;
// ParametricBufferGeometry
function ParametricBufferGeometry( func, slices, stacks ) {
BufferGeometry.call( this );
this.type = 'ParametricBufferGeometry';
this.parameters = {
func: func,
slices: slices,
stacks: stacks
};
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
var EPS = 0.00001;
var normal = new Vector3();
var p0 = new Vector3(), p1 = new Vector3();
var pu = new Vector3(), pv = new Vector3();
var i, j;
if ( func.length < 3 ) {
console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
}
// generate vertices, normals and uvs
var sliceCount = slices + 1;
for ( i = 0; i <= stacks; i ++ ) {
var v = i / stacks;
for ( j = 0; j <= slices; j ++ ) {
var u = j / slices;
// vertex
func( u, v, p0 );
vertices.push( p0.x, p0.y, p0.z );
// normal
// approximate tangent vectors via finite differences
if ( u - EPS >= 0 ) {
func( u - EPS, v, p1 );
pu.subVectors( p0, p1 );
} else {
func( u + EPS, v, p1 );
pu.subVectors( p1, p0 );
}
if ( v - EPS >= 0 ) {
func( u, v - EPS, p1 );
pv.subVectors( p0, p1 );
} else {
func( u, v + EPS, p1 );
pv.subVectors( p1, p0 );
}
// cross product of tangent vectors returns surface normal
normal.crossVectors( pu, pv ).normalize();
normals.push( normal.x, normal.y, normal.z );
// uv
uvs.push( u, v );
}
}
// generate indices
for ( i = 0; i < stacks; i ++ ) {
for ( j = 0; j < slices; j ++ ) {
var a = i * sliceCount + j;
var b = i * sliceCount + j + 1;
var c = ( i + 1 ) * sliceCount + j + 1;
var d = ( i + 1 ) * sliceCount + j;
// faces one and two
indices.push( a, b, d );
indices.push( b, c, d );
}
}
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
}
ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
/**
* @author clockworkgeek / https://github.com/clockworkgeek
* @author timothypratley / https://github.com/timothypratley
* @author WestLangley / http://github.com/WestLangley
* @author Mugen87 / https://github.com/Mugen87
*/
// PolyhedronGeometry
function PolyhedronGeometry( vertices, indices, radius, detail ) {
Geometry.call( this );
this.type = 'PolyhedronGeometry';
this.parameters = {
vertices: vertices,
indices: indices,
radius: radius,
detail: detail
};
this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
this.mergeVertices();
}
PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
// PolyhedronBufferGeometry
function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
BufferGeometry.call( this );
this.type = 'PolyhedronBufferGeometry';
this.parameters = {
vertices: vertices,
indices: indices,
radius: radius,
detail: detail
};
radius = radius || 1;
detail = detail || 0;
// default buffer data
var vertexBuffer = [];
var uvBuffer = [];
// the subdivision creates the vertex buffer data
subdivide( detail );
// all vertices should lie on a conceptual sphere with a given radius
applyRadius( radius );
// finally, create the uv data
generateUVs();
// build non-indexed geometry
this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
if ( detail === 0 ) {
this.computeVertexNormals(); // flat normals
} else {
this.normalizeNormals(); // smooth normals
}
// helper functions
function subdivide( detail ) {
var a = new Vector3();
var b = new Vector3();
var c = new Vector3();
// iterate over all faces and apply a subdivison with the given detail value
for ( var i = 0; i < indices.length; i += 3 ) {
// get the vertices of the face
getVertexByIndex( indices[ i + 0 ], a );
getVertexByIndex( indices[ i + 1 ], b );
getVertexByIndex( indices[ i + 2 ], c );
// perform subdivision
subdivideFace( a, b, c, detail );
}
}
function subdivideFace( a, b, c, detail ) {
var cols = Math.pow( 2, detail );
// we use this multidimensional array as a data structure for creating the subdivision
var v = [];
var i, j;
// construct all of the vertices for this subdivision
for ( i = 0; i <= cols; i ++ ) {
v[ i ] = [];
var aj = a.clone().lerp( c, i / cols );
var bj = b.clone().lerp( c, i / cols );
var rows = cols - i;
for ( j = 0; j <= rows; j ++ ) {
if ( j === 0 && i === cols ) {
v[ i ][ j ] = aj;
} else {
v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
}
}
}
// construct all of the faces
for ( i = 0; i < cols; i ++ ) {
for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
var k = Math.floor( j / 2 );
if ( j % 2 === 0 ) {
pushVertex( v[ i ][ k + 1 ] );
pushVertex( v[ i + 1 ][ k ] );
pushVertex( v[ i ][ k ] );
} else {
pushVertex( v[ i ][ k + 1 ] );
pushVertex( v[ i + 1 ][ k + 1 ] );
pushVertex( v[ i + 1 ][ k ] );
}
}
}
}
function applyRadius( radius ) {
var vertex = new Vector3();
// iterate over the entire buffer and apply the radius to each vertex
for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
vertex.x = vertexBuffer[ i + 0 ];
vertex.y = vertexBuffer[ i + 1 ];
vertex.z = vertexBuffer[ i + 2 ];
vertex.normalize().multiplyScalar( radius );
vertexBuffer[ i + 0 ] = vertex.x;
vertexBuffer[ i + 1 ] = vertex.y;
vertexBuffer[ i + 2 ] = vertex.z;
}
}
function generateUVs() {
var vertex = new Vector3();
for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
vertex.x = vertexBuffer[ i + 0 ];
vertex.y = vertexBuffer[ i + 1 ];
vertex.z = vertexBuffer[ i + 2 ];
var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
var v = inclination( vertex ) / Math.PI + 0.5;
uvBuffer.push( u, 1 - v );
}
correctUVs();
correctSeam();
}
function correctSeam() {
// handle case when face straddles the seam, see #3269
for ( var i = 0; i < uvBuffer.length; i += 6 ) {
// uv data of a single face
var x0 = uvBuffer[ i + 0 ];
var x1 = uvBuffer[ i + 2 ];
var x2 = uvBuffer[ i + 4 ];
var max = Math.max( x0, x1, x2 );
var min = Math.min( x0, x1, x2 );
// 0.9 is somewhat arbitrary
if ( max > 0.9 && min < 0.1 ) {
if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
}
}
}
function pushVertex( vertex ) {
vertexBuffer.push( vertex.x, vertex.y, vertex.z );
}
function getVertexByIndex( index, vertex ) {
var stride = index * 3;
vertex.x = vertices[ stride + 0 ];
vertex.y = vertices[ stride + 1 ];
vertex.z = vertices[ stride + 2 ];
}
function correctUVs() {
var a = new Vector3();
var b = new Vector3();
var c = new Vector3();
var centroid = new Vector3();
var uvA = new Vector2();
var uvB = new Vector2();
var uvC = new Vector2();
for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
var azi = azimuth( centroid );
correctUV( uvA, j + 0, a, azi );
correctUV( uvB, j + 2, b, azi );
correctUV( uvC, j + 4, c, azi );
}
}
function correctUV( uv, stride, vector, azimuth ) {
if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
uvBuffer[ stride ] = uv.x - 1;
}
if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
}
}
// Angle around the Y axis, counter-clockwise when looking from above.
function azimuth( vector ) {
return Math.atan2( vector.z, - vector.x );
}
// Angle above the XZ plane.
function inclination( vector ) {
return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
}
}
PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
/**
* @author timothypratley / https://github.com/timothypratley
* @author Mugen87 / https://github.com/Mugen87
*/
// TetrahedronGeometry
function TetrahedronGeometry( radius, detail ) {
Geometry.call( this );
this.type = 'TetrahedronGeometry';
this.parameters = {
radius: radius,
detail: detail
};
this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
this.mergeVertices();
}
TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
// TetrahedronBufferGeometry
function TetrahedronBufferGeometry( radius, detail ) {
var vertices = [
1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
];
var indices = [
2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
];
PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
this.type = 'TetrahedronBufferGeometry';
this.parameters = {
radius: radius,
detail: detail
};
}
TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
/**
* @author timothypratley / https://github.com/timothypratley
* @author Mugen87 / https://github.com/Mugen87
*/
// OctahedronGeometry
function OctahedronGeometry( radius, detail ) {
Geometry.call( this );
this.type = 'OctahedronGeometry';
this.parameters = {
radius: radius,
detail: detail
};
this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
this.mergeVertices();
}
OctahedronGeometry.prototype = Object.create( Geometry.prototype );
OctahedronGeometry.prototype.constructor = OctahedronGeometry;
// OctahedronBufferGeometry
function OctahedronBufferGeometry( radius, detail ) {
var vertices = [
1, 0, 0, - 1, 0, 0, 0, 1, 0,
0, - 1, 0, 0, 0, 1, 0, 0, - 1
];
var indices = [
0, 2, 4, 0, 4, 3, 0, 3, 5,
0, 5, 2, 1, 2, 5, 1, 5, 3,
1, 3, 4, 1, 4, 2
];
PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
this.type = 'OctahedronBufferGeometry';
this.parameters = {
radius: radius,
detail: detail
};
}
OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
/**
* @author timothypratley / https://github.com/timothypratley
* @author Mugen87 / https://github.com/Mugen87
*/
// IcosahedronGeometry
function IcosahedronGeometry( radius, detail ) {
Geometry.call( this );
this.type = 'IcosahedronGeometry';
this.parameters = {
radius: radius,
detail: detail
};
this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
this.mergeVertices();
}
IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
// IcosahedronBufferGeometry
function IcosahedronBufferGeometry( radius, detail ) {
var t = ( 1 + Math.sqrt( 5 ) ) / 2;
var vertices = [
- 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
];
var indices = [
0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
];
PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
this.type = 'IcosahedronBufferGeometry';
this.parameters = {
radius: radius,
detail: detail
};
}
IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
/**
* @author Abe Pazos / https://hamoid.com
* @author Mugen87 / https://github.com/Mugen87
*/
// DodecahedronGeometry
function DodecahedronGeometry( radius, detail ) {
Geometry.call( this );
this.type = 'DodecahedronGeometry';
this.parameters = {
radius: radius,
detail: detail
};
this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
this.mergeVertices();
}
DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
// DodecahedronBufferGeometry
function DodecahedronBufferGeometry( radius, detail ) {
var t = ( 1 + Math.sqrt( 5 ) ) / 2;
var r = 1 / t;
var vertices = [
// (±1, ±1, ±1)
- 1, - 1, - 1, - 1, - 1, 1,
- 1, 1, - 1, - 1, 1, 1,
1, - 1, - 1, 1, - 1, 1,
1, 1, - 1, 1, 1, 1,
// (0, ±1/φ, ±φ)
0, - r, - t, 0, - r, t,
0, r, - t, 0, r, t,
// (±1/φ, ±φ, 0)
- r, - t, 0, - r, t, 0,
r, - t, 0, r, t, 0,
// (±φ, 0, ±1/φ)
- t, 0, - r, t, 0, - r,
- t, 0, r, t, 0, r
];
var indices = [
3, 11, 7, 3, 7, 15, 3, 15, 13,
7, 19, 17, 7, 17, 6, 7, 6, 15,
17, 4, 8, 17, 8, 10, 17, 10, 6,
8, 0, 16, 8, 16, 2, 8, 2, 10,
0, 12, 1, 0, 1, 18, 0, 18, 16,
6, 10, 2, 6, 2, 13, 6, 13, 15,
2, 16, 18, 2, 18, 3, 2, 3, 13,
18, 1, 9, 18, 9, 11, 18, 11, 3,
4, 14, 12, 4, 12, 0, 4, 0, 8,
11, 9, 5, 11, 5, 19, 11, 19, 7,
19, 5, 14, 19, 14, 4, 19, 4, 17,
1, 12, 14, 1, 14, 5, 1, 5, 9
];
PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
this.type = 'DodecahedronBufferGeometry';
this.parameters = {
radius: radius,
detail: detail
};
}
DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
/**
* @author oosmoxiecode / https://github.com/oosmoxiecode
* @author WestLangley / https://github.com/WestLangley
* @author zz85 / https://github.com/zz85
* @author miningold / https://github.com/miningold
* @author jonobr1 / https://github.com/jonobr1
* @author Mugen87 / https://github.com/Mugen87
*
*/
// TubeGeometry
function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
Geometry.call( this );
this.type = 'TubeGeometry';
this.parameters = {
path: path,
tubularSegments: tubularSegments,
radius: radius,
radialSegments: radialSegments,
closed: closed
};
if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
// expose internals
this.tangents = bufferGeometry.tangents;
this.normals = bufferGeometry.normals;
this.binormals = bufferGeometry.binormals;
// create geometry
this.fromBufferGeometry( bufferGeometry );
this.mergeVertices();
}
TubeGeometry.prototype = Object.create( Geometry.prototype );
TubeGeometry.prototype.constructor = TubeGeometry;
// TubeBufferGeometry
function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
BufferGeometry.call( this );
this.type = 'TubeBufferGeometry';
this.parameters = {
path: path,
tubularSegments: tubularSegments,
radius: radius,
radialSegments: radialSegments,
closed: closed
};
tubularSegments = tubularSegments || 64;
radius = radius || 1;
radialSegments = radialSegments || 8;
closed = closed || false;
var frames = path.computeFrenetFrames( tubularSegments, closed );
// expose internals
this.tangents = frames.tangents;
this.normals = frames.normals;
this.binormals = frames.binormals;
// helper variables
var vertex = new Vector3();
var normal = new Vector3();
var uv = new Vector2();
var P = new Vector3();
var i, j;
// buffer
var vertices = [];
var normals = [];
var uvs = [];
var indices = [];
// create buffer data
generateBufferData();
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
// functions
function generateBufferData() {
for ( i = 0; i < tubularSegments; i ++ ) {
generateSegment( i );
}
// if the geometry is not closed, generate the last row of vertices and normals
// at the regular position on the given path
//
// if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
generateSegment( ( closed === false ) ? tubularSegments : 0 );
// uvs are generated in a separate function.
// this makes it easy compute correct values for closed geometries
generateUVs();
// finally create faces
generateIndices();
}
function generateSegment( i ) {
// we use getPointAt to sample evenly distributed points from the given path
P = path.getPointAt( i / tubularSegments, P );
// retrieve corresponding normal and binormal
var N = frames.normals[ i ];
var B = frames.binormals[ i ];
// generate normals and vertices for the current segment
for ( j = 0; j <= radialSegments; j ++ ) {
var v = j / radialSegments * Math.PI * 2;
var sin = Math.sin( v );
var cos = - Math.cos( v );
// normal
normal.x = ( cos * N.x + sin * B.x );
normal.y = ( cos * N.y + sin * B.y );
normal.z = ( cos * N.z + sin * B.z );
normal.normalize();
normals.push( normal.x, normal.y, normal.z );
// vertex
vertex.x = P.x + radius * normal.x;
vertex.y = P.y + radius * normal.y;
vertex.z = P.z + radius * normal.z;
vertices.push( vertex.x, vertex.y, vertex.z );
}
}
function generateIndices() {
for ( j = 1; j <= tubularSegments; j ++ ) {
for ( i = 1; i <= radialSegments; i ++ ) {
var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
var b = ( radialSegments + 1 ) * j + ( i - 1 );
var c = ( radialSegments + 1 ) * j + i;
var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
// faces
indices.push( a, b, d );
indices.push( b, c, d );
}
}
}
function generateUVs() {
for ( i = 0; i <= tubularSegments; i ++ ) {
for ( j = 0; j <= radialSegments; j ++ ) {
uv.x = i / tubularSegments;
uv.y = j / radialSegments;
uvs.push( uv.x, uv.y );
}
}
}
}
TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
TubeBufferGeometry.prototype.toJSON = function () {
var data = BufferGeometry.prototype.toJSON.call( this );
data.path = this.parameters.path.toJSON();
return data;
};
/**
* @author oosmoxiecode
* @author Mugen87 / https://github.com/Mugen87
*
* based on http://www.blackpawn.com/texts/pqtorus/
*/
// TorusKnotGeometry
function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
Geometry.call( this );
this.type = 'TorusKnotGeometry';
this.parameters = {
radius: radius,
tube: tube,
tubularSegments: tubularSegments,
radialSegments: radialSegments,
p: p,
q: q
};
if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
this.mergeVertices();
}
TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
// TorusKnotBufferGeometry
function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
BufferGeometry.call( this );
this.type = 'TorusKnotBufferGeometry';
this.parameters = {
radius: radius,
tube: tube,
tubularSegments: tubularSegments,
radialSegments: radialSegments,
p: p,
q: q
};
radius = radius || 1;
tube = tube || 0.4;
tubularSegments = Math.floor( tubularSegments ) || 64;
radialSegments = Math.floor( radialSegments ) || 8;
p = p || 2;
q = q || 3;
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
// helper variables
var i, j;
var vertex = new Vector3();
var normal = new Vector3();
var P1 = new Vector3();
var P2 = new Vector3();
var B = new Vector3();
var T = new Vector3();
var N = new Vector3();
// generate vertices, normals and uvs
for ( i = 0; i <= tubularSegments; ++ i ) {
// the radian "u" is used to calculate the position on the torus curve of the current tubular segement
var u = i / tubularSegments * p * Math.PI * 2;
// now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
// these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
calculatePositionOnCurve( u, p, q, radius, P1 );
calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
// calculate orthonormal basis
T.subVectors( P2, P1 );
N.addVectors( P2, P1 );
B.crossVectors( T, N );
N.crossVectors( B, T );
// normalize B, N. T can be ignored, we don't use it
B.normalize();
N.normalize();
for ( j = 0; j <= radialSegments; ++ j ) {
// now calculate the vertices. they are nothing more than an extrusion of the torus curve.
// because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
var v = j / radialSegments * Math.PI * 2;
var cx = - tube * Math.cos( v );
var cy = tube * Math.sin( v );
// now calculate the final vertex position.
// first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
vertex.x = P1.x + ( cx * N.x + cy * B.x );
vertex.y = P1.y + ( cx * N.y + cy * B.y );
vertex.z = P1.z + ( cx * N.z + cy * B.z );
vertices.push( vertex.x, vertex.y, vertex.z );
// normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
normal.subVectors( vertex, P1 ).normalize();
normals.push( normal.x, normal.y, normal.z );
// uv
uvs.push( i / tubularSegments );
uvs.push( j / radialSegments );
}
}
// generate indices
for ( j = 1; j <= tubularSegments; j ++ ) {
for ( i = 1; i <= radialSegments; i ++ ) {
// indices
var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
var b = ( radialSegments + 1 ) * j + ( i - 1 );
var c = ( radialSegments + 1 ) * j + i;
var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
// faces
indices.push( a, b, d );
indices.push( b, c, d );
}
}
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
// this function calculates the current position on the torus curve
function calculatePositionOnCurve( u, p, q, radius, position ) {
var cu = Math.cos( u );
var su = Math.sin( u );
var quOverP = q / p * u;
var cs = Math.cos( quOverP );
position.x = radius * ( 2 + cs ) * 0.5 * cu;
position.y = radius * ( 2 + cs ) * su * 0.5;
position.z = radius * Math.sin( quOverP ) * 0.5;
}
}
TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
/**
* @author oosmoxiecode
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / https://github.com/Mugen87
*/
// TorusGeometry
function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
Geometry.call( this );
this.type = 'TorusGeometry';
this.parameters = {
radius: radius,
tube: tube,
radialSegments: radialSegments,
tubularSegments: tubularSegments,
arc: arc
};
this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
this.mergeVertices();
}
TorusGeometry.prototype = Object.create( Geometry.prototype );
TorusGeometry.prototype.constructor = TorusGeometry;
// TorusBufferGeometry
function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
BufferGeometry.call( this );
this.type = 'TorusBufferGeometry';
this.parameters = {
radius: radius,
tube: tube,
radialSegments: radialSegments,
tubularSegments: tubularSegments,
arc: arc
};
radius = radius || 1;
tube = tube || 0.4;
radialSegments = Math.floor( radialSegments ) || 8;
tubularSegments = Math.floor( tubularSegments ) || 6;
arc = arc || Math.PI * 2;
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
// helper variables
var center = new Vector3();
var vertex = new Vector3();
var normal = new Vector3();
var j, i;
// generate vertices, normals and uvs
for ( j = 0; j <= radialSegments; j ++ ) {
for ( i = 0; i <= tubularSegments; i ++ ) {
var u = i / tubularSegments * arc;
var v = j / radialSegments * Math.PI * 2;
// vertex
vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
vertex.z = tube * Math.sin( v );
vertices.push( vertex.x, vertex.y, vertex.z );
// normal
center.x = radius * Math.cos( u );
center.y = radius * Math.sin( u );
normal.subVectors( vertex, center ).normalize();
normals.push( normal.x, normal.y, normal.z );
// uv
uvs.push( i / tubularSegments );
uvs.push( j / radialSegments );
}
}
// generate indices
for ( j = 1; j <= radialSegments; j ++ ) {
for ( i = 1; i <= tubularSegments; i ++ ) {
// indices
var a = ( tubularSegments + 1 ) * j + i - 1;
var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
var d = ( tubularSegments + 1 ) * j + i;
// faces
indices.push( a, b, d );
indices.push( b, c, d );
}
}
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
}
TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
/**
* @author Mugen87 / https://github.com/Mugen87
* Port from https://github.com/mapbox/earcut (v2.2.2)
*/
var Earcut = {
triangulate: function ( data, holeIndices, dim ) {
dim = dim || 2;
var hasHoles = holeIndices && holeIndices.length,
outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
outerNode = linkedList( data, 0, outerLen, dim, true ),
triangles = [];
if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
var minX, minY, maxX, maxY, x, y, invSize;
if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
if ( data.length > 80 * dim ) {
minX = maxX = data[ 0 ];
minY = maxY = data[ 1 ];
for ( var i = dim; i < outerLen; i += dim ) {
x = data[ i ];
y = data[ i + 1 ];
if ( x < minX ) minX = x;
if ( y < minY ) minY = y;
if ( x > maxX ) maxX = x;
if ( y > maxY ) maxY = y;
}
// minX, minY and invSize are later used to transform coords into integers for z-order calculation
invSize = Math.max( maxX - minX, maxY - minY );
invSize = invSize !== 0 ? 1 / invSize : 0;
}
earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
return triangles;
}
};
// create a circular doubly linked list from polygon points in the specified winding order
function linkedList( data, start, end, dim, clockwise ) {
var i, last;
if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
} else {
for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
}
if ( last && equals( last, last.next ) ) {
removeNode( last );
last = last.next;
}
return last;
}
// eliminate colinear or duplicate points
function filterPoints( start, end ) {
if ( ! start ) return start;
if ( ! end ) end = start;
var p = start,
again;
do {
again = false;
if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
removeNode( p );
p = end = p.prev;
if ( p === p.next ) break;
again = true;
} else {
p = p.next;
}
} while ( again || p !== end );
return end;
}
// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
if ( ! ear ) return;
// interlink polygon nodes in z-order
if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
var stop = ear,
prev, next;
// iterate through ears, slicing them one by one
while ( ear.prev !== ear.next ) {
prev = ear.prev;
next = ear.next;
if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
// cut off the triangle
triangles.push( prev.i / dim );
triangles.push( ear.i / dim );
triangles.push( next.i / dim );
removeNode( ear );
// skipping the next vertex leads to less sliver triangles
ear = next.next;
stop = next.next;
continue;
}
ear = next;
// if we looped through the whole remaining polygon and can't find any more ears
if ( ear === stop ) {
// try filtering points and slicing again
if ( ! pass ) {
earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
// if this didn't work, try curing all small self-intersections locally
} else if ( pass === 1 ) {
ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
// as a last resort, try splitting the remaining polygon into two
} else if ( pass === 2 ) {
splitEarcut( ear, triangles, dim, minX, minY, invSize );
}
break;
}
}
}
// check whether a polygon node forms a valid ear with adjacent nodes
function isEar( ear ) {
var a = ear.prev,
b = ear,
c = ear.next;
if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
// now make sure we don't have other points inside the potential ear
var p = ear.next.next;
while ( p !== ear.prev ) {
if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
area( p.prev, p, p.next ) >= 0 ) return false;
p = p.next;
}
return true;
}
function isEarHashed( ear, minX, minY, invSize ) {
var a = ear.prev,
b = ear,
c = ear.next;
if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
// triangle bbox; min & max are calculated like this for speed
var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
// z-order range for the current triangle bbox;
var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
var p = ear.prevZ,
n = ear.nextZ;
// look for points inside the triangle in both directions
while ( p && p.z >= minZ && n && n.z <= maxZ ) {
if ( p !== ear.prev && p !== ear.next &&
pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
area( p.prev, p, p.next ) >= 0 ) return false;
p = p.prevZ;
if ( n !== ear.prev && n !== ear.next &&
pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
area( n.prev, n, n.next ) >= 0 ) return false;
n = n.nextZ;
}
// look for remaining points in decreasing z-order
while ( p && p.z >= minZ ) {
if ( p !== ear.prev && p !== ear.next &&
pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
area( p.prev, p, p.next ) >= 0 ) return false;
p = p.prevZ;
}
// look for remaining points in increasing z-order
while ( n && n.z <= maxZ ) {
if ( n !== ear.prev && n !== ear.next &&
pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
area( n.prev, n, n.next ) >= 0 ) return false;
n = n.nextZ;
}
return true;
}
// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections( start, triangles, dim ) {
var p = start;
do {
var a = p.prev,
b = p.next.next;
if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
triangles.push( a.i / dim );
triangles.push( p.i / dim );
triangles.push( b.i / dim );
// remove two nodes involved
removeNode( p );
removeNode( p.next );
p = start = b;
}
p = p.next;
} while ( p !== start );
return filterPoints( p );
}
// try splitting polygon into two and triangulate them independently
function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
// look for a valid diagonal that divides the polygon into two
var a = start;
do {
var b = a.next.next;
while ( b !== a.prev ) {
if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
// split the polygon in two by the diagonal
var c = splitPolygon( a, b );
// filter colinear points around the cuts
a = filterPoints( a, a.next );
c = filterPoints( c, c.next );
// run earcut on each half
earcutLinked( a, triangles, dim, minX, minY, invSize );
earcutLinked( c, triangles, dim, minX, minY, invSize );
return;
}
b = b.next;
}
a = a.next;
} while ( a !== start );
}
// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles( data, holeIndices, outerNode, dim ) {
var queue = [],
i, len, start, end, list;
for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
start = holeIndices[ i ] * dim;
end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
list = linkedList( data, start, end, dim, false );
if ( list === list.next ) list.steiner = true;
queue.push( getLeftmost( list ) );
}
queue.sort( compareX );
// process holes from left to right
for ( i = 0; i < queue.length; i ++ ) {
eliminateHole( queue[ i ], outerNode );
outerNode = filterPoints( outerNode, outerNode.next );
}
return outerNode;
}
function compareX( a, b ) {
return a.x - b.x;
}
// find a bridge between vertices that connects hole with an outer ring and and link it
function eliminateHole( hole, outerNode ) {
outerNode = findHoleBridge( hole, outerNode );
if ( outerNode ) {
var b = splitPolygon( outerNode, hole );
// filter collinear points around the cuts
filterPoints( outerNode, outerNode.next );
filterPoints( b, b.next );
}
}
// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge( hole, outerNode ) {
var p = outerNode,
hx = hole.x,
hy = hole.y,
qx = - Infinity,
m;
// find a segment intersected by a ray from the hole's leftmost point to the left;
// segment's endpoint with lesser x will be potential connection point
do {
if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
if ( x <= hx && x > qx ) {
qx = x;
if ( x === hx ) {
if ( hy === p.y ) return p;
if ( hy === p.next.y ) return p.next;
}
m = p.x < p.next.x ? p : p.next;
}
}
p = p.next;
} while ( p !== outerNode );
if ( ! m ) return null;
if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
// look for points inside the triangle of hole point, segment intersection and endpoint;
// if there are no points found, we have a valid connection;
// otherwise choose the point of the minimum angle with the ray as connection point
var stop = m,
mx = m.x,
my = m.y,
tanMin = Infinity,
tan;
p = m;
do {
if ( hx >= p.x && p.x >= mx && hx !== p.x &&
pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
m = p;
tanMin = tan;
}
}
p = p.next;
} while ( p !== stop );
return m;
}
// whether sector in vertex m contains sector in vertex p in the same coordinates
function sectorContainsSector( m, p ) {
return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
}
// interlink polygon nodes in z-order
function indexCurve( start, minX, minY, invSize ) {
var p = start;
do {
if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
p.prevZ = p.prev;
p.nextZ = p.next;
p = p.next;
} while ( p !== start );
p.prevZ.nextZ = null;
p.prevZ = null;
sortLinked( p );
}
// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked( list ) {
var i, p, q, e, tail, numMerges, pSize, qSize,
inSize = 1;
do {
p = list;
list = null;
tail = null;
numMerges = 0;
while ( p ) {
numMerges ++;
q = p;
pSize = 0;
for ( i = 0; i < inSize; i ++ ) {
pSize ++;
q = q.nextZ;
if ( ! q ) break;
}
qSize = inSize;
while ( pSize > 0 || ( qSize > 0 && q ) ) {
if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
e = p;
p = p.nextZ;
pSize --;
} else {
e = q;
q = q.nextZ;
qSize --;
}
if ( tail ) tail.nextZ = e;
else list = e;
e.prevZ = tail;
tail = e;
}
p = q;
}
tail.nextZ = null;
inSize *= 2;
} while ( numMerges > 1 );
return list;
}
// z-order of a point given coords and inverse of the longer side of data bbox
function zOrder( x, y, minX, minY, invSize ) {
// coords are transformed into non-negative 15-bit integer range
x = 32767 * ( x - minX ) * invSize;
y = 32767 * ( y - minY ) * invSize;
x = ( x | ( x << 8 ) ) & 0x00FF00FF;
x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
x = ( x | ( x << 2 ) ) & 0x33333333;
x = ( x | ( x << 1 ) ) & 0x55555555;
y = ( y | ( y << 8 ) ) & 0x00FF00FF;
y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
y = ( y | ( y << 2 ) ) & 0x33333333;
y = ( y | ( y << 1 ) ) & 0x55555555;
return x | ( y << 1 );
}
// find the leftmost node of a polygon ring
function getLeftmost( start ) {
var p = start,
leftmost = start;
do {
if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
p = p.next;
} while ( p !== start );
return leftmost;
}
// check if a point lies within a convex triangle
function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
}
// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
function isValidDiagonal( a, b ) {
return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
}
// signed area of a triangle
function area( p, q, r ) {
return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
}
// check if two points are equal
function equals( p1, p2 ) {
return p1.x === p2.x && p1.y === p2.y;
}
// check if two segments intersect
function intersects( p1, q1, p2, q2 ) {
var o1 = sign( area( p1, q1, p2 ) );
var o2 = sign( area( p1, q1, q2 ) );
var o3 = sign( area( p2, q2, p1 ) );
var o4 = sign( area( p2, q2, q1 ) );
if ( o1 !== o2 && o3 !== o4 ) return true; // general case
if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
return false;
}
// for collinear points p, q, r, check if point q lies on segment pr
function onSegment( p, q, r ) {
return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y );
}
function sign( num ) {
return num > 0 ? 1 : num < 0 ? - 1 : 0;
}
// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon( a, b ) {
var p = a;
do {
if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
intersects( p, p.next, a, b ) ) return true;
p = p.next;
} while ( p !== a );
return false;
}
// check if a polygon diagonal is locally inside the polygon
function locallyInside( a, b ) {
return area( a.prev, a, a.next ) < 0 ?
area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
}
// check if the middle point of a polygon diagonal is inside the polygon
function middleInside( a, b ) {
var p = a,
inside = false,
px = ( a.x + b.x ) / 2,
py = ( a.y + b.y ) / 2;
do {
if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
inside = ! inside;
p = p.next;
} while ( p !== a );
return inside;
}
// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon( a, b ) {
var a2 = new Node( a.i, a.x, a.y ),
b2 = new Node( b.i, b.x, b.y ),
an = a.next,
bp = b.prev;
a.next = b;
b.prev = a;
a2.next = an;
an.prev = a2;
b2.next = a2;
a2.prev = b2;
bp.next = b2;
b2.prev = bp;
return b2;
}
// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode( i, x, y, last ) {
var p = new Node( i, x, y );
if ( ! last ) {
p.prev = p;
p.next = p;
} else {
p.next = last.next;
p.prev = last;
last.next.prev = p;
last.next = p;
}
return p;
}
function removeNode( p ) {
p.next.prev = p.prev;
p.prev.next = p.next;
if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
}
function Node( i, x, y ) {
// vertex index in coordinates array
this.i = i;
// vertex coordinates
this.x = x;
this.y = y;
// previous and next vertex nodes in a polygon ring
this.prev = null;
this.next = null;
// z-order curve value
this.z = null;
// previous and next nodes in z-order
this.prevZ = null;
this.nextZ = null;
// indicates whether this is a steiner point
this.steiner = false;
}
function signedArea( data, start, end, dim ) {
var sum = 0;
for ( var i = start, j = end - dim; i < end; i += dim ) {
sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
j = i;
}
return sum;
}
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
*/
var ShapeUtils = {
// calculate area of the contour polygon
area: function ( contour ) {
var n = contour.length;
var a = 0.0;
for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
}
return a * 0.5;
},
isClockWise: function ( pts ) {
return ShapeUtils.area( pts ) < 0;
},
triangulateShape: function ( contour, holes ) {
var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
var holeIndices = []; // array of hole indices
var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
removeDupEndPts( contour );
addContour( vertices, contour );
//
var holeIndex = contour.length;
holes.forEach( removeDupEndPts );
for ( var i = 0; i < holes.length; i ++ ) {
holeIndices.push( holeIndex );
holeIndex += holes[ i ].length;
addContour( vertices, holes[ i ] );
}
//
var triangles = Earcut.triangulate( vertices, holeIndices );
//
for ( var i = 0; i < triangles.length; i += 3 ) {
faces.push( triangles.slice( i, i + 3 ) );
}
return faces;
}
};
function removeDupEndPts( points ) {
var l = points.length;
if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
points.pop();
}
}
function addContour( vertices, contour ) {
for ( var i = 0; i < contour.length; i ++ ) {
vertices.push( contour[ i ].x );
vertices.push( contour[ i ].y );
}
}
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
*
* Creates extruded geometry from a path shape.
*
* parameters = {
*
* curveSegments: <int>, // number of points on the curves
* steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
* depth: <float>, // Depth to extrude the shape
*
* bevelEnabled: <bool>, // turn on bevel
* bevelThickness: <float>, // how deep into the original shape bevel goes
* bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
* bevelOffset: <float>, // how far from shape outline does bevel start
* bevelSegments: <int>, // number of bevel layers
*
* extrudePath: <THREE.Curve> // curve to extrude shape along
*
* UVGenerator: <Object> // object that provides UV generator functions
*
* }
*/
// ExtrudeGeometry
function ExtrudeGeometry( shapes, options ) {
Geometry.call( this );
this.type = 'ExtrudeGeometry';
this.parameters = {
shapes: shapes,
options: options
};
this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
this.mergeVertices();
}
ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
ExtrudeGeometry.prototype.toJSON = function () {
var data = Geometry.prototype.toJSON.call( this );
var shapes = this.parameters.shapes;
var options = this.parameters.options;
return toJSON( shapes, options, data );
};
// ExtrudeBufferGeometry
function ExtrudeBufferGeometry( shapes, options ) {
BufferGeometry.call( this );
this.type = 'ExtrudeBufferGeometry';
this.parameters = {
shapes: shapes,
options: options
};
shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
var scope = this;
var verticesArray = [];
var uvArray = [];
for ( var i = 0, l = shapes.length; i < l; i ++ ) {
var shape = shapes[ i ];
addShape( shape );
}
// build geometry
this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
this.computeVertexNormals();
// functions
function addShape( shape ) {
var placeholder = [];
// options
var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
var steps = options.steps !== undefined ? options.steps : 1;
var depth = options.depth !== undefined ? options.depth : 100;
var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
var extrudePath = options.extrudePath;
var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
// deprecated options
if ( options.amount !== undefined ) {
console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
depth = options.amount;
}
//
var extrudePts, extrudeByPath = false;
var splineTube, binormal, normal, position2;
if ( extrudePath ) {
extrudePts = extrudePath.getSpacedPoints( steps );
extrudeByPath = true;
bevelEnabled = false; // bevels not supported for path extrusion
// SETUP TNB variables
// TODO1 - have a .isClosed in spline?
splineTube = extrudePath.computeFrenetFrames( steps, false );
// console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
binormal = new Vector3();
normal = new Vector3();
position2 = new Vector3();
}
// Safeguards if bevels are not enabled
if ( ! bevelEnabled ) {
bevelSegments = 0;
bevelThickness = 0;
bevelSize = 0;
bevelOffset = 0;
}
// Variables initialization
var ahole, h, hl; // looping of holes
var shapePoints = shape.extractPoints( curveSegments );
var vertices = shapePoints.shape;
var holes = shapePoints.holes;
var reverse = ! ShapeUtils.isClockWise( vertices );
if ( reverse ) {
vertices = vertices.reverse();
// Maybe we should also check if holes are in the opposite direction, just to be safe ...
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
if ( ShapeUtils.isClockWise( ahole ) ) {
holes[ h ] = ahole.reverse();
}
}
}
var faces = ShapeUtils.triangulateShape( vertices, holes );
/* Vertices */
var contour = vertices; // vertices has all points but contour has only points of circumference
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
vertices = vertices.concat( ahole );
}
function scalePt2( pt, vec, size ) {
if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
return vec.clone().multiplyScalar( size ).add( pt );
}
var b, bs, t, z,
vert, vlen = vertices.length,
face, flen = faces.length;
// Find directions for point movement
function getBevelVec( inPt, inPrev, inNext ) {
// computes for inPt the corresponding point inPt' on a new contour
// shifted by 1 unit (length of normalized vector) to the left
// if we walk along contour clockwise, this new contour is outside the old one
//
// inPt' is the intersection of the two lines parallel to the two
// adjacent edges of inPt at a distance of 1 unit on the left side.
var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
// good reading for geometry algorithms (here: line-line intersection)
// http://geomalgorithms.com/a05-_intersect-1.html
var v_prev_x = inPt.x - inPrev.x,
v_prev_y = inPt.y - inPrev.y;
var v_next_x = inNext.x - inPt.x,
v_next_y = inNext.y - inPt.y;
var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
// check for collinear edges
var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
if ( Math.abs( collinear0 ) > Number.EPSILON ) {
// not collinear
// length of vectors for normalizing
var v_prev_len = Math.sqrt( v_prev_lensq );
var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
// shift adjacent points by unit vectors to the left
var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
// scaling factor for v_prev to intersection point
var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
( v_prev_x * v_next_y - v_prev_y * v_next_x );
// vector from inPt to intersection point
v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
// Don't normalize!, otherwise sharp corners become ugly
// but prevent crazy spikes
var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
if ( v_trans_lensq <= 2 ) {
return new Vector2( v_trans_x, v_trans_y );
} else {
shrink_by = Math.sqrt( v_trans_lensq / 2 );
}
} else {
// handle special case of collinear edges
var direction_eq = false; // assumes: opposite
if ( v_prev_x > Number.EPSILON ) {
if ( v_next_x > Number.EPSILON ) {
direction_eq = true;
}
} else {
if ( v_prev_x < - Number.EPSILON ) {
if ( v_next_x < - Number.EPSILON ) {
direction_eq = true;
}
} else {
if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
direction_eq = true;
}
}
}
if ( direction_eq ) {
// console.log("Warning: lines are a straight sequence");
v_trans_x = - v_prev_y;
v_trans_y = v_prev_x;
shrink_by = Math.sqrt( v_prev_lensq );
} else {
// console.log("Warning: lines are a straight spike");
v_trans_x = v_prev_x;
v_trans_y = v_prev_y;
shrink_by = Math.sqrt( v_prev_lensq / 2 );
}
}
return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
}
var contourMovements = [];
for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
if ( j === il ) j = 0;
if ( k === il ) k = 0;
// (j)---(i)---(k)
// console.log('i,j,k', i, j , k)
contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
}
var holesMovements = [],
oneHoleMovements, verticesMovements = contourMovements.concat();
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
oneHoleMovements = [];
for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
if ( j === il ) j = 0;
if ( k === il ) k = 0;
// (j)---(i)---(k)
oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
}
holesMovements.push( oneHoleMovements );
verticesMovements = verticesMovements.concat( oneHoleMovements );
}
// Loop bevelSegments, 1 for the front, 1 for the back
for ( b = 0; b < bevelSegments; b ++ ) {
//for ( b = bevelSegments; b > 0; b -- ) {
t = b / bevelSegments;
z = bevelThickness * Math.cos( t * Math.PI / 2 );
bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
// contract shape
for ( i = 0, il = contour.length; i < il; i ++ ) {
vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
v( vert.x, vert.y, - z );
}
// expand holes
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
oneHoleMovements = holesMovements[ h ];
for ( i = 0, il = ahole.length; i < il; i ++ ) {
vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
v( vert.x, vert.y, - z );
}
}
}
bs = bevelSize + bevelOffset;
// Back facing vertices
for ( i = 0; i < vlen; i ++ ) {
vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
if ( ! extrudeByPath ) {
v( vert.x, vert.y, 0 );
} else {
// v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
v( position2.x, position2.y, position2.z );
}
}
// Add stepped vertices...
// Including front facing vertices
var s;
for ( s = 1; s <= steps; s ++ ) {
for ( i = 0; i < vlen; i ++ ) {
vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
if ( ! extrudeByPath ) {
v( vert.x, vert.y, depth / steps * s );
} else {
// v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
v( position2.x, position2.y, position2.z );
}
}
}
// Add bevel segments planes
//for ( b = 1; b <= bevelSegments; b ++ ) {
for ( b = bevelSegments - 1; b >= 0; b -- ) {
t = b / bevelSegments;
z = bevelThickness * Math.cos( t * Math.PI / 2 );
bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
// contract shape
for ( i = 0, il = contour.length; i < il; i ++ ) {
vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
v( vert.x, vert.y, depth + z );
}
// expand holes
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
oneHoleMovements = holesMovements[ h ];
for ( i = 0, il = ahole.length; i < il; i ++ ) {
vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
if ( ! extrudeByPath ) {
v( vert.x, vert.y, depth + z );
} else {
v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
}
}
}
}
/* Faces */
// Top and bottom faces
buildLidFaces();
// Sides faces
buildSideFaces();
///// Internal functions
function buildLidFaces() {
var start = verticesArray.length / 3;
if ( bevelEnabled ) {
var layer = 0; // steps + 1
var offset = vlen * layer;
// Bottom faces
for ( i = 0; i < flen; i ++ ) {
face = faces[ i ];
f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
}
layer = steps + bevelSegments * 2;
offset = vlen * layer;
// Top faces
for ( i = 0; i < flen; i ++ ) {
face = faces[ i ];
f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
}
} else {
// Bottom faces
for ( i = 0; i < flen; i ++ ) {
face = faces[ i ];
f3( face[ 2 ], face[ 1 ], face[ 0 ] );
}
// Top faces
for ( i = 0; i < flen; i ++ ) {
face = faces[ i ];
f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
}
}
scope.addGroup( start, verticesArray.length / 3 - start, 0 );
}
// Create faces for the z-sides of the shape
function buildSideFaces() {
var start = verticesArray.length / 3;
var layeroffset = 0;
sidewalls( contour, layeroffset );
layeroffset += contour.length;
for ( h = 0, hl = holes.length; h < hl; h ++ ) {
ahole = holes[ h ];
sidewalls( ahole, layeroffset );
//, true
layeroffset += ahole.length;
}
scope.addGroup( start, verticesArray.length / 3 - start, 1 );
}
function sidewalls( contour, layeroffset ) {
var j, k;
i = contour.length;
while ( -- i >= 0 ) {
j = i;
k = i - 1;
if ( k < 0 ) k = contour.length - 1;
//console.log('b', i,j, i-1, k,vertices.length);
var s = 0,
sl = steps + bevelSegments * 2;
for ( s = 0; s < sl; s ++ ) {
var slen1 = vlen * s;
var slen2 = vlen * ( s + 1 );
var a = layeroffset + j + slen1,
b = layeroffset + k + slen1,
c = layeroffset + k + slen2,
d = layeroffset + j + slen2;
f4( a, b, c, d );
}
}
}
function v( x, y, z ) {
placeholder.push( x );
placeholder.push( y );
placeholder.push( z );
}
function f3( a, b, c ) {
addVertex( a );
addVertex( b );
addVertex( c );
var nextIndex = verticesArray.length / 3;
var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
addUV( uvs[ 0 ] );
addUV( uvs[ 1 ] );
addUV( uvs[ 2 ] );
}
function f4( a, b, c, d ) {
addVertex( a );
addVertex( b );
addVertex( d );
addVertex( b );
addVertex( c );
addVertex( d );
var nextIndex = verticesArray.length / 3;
var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
addUV( uvs[ 0 ] );
addUV( uvs[ 1 ] );
addUV( uvs[ 3 ] );
addUV( uvs[ 1 ] );
addUV( uvs[ 2 ] );
addUV( uvs[ 3 ] );
}
function addVertex( index ) {
verticesArray.push( placeholder[ index * 3 + 0 ] );
verticesArray.push( placeholder[ index * 3 + 1 ] );
verticesArray.push( placeholder[ index * 3 + 2 ] );
}
function addUV( vector2 ) {
uvArray.push( vector2.x );
uvArray.push( vector2.y );
}
}
}
ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
ExtrudeBufferGeometry.prototype.toJSON = function () {
var data = BufferGeometry.prototype.toJSON.call( this );
var shapes = this.parameters.shapes;
var options = this.parameters.options;
return toJSON( shapes, options, data );
};
//
var WorldUVGenerator = {
generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
var a_x = vertices[ indexA * 3 ];
var a_y = vertices[ indexA * 3 + 1 ];
var b_x = vertices[ indexB * 3 ];
var b_y = vertices[ indexB * 3 + 1 ];
var c_x = vertices[ indexC * 3 ];
var c_y = vertices[ indexC * 3 + 1 ];
return [
new Vector2( a_x, a_y ),
new Vector2( b_x, b_y ),
new Vector2( c_x, c_y )
];
},
generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
var a_x = vertices[ indexA * 3 ];
var a_y = vertices[ indexA * 3 + 1 ];
var a_z = vertices[ indexA * 3 + 2 ];
var b_x = vertices[ indexB * 3 ];
var b_y = vertices[ indexB * 3 + 1 ];
var b_z = vertices[ indexB * 3 + 2 ];
var c_x = vertices[ indexC * 3 ];
var c_y = vertices[ indexC * 3 + 1 ];
var c_z = vertices[ indexC * 3 + 2 ];
var d_x = vertices[ indexD * 3 ];
var d_y = vertices[ indexD * 3 + 1 ];
var d_z = vertices[ indexD * 3 + 2 ];
if ( Math.abs( a_y - b_y ) < 0.01 ) {
return [
new Vector2( a_x, 1 - a_z ),
new Vector2( b_x, 1 - b_z ),
new Vector2( c_x, 1 - c_z ),
new Vector2( d_x, 1 - d_z )
];
} else {
return [
new Vector2( a_y, 1 - a_z ),
new Vector2( b_y, 1 - b_z ),
new Vector2( c_y, 1 - c_z ),
new Vector2( d_y, 1 - d_z )
];
}
}
};
function toJSON( shapes, options, data ) {
//
data.shapes = [];
if ( Array.isArray( shapes ) ) {
for ( var i = 0, l = shapes.length; i < l; i ++ ) {
var shape = shapes[ i ];
data.shapes.push( shape.uuid );
}
} else {
data.shapes.push( shapes.uuid );
}
//
if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
return data;
}
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author alteredq / http://alteredqualia.com/
*
* Text = 3D Text
*
* parameters = {
* font: <THREE.Font>, // font
*
* size: <float>, // size of the text
* height: <float>, // thickness to extrude text
* curveSegments: <int>, // number of points on the curves
*
* bevelEnabled: <bool>, // turn on bevel
* bevelThickness: <float>, // how deep into text bevel goes
* bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
* bevelOffset: <float> // how far from text outline does bevel start
* }
*/
// TextGeometry
function TextGeometry( text, parameters ) {
Geometry.call( this );
this.type = 'TextGeometry';
this.parameters = {
text: text,
parameters: parameters
};
this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
this.mergeVertices();
}
TextGeometry.prototype = Object.create( Geometry.prototype );
TextGeometry.prototype.constructor = TextGeometry;
// TextBufferGeometry
function TextBufferGeometry( text, parameters ) {
parameters = parameters || {};
var font = parameters.font;
if ( ! ( font && font.isFont ) ) {
console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
return new Geometry();
}
var shapes = font.generateShapes( text, parameters.size );
// translate parameters to ExtrudeGeometry API
parameters.depth = parameters.height !== undefined ? parameters.height : 50;
// defaults
if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
ExtrudeBufferGeometry.call( this, shapes, parameters );
this.type = 'TextBufferGeometry';
}
TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
TextBufferGeometry.prototype.constructor = TextBufferGeometry;
/**
* @author mrdoob / http://mrdoob.com/
* @author benaadams / https://twitter.com/ben_a_adams
* @author Mugen87 / https://github.com/Mugen87
*/
// SphereGeometry
function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
Geometry.call( this );
this.type = 'SphereGeometry';
this.parameters = {
radius: radius,
widthSegments: widthSegments,
heightSegments: heightSegments,
phiStart: phiStart,
phiLength: phiLength,
thetaStart: thetaStart,
thetaLength: thetaLength
};
this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
this.mergeVertices();
}
SphereGeometry.prototype = Object.create( Geometry.prototype );
SphereGeometry.prototype.constructor = SphereGeometry;
// SphereBufferGeometry
function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
BufferGeometry.call( this );
this.type = 'SphereBufferGeometry';
this.parameters = {
radius: radius,
widthSegments: widthSegments,
heightSegments: heightSegments,
phiStart: phiStart,
phiLength: phiLength,
thetaStart: thetaStart,
thetaLength: thetaLength
};
radius = radius || 1;
widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
phiStart = phiStart !== undefined ? phiStart : 0;
phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
thetaStart = thetaStart !== undefined ? thetaStart : 0;
thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
var thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
var ix, iy;
var index = 0;
var grid = [];
var vertex = new Vector3();
var normal = new Vector3();
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
// generate vertices, normals and uvs
for ( iy = 0; iy <= heightSegments; iy ++ ) {
var verticesRow = [];
var v = iy / heightSegments;
// special case for the poles
var uOffset = 0;
if ( iy == 0 && thetaStart == 0 ) {
uOffset = 0.5 / widthSegments;
} else if ( iy == heightSegments && thetaEnd == Math.PI ) {
uOffset = - 0.5 / widthSegments;
}
for ( ix = 0; ix <= widthSegments; ix ++ ) {
var u = ix / widthSegments;
// vertex
vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
vertices.push( vertex.x, vertex.y, vertex.z );
// normal
normal.copy( vertex ).normalize();
normals.push( normal.x, normal.y, normal.z );
// uv
uvs.push( u + uOffset, 1 - v );
verticesRow.push( index ++ );
}
grid.push( verticesRow );
}
// indices
for ( iy = 0; iy < heightSegments; iy ++ ) {
for ( ix = 0; ix < widthSegments; ix ++ ) {
var a = grid[ iy ][ ix + 1 ];
var b = grid[ iy ][ ix ];
var c = grid[ iy + 1 ][ ix ];
var d = grid[ iy + 1 ][ ix + 1 ];
if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
}
}
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
}
SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
/**
* @author Kaleb Murphy
* @author Mugen87 / https://github.com/Mugen87
*/
// RingGeometry
function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
Geometry.call( this );
this.type = 'RingGeometry';
this.parameters = {
innerRadius: innerRadius,
outerRadius: outerRadius,
thetaSegments: thetaSegments,
phiSegments: phiSegments,
thetaStart: thetaStart,
thetaLength: thetaLength
};
this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
this.mergeVertices();
}
RingGeometry.prototype = Object.create( Geometry.prototype );
RingGeometry.prototype.constructor = RingGeometry;
// RingBufferGeometry
function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
BufferGeometry.call( this );
this.type = 'RingBufferGeometry';
this.parameters = {
innerRadius: innerRadius,
outerRadius: outerRadius,
thetaSegments: thetaSegments,
phiSegments: phiSegments,
thetaStart: thetaStart,
thetaLength: thetaLength
};
innerRadius = innerRadius || 0.5;
outerRadius = outerRadius || 1;
thetaStart = thetaStart !== undefined ? thetaStart : 0;
thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
// some helper variables
var segment;
var radius = innerRadius;
var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
var vertex = new Vector3();
var uv = new Vector2();
var j, i;
// generate vertices, normals and uvs
for ( j = 0; j <= phiSegments; j ++ ) {
for ( i = 0; i <= thetaSegments; i ++ ) {
// values are generate from the inside of the ring to the outside
segment = thetaStart + i / thetaSegments * thetaLength;
// vertex
vertex.x = radius * Math.cos( segment );
vertex.y = radius * Math.sin( segment );
vertices.push( vertex.x, vertex.y, vertex.z );
// normal
normals.push( 0, 0, 1 );
// uv
uv.x = ( vertex.x / outerRadius + 1 ) / 2;
uv.y = ( vertex.y / outerRadius + 1 ) / 2;
uvs.push( uv.x, uv.y );
}
// increase the radius for next row of vertices
radius += radiusStep;
}
// indices
for ( j = 0; j < phiSegments; j ++ ) {
var thetaSegmentLevel = j * ( thetaSegments + 1 );
for ( i = 0; i < thetaSegments; i ++ ) {
segment = i + thetaSegmentLevel;
var a = segment;
var b = segment + thetaSegments + 1;
var c = segment + thetaSegments + 2;
var d = segment + 1;
// faces
indices.push( a, b, d );
indices.push( b, c, d );
}
}
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
}
RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
RingBufferGeometry.prototype.constructor = RingBufferGeometry;
/**
* @author zz85 / https://github.com/zz85
* @author bhouston / http://clara.io
* @author Mugen87 / https://github.com/Mugen87
*/
// LatheGeometry
function LatheGeometry( points, segments, phiStart, phiLength ) {
Geometry.call( this );
this.type = 'LatheGeometry';
this.parameters = {
points: points,
segments: segments,
phiStart: phiStart,
phiLength: phiLength
};
this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
this.mergeVertices();
}
LatheGeometry.prototype = Object.create( Geometry.prototype );
LatheGeometry.prototype.constructor = LatheGeometry;
// LatheBufferGeometry
function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
BufferGeometry.call( this );
this.type = 'LatheBufferGeometry';
this.parameters = {
points: points,
segments: segments,
phiStart: phiStart,
phiLength: phiLength
};
segments = Math.floor( segments ) || 12;
phiStart = phiStart || 0;
phiLength = phiLength || Math.PI * 2;
// clamp phiLength so it's in range of [ 0, 2PI ]
phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );
// buffers
var indices = [];
var vertices = [];
var uvs = [];
// helper variables
var base;
var inverseSegments = 1.0 / segments;
var vertex = new Vector3();
var uv = new Vector2();
var i, j;
// generate vertices and uvs
for ( i = 0; i <= segments; i ++ ) {
var phi = phiStart + i * inverseSegments * phiLength;
var sin = Math.sin( phi );
var cos = Math.cos( phi );
for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
// vertex
vertex.x = points[ j ].x * sin;
vertex.y = points[ j ].y;
vertex.z = points[ j ].x * cos;
vertices.push( vertex.x, vertex.y, vertex.z );
// uv
uv.x = i / segments;
uv.y = j / ( points.length - 1 );
uvs.push( uv.x, uv.y );
}
}
// indices
for ( i = 0; i < segments; i ++ ) {
for ( j = 0; j < ( points.length - 1 ); j ++ ) {
base = j + i * points.length;
var a = base;
var b = base + points.length;
var c = base + points.length + 1;
var d = base + 1;
// faces
indices.push( a, b, d );
indices.push( b, c, d );
}
}
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
// generate normals
this.computeVertexNormals();
// if the geometry is closed, we need to average the normals along the seam.
// because the corresponding vertices are identical (but still have different UVs).
if ( phiLength === Math.PI * 2 ) {
var normals = this.attributes.normal.array;
var n1 = new Vector3();
var n2 = new Vector3();
var n = new Vector3();
// this is the buffer offset for the last line of vertices
base = segments * points.length * 3;
for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
// select the normal of the vertex in the first line
n1.x = normals[ j + 0 ];
n1.y = normals[ j + 1 ];
n1.z = normals[ j + 2 ];
// select the normal of the vertex in the last line
n2.x = normals[ base + j + 0 ];
n2.y = normals[ base + j + 1 ];
n2.z = normals[ base + j + 2 ];
// average normals
n.addVectors( n1, n2 ).normalize();
// assign the new values to both normals
normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
}
}
}
LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
/**
* @author jonobr1 / http://jonobr1.com
* @author Mugen87 / https://github.com/Mugen87
*/
// ShapeGeometry
function ShapeGeometry( shapes, curveSegments ) {
Geometry.call( this );
this.type = 'ShapeGeometry';
if ( typeof curveSegments === 'object' ) {
console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
curveSegments = curveSegments.curveSegments;
}
this.parameters = {
shapes: shapes,
curveSegments: curveSegments
};
this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
this.mergeVertices();
}
ShapeGeometry.prototype = Object.create( Geometry.prototype );
ShapeGeometry.prototype.constructor = ShapeGeometry;
ShapeGeometry.prototype.toJSON = function () {
var data = Geometry.prototype.toJSON.call( this );
var shapes = this.parameters.shapes;
return toJSON$1( shapes, data );
};
// ShapeBufferGeometry
function ShapeBufferGeometry( shapes, curveSegments ) {
BufferGeometry.call( this );
this.type = 'ShapeBufferGeometry';
this.parameters = {
shapes: shapes,
curveSegments: curveSegments
};
curveSegments = curveSegments || 12;
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
// helper variables
var groupStart = 0;
var groupCount = 0;
// allow single and array values for "shapes" parameter
if ( Array.isArray( shapes ) === false ) {
addShape( shapes );
} else {
for ( var i = 0; i < shapes.length; i ++ ) {
addShape( shapes[ i ] );
this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
groupStart += groupCount;
groupCount = 0;
}
}
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
// helper functions
function addShape( shape ) {
var i, l, shapeHole;
var indexOffset = vertices.length / 3;
var points = shape.extractPoints( curveSegments );
var shapeVertices = points.shape;
var shapeHoles = points.holes;
// check direction of vertices
if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
shapeVertices = shapeVertices.reverse();
}
for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
shapeHole = shapeHoles[ i ];
if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
shapeHoles[ i ] = shapeHole.reverse();
}
}
var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
// join vertices of inner and outer paths to a single array
for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
shapeHole = shapeHoles[ i ];
shapeVertices = shapeVertices.concat( shapeHole );
}
// vertices, normals, uvs
for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
var vertex = shapeVertices[ i ];
vertices.push( vertex.x, vertex.y, 0 );
normals.push( 0, 0, 1 );
uvs.push( vertex.x, vertex.y ); // world uvs
}
// incides
for ( i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
var a = face[ 0 ] + indexOffset;
var b = face[ 1 ] + indexOffset;
var c = face[ 2 ] + indexOffset;
indices.push( a, b, c );
groupCount += 3;
}
}
}
ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
ShapeBufferGeometry.prototype.toJSON = function () {
var data = BufferGeometry.prototype.toJSON.call( this );
var shapes = this.parameters.shapes;
return toJSON$1( shapes, data );
};
//
function toJSON$1( shapes, data ) {
data.shapes = [];
if ( Array.isArray( shapes ) ) {
for ( var i = 0, l = shapes.length; i < l; i ++ ) {
var shape = shapes[ i ];
data.shapes.push( shape.uuid );
}
} else {
data.shapes.push( shapes.uuid );
}
return data;
}
/**
* @author WestLangley / http://github.com/WestLangley
* @author Mugen87 / https://github.com/Mugen87
*/
function EdgesGeometry( geometry, thresholdAngle ) {
BufferGeometry.call( this );
this.type = 'EdgesGeometry';
this.parameters = {
thresholdAngle: thresholdAngle
};
thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
// buffer
var vertices = [];
// helper variables
var thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
var edge = [ 0, 0 ], edges = {}, edge1, edge2;
var key, keys = [ 'a', 'b', 'c' ];
// prepare source geometry
var geometry2;
if ( geometry.isBufferGeometry ) {
geometry2 = new Geometry();
geometry2.fromBufferGeometry( geometry );
} else {
geometry2 = geometry.clone();
}
geometry2.mergeVertices();
geometry2.computeFaceNormals();
var sourceVertices = geometry2.vertices;
var faces = geometry2.faces;
// now create a data structure where each entry represents an edge with its adjoining faces
for ( var i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
for ( var j = 0; j < 3; j ++ ) {
edge1 = face[ keys[ j ] ];
edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
edge[ 0 ] = Math.min( edge1, edge2 );
edge[ 1 ] = Math.max( edge1, edge2 );
key = edge[ 0 ] + ',' + edge[ 1 ];
if ( edges[ key ] === undefined ) {
edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
} else {
edges[ key ].face2 = i;
}
}
}
// generate vertices
for ( key in edges ) {
var e = edges[ key ];
// an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
var vertex = sourceVertices[ e.index1 ];
vertices.push( vertex.x, vertex.y, vertex.z );
vertex = sourceVertices[ e.index2 ];
vertices.push( vertex.x, vertex.y, vertex.z );
}
}
// build geometry
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
}
EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
EdgesGeometry.prototype.constructor = EdgesGeometry;
/**
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / https://github.com/Mugen87
*/
// CylinderGeometry
function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
Geometry.call( this );
this.type = 'CylinderGeometry';
this.parameters = {
radiusTop: radiusTop,
radiusBottom: radiusBottom,
height: height,
radialSegments: radialSegments,
heightSegments: heightSegments,
openEnded: openEnded,
thetaStart: thetaStart,
thetaLength: thetaLength
};
this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
this.mergeVertices();
}
CylinderGeometry.prototype = Object.create( Geometry.prototype );
CylinderGeometry.prototype.constructor = CylinderGeometry;
// CylinderBufferGeometry
function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
BufferGeometry.call( this );
this.type = 'CylinderBufferGeometry';
this.parameters = {
radiusTop: radiusTop,
radiusBottom: radiusBottom,
height: height,
radialSegments: radialSegments,
heightSegments: heightSegments,
openEnded: openEnded,
thetaStart: thetaStart,
thetaLength: thetaLength
};
var scope = this;
radiusTop = radiusTop !== undefined ? radiusTop : 1;
radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
height = height || 1;
radialSegments = Math.floor( radialSegments ) || 8;
heightSegments = Math.floor( heightSegments ) || 1;
openEnded = openEnded !== undefined ? openEnded : false;
thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
// helper variables
var index = 0;
var indexArray = [];
var halfHeight = height / 2;
var groupStart = 0;
// generate geometry
generateTorso();
if ( openEnded === false ) {
if ( radiusTop > 0 ) generateCap( true );
if ( radiusBottom > 0 ) generateCap( false );
}
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
function generateTorso() {
var x, y;
var normal = new Vector3();
var vertex = new Vector3();
var groupCount = 0;
// this will be used to calculate the normal
var slope = ( radiusBottom - radiusTop ) / height;
// generate vertices, normals and uvs
for ( y = 0; y <= heightSegments; y ++ ) {
var indexRow = [];
var v = y / heightSegments;
// calculate the radius of the current row
var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
for ( x = 0; x <= radialSegments; x ++ ) {
var u = x / radialSegments;
var theta = u * thetaLength + thetaStart;
var sinTheta = Math.sin( theta );
var cosTheta = Math.cos( theta );
// vertex
vertex.x = radius * sinTheta;
vertex.y = - v * height + halfHeight;
vertex.z = radius * cosTheta;
vertices.push( vertex.x, vertex.y, vertex.z );
// normal
normal.set( sinTheta, slope, cosTheta ).normalize();
normals.push( normal.x, normal.y, normal.z );
// uv
uvs.push( u, 1 - v );
// save index of vertex in respective row
indexRow.push( index ++ );
}
// now save vertices of the row in our index array
indexArray.push( indexRow );
}
// generate indices
for ( x = 0; x < radialSegments; x ++ ) {
for ( y = 0; y < heightSegments; y ++ ) {
// we use the index array to access the correct indices
var a = indexArray[ y ][ x ];
var b = indexArray[ y + 1 ][ x ];
var c = indexArray[ y + 1 ][ x + 1 ];
var d = indexArray[ y ][ x + 1 ];
// faces
indices.push( a, b, d );
indices.push( b, c, d );
// update group counter
groupCount += 6;
}
}
// add a group to the geometry. this will ensure multi material support
scope.addGroup( groupStart, groupCount, 0 );
// calculate new start value for groups
groupStart += groupCount;
}
function generateCap( top ) {
var x, centerIndexStart, centerIndexEnd;
var uv = new Vector2();
var vertex = new Vector3();
var groupCount = 0;
var radius = ( top === true ) ? radiusTop : radiusBottom;
var sign = ( top === true ) ? 1 : - 1;
// save the index of the first center vertex
centerIndexStart = index;
// first we generate the center vertex data of the cap.
// because the geometry needs one set of uvs per face,
// we must generate a center vertex per face/segment
for ( x = 1; x <= radialSegments; x ++ ) {
// vertex
vertices.push( 0, halfHeight * sign, 0 );
// normal
normals.push( 0, sign, 0 );
// uv
uvs.push( 0.5, 0.5 );
// increase index
index ++;
}
// save the index of the last center vertex
centerIndexEnd = index;
// now we generate the surrounding vertices, normals and uvs
for ( x = 0; x <= radialSegments; x ++ ) {
var u = x / radialSegments;
var theta = u * thetaLength + thetaStart;
var cosTheta = Math.cos( theta );
var sinTheta = Math.sin( theta );
// vertex
vertex.x = radius * sinTheta;
vertex.y = halfHeight * sign;
vertex.z = radius * cosTheta;
vertices.push( vertex.x, vertex.y, vertex.z );
// normal
normals.push( 0, sign, 0 );
// uv
uv.x = ( cosTheta * 0.5 ) + 0.5;
uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
uvs.push( uv.x, uv.y );
// increase index
index ++;
}
// generate indices
for ( x = 0; x < radialSegments; x ++ ) {
var c = centerIndexStart + x;
var i = centerIndexEnd + x;
if ( top === true ) {
// face top
indices.push( i, i + 1, c );
} else {
// face bottom
indices.push( i + 1, i, c );
}
groupCount += 3;
}
// add a group to the geometry. this will ensure multi material support
scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
// calculate new start value for groups
groupStart += groupCount;
}
}
CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
/**
* @author abelnation / http://github.com/abelnation
*/
// ConeGeometry
function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
this.type = 'ConeGeometry';
this.parameters = {
radius: radius,
height: height,
radialSegments: radialSegments,
heightSegments: heightSegments,
openEnded: openEnded,
thetaStart: thetaStart,
thetaLength: thetaLength
};
}
ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
ConeGeometry.prototype.constructor = ConeGeometry;
// ConeBufferGeometry
function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
this.type = 'ConeBufferGeometry';
this.parameters = {
radius: radius,
height: height,
radialSegments: radialSegments,
heightSegments: heightSegments,
openEnded: openEnded,
thetaStart: thetaStart,
thetaLength: thetaLength
};
}
ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
/**
* @author benaadams / https://twitter.com/ben_a_adams
* @author Mugen87 / https://github.com/Mugen87
* @author hughes
*/
// CircleGeometry
function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
Geometry.call( this );
this.type = 'CircleGeometry';
this.parameters = {
radius: radius,
segments: segments,
thetaStart: thetaStart,
thetaLength: thetaLength
};
this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
this.mergeVertices();
}
CircleGeometry.prototype = Object.create( Geometry.prototype );
CircleGeometry.prototype.constructor = CircleGeometry;
// CircleBufferGeometry
function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
BufferGeometry.call( this );
this.type = 'CircleBufferGeometry';
this.parameters = {
radius: radius,
segments: segments,
thetaStart: thetaStart,
thetaLength: thetaLength
};
radius = radius || 1;
segments = segments !== undefined ? Math.max( 3, segments ) : 8;
thetaStart = thetaStart !== undefined ? thetaStart : 0;
thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
// helper variables
var i, s;
var vertex = new Vector3();
var uv = new Vector2();
// center point
vertices.push( 0, 0, 0 );
normals.push( 0, 0, 1 );
uvs.push( 0.5, 0.5 );
for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
var segment = thetaStart + s / segments * thetaLength;
// vertex
vertex.x = radius * Math.cos( segment );
vertex.y = radius * Math.sin( segment );
vertices.push( vertex.x, vertex.y, vertex.z );
// normal
normals.push( 0, 0, 1 );
// uvs
uv.x = ( vertices[ i ] / radius + 1 ) / 2;
uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
uvs.push( uv.x, uv.y );
}
// indices
for ( i = 1; i <= segments; i ++ ) {
indices.push( i, i + 1, 0 );
}
// build geometry
this.setIndex( indices );
this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
}
CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
var Geometries = /*#__PURE__*/Object.freeze({
__proto__: null,
WireframeGeometry: WireframeGeometry,
ParametricGeometry: ParametricGeometry,
ParametricBufferGeometry: ParametricBufferGeometry,
TetrahedronGeometry: TetrahedronGeometry,
TetrahedronBufferGeometry: TetrahedronBufferGeometry,
OctahedronGeometry: OctahedronGeometry,
OctahedronBufferGeometry: OctahedronBufferGeometry,
IcosahedronGeometry: IcosahedronGeometry,
IcosahedronBufferGeometry: IcosahedronBufferGeometry,
DodecahedronGeometry: DodecahedronGeometry,
DodecahedronBufferGeometry: DodecahedronBufferGeometry,
PolyhedronGeometry: PolyhedronGeometry,
PolyhedronBufferGeometry: PolyhedronBufferGeometry,
TubeGeometry: TubeGeometry,
TubeBufferGeometry: TubeBufferGeometry,
TorusKnotGeometry: TorusKnotGeometry,
TorusKnotBufferGeometry: TorusKnotBufferGeometry,
TorusGeometry: TorusGeometry,
TorusBufferGeometry: TorusBufferGeometry,
TextGeometry: TextGeometry,
TextBufferGeometry: TextBufferGeometry,
SphereGeometry: SphereGeometry,
SphereBufferGeometry: SphereBufferGeometry,
RingGeometry: RingGeometry,
RingBufferGeometry: RingBufferGeometry,
PlaneGeometry: PlaneGeometry,
PlaneBufferGeometry: PlaneBufferGeometry,
LatheGeometry: LatheGeometry,
LatheBufferGeometry: LatheBufferGeometry,
ShapeGeometry: ShapeGeometry,
ShapeBufferGeometry: ShapeBufferGeometry,
ExtrudeGeometry: ExtrudeGeometry,
ExtrudeBufferGeometry: ExtrudeBufferGeometry,
EdgesGeometry: EdgesGeometry,
ConeGeometry: ConeGeometry,
ConeBufferGeometry: ConeBufferGeometry,
CylinderGeometry: CylinderGeometry,
CylinderBufferGeometry: CylinderBufferGeometry,
CircleGeometry: CircleGeometry,
CircleBufferGeometry: CircleBufferGeometry,
BoxGeometry: BoxGeometry,
BoxBufferGeometry: BoxBufferGeometry
});
/**
* @author mrdoob / http://mrdoob.com/
*
* parameters = {
* color: <THREE.Color>
* }
*/
function ShadowMaterial( parameters ) {
Material.call( this );
this.type = 'ShadowMaterial';
this.color = new Color( 0x000000 );
this.transparent = true;
this.setValues( parameters );
}
ShadowMaterial.prototype = Object.create( Material.prototype );
ShadowMaterial.prototype.constructor = ShadowMaterial;
ShadowMaterial.prototype.isShadowMaterial = true;
ShadowMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.color.copy( source.color );
return this;
};
/**
* @author mrdoob / http://mrdoob.com/
*/
function RawShaderMaterial( parameters ) {
ShaderMaterial.call( this, parameters );
this.type = 'RawShaderMaterial';
}
RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
RawShaderMaterial.prototype.constructor = RawShaderMaterial;
RawShaderMaterial.prototype.isRawShaderMaterial = true;
/**
* @author WestLangley / http://github.com/WestLangley
*
* parameters = {
* color: <hex>,
* roughness: <float>,
* metalness: <float>,
* opacity: <float>,
*
* map: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
* lightMapIntensity: <float>
*
* aoMap: new THREE.Texture( <Image> ),
* aoMapIntensity: <float>
*
* emissive: <hex>,
* emissiveIntensity: <float>
* emissiveMap: new THREE.Texture( <Image> ),
*
* bumpMap: new THREE.Texture( <Image> ),
* bumpScale: <float>,
*
* normalMap: new THREE.Texture( <Image> ),
* normalMapType: THREE.TangentSpaceNormalMap,
* normalScale: <Vector2>,
*
* displacementMap: new THREE.Texture( <Image> ),
* displacementScale: <float>,
* displacementBias: <float>,
*
* roughnessMap: new THREE.Texture( <Image> ),
*
* metalnessMap: new THREE.Texture( <Image> ),
*
* alphaMap: new THREE.Texture( <Image> ),
*
* envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
* envMapIntensity: <float>
*
* refractionRatio: <float>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>
* }
*/
function MeshStandardMaterial( parameters ) {
Material.call( this );
this.defines = { 'STANDARD': '' };
this.type = 'MeshStandardMaterial';
this.color = new Color( 0xffffff ); // diffuse
this.roughness = 1.0;
this.metalness = 0.0;
this.map = null;
this.lightMap = null;
this.lightMapIntensity = 1.0;
this.aoMap = null;
this.aoMapIntensity = 1.0;
this.emissive = new Color( 0x000000 );
this.emissiveIntensity = 1.0;
this.emissiveMap = null;
this.bumpMap = null;
this.bumpScale = 1;
this.normalMap = null;
this.normalMapType = TangentSpaceNormalMap;
this.normalScale = new Vector2( 1, 1 );
this.displacementMap = null;
this.displacementScale = 1;
this.displacementBias = 0;
this.roughnessMap = null;
this.metalnessMap = null;
this.alphaMap = null;
this.envMap = null;
this.envMapIntensity = 1.0;
this.refractionRatio = 0.98;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.wireframeLinecap = 'round';
this.wireframeLinejoin = 'round';
this.skinning = false;
this.morphTargets = false;
this.morphNormals = false;
this.vertexTangents = false;
this.setValues( parameters );
}
MeshStandardMaterial.prototype = Object.create( Material.prototype );
MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
MeshStandardMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.defines = { 'STANDARD': '' };
this.color.copy( source.color );
this.roughness = source.roughness;
this.metalness = source.metalness;
this.map = source.map;
this.lightMap = source.lightMap;
this.lightMapIntensity = source.lightMapIntensity;
this.aoMap = source.aoMap;
this.aoMapIntensity = source.aoMapIntensity;
this.emissive.copy( source.emissive );
this.emissiveMap = source.emissiveMap;
this.emissiveIntensity = source.emissiveIntensity;
this.bumpMap = source.bumpMap;
this.bumpScale = source.bumpScale;
this.normalMap = source.normalMap;
this.normalMapType = source.normalMapType;
this.normalScale.copy( source.normalScale );
this.displacementMap = source.displacementMap;
this.displacementScale = source.displacementScale;
this.displacementBias = source.displacementBias;
this.roughnessMap = source.roughnessMap;
this.metalnessMap = source.metalnessMap;
this.alphaMap = source.alphaMap;
this.envMap = source.envMap;
this.envMapIntensity = source.envMapIntensity;
this.refractionRatio = source.refractionRatio;
this.wireframe = source.wireframe;
this.wireframeLinewidth = source.wireframeLinewidth;
this.wireframeLinecap = source.wireframeLinecap;
this.wireframeLinejoin = source.wireframeLinejoin;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
this.morphNormals = source.morphNormals;
this.vertexTangents = source.vertexTangents;
return this;
};
/**
* @author WestLangley / http://github.com/WestLangley
*
* parameters = {
* clearcoat: <float>,
* clearcoatMap: new THREE.Texture( <Image> ),
* clearcoatRoughness: <float>,
* clearcoatRoughnessMap: new THREE.Texture( <Image> ),
* clearcoatNormalScale: <Vector2>,
* clearcoatNormalMap: new THREE.Texture( <Image> ),
*
* reflectivity: <float>,
*
* sheen: <Color>,
*
* transparency: <float>
* }
*/
function MeshPhysicalMaterial( parameters ) {
MeshStandardMaterial.call( this );
this.defines = {
'STANDARD': '',
'PHYSICAL': ''
};
this.type = 'MeshPhysicalMaterial';
this.clearcoat = 0.0;
this.clearcoatMap = null;
this.clearcoatRoughness = 0.0;
this.clearcoatRoughnessMap = null;
this.clearcoatNormalScale = new Vector2( 1, 1 );
this.clearcoatNormalMap = null;
this.reflectivity = 0.5; // maps to F0 = 0.04
this.sheen = null; // null will disable sheen bsdf
this.transparency = 0.0;
this.setValues( parameters );
}
MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
MeshPhysicalMaterial.prototype.copy = function ( source ) {
MeshStandardMaterial.prototype.copy.call( this, source );
this.defines = {
'STANDARD': '',
'PHYSICAL': ''
};
this.clearcoat = source.clearcoat;
this.clearcoatMap = source.clearcoatMap;
this.clearcoatRoughness = source.clearcoatRoughness;
this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
this.clearcoatNormalMap = source.clearcoatNormalMap;
this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
this.reflectivity = source.reflectivity;
if ( source.sheen ) {
this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
} else {
this.sheen = null;
}
this.transparency = source.transparency;
return this;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* specular: <hex>,
* shininess: <float>,
* opacity: <float>,
*
* map: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
* lightMapIntensity: <float>
*
* aoMap: new THREE.Texture( <Image> ),
* aoMapIntensity: <float>
*
* emissive: <hex>,
* emissiveIntensity: <float>
* emissiveMap: new THREE.Texture( <Image> ),
*
* bumpMap: new THREE.Texture( <Image> ),
* bumpScale: <float>,
*
* normalMap: new THREE.Texture( <Image> ),
* normalMapType: THREE.TangentSpaceNormalMap,
* normalScale: <Vector2>,
*
* displacementMap: new THREE.Texture( <Image> ),
* displacementScale: <float>,
* displacementBias: <float>,
*
* specularMap: new THREE.Texture( <Image> ),
*
* alphaMap: new THREE.Texture( <Image> ),
*
* envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
* combine: THREE.MultiplyOperation,
* reflectivity: <float>,
* refractionRatio: <float>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>
* }
*/
function MeshPhongMaterial( parameters ) {
Material.call( this );
this.type = 'MeshPhongMaterial';
this.color = new Color( 0xffffff ); // diffuse
this.specular = new Color( 0x111111 );
this.shininess = 30;
this.map = null;
this.lightMap = null;
this.lightMapIntensity = 1.0;
this.aoMap = null;
this.aoMapIntensity = 1.0;
this.emissive = new Color( 0x000000 );
this.emissiveIntensity = 1.0;
this.emissiveMap = null;
this.bumpMap = null;
this.bumpScale = 1;
this.normalMap = null;
this.normalMapType = TangentSpaceNormalMap;
this.normalScale = new Vector2( 1, 1 );
this.displacementMap = null;
this.displacementScale = 1;
this.displacementBias = 0;
this.specularMap = null;
this.alphaMap = null;
this.envMap = null;
this.combine = MultiplyOperation;
this.reflectivity = 1;
this.refractionRatio = 0.98;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.wireframeLinecap = 'round';
this.wireframeLinejoin = 'round';
this.skinning = false;
this.morphTargets = false;
this.morphNormals = false;
this.setValues( parameters );
}
MeshPhongMaterial.prototype = Object.create( Material.prototype );
MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
MeshPhongMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.color.copy( source.color );
this.specular.copy( source.specular );
this.shininess = source.shininess;
this.map = source.map;
this.lightMap = source.lightMap;
this.lightMapIntensity = source.lightMapIntensity;
this.aoMap = source.aoMap;
this.aoMapIntensity = source.aoMapIntensity;
this.emissive.copy( source.emissive );
this.emissiveMap = source.emissiveMap;
this.emissiveIntensity = source.emissiveIntensity;
this.bumpMap = source.bumpMap;
this.bumpScale = source.bumpScale;
this.normalMap = source.normalMap;
this.normalMapType = source.normalMapType;
this.normalScale.copy( source.normalScale );
this.displacementMap = source.displacementMap;
this.displacementScale = source.displacementScale;
this.displacementBias = source.displacementBias;
this.specularMap = source.specularMap;
this.alphaMap = source.alphaMap;
this.envMap = source.envMap;
this.combine = source.combine;
this.reflectivity = source.reflectivity;
this.refractionRatio = source.refractionRatio;
this.wireframe = source.wireframe;
this.wireframeLinewidth = source.wireframeLinewidth;
this.wireframeLinecap = source.wireframeLinecap;
this.wireframeLinejoin = source.wireframeLinejoin;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
this.morphNormals = source.morphNormals;
return this;
};
/**
* @author takahirox / http://github.com/takahirox
*
* parameters = {
* color: <hex>,
* specular: <hex>,
* shininess: <float>,
*
* map: new THREE.Texture( <Image> ),
* gradientMap: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
* lightMapIntensity: <float>
*
* aoMap: new THREE.Texture( <Image> ),
* aoMapIntensity: <float>
*
* emissive: <hex>,
* emissiveIntensity: <float>
* emissiveMap: new THREE.Texture( <Image> ),
*
* bumpMap: new THREE.Texture( <Image> ),
* bumpScale: <float>,
*
* normalMap: new THREE.Texture( <Image> ),
* normalMapType: THREE.TangentSpaceNormalMap,
* normalScale: <Vector2>,
*
* displacementMap: new THREE.Texture( <Image> ),
* displacementScale: <float>,
* displacementBias: <float>,
*
* specularMap: new THREE.Texture( <Image> ),
*
* alphaMap: new THREE.Texture( <Image> ),
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>
* }
*/
function MeshToonMaterial( parameters ) {
Material.call( this );
this.defines = { 'TOON': '' };
this.type = 'MeshToonMaterial';
this.color = new Color( 0xffffff );
this.specular = new Color( 0x111111 );
this.shininess = 30;
this.map = null;
this.gradientMap = null;
this.lightMap = null;
this.lightMapIntensity = 1.0;
this.aoMap = null;
this.aoMapIntensity = 1.0;
this.emissive = new Color( 0x000000 );
this.emissiveIntensity = 1.0;
this.emissiveMap = null;
this.bumpMap = null;
this.bumpScale = 1;
this.normalMap = null;
this.normalMapType = TangentSpaceNormalMap;
this.normalScale = new Vector2( 1, 1 );
this.displacementMap = null;
this.displacementScale = 1;
this.displacementBias = 0;
this.specularMap = null;
this.alphaMap = null;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.wireframeLinecap = 'round';
this.wireframeLinejoin = 'round';
this.skinning = false;
this.morphTargets = false;
this.morphNormals = false;
this.setValues( parameters );
}
MeshToonMaterial.prototype = Object.create( Material.prototype );
MeshToonMaterial.prototype.constructor = MeshToonMaterial;
MeshToonMaterial.prototype.isMeshToonMaterial = true;
MeshToonMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.color.copy( source.color );
this.specular.copy( source.specular );
this.shininess = source.shininess;
this.map = source.map;
this.gradientMap = source.gradientMap;
this.lightMap = source.lightMap;
this.lightMapIntensity = source.lightMapIntensity;
this.aoMap = source.aoMap;
this.aoMapIntensity = source.aoMapIntensity;
this.emissive.copy( source.emissive );
this.emissiveMap = source.emissiveMap;
this.emissiveIntensity = source.emissiveIntensity;
this.bumpMap = source.bumpMap;
this.bumpScale = source.bumpScale;
this.normalMap = source.normalMap;
this.normalMapType = source.normalMapType;
this.normalScale.copy( source.normalScale );
this.displacementMap = source.displacementMap;
this.displacementScale = source.displacementScale;
this.displacementBias = source.displacementBias;
this.specularMap = source.specularMap;
this.alphaMap = source.alphaMap;
this.wireframe = source.wireframe;
this.wireframeLinewidth = source.wireframeLinewidth;
this.wireframeLinecap = source.wireframeLinecap;
this.wireframeLinejoin = source.wireframeLinejoin;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
this.morphNormals = source.morphNormals;
return this;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*
* parameters = {
* opacity: <float>,
*
* bumpMap: new THREE.Texture( <Image> ),
* bumpScale: <float>,
*
* normalMap: new THREE.Texture( <Image> ),
* normalMapType: THREE.TangentSpaceNormalMap,
* normalScale: <Vector2>,
*
* displacementMap: new THREE.Texture( <Image> ),
* displacementScale: <float>,
* displacementBias: <float>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>
* }
*/
function MeshNormalMaterial( parameters ) {
Material.call( this );
this.type = 'MeshNormalMaterial';
this.bumpMap = null;
this.bumpScale = 1;
this.normalMap = null;
this.normalMapType = TangentSpaceNormalMap;
this.normalScale = new Vector2( 1, 1 );
this.displacementMap = null;
this.displacementScale = 1;
this.displacementBias = 0;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.fog = false;
this.skinning = false;
this.morphTargets = false;
this.morphNormals = false;
this.setValues( parameters );
}
MeshNormalMaterial.prototype = Object.create( Material.prototype );
MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
MeshNormalMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.bumpMap = source.bumpMap;
this.bumpScale = source.bumpScale;
this.normalMap = source.normalMap;
this.normalMapType = source.normalMapType;
this.normalScale.copy( source.normalScale );
this.displacementMap = source.displacementMap;
this.displacementScale = source.displacementScale;
this.displacementBias = source.displacementBias;
this.wireframe = source.wireframe;
this.wireframeLinewidth = source.wireframeLinewidth;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
this.morphNormals = source.morphNormals;
return this;
};
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* opacity: <float>,
*
* map: new THREE.Texture( <Image> ),
*
* lightMap: new THREE.Texture( <Image> ),
* lightMapIntensity: <float>
*
* aoMap: new THREE.Texture( <Image> ),
* aoMapIntensity: <float>
*
* emissive: <hex>,
* emissiveIntensity: <float>
* emissiveMap: new THREE.Texture( <Image> ),
*
* specularMap: new THREE.Texture( <Image> ),
*
* alphaMap: new THREE.Texture( <Image> ),
*
* envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
* combine: THREE.Multiply,
* reflectivity: <float>,
* refractionRatio: <float>,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>
* }
*/
function MeshLambertMaterial( parameters ) {
Material.call( this );
this.type = 'MeshLambertMaterial';
this.color = new Color( 0xffffff ); // diffuse
this.map = null;
this.lightMap = null;
this.lightMapIntensity = 1.0;
this.aoMap = null;
this.aoMapIntensity = 1.0;
this.emissive = new Color( 0x000000 );
this.emissiveIntensity = 1.0;
this.emissiveMap = null;
this.specularMap = null;
this.alphaMap = null;
this.envMap = null;
this.combine = MultiplyOperation;
this.reflectivity = 1;
this.refractionRatio = 0.98;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.wireframeLinecap = 'round';
this.wireframeLinejoin = 'round';
this.skinning = false;
this.morphTargets = false;
this.morphNormals = false;
this.setValues( parameters );
}
MeshLambertMaterial.prototype = Object.create( Material.prototype );
MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
MeshLambertMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.color.copy( source.color );
this.map = source.map;
this.lightMap = source.lightMap;
this.lightMapIntensity = source.lightMapIntensity;
this.aoMap = source.aoMap;
this.aoMapIntensity = source.aoMapIntensity;
this.emissive.copy( source.emissive );
this.emissiveMap = source.emissiveMap;
this.emissiveIntensity = source.emissiveIntensity;
this.specularMap = source.specularMap;
this.alphaMap = source.alphaMap;
this.envMap = source.envMap;
this.combine = source.combine;
this.reflectivity = source.reflectivity;
this.refractionRatio = source.refractionRatio;
this.wireframe = source.wireframe;
this.wireframeLinewidth = source.wireframeLinewidth;
this.wireframeLinecap = source.wireframeLinecap;
this.wireframeLinejoin = source.wireframeLinejoin;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
this.morphNormals = source.morphNormals;
return this;
};
/**
* @author WestLangley / http://github.com/WestLangley
*
* parameters = {
* color: <hex>,
* opacity: <float>,
*
* matcap: new THREE.Texture( <Image> ),
*
* map: new THREE.Texture( <Image> ),
*
* bumpMap: new THREE.Texture( <Image> ),
* bumpScale: <float>,
*
* normalMap: new THREE.Texture( <Image> ),
* normalMapType: THREE.TangentSpaceNormalMap,
* normalScale: <Vector2>,
*
* displacementMap: new THREE.Texture( <Image> ),
* displacementScale: <float>,
* displacementBias: <float>,
*
* alphaMap: new THREE.Texture( <Image> ),
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>
* }
*/
function MeshMatcapMaterial( parameters ) {
Material.call( this );
this.defines = { 'MATCAP': '' };
this.type = 'MeshMatcapMaterial';
this.color = new Color( 0xffffff ); // diffuse
this.matcap = null;
this.map = null;
this.bumpMap = null;
this.bumpScale = 1;
this.normalMap = null;
this.normalMapType = TangentSpaceNormalMap;
this.normalScale = new Vector2( 1, 1 );
this.displacementMap = null;
this.displacementScale = 1;
this.displacementBias = 0;
this.alphaMap = null;
this.skinning = false;
this.morphTargets = false;
this.morphNormals = false;
this.setValues( parameters );
}
MeshMatcapMaterial.prototype = Object.create( Material.prototype );
MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
MeshMatcapMaterial.prototype.copy = function ( source ) {
Material.prototype.copy.call( this, source );
this.defines = { 'MATCAP': '' };
this.color.copy( source.color );
this.matcap = source.matcap;
this.map = source.map;
this.bumpMap = source.bumpMap;
this.bumpScale = source.bumpScale;
this.normalMap = source.normalMap;
this.normalMapType = source.normalMapType;
this.normalScale.copy( source.normalScale );
this.displacementMap = source.displacementMap;
this.displacementScale = source.displacementScale;
this.displacementBias = source.displacementBias;
this.alphaMap = source.alphaMap;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
this.morphNormals = source.morphNormals;
return this;
};
/**
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* color: <hex>,
* opacity: <float>,
*
* linewidth: <float>,
*
* scale: <float>,
* dashSize: <float>,
* gapSize: <float>
* }
*/
function LineDashedMaterial( parameters ) {
LineBasicMaterial.call( this );
this.type = 'LineDashedMaterial';
this.scale = 1;
this.dashSize = 3;
this.gapSize = 1;
this.setValues( parameters );
}
LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
LineDashedMaterial.prototype.constructor = LineDashedMaterial;
LineDashedMaterial.prototype.isLineDashedMaterial = true;
LineDashedMaterial.prototype.copy = function ( source ) {
LineBasicMaterial.prototype.copy.call( this, source );
this.scale = source.scale;
this.dashSize = source.dashSize;
this.gapSize = source.gapSize;
return this;
};
var Materials = /*#__PURE__*/Object.freeze({
__proto__: null,
ShadowMaterial: ShadowMaterial,
SpriteMaterial: SpriteMaterial,
RawShaderMaterial: RawShaderMaterial,
ShaderMaterial: ShaderMaterial,
PointsMaterial: PointsMaterial,
MeshPhysicalMaterial: MeshPhysicalMaterial,
MeshStandardMaterial: MeshStandardMaterial,
MeshPhongMaterial: MeshPhongMaterial,
MeshToonMaterial: MeshToonMaterial,
MeshNormalMaterial: MeshNormalMaterial,
MeshLambertMaterial: MeshLambertMaterial,
MeshDepthMaterial: MeshDepthMaterial,
MeshDistanceMaterial: MeshDistanceMaterial,
MeshBasicMaterial: MeshBasicMaterial,
MeshMatcapMaterial: MeshMatcapMaterial,
LineDashedMaterial: LineDashedMaterial,
LineBasicMaterial: LineBasicMaterial,
Material: Material
});
/**
* @author tschw
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
*/
var AnimationUtils = {
// same as Array.prototype.slice, but also works on typed arrays
arraySlice: function ( array, from, to ) {
if ( AnimationUtils.isTypedArray( array ) ) {
// in ios9 array.subarray(from, undefined) will return empty array
// but array.subarray(from) or array.subarray(from, len) is correct
return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
}
return array.slice( from, to );
},
// converts an array to a specific type
convertArray: function ( array, type, forceClone ) {
if ( ! array || // let 'undefined' and 'null' pass
! forceClone && array.constructor === type ) return array;
if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
return new type( array ); // create typed array
}
return Array.prototype.slice.call( array ); // create Array
},
isTypedArray: function ( object ) {
return ArrayBuffer.isView( object ) &&
! ( object instanceof DataView );
},
// returns an array by which times and values can be sorted
getKeyframeOrder: function ( times ) {
function compareTime( i, j ) {
return times[ i ] - times[ j ];
}
var n = times.length;
var result = new Array( n );
for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
result.sort( compareTime );
return result;
},
// uses the array previously returned by 'getKeyframeOrder' to sort data
sortedArray: function ( values, stride, order ) {
var nValues = values.length;
var result = new values.constructor( nValues );
for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
var srcOffset = order[ i ] * stride;
for ( var j = 0; j !== stride; ++ j ) {
result[ dstOffset ++ ] = values[ srcOffset + j ];
}
}
return result;
},
// function for parsing AOS keyframe formats
flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
var i = 1, key = jsonKeys[ 0 ];
while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
key = jsonKeys[ i ++ ];
}
if ( key === undefined ) return; // no data
var value = key[ valuePropertyName ];
if ( value === undefined ) return; // no data
if ( Array.isArray( value ) ) {
do {
value = key[ valuePropertyName ];
if ( value !== undefined ) {
times.push( key.time );
values.push.apply( values, value ); // push all elements
}
key = jsonKeys[ i ++ ];
} while ( key !== undefined );
} else if ( value.toArray !== undefined ) {
// ...assume THREE.Math-ish
do {
value = key[ valuePropertyName ];
if ( value !== undefined ) {
times.push( key.time );
value.toArray( values, values.length );
}
key = jsonKeys[ i ++ ];
} while ( key !== undefined );
} else {
// otherwise push as-is
do {
value = key[ valuePropertyName ];
if ( value !== undefined ) {
times.push( key.time );
values.push( value );
}
key = jsonKeys[ i ++ ];
} while ( key !== undefined );
}
},
subclip: function ( sourceClip, name, startFrame, endFrame, fps ) {
fps = fps || 30;
var clip = sourceClip.clone();
clip.name = name;
var tracks = [];
for ( var i = 0; i < clip.tracks.length; ++ i ) {
var track = clip.tracks[ i ];
var valueSize = track.getValueSize();
var times = [];
var values = [];
for ( var j = 0; j < track.times.length; ++ j ) {
var frame = track.times[ j ] * fps;
if ( frame < startFrame || frame >= endFrame ) continue;
times.push( track.times[ j ] );
for ( var k = 0; k < valueSize; ++ k ) {
values.push( track.values[ j * valueSize + k ] );
}
}
if ( times.length === 0 ) continue;
track.times = AnimationUtils.convertArray( times, track.times.constructor );
track.values = AnimationUtils.convertArray( values, track.values.constructor );
tracks.push( track );
}
clip.tracks = tracks;
// find minimum .times value across all tracks in the trimmed clip
var minStartTime = Infinity;
for ( var i = 0; i < clip.tracks.length; ++ i ) {
if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
minStartTime = clip.tracks[ i ].times[ 0 ];
}
}
// shift all tracks such that clip begins at t=0
for ( var i = 0; i < clip.tracks.length; ++ i ) {
clip.tracks[ i ].shift( - 1 * minStartTime );
}
clip.resetDuration();
return clip;
},
makeClipAdditive: function ( targetClip, referenceFrame, referenceClip, fps ) {
if ( referenceFrame === undefined ) referenceFrame = 0;
if ( referenceClip === undefined ) referenceClip = targetClip;
if ( fps === undefined || fps <= 0 ) fps = 30;
var numTracks = targetClip.tracks.length;
var referenceTime = referenceFrame / fps;
// Make each track's values relative to the values at the reference frame
for ( var i = 0; i < numTracks; ++ i ) {
var referenceTrack = referenceClip.tracks[ i ];
var referenceTrackType = referenceTrack.ValueTypeName;
// Skip this track if it's non-numeric
if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
// Find the track in the target clip whose name and type matches the reference track
var targetTrack = targetClip.tracks.find( function ( track ) {
return track.name === referenceTrack.name
&& track.ValueTypeName === referenceTrackType;
} );
if ( targetTrack === undefined ) continue;
var valueSize = referenceTrack.getValueSize();
var lastIndex = referenceTrack.times.length - 1;
var referenceValue;
// Find the value to subtract out of the track
if ( referenceTime <= referenceTrack.times[ 0 ] ) {
// Reference frame is earlier than the first keyframe, so just use the first keyframe
referenceValue = AnimationUtils.arraySlice( referenceTrack.values, 0, referenceTrack.valueSize );
} else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
// Reference frame is after the last keyframe, so just use the last keyframe
var startIndex = lastIndex * valueSize;
referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex );
} else {
// Interpolate to the reference value
var interpolant = referenceTrack.createInterpolant();
interpolant.evaluate( referenceTime );
referenceValue = interpolant.resultBuffer;
}
// Conjugate the quaternion
if ( referenceTrackType === 'quaternion' ) {
var referenceQuat = new Quaternion(
referenceValue[ 0 ],
referenceValue[ 1 ],
referenceValue[ 2 ],
referenceValue[ 3 ]
).normalize().conjugate();
referenceQuat.toArray( referenceValue );
}
// Subtract the reference value from all of the track values
var numTimes = targetTrack.times.length;
for ( var j = 0; j < numTimes; ++ j ) {
var valueStart = j * valueSize;
if ( referenceTrackType === 'quaternion' ) {
// Multiply the conjugate for quaternion track types
Quaternion.multiplyQuaternionsFlat(
targetTrack.values,
valueStart,
referenceValue,
0,
targetTrack.values,
valueStart
);
} else {
// Subtract each value for all other numeric track types
for ( var k = 0; k < valueSize; ++ k ) {
targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
}
}
}
}
targetClip.blendMode = AdditiveAnimationBlendMode;
return targetClip;
}
};
/**
* Abstract base class of interpolants over parametric samples.
*
* The parameter domain is one dimensional, typically the time or a path
* along a curve defined by the data.
*
* The sample values can have any dimensionality and derived classes may
* apply special interpretations to the data.
*
* This class provides the interval seek in a Template Method, deferring
* the actual interpolation to derived classes.
*
* Time complexity is O(1) for linear access crossing at most two points
* and O(log N) for random access, where N is the number of positions.
*
* References:
*
* http://www.oodesign.com/template-method-pattern.html
*
* @author tschw
*/
function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
this.parameterPositions = parameterPositions;
this._cachedIndex = 0;
this.resultBuffer = resultBuffer !== undefined ?
resultBuffer : new sampleValues.constructor( sampleSize );
this.sampleValues = sampleValues;
this.valueSize = sampleSize;
}
Object.assign( Interpolant.prototype, {
evaluate: function ( t ) {
var pp = this.parameterPositions,
i1 = this._cachedIndex,
t1 = pp[ i1 ],
t0 = pp[ i1 - 1 ];
validate_interval: {
seek: {
var right;
linear_scan: {
//- See http://jsperf.com/comparison-to-undefined/3
//- slower code:
//-
//- if ( t >= t1 || t1 === undefined ) {
forward_scan: if ( ! ( t < t1 ) ) {
for ( var giveUpAt = i1 + 2; ; ) {
if ( t1 === undefined ) {
if ( t < t0 ) break forward_scan;
// after end
i1 = pp.length;
this._cachedIndex = i1;
return this.afterEnd_( i1 - 1, t, t0 );
}
if ( i1 === giveUpAt ) break; // this loop
t0 = t1;
t1 = pp[ ++ i1 ];
if ( t < t1 ) {
// we have arrived at the sought interval
break seek;
}
}
// prepare binary search on the right side of the index
right = pp.length;
break linear_scan;
}
//- slower code:
//- if ( t < t0 || t0 === undefined ) {
if ( ! ( t >= t0 ) ) {
// looping?
var t1global = pp[ 1 ];
if ( t < t1global ) {
i1 = 2; // + 1, using the scan for the details
t0 = t1global;
}
// linear reverse scan
for ( var giveUpAt = i1 - 2; ; ) {
if ( t0 === undefined ) {
// before start
this._cachedIndex = 0;
return this.beforeStart_( 0, t, t1 );
}
if ( i1 === giveUpAt ) break; // this loop
t1 = t0;
t0 = pp[ -- i1 - 1 ];
if ( t >= t0 ) {
// we have arrived at the sought interval
break seek;
}
}
// prepare binary search on the left side of the index
right = i1;
i1 = 0;
break linear_scan;
}
// the interval is valid
break validate_interval;
} // linear scan
// binary search
while ( i1 < right ) {
var mid = ( i1 + right ) >>> 1;
if ( t < pp[ mid ] ) {
right = mid;
} else {
i1 = mid + 1;
}
}
t1 = pp[ i1 ];
t0 = pp[ i1 - 1 ];
// check boundary cases, again
if ( t0 === undefined ) {
this._cachedIndex = 0;
return this.beforeStart_( 0, t, t1 );
}
if ( t1 === undefined ) {
i1 = pp.length;
this._cachedIndex = i1;
return this.afterEnd_( i1 - 1, t0, t );
}
} // seek
this._cachedIndex = i1;
this.intervalChanged_( i1, t0, t1 );
} // validate_interval
return this.interpolate_( i1, t0, t, t1 );
},
settings: null, // optional, subclass-specific settings structure
// Note: The indirection allows central control of many interpolants.
// --- Protected interface
DefaultSettings_: {},
getSettings_: function () {
return this.settings || this.DefaultSettings_;
},
copySampleValue_: function ( index ) {
// copies a sample value to the result buffer
var result = this.resultBuffer,
values = this.sampleValues,
stride = this.valueSize,
offset = index * stride;
for ( var i = 0; i !== stride; ++ i ) {
result[ i ] = values[ offset + i ];
}
return result;
},
// Template methods for derived classes:
interpolate_: function ( /* i1, t0, t, t1 */ ) {
throw new Error( 'call to abstract method' );
// implementations shall return this.resultBuffer
},
intervalChanged_: function ( /* i1, t0, t1 */ ) {
// empty
}
} );
// DECLARE ALIAS AFTER assign prototype
Object.assign( Interpolant.prototype, {
//( 0, t, t0 ), returns this.resultBuffer
beforeStart_: Interpolant.prototype.copySampleValue_,
//( N-1, tN-1, t ), returns this.resultBuffer
afterEnd_: Interpolant.prototype.copySampleValue_,
} );
/**
* Fast and simple cubic spline interpolant.
*
* It was derived from a Hermitian construction setting the first derivative
* at each sample position to the linear slope between neighboring positions
* over their parameter interval.
*
* @author tschw
*/
function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
this._weightPrev = - 0;
this._offsetPrev = - 0;
this._weightNext = - 0;
this._offsetNext = - 0;
}
CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
constructor: CubicInterpolant,
DefaultSettings_: {
endingStart: ZeroCurvatureEnding,
endingEnd: ZeroCurvatureEnding
},
intervalChanged_: function ( i1, t0, t1 ) {
var pp = this.parameterPositions,
iPrev = i1 - 2,
iNext = i1 + 1,
tPrev = pp[ iPrev ],
tNext = pp[ iNext ];
if ( tPrev === undefined ) {
switch ( this.getSettings_().endingStart ) {
case ZeroSlopeEnding:
// f'(t0) = 0
iPrev = i1;
tPrev = 2 * t0 - t1;
break;
case WrapAroundEnding:
// use the other end of the curve
iPrev = pp.length - 2;
tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
break;
default: // ZeroCurvatureEnding
// f''(t0) = 0 a.k.a. Natural Spline
iPrev = i1;
tPrev = t1;
}
}
if ( tNext === undefined ) {
switch ( this.getSettings_().endingEnd ) {
case ZeroSlopeEnding:
// f'(tN) = 0
iNext = i1;
tNext = 2 * t1 - t0;
break;
case WrapAroundEnding:
// use the other end of the curve
iNext = 1;
tNext = t1 + pp[ 1 ] - pp[ 0 ];
break;
default: // ZeroCurvatureEnding
// f''(tN) = 0, a.k.a. Natural Spline
iNext = i1 - 1;
tNext = t0;
}
}
var halfDt = ( t1 - t0 ) * 0.5,
stride = this.valueSize;
this._weightPrev = halfDt / ( t0 - tPrev );
this._weightNext = halfDt / ( tNext - t1 );
this._offsetPrev = iPrev * stride;
this._offsetNext = iNext * stride;
},
interpolate_: function ( i1, t0, t, t1 ) {
var result = this.resultBuffer,
values = this.sampleValues,
stride = this.valueSize,
o1 = i1 * stride, o0 = o1 - stride,
oP = this._offsetPrev, oN = this._offsetNext,
wP = this._weightPrev, wN = this._weightNext,
p = ( t - t0 ) / ( t1 - t0 ),
pp = p * p,
ppp = pp * p;
// evaluate polynomials
var sP = - wP * ppp + 2 * wP * pp - wP * p;
var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
var sN = wN * ppp - wN * pp;
// combine data linearly
for ( var i = 0; i !== stride; ++ i ) {
result[ i ] =
sP * values[ oP + i ] +
s0 * values[ o0 + i ] +
s1 * values[ o1 + i ] +
sN * values[ oN + i ];
}
return result;
}
} );
/**
* @author tschw
*/
function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
}
LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
constructor: LinearInterpolant,
interpolate_: function ( i1, t0, t, t1 ) {
var result = this.resultBuffer,
values = this.sampleValues,
stride = this.valueSize,
offset1 = i1 * stride,
offset0 = offset1 - stride,
weight1 = ( t - t0 ) / ( t1 - t0 ),
weight0 = 1 - weight1;
for ( var i = 0; i !== stride; ++ i ) {
result[ i ] =
values[ offset0 + i ] * weight0 +
values[ offset1 + i ] * weight1;
}
return result;
}
} );
/**
*
* Interpolant that evaluates to the sample value at the position preceeding
* the parameter.
*
* @author tschw
*/
function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
}
DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
constructor: DiscreteInterpolant,
interpolate_: function ( i1 /*, t0, t, t1 */ ) {
return this.copySampleValue_( i1 - 1 );
}
} );
/**
*
* A timed sequence of keyframes for a specific property.
*
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*/
function KeyframeTrack( name, times, values, interpolation ) {
if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
this.name = name;
this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
this.setInterpolation( interpolation || this.DefaultInterpolation );
}
// Static methods
Object.assign( KeyframeTrack, {
// Serialization (in static context, because of constructor invocation
// and automatic invocation of .toJSON):
toJSON: function ( track ) {
var trackType = track.constructor;
var json;
// derived classes can define a static toJSON method
if ( trackType.toJSON !== undefined ) {
json = trackType.toJSON( track );
} else {
// by default, we assume the data can be serialized as-is
json = {
'name': track.name,
'times': AnimationUtils.convertArray( track.times, Array ),
'values': AnimationUtils.convertArray( track.values, Array )
};
var interpolation = track.getInterpolation();
if ( interpolation !== track.DefaultInterpolation ) {
json.interpolation = interpolation;
}
}
json.type = track.ValueTypeName; // mandatory
return json;
}
} );
Object.assign( KeyframeTrack.prototype, {
constructor: KeyframeTrack,
TimeBufferType: Float32Array,
ValueBufferType: Float32Array,
DefaultInterpolation: InterpolateLinear,
InterpolantFactoryMethodDiscrete: function ( result ) {
return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
},
InterpolantFactoryMethodLinear: function ( result ) {
return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
},
InterpolantFactoryMethodSmooth: function ( result ) {
return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
},
setInterpolation: function ( interpolation ) {
var factoryMethod;
switch ( interpolation ) {
case InterpolateDiscrete:
factoryMethod = this.InterpolantFactoryMethodDiscrete;
break;
case InterpolateLinear:
factoryMethod = this.InterpolantFactoryMethodLinear;
break;
case InterpolateSmooth:
factoryMethod = this.InterpolantFactoryMethodSmooth;
break;
}
if ( factoryMethod === undefined ) {
var message = "unsupported interpolation for " +
this.ValueTypeName + " keyframe track named " + this.name;
if ( this.createInterpolant === undefined ) {
// fall back to default, unless the default itself is messed up
if ( interpolation !== this.DefaultInterpolation ) {
this.setInterpolation( this.DefaultInterpolation );
} else {
throw new Error( message ); // fatal, in this case
}
}
console.warn( 'THREE.KeyframeTrack:', message );
return this;
}
this.createInterpolant = factoryMethod;
return this;
},
getInterpolation: function () {
switch ( this.createInterpolant ) {
case this.InterpolantFactoryMethodDiscrete:
return InterpolateDiscrete;
case this.InterpolantFactoryMethodLinear:
return InterpolateLinear;
case this.InterpolantFactoryMethodSmooth:
return InterpolateSmooth;
}
},
getValueSize: function () {
return this.values.length / this.times.length;
},
// move all keyframes either forwards or backwards in time
shift: function ( timeOffset ) {
if ( timeOffset !== 0.0 ) {
var times = this.times;
for ( var i = 0, n = times.length; i !== n; ++ i ) {
times[ i ] += timeOffset;
}
}
return this;
},
// scale all keyframe times by a factor (useful for frame <-> seconds conversions)
scale: function ( timeScale ) {
if ( timeScale !== 1.0 ) {
var times = this.times;
for ( var i = 0, n = times.length; i !== n; ++ i ) {
times[ i ] *= timeScale;
}
}
return this;
},
// removes keyframes before and after animation without changing any values within the range [startTime, endTime].
// IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
trim: function ( startTime, endTime ) {
var times = this.times,
nKeys = times.length,
from = 0,
to = nKeys - 1;
while ( from !== nKeys && times[ from ] < startTime ) {
++ from;
}
while ( to !== - 1 && times[ to ] > endTime ) {
-- to;
}
++ to; // inclusive -> exclusive bound
if ( from !== 0 || to !== nKeys ) {
// empty tracks are forbidden, so keep at least one keyframe
if ( from >= to ) {
to = Math.max( to, 1 );
from = to - 1;
}
var stride = this.getValueSize();
this.times = AnimationUtils.arraySlice( times, from, to );
this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
}
return this;
},
// ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
validate: function () {
var valid = true;
var valueSize = this.getValueSize();
if ( valueSize - Math.floor( valueSize ) !== 0 ) {
console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
valid = false;
}
var times = this.times,
values = this.values,
nKeys = times.length;
if ( nKeys === 0 ) {
console.error( 'THREE.KeyframeTrack: Track is empty.', this );
valid = false;
}
var prevTime = null;
for ( var i = 0; i !== nKeys; i ++ ) {
var currTime = times[ i ];
if ( typeof currTime === 'number' && isNaN( currTime ) ) {
console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
valid = false;
break;
}
if ( prevTime !== null && prevTime > currTime ) {
console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
valid = false;
break;
}
prevTime = currTime;
}
if ( values !== undefined ) {
if ( AnimationUtils.isTypedArray( values ) ) {
for ( var i = 0, n = values.length; i !== n; ++ i ) {
var value = values[ i ];
if ( isNaN( value ) ) {
console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
valid = false;
break;
}
}
}
}
return valid;
},
// removes equivalent sequential keys as common in morph target sequences
// (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
optimize: function () {
// times or values may be shared with other tracks, so overwriting is unsafe
var times = AnimationUtils.arraySlice( this.times ),
values = AnimationUtils.arraySlice( this.values ),
stride = this.getValueSize(),
smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
writeIndex = 1,
lastIndex = times.length - 1;
for ( var i = 1; i < lastIndex; ++ i ) {
var keep = false;
var time = times[ i ];
var timeNext = times[ i + 1 ];
// remove adjacent keyframes scheduled at the same time
if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
if ( ! smoothInterpolation ) {
// remove unnecessary keyframes same as their neighbors
var offset = i * stride,
offsetP = offset - stride,
offsetN = offset + stride;
for ( var j = 0; j !== stride; ++ j ) {
var value = values[ offset + j ];
if ( value !== values[ offsetP + j ] ||
value !== values[ offsetN + j ] ) {
keep = true;
break;
}
}
} else {
keep = true;
}
}
// in-place compaction
if ( keep ) {
if ( i !== writeIndex ) {
times[ writeIndex ] = times[ i ];
var readOffset = i * stride,
writeOffset = writeIndex * stride;
for ( var j = 0; j !== stride; ++ j ) {
values[ writeOffset + j ] = values[ readOffset + j ];
}
}
++ writeIndex;
}
}
// flush last keyframe (compaction looks ahead)
if ( lastIndex > 0 ) {
times[ writeIndex ] = times[ lastIndex ];
for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
values[ writeOffset + j ] = values[ readOffset + j ];
}
++ writeIndex;
}
if ( writeIndex !== times.length ) {
this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
} else {
this.times = times;
this.values = values;
}
return this;
},
clone: function () {
var times = AnimationUtils.arraySlice( this.times, 0 );
var values = AnimationUtils.arraySlice( this.values, 0 );
var TypedKeyframeTrack = this.constructor;
var track = new TypedKeyframeTrack( this.name, times, values );
// Interpolant argument to constructor is not saved, so copy the factory method directly.
track.createInterpolant = this.createInterpolant;
return track;
}
} );
/**
*
* A Track of Boolean keyframe values.
*
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*/
function BooleanKeyframeTrack( name, times, values ) {
KeyframeTrack.call( this, name, times, values );
}
BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
constructor: BooleanKeyframeTrack,
ValueTypeName: 'bool',
ValueBufferType: Array,
DefaultInterpolation: InterpolateDiscrete,
InterpolantFactoryMethodLinear: undefined,
InterpolantFactoryMethodSmooth: undefined
// Note: Actually this track could have a optimized / compressed
// representation of a single value and a custom interpolant that
// computes "firstValue ^ isOdd( index )".
} );
/**
*
* A Track of keyframe values that represent color.
*
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*/
function ColorKeyframeTrack( name, times, values, interpolation ) {
KeyframeTrack.call( this, name, times, values, interpolation );
}
ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
constructor: ColorKeyframeTrack,
ValueTypeName: 'color'
// ValueBufferType is inherited
// DefaultInterpolation is inherited
// Note: Very basic implementation and nothing special yet.
// However, this is the place for color space parameterization.
} );
/**
*
* A Track of numeric keyframe values.
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*/
function NumberKeyframeTrack( name, times, values, interpolation ) {
KeyframeTrack.call( this, name, times, values, interpolation );
}
NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
constructor: NumberKeyframeTrack,
ValueTypeName: 'number'
// ValueBufferType is inherited
// DefaultInterpolation is inherited
} );
/**
* Spherical linear unit quaternion interpolant.
*
* @author tschw
*/
function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
}
QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
constructor: QuaternionLinearInterpolant,
interpolate_: function ( i1, t0, t, t1 ) {
var result = this.resultBuffer,
values = this.sampleValues,
stride = this.valueSize,
offset = i1 * stride,
alpha = ( t - t0 ) / ( t1 - t0 );
for ( var end = offset + stride; offset !== end; offset += 4 ) {
Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
}
return result;
}
} );
/**
*
* A Track of quaternion keyframe values.
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*/
function QuaternionKeyframeTrack( name, times, values, interpolation ) {
KeyframeTrack.call( this, name, times, values, interpolation );
}
QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
constructor: QuaternionKeyframeTrack,
ValueTypeName: 'quaternion',
// ValueBufferType is inherited
DefaultInterpolation: InterpolateLinear,
InterpolantFactoryMethodLinear: function ( result ) {
return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
},
InterpolantFactoryMethodSmooth: undefined // not yet implemented
} );
/**
*
* A Track that interpolates Strings
*
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*/
function StringKeyframeTrack( name, times, values, interpolation ) {
KeyframeTrack.call( this, name, times, values, interpolation );
}
StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
constructor: StringKeyframeTrack,
ValueTypeName: 'string',
ValueBufferType: Array,
DefaultInterpolation: InterpolateDiscrete,
InterpolantFactoryMethodLinear: undefined,
InterpolantFactoryMethodSmooth: undefined
} );
/**
*
* A Track of vectored keyframe values.
*
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*/
function VectorKeyframeTrack( name, times, values, interpolation ) {
KeyframeTrack.call( this, name, times, values, interpolation );
}
VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
constructor: VectorKeyframeTrack,
ValueTypeName: 'vector'
// ValueBufferType is inherited
// DefaultInterpolation is inherited
} );
/**
*
* Reusable set of Tracks that represent an animation.
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
*/
function AnimationClip( name, duration, tracks, blendMode ) {
this.name = name;
this.tracks = tracks;
this.duration = ( duration !== undefined ) ? duration : - 1;
this.blendMode = ( blendMode !== undefined ) ? blendMode : NormalAnimationBlendMode;
this.uuid = MathUtils.generateUUID();
// this means it should figure out its duration by scanning the tracks
if ( this.duration < 0 ) {
this.resetDuration();
}
}
function getTrackTypeForValueTypeName( typeName ) {
switch ( typeName.toLowerCase() ) {
case 'scalar':
case 'double':
case 'float':
case 'number':
case 'integer':
return NumberKeyframeTrack;
case 'vector':
case 'vector2':
case 'vector3':
case 'vector4':
return VectorKeyframeTrack;
case 'color':
return ColorKeyframeTrack;
case 'quaternion':
return QuaternionKeyframeTrack;
case 'bool':
case 'boolean':
return BooleanKeyframeTrack;
case 'string':
return StringKeyframeTrack;
}
throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
}
function parseKeyframeTrack( json ) {
if ( json.type === undefined ) {
throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
}
var trackType = getTrackTypeForValueTypeName( json.type );
if ( json.times === undefined ) {
var times = [], values = [];
AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
json.times = times;
json.values = values;
}
// derived classes can define a static parse method
if ( trackType.parse !== undefined ) {
return trackType.parse( json );
} else {
// by default, we assume a constructor compatible with the base
return new trackType( json.name, json.times, json.values, json.interpolation );
}
}
Object.assign( AnimationClip, {
parse: function ( json ) {
var tracks = [],
jsonTracks = json.tracks,
frameTime = 1.0 / ( json.fps || 1.0 );
for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
}
return new AnimationClip( json.name, json.duration, tracks, json.blendMode );
},
toJSON: function ( clip ) {
var tracks = [],
clipTracks = clip.tracks;
var json = {
'name': clip.name,
'duration': clip.duration,
'tracks': tracks,
'uuid': clip.uuid,
'blendMode': clip.blendMode
};
for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
}
return json;
},
CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
var numMorphTargets = morphTargetSequence.length;
var tracks = [];
for ( var i = 0; i < numMorphTargets; i ++ ) {
var times = [];
var values = [];
times.push(
( i + numMorphTargets - 1 ) % numMorphTargets,
i,
( i + 1 ) % numMorphTargets );
values.push( 0, 1, 0 );
var order = AnimationUtils.getKeyframeOrder( times );
times = AnimationUtils.sortedArray( times, 1, order );
values = AnimationUtils.sortedArray( values, 1, order );
// if there is a key at the first frame, duplicate it as the
// last frame as well for perfect loop.
if ( ! noLoop && times[ 0 ] === 0 ) {
times.push( numMorphTargets );
values.push( values[ 0 ] );
}
tracks.push(
new NumberKeyframeTrack(
'.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
times, values
).scale( 1.0 / fps ) );
}
return new AnimationClip( name, - 1, tracks );
},
findByName: function ( objectOrClipArray, name ) {
var clipArray = objectOrClipArray;
if ( ! Array.isArray( objectOrClipArray ) ) {
var o = objectOrClipArray;
clipArray = o.geometry && o.geometry.animations || o.animations;
}
for ( var i = 0; i < clipArray.length; i ++ ) {
if ( clipArray[ i ].name === name ) {
return clipArray[ i ];
}
}
return null;
},
CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
var animationToMorphTargets = {};
// tested with https://regex101.com/ on trick sequences
// such flamingo_flyA_003, flamingo_run1_003, crdeath0059
var pattern = /^([\w-]*?)([\d]+)$/;
// sort morph target names into animation groups based
// patterns like Walk_001, Walk_002, Run_001, Run_002
for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
var morphTarget = morphTargets[ i ];
var parts = morphTarget.name.match( pattern );
if ( parts && parts.length > 1 ) {
var name = parts[ 1 ];
var animationMorphTargets = animationToMorphTargets[ name ];
if ( ! animationMorphTargets ) {
animationToMorphTargets[ name ] = animationMorphTargets = [];
}
animationMorphTargets.push( morphTarget );
}
}
var clips = [];
for ( var name in animationToMorphTargets ) {
clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
}
return clips;
},
// parse the animation.hierarchy format
parseAnimation: function ( animation, bones ) {
if ( ! animation ) {
console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
return null;
}
var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
// only return track if there are actually keys.
if ( animationKeys.length !== 0 ) {
var times = [];
var values = [];
AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
// empty keys are filtered out, so check again
if ( times.length !== 0 ) {
destTracks.push( new trackType( trackName, times, values ) );
}
}
};
var tracks = [];
var clipName = animation.name || 'default';
// automatic length determination in AnimationClip.
var duration = animation.length || - 1;
var fps = animation.fps || 30;
var blendMode = animation.blendMode;
var hierarchyTracks = animation.hierarchy || [];
for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
var animationKeys = hierarchyTracks[ h ].keys;
// skip empty tracks
if ( ! animationKeys || animationKeys.length === 0 ) continue;
// process morph targets
if ( animationKeys[ 0 ].morphTargets ) {
// figure out all morph targets used in this track
var morphTargetNames = {};
for ( var k = 0; k < animationKeys.length; k ++ ) {
if ( animationKeys[ k ].morphTargets ) {
for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
}
}
}
// create a track for each morph target with all zero
// morphTargetInfluences except for the keys in which
// the morphTarget is named.
for ( var morphTargetName in morphTargetNames ) {
var times = [];
var values = [];
for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
var animationKey = animationKeys[ k ];
times.push( animationKey.time );
values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
}
tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
}
duration = morphTargetNames.length * ( fps || 1.0 );
} else {
// ...assume skeletal animation
var boneName = '.bones[' + bones[ h ].name + ']';
addNonemptyTrack(
VectorKeyframeTrack, boneName + '.position',
animationKeys, 'pos', tracks );
addNonemptyTrack(
QuaternionKeyframeTrack, boneName + '.quaternion',
animationKeys, 'rot', tracks );
addNonemptyTrack(
VectorKeyframeTrack, boneName + '.scale',
animationKeys, 'scl', tracks );
}
}
if ( tracks.length === 0 ) {
return null;
}
var clip = new AnimationClip( clipName, duration, tracks, blendMode );
return clip;
}
} );
Object.assign( AnimationClip.prototype, {
resetDuration: function () {
var tracks = this.tracks, duration = 0;
for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
var track = this.tracks[ i ];
duration = Math.max( duration, track.times[ track.times.length - 1 ] );
}
this.duration = duration;
return this;
},
trim: function () {
for ( var i = 0; i < this.tracks.length; i ++ ) {
this.tracks[ i ].trim( 0, this.duration );
}
return this;
},
validate: function () {
var valid = true;
for ( var i = 0; i < this.tracks.length; i ++ ) {
valid = valid && this.tracks[ i ].validate();
}
return valid;
},
optimize: function () {
for ( var i = 0; i < this.tracks.length; i ++ ) {
this.tracks[ i ].optimize();
}
return this;
},
clone: function () {
var tracks = [];
for ( var i = 0; i < this.tracks.length; i ++ ) {
tracks.push( this.tracks[ i ].clone() );
}
return new AnimationClip( this.name, this.duration, tracks, this.blendMode );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
var Cache = {
enabled: false,
files: {},
add: function ( key, file ) {
if ( this.enabled === false ) return;
// console.log( 'THREE.Cache', 'Adding key:', key );
this.files[ key ] = file;
},
get: function ( key ) {
if ( this.enabled === false ) return;
// console.log( 'THREE.Cache', 'Checking key:', key );
return this.files[ key ];
},
remove: function ( key ) {
delete this.files[ key ];
},
clear: function () {
this.files = {};
}
};
/**
* @author mrdoob / http://mrdoob.com/
*/
function LoadingManager( onLoad, onProgress, onError ) {
var scope = this;
var isLoading = false;
var itemsLoaded = 0;
var itemsTotal = 0;
var urlModifier = undefined;
var handlers = [];
// Refer to #5689 for the reason why we don't set .onStart
// in the constructor
this.onStart = undefined;
this.onLoad = onLoad;
this.onProgress = onProgress;
this.onError = onError;
this.itemStart = function ( url ) {
itemsTotal ++;
if ( isLoading === false ) {
if ( scope.onStart !== undefined ) {
scope.onStart( url, itemsLoaded, itemsTotal );
}
}
isLoading = true;
};
this.itemEnd = function ( url ) {
itemsLoaded ++;
if ( scope.onProgress !== undefined ) {
scope.onProgress( url, itemsLoaded, itemsTotal );
}
if ( itemsLoaded === itemsTotal ) {
isLoading = false;
if ( scope.onLoad !== undefined ) {
scope.onLoad();
}
}
};
this.itemError = function ( url ) {
if ( scope.onError !== undefined ) {
scope.onError( url );
}
};
this.resolveURL = function ( url ) {
if ( urlModifier ) {
return urlModifier( url );
}
return url;
};
this.setURLModifier = function ( transform ) {
urlModifier = transform;
return this;
};
this.addHandler = function ( regex, loader ) {
handlers.push( regex, loader );
return this;
};
this.removeHandler = function ( regex ) {
var index = handlers.indexOf( regex );
if ( index !== - 1 ) {
handlers.splice( index, 2 );
}
return this;
};
this.getHandler = function ( file ) {
for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
var regex = handlers[ i ];
var loader = handlers[ i + 1 ];
if ( regex.global ) regex.lastIndex = 0; // see #17920
if ( regex.test( file ) ) {
return loader;
}
}
return null;
};
}
var DefaultLoadingManager = new LoadingManager();
/**
* @author alteredq / http://alteredqualia.com/
*/
function Loader( manager ) {
this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
this.crossOrigin = 'anonymous';
this.path = '';
this.resourcePath = '';
}
Object.assign( Loader.prototype, {
load: function ( /* url, onLoad, onProgress, onError */ ) {},
loadAsync: function ( url, onProgress ) {
var scope = this;
return new Promise( function ( resolve, reject ) {
scope.load( url, resolve, onProgress, reject );
} );
},
parse: function ( /* data */ ) {},
setCrossOrigin: function ( crossOrigin ) {
this.crossOrigin = crossOrigin;
return this;
},
setPath: function ( path ) {
this.path = path;
return this;
},
setResourcePath: function ( resourcePath ) {
this.resourcePath = resourcePath;
return this;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
var loading = {};
function FileLoader( manager ) {
Loader.call( this, manager );
}
FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: FileLoader,
load: function ( url, onLoad, onProgress, onError ) {
if ( url === undefined ) url = '';
if ( this.path !== undefined ) url = this.path + url;
url = this.manager.resolveURL( url );
var scope = this;
var cached = Cache.get( url );
if ( cached !== undefined ) {
scope.manager.itemStart( url );
setTimeout( function () {
if ( onLoad ) onLoad( cached );
scope.manager.itemEnd( url );
}, 0 );
return cached;
}
// Check if request is duplicate
if ( loading[ url ] !== undefined ) {
loading[ url ].push( {
onLoad: onLoad,
onProgress: onProgress,
onError: onError
} );
return;
}
// Check for data: URI
var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
var dataUriRegexResult = url.match( dataUriRegex );
// Safari can not handle Data URIs through XMLHttpRequest so process manually
if ( dataUriRegexResult ) {
var mimeType = dataUriRegexResult[ 1 ];
var isBase64 = !! dataUriRegexResult[ 2 ];
var data = dataUriRegexResult[ 3 ];
data = decodeURIComponent( data );
if ( isBase64 ) data = atob( data );
try {
var response;
var responseType = ( this.responseType || '' ).toLowerCase();
switch ( responseType ) {
case 'arraybuffer':
case 'blob':
var view = new Uint8Array( data.length );
for ( var i = 0; i < data.length; i ++ ) {
view[ i ] = data.charCodeAt( i );
}
if ( responseType === 'blob' ) {
response = new Blob( [ view.buffer ], { type: mimeType } );
} else {
response = view.buffer;
}
break;
case 'document':
var parser = new DOMParser();
response = parser.parseFromString( data, mimeType );
break;
case 'json':
response = JSON.parse( data );
break;
default: // 'text' or other
response = data;
break;
}
// Wait for next browser tick like standard XMLHttpRequest event dispatching does
setTimeout( function () {
if ( onLoad ) onLoad( response );
scope.manager.itemEnd( url );
}, 0 );
} catch ( error ) {
// Wait for next browser tick like standard XMLHttpRequest event dispatching does
setTimeout( function () {
if ( onError ) onError( error );
scope.manager.itemError( url );
scope.manager.itemEnd( url );
}, 0 );
}
} else {
// Initialise array for duplicate requests
loading[ url ] = [];
loading[ url ].push( {
onLoad: onLoad,
onProgress: onProgress,
onError: onError
} );
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var response = this.response;
var callbacks = loading[ url ];
delete loading[ url ];
if ( this.status === 200 || this.status === 0 ) {
// Some browsers return HTTP Status 0 when using non-http protocol
// e.g. 'file://' or 'data://'. Handle as success.
if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
// Add to cache only on HTTP success, so that we do not cache
// error response bodies as proper responses to requests.
Cache.add( url, response );
for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
var callback = callbacks[ i ];
if ( callback.onLoad ) callback.onLoad( response );
}
scope.manager.itemEnd( url );
} else {
for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
var callback = callbacks[ i ];
if ( callback.onError ) callback.onError( event );
}
scope.manager.itemError( url );
scope.manager.itemEnd( url );
}
}, false );
request.addEventListener( 'progress', function ( event ) {
var callbacks = loading[ url ];
for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
var callback = callbacks[ i ];
if ( callback.onProgress ) callback.onProgress( event );
}
}, false );
request.addEventListener( 'error', function ( event ) {
var callbacks = loading[ url ];
delete loading[ url ];
for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
var callback = callbacks[ i ];
if ( callback.onError ) callback.onError( event );
}
scope.manager.itemError( url );
scope.manager.itemEnd( url );
}, false );
request.addEventListener( 'abort', function ( event ) {
var callbacks = loading[ url ];
delete loading[ url ];
for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
var callback = callbacks[ i ];
if ( callback.onError ) callback.onError( event );
}
scope.manager.itemError( url );
scope.manager.itemEnd( url );
}, false );
if ( this.responseType !== undefined ) request.responseType = this.responseType;
if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
for ( var header in this.requestHeader ) {
request.setRequestHeader( header, this.requestHeader[ header ] );
}
request.send( null );
}
scope.manager.itemStart( url );
return request;
},
setResponseType: function ( value ) {
this.responseType = value;
return this;
},
setWithCredentials: function ( value ) {
this.withCredentials = value;
return this;
},
setMimeType: function ( value ) {
this.mimeType = value;
return this;
},
setRequestHeader: function ( value ) {
this.requestHeader = value;
return this;
}
} );
/**
* @author bhouston / http://clara.io/
*/
function AnimationLoader( manager ) {
Loader.call( this, manager );
}
AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: AnimationLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new FileLoader( scope.manager );
loader.setPath( scope.path );
loader.load( url, function ( text ) {
onLoad( scope.parse( JSON.parse( text ) ) );
}, onProgress, onError );
},
parse: function ( json ) {
var animations = [];
for ( var i = 0; i < json.length; i ++ ) {
var clip = AnimationClip.parse( json[ i ] );
animations.push( clip );
}
return animations;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*
* Abstract Base class to block based textures loader (dds, pvr, ...)
*
* Sub classes have to implement the parse() method which will be used in load().
*/
function CompressedTextureLoader( manager ) {
Loader.call( this, manager );
}
CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: CompressedTextureLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var images = [];
var texture = new CompressedTexture();
texture.image = images;
var loader = new FileLoader( this.manager );
loader.setPath( this.path );
loader.setResponseType( 'arraybuffer' );
function loadTexture( i ) {
loader.load( url[ i ], function ( buffer ) {
var texDatas = scope.parse( buffer, true );
images[ i ] = {
width: texDatas.width,
height: texDatas.height,
format: texDatas.format,
mipmaps: texDatas.mipmaps
};
loaded += 1;
if ( loaded === 6 ) {
if ( texDatas.mipmapCount === 1 )
texture.minFilter = LinearFilter;
texture.format = texDatas.format;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}
}, onProgress, onError );
}
if ( Array.isArray( url ) ) {
var loaded = 0;
for ( var i = 0, il = url.length; i < il; ++ i ) {
loadTexture( i );
}
} else {
// compressed cubemap texture stored in a single DDS file
loader.load( url, function ( buffer ) {
var texDatas = scope.parse( buffer, true );
if ( texDatas.isCubemap ) {
var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
for ( var f = 0; f < faces; f ++ ) {
images[ f ] = { mipmaps: [] };
for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
images[ f ].format = texDatas.format;
images[ f ].width = texDatas.width;
images[ f ].height = texDatas.height;
}
}
} else {
texture.image.width = texDatas.width;
texture.image.height = texDatas.height;
texture.mipmaps = texDatas.mipmaps;
}
if ( texDatas.mipmapCount === 1 ) {
texture.minFilter = LinearFilter;
}
texture.format = texDatas.format;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}, onProgress, onError );
}
return texture;
}
} );
/**
* @author Nikos M. / https://github.com/foo123/
*
* Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
*
* Sub classes have to implement the parse() method which will be used in load().
*/
function DataTextureLoader( manager ) {
Loader.call( this, manager );
}
DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: DataTextureLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var texture = new DataTexture();
var loader = new FileLoader( this.manager );
loader.setResponseType( 'arraybuffer' );
loader.setPath( this.path );
loader.load( url, function ( buffer ) {
var texData = scope.parse( buffer );
if ( ! texData ) return;
if ( texData.image !== undefined ) {
texture.image = texData.image;
} else if ( texData.data !== undefined ) {
texture.image.width = texData.width;
texture.image.height = texData.height;
texture.image.data = texData.data;
}
texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
if ( texData.format !== undefined ) {
texture.format = texData.format;
}
if ( texData.type !== undefined ) {
texture.type = texData.type;
}
if ( texData.mipmaps !== undefined ) {
texture.mipmaps = texData.mipmaps;
texture.minFilter = LinearMipmapLinearFilter; // presumably...
}
if ( texData.mipmapCount === 1 ) {
texture.minFilter = LinearFilter;
}
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture, texData );
}, onProgress, onError );
return texture;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function ImageLoader( manager ) {
Loader.call( this, manager );
}
ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: ImageLoader,
load: function ( url, onLoad, onProgress, onError ) {
if ( this.path !== undefined ) url = this.path + url;
url = this.manager.resolveURL( url );
var scope = this;
var cached = Cache.get( url );
if ( cached !== undefined ) {
scope.manager.itemStart( url );
setTimeout( function () {
if ( onLoad ) onLoad( cached );
scope.manager.itemEnd( url );
}, 0 );
return cached;
}
var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
function onImageLoad() {
image.removeEventListener( 'load', onImageLoad, false );
image.removeEventListener( 'error', onImageError, false );
Cache.add( url, this );
if ( onLoad ) onLoad( this );
scope.manager.itemEnd( url );
}
function onImageError( event ) {
image.removeEventListener( 'load', onImageLoad, false );
image.removeEventListener( 'error', onImageError, false );
if ( onError ) onError( event );
scope.manager.itemError( url );
scope.manager.itemEnd( url );
}
image.addEventListener( 'load', onImageLoad, false );
image.addEventListener( 'error', onImageError, false );
if ( url.substr( 0, 5 ) !== 'data:' ) {
if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
}
scope.manager.itemStart( url );
image.src = url;
return image;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function CubeTextureLoader( manager ) {
Loader.call( this, manager );
}
CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: CubeTextureLoader,
load: function ( urls, onLoad, onProgress, onError ) {
var texture = new CubeTexture();
var loader = new ImageLoader( this.manager );
loader.setCrossOrigin( this.crossOrigin );
loader.setPath( this.path );
var loaded = 0;
function loadTexture( i ) {
loader.load( urls[ i ], function ( image ) {
texture.images[ i ] = image;
loaded ++;
if ( loaded === 6 ) {
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}
}, undefined, onError );
}
for ( var i = 0; i < urls.length; ++ i ) {
loadTexture( i );
}
return texture;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function TextureLoader( manager ) {
Loader.call( this, manager );
}
TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: TextureLoader,
load: function ( url, onLoad, onProgress, onError ) {
var texture = new Texture();
var loader = new ImageLoader( this.manager );
loader.setCrossOrigin( this.crossOrigin );
loader.setPath( this.path );
loader.load( url, function ( image ) {
texture.image = image;
// JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
texture.format = isJPEG ? RGBFormat : RGBAFormat;
texture.needsUpdate = true;
if ( onLoad !== undefined ) {
onLoad( texture );
}
}, onProgress, onError );
return texture;
}
} );
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* Extensible curve object
*
* Some common of curve methods:
* .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
* .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
* .getPoints(), .getSpacedPoints()
* .getLength()
* .updateArcLengths()
*
* This following curves inherit from THREE.Curve:
*
* -- 2D curves --
* THREE.ArcCurve
* THREE.CubicBezierCurve
* THREE.EllipseCurve
* THREE.LineCurve
* THREE.QuadraticBezierCurve
* THREE.SplineCurve
*
* -- 3D curves --
* THREE.CatmullRomCurve3
* THREE.CubicBezierCurve3
* THREE.LineCurve3
* THREE.QuadraticBezierCurve3
*
* A series of curves can be represented as a THREE.CurvePath.
*
**/
/**************************************************************
* Abstract Curve base class
**************************************************************/
function Curve() {
this.type = 'Curve';
this.arcLengthDivisions = 200;
}
Object.assign( Curve.prototype, {
// Virtual base class method to overwrite and implement in subclasses
// - t [0 .. 1]
getPoint: function ( /* t, optionalTarget */ ) {
console.warn( 'THREE.Curve: .getPoint() not implemented.' );
return null;
},
// Get point at relative position in curve according to arc length
// - u [0 .. 1]
getPointAt: function ( u, optionalTarget ) {
var t = this.getUtoTmapping( u );
return this.getPoint( t, optionalTarget );
},
// Get sequence of points using getPoint( t )
getPoints: function ( divisions ) {
if ( divisions === undefined ) divisions = 5;
var points = [];
for ( var d = 0; d <= divisions; d ++ ) {
points.push( this.getPoint( d / divisions ) );
}
return points;
},
// Get sequence of points using getPointAt( u )
getSpacedPoints: function ( divisions ) {
if ( divisions === undefined ) divisions = 5;
var points = [];
for ( var d = 0; d <= divisions; d ++ ) {
points.push( this.getPointAt( d / divisions ) );
}
return points;
},
// Get total curve arc length
getLength: function () {
var lengths = this.getLengths();
return lengths[ lengths.length - 1 ];
},
// Get list of cumulative segment lengths
getLengths: function ( divisions ) {
if ( divisions === undefined ) divisions = this.arcLengthDivisions;
if ( this.cacheArcLengths &&
( this.cacheArcLengths.length === divisions + 1 ) &&
! this.needsUpdate ) {
return this.cacheArcLengths;
}
this.needsUpdate = false;
var cache = [];
var current, last = this.getPoint( 0 );
var p, sum = 0;
cache.push( 0 );
for ( p = 1; p <= divisions; p ++ ) {
current = this.getPoint( p / divisions );
sum += current.distanceTo( last );
cache.push( sum );
last = current;
}
this.cacheArcLengths = cache;
return cache; // { sums: cache, sum: sum }; Sum is in the last element.
},
updateArcLengths: function () {
this.needsUpdate = true;
this.getLengths();
},
// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
getUtoTmapping: function ( u, distance ) {
var arcLengths = this.getLengths();
var i = 0, il = arcLengths.length;
var targetArcLength; // The targeted u distance value to get
if ( distance ) {
targetArcLength = distance;
} else {
targetArcLength = u * arcLengths[ il - 1 ];
}
// binary search for the index with largest value smaller than target u distance
var low = 0, high = il - 1, comparison;
while ( low <= high ) {
i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
comparison = arcLengths[ i ] - targetArcLength;
if ( comparison < 0 ) {
low = i + 1;
} else if ( comparison > 0 ) {
high = i - 1;
} else {
high = i;
break;
// DONE
}
}
i = high;
if ( arcLengths[ i ] === targetArcLength ) {
return i / ( il - 1 );
}
// we could get finer grain at lengths, or use simple interpolation between two points
var lengthBefore = arcLengths[ i ];
var lengthAfter = arcLengths[ i + 1 ];
var segmentLength = lengthAfter - lengthBefore;
// determine where we are between the 'before' and 'after' points
var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
// add that fractional amount to t
var t = ( i + segmentFraction ) / ( il - 1 );
return t;
},
// Returns a unit vector tangent at t
// In case any sub curve does not implement its tangent derivation,
// 2 points a small delta apart will be used to find its gradient
// which seems to give a reasonable approximation
getTangent: function ( t, optionalTarget ) {
var delta = 0.0001;
var t1 = t - delta;
var t2 = t + delta;
// Capping in case of danger
if ( t1 < 0 ) t1 = 0;
if ( t2 > 1 ) t2 = 1;
var pt1 = this.getPoint( t1 );
var pt2 = this.getPoint( t2 );
var tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
tangent.copy( pt2 ).sub( pt1 ).normalize();
return tangent;
},
getTangentAt: function ( u, optionalTarget ) {
var t = this.getUtoTmapping( u );
return this.getTangent( t, optionalTarget );
},
computeFrenetFrames: function ( segments, closed ) {
// see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
var normal = new Vector3();
var tangents = [];
var normals = [];
var binormals = [];
var vec = new Vector3();
var mat = new Matrix4();
var i, u, theta;
// compute the tangent vectors for each segment on the curve
for ( i = 0; i <= segments; i ++ ) {
u = i / segments;
tangents[ i ] = this.getTangentAt( u, new Vector3() );
tangents[ i ].normalize();
}
// select an initial normal vector perpendicular to the first tangent vector,
// and in the direction of the minimum tangent xyz component
normals[ 0 ] = new Vector3();
binormals[ 0 ] = new Vector3();
var min = Number.MAX_VALUE;
var tx = Math.abs( tangents[ 0 ].x );
var ty = Math.abs( tangents[ 0 ].y );
var tz = Math.abs( tangents[ 0 ].z );
if ( tx <= min ) {
min = tx;
normal.set( 1, 0, 0 );
}
if ( ty <= min ) {
min = ty;
normal.set( 0, 1, 0 );
}
if ( tz <= min ) {
normal.set( 0, 0, 1 );
}
vec.crossVectors( tangents[ 0 ], normal ).normalize();
normals[ 0 ].crossVectors( tangents[ 0 ], vec );
binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
// compute the slowly-varying normal and binormal vectors for each segment on the curve
for ( i = 1; i <= segments; i ++ ) {
normals[ i ] = normals[ i - 1 ].clone();
binormals[ i ] = binormals[ i - 1 ].clone();
vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
if ( vec.length() > Number.EPSILON ) {
vec.normalize();
theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
}
binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
}
// if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
if ( closed === true ) {
theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
theta /= segments;
if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
theta = - theta;
}
for ( i = 1; i <= segments; i ++ ) {
// twist a little...
normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
}
}
return {
tangents: tangents,
normals: normals,
binormals: binormals
};
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( source ) {
this.arcLengthDivisions = source.arcLengthDivisions;
return this;
},
toJSON: function () {
var data = {
metadata: {
version: 4.5,
type: 'Curve',
generator: 'Curve.toJSON'
}
};
data.arcLengthDivisions = this.arcLengthDivisions;
data.type = this.type;
return data;
},
fromJSON: function ( json ) {
this.arcLengthDivisions = json.arcLengthDivisions;
return this;
}
} );
function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
Curve.call( this );
this.type = 'EllipseCurve';
this.aX = aX || 0;
this.aY = aY || 0;
this.xRadius = xRadius || 1;
this.yRadius = yRadius || 1;
this.aStartAngle = aStartAngle || 0;
this.aEndAngle = aEndAngle || 2 * Math.PI;
this.aClockwise = aClockwise || false;
this.aRotation = aRotation || 0;
}
EllipseCurve.prototype = Object.create( Curve.prototype );
EllipseCurve.prototype.constructor = EllipseCurve;
EllipseCurve.prototype.isEllipseCurve = true;
EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
var point = optionalTarget || new Vector2();
var twoPi = Math.PI * 2;
var deltaAngle = this.aEndAngle - this.aStartAngle;
var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
// ensures that deltaAngle is 0 .. 2 PI
while ( deltaAngle < 0 ) deltaAngle += twoPi;
while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
if ( deltaAngle < Number.EPSILON ) {
if ( samePoints ) {
deltaAngle = 0;
} else {
deltaAngle = twoPi;
}
}
if ( this.aClockwise === true && ! samePoints ) {
if ( deltaAngle === twoPi ) {
deltaAngle = - twoPi;
} else {
deltaAngle = deltaAngle - twoPi;
}
}
var angle = this.aStartAngle + t * deltaAngle;
var x = this.aX + this.xRadius * Math.cos( angle );
var y = this.aY + this.yRadius * Math.sin( angle );
if ( this.aRotation !== 0 ) {
var cos = Math.cos( this.aRotation );
var sin = Math.sin( this.aRotation );
var tx = x - this.aX;
var ty = y - this.aY;
// Rotate the point about the center of the ellipse.
x = tx * cos - ty * sin + this.aX;
y = tx * sin + ty * cos + this.aY;
}
return point.set( x, y );
};
EllipseCurve.prototype.copy = function ( source ) {
Curve.prototype.copy.call( this, source );
this.aX = source.aX;
this.aY = source.aY;
this.xRadius = source.xRadius;
this.yRadius = source.yRadius;
this.aStartAngle = source.aStartAngle;
this.aEndAngle = source.aEndAngle;
this.aClockwise = source.aClockwise;
this.aRotation = source.aRotation;
return this;
};
EllipseCurve.prototype.toJSON = function () {
var data = Curve.prototype.toJSON.call( this );
data.aX = this.aX;
data.aY = this.aY;
data.xRadius = this.xRadius;
data.yRadius = this.yRadius;
data.aStartAngle = this.aStartAngle;
data.aEndAngle = this.aEndAngle;
data.aClockwise = this.aClockwise;
data.aRotation = this.aRotation;
return data;
};
EllipseCurve.prototype.fromJSON = function ( json ) {
Curve.prototype.fromJSON.call( this, json );
this.aX = json.aX;
this.aY = json.aY;
this.xRadius = json.xRadius;
this.yRadius = json.yRadius;
this.aStartAngle = json.aStartAngle;
this.aEndAngle = json.aEndAngle;
this.aClockwise = json.aClockwise;
this.aRotation = json.aRotation;
return this;
};
function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
this.type = 'ArcCurve';
}
ArcCurve.prototype = Object.create( EllipseCurve.prototype );
ArcCurve.prototype.constructor = ArcCurve;
ArcCurve.prototype.isArcCurve = true;
/**
* @author zz85 https://github.com/zz85
*
* Centripetal CatmullRom Curve - which is useful for avoiding
* cusps and self-intersections in non-uniform catmull rom curves.
* http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
*
* curve.type accepts centripetal(default), chordal and catmullrom
* curve.tension is used for catmullrom which defaults to 0.5
*/
/*
Based on an optimized c++ solution in
- http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
- http://ideone.com/NoEbVM
This CubicPoly class could be used for reusing some variables and calculations,
but for three.js curve use, it could be possible inlined and flatten into a single function call
which can be placed in CurveUtils.
*/
function CubicPoly() {
var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
/*
* Compute coefficients for a cubic polynomial
* p(s) = c0 + c1*s + c2*s^2 + c3*s^3
* such that
* p(0) = x0, p(1) = x1
* and
* p'(0) = t0, p'(1) = t1.
*/
function init( x0, x1, t0, t1 ) {
c0 = x0;
c1 = t0;
c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
c3 = 2 * x0 - 2 * x1 + t0 + t1;
}
return {
initCatmullRom: function ( x0, x1, x2, x3, tension ) {
init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
},
initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
// compute tangents when parameterized in [t1,t2]
var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
// rescale tangents for parametrization in [0,1]
t1 *= dt1;
t2 *= dt1;
init( x1, x2, t1, t2 );
},
calc: function ( t ) {
var t2 = t * t;
var t3 = t2 * t;
return c0 + c1 * t + c2 * t2 + c3 * t3;
}
};
}
//
var tmp = new Vector3();
var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
function CatmullRomCurve3( points, closed, curveType, tension ) {
Curve.call( this );
this.type = 'CatmullRomCurve3';
this.points = points || [];
this.closed = closed || false;
this.curveType = curveType || 'centripetal';
this.tension = tension || 0.5;
}
CatmullRomCurve3.prototype = Object.create( Curve.prototype );
CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
var point = optionalTarget || new Vector3();
var points = this.points;
var l = points.length;
var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
var intPoint = Math.floor( p );
var weight = p - intPoint;
if ( this.closed ) {
intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
} else if ( weight === 0 && intPoint === l - 1 ) {
intPoint = l - 2;
weight = 1;
}
var p0, p1, p2, p3; // 4 points
if ( this.closed || intPoint > 0 ) {
p0 = points[ ( intPoint - 1 ) % l ];
} else {
// extrapolate first point
tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
p0 = tmp;
}
p1 = points[ intPoint % l ];
p2 = points[ ( intPoint + 1 ) % l ];
if ( this.closed || intPoint + 2 < l ) {
p3 = points[ ( intPoint + 2 ) % l ];
} else {
// extrapolate last point
tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
p3 = tmp;
}
if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
// init Centripetal / Chordal Catmull-Rom
var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
// safety check for repeated points
if ( dt1 < 1e-4 ) dt1 = 1.0;
if ( dt0 < 1e-4 ) dt0 = dt1;
if ( dt2 < 1e-4 ) dt2 = dt1;
px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
} else if ( this.curveType === 'catmullrom' ) {
px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
}
point.set(
px.calc( weight ),
py.calc( weight ),
pz.calc( weight )
);
return point;
};
CatmullRomCurve3.prototype.copy = function ( source ) {
Curve.prototype.copy.call( this, source );
this.points = [];
for ( var i = 0, l = source.points.length; i < l; i ++ ) {
var point = source.points[ i ];
this.points.push( point.clone() );
}
this.closed = source.closed;
this.curveType = source.curveType;
this.tension = source.tension;
return this;
};
CatmullRomCurve3.prototype.toJSON = function () {
var data = Curve.prototype.toJSON.call( this );
data.points = [];
for ( var i = 0, l = this.points.length; i < l; i ++ ) {
var point = this.points[ i ];
data.points.push( point.toArray() );
}
data.closed = this.closed;
data.curveType = this.curveType;
data.tension = this.tension;
return data;
};
CatmullRomCurve3.prototype.fromJSON = function ( json ) {
Curve.prototype.fromJSON.call( this, json );
this.points = [];
for ( var i = 0, l = json.points.length; i < l; i ++ ) {
var point = json.points[ i ];
this.points.push( new Vector3().fromArray( point ) );
}
this.closed = json.closed;
this.curveType = json.curveType;
this.tension = json.tension;
return this;
};
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
*
* Bezier Curves formulas obtained from
* http://en.wikipedia.org/wiki/Bézier_curve
*/
function CatmullRom( t, p0, p1, p2, p3 ) {
var v0 = ( p2 - p0 ) * 0.5;
var v1 = ( p3 - p1 ) * 0.5;
var t2 = t * t;
var t3 = t * t2;
return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
}
//
function QuadraticBezierP0( t, p ) {
var k = 1 - t;
return k * k * p;
}
function QuadraticBezierP1( t, p ) {
return 2 * ( 1 - t ) * t * p;
}
function QuadraticBezierP2( t, p ) {
return t * t * p;
}
function QuadraticBezier( t, p0, p1, p2 ) {
return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
QuadraticBezierP2( t, p2 );
}
//
function CubicBezierP0( t, p ) {
var k = 1 - t;
return k * k * k * p;
}
function CubicBezierP1( t, p ) {
var k = 1 - t;
return 3 * k * k * t * p;
}
function CubicBezierP2( t, p ) {
return 3 * ( 1 - t ) * t * t * p;
}
function CubicBezierP3( t, p ) {
return t * t * t * p;
}
function CubicBezier( t, p0, p1, p2, p3 ) {
return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
CubicBezierP3( t, p3 );
}
function CubicBezierCurve( v0, v1, v2, v3 ) {
Curve.call( this );
this.type = 'CubicBezierCurve';
this.v0 = v0 || new Vector2();
this.v1 = v1 || new Vector2();
this.v2 = v2 || new Vector2();
this.v3 = v3 || new Vector2();
}
CubicBezierCurve.prototype = Object.create( Curve.prototype );
CubicBezierCurve.prototype.constructor = CubicBezierCurve;
CubicBezierCurve.prototype.isCubicBezierCurve = true;
CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
var point = optionalTarget || new Vector2();
var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
point.set(
CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
);
return point;
};
CubicBezierCurve.prototype.copy = function ( source ) {
Curve.prototype.copy.call( this, source );
this.v0.copy( source.v0 );
this.v1.copy( source.v1 );
this.v2.copy( source.v2 );
this.v3.copy( source.v3 );
return this;
};
CubicBezierCurve.prototype.toJSON = function () {
var data = Curve.prototype.toJSON.call( this );
data.v0 = this.v0.toArray();
data.v1 = this.v1.toArray();
data.v2 = this.v2.toArray();
data.v3 = this.v3.toArray();
return data;
};
CubicBezierCurve.prototype.fromJSON = function ( json ) {
Curve.prototype.fromJSON.call( this, json );
this.v0.fromArray( json.v0 );
this.v1.fromArray( json.v1 );
this.v2.fromArray( json.v2 );
this.v3.fromArray( json.v3 );
return this;
};
function CubicBezierCurve3( v0, v1, v2, v3 ) {
Curve.call( this );
this.type = 'CubicBezierCurve3';
this.v0 = v0 || new Vector3();
this.v1 = v1 || new Vector3();
this.v2 = v2 || new Vector3();
this.v3 = v3 || new Vector3();
}
CubicBezierCurve3.prototype = Object.create( Curve.prototype );
CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
var point = optionalTarget || new Vector3();
var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
point.set(
CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
);
return point;
};
CubicBezierCurve3.prototype.copy = function ( source ) {
Curve.prototype.copy.call( this, source );
this.v0.copy( source.v0 );
this.v1.copy( source.v1 );
this.v2.copy( source.v2 );
this.v3.copy( source.v3 );
return this;
};
CubicBezierCurve3.prototype.toJSON = function () {
var data = Curve.prototype.toJSON.call( this );
data.v0 = this.v0.toArray();
data.v1 = this.v1.toArray();
data.v2 = this.v2.toArray();
data.v3 = this.v3.toArray();
return data;
};
CubicBezierCurve3.prototype.fromJSON = function ( json ) {
Curve.prototype.fromJSON.call( this, json );
this.v0.fromArray( json.v0 );
this.v1.fromArray( json.v1 );
this.v2.fromArray( json.v2 );
this.v3.fromArray( json.v3 );
return this;
};
function LineCurve( v1, v2 ) {
Curve.call( this );
this.type = 'LineCurve';
this.v1 = v1 || new Vector2();
this.v2 = v2 || new Vector2();
}
LineCurve.prototype = Object.create( Curve.prototype );
LineCurve.prototype.constructor = LineCurve;
LineCurve.prototype.isLineCurve = true;
LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
var point = optionalTarget || new Vector2();
if ( t === 1 ) {
point.copy( this.v2 );
} else {
point.copy( this.v2 ).sub( this.v1 );
point.multiplyScalar( t ).add( this.v1 );
}
return point;
};
// Line curve is linear, so we can overwrite default getPointAt
LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
return this.getPoint( u, optionalTarget );
};
LineCurve.prototype.getTangent = function ( t, optionalTarget ) {
var tangent = optionalTarget || new Vector2();
var tangent = tangent.copy( this.v2 ).sub( this.v1 ).normalize();
return tangent;
};
LineCurve.prototype.copy = function ( source ) {
Curve.prototype.copy.call( this, source );
this.v1.copy( source.v1 );
this.v2.copy( source.v2 );
return this;
};
LineCurve.prototype.toJSON = function () {
var data = Curve.prototype.toJSON.call( this );
data.v1 = this.v1.toArray();
data.v2 = this.v2.toArray();
return data;
};
LineCurve.prototype.fromJSON = function ( json ) {
Curve.prototype.fromJSON.call( this, json );
this.v1.fromArray( json.v1 );
this.v2.fromArray( json.v2 );
return this;
};
function LineCurve3( v1, v2 ) {
Curve.call( this );
this.type = 'LineCurve3';
this.v1 = v1 || new Vector3();
this.v2 = v2 || new Vector3();
}
LineCurve3.prototype = Object.create( Curve.prototype );
LineCurve3.prototype.constructor = LineCurve3;
LineCurve3.prototype.isLineCurve3 = true;
LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
var point = optionalTarget || new Vector3();
if ( t === 1 ) {
point.copy( this.v2 );
} else {
point.copy( this.v2 ).sub( this.v1 );
point.multiplyScalar( t ).add( this.v1 );
}
return point;
};
// Line curve is linear, so we can overwrite default getPointAt
LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
return this.getPoint( u, optionalTarget );
};
LineCurve3.prototype.copy = function ( source ) {
Curve.prototype.copy.call( this, source );
this.v1.copy( source.v1 );
this.v2.copy( source.v2 );
return this;
};
LineCurve3.prototype.toJSON = function () {
var data = Curve.prototype.toJSON.call( this );
data.v1 = this.v1.toArray();
data.v2 = this.v2.toArray();
return data;
};
LineCurve3.prototype.fromJSON = function ( json ) {
Curve.prototype.fromJSON.call( this, json );
this.v1.fromArray( json.v1 );
this.v2.fromArray( json.v2 );
return this;
};
function QuadraticBezierCurve( v0, v1, v2 ) {
Curve.call( this );
this.type = 'QuadraticBezierCurve';
this.v0 = v0 || new Vector2();
this.v1 = v1 || new Vector2();
this.v2 = v2 || new Vector2();
}
QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
var point = optionalTarget || new Vector2();
var v0 = this.v0, v1 = this.v1, v2 = this.v2;
point.set(
QuadraticBezier( t, v0.x, v1.x, v2.x ),
QuadraticBezier( t, v0.y, v1.y, v2.y )
);
return point;
};
QuadraticBezierCurve.prototype.copy = function ( source ) {
Curve.prototype.copy.call( this, source );
this.v0.copy( source.v0 );
this.v1.copy( source.v1 );
this.v2.copy( source.v2 );
return this;
};
QuadraticBezierCurve.prototype.toJSON = function () {
var data = Curve.prototype.toJSON.call( this );
data.v0 = this.v0.toArray();
data.v1 = this.v1.toArray();
data.v2 = this.v2.toArray();
return data;
};
QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
Curve.prototype.fromJSON.call( this, json );
this.v0.fromArray( json.v0 );
this.v1.fromArray( json.v1 );
this.v2.fromArray( json.v2 );
return this;
};
function QuadraticBezierCurve3( v0, v1, v2 ) {
Curve.call( this );
this.type = 'QuadraticBezierCurve3';
this.v0 = v0 || new Vector3();
this.v1 = v1 || new Vector3();
this.v2 = v2 || new Vector3();
}
QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
var point = optionalTarget || new Vector3();
var v0 = this.v0, v1 = this.v1, v2 = this.v2;
point.set(
QuadraticBezier( t, v0.x, v1.x, v2.x ),
QuadraticBezier( t, v0.y, v1.y, v2.y ),
QuadraticBezier( t, v0.z, v1.z, v2.z )
);
return point;
};
QuadraticBezierCurve3.prototype.copy = function ( source ) {
Curve.prototype.copy.call( this, source );
this.v0.copy( source.v0 );
this.v1.copy( source.v1 );
this.v2.copy( source.v2 );
return this;
};
QuadraticBezierCurve3.prototype.toJSON = function () {
var data = Curve.prototype.toJSON.call( this );
data.v0 = this.v0.toArray();
data.v1 = this.v1.toArray();
data.v2 = this.v2.toArray();
return data;
};
QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
Curve.prototype.fromJSON.call( this, json );
this.v0.fromArray( json.v0 );
this.v1.fromArray( json.v1 );
this.v2.fromArray( json.v2 );
return this;
};
function SplineCurve( points /* array of Vector2 */ ) {
Curve.call( this );
this.type = 'SplineCurve';
this.points = points || [];
}
SplineCurve.prototype = Object.create( Curve.prototype );
SplineCurve.prototype.constructor = SplineCurve;
SplineCurve.prototype.isSplineCurve = true;
SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
var point = optionalTarget || new Vector2();
var points = this.points;
var p = ( points.length - 1 ) * t;
var intPoint = Math.floor( p );
var weight = p - intPoint;
var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
var p1 = points[ intPoint ];
var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
point.set(
CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
);
return point;
};
SplineCurve.prototype.copy = function ( source ) {
Curve.prototype.copy.call( this, source );
this.points = [];
for ( var i = 0, l = source.points.length; i < l; i ++ ) {
var point = source.points[ i ];
this.points.push( point.clone() );
}
return this;
};
SplineCurve.prototype.toJSON = function () {
var data = Curve.prototype.toJSON.call( this );
data.points = [];
for ( var i = 0, l = this.points.length; i < l; i ++ ) {
var point = this.points[ i ];
data.points.push( point.toArray() );
}
return data;
};
SplineCurve.prototype.fromJSON = function ( json ) {
Curve.prototype.fromJSON.call( this, json );
this.points = [];
for ( var i = 0, l = json.points.length; i < l; i ++ ) {
var point = json.points[ i ];
this.points.push( new Vector2().fromArray( point ) );
}
return this;
};
var Curves = /*#__PURE__*/Object.freeze({
__proto__: null,
ArcCurve: ArcCurve,
CatmullRomCurve3: CatmullRomCurve3,
CubicBezierCurve: CubicBezierCurve,
CubicBezierCurve3: CubicBezierCurve3,
EllipseCurve: EllipseCurve,
LineCurve: LineCurve,
LineCurve3: LineCurve3,
QuadraticBezierCurve: QuadraticBezierCurve,
QuadraticBezierCurve3: QuadraticBezierCurve3,
SplineCurve: SplineCurve
});
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
*
**/
/**************************************************************
* Curved Path - a curve path is simply a array of connected
* curves, but retains the api of a curve
**************************************************************/
function CurvePath() {
Curve.call( this );
this.type = 'CurvePath';
this.curves = [];
this.autoClose = false; // Automatically closes the path
}
CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
constructor: CurvePath,
add: function ( curve ) {
this.curves.push( curve );
},
closePath: function () {
// Add a line curve if start and end of lines are not connected
var startPoint = this.curves[ 0 ].getPoint( 0 );
var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
if ( ! startPoint.equals( endPoint ) ) {
this.curves.push( new LineCurve( endPoint, startPoint ) );
}
},
// To get accurate point with reference to
// entire path distance at time t,
// following has to be done:
// 1. Length of each sub path have to be known
// 2. Locate and identify type of curve
// 3. Get t for the curve
// 4. Return curve.getPointAt(t')
getPoint: function ( t ) {
var d = t * this.getLength();
var curveLengths = this.getCurveLengths();
var i = 0;
// To think about boundaries points.
while ( i < curveLengths.length ) {
if ( curveLengths[ i ] >= d ) {
var diff = curveLengths[ i ] - d;
var curve = this.curves[ i ];
var segmentLength = curve.getLength();
var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
return curve.getPointAt( u );
}
i ++;
}
return null;
// loop where sum != 0, sum > d , sum+1 <d
},
// We cannot use the default THREE.Curve getPoint() with getLength() because in
// THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
// getPoint() depends on getLength
getLength: function () {
var lens = this.getCurveLengths();
return lens[ lens.length - 1 ];
},
// cacheLengths must be recalculated.
updateArcLengths: function () {
this.needsUpdate = true;
this.cacheLengths = null;
this.getCurveLengths();
},
// Compute lengths and cache them
// We cannot overwrite getLengths() because UtoT mapping uses it.
getCurveLengths: function () {
// We use cache values if curves and cache array are same length
if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
return this.cacheLengths;
}
// Get length of sub-curve
// Push sums into cached array
var lengths = [], sums = 0;
for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
sums += this.curves[ i ].getLength();
lengths.push( sums );
}
this.cacheLengths = lengths;
return lengths;
},
getSpacedPoints: function ( divisions ) {
if ( divisions === undefined ) divisions = 40;
var points = [];
for ( var i = 0; i <= divisions; i ++ ) {
points.push( this.getPoint( i / divisions ) );
}
if ( this.autoClose ) {
points.push( points[ 0 ] );
}
return points;
},
getPoints: function ( divisions ) {
divisions = divisions || 12;
var points = [], last;
for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
var curve = curves[ i ];
var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
: ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
: ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
: divisions;
var pts = curve.getPoints( resolution );
for ( var j = 0; j < pts.length; j ++ ) {
var point = pts[ j ];
if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
points.push( point );
last = point;
}
}
if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
points.push( points[ 0 ] );
}
return points;
},
copy: function ( source ) {
Curve.prototype.copy.call( this, source );
this.curves = [];
for ( var i = 0, l = source.curves.length; i < l; i ++ ) {
var curve = source.curves[ i ];
this.curves.push( curve.clone() );
}
this.autoClose = source.autoClose;
return this;
},
toJSON: function () {
var data = Curve.prototype.toJSON.call( this );
data.autoClose = this.autoClose;
data.curves = [];
for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
var curve = this.curves[ i ];
data.curves.push( curve.toJSON() );
}
return data;
},
fromJSON: function ( json ) {
Curve.prototype.fromJSON.call( this, json );
this.autoClose = json.autoClose;
this.curves = [];
for ( var i = 0, l = json.curves.length; i < l; i ++ ) {
var curve = json.curves[ i ];
this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
}
return this;
}
} );
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* Creates free form 2d path using series of points, lines or curves.
**/
function Path( points ) {
CurvePath.call( this );
this.type = 'Path';
this.currentPoint = new Vector2();
if ( points ) {
this.setFromPoints( points );
}
}
Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
constructor: Path,
setFromPoints: function ( points ) {
this.moveTo( points[ 0 ].x, points[ 0 ].y );
for ( var i = 1, l = points.length; i < l; i ++ ) {
this.lineTo( points[ i ].x, points[ i ].y );
}
return this;
},
moveTo: function ( x, y ) {
this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
return this;
},
lineTo: function ( x, y ) {
var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
this.curves.push( curve );
this.currentPoint.set( x, y );
return this;
},
quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
var curve = new QuadraticBezierCurve(
this.currentPoint.clone(),
new Vector2( aCPx, aCPy ),
new Vector2( aX, aY )
);
this.curves.push( curve );
this.currentPoint.set( aX, aY );
return this;
},
bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
var curve = new CubicBezierCurve(
this.currentPoint.clone(),
new Vector2( aCP1x, aCP1y ),
new Vector2( aCP2x, aCP2y ),
new Vector2( aX, aY )
);
this.curves.push( curve );
this.currentPoint.set( aX, aY );
return this;
},
splineThru: function ( pts /*Array of Vector*/ ) {
var npts = [ this.currentPoint.clone() ].concat( pts );
var curve = new SplineCurve( npts );
this.curves.push( curve );
this.currentPoint.copy( pts[ pts.length - 1 ] );
return this;
},
arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
var x0 = this.currentPoint.x;
var y0 = this.currentPoint.y;
this.absarc( aX + x0, aY + y0, aRadius,
aStartAngle, aEndAngle, aClockwise );
return this;
},
absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
return this;
},
ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
var x0 = this.currentPoint.x;
var y0 = this.currentPoint.y;
this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
return this;
},
absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
if ( this.curves.length > 0 ) {
// if a previous curve is present, attempt to join
var firstPoint = curve.getPoint( 0 );
if ( ! firstPoint.equals( this.currentPoint ) ) {
this.lineTo( firstPoint.x, firstPoint.y );
}
}
this.curves.push( curve );
var lastPoint = curve.getPoint( 1 );
this.currentPoint.copy( lastPoint );
return this;
},
copy: function ( source ) {
CurvePath.prototype.copy.call( this, source );
this.currentPoint.copy( source.currentPoint );
return this;
},
toJSON: function () {
var data = CurvePath.prototype.toJSON.call( this );
data.currentPoint = this.currentPoint.toArray();
return data;
},
fromJSON: function ( json ) {
CurvePath.prototype.fromJSON.call( this, json );
this.currentPoint.fromArray( json.currentPoint );
return this;
}
} );
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* Defines a 2d shape plane using paths.
**/
// STEP 1 Create a path.
// STEP 2 Turn path into shape.
// STEP 3 ExtrudeGeometry takes in Shape/Shapes
// STEP 3a - Extract points from each shape, turn to vertices
// STEP 3b - Triangulate each shape, add faces.
function Shape( points ) {
Path.call( this, points );
this.uuid = MathUtils.generateUUID();
this.type = 'Shape';
this.holes = [];
}
Shape.prototype = Object.assign( Object.create( Path.prototype ), {
constructor: Shape,
getPointsHoles: function ( divisions ) {
var holesPts = [];
for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
holesPts[ i ] = this.holes[ i ].getPoints( divisions );
}
return holesPts;
},
// get points of shape and holes (keypoints based on segments parameter)
extractPoints: function ( divisions ) {
return {
shape: this.getPoints( divisions ),
holes: this.getPointsHoles( divisions )
};
},
copy: function ( source ) {
Path.prototype.copy.call( this, source );
this.holes = [];
for ( var i = 0, l = source.holes.length; i < l; i ++ ) {
var hole = source.holes[ i ];
this.holes.push( hole.clone() );
}
return this;
},
toJSON: function () {
var data = Path.prototype.toJSON.call( this );
data.uuid = this.uuid;
data.holes = [];
for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
var hole = this.holes[ i ];
data.holes.push( hole.toJSON() );
}
return data;
},
fromJSON: function ( json ) {
Path.prototype.fromJSON.call( this, json );
this.uuid = json.uuid;
this.holes = [];
for ( var i = 0, l = json.holes.length; i < l; i ++ ) {
var hole = json.holes[ i ];
this.holes.push( new Path().fromJSON( hole ) );
}
return this;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
function Light( color, intensity ) {
Object3D.call( this );
this.type = 'Light';
this.color = new Color( color );
this.intensity = intensity !== undefined ? intensity : 1;
this.receiveShadow = undefined;
}
Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Light,
isLight: true,
copy: function ( source ) {
Object3D.prototype.copy.call( this, source );
this.color.copy( source.color );
this.intensity = source.intensity;
return this;
},
toJSON: function ( meta ) {
var data = Object3D.prototype.toJSON.call( this, meta );
data.object.color = this.color.getHex();
data.object.intensity = this.intensity;
if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
if ( this.distance !== undefined ) data.object.distance = this.distance;
if ( this.angle !== undefined ) data.object.angle = this.angle;
if ( this.decay !== undefined ) data.object.decay = this.decay;
if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
return data;
}
} );
/**
* @author alteredq / http://alteredqualia.com/
*/
function HemisphereLight( skyColor, groundColor, intensity ) {
Light.call( this, skyColor, intensity );
this.type = 'HemisphereLight';
this.castShadow = undefined;
this.position.copy( Object3D.DefaultUp );
this.updateMatrix();
this.groundColor = new Color( groundColor );
}
HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
constructor: HemisphereLight,
isHemisphereLight: true,
copy: function ( source ) {
Light.prototype.copy.call( this, source );
this.groundColor.copy( source.groundColor );
return this;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function LightShadow( camera ) {
this.camera = camera;
this.bias = 0;
this.radius = 1;
this.mapSize = new Vector2( 512, 512 );
this.map = null;
this.mapPass = null;
this.matrix = new Matrix4();
this._frustum = new Frustum();
this._frameExtents = new Vector2( 1, 1 );
this._viewportCount = 1;
this._viewports = [
new Vector4( 0, 0, 1, 1 )
];
}
Object.assign( LightShadow.prototype, {
_projScreenMatrix: new Matrix4(),
_lightPositionWorld: new Vector3(),
_lookTarget: new Vector3(),
getViewportCount: function () {
return this._viewportCount;
},
getFrustum: function () {
return this._frustum;
},
updateMatrices: function ( light ) {
var shadowCamera = this.camera,
shadowMatrix = this.matrix,
projScreenMatrix = this._projScreenMatrix,
lookTarget = this._lookTarget,
lightPositionWorld = this._lightPositionWorld;
lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
shadowCamera.position.copy( lightPositionWorld );
lookTarget.setFromMatrixPosition( light.target.matrixWorld );
shadowCamera.lookAt( lookTarget );
shadowCamera.updateMatrixWorld();
projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
this._frustum.setFromProjectionMatrix( projScreenMatrix );
shadowMatrix.set(
0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0
);
shadowMatrix.multiply( shadowCamera.projectionMatrix );
shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
},
getViewport: function ( viewportIndex ) {
return this._viewports[ viewportIndex ];
},
getFrameExtents: function () {
return this._frameExtents;
},
copy: function ( source ) {
this.camera = source.camera.clone();
this.bias = source.bias;
this.radius = source.radius;
this.mapSize.copy( source.mapSize );
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
toJSON: function () {
var object = {};
if ( this.bias !== 0 ) object.bias = this.bias;
if ( this.radius !== 1 ) object.radius = this.radius;
if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
object.camera = this.camera.toJSON( false ).object;
delete object.camera.matrix;
return object;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function SpotLightShadow() {
LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
}
SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
constructor: SpotLightShadow,
isSpotLightShadow: true,
updateMatrices: function ( light ) {
var camera = this.camera;
var fov = MathUtils.RAD2DEG * 2 * light.angle;
var aspect = this.mapSize.width / this.mapSize.height;
var far = light.distance || camera.far;
if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
camera.fov = fov;
camera.aspect = aspect;
camera.far = far;
camera.updateProjectionMatrix();
}
LightShadow.prototype.updateMatrices.call( this, light );
}
} );
/**
* @author alteredq / http://alteredqualia.com/
*/
function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
Light.call( this, color, intensity );
this.type = 'SpotLight';
this.position.copy( Object3D.DefaultUp );
this.updateMatrix();
this.target = new Object3D();
Object.defineProperty( this, 'power', {
get: function () {
// intensity = power per solid angle.
// ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
return this.intensity * Math.PI;
},
set: function ( power ) {
// intensity = power per solid angle.
// ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
this.intensity = power / Math.PI;
}
} );
this.distance = ( distance !== undefined ) ? distance : 0;
this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
this.shadow = new SpotLightShadow();
}
SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
constructor: SpotLight,
isSpotLight: true,
copy: function ( source ) {
Light.prototype.copy.call( this, source );
this.distance = source.distance;
this.angle = source.angle;
this.penumbra = source.penumbra;
this.decay = source.decay;
this.target = source.target.clone();
this.shadow = source.shadow.clone();
return this;
}
} );
function PointLightShadow() {
LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );
this._frameExtents = new Vector2( 4, 2 );
this._viewportCount = 6;
this._viewports = [
// These viewports map a cube-map onto a 2D texture with the
// following orientation:
//
// xzXZ
// y Y
//
// X - Positive x direction
// x - Negative x direction
// Y - Positive y direction
// y - Negative y direction
// Z - Positive z direction
// z - Negative z direction
// positive X
new Vector4( 2, 1, 1, 1 ),
// negative X
new Vector4( 0, 1, 1, 1 ),
// positive Z
new Vector4( 3, 1, 1, 1 ),
// negative Z
new Vector4( 1, 1, 1, 1 ),
// positive Y
new Vector4( 3, 0, 1, 1 ),
// negative Y
new Vector4( 1, 0, 1, 1 )
];
this._cubeDirections = [
new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
];
this._cubeUps = [
new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
];
}
PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
constructor: PointLightShadow,
isPointLightShadow: true,
updateMatrices: function ( light, viewportIndex ) {
if ( viewportIndex === undefined ) viewportIndex = 0;
var camera = this.camera,
shadowMatrix = this.matrix,
lightPositionWorld = this._lightPositionWorld,
lookTarget = this._lookTarget,
projScreenMatrix = this._projScreenMatrix;
lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
camera.position.copy( lightPositionWorld );
lookTarget.copy( camera.position );
lookTarget.add( this._cubeDirections[ viewportIndex ] );
camera.up.copy( this._cubeUps[ viewportIndex ] );
camera.lookAt( lookTarget );
camera.updateMatrixWorld();
shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );
projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
this._frustum.setFromProjectionMatrix( projScreenMatrix );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function PointLight( color, intensity, distance, decay ) {
Light.call( this, color, intensity );
this.type = 'PointLight';
Object.defineProperty( this, 'power', {
get: function () {
// intensity = power per solid angle.
// ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
return this.intensity * 4 * Math.PI;
},
set: function ( power ) {
// intensity = power per solid angle.
// ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
this.intensity = power / ( 4 * Math.PI );
}
} );
this.distance = ( distance !== undefined ) ? distance : 0;
this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
this.shadow = new PointLightShadow();
}
PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
constructor: PointLight,
isPointLight: true,
copy: function ( source ) {
Light.prototype.copy.call( this, source );
this.distance = source.distance;
this.decay = source.decay;
this.shadow = source.shadow.clone();
return this;
}
} );
/**
* @author alteredq / http://alteredqualia.com/
* @author arose / http://github.com/arose
*/
function OrthographicCamera( left, right, top, bottom, near, far ) {
Camera.call( this );
this.type = 'OrthographicCamera';
this.zoom = 1;
this.view = null;
this.left = ( left !== undefined ) ? left : - 1;
this.right = ( right !== undefined ) ? right : 1;
this.top = ( top !== undefined ) ? top : 1;
this.bottom = ( bottom !== undefined ) ? bottom : - 1;
this.near = ( near !== undefined ) ? near : 0.1;
this.far = ( far !== undefined ) ? far : 2000;
this.updateProjectionMatrix();
}
OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
constructor: OrthographicCamera,
isOrthographicCamera: true,
copy: function ( source, recursive ) {
Camera.prototype.copy.call( this, source, recursive );
this.left = source.left;
this.right = source.right;
this.top = source.top;
this.bottom = source.bottom;
this.near = source.near;
this.far = source.far;
this.zoom = source.zoom;
this.view = source.view === null ? null : Object.assign( {}, source.view );
return this;
},
setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
if ( this.view === null ) {
this.view = {
enabled: true,
fullWidth: 1,
fullHeight: 1,
offsetX: 0,
offsetY: 0,
width: 1,
height: 1
};
}
this.view.enabled = true;
this.view.fullWidth = fullWidth;
this.view.fullHeight = fullHeight;
this.view.offsetX = x;
this.view.offsetY = y;
this.view.width = width;
this.view.height = height;
this.updateProjectionMatrix();
},
clearViewOffset: function () {
if ( this.view !== null ) {
this.view.enabled = false;
}
this.updateProjectionMatrix();
},
updateProjectionMatrix: function () {
var dx = ( this.right - this.left ) / ( 2 * this.zoom );
var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
var cx = ( this.right + this.left ) / 2;
var cy = ( this.top + this.bottom ) / 2;
var left = cx - dx;
var right = cx + dx;
var top = cy + dy;
var bottom = cy - dy;
if ( this.view !== null && this.view.enabled ) {
var scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
var scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
left += scaleW * this.view.offsetX;
right = left + scaleW * this.view.width;
top -= scaleH * this.view.offsetY;
bottom = top - scaleH * this.view.height;
}
this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
this.projectionMatrixInverse.getInverse( this.projectionMatrix );
},
toJSON: function ( meta ) {
var data = Object3D.prototype.toJSON.call( this, meta );
data.object.zoom = this.zoom;
data.object.left = this.left;
data.object.right = this.right;
data.object.top = this.top;
data.object.bottom = this.bottom;
data.object.near = this.near;
data.object.far = this.far;
if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
return data;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function DirectionalLightShadow() {
LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
}
DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
constructor: DirectionalLightShadow,
isDirectionalLightShadow: true,
updateMatrices: function ( light ) {
LightShadow.prototype.updateMatrices.call( this, light );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
function DirectionalLight( color, intensity ) {
Light.call( this, color, intensity );
this.type = 'DirectionalLight';
this.position.copy( Object3D.DefaultUp );
this.updateMatrix();
this.target = new Object3D();
this.shadow = new DirectionalLightShadow();
}
DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
constructor: DirectionalLight,
isDirectionalLight: true,
copy: function ( source ) {
Light.prototype.copy.call( this, source );
this.target = source.target.clone();
this.shadow = source.shadow.clone();
return this;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function AmbientLight( color, intensity ) {
Light.call( this, color, intensity );
this.type = 'AmbientLight';
this.castShadow = undefined;
}
AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
constructor: AmbientLight,
isAmbientLight: true
} );
/**
* @author abelnation / http://github.com/abelnation
*/
function RectAreaLight( color, intensity, width, height ) {
Light.call( this, color, intensity );
this.type = 'RectAreaLight';
this.width = ( width !== undefined ) ? width : 10;
this.height = ( height !== undefined ) ? height : 10;
}
RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
constructor: RectAreaLight,
isRectAreaLight: true,
copy: function ( source ) {
Light.prototype.copy.call( this, source );
this.width = source.width;
this.height = source.height;
return this;
},
toJSON: function ( meta ) {
var data = Light.prototype.toJSON.call( this, meta );
data.object.width = this.width;
data.object.height = this.height;
return data;
}
} );
/**
* @author bhouston / http://clara.io
* @author WestLangley / http://github.com/WestLangley
*
* Primary reference:
* https://graphics.stanford.edu/papers/envmap/envmap.pdf
*
* Secondary reference:
* https://www.ppsloan.org/publications/StupidSH36.pdf
*/
// 3-band SH defined by 9 coefficients
function SphericalHarmonics3() {
this.coefficients = [];
for ( var i = 0; i < 9; i ++ ) {
this.coefficients.push( new Vector3() );
}
}
Object.assign( SphericalHarmonics3.prototype, {
isSphericalHarmonics3: true,
set: function ( coefficients ) {
for ( var i = 0; i < 9; i ++ ) {
this.coefficients[ i ].copy( coefficients[ i ] );
}
return this;
},
zero: function () {
for ( var i = 0; i < 9; i ++ ) {
this.coefficients[ i ].set( 0, 0, 0 );
}
return this;
},
// get the radiance in the direction of the normal
// target is a Vector3
getAt: function ( normal, target ) {
// normal is assumed to be unit length
var x = normal.x, y = normal.y, z = normal.z;
var coeff = this.coefficients;
// band 0
target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
// band 1
target.addScaledVector( coeff[ 1 ], 0.488603 * y );
target.addScaledVector( coeff[ 2 ], 0.488603 * z );
target.addScaledVector( coeff[ 3 ], 0.488603 * x );
// band 2
target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
return target;
},
// get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
// target is a Vector3
// https://graphics.stanford.edu/papers/envmap/envmap.pdf
getIrradianceAt: function ( normal, target ) {
// normal is assumed to be unit length
var x = normal.x, y = normal.y, z = normal.z;
var coeff = this.coefficients;
// band 0
target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
// band 1
target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
// band 2
target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
return target;
},
add: function ( sh ) {
for ( var i = 0; i < 9; i ++ ) {
this.coefficients[ i ].add( sh.coefficients[ i ] );
}
return this;
},
addScaledSH: function ( sh, s ) {
for ( var i = 0; i < 9; i ++ ) {
this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
}
return this;
},
scale: function ( s ) {
for ( var i = 0; i < 9; i ++ ) {
this.coefficients[ i ].multiplyScalar( s );
}
return this;
},
lerp: function ( sh, alpha ) {
for ( var i = 0; i < 9; i ++ ) {
this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
}
return this;
},
equals: function ( sh ) {
for ( var i = 0; i < 9; i ++ ) {
if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
return false;
}
}
return true;
},
copy: function ( sh ) {
return this.set( sh.coefficients );
},
clone: function () {
return new this.constructor().copy( this );
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
var coefficients = this.coefficients;
for ( var i = 0; i < 9; i ++ ) {
coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
}
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
var coefficients = this.coefficients;
for ( var i = 0; i < 9; i ++ ) {
coefficients[ i ].toArray( array, offset + ( i * 3 ) );
}
return array;
}
} );
Object.assign( SphericalHarmonics3, {
// evaluate the basis functions
// shBasis is an Array[ 9 ]
getBasisAt: function ( normal, shBasis ) {
// normal is assumed to be unit length
var x = normal.x, y = normal.y, z = normal.z;
// band 0
shBasis[ 0 ] = 0.282095;
// band 1
shBasis[ 1 ] = 0.488603 * y;
shBasis[ 2 ] = 0.488603 * z;
shBasis[ 3 ] = 0.488603 * x;
// band 2
shBasis[ 4 ] = 1.092548 * x * y;
shBasis[ 5 ] = 1.092548 * y * z;
shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
shBasis[ 7 ] = 1.092548 * x * z;
shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
}
} );
/**
* @author WestLangley / http://github.com/WestLangley
*
* A LightProbe is a source of indirect-diffuse light
*/
function LightProbe( sh, intensity ) {
Light.call( this, undefined, intensity );
this.type = 'LightProbe';
this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();
}
LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {
constructor: LightProbe,
isLightProbe: true,
copy: function ( source ) {
Light.prototype.copy.call( this, source );
this.sh.copy( source.sh );
return this;
},
fromJSON: function ( json ) {
this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
this.sh.fromArray( json.sh );
return this;
},
toJSON: function ( meta ) {
var data = Light.prototype.toJSON.call( this, meta );
data.object.sh = this.sh.toArray();
return data;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function MaterialLoader( manager ) {
Loader.call( this, manager );
this.textures = {};
}
MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: MaterialLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new FileLoader( scope.manager );
loader.setPath( scope.path );
loader.load( url, function ( text ) {
onLoad( scope.parse( JSON.parse( text ) ) );
}, onProgress, onError );
},
parse: function ( json ) {
var textures = this.textures;
function getTexture( name ) {
if ( textures[ name ] === undefined ) {
console.warn( 'THREE.MaterialLoader: Undefined texture', name );
}
return textures[ name ];
}
var material = new Materials[ json.type ]();
if ( json.uuid !== undefined ) material.uuid = json.uuid;
if ( json.name !== undefined ) material.name = json.name;
if ( json.color !== undefined ) material.color.setHex( json.color );
if ( json.roughness !== undefined ) material.roughness = json.roughness;
if ( json.metalness !== undefined ) material.metalness = json.metalness;
if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
if ( json.specular !== undefined ) material.specular.setHex( json.specular );
if ( json.shininess !== undefined ) material.shininess = json.shininess;
if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
if ( json.fog !== undefined ) material.fog = json.fog;
if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
if ( json.blending !== undefined ) material.blending = json.blending;
if ( json.combine !== undefined ) material.combine = json.combine;
if ( json.side !== undefined ) material.side = json.side;
if ( json.opacity !== undefined ) material.opacity = json.opacity;
if ( json.transparent !== undefined ) material.transparent = json.transparent;
if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
if ( json.rotation !== undefined ) material.rotation = json.rotation;
if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
if ( json.scale !== undefined ) material.scale = json.scale;
if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
if ( json.skinning !== undefined ) material.skinning = json.skinning;
if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
if ( json.dithering !== undefined ) material.dithering = json.dithering;
if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;
if ( json.visible !== undefined ) material.visible = json.visible;
if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
if ( json.userData !== undefined ) material.userData = json.userData;
if ( json.vertexColors !== undefined ) {
if ( typeof json.vertexColors === 'number' ) {
material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
} else {
material.vertexColors = json.vertexColors;
}
}
// Shader Material
if ( json.uniforms !== undefined ) {
for ( var name in json.uniforms ) {
var uniform = json.uniforms[ name ];
material.uniforms[ name ] = {};
switch ( uniform.type ) {
case 't':
material.uniforms[ name ].value = getTexture( uniform.value );
break;
case 'c':
material.uniforms[ name ].value = new Color().setHex( uniform.value );
break;
case 'v2':
material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
break;
case 'v3':
material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
break;
case 'v4':
material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
break;
case 'm3':
material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
case 'm4':
material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
break;
default:
material.uniforms[ name ].value = uniform.value;
}
}
}
if ( json.defines !== undefined ) material.defines = json.defines;
if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
if ( json.extensions !== undefined ) {
for ( var key in json.extensions ) {
material.extensions[ key ] = json.extensions[ key ];
}
}
// Deprecated
if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
// for PointsMaterial
if ( json.size !== undefined ) material.size = json.size;
if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
// maps
if ( json.map !== undefined ) material.map = getTexture( json.map );
if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
if ( json.normalScale !== undefined ) {
var normalScale = json.normalScale;
if ( Array.isArray( normalScale ) === false ) {
// Blender exporter used to export a scalar. See #7459
normalScale = [ normalScale, normalScale ];
}
material.normalScale = new Vector2().fromArray( normalScale );
}
if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
return material;
},
setTextures: function ( value ) {
this.textures = value;
return this;
}
} );
/**
* @author Don McCurdy / https://www.donmccurdy.com
*/
var LoaderUtils = {
decodeText: function ( array ) {
if ( typeof TextDecoder !== 'undefined' ) {
return new TextDecoder().decode( array );
}
// Avoid the String.fromCharCode.apply(null, array) shortcut, which
// throws a "maximum call stack size exceeded" error for large arrays.
var s = '';
for ( var i = 0, il = array.length; i < il; i ++ ) {
// Implicitly assumes little-endian.
s += String.fromCharCode( array[ i ] );
}
try {
// merges multi-byte utf-8 characters.
return decodeURIComponent( escape( s ) );
} catch ( e ) { // see #16358
return s;
}
},
extractUrlBase: function ( url ) {
var index = url.lastIndexOf( '/' );
if ( index === - 1 ) return './';
return url.substr( 0, index + 1 );
}
};
/**
* @author benaadams / https://twitter.com/ben_a_adams
*/
function InstancedBufferGeometry() {
BufferGeometry.call( this );
this.type = 'InstancedBufferGeometry';
this.maxInstancedCount = undefined;
}
InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
constructor: InstancedBufferGeometry,
isInstancedBufferGeometry: true,
copy: function ( source ) {
BufferGeometry.prototype.copy.call( this, source );
this.maxInstancedCount = source.maxInstancedCount;
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
toJSON: function () {
var data = BufferGeometry.prototype.toJSON.call( this );
data.maxInstancedCount = this.maxInstancedCount;
data.isInstancedBufferGeometry = true;
return data;
}
} );
/**
* @author benaadams / https://twitter.com/ben_a_adams
*/
function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
if ( typeof ( normalized ) === 'number' ) {
meshPerAttribute = normalized;
normalized = false;
console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
}
BufferAttribute.call( this, array, itemSize, normalized );
this.meshPerAttribute = meshPerAttribute || 1;
}
InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
constructor: InstancedBufferAttribute,
isInstancedBufferAttribute: true,
copy: function ( source ) {
BufferAttribute.prototype.copy.call( this, source );
this.meshPerAttribute = source.meshPerAttribute;
return this;
},
toJSON: function () {
var data = BufferAttribute.prototype.toJSON.call( this );
data.meshPerAttribute = this.meshPerAttribute;
data.isInstancedBufferAttribute = true;
return data;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function BufferGeometryLoader( manager ) {
Loader.call( this, manager );
}
BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: BufferGeometryLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new FileLoader( scope.manager );
loader.setPath( scope.path );
loader.load( url, function ( text ) {
onLoad( scope.parse( JSON.parse( text ) ) );
}, onProgress, onError );
},
parse: function ( json ) {
var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
var index = json.data.index;
if ( index !== undefined ) {
var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
}
var attributes = json.data.attributes;
for ( var key in attributes ) {
var attribute = attributes[ key ];
var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
var bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
geometry.setAttribute( key, bufferAttribute );
}
var morphAttributes = json.data.morphAttributes;
if ( morphAttributes ) {
for ( var key in morphAttributes ) {
var attributeArray = morphAttributes[ key ];
var array = [];
for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
var attribute = attributeArray[ i ];
var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
array.push( bufferAttribute );
}
geometry.morphAttributes[ key ] = array;
}
}
var morphTargetsRelative = json.data.morphTargetsRelative;
if ( morphTargetsRelative ) {
geometry.morphTargetsRelative = true;
}
var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
if ( groups !== undefined ) {
for ( var i = 0, n = groups.length; i !== n; ++ i ) {
var group = groups[ i ];
geometry.addGroup( group.start, group.count, group.materialIndex );
}
}
var boundingSphere = json.data.boundingSphere;
if ( boundingSphere !== undefined ) {
var center = new Vector3();
if ( boundingSphere.center !== undefined ) {
center.fromArray( boundingSphere.center );
}
geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
}
if ( json.name ) geometry.name = json.name;
if ( json.userData ) geometry.userData = json.userData;
return geometry;
}
} );
var TYPED_ARRAYS = {
Int8Array: Int8Array,
Uint8Array: Uint8Array,
// Workaround for IE11 pre KB2929437. See #11440
Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
Int16Array: Int16Array,
Uint16Array: Uint16Array,
Int32Array: Int32Array,
Uint32Array: Uint32Array,
Float32Array: Float32Array,
Float64Array: Float64Array
};
/**
* @author mrdoob / http://mrdoob.com/
*/
function ObjectLoader( manager ) {
Loader.call( this, manager );
}
ObjectLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: ObjectLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
this.resourcePath = this.resourcePath || path;
var loader = new FileLoader( scope.manager );
loader.setPath( this.path );
loader.load( url, function ( text ) {
var json = null;
try {
json = JSON.parse( text );
} catch ( error ) {
if ( onError !== undefined ) onError( error );
console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
return;
}
var metadata = json.metadata;
if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
return;
}
scope.parse( json, onLoad );
}, onProgress, onError );
},
parse: function ( json, onLoad ) {
var shapes = this.parseShape( json.shapes );
var geometries = this.parseGeometries( json.geometries, shapes );
var images = this.parseImages( json.images, function () {
if ( onLoad !== undefined ) onLoad( object );
} );
var textures = this.parseTextures( json.textures, images );
var materials = this.parseMaterials( json.materials, textures );
var object = this.parseObject( json.object, geometries, materials );
if ( json.animations ) {
object.animations = this.parseAnimations( json.animations );
}
if ( json.images === undefined || json.images.length === 0 ) {
if ( onLoad !== undefined ) onLoad( object );
}
return object;
},
parseShape: function ( json ) {
var shapes = {};
if ( json !== undefined ) {
for ( var i = 0, l = json.length; i < l; i ++ ) {
var shape = new Shape().fromJSON( json[ i ] );
shapes[ shape.uuid ] = shape;
}
}
return shapes;
},
parseGeometries: function ( json, shapes ) {
var geometries = {};
if ( json !== undefined ) {
var bufferGeometryLoader = new BufferGeometryLoader();
for ( var i = 0, l = json.length; i < l; i ++ ) {
var geometry;
var data = json[ i ];
switch ( data.type ) {
case 'PlaneGeometry':
case 'PlaneBufferGeometry':
geometry = new Geometries[ data.type ](
data.width,
data.height,
data.widthSegments,
data.heightSegments
);
break;
case 'BoxGeometry':
case 'BoxBufferGeometry':
case 'CubeGeometry': // backwards compatible
geometry = new Geometries[ data.type ](
data.width,
data.height,
data.depth,
data.widthSegments,
data.heightSegments,
data.depthSegments
);
break;
case 'CircleGeometry':
case 'CircleBufferGeometry':
geometry = new Geometries[ data.type ](
data.radius,
data.segments,
data.thetaStart,
data.thetaLength
);
break;
case 'CylinderGeometry':
case 'CylinderBufferGeometry':
geometry = new Geometries[ data.type ](
data.radiusTop,
data.radiusBottom,
data.height,
data.radialSegments,
data.heightSegments,
data.openEnded,
data.thetaStart,
data.thetaLength
);
break;
case 'ConeGeometry':
case 'ConeBufferGeometry':
geometry = new Geometries[ data.type ](
data.radius,
data.height,
data.radialSegments,
data.heightSegments,
data.openEnded,
data.thetaStart,
data.thetaLength
);
break;
case 'SphereGeometry':
case 'SphereBufferGeometry':
geometry = new Geometries[ data.type ](
data.radius,
data.widthSegments,
data.heightSegments,
data.phiStart,
data.phiLength,
data.thetaStart,
data.thetaLength
);
break;
case 'DodecahedronGeometry':
case 'DodecahedronBufferGeometry':
case 'IcosahedronGeometry':
case 'IcosahedronBufferGeometry':
case 'OctahedronGeometry':
case 'OctahedronBufferGeometry':
case 'TetrahedronGeometry':
case 'TetrahedronBufferGeometry':
geometry = new Geometries[ data.type ](
data.radius,
data.detail
);
break;
case 'RingGeometry':
case 'RingBufferGeometry':
geometry = new Geometries[ data.type ](
data.innerRadius,
data.outerRadius,
data.thetaSegments,
data.phiSegments,
data.thetaStart,
data.thetaLength
);
break;
case 'TorusGeometry':
case 'TorusBufferGeometry':
geometry = new Geometries[ data.type ](
data.radius,
data.tube,
data.radialSegments,
data.tubularSegments,
data.arc
);
break;
case 'TorusKnotGeometry':
case 'TorusKnotBufferGeometry':
geometry = new Geometries[ data.type ](
data.radius,
data.tube,
data.tubularSegments,
data.radialSegments,
data.p,
data.q
);
break;
case 'TubeGeometry':
case 'TubeBufferGeometry':
// This only works for built-in curves (e.g. CatmullRomCurve3).
// User defined curves or instances of CurvePath will not be deserialized.
geometry = new Geometries[ data.type ](
new Curves[ data.path.type ]().fromJSON( data.path ),
data.tubularSegments,
data.radius,
data.radialSegments,
data.closed
);
break;
case 'LatheGeometry':
case 'LatheBufferGeometry':
geometry = new Geometries[ data.type ](
data.points,
data.segments,
data.phiStart,
data.phiLength
);
break;
case 'PolyhedronGeometry':
case 'PolyhedronBufferGeometry':
geometry = new Geometries[ data.type ](
data.vertices,
data.indices,
data.radius,
data.details
);
break;
case 'ShapeGeometry':
case 'ShapeBufferGeometry':
var geometryShapes = [];
for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
var shape = shapes[ data.shapes[ j ] ];
geometryShapes.push( shape );
}
geometry = new Geometries[ data.type ](
geometryShapes,
data.curveSegments
);
break;
case 'ExtrudeGeometry':
case 'ExtrudeBufferGeometry':
var geometryShapes = [];
for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
var shape = shapes[ data.shapes[ j ] ];
geometryShapes.push( shape );
}
var extrudePath = data.options.extrudePath;
if ( extrudePath !== undefined ) {
data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
}
geometry = new Geometries[ data.type ](
geometryShapes,
data.options
);
break;
case 'BufferGeometry':
case 'InstancedBufferGeometry':
geometry = bufferGeometryLoader.parse( data );
break;
case 'Geometry':
console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );
break;
default:
console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
continue;
}
geometry.uuid = data.uuid;
if ( data.name !== undefined ) geometry.name = data.name;
if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
geometries[ data.uuid ] = geometry;
}
}
return geometries;
},
parseMaterials: function ( json, textures ) {
var cache = {}; // MultiMaterial
var materials = {};
if ( json !== undefined ) {
var loader = new MaterialLoader();
loader.setTextures( textures );
for ( var i = 0, l = json.length; i < l; i ++ ) {
var data = json[ i ];
if ( data.type === 'MultiMaterial' ) {
// Deprecated
var array = [];
for ( var j = 0; j < data.materials.length; j ++ ) {
var material = data.materials[ j ];
if ( cache[ material.uuid ] === undefined ) {
cache[ material.uuid ] = loader.parse( material );
}
array.push( cache[ material.uuid ] );
}
materials[ data.uuid ] = array;
} else {
if ( cache[ data.uuid ] === undefined ) {
cache[ data.uuid ] = loader.parse( data );
}
materials[ data.uuid ] = cache[ data.uuid ];
}
}
}
return materials;
},
parseAnimations: function ( json ) {
var animations = [];
for ( var i = 0; i < json.length; i ++ ) {
var data = json[ i ];
var clip = AnimationClip.parse( data );
if ( data.uuid !== undefined ) clip.uuid = data.uuid;
animations.push( clip );
}
return animations;
},
parseImages: function ( json, onLoad ) {
var scope = this;
var images = {};
function loadImage( url ) {
scope.manager.itemStart( url );
return loader.load( url, function () {
scope.manager.itemEnd( url );
}, undefined, function () {
scope.manager.itemError( url );
scope.manager.itemEnd( url );
} );
}
if ( json !== undefined && json.length > 0 ) {
var manager = new LoadingManager( onLoad );
var loader = new ImageLoader( manager );
loader.setCrossOrigin( this.crossOrigin );
for ( var i = 0, il = json.length; i < il; i ++ ) {
var image = json[ i ];
var url = image.url;
if ( Array.isArray( url ) ) {
// load array of images e.g CubeTexture
images[ image.uuid ] = [];
for ( var j = 0, jl = url.length; j < jl; j ++ ) {
var currentUrl = url[ j ];
var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl;
images[ image.uuid ].push( loadImage( path ) );
}
} else {
// load single image
var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url;
images[ image.uuid ] = loadImage( path );
}
}
}
return images;
},
parseTextures: function ( json, images ) {
function parseConstant( value, type ) {
if ( typeof value === 'number' ) return value;
console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
return type[ value ];
}
var textures = {};
if ( json !== undefined ) {
for ( var i = 0, l = json.length; i < l; i ++ ) {
var data = json[ i ];
if ( data.image === undefined ) {
console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
}
if ( images[ data.image ] === undefined ) {
console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
}
var texture;
if ( Array.isArray( images[ data.image ] ) ) {
texture = new CubeTexture( images[ data.image ] );
} else {
texture = new Texture( images[ data.image ] );
}
texture.needsUpdate = true;
texture.uuid = data.uuid;
if ( data.name !== undefined ) texture.name = data.name;
if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
if ( data.center !== undefined ) texture.center.fromArray( data.center );
if ( data.rotation !== undefined ) texture.rotation = data.rotation;
if ( data.wrap !== undefined ) {
texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
}
if ( data.format !== undefined ) texture.format = data.format;
if ( data.type !== undefined ) texture.type = data.type;
if ( data.encoding !== undefined ) texture.encoding = data.encoding;
if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
if ( data.flipY !== undefined ) texture.flipY = data.flipY;
if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
textures[ data.uuid ] = texture;
}
}
return textures;
},
parseObject: function ( data, geometries, materials ) {
var object;
function getGeometry( name ) {
if ( geometries[ name ] === undefined ) {
console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
}
return geometries[ name ];
}
function getMaterial( name ) {
if ( name === undefined ) return undefined;
if ( Array.isArray( name ) ) {
var array = [];
for ( var i = 0, l = name.length; i < l; i ++ ) {
var uuid = name[ i ];
if ( materials[ uuid ] === undefined ) {
console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
}
array.push( materials[ uuid ] );
}
return array;
}
if ( materials[ name ] === undefined ) {
console.warn( 'THREE.ObjectLoader: Undefined material', name );
}
return materials[ name ];
}
switch ( data.type ) {
case 'Scene':
object = new Scene();
if ( data.background !== undefined ) {
if ( Number.isInteger( data.background ) ) {
object.background = new Color( data.background );
}
}
if ( data.fog !== undefined ) {
if ( data.fog.type === 'Fog' ) {
object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
} else if ( data.fog.type === 'FogExp2' ) {
object.fog = new FogExp2( data.fog.color, data.fog.density );
}
}
break;
case 'PerspectiveCamera':
object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
if ( data.focus !== undefined ) object.focus = data.focus;
if ( data.zoom !== undefined ) object.zoom = data.zoom;
if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
break;
case 'OrthographicCamera':
object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
if ( data.zoom !== undefined ) object.zoom = data.zoom;
if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
break;
case 'AmbientLight':
object = new AmbientLight( data.color, data.intensity );
break;
case 'DirectionalLight':
object = new DirectionalLight( data.color, data.intensity );
break;
case 'PointLight':
object = new PointLight( data.color, data.intensity, data.distance, data.decay );
break;
case 'RectAreaLight':
object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
break;
case 'SpotLight':
object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
break;
case 'HemisphereLight':
object = new HemisphereLight( data.color, data.groundColor, data.intensity );
break;
case 'LightProbe':
object = new LightProbe().fromJSON( data );
break;
case 'SkinnedMesh':
console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
case 'Mesh':
var geometry = getGeometry( data.geometry );
var material = getMaterial( data.material );
object = new Mesh( geometry, material );
break;
case 'InstancedMesh':
var geometry = getGeometry( data.geometry );
var material = getMaterial( data.material );
var count = data.count;
var instanceMatrix = data.instanceMatrix;
object = new InstancedMesh( geometry, material, count );
object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
break;
case 'LOD':
object = new LOD();
break;
case 'Line':
object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
break;
case 'LineLoop':
object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
break;
case 'LineSegments':
object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
break;
case 'PointCloud':
case 'Points':
object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
break;
case 'Sprite':
object = new Sprite( getMaterial( data.material ) );
break;
case 'Group':
object = new Group();
break;
default:
object = new Object3D();
}
object.uuid = data.uuid;
if ( data.name !== undefined ) object.name = data.name;
if ( data.matrix !== undefined ) {
object.matrix.fromArray( data.matrix );
if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
} else {
if ( data.position !== undefined ) object.position.fromArray( data.position );
if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
}
if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
if ( data.shadow ) {
if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
}
if ( data.visible !== undefined ) object.visible = data.visible;
if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
if ( data.userData !== undefined ) object.userData = data.userData;
if ( data.layers !== undefined ) object.layers.mask = data.layers;
if ( data.children !== undefined ) {
var children = data.children;
for ( var i = 0; i < children.length; i ++ ) {
object.add( this.parseObject( children[ i ], geometries, materials ) );
}
}
if ( data.type === 'LOD' ) {
if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
var levels = data.levels;
for ( var l = 0; l < levels.length; l ++ ) {
var level = levels[ l ];
var child = object.getObjectByProperty( 'uuid', level.object );
if ( child !== undefined ) {
object.addLevel( child, level.distance );
}
}
}
return object;
}
} );
var TEXTURE_MAPPING = {
UVMapping: UVMapping,
CubeReflectionMapping: CubeReflectionMapping,
CubeRefractionMapping: CubeRefractionMapping,
EquirectangularReflectionMapping: EquirectangularReflectionMapping,
EquirectangularRefractionMapping: EquirectangularRefractionMapping,
SphericalReflectionMapping: SphericalReflectionMapping,
CubeUVReflectionMapping: CubeUVReflectionMapping,
CubeUVRefractionMapping: CubeUVRefractionMapping
};
var TEXTURE_WRAPPING = {
RepeatWrapping: RepeatWrapping,
ClampToEdgeWrapping: ClampToEdgeWrapping,
MirroredRepeatWrapping: MirroredRepeatWrapping
};
var TEXTURE_FILTER = {
NearestFilter: NearestFilter,
NearestMipmapNearestFilter: NearestMipmapNearestFilter,
NearestMipmapLinearFilter: NearestMipmapLinearFilter,
LinearFilter: LinearFilter,
LinearMipmapNearestFilter: LinearMipmapNearestFilter,
LinearMipmapLinearFilter: LinearMipmapLinearFilter
};
/**
* @author thespite / http://clicktorelease.com/
*/
function ImageBitmapLoader( manager ) {
if ( typeof createImageBitmap === 'undefined' ) {
console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
}
if ( typeof fetch === 'undefined' ) {
console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
}
Loader.call( this, manager );
this.options = undefined;
}
ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: ImageBitmapLoader,
setOptions: function setOptions( options ) {
this.options = options;
return this;
},
load: function ( url, onLoad, onProgress, onError ) {
if ( url === undefined ) url = '';
if ( this.path !== undefined ) url = this.path + url;
url = this.manager.resolveURL( url );
var scope = this;
var cached = Cache.get( url );
if ( cached !== undefined ) {
scope.manager.itemStart( url );
setTimeout( function () {
if ( onLoad ) onLoad( cached );
scope.manager.itemEnd( url );
}, 0 );
return cached;
}
fetch( url ).then( function ( res ) {
return res.blob();
} ).then( function ( blob ) {
if ( scope.options === undefined ) {
// Workaround for FireFox. It causes an error if you pass options.
return createImageBitmap( blob );
} else {
return createImageBitmap( blob, scope.options );
}
} ).then( function ( imageBitmap ) {
Cache.add( url, imageBitmap );
if ( onLoad ) onLoad( imageBitmap );
scope.manager.itemEnd( url );
} ).catch( function ( e ) {
if ( onError ) onError( e );
scope.manager.itemError( url );
scope.manager.itemEnd( url );
} );
scope.manager.itemStart( url );
}
} );
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
**/
function ShapePath() {
this.type = 'ShapePath';
this.color = new Color();
this.subPaths = [];
this.currentPath = null;
}
Object.assign( ShapePath.prototype, {
moveTo: function ( x, y ) {
this.currentPath = new Path();
this.subPaths.push( this.currentPath );
this.currentPath.moveTo( x, y );
return this;
},
lineTo: function ( x, y ) {
this.currentPath.lineTo( x, y );
return this;
},
quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
return this;
},
bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
return this;
},
splineThru: function ( pts ) {
this.currentPath.splineThru( pts );
return this;
},
toShapes: function ( isCCW, noHoles ) {
function toShapesNoHoles( inSubpaths ) {
var shapes = [];
for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
var tmpPath = inSubpaths[ i ];
var tmpShape = new Shape();
tmpShape.curves = tmpPath.curves;
shapes.push( tmpShape );
}
return shapes;
}
function isPointInsidePolygon( inPt, inPolygon ) {
var polyLen = inPolygon.length;
// inPt on polygon contour => immediate success or
// toggling of inside/outside at every single! intersection point of an edge
// with the horizontal line through inPt, left of inPt
// not counting lowerY endpoints of edges and whole edges on that line
var inside = false;
for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
var edgeLowPt = inPolygon[ p ];
var edgeHighPt = inPolygon[ q ];
var edgeDx = edgeHighPt.x - edgeLowPt.x;
var edgeDy = edgeHighPt.y - edgeLowPt.y;
if ( Math.abs( edgeDy ) > Number.EPSILON ) {
// not parallel
if ( edgeDy < 0 ) {
edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
}
if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
if ( inPt.y === edgeLowPt.y ) {
if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
// continue; // no intersection or edgeLowPt => doesn't count !!!
} else {
var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
if ( perpEdge === 0 ) return true; // inPt is on contour ?
if ( perpEdge < 0 ) continue;
inside = ! inside; // true intersection left of inPt
}
} else {
// parallel or collinear
if ( inPt.y !== edgeLowPt.y ) continue; // parallel
// edge lies on the same horizontal line as inPt
if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
// continue;
}
}
return inside;
}
var isClockWise = ShapeUtils.isClockWise;
var subPaths = this.subPaths;
if ( subPaths.length === 0 ) return [];
if ( noHoles === true ) return toShapesNoHoles( subPaths );
var solid, tmpPath, tmpShape, shapes = [];
if ( subPaths.length === 1 ) {
tmpPath = subPaths[ 0 ];
tmpShape = new Shape();
tmpShape.curves = tmpPath.curves;
shapes.push( tmpShape );
return shapes;
}
var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
holesFirst = isCCW ? ! holesFirst : holesFirst;
// console.log("Holes first", holesFirst);
var betterShapeHoles = [];
var newShapes = [];
var newShapeHoles = [];
var mainIdx = 0;
var tmpPoints;
newShapes[ mainIdx ] = undefined;
newShapeHoles[ mainIdx ] = [];
for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
tmpPath = subPaths[ i ];
tmpPoints = tmpPath.getPoints();
solid = isClockWise( tmpPoints );
solid = isCCW ? ! solid : solid;
if ( solid ) {
if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
newShapes[ mainIdx ].s.curves = tmpPath.curves;
if ( holesFirst ) mainIdx ++;
newShapeHoles[ mainIdx ] = [];
//console.log('cw', i);
} else {
newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
//console.log('ccw', i);
}
}
// only Holes? -> probably all Shapes with wrong orientation
if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
if ( newShapes.length > 1 ) {
var ambiguous = false;
var toChange = [];
for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
betterShapeHoles[ sIdx ] = [];
}
for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
var sho = newShapeHoles[ sIdx ];
for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
var ho = sho[ hIdx ];
var hole_unassigned = true;
for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
if ( hole_unassigned ) {
hole_unassigned = false;
betterShapeHoles[ s2Idx ].push( ho );
} else {
ambiguous = true;
}
}
}
if ( hole_unassigned ) {
betterShapeHoles[ sIdx ].push( ho );
}
}
}
// console.log("ambiguous: ", ambiguous);
if ( toChange.length > 0 ) {
// console.log("to change: ", toChange);
if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
}
}
var tmpHoles;
for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
tmpShape = newShapes[ i ].s;
shapes.push( tmpShape );
tmpHoles = newShapeHoles[ i ];
for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
tmpShape.holes.push( tmpHoles[ j ].h );
}
}
//console.log("shape", shapes);
return shapes;
}
} );
/**
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author mrdoob / http://mrdoob.com/
*/
function Font( data ) {
this.type = 'Font';
this.data = data;
}
Object.assign( Font.prototype, {
isFont: true,
generateShapes: function ( text, size ) {
if ( size === undefined ) size = 100;
var shapes = [];
var paths = createPaths( text, size, this.data );
for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
}
return shapes;
}
} );
function createPaths( text, size, data ) {
var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988
var scale = size / data.resolution;
var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
var paths = [];
var offsetX = 0, offsetY = 0;
for ( var i = 0; i < chars.length; i ++ ) {
var char = chars[ i ];
if ( char === '\n' ) {
offsetX = 0;
offsetY -= line_height;
} else {
var ret = createPath( char, scale, offsetX, offsetY, data );
offsetX += ret.offsetX;
paths.push( ret.path );
}
}
return paths;
}
function createPath( char, scale, offsetX, offsetY, data ) {
var glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
if ( ! glyph ) {
console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
return;
}
var path = new ShapePath();
var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
if ( glyph.o ) {
var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
for ( var i = 0, l = outline.length; i < l; ) {
var action = outline[ i ++ ];
switch ( action ) {
case 'm': // moveTo
x = outline[ i ++ ] * scale + offsetX;
y = outline[ i ++ ] * scale + offsetY;
path.moveTo( x, y );
break;
case 'l': // lineTo
x = outline[ i ++ ] * scale + offsetX;
y = outline[ i ++ ] * scale + offsetY;
path.lineTo( x, y );
break;
case 'q': // quadraticCurveTo
cpx = outline[ i ++ ] * scale + offsetX;
cpy = outline[ i ++ ] * scale + offsetY;
cpx1 = outline[ i ++ ] * scale + offsetX;
cpy1 = outline[ i ++ ] * scale + offsetY;
path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
break;
case 'b': // bezierCurveTo
cpx = outline[ i ++ ] * scale + offsetX;
cpy = outline[ i ++ ] * scale + offsetY;
cpx1 = outline[ i ++ ] * scale + offsetX;
cpy1 = outline[ i ++ ] * scale + offsetY;
cpx2 = outline[ i ++ ] * scale + offsetX;
cpy2 = outline[ i ++ ] * scale + offsetY;
path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
break;
}
}
}
return { offsetX: glyph.ha * scale, path: path };
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function FontLoader( manager ) {
Loader.call( this, manager );
}
FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: FontLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new FileLoader( this.manager );
loader.setPath( this.path );
loader.load( url, function ( text ) {
var json;
try {
json = JSON.parse( text );
} catch ( e ) {
console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
json = JSON.parse( text.substring( 65, text.length - 2 ) );
}
var font = scope.parse( json );
if ( onLoad ) onLoad( font );
}, onProgress, onError );
},
parse: function ( json ) {
return new Font( json );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
var _context;
var AudioContext = {
getContext: function () {
if ( _context === undefined ) {
_context = new ( window.AudioContext || window.webkitAudioContext )();
}
return _context;
},
setContext: function ( value ) {
_context = value;
}
};
/**
* @author Reece Aaron Lecrivain / http://reecenotes.com/
*/
function AudioLoader( manager ) {
Loader.call( this, manager );
}
AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: AudioLoader,
load: function ( url, onLoad, onProgress, onError ) {
var loader = new FileLoader( this.manager );
loader.setResponseType( 'arraybuffer' );
loader.setPath( this.path );
loader.load( url, function ( buffer ) {
// Create a copy of the buffer. The `decodeAudioData` method
// detaches the buffer when complete, preventing reuse.
var bufferCopy = buffer.slice( 0 );
var context = AudioContext.getContext();
context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
onLoad( audioBuffer );
} );
}, onProgress, onError );
}
} );
/**
* @author WestLangley / http://github.com/WestLangley
*/
function HemisphereLightProbe( skyColor, groundColor, intensity ) {
LightProbe.call( this, undefined, intensity );
var color1 = new Color().set( skyColor );
var color2 = new Color().set( groundColor );
var sky = new Vector3( color1.r, color1.g, color1.b );
var ground = new Vector3( color2.r, color2.g, color2.b );
// without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
var c0 = Math.sqrt( Math.PI );
var c1 = c0 * Math.sqrt( 0.75 );
this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
}
HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
constructor: HemisphereLightProbe,
isHemisphereLightProbe: true,
copy: function ( source ) { // modifying colors not currently supported
LightProbe.prototype.copy.call( this, source );
return this;
},
toJSON: function ( meta ) {
var data = LightProbe.prototype.toJSON.call( this, meta );
// data.sh = this.sh.toArray(); // todo
return data;
}
} );
/**
* @author WestLangley / http://github.com/WestLangley
*/
function AmbientLightProbe( color, intensity ) {
LightProbe.call( this, undefined, intensity );
var color1 = new Color().set( color );
// without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
}
AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
constructor: AmbientLightProbe,
isAmbientLightProbe: true,
copy: function ( source ) { // modifying color not currently supported
LightProbe.prototype.copy.call( this, source );
return this;
},
toJSON: function ( meta ) {
var data = LightProbe.prototype.toJSON.call( this, meta );
// data.sh = this.sh.toArray(); // todo
return data;
}
} );
var _eyeRight = new Matrix4();
var _eyeLeft = new Matrix4();
/**
* @author mrdoob / http://mrdoob.com/
*/
function StereoCamera() {
this.type = 'StereoCamera';
this.aspect = 1;
this.eyeSep = 0.064;
this.cameraL = new PerspectiveCamera();
this.cameraL.layers.enable( 1 );
this.cameraL.matrixAutoUpdate = false;
this.cameraR = new PerspectiveCamera();
this.cameraR.layers.enable( 2 );
this.cameraR.matrixAutoUpdate = false;
this._cache = {
focus: null,
fov: null,
aspect: null,
near: null,
far: null,
zoom: null,
eyeSep: null
};
}
Object.assign( StereoCamera.prototype, {
update: function ( camera ) {
var cache = this._cache;
var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
if ( needsUpdate ) {
cache.focus = camera.focus;
cache.fov = camera.fov;
cache.aspect = camera.aspect * this.aspect;
cache.near = camera.near;
cache.far = camera.far;
cache.zoom = camera.zoom;
cache.eyeSep = this.eyeSep;
// Off-axis stereoscopic effect based on
// http://paulbourke.net/stereographics/stereorender/
var projectionMatrix = camera.projectionMatrix.clone();
var eyeSepHalf = cache.eyeSep / 2;
var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
var ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
var xmin, xmax;
// translate xOffset
_eyeLeft.elements[ 12 ] = - eyeSepHalf;
_eyeRight.elements[ 12 ] = eyeSepHalf;
// for left eye
xmin = - ymax * cache.aspect + eyeSepOnProjection;
xmax = ymax * cache.aspect + eyeSepOnProjection;
projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
this.cameraL.projectionMatrix.copy( projectionMatrix );
// for right eye
xmin = - ymax * cache.aspect - eyeSepOnProjection;
xmax = ymax * cache.aspect - eyeSepOnProjection;
projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
this.cameraR.projectionMatrix.copy( projectionMatrix );
}
this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
}
} );
/**
* @author alteredq / http://alteredqualia.com/
*/
function Clock( autoStart ) {
this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
this.startTime = 0;
this.oldTime = 0;
this.elapsedTime = 0;
this.running = false;
}
Object.assign( Clock.prototype, {
start: function () {
this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
this.oldTime = this.startTime;
this.elapsedTime = 0;
this.running = true;
},
stop: function () {
this.getElapsedTime();
this.running = false;
this.autoStart = false;
},
getElapsedTime: function () {
this.getDelta();
return this.elapsedTime;
},
getDelta: function () {
var diff = 0;
if ( this.autoStart && ! this.running ) {
this.start();
return 0;
}
if ( this.running ) {
var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
diff = ( newTime - this.oldTime ) / 1000;
this.oldTime = newTime;
this.elapsedTime += diff;
}
return diff;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
var _position$2 = new Vector3();
var _quaternion$3 = new Quaternion();
var _scale$1 = new Vector3();
var _orientation = new Vector3();
function AudioListener() {
Object3D.call( this );
this.type = 'AudioListener';
this.context = AudioContext.getContext();
this.gain = this.context.createGain();
this.gain.connect( this.context.destination );
this.filter = null;
this.timeDelta = 0;
// private
this._clock = new Clock();
}
AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: AudioListener,
getInput: function () {
return this.gain;
},
removeFilter: function ( ) {
if ( this.filter !== null ) {
this.gain.disconnect( this.filter );
this.filter.disconnect( this.context.destination );
this.gain.connect( this.context.destination );
this.filter = null;
}
return this;
},
getFilter: function () {
return this.filter;
},
setFilter: function ( value ) {
if ( this.filter !== null ) {
this.gain.disconnect( this.filter );
this.filter.disconnect( this.context.destination );
} else {
this.gain.disconnect( this.context.destination );
}
this.filter = value;
this.gain.connect( this.filter );
this.filter.connect( this.context.destination );
return this;
},
getMasterVolume: function () {
return this.gain.gain.value;
},
setMasterVolume: function ( value ) {
this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
return this;
},
updateMatrixWorld: function ( force ) {
Object3D.prototype.updateMatrixWorld.call( this, force );
var listener = this.context.listener;
var up = this.up;
this.timeDelta = this._clock.getDelta();
this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );
_orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );
if ( listener.positionX ) {
// code path for Chrome (see #14393)
var endTime = this.context.currentTime + this.timeDelta;
listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
listener.upX.linearRampToValueAtTime( up.x, endTime );
listener.upY.linearRampToValueAtTime( up.y, endTime );
listener.upZ.linearRampToValueAtTime( up.z, endTime );
} else {
listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );
}
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author Reece Aaron Lecrivain / http://reecenotes.com/
*/
function Audio( listener ) {
Object3D.call( this );
this.type = 'Audio';
this.listener = listener;
this.context = listener.context;
this.gain = this.context.createGain();
this.gain.connect( listener.getInput() );
this.autoplay = false;
this.buffer = null;
this.detune = 0;
this.loop = false;
this.loopStart = 0;
this.loopEnd = 0;
this.offset = 0;
this.duration = undefined;
this.playbackRate = 1;
this.isPlaying = false;
this.hasPlaybackControl = true;
this.sourceType = 'empty';
this._startedAt = 0;
this._progress = 0;
this.filters = [];
}
Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
constructor: Audio,
getOutput: function () {
return this.gain;
},
setNodeSource: function ( audioNode ) {
this.hasPlaybackControl = false;
this.sourceType = 'audioNode';
this.source = audioNode;
this.connect();
return this;
},
setMediaElementSource: function ( mediaElement ) {
this.hasPlaybackControl = false;
this.sourceType = 'mediaNode';
this.source = this.context.createMediaElementSource( mediaElement );
this.connect();
return this;
},
setMediaStreamSource: function ( mediaStream ) {
this.hasPlaybackControl = false;
this.sourceType = 'mediaStreamNode';
this.source = this.context.createMediaStreamSource( mediaStream );
this.connect();
return this;
},
setBuffer: function ( audioBuffer ) {
this.buffer = audioBuffer;
this.sourceType = 'buffer';
if ( this.autoplay ) this.play();
return this;
},
play: function ( delay ) {
if ( delay === undefined ) delay = 0;
if ( this.isPlaying === true ) {
console.warn( 'THREE.Audio: Audio is already playing.' );
return;
}
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return;
}
this._startedAt = this.context.currentTime + delay;
var source = this.context.createBufferSource();
source.buffer = this.buffer;
source.loop = this.loop;
source.loopStart = this.loopStart;
source.loopEnd = this.loopEnd;
source.onended = this.onEnded.bind( this );
source.start( this._startedAt, this._progress + this.offset, this.duration );
this.isPlaying = true;
this.source = source;
this.setDetune( this.detune );
this.setPlaybackRate( this.playbackRate );
return this.connect();
},
pause: function () {
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return;
}
if ( this.isPlaying === true ) {
// update current progress
this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
if ( this.loop === true ) {
// ensure _progress does not exceed duration with looped audios
this._progress = this._progress % ( this.duration || this.buffer.duration );
}
this.source.stop();
this.source.onended = null;
this.isPlaying = false;
}
return this;
},
stop: function () {
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return;
}
this._progress = 0;
this.source.stop();
this.source.onended = null;
this.isPlaying = false;
return this;
},
connect: function () {
if ( this.filters.length > 0 ) {
this.source.connect( this.filters[ 0 ] );
for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
this.filters[ i - 1 ].connect( this.filters[ i ] );
}
this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
} else {
this.source.connect( this.getOutput() );
}
return this;
},
disconnect: function () {
if ( this.filters.length > 0 ) {
this.source.disconnect( this.filters[ 0 ] );
for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
this.filters[ i - 1 ].disconnect( this.filters[ i ] );
}
this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
} else {
this.source.disconnect( this.getOutput() );
}
return this;
},
getFilters: function () {
return this.filters;
},
setFilters: function ( value ) {
if ( ! value ) value = [];
if ( this.isPlaying === true ) {
this.disconnect();
this.filters = value;
this.connect();
} else {
this.filters = value;
}
return this;
},
setDetune: function ( value ) {
this.detune = value;
if ( this.source.detune === undefined ) return; // only set detune when available
if ( this.isPlaying === true ) {
this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
}
return this;
},
getDetune: function () {
return this.detune;
},
getFilter: function () {
return this.getFilters()[ 0 ];
},
setFilter: function ( filter ) {
return this.setFilters( filter ? [ filter ] : [] );
},
setPlaybackRate: function ( value ) {
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return;
}
this.playbackRate = value;
if ( this.isPlaying === true ) {
this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
}
return this;
},
getPlaybackRate: function () {
return this.playbackRate;
},
onEnded: function () {
this.isPlaying = false;
},
getLoop: function () {
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return false;
}
return this.loop;
},
setLoop: function ( value ) {
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return;
}
this.loop = value;
if ( this.isPlaying === true ) {
this.source.loop = this.loop;
}
return this;
},
setLoopStart: function ( value ) {
this.loopStart = value;
return this;
},
setLoopEnd: function ( value ) {
this.loopEnd = value;
return this;
},
getVolume: function () {
return this.gain.gain.value;
},
setVolume: function ( value ) {
this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
return this;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
var _position$3 = new Vector3();
var _quaternion$4 = new Quaternion();
var _scale$2 = new Vector3();
var _orientation$1 = new Vector3();
function PositionalAudio( listener ) {
Audio.call( this, listener );
this.panner = this.context.createPanner();
this.panner.panningModel = 'HRTF';
this.panner.connect( this.gain );
}
PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
constructor: PositionalAudio,
getOutput: function () {
return this.panner;
},
getRefDistance: function () {
return this.panner.refDistance;
},
setRefDistance: function ( value ) {
this.panner.refDistance = value;
return this;
},
getRolloffFactor: function () {
return this.panner.rolloffFactor;
},
setRolloffFactor: function ( value ) {
this.panner.rolloffFactor = value;
return this;
},
getDistanceModel: function () {
return this.panner.distanceModel;
},
setDistanceModel: function ( value ) {
this.panner.distanceModel = value;
return this;
},
getMaxDistance: function () {
return this.panner.maxDistance;
},
setMaxDistance: function ( value ) {
this.panner.maxDistance = value;
return this;
},
setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
this.panner.coneInnerAngle = coneInnerAngle;
this.panner.coneOuterAngle = coneOuterAngle;
this.panner.coneOuterGain = coneOuterGain;
return this;
},
updateMatrixWorld: function ( force ) {
Object3D.prototype.updateMatrixWorld.call( this, force );
if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );
_orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );
var panner = this.panner;
if ( panner.positionX ) {
// code path for Chrome and Firefox (see #14393)
var endTime = this.context.currentTime + this.listener.timeDelta;
panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );
} else {
panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );
}
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function AudioAnalyser( audio, fftSize ) {
this.analyser = audio.context.createAnalyser();
this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
this.data = new Uint8Array( this.analyser.frequencyBinCount );
audio.getOutput().connect( this.analyser );
}
Object.assign( AudioAnalyser.prototype, {
getFrequencyData: function () {
this.analyser.getByteFrequencyData( this.data );
return this.data;
},
getAverageFrequency: function () {
var value = 0, data = this.getFrequencyData();
for ( var i = 0; i < data.length; i ++ ) {
value += data[ i ];
}
return value / data.length;
}
} );
/**
*
* Buffered scene graph property that allows weighted accumulation.
*
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*/
function PropertyMixer( binding, typeName, valueSize ) {
this.binding = binding;
this.valueSize = valueSize;
var mixFunction,
mixFunctionAdditive,
setIdentity;
// buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
//
// interpolators can use .buffer as their .result
// the data then goes to 'incoming'
//
// 'accu0' and 'accu1' are used frame-interleaved for
// the cumulative result and are compared to detect
// changes
//
// 'orig' stores the original state of the property
//
// 'add' is used for additive cumulative results
//
// 'work' is optional and is only present for quaternion types. It is used
// to store intermediate quaternion multiplication results
switch ( typeName ) {
case 'quaternion':
mixFunction = this._slerp;
mixFunctionAdditive = this._slerpAdditive;
setIdentity = this._setAdditiveIdentityQuaternion;
this.buffer = new Float64Array( valueSize * 6 );
this._workIndex = 5;
break;
case 'string':
case 'bool':
mixFunction = this._select;
// Use the regular mix function and for additive on these types,
// additive is not relevant for non-numeric types
mixFunctionAdditive = this._select;
setIdentity = this._setAdditiveIdentityOther;
this.buffer = new Array( valueSize * 5 );
break;
default:
mixFunction = this._lerp;
mixFunctionAdditive = this._lerpAdditive;
setIdentity = this._setAdditiveIdentityNumeric;
this.buffer = new Float64Array( valueSize * 5 );
}
this._mixBufferRegion = mixFunction;
this._mixBufferRegionAdditive = mixFunctionAdditive;
this._setIdentity = setIdentity;
this._origIndex = 3;
this._addIndex = 4;
this.cumulativeWeight = 0;
this.cumulativeWeightAdditive = 0;
this.useCount = 0;
this.referenceCount = 0;
}
Object.assign( PropertyMixer.prototype, {
// accumulate data in the 'incoming' region into 'accu<i>'
accumulate: function ( accuIndex, weight ) {
// note: happily accumulating nothing when weight = 0, the caller knows
// the weight and shouldn't have made the call in the first place
var buffer = this.buffer,
stride = this.valueSize,
offset = accuIndex * stride + stride,
currentWeight = this.cumulativeWeight;
if ( currentWeight === 0 ) {
// accuN := incoming * weight
for ( var i = 0; i !== stride; ++ i ) {
buffer[ offset + i ] = buffer[ i ];
}
currentWeight = weight;
} else {
// accuN := accuN + incoming * weight
currentWeight += weight;
var mix = weight / currentWeight;
this._mixBufferRegion( buffer, offset, 0, mix, stride );
}
this.cumulativeWeight = currentWeight;
},
// accumulate data in the 'incoming' region into 'add'
accumulateAdditive: function ( weight ) {
var buffer = this.buffer,
stride = this.valueSize,
offset = stride * this._addIndex;
if ( this.cumulativeWeightAdditive === 0 ) {
// add = identity
this._setIdentity();
}
// add := add + incoming * weight
this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
this.cumulativeWeightAdditive += weight;
},
// apply the state of 'accu<i>' to the binding when accus differ
apply: function ( accuIndex ) {
var stride = this.valueSize,
buffer = this.buffer,
offset = accuIndex * stride + stride,
weight = this.cumulativeWeight,
weightAdditive = this.cumulativeWeightAdditive,
binding = this.binding;
this.cumulativeWeight = 0;
this.cumulativeWeightAdditive = 0;
if ( weight < 1 ) {
// accuN := accuN + original * ( 1 - cumulativeWeight )
var originalValueOffset = stride * this._origIndex;
this._mixBufferRegion(
buffer, offset, originalValueOffset, 1 - weight, stride );
}
if ( weightAdditive > 0 ) {
// accuN := accuN + additive accuN
this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
}
for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
if ( buffer[ i ] !== buffer[ i + stride ] ) {
// value has changed -> update scene graph
binding.setValue( buffer, offset );
break;
}
}
},
// remember the state of the bound property and copy it to both accus
saveOriginalState: function () {
var binding = this.binding;
var buffer = this.buffer,
stride = this.valueSize,
originalValueOffset = stride * this._origIndex;
binding.getValue( buffer, originalValueOffset );
// accu[0..1] := orig -- initially detect changes against the original
for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
}
// Add to identity for additive
this._setIdentity();
this.cumulativeWeight = 0;
this.cumulativeWeightAdditive = 0;
},
// apply the state previously taken via 'saveOriginalState' to the binding
restoreOriginalState: function () {
var originalValueOffset = this.valueSize * 3;
this.binding.setValue( this.buffer, originalValueOffset );
},
_setAdditiveIdentityNumeric: function () {
var startIndex = this._addIndex * this.valueSize;
this.buffer.fill( 0, startIndex, startIndex + this.valueSize );
},
_setAdditiveIdentityQuaternion: function () {
this._setAdditiveIdentityNumeric();
this.buffer[ this._addIndex * 4 + 3 ] = 1;
},
_setAdditiveIdentityOther: function () {
var startIndex = this._origIndex * this.valueSize;
var targetIndex = this._addIndex * this.valueSize;
this.buffer.copyWithin( targetIndex, startIndex, this.valueSize );
},
// mix functions
_select: function ( buffer, dstOffset, srcOffset, t, stride ) {
if ( t >= 0.5 ) {
for ( var i = 0; i !== stride; ++ i ) {
buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
}
}
},
_slerp: function ( buffer, dstOffset, srcOffset, t ) {
Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
},
_slerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
var workOffset = this._workIndex * stride;
// Store result in intermediate buffer offset
Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
// Slerp to the intermediate result
Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
},
_lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
var s = 1 - t;
for ( var i = 0; i !== stride; ++ i ) {
var j = dstOffset + i;
buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
}
},
_lerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
for ( var i = 0; i !== stride; ++ i ) {
var j = dstOffset + i;
buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
}
}
} );
/**
*
* A reference to a real property in the scene graph.
*
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*/
// Characters [].:/ are reserved for track binding syntax.
var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
var _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
// Attempts to allow node names from any language. ES5's `\w` regexp matches
// only latin characters, and the unicode \p{L} is not yet supported. So
// instead, we exclude reserved characters and match everything else.
var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
// Parent directories, delimited by '/' or ':'. Currently unused, but must
// be matched to parse the rest of the track name.
var _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
var _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
// Object on target node, and accessor. May not contain reserved
// characters. Accessor may contain any character except closing bracket.
var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
// Property and accessor. May not contain reserved characters. Accessor may
// contain any non-bracket characters.
var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
var _trackRe = new RegExp( ''
+ '^'
+ _directoryRe
+ _nodeRe
+ _objectRe
+ _propertyRe
+ '$'
);
var _supportedObjectNames = [ 'material', 'materials', 'bones' ];
function Composite( targetGroup, path, optionalParsedPath ) {
var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
this._targetGroup = targetGroup;
this._bindings = targetGroup.subscribe_( path, parsedPath );
}
Object.assign( Composite.prototype, {
getValue: function ( array, offset ) {
this.bind(); // bind all binding
var firstValidIndex = this._targetGroup.nCachedObjects_,
binding = this._bindings[ firstValidIndex ];
// and only call .getValue on the first
if ( binding !== undefined ) binding.getValue( array, offset );
},
setValue: function ( array, offset ) {
var bindings = this._bindings;
for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
bindings[ i ].setValue( array, offset );
}
},
bind: function () {
var bindings = this._bindings;
for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
bindings[ i ].bind();
}
},
unbind: function () {
var bindings = this._bindings;
for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
bindings[ i ].unbind();
}
}
} );
function PropertyBinding( rootNode, path, parsedPath ) {
this.path = path;
this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
this.rootNode = rootNode;
}
Object.assign( PropertyBinding, {
Composite: Composite,
create: function ( root, path, parsedPath ) {
if ( ! ( root && root.isAnimationObjectGroup ) ) {
return new PropertyBinding( root, path, parsedPath );
} else {
return new PropertyBinding.Composite( root, path, parsedPath );
}
},
/**
* Replaces spaces with underscores and removes unsupported characters from
* node names, to ensure compatibility with parseTrackName().
*
* @param {string} name Node name to be sanitized.
* @return {string}
*/
sanitizeNodeName: function ( name ) {
return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
},
parseTrackName: function ( trackName ) {
var matches = _trackRe.exec( trackName );
if ( ! matches ) {
throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
}
var results = {
// directoryName: matches[ 1 ], // (tschw) currently unused
nodeName: matches[ 2 ],
objectName: matches[ 3 ],
objectIndex: matches[ 4 ],
propertyName: matches[ 5 ], // required
propertyIndex: matches[ 6 ]
};
var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
if ( lastDot !== undefined && lastDot !== - 1 ) {
var objectName = results.nodeName.substring( lastDot + 1 );
// Object names must be checked against a whitelist. Otherwise, there
// is no way to parse 'foo.bar.baz': 'baz' must be a property, but
// 'bar' could be the objectName, or part of a nodeName (which can
// include '.' characters).
if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
results.nodeName = results.nodeName.substring( 0, lastDot );
results.objectName = objectName;
}
}
if ( results.propertyName === null || results.propertyName.length === 0 ) {
throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
}
return results;
},
findNode: function ( root, nodeName ) {
if ( ! nodeName || nodeName === "" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
return root;
}
// search into skeleton bones.
if ( root.skeleton ) {
var bone = root.skeleton.getBoneByName( nodeName );
if ( bone !== undefined ) {
return bone;
}
}
// search into node subtree.
if ( root.children ) {
var searchNodeSubtree = function ( children ) {
for ( var i = 0; i < children.length; i ++ ) {
var childNode = children[ i ];
if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
return childNode;
}
var result = searchNodeSubtree( childNode.children );
if ( result ) return result;
}
return null;
};
var subTreeNode = searchNodeSubtree( root.children );
if ( subTreeNode ) {
return subTreeNode;
}
}
return null;
}
} );
Object.assign( PropertyBinding.prototype, { // prototype, continued
// these are used to "bind" a nonexistent property
_getValue_unavailable: function () {},
_setValue_unavailable: function () {},
BindingType: {
Direct: 0,
EntireArray: 1,
ArrayElement: 2,
HasFromToArray: 3
},
Versioning: {
None: 0,
NeedsUpdate: 1,
MatrixWorldNeedsUpdate: 2
},
GetterByBindingType: [
function getValue_direct( buffer, offset ) {
buffer[ offset ] = this.node[ this.propertyName ];
},
function getValue_array( buffer, offset ) {
var source = this.resolvedProperty;
for ( var i = 0, n = source.length; i !== n; ++ i ) {
buffer[ offset ++ ] = source[ i ];
}
},
function getValue_arrayElement( buffer, offset ) {
buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
},
function getValue_toArray( buffer, offset ) {
this.resolvedProperty.toArray( buffer, offset );
}
],
SetterByBindingTypeAndVersioning: [
[
// Direct
function setValue_direct( buffer, offset ) {
this.targetObject[ this.propertyName ] = buffer[ offset ];
},
function setValue_direct_setNeedsUpdate( buffer, offset ) {
this.targetObject[ this.propertyName ] = buffer[ offset ];
this.targetObject.needsUpdate = true;
},
function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
this.targetObject[ this.propertyName ] = buffer[ offset ];
this.targetObject.matrixWorldNeedsUpdate = true;
}
], [
// EntireArray
function setValue_array( buffer, offset ) {
var dest = this.resolvedProperty;
for ( var i = 0, n = dest.length; i !== n; ++ i ) {
dest[ i ] = buffer[ offset ++ ];
}
},
function setValue_array_setNeedsUpdate( buffer, offset ) {
var dest = this.resolvedProperty;
for ( var i = 0, n = dest.length; i !== n; ++ i ) {
dest[ i ] = buffer[ offset ++ ];
}
this.targetObject.needsUpdate = true;
},
function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
var dest = this.resolvedProperty;
for ( var i = 0, n = dest.length; i !== n; ++ i ) {
dest[ i ] = buffer[ offset ++ ];
}
this.targetObject.matrixWorldNeedsUpdate = true;
}
], [
// ArrayElement
function setValue_arrayElement( buffer, offset ) {
this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
},
function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
this.targetObject.needsUpdate = true;
},
function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
this.targetObject.matrixWorldNeedsUpdate = true;
}
], [
// HasToFromArray
function setValue_fromArray( buffer, offset ) {
this.resolvedProperty.fromArray( buffer, offset );
},
function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
this.resolvedProperty.fromArray( buffer, offset );
this.targetObject.needsUpdate = true;
},
function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
this.resolvedProperty.fromArray( buffer, offset );
this.targetObject.matrixWorldNeedsUpdate = true;
}
]
],
getValue: function getValue_unbound( targetArray, offset ) {
this.bind();
this.getValue( targetArray, offset );
// Note: This class uses a State pattern on a per-method basis:
// 'bind' sets 'this.getValue' / 'setValue' and shadows the
// prototype version of these methods with one that represents
// the bound state. When the property is not found, the methods
// become no-ops.
},
setValue: function getValue_unbound( sourceArray, offset ) {
this.bind();
this.setValue( sourceArray, offset );
},
// create getter / setter pair for a property in the scene graph
bind: function () {
var targetObject = this.node,
parsedPath = this.parsedPath,
objectName = parsedPath.objectName,
propertyName = parsedPath.propertyName,
propertyIndex = parsedPath.propertyIndex;
if ( ! targetObject ) {
targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
this.node = targetObject;
}
// set fail state so we can just 'return' on error
this.getValue = this._getValue_unavailable;
this.setValue = this._setValue_unavailable;
// ensure there is a value node
if ( ! targetObject ) {
console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
return;
}
if ( objectName ) {
var objectIndex = parsedPath.objectIndex;
// special cases were we need to reach deeper into the hierarchy to get the face materials....
switch ( objectName ) {
case 'materials':
if ( ! targetObject.material ) {
console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
return;
}
if ( ! targetObject.material.materials ) {
console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
return;
}
targetObject = targetObject.material.materials;
break;
case 'bones':
if ( ! targetObject.skeleton ) {
console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
return;
}
// potential future optimization: skip this if propertyIndex is already an integer
// and convert the integer string to a true integer.
targetObject = targetObject.skeleton.bones;
// support resolving morphTarget names into indices.
for ( var i = 0; i < targetObject.length; i ++ ) {
if ( targetObject[ i ].name === objectIndex ) {
objectIndex = i;
break;
}
}
break;
default:
if ( targetObject[ objectName ] === undefined ) {
console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
return;
}
targetObject = targetObject[ objectName ];
}
if ( objectIndex !== undefined ) {
if ( targetObject[ objectIndex ] === undefined ) {
console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
return;
}
targetObject = targetObject[ objectIndex ];
}
}
// resolve property
var nodeProperty = targetObject[ propertyName ];
if ( nodeProperty === undefined ) {
var nodeName = parsedPath.nodeName;
console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
'.' + propertyName + ' but it wasn\'t found.', targetObject );
return;
}
// determine versioning scheme
var versioning = this.Versioning.None;
this.targetObject = targetObject;
if ( targetObject.needsUpdate !== undefined ) { // material
versioning = this.Versioning.NeedsUpdate;
} else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
versioning = this.Versioning.MatrixWorldNeedsUpdate;
}
// determine how the property gets bound
var bindingType = this.BindingType.Direct;
if ( propertyIndex !== undefined ) {
// access a sub element of the property array (only primitives are supported right now)
if ( propertyName === "morphTargetInfluences" ) {
// potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
// support resolving morphTarget names into indices.
if ( ! targetObject.geometry ) {
console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
return;
}
if ( targetObject.geometry.isBufferGeometry ) {
if ( ! targetObject.geometry.morphAttributes ) {
console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
return;
}
for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
propertyIndex = i;
break;
}
}
} else {
if ( ! targetObject.geometry.morphTargets ) {
console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
return;
}
for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
propertyIndex = i;
break;
}
}
}
}
bindingType = this.BindingType.ArrayElement;
this.resolvedProperty = nodeProperty;
this.propertyIndex = propertyIndex;
} else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
// must use copy for Object3D.Euler/Quaternion
bindingType = this.BindingType.HasFromToArray;
this.resolvedProperty = nodeProperty;
} else if ( Array.isArray( nodeProperty ) ) {
bindingType = this.BindingType.EntireArray;
this.resolvedProperty = nodeProperty;
} else {
this.propertyName = propertyName;
}
// select getter / setter
this.getValue = this.GetterByBindingType[ bindingType ];
this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
},
unbind: function () {
this.node = null;
// back to the prototype version of getValue / setValue
// note: avoiding to mutate the shape of 'this' via 'delete'
this.getValue = this._getValue_unbound;
this.setValue = this._setValue_unbound;
}
} );
// DECLARE ALIAS AFTER assign prototype
Object.assign( PropertyBinding.prototype, {
// initial state of these methods that calls 'bind'
_getValue_unbound: PropertyBinding.prototype.getValue,
_setValue_unbound: PropertyBinding.prototype.setValue,
} );
/**
*
* A group of objects that receives a shared animation state.
*
* Usage:
*
* - Add objects you would otherwise pass as 'root' to the
* constructor or the .clipAction method of AnimationMixer.
*
* - Instead pass this object as 'root'.
*
* - You can also add and remove objects later when the mixer
* is running.
*
* Note:
*
* Objects of this class appear as one object to the mixer,
* so cache control of the individual objects must be done
* on the group.
*
* Limitation:
*
* - The animated properties must be compatible among the
* all objects in the group.
*
* - A single property can either be controlled through a
* target group or directly, but not both.
*
* @author tschw
*/
function AnimationObjectGroup() {
this.uuid = MathUtils.generateUUID();
// cached objects followed by the active ones
this._objects = Array.prototype.slice.call( arguments );
this.nCachedObjects_ = 0; // threshold
// note: read by PropertyBinding.Composite
var indices = {};
this._indicesByUUID = indices; // for bookkeeping
for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
indices[ arguments[ i ].uuid ] = i;
}
this._paths = []; // inside: string
this._parsedPaths = []; // inside: { we don't care, here }
this._bindings = []; // inside: Array< PropertyBinding >
this._bindingsIndicesByPath = {}; // inside: indices in these arrays
var scope = this;
this.stats = {
objects: {
get total() {
return scope._objects.length;
},
get inUse() {
return this.total - scope.nCachedObjects_;
}
},
get bindingsPerObject() {
return scope._bindings.length;
}
};
}
Object.assign( AnimationObjectGroup.prototype, {
isAnimationObjectGroup: true,
add: function () {
var objects = this._objects,
nObjects = objects.length,
nCachedObjects = this.nCachedObjects_,
indicesByUUID = this._indicesByUUID,
paths = this._paths,
parsedPaths = this._parsedPaths,
bindings = this._bindings,
nBindings = bindings.length,
knownObject = undefined;
for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
var object = arguments[ i ],
uuid = object.uuid,
index = indicesByUUID[ uuid ];
if ( index === undefined ) {
// unknown object -> add it to the ACTIVE region
index = nObjects ++;
indicesByUUID[ uuid ] = index;
objects.push( object );
// accounting is done, now do the same for all bindings
for ( var j = 0, m = nBindings; j !== m; ++ j ) {
bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
}
} else if ( index < nCachedObjects ) {
knownObject = objects[ index ];
// move existing object to the ACTIVE region
var firstActiveIndex = -- nCachedObjects,
lastCachedObject = objects[ firstActiveIndex ];
indicesByUUID[ lastCachedObject.uuid ] = index;
objects[ index ] = lastCachedObject;
indicesByUUID[ uuid ] = firstActiveIndex;
objects[ firstActiveIndex ] = object;
// accounting is done, now do the same for all bindings
for ( var j = 0, m = nBindings; j !== m; ++ j ) {
var bindingsForPath = bindings[ j ],
lastCached = bindingsForPath[ firstActiveIndex ],
binding = bindingsForPath[ index ];
bindingsForPath[ index ] = lastCached;
if ( binding === undefined ) {
// since we do not bother to create new bindings
// for objects that are cached, the binding may
// or may not exist
binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
}
bindingsForPath[ firstActiveIndex ] = binding;
}
} else if ( objects[ index ] !== knownObject ) {
console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
} // else the object is already where we want it to be
} // for arguments
this.nCachedObjects_ = nCachedObjects;
},
remove: function () {
var objects = this._objects,
nCachedObjects = this.nCachedObjects_,
indicesByUUID = this._indicesByUUID,
bindings = this._bindings,
nBindings = bindings.length;
for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
var object = arguments[ i ],
uuid = object.uuid,
index = indicesByUUID[ uuid ];
if ( index !== undefined && index >= nCachedObjects ) {
// move existing object into the CACHED region
var lastCachedIndex = nCachedObjects ++,
firstActiveObject = objects[ lastCachedIndex ];
indicesByUUID[ firstActiveObject.uuid ] = index;
objects[ index ] = firstActiveObject;
indicesByUUID[ uuid ] = lastCachedIndex;
objects[ lastCachedIndex ] = object;
// accounting is done, now do the same for all bindings
for ( var j = 0, m = nBindings; j !== m; ++ j ) {
var bindingsForPath = bindings[ j ],
firstActive = bindingsForPath[ lastCachedIndex ],
binding = bindingsForPath[ index ];
bindingsForPath[ index ] = firstActive;
bindingsForPath[ lastCachedIndex ] = binding;
}
}
} // for arguments
this.nCachedObjects_ = nCachedObjects;
},
// remove & forget
uncache: function () {
var objects = this._objects,
nObjects = objects.length,
nCachedObjects = this.nCachedObjects_,
indicesByUUID = this._indicesByUUID,
bindings = this._bindings,
nBindings = bindings.length;
for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
var object = arguments[ i ],
uuid = object.uuid,
index = indicesByUUID[ uuid ];
if ( index !== undefined ) {
delete indicesByUUID[ uuid ];
if ( index < nCachedObjects ) {
// object is cached, shrink the CACHED region
var firstActiveIndex = -- nCachedObjects,
lastCachedObject = objects[ firstActiveIndex ],
lastIndex = -- nObjects,
lastObject = objects[ lastIndex ];
// last cached object takes this object's place
indicesByUUID[ lastCachedObject.uuid ] = index;
objects[ index ] = lastCachedObject;
// last object goes to the activated slot and pop
indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
objects[ firstActiveIndex ] = lastObject;
objects.pop();
// accounting is done, now do the same for all bindings
for ( var j = 0, m = nBindings; j !== m; ++ j ) {
var bindingsForPath = bindings[ j ],
lastCached = bindingsForPath[ firstActiveIndex ],
last = bindingsForPath[ lastIndex ];
bindingsForPath[ index ] = lastCached;
bindingsForPath[ firstActiveIndex ] = last;
bindingsForPath.pop();
}
} else {
// object is active, just swap with the last and pop
var lastIndex = -- nObjects,
lastObject = objects[ lastIndex ];
indicesByUUID[ lastObject.uuid ] = index;
objects[ index ] = lastObject;
objects.pop();
// accounting is done, now do the same for all bindings
for ( var j = 0, m = nBindings; j !== m; ++ j ) {
var bindingsForPath = bindings[ j ];
bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
bindingsForPath.pop();
}
} // cached or active
} // if object is known
} // for arguments
this.nCachedObjects_ = nCachedObjects;
},
// Internal interface used by befriended PropertyBinding.Composite:
subscribe_: function ( path, parsedPath ) {
// returns an array of bindings for the given path that is changed
// according to the contained objects in the group
var indicesByPath = this._bindingsIndicesByPath,
index = indicesByPath[ path ],
bindings = this._bindings;
if ( index !== undefined ) return bindings[ index ];
var paths = this._paths,
parsedPaths = this._parsedPaths,
objects = this._objects,
nObjects = objects.length,
nCachedObjects = this.nCachedObjects_,
bindingsForPath = new Array( nObjects );
index = bindings.length;
indicesByPath[ path ] = index;
paths.push( path );
parsedPaths.push( parsedPath );
bindings.push( bindingsForPath );
for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
var object = objects[ i ];
bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
}
return bindingsForPath;
},
unsubscribe_: function ( path ) {
// tells the group to forget about a property path and no longer
// update the array previously obtained with 'subscribe_'
var indicesByPath = this._bindingsIndicesByPath,
index = indicesByPath[ path ];
if ( index !== undefined ) {
var paths = this._paths,
parsedPaths = this._parsedPaths,
bindings = this._bindings,
lastBindingsIndex = bindings.length - 1,
lastBindings = bindings[ lastBindingsIndex ],
lastBindingsPath = path[ lastBindingsIndex ];
indicesByPath[ lastBindingsPath ] = index;
bindings[ index ] = lastBindings;
bindings.pop();
parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
parsedPaths.pop();
paths[ index ] = paths[ lastBindingsIndex ];
paths.pop();
}
}
} );
/**
*
* Action provided by AnimationMixer for scheduling clip playback on specific
* objects.
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*
*/
function AnimationAction( mixer, clip, localRoot, blendMode ) {
this._mixer = mixer;
this._clip = clip;
this._localRoot = localRoot || null;
this.blendMode = blendMode || clip.blendMode;
var tracks = clip.tracks,
nTracks = tracks.length,
interpolants = new Array( nTracks );
var interpolantSettings = {
endingStart: ZeroCurvatureEnding,
endingEnd: ZeroCurvatureEnding
};
for ( var i = 0; i !== nTracks; ++ i ) {
var interpolant = tracks[ i ].createInterpolant( null );
interpolants[ i ] = interpolant;
interpolant.settings = interpolantSettings;
}
this._interpolantSettings = interpolantSettings;
this._interpolants = interpolants; // bound by the mixer
// inside: PropertyMixer (managed by the mixer)
this._propertyBindings = new Array( nTracks );
this._cacheIndex = null; // for the memory manager
this._byClipCacheIndex = null; // for the memory manager
this._timeScaleInterpolant = null;
this._weightInterpolant = null;
this.loop = LoopRepeat;
this._loopCount = - 1;
// global mixer time when the action is to be started
// it's set back to 'null' upon start of the action
this._startTime = null;
// scaled local time of the action
// gets clamped or wrapped to 0..clip.duration according to loop
this.time = 0;
this.timeScale = 1;
this._effectiveTimeScale = 1;
this.weight = 1;
this._effectiveWeight = 1;
this.repetitions = Infinity; // no. of repetitions when looping
this.paused = false; // true -> zero effective time scale
this.enabled = true; // false -> zero effective weight
this.clampWhenFinished = false;// keep feeding the last frame?
this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
this.zeroSlopeAtEnd = true;// clips for start, loop and end
}
Object.assign( AnimationAction.prototype, {
// State & Scheduling
play: function () {
this._mixer._activateAction( this );
return this;
},
stop: function () {
this._mixer._deactivateAction( this );
return this.reset();
},
reset: function () {
this.paused = false;
this.enabled = true;
this.time = 0; // restart clip
this._loopCount = - 1;// forget previous loops
this._startTime = null;// forget scheduling
return this.stopFading().stopWarping();
},
isRunning: function () {
return this.enabled && ! this.paused && this.timeScale !== 0 &&
this._startTime === null && this._mixer._isActiveAction( this );
},
// return true when play has been called
isScheduled: function () {
return this._mixer._isActiveAction( this );
},
startAt: function ( time ) {
this._startTime = time;
return this;
},
setLoop: function ( mode, repetitions ) {
this.loop = mode;
this.repetitions = repetitions;
return this;
},
// Weight
// set the weight stopping any scheduled fading
// although .enabled = false yields an effective weight of zero, this
// method does *not* change .enabled, because it would be confusing
setEffectiveWeight: function ( weight ) {
this.weight = weight;
// note: same logic as when updated at runtime
this._effectiveWeight = this.enabled ? weight : 0;
return this.stopFading();
},
// return the weight considering fading and .enabled
getEffectiveWeight: function () {
return this._effectiveWeight;
},
fadeIn: function ( duration ) {
return this._scheduleFading( duration, 0, 1 );
},
fadeOut: function ( duration ) {
return this._scheduleFading( duration, 1, 0 );
},
crossFadeFrom: function ( fadeOutAction, duration, warp ) {
fadeOutAction.fadeOut( duration );
this.fadeIn( duration );
if ( warp ) {
var fadeInDuration = this._clip.duration,
fadeOutDuration = fadeOutAction._clip.duration,
startEndRatio = fadeOutDuration / fadeInDuration,
endStartRatio = fadeInDuration / fadeOutDuration;
fadeOutAction.warp( 1.0, startEndRatio, duration );
this.warp( endStartRatio, 1.0, duration );
}
return this;
},
crossFadeTo: function ( fadeInAction, duration, warp ) {
return fadeInAction.crossFadeFrom( this, duration, warp );
},
stopFading: function () {
var weightInterpolant = this._weightInterpolant;
if ( weightInterpolant !== null ) {
this._weightInterpolant = null;
this._mixer._takeBackControlInterpolant( weightInterpolant );
}
return this;
},
// Time Scale Control
// set the time scale stopping any scheduled warping
// although .paused = true yields an effective time scale of zero, this
// method does *not* change .paused, because it would be confusing
setEffectiveTimeScale: function ( timeScale ) {
this.timeScale = timeScale;
this._effectiveTimeScale = this.paused ? 0 : timeScale;
return this.stopWarping();
},
// return the time scale considering warping and .paused
getEffectiveTimeScale: function () {
return this._effectiveTimeScale;
},
setDuration: function ( duration ) {
this.timeScale = this._clip.duration / duration;
return this.stopWarping();
},
syncWith: function ( action ) {
this.time = action.time;
this.timeScale = action.timeScale;
return this.stopWarping();
},
halt: function ( duration ) {
return this.warp( this._effectiveTimeScale, 0, duration );
},
warp: function ( startTimeScale, endTimeScale, duration ) {
var mixer = this._mixer, now = mixer.time,
interpolant = this._timeScaleInterpolant,
timeScale = this.timeScale;
if ( interpolant === null ) {
interpolant = mixer._lendControlInterpolant();
this._timeScaleInterpolant = interpolant;
}
var times = interpolant.parameterPositions,
values = interpolant.sampleValues;
times[ 0 ] = now;
times[ 1 ] = now + duration;
values[ 0 ] = startTimeScale / timeScale;
values[ 1 ] = endTimeScale / timeScale;
return this;
},
stopWarping: function () {
var timeScaleInterpolant = this._timeScaleInterpolant;
if ( timeScaleInterpolant !== null ) {
this._timeScaleInterpolant = null;
this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
}
return this;
},
// Object Accessors
getMixer: function () {
return this._mixer;
},
getClip: function () {
return this._clip;
},
getRoot: function () {
return this._localRoot || this._mixer._root;
},
// Interna
_update: function ( time, deltaTime, timeDirection, accuIndex ) {
// called by the mixer
if ( ! this.enabled ) {
// call ._updateWeight() to update ._effectiveWeight
this._updateWeight( time );
return;
}
var startTime = this._startTime;
if ( startTime !== null ) {
// check for scheduled start of action
var timeRunning = ( time - startTime ) * timeDirection;
if ( timeRunning < 0 || timeDirection === 0 ) {
return; // yet to come / don't decide when delta = 0
}
// start
this._startTime = null; // unschedule
deltaTime = timeDirection * timeRunning;
}
// apply time scale and advance time
deltaTime *= this._updateTimeScale( time );
var clipTime = this._updateTime( deltaTime );
// note: _updateTime may disable the action resulting in
// an effective weight of 0
var weight = this._updateWeight( time );
if ( weight > 0 ) {
var interpolants = this._interpolants;
var propertyMixers = this._propertyBindings;
switch ( this.blendMode ) {
case AdditiveAnimationBlendMode:
for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
interpolants[ j ].evaluate( clipTime );
propertyMixers[ j ].accumulateAdditive( weight );
}
break;
case NormalAnimationBlendMode:
default:
for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
interpolants[ j ].evaluate( clipTime );
propertyMixers[ j ].accumulate( accuIndex, weight );
}
}
}
},
_updateWeight: function ( time ) {
var weight = 0;
if ( this.enabled ) {
weight = this.weight;
var interpolant = this._weightInterpolant;
if ( interpolant !== null ) {
var interpolantValue = interpolant.evaluate( time )[ 0 ];
weight *= interpolantValue;
if ( time > interpolant.parameterPositions[ 1 ] ) {
this.stopFading();
if ( interpolantValue === 0 ) {
// faded out, disable
this.enabled = false;
}
}
}
}
this._effectiveWeight = weight;
return weight;
},
_updateTimeScale: function ( time ) {
var timeScale = 0;
if ( ! this.paused ) {
timeScale = this.timeScale;
var interpolant = this._timeScaleInterpolant;
if ( interpolant !== null ) {
var interpolantValue = interpolant.evaluate( time )[ 0 ];
timeScale *= interpolantValue;
if ( time > interpolant.parameterPositions[ 1 ] ) {
this.stopWarping();
if ( timeScale === 0 ) {
// motion has halted, pause
this.paused = true;
} else {
// warp done - apply final time scale
this.timeScale = timeScale;
}
}
}
}
this._effectiveTimeScale = timeScale;
return timeScale;
},
_updateTime: function ( deltaTime ) {
var time = this.time + deltaTime;
var duration = this._clip.duration;
var loop = this.loop;
var loopCount = this._loopCount;
var pingPong = ( loop === LoopPingPong );
if ( deltaTime === 0 ) {
if ( loopCount === - 1 ) return time;
return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
}
if ( loop === LoopOnce ) {
if ( loopCount === - 1 ) {
// just started
this._loopCount = 0;
this._setEndings( true, true, false );
}
handle_stop: {
if ( time >= duration ) {
time = duration;
} else if ( time < 0 ) {
time = 0;
} else {
this.time = time;
break handle_stop;
}
if ( this.clampWhenFinished ) this.paused = true;
else this.enabled = false;
this.time = time;
this._mixer.dispatchEvent( {
type: 'finished', action: this,
direction: deltaTime < 0 ? - 1 : 1
} );
}
} else { // repetitive Repeat or PingPong
if ( loopCount === - 1 ) {
// just started
if ( deltaTime >= 0 ) {
loopCount = 0;
this._setEndings( true, this.repetitions === 0, pingPong );
} else {
// when looping in reverse direction, the initial
// transition through zero counts as a repetition,
// so leave loopCount at -1
this._setEndings( this.repetitions === 0, true, pingPong );
}
}
if ( time >= duration || time < 0 ) {
// wrap around
var loopDelta = Math.floor( time / duration ); // signed
time -= duration * loopDelta;
loopCount += Math.abs( loopDelta );
var pending = this.repetitions - loopCount;
if ( pending <= 0 ) {
// have to stop (switch state, clamp time, fire event)
if ( this.clampWhenFinished ) this.paused = true;
else this.enabled = false;
time = deltaTime > 0 ? duration : 0;
this.time = time;
this._mixer.dispatchEvent( {
type: 'finished', action: this,
direction: deltaTime > 0 ? 1 : - 1
} );
} else {
// keep running
if ( pending === 1 ) {
// entering the last round
var atStart = deltaTime < 0;
this._setEndings( atStart, ! atStart, pingPong );
} else {
this._setEndings( false, false, pingPong );
}
this._loopCount = loopCount;
this.time = time;
this._mixer.dispatchEvent( {
type: 'loop', action: this, loopDelta: loopDelta
} );
}
} else {
this.time = time;
}
if ( pingPong && ( loopCount & 1 ) === 1 ) {
// invert time for the "pong round"
return duration - time;
}
}
return time;
},
_setEndings: function ( atStart, atEnd, pingPong ) {
var settings = this._interpolantSettings;
if ( pingPong ) {
settings.endingStart = ZeroSlopeEnding;
settings.endingEnd = ZeroSlopeEnding;
} else {
// assuming for LoopOnce atStart == atEnd == true
if ( atStart ) {
settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
} else {
settings.endingStart = WrapAroundEnding;
}
if ( atEnd ) {
settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
} else {
settings.endingEnd = WrapAroundEnding;
}
}
},
_scheduleFading: function ( duration, weightNow, weightThen ) {
var mixer = this._mixer, now = mixer.time,
interpolant = this._weightInterpolant;
if ( interpolant === null ) {
interpolant = mixer._lendControlInterpolant();
this._weightInterpolant = interpolant;
}
var times = interpolant.parameterPositions,
values = interpolant.sampleValues;
times[ 0 ] = now;
values[ 0 ] = weightNow;
times[ 1 ] = now + duration;
values[ 1 ] = weightThen;
return this;
}
} );
/**
*
* Player for AnimationClips.
*
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
* @author tschw
*/
function AnimationMixer( root ) {
this._root = root;
this._initMemoryManager();
this._accuIndex = 0;
this.time = 0;
this.timeScale = 1.0;
}
AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
constructor: AnimationMixer,
_bindAction: function ( action, prototypeAction ) {
var root = action._localRoot || this._root,
tracks = action._clip.tracks,
nTracks = tracks.length,
bindings = action._propertyBindings,
interpolants = action._interpolants,
rootUuid = root.uuid,
bindingsByRoot = this._bindingsByRootAndName,
bindingsByName = bindingsByRoot[ rootUuid ];
if ( bindingsByName === undefined ) {
bindingsByName = {};
bindingsByRoot[ rootUuid ] = bindingsByName;
}
for ( var i = 0; i !== nTracks; ++ i ) {
var track = tracks[ i ],
trackName = track.name,
binding = bindingsByName[ trackName ];
if ( binding !== undefined ) {
bindings[ i ] = binding;
} else {
binding = bindings[ i ];
if ( binding !== undefined ) {
// existing binding, make sure the cache knows
if ( binding._cacheIndex === null ) {
++ binding.referenceCount;
this._addInactiveBinding( binding, rootUuid, trackName );
}
continue;
}
var path = prototypeAction && prototypeAction.
_propertyBindings[ i ].binding.parsedPath;
binding = new PropertyMixer(
PropertyBinding.create( root, trackName, path ),
track.ValueTypeName, track.getValueSize() );
++ binding.referenceCount;
this._addInactiveBinding( binding, rootUuid, trackName );
bindings[ i ] = binding;
}
interpolants[ i ].resultBuffer = binding.buffer;
}
},
_activateAction: function ( action ) {
if ( ! this._isActiveAction( action ) ) {
if ( action._cacheIndex === null ) {
// this action has been forgotten by the cache, but the user
// appears to be still using it -> rebind
var rootUuid = ( action._localRoot || this._root ).uuid,
clipUuid = action._clip.uuid,
actionsForClip = this._actionsByClip[ clipUuid ];
this._bindAction( action,
actionsForClip && actionsForClip.knownActions[ 0 ] );
this._addInactiveAction( action, clipUuid, rootUuid );
}
var bindings = action._propertyBindings;
// increment reference counts / sort out state
for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
var binding = bindings[ i ];
if ( binding.useCount ++ === 0 ) {
this._lendBinding( binding );
binding.saveOriginalState();
}
}
this._lendAction( action );
}
},
_deactivateAction: function ( action ) {
if ( this._isActiveAction( action ) ) {
var bindings = action._propertyBindings;
// decrement reference counts / sort out state
for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
var binding = bindings[ i ];
if ( -- binding.useCount === 0 ) {
binding.restoreOriginalState();
this._takeBackBinding( binding );
}
}
this._takeBackAction( action );
}
},
// Memory manager
_initMemoryManager: function () {
this._actions = []; // 'nActiveActions' followed by inactive ones
this._nActiveActions = 0;
this._actionsByClip = {};
// inside:
// {
// knownActions: Array< AnimationAction > - used as prototypes
// actionByRoot: AnimationAction - lookup
// }
this._bindings = []; // 'nActiveBindings' followed by inactive ones
this._nActiveBindings = 0;
this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
this._controlInterpolants = []; // same game as above
this._nActiveControlInterpolants = 0;
var scope = this;
this.stats = {
actions: {
get total() {
return scope._actions.length;
},
get inUse() {
return scope._nActiveActions;
}
},
bindings: {
get total() {
return scope._bindings.length;
},
get inUse() {
return scope._nActiveBindings;
}
},
controlInterpolants: {
get total() {
return scope._controlInterpolants.length;
},
get inUse() {
return scope._nActiveControlInterpolants;
}
}
};
},
// Memory management for AnimationAction objects
_isActiveAction: function ( action ) {
var index = action._cacheIndex;
return index !== null && index < this._nActiveActions;
},
_addInactiveAction: function ( action, clipUuid, rootUuid ) {
var actions = this._actions,
actionsByClip = this._actionsByClip,
actionsForClip = actionsByClip[ clipUuid ];
if ( actionsForClip === undefined ) {
actionsForClip = {
knownActions: [ action ],
actionByRoot: {}
};
action._byClipCacheIndex = 0;
actionsByClip[ clipUuid ] = actionsForClip;
} else {
var knownActions = actionsForClip.knownActions;
action._byClipCacheIndex = knownActions.length;
knownActions.push( action );
}
action._cacheIndex = actions.length;
actions.push( action );
actionsForClip.actionByRoot[ rootUuid ] = action;
},
_removeInactiveAction: function ( action ) {
var actions = this._actions,
lastInactiveAction = actions[ actions.length - 1 ],
cacheIndex = action._cacheIndex;
lastInactiveAction._cacheIndex = cacheIndex;
actions[ cacheIndex ] = lastInactiveAction;
actions.pop();
action._cacheIndex = null;
var clipUuid = action._clip.uuid,
actionsByClip = this._actionsByClip,
actionsForClip = actionsByClip[ clipUuid ],
knownActionsForClip = actionsForClip.knownActions,
lastKnownAction =
knownActionsForClip[ knownActionsForClip.length - 1 ],
byClipCacheIndex = action._byClipCacheIndex;
lastKnownAction._byClipCacheIndex = byClipCacheIndex;
knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
knownActionsForClip.pop();
action._byClipCacheIndex = null;
var actionByRoot = actionsForClip.actionByRoot,
rootUuid = ( action._localRoot || this._root ).uuid;
delete actionByRoot[ rootUuid ];
if ( knownActionsForClip.length === 0 ) {
delete actionsByClip[ clipUuid ];
}
this._removeInactiveBindingsForAction( action );
},
_removeInactiveBindingsForAction: function ( action ) {
var bindings = action._propertyBindings;
for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
var binding = bindings[ i ];
if ( -- binding.referenceCount === 0 ) {
this._removeInactiveBinding( binding );
}
}
},
_lendAction: function ( action ) {
// [ active actions | inactive actions ]
// [ active actions >| inactive actions ]
// s a
// <-swap->
// a s
var actions = this._actions,
prevIndex = action._cacheIndex,
lastActiveIndex = this._nActiveActions ++,
firstInactiveAction = actions[ lastActiveIndex ];
action._cacheIndex = lastActiveIndex;
actions[ lastActiveIndex ] = action;
firstInactiveAction._cacheIndex = prevIndex;
actions[ prevIndex ] = firstInactiveAction;
},
_takeBackAction: function ( action ) {
// [ active actions | inactive actions ]
// [ active actions |< inactive actions ]
// a s
// <-swap->
// s a
var actions = this._actions,
prevIndex = action._cacheIndex,
firstInactiveIndex = -- this._nActiveActions,
lastActiveAction = actions[ firstInactiveIndex ];
action._cacheIndex = firstInactiveIndex;
actions[ firstInactiveIndex ] = action;
lastActiveAction._cacheIndex = prevIndex;
actions[ prevIndex ] = lastActiveAction;
},
// Memory management for PropertyMixer objects
_addInactiveBinding: function ( binding, rootUuid, trackName ) {
var bindingsByRoot = this._bindingsByRootAndName,
bindingByName = bindingsByRoot[ rootUuid ],
bindings = this._bindings;
if ( bindingByName === undefined ) {
bindingByName = {};
bindingsByRoot[ rootUuid ] = bindingByName;
}
bindingByName[ trackName ] = binding;
binding._cacheIndex = bindings.length;
bindings.push( binding );
},
_removeInactiveBinding: function ( binding ) {
var bindings = this._bindings,
propBinding = binding.binding,
rootUuid = propBinding.rootNode.uuid,
trackName = propBinding.path,
bindingsByRoot = this._bindingsByRootAndName,
bindingByName = bindingsByRoot[ rootUuid ],
lastInactiveBinding = bindings[ bindings.length - 1 ],
cacheIndex = binding._cacheIndex;
lastInactiveBinding._cacheIndex = cacheIndex;
bindings[ cacheIndex ] = lastInactiveBinding;
bindings.pop();
delete bindingByName[ trackName ];
if ( Object.keys( bindingByName ).length === 0 ) {
delete bindingsByRoot[ rootUuid ];
}
},
_lendBinding: function ( binding ) {
var bindings = this._bindings,
prevIndex = binding._cacheIndex,
lastActiveIndex = this._nActiveBindings ++,
firstInactiveBinding = bindings[ lastActiveIndex ];
binding._cacheIndex = lastActiveIndex;
bindings[ lastActiveIndex ] = binding;
firstInactiveBinding._cacheIndex = prevIndex;
bindings[ prevIndex ] = firstInactiveBinding;
},
_takeBackBinding: function ( binding ) {
var bindings = this._bindings,
prevIndex = binding._cacheIndex,
firstInactiveIndex = -- this._nActiveBindings,
lastActiveBinding = bindings[ firstInactiveIndex ];
binding._cacheIndex = firstInactiveIndex;
bindings[ firstInactiveIndex ] = binding;
lastActiveBinding._cacheIndex = prevIndex;
bindings[ prevIndex ] = lastActiveBinding;
},
// Memory management of Interpolants for weight and time scale
_lendControlInterpolant: function () {
var interpolants = this._controlInterpolants,
lastActiveIndex = this._nActiveControlInterpolants ++,
interpolant = interpolants[ lastActiveIndex ];
if ( interpolant === undefined ) {
interpolant = new LinearInterpolant(
new Float32Array( 2 ), new Float32Array( 2 ),
1, this._controlInterpolantsResultBuffer );
interpolant.__cacheIndex = lastActiveIndex;
interpolants[ lastActiveIndex ] = interpolant;
}
return interpolant;
},
_takeBackControlInterpolant: function ( interpolant ) {
var interpolants = this._controlInterpolants,
prevIndex = interpolant.__cacheIndex,
firstInactiveIndex = -- this._nActiveControlInterpolants,
lastActiveInterpolant = interpolants[ firstInactiveIndex ];
interpolant.__cacheIndex = firstInactiveIndex;
interpolants[ firstInactiveIndex ] = interpolant;
lastActiveInterpolant.__cacheIndex = prevIndex;
interpolants[ prevIndex ] = lastActiveInterpolant;
},
_controlInterpolantsResultBuffer: new Float32Array( 1 ),
// return an action for a clip optionally using a custom root target
// object (this method allocates a lot of dynamic memory in case a
// previously unknown clip/root combination is specified)
clipAction: function ( clip, optionalRoot, blendMode ) {
var root = optionalRoot || this._root,
rootUuid = root.uuid,
clipObject = typeof clip === 'string' ?
AnimationClip.findByName( root, clip ) : clip,
clipUuid = clipObject !== null ? clipObject.uuid : clip,
actionsForClip = this._actionsByClip[ clipUuid ],
prototypeAction = null;
if ( blendMode === undefined ) {
if ( clipObject !== null ) {
blendMode = clipObject.blendMode;
} else {
blendMode = NormalAnimationBlendMode;
}
}
if ( actionsForClip !== undefined ) {
var existingAction =
actionsForClip.actionByRoot[ rootUuid ];
if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
return existingAction;
}
// we know the clip, so we don't have to parse all
// the bindings again but can just copy
prototypeAction = actionsForClip.knownActions[ 0 ];
// also, take the clip from the prototype action
if ( clipObject === null )
clipObject = prototypeAction._clip;
}
// clip must be known when specified via string
if ( clipObject === null ) return null;
// allocate all resources required to run it
var newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
this._bindAction( newAction, prototypeAction );
// and make the action known to the memory manager
this._addInactiveAction( newAction, clipUuid, rootUuid );
return newAction;
},
// get an existing action
existingAction: function ( clip, optionalRoot ) {
var root = optionalRoot || this._root,
rootUuid = root.uuid,
clipObject = typeof clip === 'string' ?
AnimationClip.findByName( root, clip ) : clip,
clipUuid = clipObject ? clipObject.uuid : clip,
actionsForClip = this._actionsByClip[ clipUuid ];
if ( actionsForClip !== undefined ) {
return actionsForClip.actionByRoot[ rootUuid ] || null;
}
return null;
},
// deactivates all previously scheduled actions
stopAllAction: function () {
var actions = this._actions,
nActions = this._nActiveActions,
bindings = this._bindings,
nBindings = this._nActiveBindings;
this._nActiveActions = 0;
this._nActiveBindings = 0;
for ( var i = 0; i !== nActions; ++ i ) {
actions[ i ].reset();
}
for ( var i = 0; i !== nBindings; ++ i ) {
bindings[ i ].useCount = 0;
}
return this;
},
// advance the time and update apply the animation
update: function ( deltaTime ) {
deltaTime *= this.timeScale;
var actions = this._actions,
nActions = this._nActiveActions,
time = this.time += deltaTime,
timeDirection = Math.sign( deltaTime ),
accuIndex = this._accuIndex ^= 1;
// run active actions
for ( var i = 0; i !== nActions; ++ i ) {
var action = actions[ i ];
action._update( time, deltaTime, timeDirection, accuIndex );
}
// update scene graph
var bindings = this._bindings,
nBindings = this._nActiveBindings;
for ( var i = 0; i !== nBindings; ++ i ) {
bindings[ i ].apply( accuIndex );
}
return this;
},
// Allows you to seek to a specific time in an animation.
setTime: function ( timeInSeconds ) {
this.time = 0; // Zero out time attribute for AnimationMixer object;
for ( var i = 0; i < this._actions.length; i ++ ) {
this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
}
return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
},
// return this mixer's root target object
getRoot: function () {
return this._root;
},
// free all resources specific to a particular clip
uncacheClip: function ( clip ) {
var actions = this._actions,
clipUuid = clip.uuid,
actionsByClip = this._actionsByClip,
actionsForClip = actionsByClip[ clipUuid ];
if ( actionsForClip !== undefined ) {
// note: just calling _removeInactiveAction would mess up the
// iteration state and also require updating the state we can
// just throw away
var actionsToRemove = actionsForClip.knownActions;
for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
var action = actionsToRemove[ i ];
this._deactivateAction( action );
var cacheIndex = action._cacheIndex,
lastInactiveAction = actions[ actions.length - 1 ];
action._cacheIndex = null;
action._byClipCacheIndex = null;
lastInactiveAction._cacheIndex = cacheIndex;
actions[ cacheIndex ] = lastInactiveAction;
actions.pop();
this._removeInactiveBindingsForAction( action );
}
delete actionsByClip[ clipUuid ];
}
},
// free all resources specific to a particular root target object
uncacheRoot: function ( root ) {
var rootUuid = root.uuid,
actionsByClip = this._actionsByClip;
for ( var clipUuid in actionsByClip ) {
var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
action = actionByRoot[ rootUuid ];
if ( action !== undefined ) {
this._deactivateAction( action );
this._removeInactiveAction( action );
}
}
var bindingsByRoot = this._bindingsByRootAndName,
bindingByName = bindingsByRoot[ rootUuid ];
if ( bindingByName !== undefined ) {
for ( var trackName in bindingByName ) {
var binding = bindingByName[ trackName ];
binding.restoreOriginalState();
this._removeInactiveBinding( binding );
}
}
},
// remove a targeted clip from the cache
uncacheAction: function ( clip, optionalRoot ) {
var action = this.existingAction( clip, optionalRoot );
if ( action !== null ) {
this._deactivateAction( action );
this._removeInactiveAction( action );
}
}
} );
/**
* @author mrdoob / http://mrdoob.com/
*/
function Uniform( value ) {
if ( typeof value === 'string' ) {
console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
value = arguments[ 1 ];
}
this.value = value;
}
Uniform.prototype.clone = function () {
return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
};
/**
* @author benaadams / https://twitter.com/ben_a_adams
*/
function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
InterleavedBuffer.call( this, array, stride );
this.meshPerAttribute = meshPerAttribute || 1;
}
InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
constructor: InstancedInterleavedBuffer,
isInstancedInterleavedBuffer: true,
copy: function ( source ) {
InterleavedBuffer.prototype.copy.call( this, source );
this.meshPerAttribute = source.meshPerAttribute;
return this;
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author bhouston / http://clara.io/
* @author stephomi / http://stephaneginier.com/
*/
function Raycaster( origin, direction, near, far ) {
this.ray = new Ray( origin, direction );
// direction is assumed to be normalized (for accurate distance calculations)
this.near = near || 0;
this.far = far || Infinity;
this.camera = null;
this.layers = new Layers();
this.params = {
Mesh: {},
Line: { threshold: 1 },
LOD: {},
Points: { threshold: 1 },
Sprite: {}
};
Object.defineProperties( this.params, {
PointCloud: {
get: function () {
console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
return this.Points;
}
}
} );
}
function ascSort( a, b ) {
return a.distance - b.distance;
}
function intersectObject( object, raycaster, intersects, recursive ) {
if ( object.layers.test( raycaster.layers ) ) {
object.raycast( raycaster, intersects );
}
if ( recursive === true ) {
var children = object.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
intersectObject( children[ i ], raycaster, intersects, true );
}
}
}
Object.assign( Raycaster.prototype, {
set: function ( origin, direction ) {
// direction is assumed to be normalized (for accurate distance calculations)
this.ray.set( origin, direction );
},
setFromCamera: function ( coords, camera ) {
if ( ( camera && camera.isPerspectiveCamera ) ) {
this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
this.camera = camera;
} else if ( ( camera && camera.isOrthographicCamera ) ) {
this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
this.camera = camera;
} else {
console.error( 'THREE.Raycaster: Unsupported camera type.' );
}
},
intersectObject: function ( object, recursive, optionalTarget ) {
var intersects = optionalTarget || [];
intersectObject( object, this, intersects, recursive );
intersects.sort( ascSort );
return intersects;
},
intersectObjects: function ( objects, recursive, optionalTarget ) {
var intersects = optionalTarget || [];
if ( Array.isArray( objects ) === false ) {
console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
return intersects;
}
for ( var i = 0, l = objects.length; i < l; i ++ ) {
intersectObject( objects[ i ], this, intersects, recursive );
}
intersects.sort( ascSort );
return intersects;
}
} );
/**
* @author bhouston / http://clara.io
* @author WestLangley / http://github.com/WestLangley
*
* Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
*
* The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
* The azimuthal angle (theta) is measured from the positive z-axis.
*/
function Spherical( radius, phi, theta ) {
this.radius = ( radius !== undefined ) ? radius : 1.0;
this.phi = ( phi !== undefined ) ? phi : 0; // polar angle
this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle
return this;
}
Object.assign( Spherical.prototype, {
set: function ( radius, phi, theta ) {
this.radius = radius;
this.phi = phi;
this.theta = theta;
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( other ) {
this.radius = other.radius;
this.phi = other.phi;
this.theta = other.theta;
return this;
},
// restrict phi to be betwee EPS and PI-EPS
makeSafe: function () {
var EPS = 0.000001;
this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
return this;
},
setFromVector3: function ( v ) {
return this.setFromCartesianCoords( v.x, v.y, v.z );
},
setFromCartesianCoords: function ( x, y, z ) {
this.radius = Math.sqrt( x * x + y * y + z * z );
if ( this.radius === 0 ) {
this.theta = 0;
this.phi = 0;
} else {
this.theta = Math.atan2( x, z );
this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );
}
return this;
}
} );
/**
* @author Mugen87 / https://github.com/Mugen87
*
* Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
*
*/
function Cylindrical( radius, theta, y ) {
this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
return this;
}
Object.assign( Cylindrical.prototype, {
set: function ( radius, theta, y ) {
this.radius = radius;
this.theta = theta;
this.y = y;
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( other ) {
this.radius = other.radius;
this.theta = other.theta;
this.y = other.y;
return this;
},
setFromVector3: function ( v ) {
return this.setFromCartesianCoords( v.x, v.y, v.z );
},
setFromCartesianCoords: function ( x, y, z ) {
this.radius = Math.sqrt( x * x + z * z );
this.theta = Math.atan2( x, z );
this.y = y;
return this;
}
} );
/**
* @author bhouston / http://clara.io
*/
var _vector$7 = new Vector2();
function Box2( min, max ) {
this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
}
Object.assign( Box2.prototype, {
set: function ( min, max ) {
this.min.copy( min );
this.max.copy( max );
return this;
},
setFromPoints: function ( points ) {
this.makeEmpty();
for ( var i = 0, il = points.length; i < il; i ++ ) {
this.expandByPoint( points[ i ] );
}
return this;
},
setFromCenterAndSize: function ( center, size ) {
var halfSize = _vector$7.copy( size ).multiplyScalar( 0.5 );
this.min.copy( center ).sub( halfSize );
this.max.copy( center ).add( halfSize );
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( box ) {
this.min.copy( box.min );
this.max.copy( box.max );
return this;
},
makeEmpty: function () {
this.min.x = this.min.y = + Infinity;
this.max.x = this.max.y = - Infinity;
return this;
},
isEmpty: function () {
// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
},
getCenter: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Box2: .getCenter() target is now required' );
target = new Vector2();
}
return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
},
getSize: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Box2: .getSize() target is now required' );
target = new Vector2();
}
return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
},
expandByPoint: function ( point ) {
this.min.min( point );
this.max.max( point );
return this;
},
expandByVector: function ( vector ) {
this.min.sub( vector );
this.max.add( vector );
return this;
},
expandByScalar: function ( scalar ) {
this.min.addScalar( - scalar );
this.max.addScalar( scalar );
return this;
},
containsPoint: function ( point ) {
return point.x < this.min.x || point.x > this.max.x ||
point.y < this.min.y || point.y > this.max.y ? false : true;
},
containsBox: function ( box ) {
return this.min.x <= box.min.x && box.max.x <= this.max.x &&
this.min.y <= box.min.y && box.max.y <= this.max.y;
},
getParameter: function ( point, target ) {
// This can potentially have a divide by zero if the box
// has a size dimension of 0.
if ( target === undefined ) {
console.warn( 'THREE.Box2: .getParameter() target is now required' );
target = new Vector2();
}
return target.set(
( point.x - this.min.x ) / ( this.max.x - this.min.x ),
( point.y - this.min.y ) / ( this.max.y - this.min.y )
);
},
intersectsBox: function ( box ) {
// using 4 splitting planes to rule out intersections
return box.max.x < this.min.x || box.min.x > this.max.x ||
box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
},
clampPoint: function ( point, target ) {
if ( target === undefined ) {
console.warn( 'THREE.Box2: .clampPoint() target is now required' );
target = new Vector2();
}
return target.copy( point ).clamp( this.min, this.max );
},
distanceToPoint: function ( point ) {
var clampedPoint = _vector$7.copy( point ).clamp( this.min, this.max );
return clampedPoint.sub( point ).length();
},
intersect: function ( box ) {
this.min.max( box.min );
this.max.min( box.max );
return this;
},
union: function ( box ) {
this.min.min( box.min );
this.max.max( box.max );
return this;
},
translate: function ( offset ) {
this.min.add( offset );
this.max.add( offset );
return this;
},
equals: function ( box ) {
return box.min.equals( this.min ) && box.max.equals( this.max );
}
} );
/**
* @author bhouston / http://clara.io
*/
var _startP = new Vector3();
var _startEnd = new Vector3();
function Line3( start, end ) {
this.start = ( start !== undefined ) ? start : new Vector3();
this.end = ( end !== undefined ) ? end : new Vector3();
}
Object.assign( Line3.prototype, {
set: function ( start, end ) {
this.start.copy( start );
this.end.copy( end );
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( line ) {
this.start.copy( line.start );
this.end.copy( line.end );
return this;
},
getCenter: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Line3: .getCenter() target is now required' );
target = new Vector3();
}
return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
},
delta: function ( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Line3: .delta() target is now required' );
target = new Vector3();
}
return target.subVectors( this.end, this.start );
},
distanceSq: function () {
return this.start.distanceToSquared( this.end );
},
distance: function () {
return this.start.distanceTo( this.end );
},
at: function ( t, target ) {
if ( target === undefined ) {
console.warn( 'THREE.Line3: .at() target is now required' );
target = new Vector3();
}
return this.delta( target ).multiplyScalar( t ).add( this.start );
},
closestPointToPointParameter: function ( point, clampToLine ) {
_startP.subVectors( point, this.start );
_startEnd.subVectors( this.end, this.start );
var startEnd2 = _startEnd.dot( _startEnd );
var startEnd_startP = _startEnd.dot( _startP );
var t = startEnd_startP / startEnd2;
if ( clampToLine ) {
t = MathUtils.clamp( t, 0, 1 );
}
return t;
},
closestPointToPoint: function ( point, clampToLine, target ) {
var t = this.closestPointToPointParameter( point, clampToLine );
if ( target === undefined ) {
console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
target = new Vector3();
}
return this.delta( target ).multiplyScalar( t ).add( this.start );
},
applyMatrix4: function ( matrix ) {
this.start.applyMatrix4( matrix );
this.end.applyMatrix4( matrix );
return this;
},
equals: function ( line ) {
return line.start.equals( this.start ) && line.end.equals( this.end );
}
} );
/**
* @author alteredq / http://alteredqualia.com/
*/
function ImmediateRenderObject( material ) {
Object3D.call( this );
this.material = material;
this.render = function ( /* renderCallback */ ) {};
}
ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
ImmediateRenderObject.prototype.isImmediateRenderObject = true;
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
var _vector$8 = new Vector3();
function SpotLightHelper( light, color ) {
Object3D.call( this );
this.light = light;
this.light.updateMatrixWorld();
this.matrix = light.matrixWorld;
this.matrixAutoUpdate = false;
this.color = color;
var geometry = new BufferGeometry();
var positions = [
0, 0, 0, 0, 0, 1,
0, 0, 0, 1, 0, 1,
0, 0, 0, - 1, 0, 1,
0, 0, 0, 0, 1, 1,
0, 0, 0, 0, - 1, 1
];
for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
var p1 = ( i / l ) * Math.PI * 2;
var p2 = ( j / l ) * Math.PI * 2;
positions.push(
Math.cos( p1 ), Math.sin( p1 ), 1,
Math.cos( p2 ), Math.sin( p2 ), 1
);
}
geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
var material = new LineBasicMaterial( { fog: false, toneMapped: false } );
this.cone = new LineSegments( geometry, material );
this.add( this.cone );
this.update();
}
SpotLightHelper.prototype = Object.create( Object3D.prototype );
SpotLightHelper.prototype.constructor = SpotLightHelper;
SpotLightHelper.prototype.dispose = function () {
this.cone.geometry.dispose();
this.cone.material.dispose();
};
SpotLightHelper.prototype.update = function () {
this.light.updateMatrixWorld();
var coneLength = this.light.distance ? this.light.distance : 1000;
var coneWidth = coneLength * Math.tan( this.light.angle );
this.cone.scale.set( coneWidth, coneWidth, coneLength );
_vector$8.setFromMatrixPosition( this.light.target.matrixWorld );
this.cone.lookAt( _vector$8 );
if ( this.color !== undefined ) {
this.cone.material.color.set( this.color );
} else {
this.cone.material.color.copy( this.light.color );
}
};
/**
* @author Sean Griffin / http://twitter.com/sgrif
* @author Michael Guerrero / http://realitymeltdown.com
* @author mrdoob / http://mrdoob.com/
* @author ikerr / http://verold.com
* @author Mugen87 / https://github.com/Mugen87
*/
var _vector$9 = new Vector3();
var _boneMatrix = new Matrix4();
var _matrixWorldInv = new Matrix4();
function getBoneList( object ) {
var boneList = [];
if ( object && object.isBone ) {
boneList.push( object );
}
for ( var i = 0; i < object.children.length; i ++ ) {
boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
}
return boneList;
}
function SkeletonHelper( object ) {
var bones = getBoneList( object );
var geometry = new BufferGeometry();
var vertices = [];
var colors = [];
var color1 = new Color( 0, 0, 1 );
var color2 = new Color( 0, 1, 0 );
for ( var i = 0; i < bones.length; i ++ ) {
var bone = bones[ i ];
if ( bone.parent && bone.parent.isBone ) {
vertices.push( 0, 0, 0 );
vertices.push( 0, 0, 0 );
colors.push( color1.r, color1.g, color1.b );
colors.push( color2.r, color2.g, color2.b );
}
}
geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
var material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
LineSegments.call( this, geometry, material );
this.type = 'SkeletonHelper';
this.root = object;
this.bones = bones;
this.matrix = object.matrixWorld;
this.matrixAutoUpdate = false;
}
SkeletonHelper.prototype = Object.create( LineSegments.prototype );
SkeletonHelper.prototype.constructor = SkeletonHelper;
SkeletonHelper.prototype.isSkeletonHelper = true;
SkeletonHelper.prototype.updateMatrixWorld = function ( force ) {
var bones = this.bones;
var geometry = this.geometry;
var position = geometry.getAttribute( 'position' );
_matrixWorldInv.getInverse( this.root.matrixWorld );
for ( var i = 0, j = 0; i < bones.length; i ++ ) {
var bone = bones[ i ];
if ( bone.parent && bone.parent.isBone ) {
_boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
_vector$9.setFromMatrixPosition( _boneMatrix );
position.setXYZ( j, _vector$9.x, _vector$9.y, _vector$9.z );
_boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
_vector$9.setFromMatrixPosition( _boneMatrix );
position.setXYZ( j + 1, _vector$9.x, _vector$9.y, _vector$9.z );
j += 2;
}
}
geometry.getAttribute( 'position' ).needsUpdate = true;
Object3D.prototype.updateMatrixWorld.call( this, force );
};
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
*/
function PointLightHelper( light, sphereSize, color ) {
this.light = light;
this.light.updateMatrixWorld();
this.color = color;
var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
var material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
Mesh.call( this, geometry, material );
this.type = 'PointLightHelper';
this.matrix = this.light.matrixWorld;
this.matrixAutoUpdate = false;
this.update();
/*
var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
var d = light.distance;
if ( d === 0.0 ) {
this.lightDistance.visible = false;
} else {
this.lightDistance.scale.set( d, d, d );
}
this.add( this.lightDistance );
*/
}
PointLightHelper.prototype = Object.create( Mesh.prototype );
PointLightHelper.prototype.constructor = PointLightHelper;
PointLightHelper.prototype.dispose = function () {
this.geometry.dispose();
this.material.dispose();
};
PointLightHelper.prototype.update = function () {
if ( this.color !== undefined ) {
this.material.color.set( this.color );
} else {
this.material.color.copy( this.light.color );
}
/*
var d = this.light.distance;
if ( d === 0.0 ) {
this.lightDistance.visible = false;
} else {
this.lightDistance.visible = true;
this.lightDistance.scale.set( d, d, d );
}
*/
};
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / https://github.com/Mugen87
*/
var _vector$a = new Vector3();
var _color1 = new Color();
var _color2 = new Color();
function HemisphereLightHelper( light, size, color ) {
Object3D.call( this );
this.light = light;
this.light.updateMatrixWorld();
this.matrix = light.matrixWorld;
this.matrixAutoUpdate = false;
this.color = color;
var geometry = new OctahedronBufferGeometry( size );
geometry.rotateY( Math.PI * 0.5 );
this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
if ( this.color === undefined ) this.material.vertexColors = true;
var position = geometry.getAttribute( 'position' );
var colors = new Float32Array( position.count * 3 );
geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
this.add( new Mesh( geometry, this.material ) );
this.update();
}
HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
HemisphereLightHelper.prototype.dispose = function () {
this.children[ 0 ].geometry.dispose();
this.children[ 0 ].material.dispose();
};
HemisphereLightHelper.prototype.update = function () {
var mesh = this.children[ 0 ];
if ( this.color !== undefined ) {
this.material.color.set( this.color );
} else {
var colors = mesh.geometry.getAttribute( 'color' );
_color1.copy( this.light.color );
_color2.copy( this.light.groundColor );
for ( var i = 0, l = colors.count; i < l; i ++ ) {
var color = ( i < ( l / 2 ) ) ? _color1 : _color2;
colors.setXYZ( i, color.r, color.g, color.b );
}
colors.needsUpdate = true;
}
mesh.lookAt( _vector$a.setFromMatrixPosition( this.light.matrixWorld ).negate() );
};
/**
* @author mrdoob / http://mrdoob.com/
*/
function GridHelper( size, divisions, color1, color2 ) {
size = size || 10;
divisions = divisions || 10;
color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
var center = divisions / 2;
var step = size / divisions;
var halfSize = size / 2;
var vertices = [], colors = [];
for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
vertices.push( - halfSize, 0, k, halfSize, 0, k );
vertices.push( k, 0, - halfSize, k, 0, halfSize );
var color = i === center ? color1 : color2;
color.toArray( colors, j ); j += 3;
color.toArray( colors, j ); j += 3;
color.toArray( colors, j ); j += 3;
color.toArray( colors, j ); j += 3;
}
var geometry = new BufferGeometry();
geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
LineSegments.call( this, geometry, material );
this.type = 'GridHelper';
}
GridHelper.prototype = Object.assign( Object.create( LineSegments.prototype ), {
constructor: GridHelper,
copy: function ( source ) {
LineSegments.prototype.copy.call( this, source );
this.geometry.copy( source.geometry );
this.material.copy( source.material );
return this;
},
clone: function () {
return new this.constructor().copy( this );
}
} );
/**
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / http://github.com/Mugen87
* @author Hectate / http://www.github.com/Hectate
*/
function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
radius = radius || 10;
radials = radials || 16;
circles = circles || 8;
divisions = divisions || 64;
color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
var vertices = [];
var colors = [];
var x, z;
var v, i, j, r, color;
// create the radials
for ( i = 0; i <= radials; i ++ ) {
v = ( i / radials ) * ( Math.PI * 2 );
x = Math.sin( v ) * radius;
z = Math.cos( v ) * radius;
vertices.push( 0, 0, 0 );
vertices.push( x, 0, z );
color = ( i & 1 ) ? color1 : color2;
colors.push( color.r, color.g, color.b );
colors.push( color.r, color.g, color.b );
}
// create the circles
for ( i = 0; i <= circles; i ++ ) {
color = ( i & 1 ) ? color1 : color2;
r = radius - ( radius / circles * i );
for ( j = 0; j < divisions; j ++ ) {
// first vertex
v = ( j / divisions ) * ( Math.PI * 2 );
x = Math.sin( v ) * r;
z = Math.cos( v ) * r;
vertices.push( x, 0, z );
colors.push( color.r, color.g, color.b );
// second vertex
v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
x = Math.sin( v ) * r;
z = Math.cos( v ) * r;
vertices.push( x, 0, z );
colors.push( color.r, color.g, color.b );
}
}
var geometry = new BufferGeometry();
geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
LineSegments.call( this, geometry, material );
this.type = 'PolarGridHelper';
}
PolarGridHelper.prototype = Object.create( LineSegments.prototype );
PolarGridHelper.prototype.constructor = PolarGridHelper;
/**
* @author alteredq / http://alteredqualia.com/
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
*/
var _v1$5 = new Vector3();
var _v2$3 = new Vector3();
var _v3$1 = new Vector3();
function DirectionalLightHelper( light, size, color ) {
Object3D.call( this );
this.light = light;
this.light.updateMatrixWorld();
this.matrix = light.matrixWorld;
this.matrixAutoUpdate = false;
this.color = color;
if ( size === undefined ) size = 1;
var geometry = new BufferGeometry();
geometry.setAttribute( 'position', new Float32BufferAttribute( [
- size, size, 0,
size, size, 0,
size, - size, 0,
- size, - size, 0,
- size, size, 0
], 3 ) );
var material = new LineBasicMaterial( { fog: false, toneMapped: false } );
this.lightPlane = new Line( geometry, material );
this.add( this.lightPlane );
geometry = new BufferGeometry();
geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
this.targetLine = new Line( geometry, material );
this.add( this.targetLine );
this.update();
}
DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
DirectionalLightHelper.prototype.dispose = function () {
this.lightPlane.geometry.dispose();
this.lightPlane.material.dispose();
this.targetLine.geometry.dispose();
this.targetLine.material.dispose();
};
DirectionalLightHelper.prototype.update = function () {
_v1$5.setFromMatrixPosition( this.light.matrixWorld );
_v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
_v3$1.subVectors( _v2$3, _v1$5 );
this.lightPlane.lookAt( _v2$3 );
if ( this.color !== undefined ) {
this.lightPlane.material.color.set( this.color );
this.targetLine.material.color.set( this.color );
} else {
this.lightPlane.material.color.copy( this.light.color );
this.targetLine.material.color.copy( this.light.color );
}
this.targetLine.lookAt( _v2$3 );
this.targetLine.scale.z = _v3$1.length();
};
/**
* @author alteredq / http://alteredqualia.com/
* @author Mugen87 / https://github.com/Mugen87
*
* - shows frustum, line of sight and up of the camera
* - suitable for fast updates
* - based on frustum visualization in lightgl.js shadowmap example
* http://evanw.github.com/lightgl.js/tests/shadowmap.html
*/
var _vector$b = new Vector3();
var _camera = new Camera();
function CameraHelper( camera ) {
var geometry = new BufferGeometry();
var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
var vertices = [];
var colors = [];
var pointMap = {};
// colors
var colorFrustum = new Color( 0xffaa00 );
var colorCone = new Color( 0xff0000 );
var colorUp = new Color( 0x00aaff );
var colorTarget = new Color( 0xffffff );
var colorCross = new Color( 0x333333 );
// near
addLine( 'n1', 'n2', colorFrustum );
addLine( 'n2', 'n4', colorFrustum );
addLine( 'n4', 'n3', colorFrustum );
addLine( 'n3', 'n1', colorFrustum );
// far
addLine( 'f1', 'f2', colorFrustum );
addLine( 'f2', 'f4', colorFrustum );
addLine( 'f4', 'f3', colorFrustum );
addLine( 'f3', 'f1', colorFrustum );
// sides
addLine( 'n1', 'f1', colorFrustum );
addLine( 'n2', 'f2', colorFrustum );
addLine( 'n3', 'f3', colorFrustum );
addLine( 'n4', 'f4', colorFrustum );
// cone
addLine( 'p', 'n1', colorCone );
addLine( 'p', 'n2', colorCone );
addLine( 'p', 'n3', colorCone );
addLine( 'p', 'n4', colorCone );
// up
addLine( 'u1', 'u2', colorUp );
addLine( 'u2', 'u3', colorUp );
addLine( 'u3', 'u1', colorUp );
// target
addLine( 'c', 't', colorTarget );
addLine( 'p', 'c', colorCross );
// cross
addLine( 'cn1', 'cn2', colorCross );
addLine( 'cn3', 'cn4', colorCross );
addLine( 'cf1', 'cf2', colorCross );
addLine( 'cf3', 'cf4', colorCross );
function addLine( a, b, color ) {
addPoint( a, color );
addPoint( b, color );
}
function addPoint( id, color ) {
vertices.push( 0, 0, 0 );
colors.push( color.r, color.g, color.b );
if ( pointMap[ id ] === undefined ) {
pointMap[ id ] = [];
}
pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
}
geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
LineSegments.call( this, geometry, material );
this.type = 'CameraHelper';
this.camera = camera;
if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
this.matrix = camera.matrixWorld;
this.matrixAutoUpdate = false;
this.pointMap = pointMap;
this.update();
}
CameraHelper.prototype = Object.create( LineSegments.prototype );
CameraHelper.prototype.constructor = CameraHelper;
CameraHelper.prototype.update = function () {
var geometry = this.geometry;
var pointMap = this.pointMap;
var w = 1, h = 1;
// we need just camera projection matrix inverse
// world matrix must be identity
_camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
// center / target
setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
// near
setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
// far
setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
// up
setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
// cross
setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
geometry.getAttribute( 'position' ).needsUpdate = true;
};
function setPoint( point, pointMap, geometry, camera, x, y, z ) {
_vector$b.set( x, y, z ).unproject( camera );
var points = pointMap[ point ];
if ( points !== undefined ) {
var position = geometry.getAttribute( 'position' );
for ( var i = 0, l = points.length; i < l; i ++ ) {
position.setXYZ( points[ i ], _vector$b.x, _vector$b.y, _vector$b.z );
}
}
}
/**
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / http://github.com/Mugen87
*/
var _box$3 = new Box3();
function BoxHelper( object, color ) {
this.object = object;
if ( color === undefined ) color = 0xffff00;
var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
var positions = new Float32Array( 8 * 3 );
var geometry = new BufferGeometry();
geometry.setIndex( new BufferAttribute( indices, 1 ) );
geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
this.type = 'BoxHelper';
this.matrixAutoUpdate = false;
this.update();
}
BoxHelper.prototype = Object.create( LineSegments.prototype );
BoxHelper.prototype.constructor = BoxHelper;
BoxHelper.prototype.update = function ( object ) {
if ( object !== undefined ) {
console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
}
if ( this.object !== undefined ) {
_box$3.setFromObject( this.object );
}
if ( _box$3.isEmpty() ) return;
var min = _box$3.min;
var max = _box$3.max;
/*
5____4
1/___0/|
| 6__|_7
2/___3/
0: max.x, max.y, max.z
1: min.x, max.y, max.z
2: min.x, min.y, max.z
3: max.x, min.y, max.z
4: max.x, max.y, min.z
5: min.x, max.y, min.z
6: min.x, min.y, min.z
7: max.x, min.y, min.z
*/
var position = this.geometry.attributes.position;
var array = position.array;
array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
position.needsUpdate = true;
this.geometry.computeBoundingSphere();
};
BoxHelper.prototype.setFromObject = function ( object ) {
this.object = object;
this.update();
return this;
};
BoxHelper.prototype.copy = function ( source ) {
LineSegments.prototype.copy.call( this, source );
this.object = source.object;
return this;
};
BoxHelper.prototype.clone = function () {
return new this.constructor().copy( this );
};
/**
* @author WestLangley / http://github.com/WestLangley
*/
function Box3Helper( box, color ) {
this.type = 'Box3Helper';
this.box = box;
color = color || 0xffff00;
var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
var geometry = new BufferGeometry();
geometry.setIndex( new BufferAttribute( indices, 1 ) );
geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
this.type = 'Box3Helper';
this.geometry.computeBoundingSphere();
}
Box3Helper.prototype = Object.create( LineSegments.prototype );
Box3Helper.prototype.constructor = Box3Helper;
Box3Helper.prototype.updateMatrixWorld = function ( force ) {
var box = this.box;
if ( box.isEmpty() ) return;
box.getCenter( this.position );
box.getSize( this.scale );
this.scale.multiplyScalar( 0.5 );
Object3D.prototype.updateMatrixWorld.call( this, force );
};
/**
* @author WestLangley / http://github.com/WestLangley
*/
function PlaneHelper( plane, size, hex ) {
this.plane = plane;
this.size = ( size === undefined ) ? 1 : size;
var color = ( hex !== undefined ) ? hex : 0xffff00;
var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];
var geometry = new BufferGeometry();
geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
geometry.computeBoundingSphere();
Line.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
this.type = 'PlaneHelper';
//
var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
var geometry2 = new BufferGeometry();
geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
geometry2.computeBoundingSphere();
this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
}
PlaneHelper.prototype = Object.create( Line.prototype );
PlaneHelper.prototype.constructor = PlaneHelper;
PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
var scale = - this.plane.constant;
if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
this.lookAt( this.plane.normal );
Object3D.prototype.updateMatrixWorld.call( this, force );
};
/**
* @author WestLangley / http://github.com/WestLangley
* @author zz85 / http://github.com/zz85
* @author bhouston / http://clara.io
*
* Creates an arrow for visualizing directions
*
* Parameters:
* dir - Vector3
* origin - Vector3
* length - Number
* color - color in hex value
* headLength - Number
* headWidth - Number
*/
var _axis = new Vector3();
var _lineGeometry, _coneGeometry;
function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
// dir is assumed to be normalized
Object3D.call( this );
this.type = 'ArrowHelper';
if ( dir === undefined ) dir = new Vector3( 0, 0, 1 );
if ( origin === undefined ) origin = new Vector3( 0, 0, 0 );
if ( length === undefined ) length = 1;
if ( color === undefined ) color = 0xffff00;
if ( headLength === undefined ) headLength = 0.2 * length;
if ( headWidth === undefined ) headWidth = 0.2 * headLength;
if ( _lineGeometry === undefined ) {
_lineGeometry = new BufferGeometry();
_lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
_coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
_coneGeometry.translate( 0, - 0.5, 0 );
}
this.position.copy( origin );
this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
this.line.matrixAutoUpdate = false;
this.add( this.line );
this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
this.cone.matrixAutoUpdate = false;
this.add( this.cone );
this.setDirection( dir );
this.setLength( length, headLength, headWidth );
}
ArrowHelper.prototype = Object.create( Object3D.prototype );
ArrowHelper.prototype.constructor = ArrowHelper;
ArrowHelper.prototype.setDirection = function ( dir ) {
// dir is assumed to be normalized
if ( dir.y > 0.99999 ) {
this.quaternion.set( 0, 0, 0, 1 );
} else if ( dir.y < - 0.99999 ) {
this.quaternion.set( 1, 0, 0, 0 );
} else {
_axis.set( dir.z, 0, - dir.x ).normalize();
var radians = Math.acos( dir.y );
this.quaternion.setFromAxisAngle( _axis, radians );
}
};
ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
if ( headLength === undefined ) headLength = 0.2 * length;
if ( headWidth === undefined ) headWidth = 0.2 * headLength;
this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
this.line.updateMatrix();
this.cone.scale.set( headWidth, headLength, headWidth );
this.cone.position.y = length;
this.cone.updateMatrix();
};
ArrowHelper.prototype.setColor = function ( color ) {
this.line.material.color.set( color );
this.cone.material.color.set( color );
};
ArrowHelper.prototype.copy = function ( source ) {
Object3D.prototype.copy.call( this, source, false );
this.line.copy( source.line );
this.cone.copy( source.cone );
return this;
};
ArrowHelper.prototype.clone = function () {
return new this.constructor().copy( this );
};
/**
* @author sroucheray / http://sroucheray.org/
* @author mrdoob / http://mrdoob.com/
*/
function AxesHelper( size ) {
size = size || 1;
var vertices = [
0, 0, 0, size, 0, 0,
0, 0, 0, 0, size, 0,
0, 0, 0, 0, 0, size
];
var colors = [
1, 0, 0, 1, 0.6, 0,
0, 1, 0, 0.6, 1, 0,
0, 0, 1, 0, 0.6, 1
];
var geometry = new BufferGeometry();
geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
LineSegments.call( this, geometry, material );
this.type = 'AxesHelper';
}
AxesHelper.prototype = Object.create( LineSegments.prototype );
AxesHelper.prototype.constructor = AxesHelper;
/**
* @author Emmett Lalish / elalish
*
* This class generates a Prefiltered, Mipmapped Radiance Environment Map
* (PMREM) from a cubeMap environment texture. This allows different levels of
* blur to be quickly accessed based on material roughness. It is packed into a
* special CubeUV format that allows us to perform custom interpolation so that
* we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
* chain, it only goes down to the LOD_MIN level (above), and then creates extra
* even more filtered 'mips' at the same LOD_MIN resolution, associated with
* higher roughness levels. In this way we maintain resolution to smoothly
* interpolate diffuse lighting while limiting sampling computation.
*/
var LOD_MIN = 4;
var LOD_MAX = 8;
var SIZE_MAX = Math.pow( 2, LOD_MAX );
// The standard deviations (radians) associated with the extra mips. These are
// chosen to approximate a Trowbridge-Reitz distribution function times the
// geometric shadowing function. These sigma values squared must match the
// variance #defines in cube_uv_reflection_fragment.glsl.js.
var EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
// The maximum length of the blur for loop. Smaller sigmas will use fewer
// samples and exit early, but not recompile the shader.
var MAX_SAMPLES = 20;
var ENCODINGS = {
[ LinearEncoding ]: 0,
[ sRGBEncoding ]: 1,
[ RGBEEncoding ]: 2,
[ RGBM7Encoding ]: 3,
[ RGBM16Encoding ]: 4,
[ RGBDEncoding ]: 5,
[ GammaEncoding ]: 6
};
var _flatCamera = new OrthographicCamera();
var { _lodPlanes, _sizeLods, _sigmas } = _createPlanes();
var _oldTarget = null;
// Golden Ratio
var PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
var INV_PHI = 1 / PHI;
// Vertices of a dodecahedron (except the opposites, which represent the
// same axis), used as axis directions evenly spread on a sphere.
var _axisDirections = [
new Vector3( 1, 1, 1 ),
new Vector3( - 1, 1, 1 ),
new Vector3( 1, 1, - 1 ),
new Vector3( - 1, 1, - 1 ),
new Vector3( 0, PHI, INV_PHI ),
new Vector3( 0, PHI, - INV_PHI ),
new Vector3( INV_PHI, 0, PHI ),
new Vector3( - INV_PHI, 0, PHI ),
new Vector3( PHI, INV_PHI, 0 ),
new Vector3( - PHI, INV_PHI, 0 ) ];
function PMREMGenerator( renderer ) {
this._renderer = renderer;
this._pingPongRenderTarget = null;
this._blurMaterial = _getBlurShader( MAX_SAMPLES );
this._equirectShader = null;
this._cubemapShader = null;
this._compileMaterial( this._blurMaterial );
}
PMREMGenerator.prototype = {
constructor: PMREMGenerator,
/**
* Generates a PMREM from a supplied Scene, which can be faster than using an
* image if networking bandwidth is low. Optional sigma specifies a blur radius
* in radians to be applied to the scene before PMREM generation. Optional near
* and far planes ensure the scene is rendered in its entirety (the cubeCamera
* is placed at the origin).
*/
fromScene: function ( scene, sigma = 0, near = 0.1, far = 100 ) {
_oldTarget = this._renderer.getRenderTarget();
var cubeUVRenderTarget = this._allocateTargets();
this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
if ( sigma > 0 ) {
this._blur( cubeUVRenderTarget, 0, 0, sigma );
}
this._applyPMREM( cubeUVRenderTarget );
this._cleanup( cubeUVRenderTarget );
return cubeUVRenderTarget;
},
/**
* Generates a PMREM from an equirectangular texture, which can be either LDR
* (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
* as this matches best with the 256 x 256 cubemap output.
*/
fromEquirectangular: function ( equirectangular ) {
equirectangular.magFilter = NearestFilter;
equirectangular.minFilter = NearestFilter;
equirectangular.generateMipmaps = false;
return this.fromCubemap( equirectangular );
},
/**
* Generates a PMREM from an cubemap texture, which can be either LDR
* (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
* as this matches best with the 256 x 256 cubemap output.
*/
fromCubemap: function ( cubemap ) {
_oldTarget = this._renderer.getRenderTarget();
var cubeUVRenderTarget = this._allocateTargets( cubemap );
this._textureToCubeUV( cubemap, cubeUVRenderTarget );
this._applyPMREM( cubeUVRenderTarget );
this._cleanup( cubeUVRenderTarget );
return cubeUVRenderTarget;
},
/**
* Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
* your texture's network fetch for increased concurrency.
*/
compileCubemapShader: function () {
if ( this._cubemapShader === null ) {
this._cubemapShader = _getCubemapShader();
this._compileMaterial( this._cubemapShader );
}
},
/**
* Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
* your texture's network fetch for increased concurrency.
*/
compileEquirectangularShader: function () {
if ( this._equirectShader === null ) {
this._equirectShader = _getEquirectShader();
this._compileMaterial( this._equirectShader );
}
},
/**
* Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
* so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
* one of them will cause any others to also become unusable.
*/
dispose: function () {
this._blurMaterial.dispose();
if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
if ( this._equirectShader !== null ) this._equirectShader.dispose();
for ( var i = 0; i < _lodPlanes.length; i ++ ) {
_lodPlanes[ i ].dispose();
}
},
// private interface
_cleanup: function ( outputTarget ) {
this._pingPongRenderTarget.dispose();
this._renderer.setRenderTarget( _oldTarget );
outputTarget.scissorTest = false;
// reset viewport and scissor
outputTarget.setSize( outputTarget.width, outputTarget.height );
},
_allocateTargets: function ( equirectangular ) {
var params = {
magFilter: NearestFilter,
minFilter: NearestFilter,
generateMipmaps: false,
type: UnsignedByteType,
format: RGBEFormat,
encoding: _isLDR( equirectangular ) ? equirectangular.encoding : RGBEEncoding,
depthBuffer: false,
stencilBuffer: false
};
var cubeUVRenderTarget = _createRenderTarget( params );
cubeUVRenderTarget.depthBuffer = equirectangular ? false : true;
this._pingPongRenderTarget = _createRenderTarget( params );
return cubeUVRenderTarget;
},
_compileMaterial: function ( material ) {
var tmpScene = new Scene();
tmpScene.add( new Mesh( _lodPlanes[ 0 ], material ) );
this._renderer.compile( tmpScene, _flatCamera );
},
_sceneToCubeUV: function ( scene, near, far, cubeUVRenderTarget ) {
var fov = 90;
var aspect = 1;
var cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
var upSign = [ 1, 1, 1, 1, - 1, 1 ];
var forwardSign = [ 1, 1, - 1, - 1, - 1, 1 ];
var renderer = this._renderer;
var outputEncoding = renderer.outputEncoding;
var toneMapping = renderer.toneMapping;
var toneMappingExposure = renderer.toneMappingExposure;
var clearColor = renderer.getClearColor();
var clearAlpha = renderer.getClearAlpha();
renderer.toneMapping = LinearToneMapping;
renderer.toneMappingExposure = 1.0;
renderer.outputEncoding = LinearEncoding;
scene.scale.z *= - 1;
var background = scene.background;
if ( background && background.isColor ) {
background.convertSRGBToLinear();
// Convert linear to RGBE
var maxComponent = Math.max( background.r, background.g, background.b );
var fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
var alpha = ( fExp + 128.0 ) / 255.0;
renderer.setClearColor( background, alpha );
scene.background = null;
}
for ( var i = 0; i < 6; i ++ ) {
var col = i % 3;
if ( col == 0 ) {
cubeCamera.up.set( 0, upSign[ i ], 0 );
cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
} else if ( col == 1 ) {
cubeCamera.up.set( 0, 0, upSign[ i ] );
cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
} else {
cubeCamera.up.set( 0, upSign[ i ], 0 );
cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
}
_setViewport( cubeUVRenderTarget,
col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
renderer.setRenderTarget( cubeUVRenderTarget );
renderer.render( scene, cubeCamera );
}
renderer.toneMapping = toneMapping;
renderer.toneMappingExposure = toneMappingExposure;
renderer.outputEncoding = outputEncoding;
renderer.setClearColor( clearColor, clearAlpha );
scene.scale.z *= - 1;
},
_textureToCubeUV: function ( texture, cubeUVRenderTarget ) {
var scene = new Scene();
var renderer = this._renderer;
if ( texture.isCubeTexture ) {
if ( this._cubemapShader == null ) {
this._cubemapShader = _getCubemapShader();
}
} else {
if ( this._equirectShader == null ) {
this._equirectShader = _getEquirectShader();
}
}
var material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
scene.add( new Mesh( _lodPlanes[ 0 ], material ) );
var uniforms = material.uniforms;
uniforms[ 'envMap' ].value = texture;
if ( ! texture.isCubeTexture ) {
uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
}
uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
_setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
renderer.setRenderTarget( cubeUVRenderTarget );
renderer.render( scene, _flatCamera );
},
_applyPMREM: function ( cubeUVRenderTarget ) {
var renderer = this._renderer;
var autoClear = renderer.autoClear;
renderer.autoClear = false;
for ( var i = 1; i < TOTAL_LODS; i ++ ) {
var sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
var poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
}
renderer.autoClear = autoClear;
},
/**
* This is a two-pass Gaussian blur for a cubemap. Normally this is done
* vertically and horizontally, but this breaks down on a cube. Here we apply
* the blur latitudinally (around the poles), and then longitudinally (towards
* the poles) to approximate the orthogonally-separable blur. It is least
* accurate at the poles, but still does a decent job.
*/
_blur: function ( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
var pingPongRenderTarget = this._pingPongRenderTarget;
this._halfBlur(
cubeUVRenderTarget,
pingPongRenderTarget,
lodIn,
lodOut,
sigma,
'latitudinal',
poleAxis );
this._halfBlur(
pingPongRenderTarget,
cubeUVRenderTarget,
lodOut,
lodOut,
sigma,
'longitudinal',
poleAxis );
},
_halfBlur: function ( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
var renderer = this._renderer;
var blurMaterial = this._blurMaterial;
if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
console.error(
'blur direction must be either latitudinal or longitudinal!' );
}
// Number of standard deviations at which to cut off the discrete approximation.
var STANDARD_DEVIATIONS = 3;
var blurScene = new Scene();
blurScene.add( new Mesh( _lodPlanes[ lodOut ], blurMaterial ) );
var blurUniforms = blurMaterial.uniforms;
var pixels = _sizeLods[ lodIn ] - 1;
var radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
var sigmaPixels = sigmaRadians / radiansPerPixel;
var samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
if ( samples > MAX_SAMPLES ) {
console.warn( `sigmaRadians, ${
sigmaRadians}, is too large and will clip, as it requested ${
samples} samples when the maximum is set to ${MAX_SAMPLES}` );
}
var weights = [];
var sum = 0;
for ( var i = 0; i < MAX_SAMPLES; ++ i ) {
var x = i / sigmaPixels;
var weight = Math.exp( - x * x / 2 );
weights.push( weight );
if ( i == 0 ) {
sum += weight;
} else if ( i < samples ) {
sum += 2 * weight;
}
}
for ( var i = 0; i < weights.length; i ++ ) {
weights[ i ] = weights[ i ] / sum;
}
blurUniforms[ 'envMap' ].value = targetIn.texture;
blurUniforms[ 'samples' ].value = samples;
blurUniforms[ 'weights' ].value = weights;
blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
if ( poleAxis ) {
blurUniforms[ 'poleAxis' ].value = poleAxis;
}
blurUniforms[ 'dTheta' ].value = radiansPerPixel;
blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
var outputSize = _sizeLods[ lodOut ];
var x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
var y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
_setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
renderer.setRenderTarget( targetOut );
renderer.render( blurScene, _flatCamera );
}
};
function _isLDR( texture ) {
if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
}
function _createPlanes() {
var _lodPlanes = [];
var _sizeLods = [];
var _sigmas = [];
var lod = LOD_MAX;
for ( var i = 0; i < TOTAL_LODS; i ++ ) {
var sizeLod = Math.pow( 2, lod );
_sizeLods.push( sizeLod );
var sigma = 1.0 / sizeLod;
if ( i > LOD_MAX - LOD_MIN ) {
sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
} else if ( i == 0 ) {
sigma = 0;
}
_sigmas.push( sigma );
var texelSize = 1.0 / ( sizeLod - 1 );
var min = - texelSize / 2;
var max = 1 + texelSize / 2;
var uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
var cubeFaces = 6;
var vertices = 6;
var positionSize = 3;
var uvSize = 2;
var faceIndexSize = 1;
var position = new Float32Array( positionSize * vertices * cubeFaces );
var uv = new Float32Array( uvSize * vertices * cubeFaces );
var faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
for ( var face = 0; face < cubeFaces; face ++ ) {
var x = ( face % 3 ) * 2 / 3 - 1;
var y = face > 2 ? 0 : - 1;
var coordinates = [
x, y, 0,
x + 2 / 3, y, 0,
x + 2 / 3, y + 1, 0,
x, y, 0,
x + 2 / 3, y + 1, 0,
x, y + 1, 0
];
position.set( coordinates, positionSize * vertices * face );
uv.set( uv1, uvSize * vertices * face );
var fill = [ face, face, face, face, face, face ];
faceIndex.set( fill, faceIndexSize * vertices * face );
}
var planes = new BufferGeometry();
planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
_lodPlanes.push( planes );
if ( lod > LOD_MIN ) {
lod --;
}
}
return { _lodPlanes, _sizeLods, _sigmas };
}
function _createRenderTarget( params ) {
var cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
cubeUVRenderTarget.scissorTest = true;
return cubeUVRenderTarget;
}
function _setViewport( target, x, y, width, height ) {
target.viewport.set( x, y, width, height );
target.scissor.set( x, y, width, height );
}
function _getBlurShader( maxSamples ) {
var weights = new Float32Array( maxSamples );
var poleAxis = new Vector3( 0, 1, 0 );
var shaderMaterial = new RawShaderMaterial( {
defines: { 'n': maxSamples },
uniforms: {
'envMap': { value: null },
'samples': { value: 1 },
'weights': { value: weights },
'latitudinal': { value: false },
'dTheta': { value: 0 },
'mipInt': { value: 0 },
'poleAxis': { value: poleAxis },
'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
},
vertexShader: _getCommonVertexShader(),
fragmentShader: `
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
uniform int samples;
uniform float weights[n];
uniform bool latitudinal;
uniform float dTheta;
uniform float mipInt;
uniform vec3 poleAxis;
${_getEncodings()}
#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>
vec3 getSample(float theta, vec3 axis) {
float cosTheta = cos(theta);
// Rodrigues' axis-angle rotation
vec3 sampleDirection = vOutputDirection * cosTheta
+ cross(axis, vOutputDirection) * sin(theta)
+ axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);
return bilinearCubeUV(envMap, sampleDirection, mipInt);
}
void main() {
vec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);
if (all(equal(axis, vec3(0.0))))
axis = vec3(vOutputDirection.z, 0.0, - vOutputDirection.x);
axis = normalize(axis);
gl_FragColor = vec4(0.0);
gl_FragColor.rgb += weights[0] * getSample(0.0, axis);
for (int i = 1; i < n; i++) {
if (i >= samples)
break;
float theta = dTheta * float(i);
gl_FragColor.rgb += weights[i] * getSample(-1.0 * theta, axis);
gl_FragColor.rgb += weights[i] * getSample(theta, axis);
}
gl_FragColor = linearToOutputTexel(gl_FragColor);
}
`,
blending: NoBlending,
depthTest: false,
depthWrite: false
} );
shaderMaterial.type = 'SphericalGaussianBlur';
return shaderMaterial;
}
function _getEquirectShader() {
var texelSize = new Vector2( 1, 1 );
var shaderMaterial = new RawShaderMaterial( {
uniforms: {
'envMap': { value: null },
'texelSize': { value: texelSize },
'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
},
vertexShader: _getCommonVertexShader(),
fragmentShader: `
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
uniform vec2 texelSize;
${_getEncodings()}
#define RECIPROCAL_PI 0.31830988618
#define RECIPROCAL_PI2 0.15915494
void main() {
gl_FragColor = vec4(0.0);
vec3 outputDirection = normalize(vOutputDirection);
vec2 uv;
uv.y = asin(clamp(outputDirection.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;
uv.x = atan(outputDirection.z, outputDirection.x) * RECIPROCAL_PI2 + 0.5;
vec2 f = fract(uv / texelSize - 0.5);
uv -= f * texelSize;
vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
uv.x += texelSize.x;
vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
uv.y += texelSize.y;
vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
uv.x -= texelSize.x;
vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
vec3 tm = mix(tl, tr, f.x);
vec3 bm = mix(bl, br, f.x);
gl_FragColor.rgb = mix(tm, bm, f.y);
gl_FragColor = linearToOutputTexel(gl_FragColor);
}
`,
blending: NoBlending,
depthTest: false,
depthWrite: false
} );
shaderMaterial.type = 'EquirectangularToCubeUV';
return shaderMaterial;
}
function _getCubemapShader() {
var shaderMaterial = new RawShaderMaterial( {
uniforms: {
'envMap': { value: null },
'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
},
vertexShader: _getCommonVertexShader(),
fragmentShader: `
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform samplerCube envMap;
${_getEncodings()}
void main() {
gl_FragColor = vec4(0.0);
gl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;
gl_FragColor = linearToOutputTexel(gl_FragColor);
}
`,
blending: NoBlending,
depthTest: false,
depthWrite: false
} );
shaderMaterial.type = 'CubemapToCubeUV';
return shaderMaterial;
}
function _getCommonVertexShader() {
return `
precision mediump float;
precision mediump int;
attribute vec3 position;
attribute vec2 uv;
attribute float faceIndex;
varying vec3 vOutputDirection;
vec3 getDirection(vec2 uv, float face) {
uv = 2.0 * uv - 1.0;
vec3 direction = vec3(uv, 1.0);
if (face == 0.0) {
direction = direction.zyx;
direction.z *= -1.0;
} else if (face == 1.0) {
direction = direction.xzy;
direction.z *= -1.0;
} else if (face == 3.0) {
direction = direction.zyx;
direction.x *= -1.0;
} else if (face == 4.0) {
direction = direction.xzy;
direction.y *= -1.0;
} else if (face == 5.0) {
direction.xz *= -1.0;
}
return direction;
}
void main() {
vOutputDirection = getDirection(uv, faceIndex);
gl_Position = vec4( position, 1.0 );
}
`;
}
function _getEncodings() {
return `
uniform int inputEncoding;
uniform int outputEncoding;
#include <encodings_pars_fragment>
vec4 inputTexelToLinear(vec4 value){
if(inputEncoding == 0){
return value;
}else if(inputEncoding == 1){
return sRGBToLinear(value);
}else if(inputEncoding == 2){
return RGBEToLinear(value);
}else if(inputEncoding == 3){
return RGBMToLinear(value, 7.0);
}else if(inputEncoding == 4){
return RGBMToLinear(value, 16.0);
}else if(inputEncoding == 5){
return RGBDToLinear(value, 256.0);
}else{
return GammaToLinear(value, 2.2);
}
}
vec4 linearToOutputTexel(vec4 value){
if(outputEncoding == 0){
return value;
}else if(outputEncoding == 1){
return LinearTosRGB(value);
}else if(outputEncoding == 2){
return LinearToRGBE(value);
}else if(outputEncoding == 3){
return LinearToRGBM(value, 7.0);
}else if(outputEncoding == 4){
return LinearToRGBM(value, 16.0);
}else if(outputEncoding == 5){
return LinearToRGBD(value, 256.0);
}else{
return LinearToGamma(value, 2.2);
}
}
vec4 envMapTexelToLinear(vec4 color) {
return inputTexelToLinear(color);
}
`;
}
/**
* @author mrdoob / http://mrdoob.com/
*/
function Face4( a, b, c, d, normal, color, materialIndex ) {
console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
return new Face3( a, b, c, normal, color, materialIndex );
}
var LineStrip = 0;
var LinePieces = 1;
var NoColors = 0;
var FaceColors = 1;
var VertexColors = 2;
function MeshFaceMaterial( materials ) {
console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
return materials;
}
function MultiMaterial( materials ) {
if ( materials === undefined ) materials = [];
console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
materials.isMultiMaterial = true;
materials.materials = materials;
materials.clone = function () {
return materials.slice();
};
return materials;
}
function PointCloud( geometry, material ) {
console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
return new Points( geometry, material );
}
function Particle( material ) {
console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
return new Sprite( material );
}
function ParticleSystem( geometry, material ) {
console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
return new Points( geometry, material );
}
function PointCloudMaterial( parameters ) {
console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
return new PointsMaterial( parameters );
}
function ParticleBasicMaterial( parameters ) {
console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
return new PointsMaterial( parameters );
}
function ParticleSystemMaterial( parameters ) {
console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
return new PointsMaterial( parameters );
}
function Vertex( x, y, z ) {
console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
return new Vector3( x, y, z );
}
//
function DynamicBufferAttribute( array, itemSize ) {
console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
}
function Int8Attribute( array, itemSize ) {
console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
return new Int8BufferAttribute( array, itemSize );
}
function Uint8Attribute( array, itemSize ) {
console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
return new Uint8BufferAttribute( array, itemSize );
}
function Uint8ClampedAttribute( array, itemSize ) {
console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
return new Uint8ClampedBufferAttribute( array, itemSize );
}
function Int16Attribute( array, itemSize ) {
console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
return new Int16BufferAttribute( array, itemSize );
}
function Uint16Attribute( array, itemSize ) {
console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
return new Uint16BufferAttribute( array, itemSize );
}
function Int32Attribute( array, itemSize ) {
console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
return new Int32BufferAttribute( array, itemSize );
}
function Uint32Attribute( array, itemSize ) {
console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
return new Uint32BufferAttribute( array, itemSize );
}
function Float32Attribute( array, itemSize ) {
console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
return new Float32BufferAttribute( array, itemSize );
}
function Float64Attribute( array, itemSize ) {
console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
return new Float64BufferAttribute( array, itemSize );
}
//
Curve.create = function ( construct, getPoint ) {
console.log( 'THREE.Curve.create() has been deprecated' );
construct.prototype = Object.create( Curve.prototype );
construct.prototype.constructor = construct;
construct.prototype.getPoint = getPoint;
return construct;
};
//
Object.assign( CurvePath.prototype, {
createPointsGeometry: function ( divisions ) {
console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
// generate geometry from path points (for Line or Points objects)
var pts = this.getPoints( divisions );
return this.createGeometry( pts );
},
createSpacedPointsGeometry: function ( divisions ) {
console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
// generate geometry from equidistant sampling along the path
var pts = this.getSpacedPoints( divisions );
return this.createGeometry( pts );
},
createGeometry: function ( points ) {
console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
var geometry = new Geometry();
for ( var i = 0, l = points.length; i < l; i ++ ) {
var point = points[ i ];
geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
}
return geometry;
}
} );
//
Object.assign( Path.prototype, {
fromPoints: function ( points ) {
console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
return this.setFromPoints( points );
}
} );
//
function ClosedSplineCurve3( points ) {
console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
CatmullRomCurve3.call( this, points );
this.type = 'catmullrom';
this.closed = true;
}
ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
//
function SplineCurve3( points ) {
console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
CatmullRomCurve3.call( this, points );
this.type = 'catmullrom';
}
SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
//
function Spline( points ) {
console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
CatmullRomCurve3.call( this, points );
this.type = 'catmullrom';
}
Spline.prototype = Object.create( CatmullRomCurve3.prototype );
Object.assign( Spline.prototype, {
initFromArray: function ( /* a */ ) {
console.error( 'THREE.Spline: .initFromArray() has been removed.' );
},
getControlPointsArray: function ( /* optionalTarget */ ) {
console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
},
reparametrizeByArcLength: function ( /* samplingCoef */ ) {
console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
}
} );
//
function AxisHelper( size ) {
console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
return new AxesHelper( size );
}
function BoundingBoxHelper( object, color ) {
console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
return new BoxHelper( object, color );
}
function EdgesHelper( object, hex ) {
console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
}
GridHelper.prototype.setColors = function () {
console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
};
SkeletonHelper.prototype.update = function () {
console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
};
function WireframeHelper( object, hex ) {
console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
}
//
Object.assign( Loader.prototype, {
extractUrlBase: function ( url ) {
console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
return LoaderUtils.extractUrlBase( url );
}
} );
Loader.Handlers = {
add: function ( /* regex, loader */ ) {
console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
},
get: function ( /* file */ ) {
console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
}
};
function XHRLoader( manager ) {
console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
return new FileLoader( manager );
}
function BinaryTextureLoader( manager ) {
console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
return new DataTextureLoader( manager );
}
Object.assign( ObjectLoader.prototype, {
setTexturePath: function ( value ) {
console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
return this.setResourcePath( value );
}
} );
//
Object.assign( Box2.prototype, {
center: function ( optionalTarget ) {
console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
return this.getCenter( optionalTarget );
},
empty: function () {
console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
return this.isEmpty();
},
isIntersectionBox: function ( box ) {
console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
return this.intersectsBox( box );
},
size: function ( optionalTarget ) {
console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
return this.getSize( optionalTarget );
}
} );
Object.assign( Box3.prototype, {
center: function ( optionalTarget ) {
console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
return this.getCenter( optionalTarget );
},
empty: function () {
console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
return this.isEmpty();
},
isIntersectionBox: function ( box ) {
console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
return this.intersectsBox( box );
},
isIntersectionSphere: function ( sphere ) {
console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
return this.intersectsSphere( sphere );
},
size: function ( optionalTarget ) {
console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
return this.getSize( optionalTarget );
}
} );
Object.assign( Sphere.prototype, {
empty: function () {
console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
return this.isEmpty();
},
} );
Frustum.prototype.setFromMatrix = function ( m ) {
console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
return this.setFromProjectionMatrix( m );
};
Line3.prototype.center = function ( optionalTarget ) {
console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
return this.getCenter( optionalTarget );
};
Object.assign( MathUtils, {
random16: function () {
console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
return Math.random();
},
nearestPowerOfTwo: function ( value ) {
console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
return MathUtils.floorPowerOfTwo( value );
},
nextPowerOfTwo: function ( value ) {
console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
return MathUtils.ceilPowerOfTwo( value );
}
} );
Object.assign( Matrix3.prototype, {
flattenToArrayOffset: function ( array, offset ) {
console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
return this.toArray( array, offset );
},
multiplyVector3: function ( vector ) {
console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
return vector.applyMatrix3( this );
},
multiplyVector3Array: function ( /* a */ ) {
console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
},
applyToBufferAttribute: function ( attribute ) {
console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
return attribute.applyMatrix3( this );
},
applyToVector3Array: function ( /* array, offset, length */ ) {
console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
}
} );
Object.assign( Matrix4.prototype, {
extractPosition: function ( m ) {
console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
return this.copyPosition( m );
},
flattenToArrayOffset: function ( array, offset ) {
console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
return this.toArray( array, offset );
},
getPosition: function () {
console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
return new Vector3().setFromMatrixColumn( this, 3 );
},
setRotationFromQuaternion: function ( q ) {
console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
return this.makeRotationFromQuaternion( q );
},
multiplyToArray: function () {
console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
},
multiplyVector3: function ( vector ) {
console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
return vector.applyMatrix4( this );
},
multiplyVector4: function ( vector ) {
console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
return vector.applyMatrix4( this );
},
multiplyVector3Array: function ( /* a */ ) {
console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
},
rotateAxis: function ( v ) {
console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
v.transformDirection( this );
},
crossVector: function ( vector ) {
console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
return vector.applyMatrix4( this );
},
translate: function () {
console.error( 'THREE.Matrix4: .translate() has been removed.' );
},
rotateX: function () {
console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
},
rotateY: function () {
console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
},
rotateZ: function () {
console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
},
rotateByAxis: function () {
console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
},
applyToBufferAttribute: function ( attribute ) {
console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
return attribute.applyMatrix4( this );
},
applyToVector3Array: function ( /* array, offset, length */ ) {
console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
},
makeFrustum: function ( left, right, bottom, top, near, far ) {
console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
return this.makePerspective( left, right, top, bottom, near, far );
}
} );
Plane.prototype.isIntersectionLine = function ( line ) {
console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
return this.intersectsLine( line );
};
Quaternion.prototype.multiplyVector3 = function ( vector ) {
console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
return vector.applyQuaternion( this );
};
Object.assign( Ray.prototype, {
isIntersectionBox: function ( box ) {
console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
return this.intersectsBox( box );
},
isIntersectionPlane: function ( plane ) {
console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
return this.intersectsPlane( plane );
},
isIntersectionSphere: function ( sphere ) {
console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
return this.intersectsSphere( sphere );
}
} );
Object.assign( Triangle.prototype, {
area: function () {
console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
return this.getArea();
},
barycoordFromPoint: function ( point, target ) {
console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
return this.getBarycoord( point, target );
},
midpoint: function ( target ) {
console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
return this.getMidpoint( target );
},
normal: function ( target ) {
console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
return this.getNormal( target );
},
plane: function ( target ) {
console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
return this.getPlane( target );
}
} );
Object.assign( Triangle, {
barycoordFromPoint: function ( point, a, b, c, target ) {
console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
return Triangle.getBarycoord( point, a, b, c, target );
},
normal: function ( a, b, c, target ) {
console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
return Triangle.getNormal( a, b, c, target );
}
} );
Object.assign( Shape.prototype, {
extractAllPoints: function ( divisions ) {
console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
return this.extractPoints( divisions );
},
extrude: function ( options ) {
console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
return new ExtrudeGeometry( this, options );
},
makeGeometry: function ( options ) {
console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
return new ShapeGeometry( this, options );
}
} );
Object.assign( Vector2.prototype, {
fromAttribute: function ( attribute, index, offset ) {
console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
return this.fromBufferAttribute( attribute, index, offset );
},
distanceToManhattan: function ( v ) {
console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
return this.manhattanDistanceTo( v );
},
lengthManhattan: function () {
console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
return this.manhattanLength();
}
} );
Object.assign( Vector3.prototype, {
setEulerFromRotationMatrix: function () {
console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
},
setEulerFromQuaternion: function () {
console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
},
getPositionFromMatrix: function ( m ) {
console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
return this.setFromMatrixPosition( m );
},
getScaleFromMatrix: function ( m ) {
console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
return this.setFromMatrixScale( m );
},
getColumnFromMatrix: function ( index, matrix ) {
console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
return this.setFromMatrixColumn( matrix, index );
},
applyProjection: function ( m ) {
console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
return this.applyMatrix4( m );
},
fromAttribute: function ( attribute, index, offset ) {
console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
return this.fromBufferAttribute( attribute, index, offset );
},
distanceToManhattan: function ( v ) {
console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
return this.manhattanDistanceTo( v );
},
lengthManhattan: function () {
console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
return this.manhattanLength();
}
} );
Object.assign( Vector4.prototype, {
fromAttribute: function ( attribute, index, offset ) {
console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
return this.fromBufferAttribute( attribute, index, offset );
},
lengthManhattan: function () {
console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
return this.manhattanLength();
}
} );
//
Object.assign( Geometry.prototype, {
computeTangents: function () {
console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
},
computeLineDistances: function () {
console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
},
applyMatrix: function ( matrix ) {
console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' );
return this.applyMatrix4( matrix );
}
} );
Object.assign( Object3D.prototype, {
getChildByName: function ( name ) {
console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
return this.getObjectByName( name );
},
renderDepth: function () {
console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
},
translate: function ( distance, axis ) {
console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
return this.translateOnAxis( axis, distance );
},
getWorldRotation: function () {
console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
},
applyMatrix: function ( matrix ) {
console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
return this.applyMatrix4( matrix );
}
} );
Object.defineProperties( Object3D.prototype, {
eulerOrder: {
get: function () {
console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
return this.rotation.order;
},
set: function ( value ) {
console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
this.rotation.order = value;
}
},
useQuaternion: {
get: function () {
console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
},
set: function () {
console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
}
}
} );
Object.assign( Mesh.prototype, {
setDrawMode: function () {
console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
},
} );
Object.defineProperties( Mesh.prototype, {
drawMode: {
get: function () {
console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
return TrianglesDrawMode;
},
set: function () {
console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
}
}
} );
Object.defineProperties( LOD.prototype, {
objects: {
get: function () {
console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
return this.levels;
}
}
} );
Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
get: function () {
console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
},
set: function () {
console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
}
} );
SkinnedMesh.prototype.initBones = function () {
console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
};
Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
get: function () {
console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
return this.arcLengthDivisions;
},
set: function ( value ) {
console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
this.arcLengthDivisions = value;
}
} );
//
PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
"Use .setFocalLength and .filmGauge for a photographic setup." );
if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
this.setFocalLength( focalLength );
};
//
Object.defineProperties( Light.prototype, {
onlyShadow: {
set: function () {
console.warn( 'THREE.Light: .onlyShadow has been removed.' );
}
},
shadowCameraFov: {
set: function ( value ) {
console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
this.shadow.camera.fov = value;
}
},
shadowCameraLeft: {
set: function ( value ) {
console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
this.shadow.camera.left = value;
}
},
shadowCameraRight: {
set: function ( value ) {
console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
this.shadow.camera.right = value;
}
},
shadowCameraTop: {
set: function ( value ) {
console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
this.shadow.camera.top = value;
}
},
shadowCameraBottom: {
set: function ( value ) {
console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
this.shadow.camera.bottom = value;
}
},
shadowCameraNear: {
set: function ( value ) {
console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
this.shadow.camera.near = value;
}
},
shadowCameraFar: {
set: function ( value ) {
console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
this.shadow.camera.far = value;
}
},
shadowCameraVisible: {
set: function () {
console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
}
},
shadowBias: {
set: function ( value ) {
console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
this.shadow.bias = value;
}
},
shadowDarkness: {
set: function () {
console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
}
},
shadowMapWidth: {
set: function ( value ) {
console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
this.shadow.mapSize.width = value;
}
},
shadowMapHeight: {
set: function ( value ) {
console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
this.shadow.mapSize.height = value;
}
}
} );
//
Object.defineProperties( BufferAttribute.prototype, {
length: {
get: function () {
console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
return this.array.length;
}
},
dynamic: {
get: function () {
console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
return this.usage === DynamicDrawUsage;
},
set: function ( /* value */ ) {
console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
this.setUsage( DynamicDrawUsage );
}
}
} );
Object.assign( BufferAttribute.prototype, {
setDynamic: function ( value ) {
console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
return this;
},
copyIndicesArray: function ( /* indices */ ) {
console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
},
setArray: function ( /* array */ ) {
console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
}
} );
Object.assign( BufferGeometry.prototype, {
addIndex: function ( index ) {
console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
this.setIndex( index );
},
addAttribute: function ( name, attribute ) {
console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
}
if ( name === 'index' ) {
console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
this.setIndex( attribute );
return this;
}
return this.setAttribute( name, attribute );
},
addDrawCall: function ( start, count, indexOffset ) {
if ( indexOffset !== undefined ) {
console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
}
console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
this.addGroup( start, count );
},
clearDrawCalls: function () {
console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
this.clearGroups();
},
computeTangents: function () {
console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
},
computeOffsets: function () {
console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
},
removeAttribute: function ( name ) {
console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
return this.deleteAttribute( name );
},
applyMatrix: function ( matrix ) {
console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
return this.applyMatrix4( matrix );
}
} );
Object.defineProperties( BufferGeometry.prototype, {
drawcalls: {
get: function () {
console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
return this.groups;
}
},
offsets: {
get: function () {
console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
return this.groups;
}
}
} );
Object.defineProperties( Raycaster.prototype, {
linePrecision: {
get: function () {
console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
return this.params.Line.threshold;
},
set: function ( value ) {
console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
this.params.Line.threshold = value;
}
}
} );
Object.defineProperties( InterleavedBuffer.prototype, {
dynamic: {
get: function () {
console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
return this.usage === DynamicDrawUsage;
},
set: function ( value ) {
console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
this.setUsage( value );
}
}
} );
Object.assign( InterleavedBuffer.prototype, {
setDynamic: function ( value ) {
console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
return this;
},
setArray: function ( /* array */ ) {
console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
}
} );
//
Object.assign( ExtrudeBufferGeometry.prototype, {
getArrays: function () {
console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
},
addShapeList: function () {
console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
},
addShape: function () {
console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
}
} );
//
Object.defineProperties( Uniform.prototype, {
dynamic: {
set: function () {
console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
}
},
onUpdate: {
value: function () {
console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
return this;
}
}
} );
//
Object.defineProperties( Material.prototype, {
wrapAround: {
get: function () {
console.warn( 'THREE.Material: .wrapAround has been removed.' );
},
set: function () {
console.warn( 'THREE.Material: .wrapAround has been removed.' );
}
},
overdraw: {
get: function () {
console.warn( 'THREE.Material: .overdraw has been removed.' );
},
set: function () {
console.warn( 'THREE.Material: .overdraw has been removed.' );
}
},
wrapRGB: {
get: function () {
console.warn( 'THREE.Material: .wrapRGB has been removed.' );
return new Color();
}
},
shading: {
get: function () {
console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
},
set: function ( value ) {
console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
this.flatShading = ( value === FlatShading );
}
},
stencilMask: {
get: function () {
console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
return this.stencilFuncMask;
},
set: function ( value ) {
console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
this.stencilFuncMask = value;
}
}
} );
Object.defineProperties( MeshPhongMaterial.prototype, {
metal: {
get: function () {
console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
return false;
},
set: function () {
console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
}
}
} );
Object.defineProperties( ShaderMaterial.prototype, {
derivatives: {
get: function () {
console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
return this.extensions.derivatives;
},
set: function ( value ) {
console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
this.extensions.derivatives = value;
}
}
} );
//
Object.assign( WebGLRenderer.prototype, {
clearTarget: function ( renderTarget, color, depth, stencil ) {
console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
this.setRenderTarget( renderTarget );
this.clear( color, depth, stencil );
},
animate: function ( callback ) {
console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
this.setAnimationLoop( callback );
},
getCurrentRenderTarget: function () {
console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
return this.getRenderTarget();
},
getMaxAnisotropy: function () {
console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
return this.capabilities.getMaxAnisotropy();
},
getPrecision: function () {
console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
return this.capabilities.precision;
},
resetGLState: function () {
console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
return this.state.reset();
},
supportsFloatTextures: function () {
console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
return this.extensions.get( 'OES_texture_float' );
},
supportsHalfFloatTextures: function () {
console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
return this.extensions.get( 'OES_texture_half_float' );
},
supportsStandardDerivatives: function () {
console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
return this.extensions.get( 'OES_standard_derivatives' );
},
supportsCompressedTextureS3TC: function () {
console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
},
supportsCompressedTexturePVRTC: function () {
console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
},
supportsBlendMinMax: function () {
console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
return this.extensions.get( 'EXT_blend_minmax' );
},
supportsVertexTextures: function () {
console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
return this.capabilities.vertexTextures;
},
supportsInstancedArrays: function () {
console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
return this.extensions.get( 'ANGLE_instanced_arrays' );
},
enableScissorTest: function ( boolean ) {
console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
this.setScissorTest( boolean );
},
initMaterial: function () {
console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
},
addPrePlugin: function () {
console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
},
addPostPlugin: function () {
console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
},
updateShadowMap: function () {
console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
},
setFaceCulling: function () {
console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
},
allocTextureUnit: function () {
console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
},
setTexture: function () {
console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
},
setTexture2D: function () {
console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
},
setTextureCube: function () {
console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
},
getActiveMipMapLevel: function () {
console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
return this.getActiveMipmapLevel();
}
} );
Object.defineProperties( WebGLRenderer.prototype, {
shadowMapEnabled: {
get: function () {
return this.shadowMap.enabled;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
this.shadowMap.enabled = value;
}
},
shadowMapType: {
get: function () {
return this.shadowMap.type;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
this.shadowMap.type = value;
}
},
shadowMapCullFace: {
get: function () {
console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
return undefined;
},
set: function ( /* value */ ) {
console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
}
},
context: {
get: function () {
console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
return this.getContext();
}
},
vr: {
get: function () {
console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
return this.xr;
}
},
gammaInput: {
get: function () {
console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
return false;
},
set: function () {
console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
}
},
gammaOutput: {
get: function () {
console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
return false;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
}
}
} );
Object.defineProperties( WebGLShadowMap.prototype, {
cullFace: {
get: function () {
console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
return undefined;
},
set: function ( /* cullFace */ ) {
console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
}
},
renderReverseSided: {
get: function () {
console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
return undefined;
},
set: function () {
console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
}
},
renderSingleSided: {
get: function () {
console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
return undefined;
},
set: function () {
console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
}
}
} );
function WebGLRenderTargetCube( width, height, options ) {
console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
return new WebGLCubeRenderTarget( width, options );
}
//
Object.defineProperties( WebGLRenderTarget.prototype, {
wrapS: {
get: function () {
console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
return this.texture.wrapS;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
this.texture.wrapS = value;
}
},
wrapT: {
get: function () {
console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
return this.texture.wrapT;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
this.texture.wrapT = value;
}
},
magFilter: {
get: function () {
console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
return this.texture.magFilter;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
this.texture.magFilter = value;
}
},
minFilter: {
get: function () {
console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
return this.texture.minFilter;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
this.texture.minFilter = value;
}
},
anisotropy: {
get: function () {
console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
return this.texture.anisotropy;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
this.texture.anisotropy = value;
}
},
offset: {
get: function () {
console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
return this.texture.offset;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
this.texture.offset = value;
}
},
repeat: {
get: function () {
console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
return this.texture.repeat;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
this.texture.repeat = value;
}
},
format: {
get: function () {
console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
return this.texture.format;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
this.texture.format = value;
}
},
type: {
get: function () {
console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
return this.texture.type;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
this.texture.type = value;
}
},
generateMipmaps: {
get: function () {
console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
return this.texture.generateMipmaps;
},
set: function ( value ) {
console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
this.texture.generateMipmaps = value;
}
}
} );
//
Object.defineProperties( Audio.prototype, {
load: {
value: function ( file ) {
console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
var scope = this;
var audioLoader = new AudioLoader();
audioLoader.load( file, function ( buffer ) {
scope.setBuffer( buffer );
} );
return this;
}
},
startTime: {
set: function () {
console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );
}
}
} );
AudioAnalyser.prototype.getData = function () {
console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
return this.getFrequencyData();
};
//
CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
return this.update( renderer, scene );
};
//
var GeometryUtils = {
merge: function ( geometry1, geometry2, materialIndexOffset ) {
console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
var matrix;
if ( geometry2.isMesh ) {
geometry2.matrixAutoUpdate && geometry2.updateMatrix();
matrix = geometry2.matrix;
geometry2 = geometry2.geometry;
}
geometry1.merge( geometry2, matrix, materialIndexOffset );
},
center: function ( geometry ) {
console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
return geometry.center();
}
};
ImageUtils.crossOrigin = undefined;
ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
var loader = new TextureLoader();
loader.setCrossOrigin( this.crossOrigin );
var texture = loader.load( url, onLoad, undefined, onError );
if ( mapping ) texture.mapping = mapping;
return texture;
};
ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
var loader = new CubeTextureLoader();
loader.setCrossOrigin( this.crossOrigin );
var texture = loader.load( urls, onLoad, undefined, onError );
if ( mapping ) texture.mapping = mapping;
return texture;
};
ImageUtils.loadCompressedTexture = function () {
console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
};
ImageUtils.loadCompressedTextureCube = function () {
console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
};
//
function CanvasRenderer() {
console.error( 'THREE.CanvasRenderer has been removed' );
}
//
function JSONLoader() {
console.error( 'THREE.JSONLoader has been removed.' );
}
//
var SceneUtils = {
createMultiMaterialObject: function ( /* geometry, materials */ ) {
console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
},
detach: function ( /* child, parent, scene */ ) {
console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
},
attach: function ( /* child, scene, parent */ ) {
console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
}
};
//
function LensFlare() {
console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
}
if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
/* eslint-disable no-undef */
__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
revision: REVISION,
} } ) );
/* eslint-enable no-undef */
}
/***/ }),
/***/ "./node_modules/three/examples/jsm/loaders/ColladaLoader.js":
/*!******************************************************************!*\
!*** ./node_modules/three/examples/jsm/loaders/ColladaLoader.js ***!
\******************************************************************/
/*! exports provided: ColladaLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColladaLoader", function() { return ColladaLoader; });
/* harmony import */ var _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../build/three.module.js */ "./node_modules/three/build/three.module.js");
/* harmony import */ var _loaders_TGALoader_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loaders/TGALoader.js */ "./node_modules/three/examples/jsm/loaders/TGALoader.js");
/**
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / https://github.com/Mugen87
*/
var ColladaLoader = function ( manager ) {
_build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Loader"].call( this, manager );
};
ColladaLoader.prototype = Object.assign( Object.create( _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Loader"].prototype ), {
constructor: ColladaLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var path = ( scope.path === '' ) ? _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["LoaderUtils"].extractUrlBase( url ) : scope.path;
var loader = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["FileLoader"]( scope.manager );
loader.setPath( scope.path );
loader.load( url, function ( text ) {
onLoad( scope.parse( text, path ) );
}, onProgress, onError );
},
options: {
set convertUpAxis( value ) {
console.warn( 'THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.' );
}
},
parse: function ( text, path ) {
function getElementsByTagName( xml, name ) {
// Non recursive xml.getElementsByTagName() ...
var array = [];
var childNodes = xml.childNodes;
for ( var i = 0, l = childNodes.length; i < l; i ++ ) {
var child = childNodes[ i ];
if ( child.nodeName === name ) {
array.push( child );
}
}
return array;
}
function parseStrings( text ) {
if ( text.length === 0 ) return [];
var parts = text.trim().split( /\s+/ );
var array = new Array( parts.length );
for ( var i = 0, l = parts.length; i < l; i ++ ) {
array[ i ] = parts[ i ];
}
return array;
}
function parseFloats( text ) {
if ( text.length === 0 ) return [];
var parts = text.trim().split( /\s+/ );
var array = new Array( parts.length );
for ( var i = 0, l = parts.length; i < l; i ++ ) {
array[ i ] = parseFloat( parts[ i ] );
}
return array;
}
function parseInts( text ) {
if ( text.length === 0 ) return [];
var parts = text.trim().split( /\s+/ );
var array = new Array( parts.length );
for ( var i = 0, l = parts.length; i < l; i ++ ) {
array[ i ] = parseInt( parts[ i ] );
}
return array;
}
function parseId( text ) {
return text.substring( 1 );
}
function generateId() {
return 'three_default_' + ( count ++ );
}
function isEmpty( object ) {
return Object.keys( object ).length === 0;
}
// asset
function parseAsset( xml ) {
return {
unit: parseAssetUnit( getElementsByTagName( xml, 'unit' )[ 0 ] ),
upAxis: parseAssetUpAxis( getElementsByTagName( xml, 'up_axis' )[ 0 ] )
};
}
function parseAssetUnit( xml ) {
if ( ( xml !== undefined ) && ( xml.hasAttribute( 'meter' ) === true ) ) {
return parseFloat( xml.getAttribute( 'meter' ) );
} else {
return 1; // default 1 meter
}
}
function parseAssetUpAxis( xml ) {
return xml !== undefined ? xml.textContent : 'Y_UP';
}
// library
function parseLibrary( xml, libraryName, nodeName, parser ) {
var library = getElementsByTagName( xml, libraryName )[ 0 ];
if ( library !== undefined ) {
var elements = getElementsByTagName( library, nodeName );
for ( var i = 0; i < elements.length; i ++ ) {
parser( elements[ i ] );
}
}
}
function buildLibrary( data, builder ) {
for ( var name in data ) {
var object = data[ name ];
object.build = builder( data[ name ] );
}
}
// get
function getBuild( data, builder ) {
if ( data.build !== undefined ) return data.build;
data.build = builder( data );
return data.build;
}
// animation
function parseAnimation( xml ) {
var data = {
sources: {},
samplers: {},
channels: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
var id;
switch ( child.nodeName ) {
case 'source':
id = child.getAttribute( 'id' );
data.sources[ id ] = parseSource( child );
break;
case 'sampler':
id = child.getAttribute( 'id' );
data.samplers[ id ] = parseAnimationSampler( child );
break;
case 'channel':
id = child.getAttribute( 'target' );
data.channels[ id ] = parseAnimationChannel( child );
break;
default:
console.log( child );
}
}
library.animations[ xml.getAttribute( 'id' ) ] = data;
}
function parseAnimationSampler( xml ) {
var data = {
inputs: {},
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var id = parseId( child.getAttribute( 'source' ) );
var semantic = child.getAttribute( 'semantic' );
data.inputs[ semantic ] = id;
break;
}
}
return data;
}
function parseAnimationChannel( xml ) {
var data = {};
var target = xml.getAttribute( 'target' );
// parsing SID Addressing Syntax
var parts = target.split( '/' );
var id = parts.shift();
var sid = parts.shift();
// check selection syntax
var arraySyntax = ( sid.indexOf( '(' ) !== - 1 );
var memberSyntax = ( sid.indexOf( '.' ) !== - 1 );
if ( memberSyntax ) {
// member selection access
parts = sid.split( '.' );
sid = parts.shift();
data.member = parts.shift();
} else if ( arraySyntax ) {
// array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
var indices = sid.split( '(' );
sid = indices.shift();
for ( var i = 0; i < indices.length; i ++ ) {
indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) );
}
data.indices = indices;
}
data.id = id;
data.sid = sid;
data.arraySyntax = arraySyntax;
data.memberSyntax = memberSyntax;
data.sampler = parseId( xml.getAttribute( 'source' ) );
return data;
}
function buildAnimation( data ) {
var tracks = [];
var channels = data.channels;
var samplers = data.samplers;
var sources = data.sources;
for ( var target in channels ) {
if ( channels.hasOwnProperty( target ) ) {
var channel = channels[ target ];
var sampler = samplers[ channel.sampler ];
var inputId = sampler.inputs.INPUT;
var outputId = sampler.inputs.OUTPUT;
var inputSource = sources[ inputId ];
var outputSource = sources[ outputId ];
var animation = buildAnimationChannel( channel, inputSource, outputSource );
createKeyframeTracks( animation, tracks );
}
}
return tracks;
}
function getAnimation( id ) {
return getBuild( library.animations[ id ], buildAnimation );
}
function buildAnimationChannel( channel, inputSource, outputSource ) {
var node = library.nodes[ channel.id ];
var object3D = getNode( node.id );
var transform = node.transforms[ channel.sid ];
var defaultMatrix = node.matrix.clone().transpose();
var time, stride;
var i, il, j, jl;
var data = {};
// the collada spec allows the animation of data in various ways.
// depending on the transform type (matrix, translate, rotate, scale), we execute different logic
switch ( transform ) {
case 'matrix':
for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {
time = inputSource.array[ i ];
stride = i * outputSource.stride;
if ( data[ time ] === undefined ) data[ time ] = {};
if ( channel.arraySyntax === true ) {
var value = outputSource.array[ stride ];
var index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
data[ time ][ index ] = value;
} else {
for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {
data[ time ][ j ] = outputSource.array[ stride + j ];
}
}
}
break;
case 'translate':
console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
break;
case 'rotate':
console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
break;
case 'scale':
console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
break;
}
var keyframes = prepareAnimationData( data, defaultMatrix );
var animation = {
name: object3D.uuid,
keyframes: keyframes
};
return animation;
}
function prepareAnimationData( data, defaultMatrix ) {
var keyframes = [];
// transfer data into a sortable array
for ( var time in data ) {
keyframes.push( { time: parseFloat( time ), value: data[ time ] } );
}
// ensure keyframes are sorted by time
keyframes.sort( ascending );
// now we clean up all animation data, so we can use them for keyframe tracks
for ( var i = 0; i < 16; i ++ ) {
transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
}
return keyframes;
// array sort function
function ascending( a, b ) {
return a.time - b.time;
}
}
var position = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
var scale = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
var quaternion = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Quaternion"]();
function createKeyframeTracks( animation, tracks ) {
var keyframes = animation.keyframes;
var name = animation.name;
var times = [];
var positionData = [];
var quaternionData = [];
var scaleData = [];
for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
var keyframe = keyframes[ i ];
var time = keyframe.time;
var value = keyframe.value;
matrix.fromArray( value ).transpose();
matrix.decompose( position, quaternion, scale );
times.push( time );
positionData.push( position.x, position.y, position.z );
quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
scaleData.push( scale.x, scale.y, scale.z );
}
if ( positionData.length > 0 ) tracks.push( new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["VectorKeyframeTrack"]( name + '.position', times, positionData ) );
if ( quaternionData.length > 0 ) tracks.push( new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["QuaternionKeyframeTrack"]( name + '.quaternion', times, quaternionData ) );
if ( scaleData.length > 0 ) tracks.push( new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["VectorKeyframeTrack"]( name + '.scale', times, scaleData ) );
return tracks;
}
function transformAnimationData( keyframes, property, defaultValue ) {
var keyframe;
var empty = true;
var i, l;
// check, if values of a property are missing in our keyframes
for ( i = 0, l = keyframes.length; i < l; i ++ ) {
keyframe = keyframes[ i ];
if ( keyframe.value[ property ] === undefined ) {
keyframe.value[ property ] = null; // mark as missing
} else {
empty = false;
}
}
if ( empty === true ) {
// no values at all, so we set a default value
for ( i = 0, l = keyframes.length; i < l; i ++ ) {
keyframe = keyframes[ i ];
keyframe.value[ property ] = defaultValue;
}
} else {
// filling gaps
createMissingKeyframes( keyframes, property );
}
}
function createMissingKeyframes( keyframes, property ) {
var prev, next;
for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
var keyframe = keyframes[ i ];
if ( keyframe.value[ property ] === null ) {
prev = getPrev( keyframes, i, property );
next = getNext( keyframes, i, property );
if ( prev === null ) {
keyframe.value[ property ] = next.value[ property ];
continue;
}
if ( next === null ) {
keyframe.value[ property ] = prev.value[ property ];
continue;
}
interpolate( keyframe, prev, next, property );
}
}
}
function getPrev( keyframes, i, property ) {
while ( i >= 0 ) {
var keyframe = keyframes[ i ];
if ( keyframe.value[ property ] !== null ) return keyframe;
i --;
}
return null;
}
function getNext( keyframes, i, property ) {
while ( i < keyframes.length ) {
var keyframe = keyframes[ i ];
if ( keyframe.value[ property ] !== null ) return keyframe;
i ++;
}
return null;
}
function interpolate( key, prev, next, property ) {
if ( ( next.time - prev.time ) === 0 ) {
key.value[ property ] = prev.value[ property ];
return;
}
key.value[ property ] = ( ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) ) + prev.value[ property ];
}
// animation clips
function parseAnimationClip( xml ) {
var data = {
name: xml.getAttribute( 'id' ) || 'default',
start: parseFloat( xml.getAttribute( 'start' ) || 0 ),
end: parseFloat( xml.getAttribute( 'end' ) || 0 ),
animations: []
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'instance_animation':
data.animations.push( parseId( child.getAttribute( 'url' ) ) );
break;
}
}
library.clips[ xml.getAttribute( 'id' ) ] = data;
}
function buildAnimationClip( data ) {
var tracks = [];
var name = data.name;
var duration = ( data.end - data.start ) || - 1;
var animations = data.animations;
for ( var i = 0, il = animations.length; i < il; i ++ ) {
var animationTracks = getAnimation( animations[ i ] );
for ( var j = 0, jl = animationTracks.length; j < jl; j ++ ) {
tracks.push( animationTracks[ j ] );
}
}
return new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["AnimationClip"]( name, duration, tracks );
}
function getAnimationClip( id ) {
return getBuild( library.clips[ id ], buildAnimationClip );
}
// controller
function parseController( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'skin':
// there is exactly one skin per controller
data.id = parseId( child.getAttribute( 'source' ) );
data.skin = parseSkin( child );
break;
case 'morph':
data.id = parseId( child.getAttribute( 'source' ) );
console.warn( 'THREE.ColladaLoader: Morph target animation not supported yet.' );
break;
}
}
library.controllers[ xml.getAttribute( 'id' ) ] = data;
}
function parseSkin( xml ) {
var data = {
sources: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'bind_shape_matrix':
data.bindShapeMatrix = parseFloats( child.textContent );
break;
case 'source':
var id = child.getAttribute( 'id' );
data.sources[ id ] = parseSource( child );
break;
case 'joints':
data.joints = parseJoints( child );
break;
case 'vertex_weights':
data.vertexWeights = parseVertexWeights( child );
break;
}
}
return data;
}
function parseJoints( xml ) {
var data = {
inputs: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var semantic = child.getAttribute( 'semantic' );
var id = parseId( child.getAttribute( 'source' ) );
data.inputs[ semantic ] = id;
break;
}
}
return data;
}
function parseVertexWeights( xml ) {
var data = {
inputs: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var semantic = child.getAttribute( 'semantic' );
var id = parseId( child.getAttribute( 'source' ) );
var offset = parseInt( child.getAttribute( 'offset' ) );
data.inputs[ semantic ] = { id: id, offset: offset };
break;
case 'vcount':
data.vcount = parseInts( child.textContent );
break;
case 'v':
data.v = parseInts( child.textContent );
break;
}
}
return data;
}
function buildController( data ) {
var build = {
id: data.id
};
var geometry = library.geometries[ build.id ];
if ( data.skin !== undefined ) {
build.skin = buildSkin( data.skin );
// we enhance the 'sources' property of the corresponding geometry with our skin data
geometry.sources.skinIndices = build.skin.indices;
geometry.sources.skinWeights = build.skin.weights;
}
return build;
}
function buildSkin( data ) {
var BONE_LIMIT = 4;
var build = {
joints: [], // this must be an array to preserve the joint order
indices: {
array: [],
stride: BONE_LIMIT
},
weights: {
array: [],
stride: BONE_LIMIT
}
};
var sources = data.sources;
var vertexWeights = data.vertexWeights;
var vcount = vertexWeights.vcount;
var v = vertexWeights.v;
var jointOffset = vertexWeights.inputs.JOINT.offset;
var weightOffset = vertexWeights.inputs.WEIGHT.offset;
var jointSource = data.sources[ data.joints.inputs.JOINT ];
var inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
var weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
var stride = 0;
var i, j, l;
// procces skin data for each vertex
for ( i = 0, l = vcount.length; i < l; i ++ ) {
var jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
var vertexSkinData = [];
for ( j = 0; j < jointCount; j ++ ) {
var skinIndex = v[ stride + jointOffset ];
var weightId = v[ stride + weightOffset ];
var skinWeight = weights[ weightId ];
vertexSkinData.push( { index: skinIndex, weight: skinWeight } );
stride += 2;
}
// we sort the joints in descending order based on the weights.
// this ensures, we only procced the most important joints of the vertex
vertexSkinData.sort( descending );
// now we provide for each vertex a set of four index and weight values.
// the order of the skin data matches the order of vertices
for ( j = 0; j < BONE_LIMIT; j ++ ) {
var d = vertexSkinData[ j ];
if ( d !== undefined ) {
build.indices.array.push( d.index );
build.weights.array.push( d.weight );
} else {
build.indices.array.push( 0 );
build.weights.array.push( 0 );
}
}
}
// setup bind matrix
if ( data.bindShapeMatrix ) {
build.bindMatrix = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Matrix4"]().fromArray( data.bindShapeMatrix ).transpose();
} else {
build.bindMatrix = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Matrix4"]().identity();
}
// process bones and inverse bind matrix data
for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
var name = jointSource.array[ i ];
var boneInverse = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Matrix4"]().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
build.joints.push( { name: name, boneInverse: boneInverse } );
}
return build;
// array sort function
function descending( a, b ) {
return b.weight - a.weight;
}
}
function getController( id ) {
return getBuild( library.controllers[ id ], buildController );
}
// image
function parseImage( xml ) {
var data = {
init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent
};
library.images[ xml.getAttribute( 'id' ) ] = data;
}
function buildImage( data ) {
if ( data.build !== undefined ) return data.build;
return data.init_from;
}
function getImage( id ) {
var data = library.images[ id ];
if ( data !== undefined ) {
return getBuild( data, buildImage );
}
console.warn( 'THREE.ColladaLoader: Couldn\'t find image with ID:', id );
return null;
}
// effect
function parseEffect( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'profile_COMMON':
data.profile = parseEffectProfileCOMMON( child );
break;
}
}
library.effects[ xml.getAttribute( 'id' ) ] = data;
}
function parseEffectProfileCOMMON( xml ) {
var data = {
surfaces: {},
samplers: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'newparam':
parseEffectNewparam( child, data );
break;
case 'technique':
data.technique = parseEffectTechnique( child );
break;
case 'extra':
data.extra = parseEffectExtra( child );
break;
}
}
return data;
}
function parseEffectNewparam( xml, data ) {
var sid = xml.getAttribute( 'sid' );
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'surface':
data.surfaces[ sid ] = parseEffectSurface( child );
break;
case 'sampler2D':
data.samplers[ sid ] = parseEffectSampler( child );
break;
}
}
}
function parseEffectSurface( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'init_from':
data.init_from = child.textContent;
break;
}
}
return data;
}
function parseEffectSampler( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'source':
data.source = child.textContent;
break;
}
}
return data;
}
function parseEffectTechnique( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'constant':
case 'lambert':
case 'blinn':
case 'phong':
data.type = child.nodeName;
data.parameters = parseEffectParameters( child );
break;
}
}
return data;
}
function parseEffectParameters( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'emission':
case 'diffuse':
case 'specular':
case 'bump':
case 'ambient':
case 'shininess':
case 'transparency':
data[ child.nodeName ] = parseEffectParameter( child );
break;
case 'transparent':
data[ child.nodeName ] = {
opaque: child.getAttribute( 'opaque' ),
data: parseEffectParameter( child )
};
break;
}
}
return data;
}
function parseEffectParameter( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'color':
data[ child.nodeName ] = parseFloats( child.textContent );
break;
case 'float':
data[ child.nodeName ] = parseFloat( child.textContent );
break;
case 'texture':
data[ child.nodeName ] = { id: child.getAttribute( 'texture' ), extra: parseEffectParameterTexture( child ) };
break;
}
}
return data;
}
function parseEffectParameterTexture( xml ) {
var data = {
technique: {}
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'extra':
parseEffectParameterTextureExtra( child, data );
break;
}
}
return data;
}
function parseEffectParameterTextureExtra( xml, data ) {
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'technique':
parseEffectParameterTextureExtraTechnique( child, data );
break;
}
}
}
function parseEffectParameterTextureExtraTechnique( xml, data ) {
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'repeatU':
case 'repeatV':
case 'offsetU':
case 'offsetV':
data.technique[ child.nodeName ] = parseFloat( child.textContent );
break;
case 'wrapU':
case 'wrapV':
// some files have values for wrapU/wrapV which become NaN via parseInt
if ( child.textContent.toUpperCase() === 'TRUE' ) {
data.technique[ child.nodeName ] = 1;
} else if ( child.textContent.toUpperCase() === 'FALSE' ) {
data.technique[ child.nodeName ] = 0;
} else {
data.technique[ child.nodeName ] = parseInt( child.textContent );
}
break;
}
}
}
function parseEffectExtra( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'technique':
data.technique = parseEffectExtraTechnique( child );
break;
}
}
return data;
}
function parseEffectExtraTechnique( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'double_sided':
data[ child.nodeName ] = parseInt( child.textContent );
break;
}
}
return data;
}
function buildEffect( data ) {
return data;
}
function getEffect( id ) {
return getBuild( library.effects[ id ], buildEffect );
}
// material
function parseMaterial( xml ) {
var data = {
name: xml.getAttribute( 'name' )
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'instance_effect':
data.url = parseId( child.getAttribute( 'url' ) );
break;
}
}
library.materials[ xml.getAttribute( 'id' ) ] = data;
}
function getTextureLoader( image ) {
var loader;
var extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
extension = extension.toLowerCase();
switch ( extension ) {
case 'tga':
loader = tgaLoader;
break;
default:
loader = textureLoader;
}
return loader;
}
function buildMaterial( data ) {
var effect = getEffect( data.url );
var technique = effect.profile.technique;
var extra = effect.profile.extra;
var material;
switch ( technique.type ) {
case 'phong':
case 'blinn':
material = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["MeshPhongMaterial"]();
break;
case 'lambert':
material = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["MeshLambertMaterial"]();
break;
default:
material = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["MeshBasicMaterial"]();
break;
}
material.name = data.name || '';
function getTexture( textureObject ) {
var sampler = effect.profile.samplers[ textureObject.id ];
var image = null;
// get image
if ( sampler !== undefined ) {
var surface = effect.profile.surfaces[ sampler.source ];
image = getImage( surface.init_from );
} else {
console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
image = getImage( textureObject.id );
}
// create texture if image is avaiable
if ( image !== null ) {
var loader = getTextureLoader( image );
if ( loader !== undefined ) {
var texture = loader.load( image );
var extra = textureObject.extra;
if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
var technique = extra.technique;
texture.wrapS = technique.wrapU ? _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["RepeatWrapping"] : _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["ClampToEdgeWrapping"];
texture.wrapT = technique.wrapV ? _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["RepeatWrapping"] : _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["ClampToEdgeWrapping"];
texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
} else {
texture.wrapS = _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["RepeatWrapping"];
texture.wrapT = _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["RepeatWrapping"];
}
return texture;
} else {
console.warn( 'THREE.ColladaLoader: Loader for texture %s not found.', image );
return null;
}
} else {
console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
return null;
}
}
var parameters = technique.parameters;
for ( var key in parameters ) {
var parameter = parameters[ key ];
switch ( key ) {
case 'diffuse':
if ( parameter.color ) material.color.fromArray( parameter.color );
if ( parameter.texture ) material.map = getTexture( parameter.texture );
break;
case 'specular':
if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
break;
case 'bump':
if ( parameter.texture ) material.normalMap = getTexture( parameter.texture );
break;
case 'ambient':
if ( parameter.texture ) material.lightMap = getTexture( parameter.texture );
break;
case 'shininess':
if ( parameter.float && material.shininess ) material.shininess = parameter.float;
break;
case 'emission':
if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture );
break;
}
}
//
var transparent = parameters[ 'transparent' ];
var transparency = parameters[ 'transparency' ];
// <transparency> does not exist but <transparent>
if ( transparency === undefined && transparent ) {
transparency = {
float: 1
};
}
// <transparent> does not exist but <transparency>
if ( transparent === undefined && transparency ) {
transparent = {
opaque: 'A_ONE',
data: {
color: [ 1, 1, 1, 1 ]
} };
}
if ( transparent && transparency ) {
// handle case if a texture exists but no color
if ( transparent.data.texture ) {
// we do not set an alpha map (see #13792)
material.transparent = true;
} else {
var color = transparent.data.color;
switch ( transparent.opaque ) {
case 'A_ONE':
material.opacity = color[ 3 ] * transparency.float;
break;
case 'RGB_ZERO':
material.opacity = 1 - ( color[ 0 ] * transparency.float );
break;
case 'A_ZERO':
material.opacity = 1 - ( color[ 3 ] * transparency.float );
break;
case 'RGB_ONE':
material.opacity = color[ 0 ] * transparency.float;
break;
default:
console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
}
if ( material.opacity < 1 ) material.transparent = true;
}
}
//
if ( extra !== undefined && extra.technique !== undefined && extra.technique.double_sided === 1 ) {
material.side = _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["DoubleSide"];
}
return material;
}
function getMaterial( id ) {
return getBuild( library.materials[ id ], buildMaterial );
}
// camera
function parseCamera( xml ) {
var data = {
name: xml.getAttribute( 'name' )
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'optics':
data.optics = parseCameraOptics( child );
break;
}
}
library.cameras[ xml.getAttribute( 'id' ) ] = data;
}
function parseCameraOptics( xml ) {
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
switch ( child.nodeName ) {
case 'technique_common':
return parseCameraTechnique( child );
}
}
return {};
}
function parseCameraTechnique( xml ) {
var data = {};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
switch ( child.nodeName ) {
case 'perspective':
case 'orthographic':
data.technique = child.nodeName;
data.parameters = parseCameraParameters( child );
break;
}
}
return data;
}
function parseCameraParameters( xml ) {
var data = {};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
switch ( child.nodeName ) {
case 'xfov':
case 'yfov':
case 'xmag':
case 'ymag':
case 'znear':
case 'zfar':
case 'aspect_ratio':
data[ child.nodeName ] = parseFloat( child.textContent );
break;
}
}
return data;
}
function buildCamera( data ) {
var camera;
switch ( data.optics.technique ) {
case 'perspective':
camera = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["PerspectiveCamera"](
data.optics.parameters.yfov,
data.optics.parameters.aspect_ratio,
data.optics.parameters.znear,
data.optics.parameters.zfar
);
break;
case 'orthographic':
var ymag = data.optics.parameters.ymag;
var xmag = data.optics.parameters.xmag;
var aspectRatio = data.optics.parameters.aspect_ratio;
xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;
xmag *= 0.5;
ymag *= 0.5;
camera = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["OrthographicCamera"](
- xmag, xmag, ymag, - ymag, // left, right, top, bottom
data.optics.parameters.znear,
data.optics.parameters.zfar
);
break;
default:
camera = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["PerspectiveCamera"]();
break;
}
camera.name = data.name || '';
return camera;
}
function getCamera( id ) {
var data = library.cameras[ id ];
if ( data !== undefined ) {
return getBuild( data, buildCamera );
}
console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
return null;
}
// light
function parseLight( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'technique_common':
data = parseLightTechnique( child );
break;
}
}
library.lights[ xml.getAttribute( 'id' ) ] = data;
}
function parseLightTechnique( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'directional':
case 'point':
case 'spot':
case 'ambient':
data.technique = child.nodeName;
data.parameters = parseLightParameters( child );
}
}
return data;
}
function parseLightParameters( xml ) {
var data = {};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'color':
var array = parseFloats( child.textContent );
data.color = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Color"]().fromArray( array );
break;
case 'falloff_angle':
data.falloffAngle = parseFloat( child.textContent );
break;
case 'quadratic_attenuation':
var f = parseFloat( child.textContent );
data.distance = f ? Math.sqrt( 1 / f ) : 0;
break;
}
}
return data;
}
function buildLight( data ) {
var light;
switch ( data.technique ) {
case 'directional':
light = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["DirectionalLight"]();
break;
case 'point':
light = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["PointLight"]();
break;
case 'spot':
light = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["SpotLight"]();
break;
case 'ambient':
light = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["AmbientLight"]();
break;
}
if ( data.parameters.color ) light.color.copy( data.parameters.color );
if ( data.parameters.distance ) light.distance = data.parameters.distance;
return light;
}
function getLight( id ) {
var data = library.lights[ id ];
if ( data !== undefined ) {
return getBuild( data, buildLight );
}
console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
return null;
}
// geometry
function parseGeometry( xml ) {
var data = {
name: xml.getAttribute( 'name' ),
sources: {},
vertices: {},
primitives: []
};
var mesh = getElementsByTagName( xml, 'mesh' )[ 0 ];
// the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
if ( mesh === undefined ) return;
for ( var i = 0; i < mesh.childNodes.length; i ++ ) {
var child = mesh.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
var id = child.getAttribute( 'id' );
switch ( child.nodeName ) {
case 'source':
data.sources[ id ] = parseSource( child );
break;
case 'vertices':
// data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
data.vertices = parseGeometryVertices( child );
break;
case 'polygons':
console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
break;
case 'lines':
case 'linestrips':
case 'polylist':
case 'triangles':
data.primitives.push( parseGeometryPrimitive( child ) );
break;
default:
console.log( child );
}
}
library.geometries[ xml.getAttribute( 'id' ) ] = data;
}
function parseSource( xml ) {
var data = {
array: [],
stride: 3
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'float_array':
data.array = parseFloats( child.textContent );
break;
case 'Name_array':
data.array = parseStrings( child.textContent );
break;
case 'technique_common':
var accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
if ( accessor !== undefined ) {
data.stride = parseInt( accessor.getAttribute( 'stride' ) );
}
break;
}
}
return data;
}
function parseGeometryVertices( xml ) {
var data = {};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
}
return data;
}
function parseGeometryPrimitive( xml ) {
var primitive = {
type: xml.nodeName,
material: xml.getAttribute( 'material' ),
count: parseInt( xml.getAttribute( 'count' ) ),
inputs: {},
stride: 0,
hasUV: false
};
for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var id = parseId( child.getAttribute( 'source' ) );
var semantic = child.getAttribute( 'semantic' );
var offset = parseInt( child.getAttribute( 'offset' ) );
var set = parseInt( child.getAttribute( 'set' ) );
var inputname = ( set > 0 ? semantic + set : semantic );
primitive.inputs[ inputname ] = { id: id, offset: offset };
primitive.stride = Math.max( primitive.stride, offset + 1 );
if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
break;
case 'vcount':
primitive.vcount = parseInts( child.textContent );
break;
case 'p':
primitive.p = parseInts( child.textContent );
break;
}
}
return primitive;
}
function groupPrimitives( primitives ) {
var build = {};
for ( var i = 0; i < primitives.length; i ++ ) {
var primitive = primitives[ i ];
if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
build[ primitive.type ].push( primitive );
}
return build;
}
function checkUVCoordinates( primitives ) {
var count = 0;
for ( var i = 0, l = primitives.length; i < l; i ++ ) {
var primitive = primitives[ i ];
if ( primitive.hasUV === true ) {
count ++;
}
}
if ( count > 0 && count < primitives.length ) {
primitives.uvsNeedsFix = true;
}
}
function buildGeometry( data ) {
var build = {};
var sources = data.sources;
var vertices = data.vertices;
var primitives = data.primitives;
if ( primitives.length === 0 ) return {};
// our goal is to create one buffer geometry for a single type of primitives
// first, we group all primitives by their type
var groupedPrimitives = groupPrimitives( primitives );
for ( var type in groupedPrimitives ) {
var primitiveType = groupedPrimitives[ type ];
// second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
checkUVCoordinates( primitiveType );
// third, create a buffer geometry for each type of primitives
build[ type ] = buildGeometryType( primitiveType, sources, vertices );
}
return build;
}
function buildGeometryType( primitives, sources, vertices ) {
var build = {};
var position = { array: [], stride: 0 };
var normal = { array: [], stride: 0 };
var uv = { array: [], stride: 0 };
var uv2 = { array: [], stride: 0 };
var color = { array: [], stride: 0 };
var skinIndex = { array: [], stride: 4 };
var skinWeight = { array: [], stride: 4 };
var geometry = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["BufferGeometry"]();
var materialKeys = [];
var start = 0;
for ( var p = 0; p < primitives.length; p ++ ) {
var primitive = primitives[ p ];
var inputs = primitive.inputs;
// groups
var count = 0;
switch ( primitive.type ) {
case 'lines':
case 'linestrips':
count = primitive.count * 2;
break;
case 'triangles':
count = primitive.count * 3;
break;
case 'polylist':
for ( var g = 0; g < primitive.count; g ++ ) {
var vc = primitive.vcount[ g ];
switch ( vc ) {
case 3:
count += 3; // single triangle
break;
case 4:
count += 6; // quad, subdivided into two triangles
break;
default:
count += ( vc - 2 ) * 3; // polylist with more than four vertices
break;
}
}
break;
default:
console.warn( 'THREE.ColladaLoader: Unknow primitive type:', primitive.type );
}
geometry.addGroup( start, count, p );
start += count;
// material
if ( primitive.material ) {
materialKeys.push( primitive.material );
}
// geometry data
for ( var name in inputs ) {
var input = inputs[ name ];
switch ( name ) {
case 'VERTEX':
for ( var key in vertices ) {
var id = vertices[ key ];
switch ( key ) {
case 'POSITION':
var prevLength = position.array.length;
buildGeometryData( primitive, sources[ id ], input.offset, position.array );
position.stride = sources[ id ].stride;
if ( sources.skinWeights && sources.skinIndices ) {
buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
}
// see #3803
if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
var count = ( position.array.length - prevLength ) / position.stride;
for ( var i = 0; i < count; i ++ ) {
// fill missing uv coordinates
uv.array.push( 0, 0 );
}
}
break;
case 'NORMAL':
buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
normal.stride = sources[ id ].stride;
break;
case 'COLOR':
buildGeometryData( primitive, sources[ id ], input.offset, color.array );
color.stride = sources[ id ].stride;
break;
case 'TEXCOORD':
buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
uv.stride = sources[ id ].stride;
break;
case 'TEXCOORD1':
buildGeometryData( primitive, sources[ id ], input.offset, uv2.array );
uv.stride = sources[ id ].stride;
break;
default:
console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
}
}
break;
case 'NORMAL':
buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
normal.stride = sources[ input.id ].stride;
break;
case 'COLOR':
buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
color.stride = sources[ input.id ].stride;
break;
case 'TEXCOORD':
buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
uv.stride = sources[ input.id ].stride;
break;
case 'TEXCOORD1':
buildGeometryData( primitive, sources[ input.id ], input.offset, uv2.array );
uv2.stride = sources[ input.id ].stride;
break;
}
}
}
// build geometry
if ( position.array.length > 0 ) geometry.setAttribute( 'position', new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Float32BufferAttribute"]( position.array, position.stride ) );
if ( normal.array.length > 0 ) geometry.setAttribute( 'normal', new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Float32BufferAttribute"]( normal.array, normal.stride ) );
if ( color.array.length > 0 ) geometry.setAttribute( 'color', new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Float32BufferAttribute"]( color.array, color.stride ) );
if ( uv.array.length > 0 ) geometry.setAttribute( 'uv', new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Float32BufferAttribute"]( uv.array, uv.stride ) );
if ( uv2.array.length > 0 ) geometry.setAttribute( 'uv2', new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Float32BufferAttribute"]( uv2.array, uv2.stride ) );
if ( skinIndex.array.length > 0 ) geometry.setAttribute( 'skinIndex', new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Float32BufferAttribute"]( skinIndex.array, skinIndex.stride ) );
if ( skinWeight.array.length > 0 ) geometry.setAttribute( 'skinWeight', new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Float32BufferAttribute"]( skinWeight.array, skinWeight.stride ) );
build.data = geometry;
build.type = primitives[ 0 ].type;
build.materialKeys = materialKeys;
return build;
}
function buildGeometryData( primitive, source, offset, array ) {
var indices = primitive.p;
var stride = primitive.stride;
var vcount = primitive.vcount;
function pushVector( i ) {
var index = indices[ i + offset ] * sourceStride;
var length = index + sourceStride;
for ( ; index < length; index ++ ) {
array.push( sourceArray[ index ] );
}
}
var sourceArray = source.array;
var sourceStride = source.stride;
if ( primitive.vcount !== undefined ) {
var index = 0;
for ( var i = 0, l = vcount.length; i < l; i ++ ) {
var count = vcount[ i ];
if ( count === 4 ) {
var a = index + stride * 0;
var b = index + stride * 1;
var c = index + stride * 2;
var d = index + stride * 3;
pushVector( a ); pushVector( b ); pushVector( d );
pushVector( b ); pushVector( c ); pushVector( d );
} else if ( count === 3 ) {
var a = index + stride * 0;
var b = index + stride * 1;
var c = index + stride * 2;
pushVector( a ); pushVector( b ); pushVector( c );
} else if ( count > 4 ) {
for ( var k = 1, kl = ( count - 2 ); k <= kl; k ++ ) {
var a = index + stride * 0;
var b = index + stride * k;
var c = index + stride * ( k + 1 );
pushVector( a ); pushVector( b ); pushVector( c );
}
}
index += stride * count;
}
} else {
for ( var i = 0, l = indices.length; i < l; i += stride ) {
pushVector( i );
}
}
}
function getGeometry( id ) {
return getBuild( library.geometries[ id ], buildGeometry );
}
// kinematics
function parseKinematicsModel( xml ) {
var data = {
name: xml.getAttribute( 'name' ) || '',
joints: {},
links: []
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'technique_common':
parseKinematicsTechniqueCommon( child, data );
break;
}
}
library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
}
function buildKinematicsModel( data ) {
if ( data.build !== undefined ) return data.build;
return data;
}
function getKinematicsModel( id ) {
return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
}
function parseKinematicsTechniqueCommon( xml, data ) {
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'joint':
data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
break;
case 'link':
data.links.push( parseKinematicsLink( child ) );
break;
}
}
}
function parseKinematicsJoint( xml ) {
var data;
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'prismatic':
case 'revolute':
data = parseKinematicsJointParameter( child );
break;
}
}
return data;
}
function parseKinematicsJointParameter( xml, data ) {
var data = {
sid: xml.getAttribute( 'sid' ),
name: xml.getAttribute( 'name' ) || '',
axis: new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Vector3"](),
limits: {
min: 0,
max: 0
},
type: xml.nodeName,
static: false,
zeroPosition: 0,
middlePosition: 0
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'axis':
var array = parseFloats( child.textContent );
data.axis.fromArray( array );
break;
case 'limits':
var max = child.getElementsByTagName( 'max' )[ 0 ];
var min = child.getElementsByTagName( 'min' )[ 0 ];
data.limits.max = parseFloat( max.textContent );
data.limits.min = parseFloat( min.textContent );
break;
}
}
// if min is equal to or greater than max, consider the joint static
if ( data.limits.min >= data.limits.max ) {
data.static = true;
}
// calculate middle position
data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
return data;
}
function parseKinematicsLink( xml ) {
var data = {
sid: xml.getAttribute( 'sid' ),
name: xml.getAttribute( 'name' ) || '',
attachments: [],
transforms: []
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'attachment_full':
data.attachments.push( parseKinematicsAttachment( child ) );
break;
case 'matrix':
case 'translate':
case 'rotate':
data.transforms.push( parseKinematicsTransform( child ) );
break;
}
}
return data;
}
function parseKinematicsAttachment( xml ) {
var data = {
joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
transforms: [],
links: []
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'link':
data.links.push( parseKinematicsLink( child ) );
break;
case 'matrix':
case 'translate':
case 'rotate':
data.transforms.push( parseKinematicsTransform( child ) );
break;
}
}
return data;
}
function parseKinematicsTransform( xml ) {
var data = {
type: xml.nodeName
};
var array = parseFloats( xml.textContent );
switch ( data.type ) {
case 'matrix':
data.obj = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Matrix4"]();
data.obj.fromArray( array ).transpose();
break;
case 'translate':
data.obj = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
data.obj.fromArray( array );
break;
case 'rotate':
data.obj = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
data.obj.fromArray( array );
data.angle = _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["MathUtils"].degToRad( array[ 3 ] );
break;
}
return data;
}
// physics
function parsePhysicsModel( xml ) {
var data = {
name: xml.getAttribute( 'name' ) || '',
rigidBodies: {}
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'rigid_body':
data.rigidBodies[ child.getAttribute( 'name' ) ] = {};
parsePhysicsRigidBody( child, data.rigidBodies[ child.getAttribute( 'name' ) ] );
break;
}
}
library.physicsModels[ xml.getAttribute( 'id' ) ] = data;
}
function parsePhysicsRigidBody( xml, data ) {
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'technique_common':
parsePhysicsTechniqueCommon( child, data );
break;
}
}
}
function parsePhysicsTechniqueCommon( xml, data ) {
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'inertia':
data.inertia = parseFloats( child.textContent );
break;
case 'mass':
data.mass = parseFloats( child.textContent )[ 0 ];
break;
}
}
}
// scene
function parseKinematicsScene( xml ) {
var data = {
bindJointAxis: []
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'bind_joint_axis':
data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
break;
}
}
library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
}
function parseKinematicsBindJointAxis( xml ) {
var data = {
target: xml.getAttribute( 'target' ).split( '/' ).pop()
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'axis':
var param = child.getElementsByTagName( 'param' )[ 0 ];
data.axis = param.textContent;
var tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
break;
}
}
return data;
}
function buildKinematicsScene( data ) {
if ( data.build !== undefined ) return data.build;
return data;
}
function getKinematicsScene( id ) {
return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
}
function setupKinematics() {
var kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
var kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
var visualSceneId = Object.keys( library.visualScenes )[ 0 ];
if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
var kinematicsModel = getKinematicsModel( kinematicsModelId );
var kinematicsScene = getKinematicsScene( kinematicsSceneId );
var visualScene = getVisualScene( visualSceneId );
var bindJointAxis = kinematicsScene.bindJointAxis;
var jointMap = {};
for ( var i = 0, l = bindJointAxis.length; i < l; i ++ ) {
var axis = bindJointAxis[ i ];
// the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
var targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
if ( targetElement ) {
// get the parent of the transform element
var parentVisualElement = targetElement.parentElement;
// connect the joint of the kinematics model with the element in the visual scene
connect( axis.jointIndex, parentVisualElement );
}
}
function connect( jointIndex, visualElement ) {
var visualElementName = visualElement.getAttribute( 'name' );
var joint = kinematicsModel.joints[ jointIndex ];
visualScene.traverse( function ( object ) {
if ( object.name === visualElementName ) {
jointMap[ jointIndex ] = {
object: object,
transforms: buildTransformList( visualElement ),
joint: joint,
position: joint.zeroPosition
};
}
} );
}
var m0 = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Matrix4"]();
kinematics = {
joints: kinematicsModel && kinematicsModel.joints,
getJointValue: function ( jointIndex ) {
var jointData = jointMap[ jointIndex ];
if ( jointData ) {
return jointData.position;
} else {
console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
}
},
setJointValue: function ( jointIndex, value ) {
var jointData = jointMap[ jointIndex ];
if ( jointData ) {
var joint = jointData.joint;
if ( value > joint.limits.max || value < joint.limits.min ) {
console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
} else if ( joint.static ) {
console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
} else {
var object = jointData.object;
var axis = joint.axis;
var transforms = jointData.transforms;
matrix.identity();
// each update, we have to apply all transforms in the correct order
for ( var i = 0; i < transforms.length; i ++ ) {
var transform = transforms[ i ];
// if there is a connection of the transform node with a joint, apply the joint value
if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
switch ( joint.type ) {
case 'revolute':
matrix.multiply( m0.makeRotationAxis( axis, _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["MathUtils"].degToRad( value ) ) );
break;
case 'prismatic':
matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
break;
default:
console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
break;
}
} else {
switch ( transform.type ) {
case 'matrix':
matrix.multiply( transform.obj );
break;
case 'translate':
matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
break;
case 'scale':
matrix.scale( transform.obj );
break;
case 'rotate':
matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
break;
}
}
}
object.matrix.copy( matrix );
object.matrix.decompose( object.position, object.quaternion, object.scale );
jointMap[ jointIndex ].position = value;
}
} else {
console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
}
}
};
}
function buildTransformList( node ) {
var transforms = [];
var xml = collada.querySelector( '[id="' + node.id + '"]' );
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'matrix':
var array = parseFloats( child.textContent );
var matrix = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Matrix4"]().fromArray( array ).transpose();
transforms.push( {
sid: child.getAttribute( 'sid' ),
type: child.nodeName,
obj: matrix
} );
break;
case 'translate':
case 'scale':
var array = parseFloats( child.textContent );
var vector = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Vector3"]().fromArray( array );
transforms.push( {
sid: child.getAttribute( 'sid' ),
type: child.nodeName,
obj: vector
} );
break;
case 'rotate':
var array = parseFloats( child.textContent );
var vector = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Vector3"]().fromArray( array );
var angle = _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["MathUtils"].degToRad( array[ 3 ] );
transforms.push( {
sid: child.getAttribute( 'sid' ),
type: child.nodeName,
obj: vector,
angle: angle
} );
break;
}
}
return transforms;
}
// nodes
function prepareNodes( xml ) {
var elements = xml.getElementsByTagName( 'node' );
// ensure all node elements have id attributes
for ( var i = 0; i < elements.length; i ++ ) {
var element = elements[ i ];
if ( element.hasAttribute( 'id' ) === false ) {
element.setAttribute( 'id', generateId() );
}
}
}
var matrix = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Matrix4"]();
var vector = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
function parseNode( xml ) {
var data = {
name: xml.getAttribute( 'name' ) || '',
type: xml.getAttribute( 'type' ),
id: xml.getAttribute( 'id' ),
sid: xml.getAttribute( 'sid' ),
matrix: new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Matrix4"](),
nodes: [],
instanceCameras: [],
instanceControllers: [],
instanceLights: [],
instanceGeometries: [],
instanceNodes: [],
transforms: {}
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'node':
data.nodes.push( child.getAttribute( 'id' ) );
parseNode( child );
break;
case 'instance_camera':
data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
break;
case 'instance_controller':
data.instanceControllers.push( parseNodeInstance( child ) );
break;
case 'instance_light':
data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
break;
case 'instance_geometry':
data.instanceGeometries.push( parseNodeInstance( child ) );
break;
case 'instance_node':
data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
break;
case 'matrix':
var array = parseFloats( child.textContent );
data.matrix.multiply( matrix.fromArray( array ).transpose() );
data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
break;
case 'translate':
var array = parseFloats( child.textContent );
vector.fromArray( array );
data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
break;
case 'rotate':
var array = parseFloats( child.textContent );
var angle = _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["MathUtils"].degToRad( array[ 3 ] );
data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
break;
case 'scale':
var array = parseFloats( child.textContent );
data.matrix.scale( vector.fromArray( array ) );
data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
break;
case 'extra':
break;
default:
console.log( child );
}
}
if ( hasNode( data.id ) ) {
console.warn( 'THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id );
} else {
library.nodes[ data.id ] = data;
}
return data;
}
function parseNodeInstance( xml ) {
var data = {
id: parseId( xml.getAttribute( 'url' ) ),
materials: {},
skeletons: []
};
for ( var i = 0; i < xml.childNodes.length; i ++ ) {
var child = xml.childNodes[ i ];
switch ( child.nodeName ) {
case 'bind_material':
var instances = child.getElementsByTagName( 'instance_material' );
for ( var j = 0; j < instances.length; j ++ ) {
var instance = instances[ j ];
var symbol = instance.getAttribute( 'symbol' );
var target = instance.getAttribute( 'target' );
data.materials[ symbol ] = parseId( target );
}
break;
case 'skeleton':
data.skeletons.push( parseId( child.textContent ) );
break;
default:
break;
}
}
return data;
}
function buildSkeleton( skeletons, joints ) {
var boneData = [];
var sortedBoneData = [];
var i, j, data;
// a skeleton can have multiple root bones. collada expresses this
// situtation with multiple "skeleton" tags per controller instance
for ( i = 0; i < skeletons.length; i ++ ) {
var skeleton = skeletons[ i ];
var root;
if ( hasNode( skeleton ) ) {
root = getNode( skeleton );
buildBoneHierarchy( root, joints, boneData );
} else if ( hasVisualScene( skeleton ) ) {
// handle case where the skeleton refers to the visual scene (#13335)
var visualScene = library.visualScenes[ skeleton ];
var children = visualScene.children;
for ( var j = 0; j < children.length; j ++ ) {
var child = children[ j ];
if ( child.type === 'JOINT' ) {
var root = getNode( child.id );
buildBoneHierarchy( root, joints, boneData );
}
}
} else {
console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
}
}
// sort bone data (the order is defined in the corresponding controller)
for ( i = 0; i < joints.length; i ++ ) {
for ( j = 0; j < boneData.length; j ++ ) {
data = boneData[ j ];
if ( data.bone.name === joints[ i ].name ) {
sortedBoneData[ i ] = data;
data.processed = true;
break;
}
}
}
// add unprocessed bone data at the end of the list
for ( i = 0; i < boneData.length; i ++ ) {
data = boneData[ i ];
if ( data.processed === false ) {
sortedBoneData.push( data );
data.processed = true;
}
}
// setup arrays for skeleton creation
var bones = [];
var boneInverses = [];
for ( i = 0; i < sortedBoneData.length; i ++ ) {
data = sortedBoneData[ i ];
bones.push( data.bone );
boneInverses.push( data.boneInverse );
}
return new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Skeleton"]( bones, boneInverses );
}
function buildBoneHierarchy( root, joints, boneData ) {
// setup bone data from visual scene
root.traverse( function ( object ) {
if ( object.isBone === true ) {
var boneInverse;
// retrieve the boneInverse from the controller data
for ( var i = 0; i < joints.length; i ++ ) {
var joint = joints[ i ];
if ( joint.name === object.name ) {
boneInverse = joint.boneInverse;
break;
}
}
if ( boneInverse === undefined ) {
// Unfortunately, there can be joints in the visual scene that are not part of the
// corresponding controller. In this case, we have to create a dummy boneInverse matrix
// for the respective bone. This bone won't affect any vertices, because there are no skin indices
// and weights defined for it. But we still have to add the bone to the sorted bone list in order to
// ensure a correct animation of the model.
boneInverse = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Matrix4"]();
}
boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );
}
} );
}
function buildNode( data ) {
var objects = [];
var matrix = data.matrix;
var nodes = data.nodes;
var type = data.type;
var instanceCameras = data.instanceCameras;
var instanceControllers = data.instanceControllers;
var instanceLights = data.instanceLights;
var instanceGeometries = data.instanceGeometries;
var instanceNodes = data.instanceNodes;
// nodes
for ( var i = 0, l = nodes.length; i < l; i ++ ) {
objects.push( getNode( nodes[ i ] ) );
}
// instance cameras
for ( var i = 0, l = instanceCameras.length; i < l; i ++ ) {
var instanceCamera = getCamera( instanceCameras[ i ] );
if ( instanceCamera !== null ) {
objects.push( instanceCamera.clone() );
}
}
// instance controllers
for ( var i = 0, l = instanceControllers.length; i < l; i ++ ) {
var instance = instanceControllers[ i ];
var controller = getController( instance.id );
var geometries = getGeometry( controller.id );
var newObjects = buildObjects( geometries, instance.materials );
var skeletons = instance.skeletons;
var joints = controller.skin.joints;
var skeleton = buildSkeleton( skeletons, joints );
for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
var object = newObjects[ j ];
if ( object.isSkinnedMesh ) {
object.bind( skeleton, controller.skin.bindMatrix );
object.normalizeSkinWeights();
}
objects.push( object );
}
}
// instance lights
for ( var i = 0, l = instanceLights.length; i < l; i ++ ) {
var instanceLight = getLight( instanceLights[ i ] );
if ( instanceLight !== null ) {
objects.push( instanceLight.clone() );
}
}
// instance geometries
for ( var i = 0, l = instanceGeometries.length; i < l; i ++ ) {
var instance = instanceGeometries[ i ];
// a single geometry instance in collada can lead to multiple object3Ds.
// this is the case when primitives are combined like triangles and lines
var geometries = getGeometry( instance.id );
var newObjects = buildObjects( geometries, instance.materials );
for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
objects.push( newObjects[ j ] );
}
}
// instance nodes
for ( var i = 0, l = instanceNodes.length; i < l; i ++ ) {
objects.push( getNode( instanceNodes[ i ] ).clone() );
}
var object;
if ( nodes.length === 0 && objects.length === 1 ) {
object = objects[ 0 ];
} else {
object = ( type === 'JOINT' ) ? new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Bone"]() : new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Group"]();
for ( var i = 0; i < objects.length; i ++ ) {
object.add( objects[ i ] );
}
}
if ( object.name === '' ) {
object.name = ( type === 'JOINT' ) ? data.sid : data.name;
}
object.matrix.copy( matrix );
object.matrix.decompose( object.position, object.quaternion, object.scale );
return object;
}
var fallbackMaterial = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["MeshBasicMaterial"]( { color: 0xff00ff } );
function resolveMaterialBinding( keys, instanceMaterials ) {
var materials = [];
for ( var i = 0, l = keys.length; i < l; i ++ ) {
var id = instanceMaterials[ keys[ i ] ];
if ( id === undefined ) {
console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
materials.push( fallbackMaterial );
} else {
materials.push( getMaterial( id ) );
}
}
return materials;
}
function buildObjects( geometries, instanceMaterials ) {
var objects = [];
for ( var type in geometries ) {
var geometry = geometries[ type ];
var materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
// handle case if no materials are defined
if ( materials.length === 0 ) {
if ( type === 'lines' || type === 'linestrips' ) {
materials.push( new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["LineBasicMaterial"]() );
} else {
materials.push( new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["MeshPhongMaterial"]() );
}
}
// regard skinning
var skinning = ( geometry.data.attributes.skinIndex !== undefined );
if ( skinning ) {
for ( var i = 0, l = materials.length; i < l; i ++ ) {
materials[ i ].skinning = true;
}
}
// choose between a single or multi materials (material array)
var material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
// now create a specific 3D object
var object;
switch ( type ) {
case 'lines':
object = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["LineSegments"]( geometry.data, material );
break;
case 'linestrips':
object = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Line"]( geometry.data, material );
break;
case 'triangles':
case 'polylist':
if ( skinning ) {
object = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["SkinnedMesh"]( geometry.data, material );
} else {
object = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Mesh"]( geometry.data, material );
}
break;
}
objects.push( object );
}
return objects;
}
function hasNode( id ) {
return library.nodes[ id ] !== undefined;
}
function getNode( id ) {
return getBuild( library.nodes[ id ], buildNode );
}
// visual scenes
function parseVisualScene( xml ) {
var data = {
name: xml.getAttribute( 'name' ),
children: []
};
prepareNodes( xml );
var elements = getElementsByTagName( xml, 'node' );
for ( var i = 0; i < elements.length; i ++ ) {
data.children.push( parseNode( elements[ i ] ) );
}
library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
}
function buildVisualScene( data ) {
var group = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Group"]();
group.name = data.name;
var children = data.children;
for ( var i = 0; i < children.length; i ++ ) {
var child = children[ i ];
group.add( getNode( child.id ) );
}
return group;
}
function hasVisualScene( id ) {
return library.visualScenes[ id ] !== undefined;
}
function getVisualScene( id ) {
return getBuild( library.visualScenes[ id ], buildVisualScene );
}
// scenes
function parseScene( xml ) {
var instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
}
function setupAnimations() {
var clips = library.clips;
if ( isEmpty( clips ) === true ) {
if ( isEmpty( library.animations ) === false ) {
// if there are animations but no clips, we create a default clip for playback
var tracks = [];
for ( var id in library.animations ) {
var animationTracks = getAnimation( id );
for ( var i = 0, l = animationTracks.length; i < l; i ++ ) {
tracks.push( animationTracks[ i ] );
}
}
animations.push( new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["AnimationClip"]( 'default', - 1, tracks ) );
}
} else {
for ( var id in clips ) {
animations.push( getAnimationClip( id ) );
}
}
}
// convert the parser error element into text with each child elements text
// separated by new lines.
function parserErrorToText( parserError ) {
var result = '';
var stack = [ parserError ];
while ( stack.length ) {
var node = stack.shift();
if ( node.nodeType === Node.TEXT_NODE ) {
result += node.textContent;
} else {
result += '\n';
stack.push.apply( stack, node.childNodes );
}
}
return result.trim();
}
if ( text.length === 0 ) {
return { scene: new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Scene"]() };
}
var xml = new DOMParser().parseFromString( text, 'application/xml' );
var collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
var parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ];
if ( parserError !== undefined ) {
// Chrome will return parser error with a div in it
var errorElement = getElementsByTagName( parserError, 'div' )[ 0 ];
var errorText;
if ( errorElement ) {
errorText = errorElement.textContent;
} else {
errorText = parserErrorToText( parserError );
}
console.error( 'THREE.ColladaLoader: Failed to parse collada file.\n', errorText );
return null;
}
// metadata
var version = collada.getAttribute( 'version' );
console.log( 'THREE.ColladaLoader: File version', version );
var asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
var textureLoader = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["TextureLoader"]( this.manager );
textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
var tgaLoader;
if ( _loaders_TGALoader_js__WEBPACK_IMPORTED_MODULE_1__["TGALoader"] ) {
tgaLoader = new _loaders_TGALoader_js__WEBPACK_IMPORTED_MODULE_1__["TGALoader"]( this.manager );
tgaLoader.setPath( this.resourcePath || path );
}
//
var animations = [];
var kinematics = {};
var count = 0;
//
var library = {
animations: {},
clips: {},
controllers: {},
images: {},
effects: {},
materials: {},
cameras: {},
lights: {},
geometries: {},
nodes: {},
visualScenes: {},
kinematicsModels: {},
physicsModels: {},
kinematicsScenes: {}
};
parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
parseLibrary( collada, 'library_controllers', 'controller', parseController );
parseLibrary( collada, 'library_images', 'image', parseImage );
parseLibrary( collada, 'library_effects', 'effect', parseEffect );
parseLibrary( collada, 'library_materials', 'material', parseMaterial );
parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
parseLibrary( collada, 'library_lights', 'light', parseLight );
parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
parseLibrary( collada, 'library_nodes', 'node', parseNode );
parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
parseLibrary( collada, 'library_physics_models', 'physics_model', parsePhysicsModel );
parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
buildLibrary( library.animations, buildAnimation );
buildLibrary( library.clips, buildAnimationClip );
buildLibrary( library.controllers, buildController );
buildLibrary( library.images, buildImage );
buildLibrary( library.effects, buildEffect );
buildLibrary( library.materials, buildMaterial );
buildLibrary( library.cameras, buildCamera );
buildLibrary( library.lights, buildLight );
buildLibrary( library.geometries, buildGeometry );
buildLibrary( library.visualScenes, buildVisualScene );
setupAnimations();
setupKinematics();
var scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
if ( asset.upAxis === 'Z_UP' ) {
scene.quaternion.setFromEuler( new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Euler"]( - Math.PI / 2, 0, 0 ) );
}
scene.scale.multiplyScalar( asset.unit );
return {
animations: animations,
kinematics: kinematics,
library: library,
scene: scene
};
}
} );
/***/ }),
/***/ "./node_modules/three/examples/jsm/loaders/TGALoader.js":
/*!**************************************************************!*\
!*** ./node_modules/three/examples/jsm/loaders/TGALoader.js ***!
\**************************************************************/
/*! exports provided: TGALoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TGALoader", function() { return TGALoader; });
/* harmony import */ var _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../build/three.module.js */ "./node_modules/three/build/three.module.js");
/**
* @author Daosheng Mu / https://github.com/DaoshengMu/
* @author mrdoob / http://mrdoob.com/
* @author takahirox / https://github.com/takahirox/
*/
var TGALoader = function ( manager ) {
_build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Loader"].call( this, manager );
};
TGALoader.prototype = Object.assign( Object.create( _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Loader"].prototype ), {
constructor: TGALoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var texture = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["Texture"]();
var loader = new _build_three_module_js__WEBPACK_IMPORTED_MODULE_0__["FileLoader"]( this.manager );
loader.setResponseType( 'arraybuffer' );
loader.setPath( this.path );
loader.load( url, function ( buffer ) {
texture.image = scope.parse( buffer );
texture.needsUpdate = true;
if ( onLoad !== undefined ) {
onLoad( texture );
}
}, onProgress, onError );
return texture;
},
parse: function ( buffer ) {
// reference from vthibault, https://github.com/vthibault/roBrowser/blob/master/src/Loaders/Targa.js
function tgaCheckHeader( header ) {
switch ( header.image_type ) {
// check indexed type
case TGA_TYPE_INDEXED:
case TGA_TYPE_RLE_INDEXED:
if ( header.colormap_length > 256 || header.colormap_size !== 24 || header.colormap_type !== 1 ) {
console.error( 'THREE.TGALoader: Invalid type colormap data for indexed type.' );
}
break;
// check colormap type
case TGA_TYPE_RGB:
case TGA_TYPE_GREY:
case TGA_TYPE_RLE_RGB:
case TGA_TYPE_RLE_GREY:
if ( header.colormap_type ) {
console.error( 'THREE.TGALoader: Invalid type colormap data for colormap type.' );
}
break;
// What the need of a file without data ?
case TGA_TYPE_NO_DATA:
console.error( 'THREE.TGALoader: No data.' );
// Invalid type ?
default:
console.error( 'THREE.TGALoader: Invalid type "%s".', header.image_type );
}
// check image width and height
if ( header.width <= 0 || header.height <= 0 ) {
console.error( 'THREE.TGALoader: Invalid image size.' );
}
// check image pixel size
if ( header.pixel_size !== 8 && header.pixel_size !== 16 &&
header.pixel_size !== 24 && header.pixel_size !== 32 ) {
console.error( 'THREE.TGALoader: Invalid pixel size "%s".', header.pixel_size );
}
}
// parse tga image buffer
function tgaParse( use_rle, use_pal, header, offset, data ) {
var pixel_data,
pixel_size,
pixel_total,
palettes;
pixel_size = header.pixel_size >> 3;
pixel_total = header.width * header.height * pixel_size;
// read palettes
if ( use_pal ) {
palettes = data.subarray( offset, offset += header.colormap_length * ( header.colormap_size >> 3 ) );
}
// read RLE
if ( use_rle ) {
pixel_data = new Uint8Array( pixel_total );
var c, count, i;
var shift = 0;
var pixels = new Uint8Array( pixel_size );
while ( shift < pixel_total ) {
c = data[ offset ++ ];
count = ( c & 0x7f ) + 1;
// RLE pixels
if ( c & 0x80 ) {
// bind pixel tmp array
for ( i = 0; i < pixel_size; ++ i ) {
pixels[ i ] = data[ offset ++ ];
}
// copy pixel array
for ( i = 0; i < count; ++ i ) {
pixel_data.set( pixels, shift + i * pixel_size );
}
shift += pixel_size * count;
} else {
// raw pixels
count *= pixel_size;
for ( i = 0; i < count; ++ i ) {
pixel_data[ shift + i ] = data[ offset ++ ];
}
shift += count;
}
}
} else {
// raw pixels
pixel_data = data.subarray(
offset, offset += ( use_pal ? header.width * header.height : pixel_total )
);
}
return {
pixel_data: pixel_data,
palettes: palettes
};
}
function tgaGetImageData8bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image, palettes ) {
var colormap = palettes;
var color, i = 0, x, y;
var width = header.width;
for ( y = y_start; y !== y_end; y += y_step ) {
for ( x = x_start; x !== x_end; x += x_step, i ++ ) {
color = image[ i ];
imageData[ ( x + width * y ) * 4 + 3 ] = 255;
imageData[ ( x + width * y ) * 4 + 2 ] = colormap[ ( color * 3 ) + 0 ];
imageData[ ( x + width * y ) * 4 + 1 ] = colormap[ ( color * 3 ) + 1 ];
imageData[ ( x + width * y ) * 4 + 0 ] = colormap[ ( color * 3 ) + 2 ];
}
}
return imageData;
}
function tgaGetImageData16bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) {
var color, i = 0, x, y;
var width = header.width;
for ( y = y_start; y !== y_end; y += y_step ) {
for ( x = x_start; x !== x_end; x += x_step, i += 2 ) {
color = image[ i + 0 ] + ( image[ i + 1 ] << 8 ); // Inversed ?
imageData[ ( x + width * y ) * 4 + 0 ] = ( color & 0x7C00 ) >> 7;
imageData[ ( x + width * y ) * 4 + 1 ] = ( color & 0x03E0 ) >> 2;
imageData[ ( x + width * y ) * 4 + 2 ] = ( color & 0x001F ) >> 3;
imageData[ ( x + width * y ) * 4 + 3 ] = ( color & 0x8000 ) ? 0 : 255;
}
}
return imageData;
}
function tgaGetImageData24bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) {
var i = 0, x, y;
var width = header.width;
for ( y = y_start; y !== y_end; y += y_step ) {
for ( x = x_start; x !== x_end; x += x_step, i += 3 ) {
imageData[ ( x + width * y ) * 4 + 3 ] = 255;
imageData[ ( x + width * y ) * 4 + 2 ] = image[ i + 0 ];
imageData[ ( x + width * y ) * 4 + 1 ] = image[ i + 1 ];
imageData[ ( x + width * y ) * 4 + 0 ] = image[ i + 2 ];
}
}
return imageData;
}
function tgaGetImageData32bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) {
var i = 0, x, y;
var width = header.width;
for ( y = y_start; y !== y_end; y += y_step ) {
for ( x = x_start; x !== x_end; x += x_step, i += 4 ) {
imageData[ ( x + width * y ) * 4 + 2 ] = image[ i + 0 ];
imageData[ ( x + width * y ) * 4 + 1 ] = image[ i + 1 ];
imageData[ ( x + width * y ) * 4 + 0 ] = image[ i + 2 ];
imageData[ ( x + width * y ) * 4 + 3 ] = image[ i + 3 ];
}
}
return imageData;
}
function tgaGetImageDataGrey8bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) {
var color, i = 0, x, y;
var width = header.width;
for ( y = y_start; y !== y_end; y += y_step ) {
for ( x = x_start; x !== x_end; x += x_step, i ++ ) {
color = image[ i ];
imageData[ ( x + width * y ) * 4 + 0 ] = color;
imageData[ ( x + width * y ) * 4 + 1 ] = color;
imageData[ ( x + width * y ) * 4 + 2 ] = color;
imageData[ ( x + width * y ) * 4 + 3 ] = 255;
}
}
return imageData;
}
function tgaGetImageDataGrey16bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) {
var i = 0, x, y;
var width = header.width;
for ( y = y_start; y !== y_end; y += y_step ) {
for ( x = x_start; x !== x_end; x += x_step, i += 2 ) {
imageData[ ( x + width * y ) * 4 + 0 ] = image[ i + 0 ];
imageData[ ( x + width * y ) * 4 + 1 ] = image[ i + 0 ];
imageData[ ( x + width * y ) * 4 + 2 ] = image[ i + 0 ];
imageData[ ( x + width * y ) * 4 + 3 ] = image[ i + 1 ];
}
}
return imageData;
}
function getTgaRGBA( data, width, height, image, palette ) {
var x_start,
y_start,
x_step,
y_step,
x_end,
y_end;
switch ( ( header.flags & TGA_ORIGIN_MASK ) >> TGA_ORIGIN_SHIFT ) {
default:
case TGA_ORIGIN_UL:
x_start = 0;
x_step = 1;
x_end = width;
y_start = 0;
y_step = 1;
y_end = height;
break;
case TGA_ORIGIN_BL:
x_start = 0;
x_step = 1;
x_end = width;
y_start = height - 1;
y_step = - 1;
y_end = - 1;
break;
case TGA_ORIGIN_UR:
x_start = width - 1;
x_step = - 1;
x_end = - 1;
y_start = 0;
y_step = 1;
y_end = height;
break;
case TGA_ORIGIN_BR:
x_start = width - 1;
x_step = - 1;
x_end = - 1;
y_start = height - 1;
y_step = - 1;
y_end = - 1;
break;
}
if ( use_grey ) {
switch ( header.pixel_size ) {
case 8:
tgaGetImageDataGrey8bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image );
break;
case 16:
tgaGetImageDataGrey16bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image );
break;
default:
console.error( 'THREE.TGALoader: Format not supported.' );
break;
}
} else {
switch ( header.pixel_size ) {
case 8:
tgaGetImageData8bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image, palette );
break;
case 16:
tgaGetImageData16bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image );
break;
case 24:
tgaGetImageData24bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image );
break;
case 32:
tgaGetImageData32bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image );
break;
default:
console.error( 'THREE.TGALoader: Format not supported.' );
break;
}
}
// Load image data according to specific method
// var func = 'tgaGetImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
// func(data, y_start, y_step, y_end, x_start, x_step, x_end, width, image, palette );
return data;
}
// TGA constants
var TGA_TYPE_NO_DATA = 0,
TGA_TYPE_INDEXED = 1,
TGA_TYPE_RGB = 2,
TGA_TYPE_GREY = 3,
TGA_TYPE_RLE_INDEXED = 9,
TGA_TYPE_RLE_RGB = 10,
TGA_TYPE_RLE_GREY = 11,
TGA_ORIGIN_MASK = 0x30,
TGA_ORIGIN_SHIFT = 0x04,
TGA_ORIGIN_BL = 0x00,
TGA_ORIGIN_BR = 0x01,
TGA_ORIGIN_UL = 0x02,
TGA_ORIGIN_UR = 0x03;
if ( buffer.length < 19 ) console.error( 'THREE.TGALoader: Not enough data to contain header.' );
var content = new Uint8Array( buffer ),
offset = 0,
header = {
id_length: content[ offset ++ ],
colormap_type: content[ offset ++ ],
image_type: content[ offset ++ ],
colormap_index: content[ offset ++ ] | content[ offset ++ ] << 8,
colormap_length: content[ offset ++ ] | content[ offset ++ ] << 8,
colormap_size: content[ offset ++ ],
origin: [
content[ offset ++ ] | content[ offset ++ ] << 8,
content[ offset ++ ] | content[ offset ++ ] << 8
],
width: content[ offset ++ ] | content[ offset ++ ] << 8,
height: content[ offset ++ ] | content[ offset ++ ] << 8,
pixel_size: content[ offset ++ ],
flags: content[ offset ++ ]
};
// check tga if it is valid format
tgaCheckHeader( header );
if ( header.id_length + offset > buffer.length ) {
console.error( 'THREE.TGALoader: No data.' );
}
// skip the needn't data
offset += header.id_length;
// get targa information about RLE compression and palette
var use_rle = false,
use_pal = false,
use_grey = false;
switch ( header.image_type ) {
case TGA_TYPE_RLE_INDEXED:
use_rle = true;
use_pal = true;
break;
case TGA_TYPE_INDEXED:
use_pal = true;
break;
case TGA_TYPE_RLE_RGB:
use_rle = true;
break;
case TGA_TYPE_RGB:
break;
case TGA_TYPE_RLE_GREY:
use_rle = true;
use_grey = true;
break;
case TGA_TYPE_GREY:
use_grey = true;
break;
}
//
var useOffscreen = typeof OffscreenCanvas !== 'undefined';
var canvas = useOffscreen ? new OffscreenCanvas( header.width, header.height ) : document.createElement( 'canvas' );
canvas.width = header.width;
canvas.height = header.height;
var context = canvas.getContext( '2d' );
var imageData = context.createImageData( header.width, header.height );
var result = tgaParse( use_rle, use_pal, header, offset, content );
getTgaRGBA( imageData.data, header.width, header.height, result.pixel_data, result.palettes );
context.putImageData( imageData, 0, 0 );
return useOffscreen ? canvas.transferToImageBitmap() : canvas;
}
} );
/***/ })
}]);
//# sourceMappingURL=vendor-es2015.js.map