@angular/platform-browser
Version:
Angular - library for using Angular in a web browser
1,216 lines (1,204 loc) • 87.3 kB
JavaScript
/**
* @license Angular v16.2.6
* (c) 2010-2022 Google LLC. https://angular.io/
* License: MIT
*/
import * as i0 from '@angular/core';
import { ɵglobal, ɵRuntimeError, Injectable, InjectionToken, Inject, APP_ID, CSP_NONCE, PLATFORM_ID, Optional, ViewEncapsulation, RendererStyleFlags2, ɵinternalCreateApplication, ErrorHandler, ɵsetDocument, PLATFORM_INITIALIZER, createPlatformFactory, platformCore, ɵTESTABILITY_GETTER, ɵTESTABILITY, Testability, NgZone, TestabilityRegistry, ɵINJECTOR_SCOPE, RendererFactory2, ApplicationModule, NgModule, SkipSelf, ɵɵinject, ApplicationRef, ɵConsole, forwardRef, ɵXSS_SECURITY_URL, SecurityContext, ɵallowSanitizationBypassAndThrow, ɵunwrapSafeValue, ɵ_sanitizeUrl, ɵ_sanitizeHtml, ɵbypassSanitizationTrustHtml, ɵbypassSanitizationTrustStyle, ɵbypassSanitizationTrustScript, ɵbypassSanitizationTrustUrl, ɵbypassSanitizationTrustResourceUrl, Injector, ENVIRONMENT_INITIALIZER, inject, ɵformatRuntimeError, makeEnvironmentProviders, ɵwithDomHydration, Version, makeStateKey as makeStateKey$1, TransferState as TransferState$1 } from '@angular/core';
import { ɵDomAdapter, ɵsetRootDomAdapter, ɵparseCookieValue, ɵgetDOM, isPlatformServer, DOCUMENT, ɵPLATFORM_BROWSER_ID, XhrFactory, CommonModule } from '@angular/common';
export { ɵgetDOM } from '@angular/common';
import { ɵwithHttpTransferCache } from '@angular/common/http';
/**
* 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;
}
}
/**
* 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);
return () => {
el.removeEventListener(evt, listener);
};
}
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}`;
}
class BrowserGetTestability {
addToWindow(registry) {
ɵglobal['getAngularTestability'] = (elem, findInAncestors = true) => {
const testability = registry.findTestabilityInTree(elem, findInAncestors);
if (testability == null) {
throw new ɵRuntimeError(5103 /* RuntimeErrorCode.TESTABILITY_NOT_FOUND */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
'Could not find testability for element.');
}
return testability;
};
ɵglobal['getAllAngularTestabilities'] = () => registry.getAllTestabilities();
ɵglobal['getAllAngularRootElements'] = () => registry.getAllRootElements();
const whenAllStable = (callback) => {
const testabilities = ɵglobal['getAllAngularTestabilities']();
let count = testabilities.length;
let didWork = false;
const decrement = function (didWork_) {
didWork = didWork || didWork_;
count--;
if (count == 0) {
callback(didWork);
}
};
testabilities.forEach((testability) => {
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();
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: BrowserXhr, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: BrowserXhr }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: BrowserXhr, decorators: [{
type: Injectable
}] });
/**
* 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((plugin) => {
plugin.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);
}
/**
* Retrieves the compilation zone in which event listeners are registered.
*/
getZone() {
return this._zone;
}
/** @internal */
_findPluginFor(eventName) {
let plugin = this._eventNameToPlugin.get(eventName);
if (plugin) {
return plugin;
}
const plugins = this._plugins;
plugin = plugins.find((plugin) => plugin.supports(eventName));
if (!plugin) {
throw new ɵRuntimeError(5101 /* RuntimeErrorCode.NO_PLUGIN_FOR_EVENT */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
`No event manager plugin found for event ${eventName}`);
}
this._eventNameToPlugin.set(eventName, plugin);
return plugin;
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: EventManager, deps: [{ token: EVENT_MANAGER_PLUGINS }, { token: i0.NgZone }], target: i0.ɵɵFactoryTarget.Injectable }); }
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: EventManager }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.6", 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;
}
}
/** The style elements attribute name used to set value of `APP_ID` token. */
const APP_ID_ATTRIBUTE_NAME = 'ng-app-id';
class SharedStylesHost {
constructor(doc, appId, nonce, platformId = {}) {
this.doc = doc;
this.appId = appId;
this.nonce = nonce;
this.platformId = platformId;
// Maps all registered host nodes to a list of style nodes that have been added to the host node.
this.styleRef = new Map();
this.hostNodes = new Set();
this.styleNodesInDOM = this.collectServerRenderedStyles();
this.platformIsServer = isPlatformServer(platformId);
this.resetHostNodes();
}
addStyles(styles) {
for (const style of styles) {
const usageCount = this.changeUsageCount(style, 1);
if (usageCount === 1) {
this.onStyleAdded(style);
}
}
}
removeStyles(styles) {
for (const style of styles) {
const usageCount = this.changeUsageCount(style, -1);
if (usageCount <= 0) {
this.onStyleRemoved(style);
}
}
}
ngOnDestroy() {
const styleNodesInDOM = this.styleNodesInDOM;
if (styleNodesInDOM) {
styleNodesInDOM.forEach((node) => node.remove());
styleNodesInDOM.clear();
}
for (const style of this.getAllStyles()) {
this.onStyleRemoved(style);
}
this.resetHostNodes();
}
addHost(hostNode) {
this.hostNodes.add(hostNode);
for (const style of this.getAllStyles()) {
this.addStyleToHost(hostNode, style);
}
}
removeHost(hostNode) {
this.hostNodes.delete(hostNode);
}
getAllStyles() {
return this.styleRef.keys();
}
onStyleAdded(style) {
for (const host of this.hostNodes) {
this.addStyleToHost(host, style);
}
}
onStyleRemoved(style) {
const styleRef = this.styleRef;
styleRef.get(style)?.elements?.forEach((node) => node.remove());
styleRef.delete(style);
}
collectServerRenderedStyles() {
const styles = this.doc.head?.querySelectorAll(`style[${APP_ID_ATTRIBUTE_NAME}="${this.appId}"]`);
if (styles?.length) {
const styleMap = new Map();
styles.forEach((style) => {
if (style.textContent != null) {
styleMap.set(style.textContent, style);
}
});
return styleMap;
}
return null;
}
changeUsageCount(style, delta) {
const map = this.styleRef;
if (map.has(style)) {
const styleRefValue = map.get(style);
styleRefValue.usage += delta;
return styleRefValue.usage;
}
map.set(style, { usage: delta, elements: [] });
return delta;
}
getStyleElement(host, style) {
const styleNodesInDOM = this.styleNodesInDOM;
const styleEl = styleNodesInDOM?.get(style);
if (styleEl?.parentNode === host) {
// `styleNodesInDOM` cannot be undefined due to the above `styleNodesInDOM?.get`.
styleNodesInDOM.delete(style);
styleEl.removeAttribute(APP_ID_ATTRIBUTE_NAME);
if (typeof ngDevMode === 'undefined' || ngDevMode) {
// This attribute is solely used for debugging purposes.
styleEl.setAttribute('ng-style-reused', '');
}
return styleEl;
}
else {
const styleEl = this.doc.createElement('style');
if (this.nonce) {
styleEl.setAttribute('nonce', this.nonce);
}
styleEl.textContent = style;
if (this.platformIsServer) {
styleEl.setAttribute(APP_ID_ATTRIBUTE_NAME, this.appId);
}
return styleEl;
}
}
addStyleToHost(host, style) {
const styleEl = this.getStyleElement(host, style);
host.appendChild(styleEl);
const styleRef = this.styleRef;
const styleElRef = styleRef.get(style)?.elements;
if (styleElRef) {
styleElRef.push(styleEl);
}
else {
styleRef.set(style, { elements: [styleEl], usage: 1 });
}
}
resetHostNodes() {
const hostNodes = this.hostNodes;
hostNodes.clear();
// Re-add the head element back since this is the default host.
hostNodes.add(this.doc.head);
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: SharedStylesHost, deps: [{ token: DOCUMENT }, { token: APP_ID }, { token: CSP_NONCE, optional: true }, { token: PLATFORM_ID }], target: i0.ɵɵFactoryTarget.Injectable }); }
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: SharedStylesHost }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: SharedStylesHost, decorators: [{
type: Injectable
}], ctorParameters: function () { return [{ type: Document, decorators: [{
type: Inject,
args: [DOCUMENT]
}] }, { type: undefined, decorators: [{
type: Inject,
args: [APP_ID]
}] }, { type: undefined, decorators: [{
type: Inject,
args: [CSP_NONCE]
}, {
type: Optional
}] }, { type: undefined, decorators: [{
type: Inject,
args: [PLATFORM_ID]
}] }]; } });
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/',
'math': 'http://www.w3.org/1998/MathML/',
};
const COMPONENT_REGEX = /%COMP%/g;
const COMPONENT_VARIABLE = '%COMP%';
const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
/**
* The default value for the `REMOVE_STYLES_ON_COMPONENT_DESTROY` DI token.
*/
const REMOVE_STYLES_ON_COMPONENT_DESTROY_DEFAULT = false;
/**
* A [DI token](guide/glossary#di-token "DI token definition") that indicates whether styles
* of destroyed components should be removed from DOM.
*
* By default, the value is set to `false`. This will be changed in the next major version.
* @publicApi
*/
const REMOVE_STYLES_ON_COMPONENT_DESTROY = new InjectionToken('RemoveStylesOnCompDestroy', {
providedIn: 'root',
factory: () => REMOVE_STYLES_ON_COMPONENT_DESTROY_DEFAULT,
});
function shimContentAttribute(componentShortId) {
return CONTENT_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
function shimHostAttribute(componentShortId) {
return HOST_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
function shimStylesContent(compId, styles) {
return styles.map(s => s.replace(COMPONENT_REGEX, compId));
}
class DomRendererFactory2 {
constructor(eventManager, sharedStylesHost, appId, removeStylesOnCompDestroy, doc, platformId, ngZone, nonce = null) {
this.eventManager = eventManager;
this.sharedStylesHost = sharedStylesHost;
this.appId = appId;
this.removeStylesOnCompDestroy = removeStylesOnCompDestroy;
this.doc = doc;
this.platformId = platformId;
this.ngZone = ngZone;
this.nonce = nonce;
this.rendererByCompId = new Map();
this.platformIsServer = isPlatformServer(platformId);
this.defaultRenderer =
new DefaultDomRenderer2(eventManager, doc, ngZone, this.platformIsServer);
}
createRenderer(element, type) {
if (!element || !type) {
return this.defaultRenderer;
}
if (this.platformIsServer && type.encapsulation === ViewEncapsulation.ShadowDom) {
// Domino does not support shadow DOM.
type = { ...type, encapsulation: ViewEncapsulation.Emulated };
}
const renderer = this.getOrCreateRenderer(element, type);
// Renderers have different logic due to different encapsulation behaviours.
// Ex: for emulated, an attribute is added to the element.
if (renderer instanceof EmulatedEncapsulationDomRenderer2) {
renderer.applyToHost(element);
}
else if (renderer instanceof NoneEncapsulationDomRenderer) {
renderer.applyStyles();
}
return renderer;
}
getOrCreateRenderer(element, type) {
const rendererByCompId = this.rendererByCompId;
let renderer = rendererByCompId.get(type.id);
if (!renderer) {
const doc = this.doc;
const ngZone = this.ngZone;
const eventManager = this.eventManager;
const sharedStylesHost = this.sharedStylesHost;
const removeStylesOnCompDestroy = this.removeStylesOnCompDestroy;
const platformIsServer = this.platformIsServer;
switch (type.encapsulation) {
case ViewEncapsulation.Emulated:
renderer = new EmulatedEncapsulationDomRenderer2(eventManager, sharedStylesHost, type, this.appId, removeStylesOnCompDestroy, doc, ngZone, platformIsServer);
break;
case ViewEncapsulation.ShadowDom:
return new ShadowDomRenderer(eventManager, sharedStylesHost, element, type, doc, ngZone, this.nonce, platformIsServer);
default:
renderer = new NoneEncapsulationDomRenderer(eventManager, sharedStylesHost, type, removeStylesOnCompDestroy, doc, ngZone, platformIsServer);
break;
}
rendererByCompId.set(type.id, renderer);
}
return renderer;
}
ngOnDestroy() {
this.rendererByCompId.clear();
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: DomRendererFactory2, deps: [{ token: EventManager }, { token: SharedStylesHost }, { token: APP_ID }, { token: REMOVE_STYLES_ON_COMPONENT_DESTROY }, { token: DOCUMENT }, { token: PLATFORM_ID }, { token: i0.NgZone }, { token: CSP_NONCE }], target: i0.ɵɵFactoryTarget.Injectable }); }
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: DomRendererFactory2 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: DomRendererFactory2, decorators: [{
type: Injectable
}], ctorParameters: function () { return [{ type: EventManager }, { type: SharedStylesHost }, { type: undefined, decorators: [{
type: Inject,
args: [APP_ID]
}] }, { type: undefined, decorators: [{
type: Inject,
args: [REMOVE_STYLES_ON_COMPONENT_DESTROY]
}] }, { type: Document, decorators: [{
type: Inject,
args: [DOCUMENT]
}] }, { type: Object, decorators: [{
type: Inject,
args: [PLATFORM_ID]
}] }, { type: i0.NgZone }, { type: undefined, decorators: [{
type: Inject,
args: [CSP_NONCE]
}] }]; } });
class DefaultDomRenderer2 {
constructor(eventManager, doc, ngZone, platformIsServer) {
this.eventManager = eventManager;
this.doc = doc;
this.ngZone = ngZone;
this.platformIsServer = platformIsServer;
this.data = Object.create(null);
this.destroyNode = null;
}
destroy() { }
createElement(name, namespace) {
if (namespace) {
// TODO: `|| namespace` was added in
// https://github.com/angular/angular/commit/2b9cc8503d48173492c29f5a271b61126104fbdb to
// support how Ivy passed around the namespace URI rather than short name at the time. It did
// not, however extend the support to other parts of the system (setAttribute, setAttribute,
// and the ServerRenderer). We should decide what exactly the semantics for dealing with
// namespaces should be and make it consistent.
// Related issues:
// https://github.com/angular/angular/issues/44028
// https://github.com/angular/angular/issues/44883
return this.doc.createElementNS(NAMESPACE_URIS[namespace] || namespace, name);
}
return this.doc.createElement(name);
}
createComment(value) {
return this.doc.createComment(value);
}
createText(value) {
return this.doc.createTextNode(value);
}
appendChild(parent, newChild) {
const targetParent = isTemplateNode(parent) ? parent.content : parent;
targetParent.appendChild(newChild);
}
insertBefore(parent, newChild, refChild) {
if (parent) {
const targetParent = isTemplateNode(parent) ? parent.content : parent;
targetParent.insertBefore(newChild, refChild);
}
}
removeChild(parent, oldChild) {
if (parent) {
parent.removeChild(oldChild);
}
}
selectRootElement(selectorOrNode, preserveContent) {
let el = typeof selectorOrNode === 'string' ? this.doc.querySelector(selectorOrNode) :
selectorOrNode;
if (!el) {
throw new ɵRuntimeError(-5104 /* RuntimeErrorCode.ROOT_NODE_NOT_FOUND */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
`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;
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) {
const namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.removeAttributeNS(namespaceUri, name);
}
else {
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) {
// removeProperty has no effect when used on camelCased properties.
el.style.removeProperty(style);
}
else {
el.style[style] = '';
}
}
setProperty(el, name, value) {
(typeof ngDevMode === 'undefined' || ngDevMode) && checkNoSyntheticProp(name, 'property');
el[name] = value;
}
setValue(node, value) {
node.nodeValue = value;
}
listen(target, event, callback) {
(typeof ngDevMode === 'undefined' || ngDevMode) && checkNoSyntheticProp(event, 'listener');
if (typeof target === 'string') {
target = ɵgetDOM().getGlobalEventTarget(this.doc, target);
if (!target) {
throw new Error(`Unsupported event target ${target} for event ${event}`);
}
}
return this.eventManager.addEventListener(target, event, this.decoratePreventDefault(callback));
}
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;
}
// Run the event handler inside the ngZone because event handlers are not patched
// by Zone on the server. This is required only for tests.
const allowDefaultBehavior = this.platformIsServer ?
this.ngZone.runGuarded(() => eventHandler(event)) :
eventHandler(event);
if (allowDefaultBehavior === false) {
event.preventDefault();
}
return undefined;
};
}
}
const AT_CHARCODE = (() => '@'.charCodeAt(0))();
function checkNoSyntheticProp(name, nameKind) {
if (name.charCodeAt(0) === AT_CHARCODE) {
throw new ɵRuntimeError(5105 /* RuntimeErrorCode.UNEXPECTED_SYNTHETIC_PROPERTY */, `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).`);
}
}
function isTemplateNode(node) {
return node.tagName === 'TEMPLATE' && node.content !== undefined;
}
class ShadowDomRenderer extends DefaultDomRenderer2 {
constructor(eventManager, sharedStylesHost, hostEl, component, doc, ngZone, nonce, platformIsServer) {
super(eventManager, doc, ngZone, platformIsServer);
this.sharedStylesHost = sharedStylesHost;
this.hostEl = hostEl;
this.shadowRoot = hostEl.attachShadow({ mode: 'open' });
this.sharedStylesHost.addHost(this.shadowRoot);
const styles = shimStylesContent(component.id, component.styles);
for (const style of styles) {
const styleEl = document.createElement('style');
if (nonce) {
styleEl.setAttribute('nonce', nonce);
}
styleEl.textContent = style;
this.shadowRoot.appendChild(styleEl);
}
}
nodeOrShadowRoot(node) {
return node === this.hostEl ? this.shadowRoot : node;
}
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)));
}
destroy() {
this.sharedStylesHost.removeHost(this.shadowRoot);
}
}
class NoneEncapsulationDomRenderer extends DefaultDomRenderer2 {
constructor(eventManager, sharedStylesHost, component, removeStylesOnCompDestroy, doc, ngZone, platformIsServer, compId) {
super(eventManager, doc, ngZone, platformIsServer);
this.sharedStylesHost = sharedStylesHost;
this.removeStylesOnCompDestroy = removeStylesOnCompDestroy;
this.styles = compId ? shimStylesContent(compId, component.styles) : component.styles;
}
applyStyles() {
this.sharedStylesHost.addStyles(this.styles);
}
destroy() {
if (!this.removeStylesOnCompDestroy) {
return;
}
this.sharedStylesHost.removeStyles(this.styles);
}
}
class EmulatedEncapsulationDomRenderer2 extends NoneEncapsulationDomRenderer {
constructor(eventManager, sharedStylesHost, component, appId, removeStylesOnCompDestroy, doc, ngZone, platformIsServer) {
const compId = appId + '-' + component.id;
super(eventManager, sharedStylesHost, component, removeStylesOnCompDestroy, doc, ngZone, platformIsServer, compId);
this.contentAttr = shimContentAttribute(compId);
this.hostAttr = shimHostAttribute(compId);
}
applyToHost(element) {
this.applyStyles();
this.setAttribute(element, this.hostAttr, '');
}
createElement(parent, name) {
const el = super.createElement(parent, name);
super.setAttribute(el, this.contentAttr, '');
return el;
}
}
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);
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: DomEventsPlugin, deps: [{ token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable }); }
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: DomEventsPlugin }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: DomEventsPlugin, decorators: [{
type: Injectable
}], ctorParameters: function () { return [{ type: undefined, decorators: [{
type: Inject,
args: [DOCUMENT]
}] }]; } });
/**
* Defines supported modifiers for key events.
*/
const MODIFIER_KEYS = ['alt', 'control', 'meta', 'shift'];
// 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/
const _keyMap = {
'\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'
};
/**
* 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);
});
}
/**
* Parses the user provided full keyboard event definition and normalizes it for
* later internal use. It ensures the string is all lowercase, converts special
* characters to a standard spelling, and orders all the values consistently.
*
* @param eventName The name of the key event to listen for.
* @returns an object with the full, normalized string, and the dom event name
* or null in the case when the event doesn't match a keyboard event.
*/
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 = '';
let codeIX = parts.indexOf('code');
if (codeIX > -1) {
parts.splice(codeIX, 1);
fullKey = 'code.';
}
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;
}
/**
* Determines whether the actual keys pressed match the configured key code string.
* The `fullKeyCode` event is normalized in the `parseEventName` method when the
* event is attached to the DOM during the `addEventListener` call. This is unseen
* by the end user and is normalized for internal consistency and parsing.
*
* @param event The keyboard event.
* @param fullKeyCode The normalized user defined expected key event string
* @returns boolean.
*/
static matchEventFullKeyCode(event, fullKeyCode) {
let keycode = _keyMap[event.key] || event.key;
let key = '';
if (fullKeyCode.indexOf('code.') > -1) {
keycode = event.code;
key = 'code.';
}
// the keycode could be unidentified so we have to check here
if (keycode == null || !keycode)
return false;
keycode = keycode.toLowerCase();
if (keycode === ' ') {
keycode = 'space'; // for readability
}
else if (keycode === '.') {
keycode = 'dot'; // because '.' is used as a separator in event names
}
MODIFIER_KEYS.forEach(modifierName => {
if (modifierName !== keycode) {
const modifierGetter = MODIFIER_KEY_GETTERS[modifierName];
if (modifierGetter(event)) {
key += modifierName + '.';
}
}
});
key += keycode;
return key === fullKeyCode;
}
/**
* 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) => {
if (KeyEventsPlugin.matchEventFullKeyCode(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;
}
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: KeyEventsPlugin, deps: [{ token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable }); }
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: KeyEventsPlugin }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: KeyEventsPlugin, decorators: [{
type: Injectable
}], ctorParameters: function () { return [{ type: undefined, decorators: [{
type: Inject,
args: [DOCUMENT]
}] }]; } });
/**
* Bootstraps an instance of an Angular application and renders a standalone component as the
* application's root component. More information about standalone components can be found in [this
* guide](guide/standalone-components).
*
* @usageNotes
* The root component passed into this function *must* be a standalone one (should have the
* `standalone: true` flag in the `@Component` decorator config).
*
* ```typescript
* @Component({
* standalone: true,
* template: 'Hello world!'
* })
* class RootComponent {}
*
* const appRef: ApplicationRef = await bootstrapApplication(RootComponent);
* ```
*
* You can add the list of providers that should be available in the application injector by
* specifying the `providers` field in an object passed as the second argument:
*
* ```typescript
* await bootstrapApplication(RootComponent, {
* providers: [
* {provide: BACKEND_URL, useValue: 'https://yourdomain.com/api'}
* ]
* });
* ```
*
* The `importProvidersFrom` helper method can be used to collect all providers from any
* existing NgModule (and transitively from all NgModules that it imports):
*
* ```typescript
* await bootstrapApplication(RootComponent, {
* providers: [
* importProvidersFrom(SomeNgModule)
* ]
* });
* ```
*
* Note: the `bootstrapApplication` method doesn't include [Testability](api/core/Testability) by
* default. You can add [Testability](api/core/Testability) by getting the list of necessary
* providers using `provideProtractorTestingSupport()` function and adding them into the `providers`
* array, for example:
*
* ```typescript
* import {provideProtractorTestingSupport} from '@angular/platform-browser';
*
* await bootstrapApplication(RootComponent, {providers: [provideProtractorTestingSupport()]});
* ```
*
* @param rootComponent A reference to a standalone component that should be rendered.
* @param options Extra configuration for the bootstrap operation, see `ApplicationConfig` for
* additional info.
* @returns A promise that returns an `ApplicationRef` instance once resolved.
*
* @publicApi
*/
function bootstrapApplication(rootComponent, options) {
return ɵinternalCreateApplication({ rootComponent, ...createProvidersConfig(options) });
}
/**
* Create an instance of an Angular application without bootstrapping any components. This is useful
* for the situation where one wants to decouple application environment creation (a platform and
* associated injectors) from rendering components on a screen. Components can be subsequently
* bootstrapped on the returned `ApplicationRef`.
*
* @param options Extra configuration for the application environment, see `ApplicationConfig` for
* additional info.
* @returns A promise that returns an `ApplicationRef` instance once resolved.
*
* @publicApi
*/
function createApplication(options) {
return ɵinternalCreateApplication(createProvidersConfig(options));
}
function createProvidersConfig(options) {
return {
appProviders: [
...BROWSER_MODULE_PROVIDERS,
...(options?.providers ?? []),
],
platformProviders: INTERNAL_BROWSER_PLATFORM_PROVIDERS
};
}
/**
* Returns a set of providers required to setup [Testability](api/core/Testability) for an
* application bootstrapped using the `bootstrapApplication` function. The set of providers is
* needed to support testing an application with Protractor (which relies on the Testability APIs
* to be present).
*
* @returns An array of providers required to setup Testability for an application and make it
* available for testing using Protractor.
*
* @publicApi
*/
function provideProtractorTestingSupport() {
// Return a copy to prevent changes to the original array in case any in-place
// alterations are performed to the `provideProtractorTestingSupport` call results in app
// code.
return [...TESTABILITY_PROVIDERS];
}
function initDomAdapter() {
BrowserDomAdapter.makeCurrent();
}
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);
/**
* Internal marker to signal whether providers from the `BrowserModule` are already present in DI.
* This is needed to avoid loading `BrowserModule` providers twice. We can't rely on the
* `BrowserModule` presence itself, since the standalone-based bootstrap just imports
* `BrowserModule` providers without referencing the module itself.
*/
const BROWSER_MODULE_PROVIDERS_MARKER = new InjectionToken((typeof ngDevMode === 'undefined' || ngDevMode) ? 'BrowserModule Providers Marker' : '');
const TESTABILITY_PROVIDERS = [
{
provide: ɵTESTABILITY_GETTER,
useClass: BrowserGetTestability,
deps: [],
},
{
provide: ɵTESTABILITY,
useClass: Testability,
deps: [NgZone, TestabilityRegistry, ɵTESTABILITY_GETTER]
},
{
provide: Testability,
useClass: Testability,
deps: [NgZone, TestabilityRegistry, ɵTESTABILITY_GETTER]
}
];
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] },
DomRendererFactory2, SharedStylesHost, EventManager,
{ provide: RendererFactory2, useExisting: DomRendererFactory2 },
{ provide: XhrFactory, useClass: BrowserXhr, deps: [] },
(typeof ngDevMode === 'undefined' || ngDevMode) ?
{ provide: BROWSER_MODULE_PROVIDERS_MARKER, useValue: true } :
[]
];
/**
* 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(providersAlreadyPresent) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && providersAlreadyPresent) {
throw new ɵRuntimeError(5100 /* RuntimeErrorCode.BROWER_MODULE_ALREADY_LOADED */, `Providers from the \`BrowserModule\` have already been loaded. If you need access ` +
`to common directives such as NgIf and NgFor, import the \`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`.
*
* @deprecated Use {@link APP_ID} instead to set the application ID.
*/
static withServerTransition(params) {
return {
ngModule: BrowserModule,
providers: [
{ provide: APP_ID, useValue: params.appId },
],
};
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: BrowserModule, deps: [{ token: BROWSER_MODULE_PROVIDERS_MARKER, optional: true, skipSelf: true }], target: i0.ɵɵFactoryTarget.NgModule }); }
static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.2.6", ngImport: i0, type: BrowserModule, exports: [CommonModule, ApplicationModule] }); }
static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: BrowserModule, providers: [...BROWSER_MODULE_PROVIDERS, ...TESTABILITY_PROVIDERS], imports: [CommonModule, ApplicationModule] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.6", ngImport: i0, type: BrowserModule, decorators: [{
type: NgModule,
args: [{
providers: [...BROWSER_MODULE_PROVIDERS, ...TESTABILITY_PROVIDERS],
exports: [CommonModule, ApplicationModule],
}]
}], ctorParameters: function () { return [{ type: undefined, decorators: [{
type: Optional
}, {
type: SkipSelf
}, {
type: Inject,
args: [BROWSER_MODULE_PROVIDERS_MARKER]
}] }]; } });
/**
* 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