refactor(ivy): queries should not rely on LNode (#25415)

PR Close #25415
This commit is contained in:
Kara Erickson 2018-08-09 10:00:07 -07:00 committed by Ben Lesh
parent 209cc7e1b0
commit 2b128a47b9
8 changed files with 384 additions and 202 deletions

View File

@ -584,15 +584,10 @@ export function getOrCreateContainerRef(di: LInjector): viewEngine.ViewContainer
const hostParent = getParentLNode(vcRefHost) !; const hostParent = getParentLNode(vcRefHost) !;
const lContainer = createLContainer(hostParent, vcRefHost.view, true); const lContainer = createLContainer(hostParent, vcRefHost.view, true);
const comment = vcRefHost.view[RENDERER].createComment(ngDevMode ? 'container' : ''); const comment = vcRefHost.view[RENDERER].createComment(ngDevMode ? 'container' : '');
const lContainerNode: LContainerNode = createLNodeObject( const lContainerNode: LContainerNode =
TNodeType.Container, vcRefHost.view, hostParent, comment, lContainer, null); createLNodeObject(TNodeType.Container, vcRefHost.view, hostParent, comment, lContainer);
appendChild(hostParent, comment, vcRefHost.view); appendChild(hostParent, comment, vcRefHost.view);
if (vcRefHost.queries) {
lContainerNode.queries = vcRefHost.queries.container();
}
const hostTNode = vcRefHost.tNode as TElementNode | TContainerNode; const hostTNode = vcRefHost.tNode as TElementNode | TContainerNode;
if (!hostTNode.dynamicContainerNode) { if (!hostTNode.dynamicContainerNode) {
hostTNode.dynamicContainerNode = hostTNode.dynamicContainerNode =

View File

@ -175,12 +175,18 @@ let currentQueries: LQueries|null;
* - when creating content queries (inb this previousOrParentNode points to a node on which we * - when creating content queries (inb this previousOrParentNode points to a node on which we
* create content queries). * create content queries).
*/ */
export function getCurrentQueries(QueryType: {new (): LQueries}): LQueries { export function getOrCreateCurrentQueries(
// top level variables should not be exported for performance reasons (PERF_NOTES.md) QueryType: {new (parent: null, shallow: null, deep: null): LQueries}): LQueries {
return currentQueries || const tNode = previousOrParentNode.tNode;
(currentQueries =
(previousOrParentNode.queries && previousOrParentNode.queries.clone() || // if this is the first content query on a node, any existing LQueries needs to be cloned
new QueryType())); // in subsequent template passes, the cloning occurs before directive instantiation.
if (previousOrParentNode.data !== viewData && !isContentQueryHost(tNode)) {
currentQueries && (currentQueries = currentQueries.clone());
tNode.flags |= TNodeFlags.hasContentQuery;
}
return currentQueries || (currentQueries = new QueryType(null, null, null));
} }
/** /**
@ -392,14 +398,13 @@ export function createLViewData<T>(
*/ */
export function createLNodeObject( export function createLNodeObject(
type: TNodeType, currentView: LViewData, parent: LNode | null, type: TNodeType, currentView: LViewData, parent: LNode | null,
native: RText | RElement | RComment | null, state: any, native: RText | RElement | RComment | null,
queries: LQueries | null): LElementNode&LTextNode&LViewNode&LContainerNode&LProjectionNode { state: any): LElementNode&LTextNode&LViewNode&LContainerNode&LProjectionNode {
return { return {
native: native as any, native: native as any,
view: currentView, view: currentView,
nodeInjector: parent ? parent.nodeInjector : null, nodeInjector: parent ? parent.nodeInjector : null,
data: state, data: state,
queries: queries,
tNode: null !, tNode: null !,
dynamicLContainerNode: null dynamicLContainerNode: null
}; };
@ -442,12 +447,9 @@ export function createLNode(
// so it's only set if the view is the same. // so it's only set if the view is the same.
const tParent = const tParent =
parent && parent.view === viewData ? parent.tNode as TElementNode | TContainerNode : null; parent && parent.view === viewData ? parent.tNode as TElementNode | TContainerNode : null;
let queries =
(isParent ? currentQueries : previousOrParentNode && previousOrParentNode.queries) ||
parent && parent.queries && parent.queries.child();
const isState = state != null; const isState = state != null;
const node = const node = createLNodeObject(type, viewData, parent, native, isState ? state as any : null);
createLNodeObject(type, viewData, parent, native, isState ? state as any : null, queries);
if (index === -1 || type === TNodeType.View) { if (index === -1 || type === TNodeType.View) {
// View nodes are not stored in data because they can be added / removed at runtime (which // View nodes are not stored in data because they can be added / removed at runtime (which
@ -477,7 +479,6 @@ export function createLNode(
// Now link ourselves into the tree. // Now link ourselves into the tree.
if (isParent) { if (isParent) {
currentQueries = null;
if (previousOrParentNode.tNode.child == null && previousOrParentNode.view === viewData || if (previousOrParentNode.tNode.child == null && previousOrParentNode.view === viewData ||
previousOrParentNode.tNode.type === TNodeType.View) { previousOrParentNode.tNode.type === TNodeType.View) {
// We are in the same view, which means we are adding content node to the parent View. // We are in the same view, which means we are adding content node to the parent View.
@ -747,8 +748,9 @@ export function elementContainerEnd(): void {
} }
ngDevMode && assertNodeType(previousOrParentNode, TNodeType.ElementContainer); ngDevMode && assertNodeType(previousOrParentNode, TNodeType.ElementContainer);
const queries = previousOrParentNode.queries;
queries && queries.addNode(previousOrParentNode); currentQueries && (currentQueries = currentQueries.addNode(previousOrParentNode));
queueLifecycleHooks(previousOrParentNode.tNode.flags, tView); queueLifecycleHooks(previousOrParentNode.tNode.flags, tView);
} }
@ -907,6 +909,10 @@ export function initChangeDetectorIfExisting(
} }
} }
export function isContentQueryHost(tNode: TNode): boolean {
return (tNode.flags & TNodeFlags.hasContentQuery) !== 0;
}
export function isComponent(tNode: TNode): boolean { export function isComponent(tNode: TNode): boolean {
return (tNode.flags & TNodeFlags.isComponent) === TNodeFlags.isComponent; return (tNode.flags & TNodeFlags.isComponent) === TNodeFlags.isComponent;
} }
@ -915,9 +921,16 @@ export function isComponent(tNode: TNode): boolean {
* This function instantiates the given directives. * This function instantiates the given directives.
*/ */
function instantiateDirectivesDirectly() { function instantiateDirectivesDirectly() {
ngDevMode && assertEqual(
firstTemplatePass, false,
`Directives should only be instantiated directly after first template pass`);
const tNode = previousOrParentNode.tNode; const tNode = previousOrParentNode.tNode;
const count = tNode.flags & TNodeFlags.DirectiveCountMask; const count = tNode.flags & TNodeFlags.DirectiveCountMask;
if (isContentQueryHost(tNode) && currentQueries) {
currentQueries = currentQueries.clone();
}
if (count > 0) { if (count > 0) {
const start = tNode.flags >> TNodeFlags.DirectiveStartingIndexShift; const start = tNode.flags >> TNodeFlags.DirectiveStartingIndexShift;
const end = start + count; const end = start + count;
@ -1233,8 +1246,7 @@ export function elementEnd(): void {
previousOrParentNode = getParentLNode(previousOrParentNode) as LElementNode; previousOrParentNode = getParentLNode(previousOrParentNode) as LElementNode;
} }
ngDevMode && assertNodeType(previousOrParentNode, TNodeType.Element); ngDevMode && assertNodeType(previousOrParentNode, TNodeType.Element);
const queries = previousOrParentNode.queries; currentQueries && (currentQueries = currentQueries.addNode(previousOrParentNode));
queries && queries.addNode(previousOrParentNode);
queueLifecycleHooks(previousOrParentNode.tNode.flags, tView); queueLifecycleHooks(previousOrParentNode.tNode.flags, tView);
currentElementNode = null; currentElementNode = null;
} }
@ -1853,17 +1865,17 @@ export function container(
// because views can be removed and re-inserted. // because views can be removed and re-inserted.
addToViewTree(viewData, index + HEADER_OFFSET, node.data); addToViewTree(viewData, index + HEADER_OFFSET, node.data);
const queries = node.queries; if (currentQueries) {
if (queries) {
// prepare place for matching nodes from views inserted into a given container // prepare place for matching nodes from views inserted into a given container
lContainer[QUERIES] = queries.container(); lContainer[QUERIES] = currentQueries.container();
} }
createDirectivesAndLocals(localRefs); createDirectivesAndLocals(localRefs);
isParent = false; isParent = false;
ngDevMode && assertNodeType(previousOrParentNode, TNodeType.Container); ngDevMode && assertNodeType(previousOrParentNode, TNodeType.Container);
queries && queries.addNode(node); // check if a given container node matches // check if a given container node matches
currentQueries && (currentQueries = currentQueries.addNode(node));
queueLifecycleHooks(node.tNode.flags, tView); queueLifecycleHooks(node.tNode.flags, tView);
} }

View File

@ -42,8 +42,11 @@ export const enum TNodeFlags {
/** This bit is set if the node has been projected */ /** This bit is set if the node has been projected */
isProjected = 0b00000000000000000010000000000000, isProjected = 0b00000000000000000010000000000000,
/** This bit is set if the node has any content queries */
hasContentQuery = 0b00000000000000000100000000000000,
/** The index of the first directive on this node is encoded on the most significant bits */ /** The index of the first directive on this node is encoded on the most significant bits */
DirectiveStartingIndexShift = 14, DirectiveStartingIndexShift = 15,
} }
/** /**
@ -89,13 +92,6 @@ export interface LNode {
/** The injector associated with this node. Necessary for DI. */ /** The injector associated with this node. Necessary for DI. */
nodeInjector: LInjector|null; nodeInjector: LInjector|null;
/**
* Optional set of queries that track query-related events for this node.
*
* If present the node creation/updates are reported to the `LQueries`.
*/
queries: LQueries|null;
/** /**
* Pointer to the corresponding TNode object, which stores static * Pointer to the corresponding TNode object, which stores static
* data about this node. * data about this node.

View File

@ -13,26 +13,27 @@ import {LNode} from './node';
/** Used for tracking queries (e.g. ViewChild, ContentChild). */ /** Used for tracking queries (e.g. ViewChild, ContentChild). */
export interface LQueries { export interface LQueries {
/** /**
* Ask queries to prepare copy of itself. This assures that tracking new queries on child nodes * The parent LQueries instance.
*
* When there is a content query, a new LQueries instance is created to avoid mutating any
* existing LQueries. After we are done searching content children, the parent property allows
* us to traverse back up to the original LQueries instance to continue to search for matches
* in the main view.
*/
parent: LQueries|null;
/**
* Ask queries to prepare copy of itself. This assures that tracking new queries on content nodes
* doesn't mutate list of queries tracked on a parent node. We will clone LQueries before * doesn't mutate list of queries tracked on a parent node. We will clone LQueries before
* constructing content queries. * constructing content queries.
*/ */
clone(): LQueries|null; clone(): LQueries;
/**
* Used to ask queries if those should be cloned to the child element.
*
* For example in the case of deep queries the `child()` returns
* queries for the child node. In case of shallow queries it returns
* `null`.
*/
child(): LQueries|null;
/** /**
* Notify `LQueries` that a new `LNode` has been created and needs to be added to query results * Notify `LQueries` that a new `LNode` has been created and needs to be added to query results
* if matching query predicate. * if matching query predicate.
*/ */
addNode(node: LNode): void; addNode(node: LNode): LQueries|null;
/** /**
* Notify `LQueries` that a new LContainer was added to ivy data structures. As a result we need * Notify `LQueries` that a new LContainer was added to ivy data structures. As a result we need

View File

@ -17,7 +17,7 @@ import {getSymbolIterator} from '../util';
import {assertDefined, assertEqual} from './assert'; import {assertDefined, assertEqual} from './assert';
import {ReadFromInjectorFn, getOrCreateNodeInjectorForNode} from './di'; import {ReadFromInjectorFn, getOrCreateNodeInjectorForNode} from './di';
import {assertPreviousIsParent, getCurrentQueries, store, storeCleanupWithContext} from './instructions'; import {assertPreviousIsParent, getOrCreateCurrentQueries, isContentQueryHost, store, storeCleanupWithContext} from './instructions';
import {DirectiveDefInternal, unusedValueExportToPlacateAjd as unused1} from './interfaces/definition'; import {DirectiveDefInternal, unusedValueExportToPlacateAjd as unused1} from './interfaces/definition';
import {LInjector, unusedValueExportToPlacateAjd as unused2} from './interfaces/injector'; import {LInjector, unusedValueExportToPlacateAjd as unused2} from './interfaces/injector';
import {LContainerNode, LElementNode, LNode, TNode, TNodeFlags, unusedValueExportToPlacateAjd as unused3} from './interfaces/node'; import {LContainerNode, LElementNode, LNode, TNode, TNodeFlags, unusedValueExportToPlacateAjd as unused3} from './interfaces/node';
@ -86,10 +86,9 @@ export interface LQuery<T> {
} }
export class LQueries_ implements LQueries { export class LQueries_ implements LQueries {
shallow: LQuery<any>|null = null; constructor(
deep: LQuery<any>|null = null; public parent: LQueries_|null, private shallow: LQuery<any>|null,
private deep: LQuery<any>|null) {}
constructor(deep?: LQuery<any>) { this.deep = deep == null ? null : deep; }
track<T>( track<T>(
queryList: viewEngine_QueryList<T>, predicate: Type<T>|string[], descend?: boolean, queryList: viewEngine_QueryList<T>, predicate: Type<T>|string[], descend?: boolean,
@ -101,103 +100,124 @@ export class LQueries_ implements LQueries {
} }
} }
clone(): LQueries|null { return this.deep ? new LQueries_(this.deep) : null; } clone(): LQueries { return new LQueries_(this, null, this.deep); }
child(): LQueries|null {
if (this.deep === null) {
// if we don't have any deep queries then no need to track anything more.
return null;
}
if (this.shallow === null) {
// DeepQuery: We can reuse the current state if the child state would be same as current
// state.
return this;
} else {
// We need to create new state
return new LQueries_(this.deep);
}
}
container(): LQueries|null { container(): LQueries|null {
let result: LQuery<any>|null = null; const shallowResults = copyQueriesToContainer(this.shallow);
let query = this.deep; const deepResults = copyQueriesToContainer(this.deep);
while (query) { return shallowResults || deepResults ? new LQueries_(this, shallowResults, deepResults) : null;
const containerValues: any[] = []; // prepare room for views
query.values.push(containerValues);
const clonedQuery: LQuery<any> = {
next: null,
list: query.list,
predicate: query.predicate,
values: containerValues,
containerValues: null
};
clonedQuery.next = result;
result = clonedQuery;
query = query.next;
}
return result ? new LQueries_(result) : null;
} }
createView(): LQueries|null { createView(): LQueries|null {
let result: LQuery<any>|null = null; const shallowResults = copyQueriesToView(this.shallow);
let query = this.deep; const deepResults = copyQueriesToView(this.deep);
while (query) { return shallowResults || deepResults ? new LQueries_(this, shallowResults, deepResults) : null;
const clonedQuery: LQuery<any> = {
next: null,
list: query.list,
predicate: query.predicate,
values: [],
containerValues: query.values
};
clonedQuery.next = result;
result = clonedQuery;
query = query.next;
}
return result ? new LQueries_(result) : null;
} }
insertView(index: number): void { insertView(index: number): void {
let query = this.deep; insertView(index, this.shallow);
while (query) { insertView(index, this.deep);
ngDevMode &&
assertDefined(
query.containerValues, 'View queries need to have a pointer to container values.');
query.containerValues !.splice(index, 0, query.values);
query = query.next;
}
} }
addNode(node: LNode): void { addNode(node: LNode): LQueries|null {
add(this.shallow, node);
add(this.deep, node); add(this.deep, node);
if (isContentQueryHost(node.tNode)) {
add(this.shallow, node);
if (node.tNode.parent && isContentQueryHost(node.tNode.parent)) {
// if node has a content query and parent also has a content query
// both queries need to check this node for shallow matches
add(this.parent !.shallow, node);
}
return this.parent;
}
isRootNodeOfQuery(node.tNode) && add(this.shallow, node);
return this;
} }
removeView(): void { removeView(): void {
let query = this.deep; removeView(this.shallow);
while (query) { removeView(this.deep);
ngDevMode &&
assertDefined(
query.containerValues, 'View queries need to have a pointer to container values.');
const containerValues = query.containerValues !;
const viewValuesIdx = containerValues.indexOf(query.values);
const removed = containerValues.splice(viewValuesIdx, 1);
// mark a query as dirty only when removed view had matching modes
ngDevMode && assertEqual(removed.length, 1, 'removed.length');
if (removed[0].length) {
query.list.setDirty();
}
query = query.next;
}
} }
} }
function isRootNodeOfQuery(tNode: TNode) {
return tNode.parent === null || isContentQueryHost(tNode.parent);
}
function copyQueriesToContainer(query: LQuery<any>| null): LQuery<any>|null {
let result: LQuery<any>|null = null;
while (query) {
const containerValues: any[] = []; // prepare room for views
query.values.push(containerValues);
const clonedQuery: LQuery<any> = {
next: result,
list: query.list,
predicate: query.predicate,
values: containerValues,
containerValues: null
};
result = clonedQuery;
query = query.next;
}
return result;
}
function copyQueriesToView(query: LQuery<any>| null): LQuery<any>|null {
let result: LQuery<any>|null = null;
while (query) {
const clonedQuery: LQuery<any> = {
next: result,
list: query.list,
predicate: query.predicate,
values: [],
containerValues: query.values
};
result = clonedQuery;
query = query.next;
}
return result;
}
function insertView(index: number, query: LQuery<any>| null) {
while (query) {
ngDevMode &&
assertDefined(
query.containerValues, 'View queries need to have a pointer to container values.');
query.containerValues !.splice(index, 0, query.values);
query = query.next;
}
}
function removeView(query: LQuery<any>| null) {
while (query) {
ngDevMode &&
assertDefined(
query.containerValues, 'View queries need to have a pointer to container values.');
const containerValues = query.containerValues !;
const viewValuesIdx = containerValues.indexOf(query.values);
const removed = containerValues.splice(viewValuesIdx, 1);
// mark a query as dirty only when removed view had matching modes
ngDevMode && assertEqual(removed.length, 1, 'removed.length');
if (removed[0].length) {
query.list.setDirty();
}
query = query.next;
}
}
/** /**
* Iterates over local names for a given node and returns directive index * Iterates over local names for a given node and returns directive index
* (or -1 if a local name points to an element). * (or -1 if a local name points to an element).
@ -418,7 +438,7 @@ export function query<T>(
read?: QueryReadType<T>| Type<T>): QueryList<T> { read?: QueryReadType<T>| Type<T>): QueryList<T> {
ngDevMode && assertPreviousIsParent(); ngDevMode && assertPreviousIsParent();
const queryList = new QueryList<T>(); const queryList = new QueryList<T>();
const queries = getCurrentQueries(LQueries_); const queries = getOrCreateCurrentQueries(LQueries_);
queries.track(queryList, predicate, descend, read); queries.track(queryList, predicate, descend, read);
storeCleanupWithContext(null, queryList, queryList.destroy); storeCleanupWithContext(null, queryList, queryList.destroy);
if (memoryIndex != null) { if (memoryIndex != null) {

View File

@ -62,9 +62,6 @@
{ {
"name": "PublicFeature" "name": "PublicFeature"
}, },
{
"name": "QUERIES"
},
{ {
"name": "RENDERER" "name": "RENDERER"
}, },

View File

@ -677,6 +677,9 @@
{ {
"name": "isComponent" "name": "isComponent"
}, },
{
"name": "isContentQueryHost"
},
{ {
"name": "isContextDirty" "name": "isContextDirty"
}, },

View File

@ -49,7 +49,7 @@ function isViewContainerRef(candidate: any): boolean {
} }
describe('query', () => { describe('query', () => {
it('should project query children', () => { it('should match projected query children', () => {
const Child = createComponent('child', function(rf: RenderFlags, ctx: any) {}); const Child = createComponent('child', function(rf: RenderFlags, ctx: any) {});
let child1 = null; let child1 = null;
@ -1617,7 +1617,9 @@ describe('query', () => {
it('should support combination of deep and shallow queries', () => { it('should support combination of deep and shallow queries', () => {
/** /**
* % if (exp) { "> * % if (exp) { ">
* <div #foo></div> * <div #foo>
* <div #foo></div>
* </div>
* % } * % }
* <span #foo></span> * <span #foo></span>
* class Cmpt { * class Cmpt {
@ -1639,7 +1641,9 @@ describe('query', () => {
let rf0 = embeddedViewStart(0); let rf0 = embeddedViewStart(0);
{ {
if (rf0 & RenderFlags.Create) { if (rf0 & RenderFlags.Create) {
element(0, 'div', null, ['foo', '']); elementStart(0, 'div', null, ['foo', '']);
{ element(2, 'div', null, ['foo', '']); }
elementEnd();
} }
} }
embeddedViewEnd(); embeddedViewEnd();
@ -1671,8 +1675,12 @@ describe('query', () => {
cmptInstance.exp = true; cmptInstance.exp = true;
detectChanges(cmptInstance); detectChanges(cmptInstance);
expect(deep.length).toBe(2); expect(deep.length).toBe(3);
expect(shallow.length).toBe(1);
// embedded % if blocks should behave the same way as *ngIf, namely they
// should match shallow queries on the first level of elements underneath
// the embedded view boundary.
expect(shallow.length).toBe(2);
cmptInstance.exp = false; cmptInstance.exp = false;
detectChanges(cmptInstance); detectChanges(cmptInstance);
@ -1773,43 +1781,66 @@ describe('query', () => {
}); });
describe('content', () => { describe('content', () => {
let withContentInstance: WithContentDirective|null;
let shallowCompInstance: ShallowComp|null;
it('should support content queries for directives', () => { beforeEach(() => {
let withContentInstance: WithContentDirective|null = null; withContentInstance = null;
shallowCompInstance = null;
});
class WithContentDirective { class WithContentDirective {
// @ContentChildren('foo') foos; // @ContentChildren('foo')
foos !: QueryList<ElementRef>; foos !: QueryList<ElementRef>;
contentInitQuerySnapshot = 0; contentInitQuerySnapshot = 0;
contentCheckedQuerySnapshot = 0; contentCheckedQuerySnapshot = 0;
ngAfterContentInit() { this.contentInitQuerySnapshot = this.foos ? this.foos.length : 0; } ngAfterContentInit() { this.contentInitQuerySnapshot = this.foos ? this.foos.length : 0; }
ngAfterContentChecked() { ngAfterContentChecked() {
this.contentCheckedQuerySnapshot = this.foos ? this.foos.length : 0; this.contentCheckedQuerySnapshot = this.foos ? this.foos.length : 0;
}
static ngComponentDef = defineDirective({
type: WithContentDirective,
selectors: [['', 'with-content', '']],
factory: () => new WithContentDirective(),
contentQueries:
() => { registerContentQuery(query(null, ['foo'], true, QUERY_READ_FROM_NODE)); },
contentQueriesRefresh: (dirIndex: number, queryStartIdx: number) => {
let tmp: any;
withContentInstance = loadDirective<WithContentDirective>(dirIndex);
queryRefresh(tmp = loadQueryList<ElementRef>(queryStartIdx)) &&
(withContentInstance.foos = tmp);
}
});
} }
static ngComponentDef = defineDirective({
type: WithContentDirective,
selectors: [['', 'with-content', '']],
factory: () => new WithContentDirective(),
contentQueries:
() => { registerContentQuery(query(null, ['foo'], true, QUERY_READ_FROM_NODE)); },
contentQueriesRefresh: (dirIndex: number, queryStartIdx: number) => {
let tmp: any;
withContentInstance = loadDirective<WithContentDirective>(dirIndex);
queryRefresh(tmp = loadQueryList<ElementRef>(queryStartIdx)) &&
(withContentInstance.foos = tmp);
}
});
}
class ShallowComp {
// @ContentChildren('foo', {descendants: false})
foos !: QueryList<ElementRef>;
static ngComponentDef = defineComponent({
type: ShallowComp,
selectors: [['shallow-comp']],
factory: () => new ShallowComp(),
template: function(rf: RenderFlags, ctx: any) {},
contentQueries:
() => { registerContentQuery(query(null, ['foo'], false, QUERY_READ_FROM_NODE)); },
contentQueriesRefresh: (dirIndex: number, queryStartIdx: number) => {
let tmp: any;
shallowCompInstance = loadDirective<ShallowComp>(dirIndex);
queryRefresh(tmp = loadQueryList<ElementRef>(queryStartIdx)) &&
(shallowCompInstance.foos = tmp);
}
});
}
it('should support content queries for directives', () => {
/** /**
* <div with-content> * <div with-content>
* <span #foo></span> * <span #foo></span>
* </div> * </div>
* class Cmpt {
* }
*/ */
const AppComponent = createComponent('app-component', function(rf: RenderFlags, ctx: any) { const AppComponent = createComponent('app-component', function(rf: RenderFlags, ctx: any) {
if (rf & RenderFlags.Create) { if (rf & RenderFlags.Create) {
@ -1834,37 +1865,65 @@ describe('query', () => {
`Expected content query results to be available when ngAfterContentChecked was called.`); `Expected content query results to be available when ngAfterContentChecked was called.`);
}); });
// https://stackblitz.com/edit/angular-wlenwd?file=src%2Fapp%2Fapp.component.ts it('should support content query matches on directive hosts', () => {
it('should support view and content queries matching the same element', () => { /**
let withContentComponentInstance: WithContentComponent; * <div with-content #foo>
* </div>
*/
const AppComponent = createComponent('app-component', function(rf: RenderFlags, ctx: any) {
if (rf & RenderFlags.Create) {
element(0, 'div', ['with-content', ''], ['foo', '']);
}
}, [WithContentDirective]);
class WithContentComponent { const fixture = new ComponentFixture(AppComponent);
// @ContentChildren('foo') foos; expect(withContentInstance !.foos.length)
// TODO(issue/24571): remove '!'. .toBe(1, `Expected content query to match <div with-content #foo>.`);
foos !: QueryList<ElementRef>; });
static ngComponentDef = defineComponent({ it('should match shallow content queries in views inserted / removed by ngIf', () => {
type: WithContentComponent, function IfTemplate(rf: RenderFlags, ctx: any) {
selectors: [['with-content']], if (rf & RenderFlags.Create) {
factory: () => new WithContentComponent(), element(0, 'div', null, ['foo', '']);
contentQueries: }
() => { registerContentQuery(query(null, ['foo'], true, QUERY_READ_FROM_NODE)); },
template: (rf: RenderFlags, ctx: WithContentComponent) => {
// intentionally left empty, don't need anything for this test
},
contentQueriesRefresh: (dirIndex: number, queryStartIdx: number) => {
let tmp: any;
withContentComponentInstance = loadDirective<WithContentComponent>(dirIndex);
queryRefresh(tmp = loadQueryList<ElementRef>(queryStartIdx)) &&
(withContentComponentInstance.foos = tmp);
},
});
} }
/** /**
* <with-content> * <shallow-comp>
* <div *ngIf="showing" #foo></div>
* </shallow-comp>
*/
const AppComponent = createComponent('app-component', function(rf: RenderFlags, ctx: any) {
if (rf & RenderFlags.Create) {
elementStart(0, 'shallow-comp');
{ container(1, IfTemplate, null, [AttributeMarker.SelectOnly, 'ngIf', '']); }
elementEnd();
}
if (rf & RenderFlags.Update) {
elementProperty(1, 'ngIf', bind(ctx.showing));
}
}, [ShallowComp, NgIf]);
const fixture = new ComponentFixture(AppComponent);
const qList = shallowCompInstance !.foos;
expect(qList.length).toBe(0);
fixture.component.showing = true;
fixture.update();
expect(qList.length).toBe(1);
fixture.component.showing = false;
fixture.update();
expect(qList.length).toBe(0);
});
// https://stackblitz.com/edit/angular-wlenwd?file=src%2Fapp%2Fapp.component.ts
it('should support view and content queries matching the same element', () => {
/**
* <div with-content>
* <div #foo></div> * <div #foo></div>
* </with-content> * </div>
* <div id="after" #bar></div> * <div id="after" #bar></div>
* class Cmpt { * class Cmpt {
* @ViewChildren('foo, bar') foos; * @ViewChildren('foo, bar') foos;
@ -1874,13 +1933,13 @@ describe('query', () => {
'app-component', 'app-component',
function(rf: RenderFlags, ctx: any) { function(rf: RenderFlags, ctx: any) {
if (rf & RenderFlags.Create) { if (rf & RenderFlags.Create) {
elementStart(1, 'with-content'); elementStart(1, 'div', ['with-content', '']);
{ element(2, 'div', null, ['foo', '']); } { element(2, 'div', null, ['foo', '']); }
elementEnd(); elementEnd();
element(4, 'div', ['id', 'after'], ['bar', '']); element(4, 'div', ['id', 'after'], ['bar', '']);
} }
}, },
[WithContentComponent], [], [WithContentDirective], [],
function(rf: RenderFlags, ctx: any) { function(rf: RenderFlags, ctx: any) {
if (rf & RenderFlags.Create) { if (rf & RenderFlags.Create) {
query(0, ['foo', 'bar'], true, QUERY_READ_FROM_NODE); query(0, ['foo', 'bar'], true, QUERY_READ_FROM_NODE);
@ -1895,14 +1954,48 @@ describe('query', () => {
const viewQList = fixture.component.foos; const viewQList = fixture.component.foos;
expect(viewQList.length).toBe(2); expect(viewQList.length).toBe(2);
expect(withContentComponentInstance !.foos.length).toBe(1); expect(withContentInstance !.foos.length).toBe(1);
expect(viewQList.first.nativeElement) expect(viewQList.first.nativeElement).toBe(withContentInstance !.foos.first.nativeElement);
.toBe(withContentComponentInstance !.foos.first.nativeElement);
expect(viewQList.last.nativeElement.id).toBe('after'); expect(viewQList.last.nativeElement.id).toBe('after');
}); });
it('should report results to appropriate queries where content queries are nested', () => { it('should not report deep content query matches found above content children', () => {
/**
* <div with-content>
* <div #foo id="yes"></div> <-- should match content query
* </div>
* <div #foo></div> <-- should not match content query
* class AppComponent {
* @ViewChildren('bar') bars: QueryList<ElementRef>;
* }
*/
const AppComponent = createComponent(
'app-component',
function(rf: RenderFlags, ctx: any) {
if (rf & RenderFlags.Create) {
elementStart(1, 'div', ['with-content', '']);
{ element(2, 'div', ['id', 'yes'], ['foo', '']); }
elementEnd();
element(4, 'div', null, ['foo', '']);
}
},
[WithContentDirective], [],
function(rf: RenderFlags, ctx: any) {
if (rf & RenderFlags.Create) {
query(0, ['bar'], true, QUERY_READ_FROM_NODE);
}
if (rf & RenderFlags.Update) {
let tmp: any;
queryRefresh(tmp = load<QueryList<any>>(0)) && (ctx.bars = tmp as QueryList<any>);
}
});
const fixture = new ComponentFixture(AppComponent);
expect(withContentInstance !.foos.length).toBe(1);
expect(withContentInstance !.foos.first.nativeElement.id).toEqual('yes');
});
it('should report results to appropriate queries where deep content queries are nested', () => {
class QueryDirective { class QueryDirective {
fooBars: any; fooBars: any;
static ngDirectiveDef = defineDirective({ static ngDirectiveDef = defineDirective({
@ -1962,6 +2055,63 @@ describe('query', () => {
expect(inInstance !.fooBars.length).toBe(1); expect(inInstance !.fooBars.length).toBe(1);
}); });
it('should support nested shallow content queries ', () => {
let outInstance: QueryDirective;
let inInstance: QueryDirective;
class QueryDirective {
fooBars: any;
static ngDirectiveDef = defineDirective({
type: QueryDirective,
selectors: [['', 'query', '']],
exportAs: 'query',
factory: () => new QueryDirective(),
contentQueries: () => {
// @ContentChildren('foo, bar, baz', {descendants: true}) fooBars:
// QueryList<ElementRef>;
registerContentQuery(query(null, ['foo'], false, QUERY_READ_FROM_NODE));
},
contentQueriesRefresh: (dirIndex: number, queryStartIdx: number) => {
let tmp: any;
const instance = loadDirective<QueryDirective>(dirIndex);
queryRefresh(tmp = loadQueryList<ElementRef>(queryStartIdx)) &&
(instance.fooBars = tmp);
},
});
}
const AppComponent = createComponent(
'app-component',
/**
* <div query #out="query">
* <div query #in="query" #foo>
* <span #foo></span>
* </div>
* </div>
*/
function(rf: RenderFlags, ctx: any) {
if (rf & RenderFlags.Create) {
elementStart(0, 'div', ['query', ''], ['out', 'query']);
{
elementStart(2, 'div', ['query', ''], ['in', 'query', 'foo', '']);
{ element(5, 'span', ['id', 'bar'], ['foo', '']); }
elementEnd();
}
elementEnd();
}
if (rf & RenderFlags.Update) {
outInstance = load<QueryDirective>(1);
inInstance = load<QueryDirective>(3);
}
},
[QueryDirective]);
const fixture = new ComponentFixture(AppComponent);
expect(outInstance !.fooBars.length).toBe(1);
expect(inInstance !.fooBars.length).toBe(2);
});
it('should respect shallow flag on content queries when mixing deep and shallow queries', it('should respect shallow flag on content queries when mixing deep and shallow queries',
() => { () => {
class ShallowQueryDirective { class ShallowQueryDirective {
@ -2012,6 +2162,9 @@ describe('query', () => {
/** /**
* <div shallow-query #shallow="shallow-query" deep-query #deep="deep-query"> * <div shallow-query #shallow="shallow-query" deep-query #deep="deep-query">
* <span #foo></span> * <span #foo></span>
* <div>
* <span #foo></span>
* </div>
* </div> * </div>
*/ */
function(rf: RenderFlags, ctx: any) { function(rf: RenderFlags, ctx: any) {
@ -2019,7 +2172,12 @@ describe('query', () => {
elementStart( elementStart(
0, 'div', [AttributeMarker.SelectOnly, 'shallow-query', 'deep-query'], 0, 'div', [AttributeMarker.SelectOnly, 'shallow-query', 'deep-query'],
['shallow', 'shallow-query', 'deep', 'deep-query']); ['shallow', 'shallow-query', 'deep', 'deep-query']);
{ element(3, 'span', ['id', 'foo'], ['foo', '']); } {
element(3, 'span', null, ['foo', '']);
elementStart(5, 'div');
{ element(6, 'span', null, ['foo', '']); }
elementEnd();
}
elementEnd(); elementEnd();
} }
if (rf & RenderFlags.Update) { if (rf & RenderFlags.Update) {
@ -2031,7 +2189,7 @@ describe('query', () => {
const fixture = new ComponentFixture(AppComponent); const fixture = new ComponentFixture(AppComponent);
expect(shallowInstance !.foos.length).toBe(1); expect(shallowInstance !.foos.length).toBe(1);
expect(deepInstance !.foos.length).toBe(1); expect(deepInstance !.foos.length).toBe(2);
}); });
}); });
}); });