@angular/platform-browser
Version:
Angular - library for using Angular in a web browser
1,261 lines (1,247 loc) • 82.2 kB
JavaScript
/**
* @license Angular v13.0.3
* (c) 2010-2021 Google LLC. https://angular.io/
* License: MIT
*/
import { ɵDomAdapter, ɵsetRootDomAdapter, ɵparseCookieValue, ɵgetDOM, DOCUMENT, ɵPLATFORM_BROWSER_ID, XhrFactory, CommonModule } from '@angular/common';
export { ɵgetDOM } from '@angular/common';
import * as i0 from '@angular/core';
import { InjectionToken, ApplicationInitStatus, APP_INITIALIZER, Injector, setTestabilityGetter, ɵglobal, Injectable, Inject, ViewEncapsulation, APP_ID, RendererStyleFlags2, ErrorHandler, ɵsetDocument, PLATFORM_ID, PLATFORM_INITIALIZER, createPlatformFactory, platformCore, ɵINJECTOR_SCOPE, NgZone, RendererFactory2, Testability, ApplicationModule, NgModule, Optional, SkipSelf, ɵɵinject, ApplicationRef, ɵConsole, forwardRef, SecurityContext, ɵallowSanitizationBypassAndThrow, ɵunwrapSafeValue, ɵgetSanitizationBypassType, ɵ_sanitizeUrl, ɵ_sanitizeHtml, ɵbypassSanitizationTrustHtml, ɵbypassSanitizationTrustStyle, ɵbypassSanitizationTrustScript, ɵbypassSanitizationTrustUrl, ɵbypassSanitizationTrustResourceUrl, Version } from '@angular/core';
/**
* @license
* Copyright Google LLC 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 DOM operations in any browser environment.
*
* @security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
*/
class GenericBrowserDomAdapter extends ɵDomAdapter {
constructor() {
super(...arguments);
this.supportsDOMEvents = true;
}
}
/**
* @license
* Copyright Google LLC 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 `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 {
static makeCurrent() {
ɵsetRootDomAdapter(new BrowserDomAdapter());
}
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 () => {
el.removeEventListener(evt, listener, false);
};
}
dispatchEvent(el, evt) {
el.dispatchEvent(evt);
}
remove(node) {
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
createElement(tagName, doc) {
doc = doc || this.getDefaultDocument();
return doc.createElement(tagName);
}
createHtmlDocument() {
return document.implementation.createHTMLDocument('fakeTitle');
}
getDefaultDocument() {
return document;
}
isElementNode(node) {
return node.nodeType === Node.ELEMENT_NODE;
}
isShadowRoot(node) {
return node instanceof DocumentFragment;
}
/** @deprecated No longer being used in Ivy code. To be removed in version 14. */
getGlobalEventTarget(doc, target) {
if (target === 'window') {
return window;
}
if (target === 'document') {
return doc;
}
if (target === 'body') {
return doc.body;
}
return null;
}
getBaseHref(doc) {
const href = getBaseElementHref();
return href == null ? null : relativePath(href);
}
resetBaseElement() {
baseElement = null;
}
getUserAgent() {
return window.navigator.userAgent;
}
getCookie(name) {
return ɵparseCookieValue(document.cookie, name);
}
}
let baseElement = null;
function getBaseElementHref() {
baseElement = baseElement || document.querySelector('base');
return baseElement ? baseElement.getAttribute('href') : null;
}
// based on urlUtils.js in AngularJS 1
let urlParsingNode;
function relativePath(url) {
urlParsingNode = urlParsingNode || document.createElement('a');
urlParsingNode.setAttribute('href', url);
const pathName = urlParsingNode.pathname;
return pathName.charAt(0) === '/' ? pathName : `/${pathName}`;
}
/**
* @license
* Copyright Google LLC 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 id that identifies a particular application being bootstrapped, that should
* match across the client/server boundary.
*/
const TRANSITION_ID = new InjectionToken('TRANSITION_ID');
function appInitializerFactory(transitionId, document, injector) {
return () => {
// Wait for all application initializers to be completed before removing the styles set by
// the server.
injector.get(ApplicationInitStatus).donePromise.then(() => {
const dom = ɵgetDOM();
const styles = document.querySelectorAll(`style[ng-transition="${transitionId}"]`);
for (let i = 0; i < styles.length; i++) {
dom.remove(styles[i]);
}
});
};
}
const SERVER_TRANSITION_PROVIDERS = [
{
provide: APP_INITIALIZER,
useFactory: appInitializerFactory,
deps: [TRANSITION_ID, DOCUMENT, Injector],
multi: true
},
];
/**
* @license
* Copyright Google LLC 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
*/
class BrowserGetTestability {
static init() {
setTestabilityGetter(new BrowserGetTestability());
}
addToWindow(registry) {
ɵglobal['getAngularTestability'] = (elem, findInAncestors = true) => {
const testability = registry.findTestabilityInTree(elem, findInAncestors);
if (testability == null) {
throw new Error('Could not find testability for element.');
}
return testability;
};
ɵglobal['getAllAngularTestabilities'] = () => registry.getAllTestabilities();
ɵglobal['getAllAngularRootElements'] = () => registry.getAllRootElements();
const whenAllStable = (callback /** TODO #9100 */) => {
const testabilities = ɵglobal['getAllAngularTestabilities']();
let count = testabilities.length;
let didWork = false;
const decrement = function (didWork_ /** TODO #9100 */) {
didWork = didWork || didWork_;
count--;
if (count == 0) {
callback(didWork);
}
};
testabilities.forEach(function (testability /** TODO #9100 */) {
testability.whenStable(decrement);
});
};
if (!ɵglobal['frameworkStabilizers']) {
ɵglobal['frameworkStabilizers'] = [];
}
ɵglobal['frameworkStabilizers'].push(whenAllStable);
}
findTestabilityInTree(registry, elem, findInAncestors) {
if (elem == null) {
return null;
}
const t = registry.getTestability(elem);
if (t != null) {
return t;
}
else if (!findInAncestors) {
return null;
}
if (ɵgetDOM().isShadowRoot(elem)) {
return this.findTestabilityInTree(registry, elem.host, true);
}
return this.findTestabilityInTree(registry, elem.parentElement, true);
}
}
/**
* A factory for `HttpXhrBackend` that uses the `XMLHttpRequest` browser API.
*/
class BrowserXhr {
build() {
return new XMLHttpRequest();
}
}
BrowserXhr.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: BrowserXhr, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
BrowserXhr.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: BrowserXhr });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: BrowserXhr, decorators: [{
type: Injectable
}] });
/**
* @license
* Copyright Google LLC 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 injection token for the event-manager plug-in service.
*
* @publicApi
*/
const EVENT_MANAGER_PLUGINS = new 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.
*/
constructor(plugins, _zone) {
this._zone = _zone;
this._eventNameToPlugin = new Map();
plugins.forEach(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.
* @returns A callback function that can be used to remove the handler.
*/
addEventListener(element, eventName, handler) {
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.
* @returns A callback function that can be used to remove the handler.
* @deprecated No longer being used in Ivy code. To be removed in version 14.
*/
addGlobalEventListener(target, eventName, handler) {
const plugin = this._findPluginFor(eventName);
return plugin.addGlobalEventListener(target, eventName, handler);
}
/**
* Retrieves the compilation zone in which event listeners are registered.
*/
getZone() {
return this._zone;
}
/** @internal */
_findPluginFor(eventName) {
const plugin = this._eventNameToPlugin.get(eventName);
if (plugin) {
return plugin;
}
const plugins = this._plugins;
for (let i = 0; i < plugins.length; i++) {
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 = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: EventManager, deps: [{ token: EVENT_MANAGER_PLUGINS }, { token: i0.NgZone }], target: i0.ɵɵFactoryTarget.Injectable });
EventManager.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: EventManager });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: EventManager, decorators: [{
type: Injectable
}], ctorParameters: function () {
return [{ type: undefined, decorators: [{
type: Inject,
args: [EVENT_MANAGER_PLUGINS]
}] }, { type: i0.NgZone }];
} });
class EventManagerPlugin {
constructor(_doc) {
this._doc = _doc;
}
addGlobalEventListener(element, eventName, handler) {
const target = ɵgetDOM().getGlobalEventTarget(this._doc, element);
if (!target) {
throw new Error(`Unsupported event target ${target} for event ${eventName}`);
}
return this.addEventListener(target, eventName, handler);
}
}
/**
* @license
* Copyright Google LLC 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
*/
class SharedStylesHost {
constructor() {
/** @internal */
this._stylesSet = new Set();
}
addStyles(styles) {
const additions = new Set();
styles.forEach(style => {
if (!this._stylesSet.has(style)) {
this._stylesSet.add(style);
additions.add(style);
}
});
this.onStylesAdded(additions);
}
onStylesAdded(additions) { }
getAllStyles() {
return Array.from(this._stylesSet);
}
}
SharedStylesHost.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: SharedStylesHost, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
SharedStylesHost.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: SharedStylesHost });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: SharedStylesHost, decorators: [{
type: Injectable
}] });
class DomSharedStylesHost extends SharedStylesHost {
constructor(_doc) {
super();
this._doc = _doc;
// Maps all registered host nodes to a list of style nodes that have been added to the host node.
this._hostNodes = new Map();
this._hostNodes.set(_doc.head, []);
}
_addStylesToHost(styles, host, styleNodes) {
styles.forEach((style) => {
const styleEl = this._doc.createElement('style');
styleEl.textContent = style;
styleNodes.push(host.appendChild(styleEl));
});
}
addHost(hostNode) {
const styleNodes = [];
this._addStylesToHost(this._stylesSet, hostNode, styleNodes);
this._hostNodes.set(hostNode, styleNodes);
}
removeHost(hostNode) {
const styleNodes = this._hostNodes.get(hostNode);
if (styleNodes) {
styleNodes.forEach(removeStyle);
}
this._hostNodes.delete(hostNode);
}
onStylesAdded(additions) {
this._hostNodes.forEach((styleNodes, hostNode) => {
this._addStylesToHost(additions, hostNode, styleNodes);
});
}
ngOnDestroy() {
this._hostNodes.forEach(styleNodes => styleNodes.forEach(removeStyle));
}
}
DomSharedStylesHost.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: DomSharedStylesHost, deps: [{ token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable });
DomSharedStylesHost.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: DomSharedStylesHost });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: DomSharedStylesHost, decorators: [{
type: Injectable
}], ctorParameters: function () {
return [{ type: undefined, decorators: [{
type: Inject,
args: [DOCUMENT]
}] }];
} });
function removeStyle(styleNode) {
ɵgetDOM().remove(styleNode);
}
/**
* @license
* Copyright Google LLC 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 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/',
};
const COMPONENT_REGEX = /%COMP%/g;
const NG_DEV_MODE = typeof ngDevMode === 'undefined' || !!ngDevMode;
const COMPONENT_VARIABLE = '%COMP%';
const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
function shimContentAttribute(componentShortId) {
return CONTENT_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
function shimHostAttribute(componentShortId) {
return HOST_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
function flattenStyles(compId, styles, target) {
for (let i = 0; i < styles.length; i++) {
let style = styles[i];
if (Array.isArray(style)) {
flattenStyles(compId, style, target);
}
else {
style = style.replace(COMPONENT_REGEX, compId);
target.push(style);
}
}
return target;
}
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 (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;
}
const allowDefaultBehavior = eventHandler(event);
if (allowDefaultBehavior === false) {
// TODO(tbosch): move preventDefault into event plugins...
event.preventDefault();
event.returnValue = false;
}
return undefined;
};
}
let hasLoggedNativeEncapsulationWarning = false;
class DomRendererFactory2 {
constructor(eventManager, sharedStylesHost, appId) {
this.eventManager = eventManager;
this.sharedStylesHost = sharedStylesHost;
this.appId = appId;
this.rendererByCompId = new Map();
this.defaultRenderer = new DefaultDomRenderer2(eventManager);
}
createRenderer(element, type) {
if (!element || !type) {
return this.defaultRenderer;
}
switch (type.encapsulation) {
case ViewEncapsulation.Emulated: {
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);
}
renderer.applyToHost(element);
return renderer;
}
// @ts-ignore TODO: Remove as part of FW-2290. TS complains about us dealing with an enum
// value that is not known (but previously was the value for ViewEncapsulation.Native)
case 1:
case ViewEncapsulation.ShadowDom:
// TODO(FW-2290): remove the `case 1:` fallback logic and the warning in v12.
if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
// @ts-ignore TODO: Remove as part of FW-2290. TS complains about us dealing with an
// enum value that is not known (but previously was the value for
// ViewEncapsulation.Native)
!hasLoggedNativeEncapsulationWarning && type.encapsulation === 1) {
hasLoggedNativeEncapsulationWarning = true;
console.warn('ViewEncapsulation.Native is no longer supported. Falling back to ViewEncapsulation.ShadowDom. The fallback will be removed in v12.');
}
return new ShadowDomRenderer(this.eventManager, this.sharedStylesHost, element, type);
default: {
if (!this.rendererByCompId.has(type.id)) {
const styles = flattenStyles(type.id, type.styles, []);
this.sharedStylesHost.addStyles(styles);
this.rendererByCompId.set(type.id, this.defaultRenderer);
}
return this.defaultRenderer;
}
}
}
begin() { }
end() { }
}
DomRendererFactory2.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: DomRendererFactory2, deps: [{ token: EventManager }, { token: DomSharedStylesHost }, { token: APP_ID }], target: i0.ɵɵFactoryTarget.Injectable });
DomRendererFactory2.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: DomRendererFactory2 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: DomRendererFactory2, decorators: [{
type: Injectable
}], ctorParameters: function () {
return [{ type: EventManager }, { type: DomSharedStylesHost }, { type: undefined, decorators: [{
type: Inject,
args: [APP_ID]
}] }];
} });
class DefaultDomRenderer2 {
constructor(eventManager) {
this.eventManager = eventManager;
this.data = Object.create(null);
this.destroyNode = null;
}
destroy() { }
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);
}
createComment(value) {
return document.createComment(value);
}
createText(value) {
return document.createTextNode(value);
}
appendChild(parent, newChild) {
parent.appendChild(newChild);
}
insertBefore(parent, newChild, refChild) {
if (parent) {
parent.insertBefore(newChild, refChild);
}
}
removeChild(parent, oldChild) {
if (parent) {
parent.removeChild(oldChild);
}
}
selectRootElement(selectorOrNode, preserveContent) {
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;
}
parentNode(node) {
return node.parentNode;
}
nextSibling(node) {
return node.nextSibling;
}
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.
const namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.setAttributeNS(namespaceUri, name, value);
}
else {
el.setAttribute(name, value);
}
}
else {
el.setAttribute(name, value);
}
}
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.
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);
}
}
addClass(el, name) {
el.classList.add(name);
}
removeClass(el, name) {
el.classList.remove(name);
}
setStyle(el, style, value, flags) {
if (flags & (RendererStyleFlags2.DashCase | RendererStyleFlags2.Important)) {
el.style.setProperty(style, value, flags & RendererStyleFlags2.Important ? 'important' : '');
}
else {
el.style[style] = value;
}
}
removeStyle(el, style, flags) {
if (flags & RendererStyleFlags2.DashCase) {
el.style.removeProperty(style);
}
else {
// IE requires '' instead of null
// see https://github.com/angular/angular/issues/7916
el.style[style] = '';
}
}
setProperty(el, name, value) {
NG_DEV_MODE && checkNoSyntheticProp(name, 'property');
el[name] = value;
}
setValue(node, value) {
node.nodeValue = value;
}
listen(target, event, callback) {
NG_DEV_MODE && checkNoSyntheticProp(event, 'listener');
if (typeof target === 'string') {
return this.eventManager.addGlobalEventListener(target, event, decoratePreventDefault(callback));
}
return this.eventManager.addEventListener(target, event, decoratePreventDefault(callback));
}
}
const AT_CHARCODE = (() => '@'.charCodeAt(0))();
function checkNoSyntheticProp(name, nameKind) {
if (name.charCodeAt(0) === AT_CHARCODE) {
throw new Error(`Unexpected synthetic ${nameKind} ${name} found. Please make sure that:
- Either \`BrowserAnimationsModule\` or \`NoopAnimationsModule\` are imported in your application.
- There is corresponding configuration for the animation named \`${name}\` defined in the \`animations\` field of the \`@Component\` decorator (see https://angular.io/api/core/Component#animations).`);
}
}
class EmulatedEncapsulationDomRenderer2 extends DefaultDomRenderer2 {
constructor(eventManager, sharedStylesHost, component, appId) {
super(eventManager);
this.component = component;
const styles = flattenStyles(appId + '-' + component.id, component.styles, []);
sharedStylesHost.addStyles(styles);
this.contentAttr = shimContentAttribute(appId + '-' + component.id);
this.hostAttr = shimHostAttribute(appId + '-' + component.id);
}
applyToHost(element) {
super.setAttribute(element, this.hostAttr, '');
}
createElement(parent, name) {
const el = super.createElement(parent, name);
super.setAttribute(el, this.contentAttr, '');
return el;
}
}
class ShadowDomRenderer extends DefaultDomRenderer2 {
constructor(eventManager, sharedStylesHost, hostEl, component) {
super(eventManager);
this.sharedStylesHost = sharedStylesHost;
this.hostEl = hostEl;
this.shadowRoot = hostEl.attachShadow({ mode: 'open' });
this.sharedStylesHost.addHost(this.shadowRoot);
const styles = flattenStyles(component.id, component.styles, []);
for (let i = 0; i < styles.length; i++) {
const styleEl = document.createElement('style');
styleEl.textContent = styles[i];
this.shadowRoot.appendChild(styleEl);
}
}
nodeOrShadowRoot(node) {
return node === this.hostEl ? this.shadowRoot : node;
}
destroy() {
this.sharedStylesHost.removeHost(this.shadowRoot);
}
appendChild(parent, newChild) {
return super.appendChild(this.nodeOrShadowRoot(parent), newChild);
}
insertBefore(parent, newChild, refChild) {
return super.insertBefore(this.nodeOrShadowRoot(parent), newChild, refChild);
}
removeChild(parent, oldChild) {
return super.removeChild(this.nodeOrShadowRoot(parent), oldChild);
}
parentNode(node) {
return this.nodeOrShadowRoot(super.parentNode(this.nodeOrShadowRoot(node)));
}
}
/**
* @license
* Copyright Google LLC 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
*/
class DomEventsPlugin extends EventManagerPlugin {
constructor(doc) {
super(doc);
}
// This plugin should come last in the list of plugins, because it accepts all
// events.
supports(eventName) {
return true;
}
addEventListener(element, eventName, handler) {
element.addEventListener(eventName, handler, false);
return () => this.removeEventListener(element, eventName, handler);
}
removeEventListener(target, eventName, callback) {
return target.removeEventListener(eventName, callback);
}
}
DomEventsPlugin.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: DomEventsPlugin, deps: [{ token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable });
DomEventsPlugin.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: DomEventsPlugin });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: DomEventsPlugin, decorators: [{
type: Injectable
}], ctorParameters: function () {
return [{ type: undefined, decorators: [{
type: Inject,
args: [DOCUMENT]
}] }];
} });
/**
* @license
* Copyright Google LLC 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
*/
/**
* Defines supported modifiers for key events.
*/
const MODIFIER_KEYS = ['alt', 'control', 'meta', 'shift'];
const DOM_KEY_LOCATION_NUMPAD = 3;
// Map to convert some key or keyIdentifier values to what will be returned by getEventKey
const _keyMap = {
// The following values are here for cross-browser compatibility and to match the W3C standard
// cf https://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 ...
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'
};
/**
* Retrieves modifiers from key-event objects.
*/
const MODIFIER_KEY_GETTERS = {
'alt': (event) => event.altKey,
'control': (event) => event.ctrlKey,
'meta': (event) => event.metaKey,
'shift': (event) => event.shiftKey
};
/**
* @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.
* @returns The key event that was registered.
*/
addEventListener(element, eventName, handler) {
const parsedEvent = KeyEventsPlugin.parseEventName(eventName);
const outsideHandler = KeyEventsPlugin.eventCallback(parsedEvent['fullKey'], handler, this.manager.getZone());
return this.manager.getZone().runOutsideAngular(() => {
return ɵgetDOM().onAndCancel(element, parsedEvent['domEventName'], outsideHandler);
});
}
static parseEventName(eventName) {
const parts = eventName.toLowerCase().split('.');
const domEventName = parts.shift();
if ((parts.length === 0) || !(domEventName === 'keydown' || domEventName === 'keyup')) {
return null;
}
const key = KeyEventsPlugin._normalizeKey(parts.pop());
let fullKey = '';
MODIFIER_KEYS.forEach(modifierName => {
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;
}
// NOTE: Please don't rewrite this as so, as it will break JSCompiler property renaming.
// The code must remain in the `result['domEventName']` form.
// return {domEventName, fullKey};
const result = {};
result['domEventName'] = domEventName;
result['fullKey'] = fullKey;
return result;
}
static getEventFullKey(event) {
let fullKey = '';
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(modifierName => {
if (modifierName != key) {
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.
* @returns A callback function.
*/
static eventCallback(fullKey, handler, zone) {
return (event /** TODO #9100 */) => {
if (KeyEventsPlugin.getEventFullKey(event) === fullKey) {
zone.runGuarded(() => handler(event));
}
};
}
/** @internal */
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 = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: KeyEventsPlugin, deps: [{ token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable });
KeyEventsPlugin.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: KeyEventsPlugin });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: KeyEventsPlugin, decorators: [{
type: Injectable
}], ctorParameters: function () {
return [{ type: undefined, decorators: [{
type: Inject,
args: [DOCUMENT]
}] }];
} });
function getEventKey(event) {
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
// https://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 = _chromeNumKeyPadMap[key];
}
}
}
return _keyMap[key] || key;
}
/**
* @license
* Copyright Google LLC 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 initDomAdapter() {
BrowserDomAdapter.makeCurrent();
BrowserGetTestability.init();
}
function errorHandler() {
return new ErrorHandler();
}
function _document() {
// Tell ivy about the global document
ɵsetDocument(document);
return document;
}
const INTERNAL_BROWSER_PLATFORM_PROVIDERS = [
{ provide: PLATFORM_ID, useValue: ɵPLATFORM_BROWSER_ID },
{ provide: PLATFORM_INITIALIZER, useValue: initDomAdapter, multi: true },
{ provide: DOCUMENT, useFactory: _document, deps: [] },
];
/**
* A factory function that returns a `PlatformRef` instance associated with browser service
* providers.
*
* @publicApi
*/
const platformBrowser = createPlatformFactory(platformCore, 'browser', INTERNAL_BROWSER_PLATFORM_PROVIDERS);
const BROWSER_MODULE_PROVIDERS = [
{ provide: ɵINJECTOR_SCOPE, useValue: 'root' },
{ provide: ErrorHandler, useFactory: errorHandler, deps: [] },
{
provide: EVENT_MANAGER_PLUGINS,
useClass: DomEventsPlugin,
multi: true,
deps: [DOCUMENT, NgZone, PLATFORM_ID]
},
{ provide: EVENT_MANAGER_PLUGINS, useClass: KeyEventsPlugin, multi: true, deps: [DOCUMENT] },
{
provide: DomRendererFactory2,
useClass: DomRendererFactory2,
deps: [EventManager, DomSharedStylesHost, APP_ID]
},
{ provide: RendererFactory2, useExisting: DomRendererFactory2 },
{ provide: SharedStylesHost, useExisting: DomSharedStylesHost },
{ provide: DomSharedStylesHost, useClass: DomSharedStylesHost, deps: [DOCUMENT] },
{ provide: Testability, useClass: Testability, deps: [NgZone] },
{ provide: EventManager, useClass: EventManager, deps: [EVENT_MANAGER_PLUGINS, NgZone] },
{ provide: XhrFactory, useClass: BrowserXhr, deps: [] },
];
/**
* 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 {
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.
* @returns The reconfigured `BrowserModule` to import into the app's root `AppModule`.
*/
static withServerTransition(params) {
return {
ngModule: BrowserModule,
providers: [
{ provide: APP_ID, useValue: params.appId },
{ provide: TRANSITION_ID, useExisting: APP_ID },
SERVER_TRANSITION_PROVIDERS,
],
};
}
}
BrowserModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: BrowserModule, deps: [{ token: BrowserModule, optional: true, skipSelf: true }], target: i0.ɵɵFactoryTarget.NgModule });
BrowserModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: BrowserModule, exports: [CommonModule, ApplicationModule] });
BrowserModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: BrowserModule, providers: BROWSER_MODULE_PROVIDERS, imports: [CommonModule, ApplicationModule] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: BrowserModule, decorators: [{
type: NgModule,
args: [{ providers: BROWSER_MODULE_PROVIDERS, exports: [CommonModule, ApplicationModule] }]
}], ctorParameters: function () {
return [{ type: BrowserModule, decorators: [{
type: Optional
}, {
type: SkipSelf
}, {
type: Inject,
args: [BrowserModule]
}] }];
} });
/**
* @license
* Copyright Google LLC 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 to create a `Meta` service instance for the current DOM document.
*/
function createMeta() {
return new Meta(ɵɵinject(DOCUMENT));
}
/**
* A service for managing HTML `<meta>` tags.
*
* Properties of the `MetaDefinition` object match the attributes of the
* HTML `<meta>` tag. These tags define document metadata that is important for
* things like configuring a Content Security Policy, defining browser compatibility
* and security settings, setting HTTP Headers, defining rich content for social sharing,
* and Search Engine Optimization (SEO).
*
* To identify specific `<meta>` tags in a document, use an attribute selection
* string in the format `"tag_attribute='value string'"`.
* For example, an `attrSelector` value of `"name='description'"` matches a tag
* whose `name` attribute has the value `"description"`.
* Selectors are used with the `querySelector()` Document method,
* in the format `meta[{attrSelector}]`.
*
* @see [HTML meta tag](https://developer.mozilla.org/docs/Web/HTML/Element/meta)
* @see [Document.querySelector()](https://developer.mozilla.org/docs/Web/API/Document/querySelector)
*
*
* @publicApi
*/
class Meta {
constructor(_doc) {
this._doc = _doc;
this._dom = ɵgetDOM();
}
/**
* Retrieves or creates a specific `<meta>` tag element in the current HTML document.
* In searching for an existing tag, Angular attempts to match the `name` or `property` attribute
* values in the provided tag definition, and verifies that all other attribute values are equal.
* If an existing element is found, it is returned and is not modified in any way.
* @param tag The definition of a `<meta>` element to match or create.
* @param forceCreation True to create a new element without checking whether one already exists.
* @returns The existing element with the same attributes and values if found,
* the new element if no match is found, or `null` if the tag parameter is not defined.
*/
addTag(tag, forceCreation = false) {
if (!tag)
return null;
return this._getOrCreateElement(tag, forceCreation);
}
/**
* Retrieves or creates a set of `<meta>` tag elements in the current HTML document.
* In searching for an existing tag, Angular attempts to match the `name` or `property` attribute
* values in the provided tag definition, and verifies that all other attribute values are equal.
* @param tags An array of tag definitions to match or create.
* @param forceCreation True to create new elements without checking whether they already exist.
* @returns The matching elements if found, or the new elements.
*/
addTags(tags, forceCreation = false) {
if (!tags)
return [];
return tags.reduce((result, tag) => {
if (tag) {
result.push(this._getOrCreateElement(tag, forceCreation));
}
return result;
}, []);
}
/**
* Retrieves a `<meta>` tag element in the current HTML document.
* @param attrSelector The tag attribute and value to match against, in the format
* `"tag_attribute='value string'"`.
* @returns The matching element, if any.
*/
getTag(attrSelector) {
if (!attrSelector)
return null;
return this._doc.querySelector(`meta[${attrSelector}]`) || null;
}
/**
* Retrieves a set of `<meta>` tag elements in the current HTML document.
* @param attrSelector The tag attribute and value to match against, in the format
* `"tag_attribute='value string'"`.
* @returns The matching elements, if any.
*/
getTags(attrSelector) {
if (!attrSelector)
return [];
const list /*NodeList*/ = this._doc.querySelectorAll(`meta[${attrSelector}]`);
return list ? [].slice.call(list) : [];
}
/**
* Modifies an existing `<meta>` tag element in the current HTML document.
* @param tag The tag description with which to replace the existing tag content.
* @param selector A tag attribute and value to match against, to identify
* an existing tag. A string in the format `"tag_attribute=`value string`"`.
* If not supplied, matches a tag with the same `name` or `property` attribute value as the
* replacement tag.
* @return The modified element.
*/
updateTag(tag, selector) {
if (!tag)
return null;
selector = selector || this._parseSelector(tag);
const meta = this.getTag(selector);
if (meta) {
return this._setMetaElementAttributes(tag, meta);
}
return this._getOrCreateElement(tag, true);
}
/**
* Removes an existing `<meta>` tag element from the current HTML document.
* @param attrSelector A tag attribute and value to match against, to identify
* an existing tag. A string in the format `"tag_attribute=`value string`"`.
*/
removeTag(attrSelector) {
this.removeTagElement(this.getTag(attrSelector));
}
/**
* Removes an existing `<meta>` tag element from the current HTML document.
* @param meta The tag definition to match against to identify an existing tag.
*/
removeTagElement(meta) {
if (meta) {
this._dom.remove(meta);
}
}
_getOrCreateElement(meta, forceCreation = false) {
if (!forceCreation) {
const selector = this._parseSelector(meta);
// 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
const elem = this.getTags(selector).filter(elem => this._containsAttributes(meta, elem))[0];
if (elem !== undefined)
return elem;
}
const element = this._dom.createElement('meta');
this._setMetaElementAttributes(meta, element);
const head = this._doc.getElementsByTagName('head')[0];
head.appendChild(element);
return element;
}
_setMetaElementAttributes(tag, el) {
Object.keys(tag).forEach((prop) => el.setAttribute(this._getMetaKeyMap(prop), tag[prop]));
return el;
}
_parseSelector(tag) {
const attr = tag.name ? 'name' : 'property';
return `${attr}="${tag[attr]}"`;
}
_containsAttributes(tag, elem) {
return Object.keys(tag).every((key) => elem.getAttribute(this._getMetaKeyMap(key)) === tag[key]);
}
_getMetaKeyMap(prop) {
return META_KEYS_MAP[prop] || prop;
}
}
Meta.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: Meta, deps: [{ token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable });
Meta.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: Meta, providedIn: 'root', useFactory: createMeta, deps: [] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: Meta, decorators: [{
type: Injectable,
args: [{ providedIn: 'root', useFactory: createMeta, deps: [] }]
}], ctorParameters: function () {
return [{ type: undefined, decorators: [{
type: Inject,
args: [DOCUMENT]
}] }];
} });
/**
* Mapping for MetaDefinition properties with their correct meta attribute names
*/
const META_KEYS_MAP = {
httpEquiv: 'http-equiv'
};
/**
* @license
* Copyright Google LLC 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 to create Title service.
*/
function createTitle() {
return new Title(ɵɵinject(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
* ti