@angular/core
Version:
Angular - the core framework
1,080 lines • 235 kB
JavaScript
import { ErrorHandler } from '../../error_handler';
import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '../../metadata/schema';
import { validateAgainstEventAttributes, validateAgainstEventProperties } from '../../sanitization/sanitization';
import { assertDataInRange, assertDefined, assertDomNode, assertEqual, assertNotEqual, assertNotSame } from '../../util/assert';
import { createNamedArrayType } from '../../util/named_array_type';
import { normalizeDebugBindingName, normalizeDebugBindingValue } from '../../util/ng_reflect';
import { assertLView, assertPreviousIsParent } from '../assert';
import { attachPatchData, getComponentViewByInstance } from '../context_discovery';
import { diPublicInInjector, getNodeInjectable, getOrCreateNodeInjectorForNode } from '../di';
import { throwMultipleComponentError } from '../errors';
import { executeHooks, executePreOrderHooks, registerPreOrderHooks } from '../hooks';
import { ACTIVE_INDEX, CONTAINER_HEADER_OFFSET } from '../interfaces/container';
import { INJECTOR_BLOOM_PARENT_SIZE, NodeInjectorFactory } from '../interfaces/injector';
import { isProceduralRenderer } from '../interfaces/renderer';
import { BINDING_INDEX, CHILD_HEAD, CHILD_TAIL, CLEANUP, CONTEXT, DECLARATION_VIEW, FLAGS, HEADER_OFFSET, HOST, INJECTOR, NEXT, PARENT, QUERIES, RENDERER, RENDERER_FACTORY, SANITIZER, TVIEW, T_HOST } from '../interfaces/view';
import { assertNodeOfPossibleTypes, assertNodeType } from '../node_assert';
import { isNodeMatchingSelectorList } from '../node_selector_matcher';
import { enterView, getBindingsEnabled, getCheckNoChangesMode, getIsParent, getLView, getNamespace, getPreviousOrParentTNode, getSelectedIndex, incrementActiveDirectiveId, isCreationMode, leaveView, setActiveHostElement, setBindingRoot, setCheckNoChangesMode, setCurrentDirectiveDef, setCurrentQueryIndex, setPreviousOrParentTNode, setSelectedIndex, ɵɵnamespaceHTML } from '../state';
import { initializeStaticContext as initializeStaticStylingContext } from '../styling/class_and_style_bindings';
import { ANIMATION_PROP_PREFIX, isAnimationProp } from '../styling/util';
import { NO_CHANGE } from '../tokens';
import { attrsStylingIndexOf } from '../util/attrs_utils';
import { INTERPOLATION_DELIMITER, renderStringify, stringifyForError } from '../util/misc_utils';
import { getLViewParent, getRootContext } from '../util/view_traversal_utils';
import { getComponentViewByIndex, getNativeByIndex, getNativeByTNode, getTNode, isComponent, isComponentDef, isContentQueryHost, isLContainer, isRootView, readPatchedLView, resetPreOrderHookFlags, unwrapRNode, viewAttachedToChangeDetector } from '../util/view_utils';
import { LCleanup, LViewBlueprint, MatchesArray, TCleanup, TNodeInitialData, TNodeInitialInputs, TNodeLocalNames, TViewComponents, TViewConstructor, attachLContainerDebug, attachLViewDebug, cloneToLView, cloneToTViewData } from './lview_debug';
import { selectInternal } from './select';
var ɵ0 = function () { return Promise.resolve(null); };
/**
* A permanent marker promise which signifies that the current CD tree is
* clean.
*/
var _CLEAN_PROMISE = (ɵ0)();
/**
* Refreshes the view, executing the following steps in that order:
* triggers init hooks, refreshes dynamic embedded views, triggers content hooks, sets host
* bindings, refreshes child components.
* Note: view hooks are triggered later when leaving the view.
*/
export function refreshDescendantViews(lView) {
var tView = lView[TVIEW];
var creationMode = isCreationMode(lView);
// This needs to be set before children are processed to support recursive components
tView.firstTemplatePass = false;
// Resetting the bindingIndex of the current LView as the next steps may trigger change detection.
lView[BINDING_INDEX] = tView.bindingStartIndex;
// If this is a creation pass, we should not call lifecycle hooks or evaluate bindings.
// This will be done in the update pass.
if (!creationMode) {
var checkNoChangesMode = getCheckNoChangesMode();
executePreOrderHooks(lView, tView, checkNoChangesMode, undefined);
refreshDynamicEmbeddedViews(lView);
// Content query results must be refreshed before content hooks are called.
refreshContentQueries(tView, lView);
resetPreOrderHookFlags(lView);
executeHooks(lView, tView.contentHooks, tView.contentCheckHooks, checkNoChangesMode, 1 /* AfterContentInitHooksToBeRun */, undefined);
setHostBindings(tView, lView);
}
// 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 (creationMode && tView.staticContentQueries) {
refreshContentQueries(tView, lView);
}
refreshChildComponents(tView.components);
}
/** Sets the host bindings for the current view. */
export function setHostBindings(tView, viewData) {
var selectedIndex = getSelectedIndex();
try {
if (tView.expandoInstructions) {
var bindingRootIndex = viewData[BINDING_INDEX] = tView.expandoStartIndex;
setBindingRoot(bindingRootIndex);
var currentDirectiveIndex = -1;
var currentElementIndex = -1;
for (var i = 0; i < tView.expandoInstructions.length; i++) {
var instruction = tView.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.
currentElementIndex = -instruction;
setActiveHostElement(currentElementIndex);
// Injector block and providers are taken into account.
var providerCount = tView.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;
}
setBindingRoot(bindingRootIndex);
}
else {
// If it's not a number, it's a host binding function that needs to be executed.
if (instruction !== null) {
viewData[BINDING_INDEX] = bindingRootIndex;
var hostCtx = unwrapRNode(viewData[currentDirectiveIndex]);
instruction(2 /* Update */, hostCtx, currentElementIndex);
// Each directive gets a uniqueId value that is the same for both
// create and update calls when the hostBindings function is called. The
// directive uniqueId is not set anywhere--it is just incremented between
// each hostBindings call and is useful for helping instruction code
// uniquely determine which directive is currently active when executed.
incrementActiveDirectiveId();
}
currentDirectiveIndex++;
}
}
}
}
finally {
setActiveHostElement(selectedIndex);
}
}
/** Refreshes content queries for all directives in the given view. */
function refreshContentQueries(tView, lView) {
if (tView.contentQueries != null) {
setCurrentQueryIndex(0);
for (var i = 0; i < tView.contentQueries.length; i++) {
var directiveDefIdx = tView.contentQueries[i];
var directiveDef = tView.data[directiveDefIdx];
ngDevMode &&
assertDefined(directiveDef.contentQueries, 'contentQueries function should be defined');
directiveDef.contentQueries(2 /* Update */, lView[directiveDefIdx], directiveDefIdx);
}
}
}
/** Refreshes child components in the current view. */
function refreshChildComponents(components) {
if (components != null) {
for (var i = 0; i < components.length; i++) {
componentRefresh(components[i]);
}
}
}
/**
* Creates a native element from a tag name, using a renderer.
* @param name the tag name
* @param overriddenRenderer Optional A renderer to override the default one
* @returns the element created
*/
export function elementCreate(name, overriddenRenderer) {
var native;
var rendererToUse = overriddenRenderer || getLView()[RENDERER];
var namespace = getNamespace();
if (isProceduralRenderer(rendererToUse)) {
native = rendererToUse.createElement(name, namespace);
}
else {
if (namespace === null) {
native = rendererToUse.createElement(name);
}
else {
native = rendererToUse.createElementNS(namespace, name);
}
}
return native;
}
export function createLView(parentLView, tView, context, flags, host, tHostNode, rendererFactory, renderer, sanitizer, injector) {
var lView = ngDevMode ? cloneToLView(tView.blueprint) : 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] = (rendererFactory || parentLView && parentLView[RENDERER_FACTORY]);
ngDevMode && assertDefined(lView[RENDERER_FACTORY], 'RendererFactory is required');
lView[RENDERER] = (renderer || parentLView && parentLView[RENDERER]);
ngDevMode && assertDefined(lView[RENDERER], 'Renderer is required');
lView[SANITIZER] = sanitizer || parentLView && parentLView[SANITIZER] || null;
lView[INJECTOR] = injector || parentLView && parentLView[INJECTOR] || null;
lView[T_HOST] = tHostNode;
ngDevMode && attachLViewDebug(lView);
return lView;
}
export function getOrCreateTNode(tView, tHostNode, index, type, name, attrs) {
// Keep this function short, so that the VM will inline it.
var adjustedIndex = index + HEADER_OFFSET;
var tNode = tView.data[adjustedIndex] ||
createTNodeAtIndex(tView, tHostNode, adjustedIndex, type, name, attrs, index);
setPreviousOrParentTNode(tNode, true);
return tNode;
}
function createTNodeAtIndex(tView, tHostNode, adjustedIndex, type, name, attrs, index) {
var previousOrParentTNode = getPreviousOrParentTNode();
var isParent = getIsParent();
var 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.
var parentInSameView = parent && parent !== tHostNode;
var tParentNode = parentInSameView ? parent : null;
var tNode = tView.data[adjustedIndex] =
createTNode(tParentNode, type, adjustedIndex, name, attrs);
// 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
if (index === 0 || !tView.firstChild) {
tView.firstChild = tNode;
}
// Now link ourselves into the tree.
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;
}
export 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.
var tNode = tView.node;
if (tNode == null) {
ngDevMode && tParentNode &&
assertNodeOfPossibleTypes(tParentNode, 3 /* Element */, 0 /* Container */);
tView.node = tNode = createTNode(tParentNode, //
2 /* View */, index, null, null);
}
return lView[T_HOST] = 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.
*/
export function allocExpando(view, numSlotsToAlloc) {
var tView = view[TVIEW];
if (tView.firstTemplatePass) {
for (var i = 0; i < numSlotsToAlloc; i++) {
tView.blueprint.push(null);
tView.data.push(null);
view.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
//////////////////////////
/**
* Used for creating the LViewNode of a dynamic embedded view,
* either through ViewContainerRef.createEmbeddedView() or TemplateRef.createEmbeddedView().
* Such lViewNode will then be renderer with renderEmbeddedTemplate() (see below).
*/
export function createEmbeddedViewAndNode(tView, context, declarationView, queries, injectorIndex) {
var _isParent = getIsParent();
var _previousOrParentTNode = getPreviousOrParentTNode();
setPreviousOrParentTNode(null, true);
var lView = createLView(declarationView, tView, context, 16 /* CheckAlways */, null, null);
lView[DECLARATION_VIEW] = declarationView;
if (queries) {
lView[QUERIES] = queries.createView();
}
assignTViewNodeToLView(tView, null, -1, lView);
if (tView.firstTemplatePass) {
tView.node.injectorIndex = injectorIndex;
}
setPreviousOrParentTNode(_previousOrParentTNode, _isParent);
return lView;
}
/**
* Used for rendering embedded views (e.g. dynamically created views)
*
* Dynamically created views must store/retrieve their TViews differently from component views
* because their template functions are nested in the template functions of their hosts, creating
* closures. If their host template happens to be an embedded template in a loop (e.g. ngFor
* inside
* an ngFor), the nesting would mean we'd have multiple instances of the template function, so we
* can't store TViews in the template function itself (as we do for comps). Instead, we store the
* TView for dynamically created views on their host TNode, which only has one instance.
*/
export function renderEmbeddedTemplate(viewToRender, tView, context) {
var _isParent = getIsParent();
var _previousOrParentTNode = getPreviousOrParentTNode();
var oldView;
if (viewToRender[FLAGS] & 512 /* IsRoot */) {
// This is a root view inside the view tree
tickRootContext(getRootContext(viewToRender));
}
else {
// Will become true if the `try` block executes with no errors.
var safeToRunHooks = false;
try {
setPreviousOrParentTNode(null, true);
oldView = enterView(viewToRender, viewToRender[T_HOST]);
resetPreOrderHookFlags(viewToRender);
executeTemplate(viewToRender, tView.template, getRenderFlags(viewToRender), context);
// 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 firstTemplatePass. If we don't set it here, instances will perform directive
// matching, etc again and again.
viewToRender[TVIEW].firstTemplatePass = false;
refreshDescendantViews(viewToRender);
safeToRunHooks = true;
}
finally {
leaveView(oldView, safeToRunHooks);
setPreviousOrParentTNode(_previousOrParentTNode, _isParent);
}
}
}
export function renderComponentOrTemplate(hostView, context, templateFn) {
var rendererFactory = hostView[RENDERER_FACTORY];
var oldView = enterView(hostView, hostView[T_HOST]);
var normalExecutionPath = !getCheckNoChangesMode();
var creationModeIsActive = isCreationMode(hostView);
// Will become true if the `try` block executes with no errors.
var safeToRunHooks = false;
try {
if (normalExecutionPath && !creationModeIsActive && rendererFactory.begin) {
rendererFactory.begin();
}
if (creationModeIsActive) {
// creation mode pass
templateFn && executeTemplate(hostView, templateFn, 1 /* Create */, context);
refreshDescendantViews(hostView);
hostView[FLAGS] &= ~4 /* CreationMode */;
}
// update mode pass
resetPreOrderHookFlags(hostView);
templateFn && executeTemplate(hostView, templateFn, 2 /* Update */, context);
refreshDescendantViews(hostView);
safeToRunHooks = true;
}
finally {
if (normalExecutionPath && !creationModeIsActive && rendererFactory.end) {
rendererFactory.end();
}
leaveView(oldView, safeToRunHooks);
}
}
function executeTemplate(lView, templateFn, rf, context) {
ɵɵnamespaceHTML();
var prevSelectedIndex = getSelectedIndex();
try {
setActiveHostElement(null);
if (rf & 2 /* Update */) {
// When we're updating, have an inherent ɵɵselect(0) so we don't have to generate that
// instruction for most update blocks
selectInternal(lView, 0);
}
templateFn(rf, context);
}
finally {
setSelectedIndex(prevSelectedIndex);
}
}
/**
* This function returns the default configuration of rendering flags depending on when the
* template is in creation mode or update mode. Update block and create block are
* always run separately.
*/
function getRenderFlags(view) {
return isCreationMode(view) ? 1 /* Create */ : 2 /* Update */;
}
//////////////////////////
//// Element
//////////////////////////
/**
* Appropriately sets `stylingTemplate` on a TNode
*
* Does not apply styles to DOM nodes
*
* @param tNode The node whose `stylingTemplate` to set
* @param attrs The attribute array source to set the attributes from
* @param attrsStartIndex Optional start index to start processing the `attrs` from
*/
export function setNodeStylingTemplate(tView, tNode, attrs, attrsStartIndex) {
if (tView.firstTemplatePass && !tNode.stylingTemplate) {
var stylingAttrsStartIndex = attrsStylingIndexOf(attrs, attrsStartIndex);
if (stylingAttrsStartIndex >= 0) {
tNode.stylingTemplate = initializeStaticStylingContext(attrs, stylingAttrsStartIndex);
}
}
}
export function executeContentQueries(tView, tNode, lView) {
if (isContentQueryHost(tNode)) {
var start = tNode.directiveStart;
var end = tNode.directiveEnd;
for (var directiveIndex = start; directiveIndex < end; directiveIndex++) {
var def = tView.data[directiveIndex];
if (def.contentQueries) {
def.contentQueries(1 /* Create */, lView[directiveIndex], directiveIndex);
}
}
}
}
/**
* Creates directive instances and populates local refs.
*
* @param localRefs Local refs of the node in question
* @param localRefExtractor mapping function that extracts local ref value from TNode
*/
export function createDirectivesAndLocals(tView, lView, localRefs, localRefExtractor) {
if (localRefExtractor === void 0) { localRefExtractor = getNativeByTNode; }
if (!getBindingsEnabled())
return;
var previousOrParentTNode = getPreviousOrParentTNode();
if (tView.firstTemplatePass) {
ngDevMode && ngDevMode.firstTemplatePass++;
resolveDirectives(tView, lView, findDirectiveMatches(tView, lView, previousOrParentTNode), previousOrParentTNode, localRefs || null);
}
instantiateAllDirectives(tView, lView, previousOrParentTNode);
invokeDirectivesHostBindings(tView, lView, previousOrParentTNode);
saveResolvedLocalsInData(lView, previousOrParentTNode, localRefExtractor);
setActiveHostElement(null);
}
/**
* 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().
*/
function saveResolvedLocalsInData(viewData, tNode, localRefExtractor) {
var localNames = tNode.localNames;
if (localNames) {
var localIndex = tNode.index + 1;
for (var i = 0; i < localNames.length; i += 2) {
var index = localNames[i + 1];
var value = index === -1 ?
localRefExtractor(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
* @returns TView
*/
export function getOrCreateTView(def) {
return def.tView || (def.tView = createTView(-1, def.template, def.consts, def.vars, def.directiveDefs, def.pipeDefs, def.viewQuery, def.schemas));
}
/**
* Creates a TView instance
*
* @param viewIndex The viewBlockId for inline views, or -1 if it's a component/dynamic
* @param templateFn Template function
* @param consts The number of nodes, local refs, and pipes in this template
* @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
*/
export function createTView(viewIndex, templateFn, consts, vars, directives, pipes, viewQuery, schemas) {
ngDevMode && ngDevMode.tView++;
var bindingStartIndex = HEADER_OFFSET + consts;
// 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.
var initialViewLength = bindingStartIndex + vars;
var blueprint = createViewBlueprint(bindingStartIndex, initialViewLength);
return blueprint[TVIEW] = ngDevMode ?
new TViewConstructor(viewIndex, // id: number,
blueprint, // blueprint: LView,
templateFn, // template: ComponentTemplate<{}>|null,
viewQuery, // viewQuery: ViewQueriesFunction<{}>|null,
null, // node: TViewNode|TElementNode|null,
cloneToTViewData(blueprint).fill(null, bindingStartIndex), // data: TData,
bindingStartIndex, // bindingStartIndex: number,
initialViewLength, // viewQueryStartIndex: number,
initialViewLength, // expandoStartIndex: number,
null, // expandoInstructions: ExpandoInstructions|null,
true, // firstTemplatePass: 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: HookData|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) :
{
id: viewIndex,
blueprint: blueprint,
template: templateFn,
viewQuery: viewQuery,
node: null,
data: blueprint.slice().fill(null, bindingStartIndex),
bindingStartIndex: bindingStartIndex,
viewQueryStartIndex: initialViewLength,
expandoStartIndex: initialViewLength,
expandoInstructions: null,
firstTemplatePass: 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,
};
}
function createViewBlueprint(bindingStartIndex, initialViewLength) {
var blueprint = new (ngDevMode ? LViewBlueprint : Array)(initialViewLength)
.fill(null, 0, bindingStartIndex)
.fill(NO_CHANGE, bindingStartIndex);
blueprint[BINDING_INDEX] = bindingStartIndex;
return blueprint;
}
export function createError(text, token) {
return new Error("Renderer: " + text + " [" + stringifyForError(token) + "]");
}
/**
* Locates the host native element, used for bootstrapping existing nodes into rendering pipeline.
*
* @param elementOrSelector Render element or CSS selector to locate the element.
*/
export function locateHostElement(factory, elementOrSelector) {
var defaultRenderer = factory.createRenderer(null, null);
var rNode = typeof elementOrSelector === 'string' ?
(isProceduralRenderer(defaultRenderer) ?
defaultRenderer.selectRootElement(elementOrSelector) :
defaultRenderer.querySelector(elementOrSelector)) :
elementOrSelector;
if (ngDevMode && !rNode) {
if (typeof elementOrSelector === 'string') {
throw createError('Host node with selector not found:', elementOrSelector);
}
else {
throw createError('Host node is required:', elementOrSelector);
}
}
return rNode;
}
/**
* 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
*/
export function storeCleanupWithContext(lView, context, cleanupFn) {
var lCleanup = getCleanup(lView);
lCleanup.push(context);
if (lView[TVIEW].firstTemplatePass) {
getTViewCleanup(lView).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.
*/
export function storeCleanupFn(view, cleanupFn) {
getCleanup(view).push(cleanupFn);
if (view[TVIEW].firstTemplatePass) {
getTViewCleanup(view).push(view[CLEANUP].length - 1, null);
}
}
/**
* Constructs a TNode object from the arguments.
*
* @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
* @param tViews Any TViews attached to this node
* @returns the TNode object
*/
export function createTNode(tParent, type, adjustedIndex, tagName, attrs) {
ngDevMode && ngDevMode.tNode++;
return {
type: type,
index: adjustedIndex,
injectorIndex: tParent ? tParent.injectorIndex : -1,
directiveStart: -1,
directiveEnd: -1,
propertyMetadataStartIndex: -1,
propertyMetadataEndIndex: -1,
flags: 0,
providerIndexes: 0,
tagName: tagName,
attrs: attrs,
localNames: null,
initialInputs: undefined,
inputs: undefined,
outputs: undefined,
tViews: null,
next: null,
projectionNext: null,
child: null,
parent: tParent,
stylingTemplate: null,
projection: null,
onElementCreationFns: null,
// TODO (matsko): rename this to `styles` once the old styling impl is gone
newStyles: null,
// TODO (matsko): rename this to `classes` once the old styling impl is gone
newClasses: null,
};
}
/**
* Consolidates all inputs or outputs of all directives on this logical node.
*
* @param tNode
* @param direction whether to consider inputs or outputs
* @returns PropertyAliases|null aggregate of all properties if any, `null` otherwise
*/
export function generatePropertyAliases(tNode, direction) {
var tView = getLView()[TVIEW];
var propStore = null;
var start = tNode.directiveStart;
var end = tNode.directiveEnd;
if (end > start) {
var isInput = direction === 0 /* Input */;
var defs = tView.data;
for (var i = start; i < end; i++) {
var directiveDef = defs[i];
var propertyAliasMap = isInput ? directiveDef.inputs : directiveDef.outputs;
for (var publicName in propertyAliasMap) {
if (propertyAliasMap.hasOwnProperty(publicName)) {
propStore = propStore || {};
var internalName = propertyAliasMap[publicName];
var hasProperty = propStore.hasOwnProperty(publicName);
hasProperty ? propStore[publicName].push(i, publicName, internalName) :
(propStore[publicName] = [i, publicName, internalName]);
}
}
}
}
return propStore;
}
/**
* Mapping between attributes names that don't correspond to their element property names.
* Note: this mapping has to be kept in sync with the equally named mapping in the template
* type-checking machinery of ngtsc.
*/
var ATTR_TO_PROP = {
'class': 'className',
'for': 'htmlFor',
'formaction': 'formAction',
'innerHtml': 'innerHTML',
'readonly': 'readOnly',
'tabindex': 'tabIndex',
};
export function elementPropertyInternal(index, propName, value, sanitizer, nativeOnly, loadRendererFn) {
ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
var lView = getLView();
var element = getNativeByIndex(index, lView);
var tNode = getTNode(index, lView);
var inputData;
var dataValue;
if (!nativeOnly && (inputData = initializeTNodeInputs(tNode)) &&
(dataValue = inputData[propName])) {
setInputsForProperty(lView, dataValue, value);
if (isComponent(tNode))
markDirtyIfOnPush(lView, index + HEADER_OFFSET);
if (ngDevMode) {
if (tNode.type === 3 /* Element */ || tNode.type === 0 /* Container */) {
/**
* dataValue is an array containing runtime input or output names for the directives:
* i+0: directive instance index
* i+1: publicName
* i+2: privateName
*
* e.g. [0, 'change', 'change-minified']
* we want to set the reflected property with the privateName: dataValue[i+2]
*/
for (var i = 0; i < dataValue.length; i += 3) {
setNgReflectProperty(lView, element, tNode.type, dataValue[i + 2], value);
}
}
}
}
else if (tNode.type === 3 /* Element */) {
propName = ATTR_TO_PROP[propName] || propName;
if (ngDevMode) {
validateAgainstEventProperties(propName);
validateAgainstUnknownProperties(lView, element, propName, tNode);
ngDevMode.rendererSetProperty++;
}
savePropertyDebugData(tNode, lView, propName, lView[TVIEW].data, nativeOnly);
var renderer = loadRendererFn ? loadRendererFn(tNode, lView) : lView[RENDERER];
// 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 ? sanitizer(value, tNode.tagName || '', propName) : value;
if (isProceduralRenderer(renderer)) {
renderer.setProperty(element, propName, value);
}
else if (!isAnimationProp(propName)) {
element.setProperty ? element.setProperty(propName, value) :
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(lView, tNode.tagName)) {
throw createUnknownPropertyError(propName, tNode);
}
}
}
/** If node is an OnPush component, marks its LView dirty. */
function markDirtyIfOnPush(lView, viewIndex) {
ngDevMode && assertLView(lView);
var childComponentLView = getComponentViewByIndex(viewIndex, lView);
if (!(childComponentLView[FLAGS] & 16 /* CheckAlways */)) {
childComponentLView[FLAGS] |= 64 /* Dirty */;
}
}
export function setNgReflectProperty(lView, element, type, attrName, value) {
var _a;
var renderer = lView[RENDERER];
attrName = normalizeDebugBindingName(attrName);
var debugValue = normalizeDebugBindingValue(value);
if (type === 3 /* Element */) {
if (value == null) {
isProceduralRenderer(renderer) ? renderer.removeAttribute(element, attrName) :
element.removeAttribute(attrName);
}
else {
isProceduralRenderer(renderer) ?
renderer.setAttribute(element, attrName, debugValue) :
element.setAttribute(attrName, debugValue);
}
}
else {
var textContent = "bindings=" + JSON.stringify((_a = {}, _a[attrName] = debugValue, _a), null, 2);
if (isProceduralRenderer(renderer)) {
renderer.setValue(element, textContent);
}
else {
element.textContent = textContent;
}
}
}
function validateAgainstUnknownProperties(hostView, element, propName, tNode) {
// If the tag matches any of the schemas we shouldn't throw.
if (matchingSchemas(hostView, tNode.tagName)) {
return;
}
// If prop is not a known property of the HTML element...
if (!(propName in element) &&
// and we are in a browser context... (web worker nodes should be skipped)
typeof Node === 'function' && element instanceof Node &&
// and isn't a synthetic animation property...
propName[0] !== ANIMATION_PROP_PREFIX) {
// ... it is probably a user error and we should throw.
throw createUnknownPropertyError(propName, tNode);
}
}
function matchingSchemas(hostView, tagName) {
var schemas = hostView[TVIEW].schemas;
if (schemas !== null) {
for (var i = 0; i < schemas.length; i++) {
var schema = schemas[i];
if (schema === NO_ERRORS_SCHEMA ||
schema === CUSTOM_ELEMENTS_SCHEMA && tagName && tagName.indexOf('-') > -1) {
return true;
}
}
}
return false;
}
/**
* Stores debugging data for this property binding on first template pass.
* This enables features like DebugElement.properties.
*/
function savePropertyDebugData(tNode, lView, propName, tData, nativeOnly) {
var lastBindingIndex = lView[BINDING_INDEX] - 1;
// Bind/interpolation functions save binding metadata in the last binding index,
// but leave the property name blank. If the interpolation delimiter is at the 0
// index, we know that this is our first pass and the property name still needs to
// be set.
var bindingMetadata = tData[lastBindingIndex];
if (bindingMetadata[0] == INTERPOLATION_DELIMITER) {
tData[lastBindingIndex] = propName + bindingMetadata;
// We don't want to store indices for host bindings because they are stored in a
// different part of LView (the expando section).
if (!nativeOnly) {
if (tNode.propertyMetadataStartIndex == -1) {
tNode.propertyMetadataStartIndex = lastBindingIndex;
}
tNode.propertyMetadataEndIndex = lastBindingIndex + 1;
}
}
}
/**
* Creates an error that should be thrown when encountering an unknown property on an element.
* @param propName Name of the invalid property.
* @param tNode Node on which we encountered the error.
*/
function createUnknownPropertyError(propName, tNode) {
return new Error("Template error: Can't bind to '" + propName + "' since it isn't a known property of '" + tNode.tagName + "'.");
}
/**
* Instantiate a root component.
*/
export function instantiateRootComponent(tView, viewData, def) {
var rootTNode = getPreviousOrParentTNode();
if (tView.firstTemplatePass) {
if (def.providersResolver)
def.providersResolver(def);
generateExpandoInstructionBlock(tView, rootTNode, 1);
baseResolveDirective(tView, viewData, def, def.factory);
}
var directive = getNodeInjectable(tView.data, viewData, viewData.length - 1, rootTNode);
postProcessBaseDirective(viewData, rootTNode, directive);
return directive;
}
/**
* Resolve the matched directives on a node.
*/
function resolveDirectives(tView, viewData, directives, tNode, localRefs) {
// Please make sure to have explicit type for `exportsMap`. Inferred type triggers bug in
// tsickle.
ngDevMode && assertEqual(tView.firstTemplatePass, true, 'should run on first template pass only');
var exportsMap = localRefs ? { '': -1 } : null;
if (directives) {
initNodeFlags(tNode, tView.data.length, directives.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 (var i = 0; i < directives.length; i++) {
var def = directives[i];
if (def.providersResolver)
def.providersResolver(def);
}
generateExpandoInstructionBlock(tView, tNode, directives.length);
var initialPreOrderHooksLength = (tView.preOrderHooks && tView.preOrderHooks.length) || 0;
var initialPreOrderCheckHooksLength = (tView.preOrderCheckHooks && tView.preOrderCheckHooks.length) || 0;
var nodeIndex = tNode.index - HEADER_OFFSET;
for (var i = 0; i < directives.length; i++) {
var def = directives[i];
var directiveDefIdx = tView.data.length;
baseResolveDirective(tView, viewData, def, def.factory);
saveNameToExportMap(tView.data.length - 1, def, exportsMap);
// Init hooks are queued now so ngOnInit is called in host components before
// any projected components.
registerPreOrderHooks(directiveDefIdx, def, tView, nodeIndex, initialPreOrderHooksLength, initialPreOrderCheckHooksLength);
}
}
if (exportsMap)
cacheMatchingLocalNames(tNode, localRefs, exportsMap);
}
/**
* Instantiate all the directives that were previously resolved on the current node.
*/
function instantiateAllDirectives(tView, lView, tNode) {
var start = tNode.directiveStart;
var end = tNode.directiveEnd;
if (!tView.firstTemplatePass && start < end) {
getOrCreateNodeInjectorForNode(tNode, lView);
}
for (var i = start; i < end; i++) {
var def = tView.data[i];
if (isComponentDef(def)) {
addComponentLogic(lView, tNode, def);
}
var directive = getNodeInjectable(tView.data, lView, i, tNode);
postProcessDirective(lView, directive, def, i);
}
}
function invokeDirectivesHostBindings(tView, viewData, tNode) {
var start = tNode.directiveStart;
var end = tNode.directiveEnd;
var expando = tView.expandoInstructions;
var firstTemplatePass = tView.firstTemplatePass;
var elementIndex = tNode.index - HEADER_OFFSET;
var selectedIndex = getSelectedIndex();
try {
setActiveHostElement(elementIndex);
for (var i = start; i < end; i++) {
var def = tView.data[i];
var directive = viewData[i];
if (def.hostBindings) {
invokeHostBindingsInCreationMode(def, expando, directive, tNode, firstTemplatePass);
// Each directive gets a uniqueId value that is the same for both
// create and update calls when the hostBindings function is called. The
// directive uniqueId is not set anywhere--it is just incremented between
// each hostBindings call and is useful for helping instruction code
// uniquely determine which directive is currently active when executed.
incrementActiveDirectiveId();
}
else if (firstTemplatePass) {
expando.push(null);
}
}
}
finally {
setActiveHostElement(selectedIndex);
}
}
export function invokeHostBindingsInCreationMode(def, expando, directive, tNode, firstTemplatePass) {
var previousExpandoLength = expando.length;
setCurrentDirectiveDef(def);
var elementIndex = tNode.index - HEADER_OFFSET;
def.hostBindings(1 /* Create */, directive, elementIndex);
setCurrentDirectiveDef(null);
// `hostBindings` function may or may not contain `allocHostVars` call
// (e.g. it may not if it only contains host listeners), so we need to check whether
// `expandoInstructions` has changed and if not - we still push `hostBindings` to
// expando block, to make sure we execute it for DI cycle
if (previousExpandoLength === expando.length && firstTemplatePass) {
expando.push(def.hostBindings);
}
}
/**
* 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.
*/
export function generateExpandoInstructionBlock(tView, tNode, directiveCount) {
ngDevMode && assertEqual(tView.firstTemplatePass, true, 'Expando block should only be generated on first template pass.');
var elementIndex = -(tNode.index - HEADER_OFFSET);
var providerStartIndex = tNode.providerIndexes & 65535 /* ProvidersStartIndexMask */;
var providerCount = tView.data.length - providerStartIndex;
(tView.expandoInstructions || (tView.expandoInstructions = [])).push(elementIndex, providerCount, directiveCount);
}
/**
* Process a directive on the current node after its creation.
*/
function postProcessDirective(viewData, directive, def, directiveDefIdx) {
var previousOrParentTNode = getPreviousOrParentTNode();
postProcessBaseDirective(viewData, previousOrParentTNode, directive);
ngDevMode && assertDefined(previousOrParentTNode, 'previousOrParentTNode');
if (previousOrParentTNode && previousOrParentTNode.attrs) {
setInputsFromAttrs(directiveDefIdx, directive, def, previousOrParentTNode);
}
if (viewData[TVIEW].firstTemplatePass && def.contentQueries) {
previousOrParentTNode.flags |= 4 /* hasContentQuery */;
}
if (isComponentDef(def)) {
var componentView = getComponentViewByIndex(previousOrParentTNode.index, viewData);
componentView[CONTEXT] = directive;
}
}
/**
* A lighter version of postProcessDirective() that is used for the root component.
*/
function postProcessBaseDirective(lView, previousOrParentTNode, directive) {
var native = getNativeByTNode(previousOrParentTNode, lView);
ngDevMode && assertEqual(lView[BINDING_INDEX], lView[TVIEW].bindingStartIndex, 'directives should be created before any bindings');
ngDevMode && assertPreviousIsParent(getIsParent());
attachPatchData(directive, lView);
if (native) {
attachPatchData(native, lView);
}
}
/**
* 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.
*/
function findDirectiveMatches(tView, viewData, tNode) {
ngDevMode && assertEqual(tView.firstTemplatePass, true, 'should run on first template pass only');
var registry = tView.directiveRegistry;
var matches = null;
if (registry) {
for (var i = 0; i < registry.length; i++) {
var def = registry[i];
if (isNodeMatchingSelectorList(tNode, def.selectors, /* isProjectionMode */ false)) {
matches || (matches = ngDevMode ? new MatchesArray() : []);
diPublicInInjector(getOrCreateNodeInjectorForNode(getPreviousOrParentTNode(), viewData), viewData, def.type);
if (isComponentDef(def)) {
if (tNode.flags & 1 /* isComponent */)
throwMultipleComponentError(tNode);
tNode.flags = 1 /* isComponent */;
// The component is always stored first with directives after.
matches.unshift(def);
}
else {
matches.push(def);
}
}
}
}
return matches;
}
/** Stores index of component's host element so it will be queued for view refresh during CD. */
export function queueComponentIndexForCheck(previousOrParentTNode) {
var tView = getLView()[TVIEW];
ngDevMode &&
assertEqual(tView.firstTemplatePass, true, 'Should only be called in first template pass.');
(tView.components || (tView.components = ngDevMode ? new TViewComponents() : [])).push(previousOrParentTNode.index);
}
/** Caches local names and their matching directive indices for query and template lookups. */
function cacheMatchingLocalNames(tNode, localRefs, exportsMap) {
if (localRefs) {
var 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 (var i = 0; i < localRefs.length; i += 2) {
var 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.
*/
function saveNameToExportMap(index, def, exportsMap) {
if (exportsMap) {
if (def.exportAs) {
for (var i = 0; i < def.exportAs.length; i++) {
exportsMap[def.exportAs[i]] = index;
}
}
if (def.template)
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 index the initial index
*/
export function initNodeFlags(tNode, index, numberOfDirectives) {
var flags = tNode.flags;
ngDevMode && assertEqual(flags === 0 || flags === 1 /* isComponent */, true, 'expected node flags to not be initialized');
ngDevMode && assertNotEqual(numberOfDirectives, tNode.directiveEnd - tNode.directiveStart, 'Reached the max number of directives');
// When the first directive is created on a node, save the index
tNode.flags = flags & 1 /* isComponent */;
tNode.directiveStart = index;
tNode.directiveEnd = index + numberOfDirectives;
tNode.providerIndexes = index;
}
function baseResolveDirective(tView, viewData, def, directiveFactory) {
tView.data.push(def);
var nodeInjectorFactory = new NodeInjectorFactory(directiveFactory, isComponentDef(def), null);
tView.blueprint.push(nodeInjectorFactory);
viewData.push(nodeInjectorFactory);
}
function addComponentLogic(lView, previousOrParentTNode, def) {
var native = getNativeByTNode(previousOrParentTNode, lView);
var tView = getOrCreateTView(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.
var rendererFactory = lView[RENDERER_FACTORY];
var componentView = addToViewTree(lView, createLView(lView, tView, null, def.onPush ? 64 /* Dirty */ : 16 /* CheckAlways */, lView[previousOrParentTNode.index], previousOrParentTNode, rendererFactory, rendererFactory.createRenderer(native, def)));
componentView[T_HOST] =