UNPKG

39.4 kBJavaScriptView Raw
1import { SelectionModel, isDataSource } from '@angular/cdk/collections';
2import { isObservable, Subject, BehaviorSubject, of } from 'rxjs';
3import { take, filter, takeUntil } from 'rxjs/operators';
4import * as i0 from '@angular/core';
5import { InjectionToken, Directive, Inject, Optional, Component, ViewEncapsulation, ChangeDetectionStrategy, Input, ViewChild, ContentChildren, NgModule } from '@angular/core';
6import { coerceNumberProperty, coerceBooleanProperty } from '@angular/cdk/coercion';
7import * as i2 from '@angular/cdk/bidi';
8
9/** Base tree control. It has basic toggle/expand/collapse operations on a single data node. */
10class BaseTreeControl {
11 constructor() {
12 /** A selection model with multi-selection to track expansion status. */
13 this.expansionModel = new SelectionModel(true);
14 }
15 /** Toggles one single data node's expanded/collapsed state. */
16 toggle(dataNode) {
17 this.expansionModel.toggle(this._trackByValue(dataNode));
18 }
19 /** Expands one single data node. */
20 expand(dataNode) {
21 this.expansionModel.select(this._trackByValue(dataNode));
22 }
23 /** Collapses one single data node. */
24 collapse(dataNode) {
25 this.expansionModel.deselect(this._trackByValue(dataNode));
26 }
27 /** Whether a given data node is expanded or not. Returns true if the data node is expanded. */
28 isExpanded(dataNode) {
29 return this.expansionModel.isSelected(this._trackByValue(dataNode));
30 }
31 /** Toggles a subtree rooted at `node` recursively. */
32 toggleDescendants(dataNode) {
33 this.expansionModel.isSelected(this._trackByValue(dataNode))
34 ? this.collapseDescendants(dataNode)
35 : this.expandDescendants(dataNode);
36 }
37 /** Collapse all dataNodes in the tree. */
38 collapseAll() {
39 this.expansionModel.clear();
40 }
41 /** Expands a subtree rooted at given data node recursively. */
42 expandDescendants(dataNode) {
43 let toBeProcessed = [dataNode];
44 toBeProcessed.push(...this.getDescendants(dataNode));
45 this.expansionModel.select(...toBeProcessed.map(value => this._trackByValue(value)));
46 }
47 /** Collapses a subtree rooted at given data node recursively. */
48 collapseDescendants(dataNode) {
49 let toBeProcessed = [dataNode];
50 toBeProcessed.push(...this.getDescendants(dataNode));
51 this.expansionModel.deselect(...toBeProcessed.map(value => this._trackByValue(value)));
52 }
53 _trackByValue(value) {
54 return this.trackBy ? this.trackBy(value) : value;
55 }
56}
57
58/** Flat tree control. Able to expand/collapse a subtree recursively for flattened tree. */
59class FlatTreeControl extends BaseTreeControl {
60 /** Construct with flat tree data node functions getLevel and isExpandable. */
61 constructor(getLevel, isExpandable, options) {
62 super();
63 this.getLevel = getLevel;
64 this.isExpandable = isExpandable;
65 this.options = options;
66 if (this.options) {
67 this.trackBy = this.options.trackBy;
68 }
69 }
70 /**
71 * Gets a list of the data node's subtree of descendent data nodes.
72 *
73 * To make this working, the `dataNodes` of the TreeControl must be flattened tree nodes
74 * with correct levels.
75 */
76 getDescendants(dataNode) {
77 const startIndex = this.dataNodes.indexOf(dataNode);
78 const results = [];
79 // Goes through flattened tree nodes in the `dataNodes` array, and get all descendants.
80 // The level of descendants of a tree node must be greater than the level of the given
81 // tree node.
82 // If we reach a node whose level is equal to the level of the tree node, we hit a sibling.
83 // If we reach a node whose level is greater than the level of the tree node, we hit a
84 // sibling of an ancestor.
85 for (let i = startIndex + 1; i < this.dataNodes.length && this.getLevel(dataNode) < this.getLevel(this.dataNodes[i]); i++) {
86 results.push(this.dataNodes[i]);
87 }
88 return results;
89 }
90 /**
91 * Expands all data nodes in the tree.
92 *
93 * To make this working, the `dataNodes` variable of the TreeControl must be set to all flattened
94 * data nodes of the tree.
95 */
96 expandAll() {
97 this.expansionModel.select(...this.dataNodes.map(node => this._trackByValue(node)));
98 }
99}
100
101/** Nested tree control. Able to expand/collapse a subtree recursively for NestedNode type. */
102class NestedTreeControl extends BaseTreeControl {
103 /** Construct with nested tree function getChildren. */
104 constructor(getChildren, options) {
105 super();
106 this.getChildren = getChildren;
107 this.options = options;
108 if (this.options) {
109 this.trackBy = this.options.trackBy;
110 }
111 }
112 /**
113 * Expands all dataNodes in the tree.
114 *
115 * To make this working, the `dataNodes` variable of the TreeControl must be set to all root level
116 * data nodes of the tree.
117 */
118 expandAll() {
119 this.expansionModel.clear();
120 const allNodes = this.dataNodes.reduce((accumulator, dataNode) => [...accumulator, ...this.getDescendants(dataNode), dataNode], []);
121 this.expansionModel.select(...allNodes.map(node => this._trackByValue(node)));
122 }
123 /** Gets a list of descendant dataNodes of a subtree rooted at given data node recursively. */
124 getDescendants(dataNode) {
125 const descendants = [];
126 this._getDescendants(descendants, dataNode);
127 // Remove the node itself
128 return descendants.splice(1);
129 }
130 /** A helper function to get descendants recursively. */
131 _getDescendants(descendants, dataNode) {
132 descendants.push(dataNode);
133 const childrenNodes = this.getChildren(dataNode);
134 if (Array.isArray(childrenNodes)) {
135 childrenNodes.forEach((child) => this._getDescendants(descendants, child));
136 }
137 else if (isObservable(childrenNodes)) {
138 // TypeScript as of version 3.5 doesn't seem to treat `Boolean` like a function that
139 // returns a `boolean` specifically in the context of `filter`, so we manually clarify that.
140 childrenNodes.pipe(take(1), filter(Boolean)).subscribe(children => {
141 for (const child of children) {
142 this._getDescendants(descendants, child);
143 }
144 });
145 }
146 }
147}
148
149/**
150 * Injection token used to provide a `CdkTreeNode` to its outlet.
151 * Used primarily to avoid circular imports.
152 * @docs-private
153 */
154const CDK_TREE_NODE_OUTLET_NODE = new InjectionToken('CDK_TREE_NODE_OUTLET_NODE');
155/**
156 * Outlet for nested CdkNode. Put `[cdkTreeNodeOutlet]` on a tag to place children dataNodes
157 * inside the outlet.
158 */
159class CdkTreeNodeOutlet {
160 constructor(viewContainer, _node) {
161 this.viewContainer = viewContainer;
162 this._node = _node;
163 }
164 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeNodeOutlet, deps: [{ token: i0.ViewContainerRef }, { token: CDK_TREE_NODE_OUTLET_NODE, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
165 static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: CdkTreeNodeOutlet, selector: "[cdkTreeNodeOutlet]", ngImport: i0 }); }
166}
167i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeNodeOutlet, decorators: [{
168 type: Directive,
169 args: [{
170 selector: '[cdkTreeNodeOutlet]',
171 }]
172 }], ctorParameters: function () { return [{ type: i0.ViewContainerRef }, { type: undefined, decorators: [{
173 type: Inject,
174 args: [CDK_TREE_NODE_OUTLET_NODE]
175 }, {
176 type: Optional
177 }] }]; } });
178
179/** Context provided to the tree node component. */
180class CdkTreeNodeOutletContext {
181 constructor(data) {
182 this.$implicit = data;
183 }
184}
185/**
186 * Data node definition for the CdkTree.
187 * Captures the node's template and a when predicate that describes when this node should be used.
188 */
189class CdkTreeNodeDef {
190 /** @docs-private */
191 constructor(template) {
192 this.template = template;
193 }
194 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeNodeDef, deps: [{ token: i0.TemplateRef }], target: i0.ɵɵFactoryTarget.Directive }); }
195 static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: CdkTreeNodeDef, selector: "[cdkTreeNodeDef]", inputs: { when: ["cdkTreeNodeDefWhen", "when"] }, ngImport: i0 }); }
196}
197i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeNodeDef, decorators: [{
198 type: Directive,
199 args: [{
200 selector: '[cdkTreeNodeDef]',
201 inputs: ['when: cdkTreeNodeDefWhen'],
202 }]
203 }], ctorParameters: function () { return [{ type: i0.TemplateRef }]; } });
204
205/**
206 * Returns an error to be thrown when there is no usable data.
207 * @docs-private
208 */
209function getTreeNoValidDataSourceError() {
210 return Error(`A valid data source must be provided.`);
211}
212/**
213 * Returns an error to be thrown when there are multiple nodes that are missing a when function.
214 * @docs-private
215 */
216function getTreeMultipleDefaultNodeDefsError() {
217 return Error(`There can only be one default row without a when predicate function.`);
218}
219/**
220 * Returns an error to be thrown when there are no matching node defs for a particular set of data.
221 * @docs-private
222 */
223function getTreeMissingMatchingNodeDefError() {
224 return Error(`Could not find a matching node definition for the provided node data.`);
225}
226/**
227 * Returns an error to be thrown when there are tree control.
228 * @docs-private
229 */
230function getTreeControlMissingError() {
231 return Error(`Could not find a tree control for the tree.`);
232}
233/**
234 * Returns an error to be thrown when tree control did not implement functions for flat/nested node.
235 * @docs-private
236 */
237function getTreeControlFunctionsMissingError() {
238 return Error(`Could not find functions for nested/flat tree in tree control.`);
239}
240
241/**
242 * CDK tree component that connects with a data source to retrieve data of type `T` and renders
243 * dataNodes with hierarchy. Updates the dataNodes when new data is provided by the data source.
244 */
245class CdkTree {
246 /**
247 * Provides a stream containing the latest data array to render. Influenced by the tree's
248 * stream of view window (what dataNodes are currently on screen).
249 * Data source can be an observable of data array, or a data array to render.
250 */
251 get dataSource() {
252 return this._dataSource;
253 }
254 set dataSource(dataSource) {
255 if (this._dataSource !== dataSource) {
256 this._switchDataSource(dataSource);
257 }
258 }
259 constructor(_differs, _changeDetectorRef) {
260 this._differs = _differs;
261 this._changeDetectorRef = _changeDetectorRef;
262 /** Subject that emits when the component has been destroyed. */
263 this._onDestroy = new Subject();
264 /** Level of nodes */
265 this._levels = new Map();
266 // TODO(tinayuangao): Setup a listener for scrolling, emit the calculated view to viewChange.
267 // Remove the MAX_VALUE in viewChange
268 /**
269 * Stream containing the latest information on what rows are being displayed on screen.
270 * Can be used by the data source to as a heuristic of what data should be provided.
271 */
272 this.viewChange = new BehaviorSubject({
273 start: 0,
274 end: Number.MAX_VALUE,
275 });
276 }
277 ngOnInit() {
278 this._dataDiffer = this._differs.find([]).create(this.trackBy);
279 if (!this.treeControl && (typeof ngDevMode === 'undefined' || ngDevMode)) {
280 throw getTreeControlMissingError();
281 }
282 }
283 ngOnDestroy() {
284 this._nodeOutlet.viewContainer.clear();
285 this.viewChange.complete();
286 this._onDestroy.next();
287 this._onDestroy.complete();
288 if (this._dataSource && typeof this._dataSource.disconnect === 'function') {
289 this.dataSource.disconnect(this);
290 }
291 if (this._dataSubscription) {
292 this._dataSubscription.unsubscribe();
293 this._dataSubscription = null;
294 }
295 }
296 ngAfterContentChecked() {
297 const defaultNodeDefs = this._nodeDefs.filter(def => !def.when);
298 if (defaultNodeDefs.length > 1 && (typeof ngDevMode === 'undefined' || ngDevMode)) {
299 throw getTreeMultipleDefaultNodeDefsError();
300 }
301 this._defaultNodeDef = defaultNodeDefs[0];
302 if (this.dataSource && this._nodeDefs && !this._dataSubscription) {
303 this._observeRenderChanges();
304 }
305 }
306 // TODO(tinayuangao): Work on keyboard traversal and actions, make sure it's working for RTL
307 // and nested trees.
308 /**
309 * Switch to the provided data source by resetting the data and unsubscribing from the current
310 * render change subscription if one exists. If the data source is null, interpret this by
311 * clearing the node outlet. Otherwise start listening for new data.
312 */
313 _switchDataSource(dataSource) {
314 if (this._dataSource && typeof this._dataSource.disconnect === 'function') {
315 this.dataSource.disconnect(this);
316 }
317 if (this._dataSubscription) {
318 this._dataSubscription.unsubscribe();
319 this._dataSubscription = null;
320 }
321 // Remove the all dataNodes if there is now no data source
322 if (!dataSource) {
323 this._nodeOutlet.viewContainer.clear();
324 }
325 this._dataSource = dataSource;
326 if (this._nodeDefs) {
327 this._observeRenderChanges();
328 }
329 }
330 /** Set up a subscription for the data provided by the data source. */
331 _observeRenderChanges() {
332 let dataStream;
333 if (isDataSource(this._dataSource)) {
334 dataStream = this._dataSource.connect(this);
335 }
336 else if (isObservable(this._dataSource)) {
337 dataStream = this._dataSource;
338 }
339 else if (Array.isArray(this._dataSource)) {
340 dataStream = of(this._dataSource);
341 }
342 if (dataStream) {
343 this._dataSubscription = dataStream
344 .pipe(takeUntil(this._onDestroy))
345 .subscribe(data => this.renderNodeChanges(data));
346 }
347 else if (typeof ngDevMode === 'undefined' || ngDevMode) {
348 throw getTreeNoValidDataSourceError();
349 }
350 }
351 /** Check for changes made in the data and render each change (node added/removed/moved). */
352 renderNodeChanges(data, dataDiffer = this._dataDiffer, viewContainer = this._nodeOutlet.viewContainer, parentData) {
353 const changes = dataDiffer.diff(data);
354 if (!changes) {
355 return;
356 }
357 changes.forEachOperation((item, adjustedPreviousIndex, currentIndex) => {
358 if (item.previousIndex == null) {
359 this.insertNode(data[currentIndex], currentIndex, viewContainer, parentData);
360 }
361 else if (currentIndex == null) {
362 viewContainer.remove(adjustedPreviousIndex);
363 this._levels.delete(item.item);
364 }
365 else {
366 const view = viewContainer.get(adjustedPreviousIndex);
367 viewContainer.move(view, currentIndex);
368 }
369 });
370 this._changeDetectorRef.detectChanges();
371 }
372 /**
373 * Finds the matching node definition that should be used for this node data. If there is only
374 * one node definition, it is returned. Otherwise, find the node definition that has a when
375 * predicate that returns true with the data. If none return true, return the default node
376 * definition.
377 */
378 _getNodeDef(data, i) {
379 if (this._nodeDefs.length === 1) {
380 return this._nodeDefs.first;
381 }
382 const nodeDef = this._nodeDefs.find(def => def.when && def.when(i, data)) || this._defaultNodeDef;
383 if (!nodeDef && (typeof ngDevMode === 'undefined' || ngDevMode)) {
384 throw getTreeMissingMatchingNodeDefError();
385 }
386 return nodeDef;
387 }
388 /**
389 * Create the embedded view for the data node template and place it in the correct index location
390 * within the data node view container.
391 */
392 insertNode(nodeData, index, viewContainer, parentData) {
393 const node = this._getNodeDef(nodeData, index);
394 // Node context that will be provided to created embedded view
395 const context = new CdkTreeNodeOutletContext(nodeData);
396 // If the tree is flat tree, then use the `getLevel` function in flat tree control
397 // Otherwise, use the level of parent node.
398 if (this.treeControl.getLevel) {
399 context.level = this.treeControl.getLevel(nodeData);
400 }
401 else if (typeof parentData !== 'undefined' && this._levels.has(parentData)) {
402 context.level = this._levels.get(parentData) + 1;
403 }
404 else {
405 context.level = 0;
406 }
407 this._levels.set(nodeData, context.level);
408 // Use default tree nodeOutlet, or nested node's nodeOutlet
409 const container = viewContainer ? viewContainer : this._nodeOutlet.viewContainer;
410 container.createEmbeddedView(node.template, context, index);
411 // Set the data to just created `CdkTreeNode`.
412 // The `CdkTreeNode` created from `createEmbeddedView` will be saved in static variable
413 // `mostRecentTreeNode`. We get it from static variable and pass the node data to it.
414 if (CdkTreeNode.mostRecentTreeNode) {
415 CdkTreeNode.mostRecentTreeNode.data = nodeData;
416 }
417 }
418 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTree, deps: [{ token: i0.IterableDiffers }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component }); }
419 static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: CdkTree, selector: "cdk-tree", inputs: { dataSource: "dataSource", treeControl: "treeControl", trackBy: "trackBy" }, host: { attributes: { "role": "tree" }, classAttribute: "cdk-tree" }, queries: [{ propertyName: "_nodeDefs", predicate: CdkTreeNodeDef, descendants: true }], viewQueries: [{ propertyName: "_nodeOutlet", first: true, predicate: CdkTreeNodeOutlet, descendants: true, static: true }], exportAs: ["cdkTree"], ngImport: i0, template: `<ng-container cdkTreeNodeOutlet></ng-container>`, isInline: true, dependencies: [{ kind: "directive", type: CdkTreeNodeOutlet, selector: "[cdkTreeNodeOutlet]" }], changeDetection: i0.ChangeDetectionStrategy.Default, encapsulation: i0.ViewEncapsulation.None }); }
420}
421i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTree, decorators: [{
422 type: Component,
423 args: [{
424 selector: 'cdk-tree',
425 exportAs: 'cdkTree',
426 template: `<ng-container cdkTreeNodeOutlet></ng-container>`,
427 host: {
428 'class': 'cdk-tree',
429 'role': 'tree',
430 },
431 encapsulation: ViewEncapsulation.None,
432 // The "OnPush" status for the `CdkTree` component is effectively a noop, so we are removing it.
433 // The view for `CdkTree` consists entirely of templates declared in other views. As they are
434 // declared elsewhere, they are checked when their declaration points are checked.
435 // tslint:disable-next-line:validate-decorators
436 changeDetection: ChangeDetectionStrategy.Default,
437 }]
438 }], ctorParameters: function () { return [{ type: i0.IterableDiffers }, { type: i0.ChangeDetectorRef }]; }, propDecorators: { dataSource: [{
439 type: Input
440 }], treeControl: [{
441 type: Input
442 }], trackBy: [{
443 type: Input
444 }], _nodeOutlet: [{
445 type: ViewChild,
446 args: [CdkTreeNodeOutlet, { static: true }]
447 }], _nodeDefs: [{
448 type: ContentChildren,
449 args: [CdkTreeNodeDef, {
450 // We need to use `descendants: true`, because Ivy will no longer match
451 // indirect descendants if it's left as false.
452 descendants: true,
453 }]
454 }] } });
455/**
456 * Tree node for CdkTree. It contains the data in the tree node.
457 */
458class CdkTreeNode {
459 /**
460 * The role of the tree node.
461 * @deprecated The correct role is 'treeitem', 'group' should not be used. This input will be
462 * removed in a future version.
463 * @breaking-change 12.0.0 Remove this input
464 */
465 get role() {
466 return 'treeitem';
467 }
468 set role(_role) {
469 // TODO: move to host after View Engine deprecation
470 this._elementRef.nativeElement.setAttribute('role', _role);
471 }
472 /**
473 * The most recently created `CdkTreeNode`. We save it in static variable so we can retrieve it
474 * in `CdkTree` and set the data to it.
475 */
476 static { this.mostRecentTreeNode = null; }
477 /** The tree node's data. */
478 get data() {
479 return this._data;
480 }
481 set data(value) {
482 if (value !== this._data) {
483 this._data = value;
484 this._setRoleFromData();
485 this._dataChanges.next();
486 }
487 }
488 get isExpanded() {
489 return this._tree.treeControl.isExpanded(this._data);
490 }
491 get level() {
492 // If the treeControl has a getLevel method, use it to get the level. Otherwise read the
493 // aria-level off the parent node and use it as the level for this node (note aria-level is
494 // 1-indexed, while this property is 0-indexed, so we don't need to increment).
495 return this._tree.treeControl.getLevel
496 ? this._tree.treeControl.getLevel(this._data)
497 : this._parentNodeAriaLevel;
498 }
499 constructor(_elementRef, _tree) {
500 this._elementRef = _elementRef;
501 this._tree = _tree;
502 /** Subject that emits when the component has been destroyed. */
503 this._destroyed = new Subject();
504 /** Emits when the node's data has changed. */
505 this._dataChanges = new Subject();
506 CdkTreeNode.mostRecentTreeNode = this;
507 this.role = 'treeitem';
508 }
509 ngOnInit() {
510 this._parentNodeAriaLevel = getParentNodeAriaLevel(this._elementRef.nativeElement);
511 this._elementRef.nativeElement.setAttribute('aria-level', `${this.level + 1}`);
512 }
513 ngOnDestroy() {
514 // If this is the last tree node being destroyed,
515 // clear out the reference to avoid leaking memory.
516 if (CdkTreeNode.mostRecentTreeNode === this) {
517 CdkTreeNode.mostRecentTreeNode = null;
518 }
519 this._dataChanges.complete();
520 this._destroyed.next();
521 this._destroyed.complete();
522 }
523 /** Focuses the menu item. Implements for FocusableOption. */
524 focus() {
525 this._elementRef.nativeElement.focus();
526 }
527 // TODO: role should eventually just be set in the component host
528 _setRoleFromData() {
529 if (!this._tree.treeControl.isExpandable &&
530 !this._tree.treeControl.getChildren &&
531 (typeof ngDevMode === 'undefined' || ngDevMode)) {
532 throw getTreeControlFunctionsMissingError();
533 }
534 this.role = 'treeitem';
535 }
536 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeNode, deps: [{ token: i0.ElementRef }, { token: CdkTree }], target: i0.ɵɵFactoryTarget.Directive }); }
537 static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: CdkTreeNode, selector: "cdk-tree-node", inputs: { role: "role" }, host: { properties: { "attr.aria-expanded": "isExpanded" }, classAttribute: "cdk-tree-node" }, exportAs: ["cdkTreeNode"], ngImport: i0 }); }
538}
539i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeNode, decorators: [{
540 type: Directive,
541 args: [{
542 selector: 'cdk-tree-node',
543 exportAs: 'cdkTreeNode',
544 host: {
545 'class': 'cdk-tree-node',
546 '[attr.aria-expanded]': 'isExpanded',
547 },
548 }]
549 }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: CdkTree }]; }, propDecorators: { role: [{
550 type: Input
551 }] } });
552function getParentNodeAriaLevel(nodeElement) {
553 let parent = nodeElement.parentElement;
554 while (parent && !isNodeElement(parent)) {
555 parent = parent.parentElement;
556 }
557 if (!parent) {
558 if (typeof ngDevMode === 'undefined' || ngDevMode) {
559 throw Error('Incorrect tree structure containing detached node.');
560 }
561 else {
562 return -1;
563 }
564 }
565 else if (parent.classList.contains('cdk-nested-tree-node')) {
566 return coerceNumberProperty(parent.getAttribute('aria-level'));
567 }
568 else {
569 // The ancestor element is the cdk-tree itself
570 return 0;
571 }
572}
573function isNodeElement(element) {
574 const classList = element.classList;
575 return !!(classList?.contains('cdk-nested-tree-node') || classList?.contains('cdk-tree'));
576}
577
578/**
579 * Nested node is a child of `<cdk-tree>`. It works with nested tree.
580 * By using `cdk-nested-tree-node` component in tree node template, children of the parent node will
581 * be added in the `cdkTreeNodeOutlet` in tree node template.
582 * The children of node will be automatically added to `cdkTreeNodeOutlet`.
583 */
584class CdkNestedTreeNode extends CdkTreeNode {
585 constructor(elementRef, tree, _differs) {
586 super(elementRef, tree);
587 this._differs = _differs;
588 }
589 ngAfterContentInit() {
590 this._dataDiffer = this._differs.find([]).create(this._tree.trackBy);
591 if (!this._tree.treeControl.getChildren && (typeof ngDevMode === 'undefined' || ngDevMode)) {
592 throw getTreeControlFunctionsMissingError();
593 }
594 const childrenNodes = this._tree.treeControl.getChildren(this.data);
595 if (Array.isArray(childrenNodes)) {
596 this.updateChildrenNodes(childrenNodes);
597 }
598 else if (isObservable(childrenNodes)) {
599 childrenNodes
600 .pipe(takeUntil(this._destroyed))
601 .subscribe(result => this.updateChildrenNodes(result));
602 }
603 this.nodeOutlet.changes
604 .pipe(takeUntil(this._destroyed))
605 .subscribe(() => this.updateChildrenNodes());
606 }
607 // This is a workaround for https://github.com/angular/angular/issues/23091
608 // In aot mode, the lifecycle hooks from parent class are not called.
609 ngOnInit() {
610 super.ngOnInit();
611 }
612 ngOnDestroy() {
613 this._clear();
614 super.ngOnDestroy();
615 }
616 /** Add children dataNodes to the NodeOutlet */
617 updateChildrenNodes(children) {
618 const outlet = this._getNodeOutlet();
619 if (children) {
620 this._children = children;
621 }
622 if (outlet && this._children) {
623 const viewContainer = outlet.viewContainer;
624 this._tree.renderNodeChanges(this._children, this._dataDiffer, viewContainer, this._data);
625 }
626 else {
627 // Reset the data differ if there's no children nodes displayed
628 this._dataDiffer.diff([]);
629 }
630 }
631 /** Clear the children dataNodes. */
632 _clear() {
633 const outlet = this._getNodeOutlet();
634 if (outlet) {
635 outlet.viewContainer.clear();
636 this._dataDiffer.diff([]);
637 }
638 }
639 /** Gets the outlet for the current node. */
640 _getNodeOutlet() {
641 const outlets = this.nodeOutlet;
642 // Note that since we use `descendants: true` on the query, we have to ensure
643 // that we don't pick up the outlet of a child node by accident.
644 return outlets && outlets.find(outlet => !outlet._node || outlet._node === this);
645 }
646 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkNestedTreeNode, deps: [{ token: i0.ElementRef }, { token: CdkTree }, { token: i0.IterableDiffers }], target: i0.ɵɵFactoryTarget.Directive }); }
647 static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: CdkNestedTreeNode, selector: "cdk-nested-tree-node", inputs: { role: "role", disabled: "disabled", tabIndex: "tabIndex" }, host: { classAttribute: "cdk-nested-tree-node" }, providers: [
648 { provide: CdkTreeNode, useExisting: CdkNestedTreeNode },
649 { provide: CDK_TREE_NODE_OUTLET_NODE, useExisting: CdkNestedTreeNode },
650 ], queries: [{ propertyName: "nodeOutlet", predicate: CdkTreeNodeOutlet, descendants: true }], exportAs: ["cdkNestedTreeNode"], usesInheritance: true, ngImport: i0 }); }
651}
652i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkNestedTreeNode, decorators: [{
653 type: Directive,
654 args: [{
655 selector: 'cdk-nested-tree-node',
656 exportAs: 'cdkNestedTreeNode',
657 inputs: ['role', 'disabled', 'tabIndex'],
658 providers: [
659 { provide: CdkTreeNode, useExisting: CdkNestedTreeNode },
660 { provide: CDK_TREE_NODE_OUTLET_NODE, useExisting: CdkNestedTreeNode },
661 ],
662 host: {
663 'class': 'cdk-nested-tree-node',
664 },
665 }]
666 }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: CdkTree }, { type: i0.IterableDiffers }]; }, propDecorators: { nodeOutlet: [{
667 type: ContentChildren,
668 args: [CdkTreeNodeOutlet, {
669 // We need to use `descendants: true`, because Ivy will no longer match
670 // indirect descendants if it's left as false.
671 descendants: true,
672 }]
673 }] } });
674
675/** Regex used to split a string on its CSS units. */
676const cssUnitPattern = /([A-Za-z%]+)$/;
677/**
678 * Indent for the children tree dataNodes.
679 * This directive will add left-padding to the node to show hierarchy.
680 */
681class CdkTreeNodePadding {
682 /** The level of depth of the tree node. The padding will be `level * indent` pixels. */
683 get level() {
684 return this._level;
685 }
686 set level(value) {
687 this._setLevelInput(value);
688 }
689 /**
690 * The indent for each level. Can be a number or a CSS string.
691 * Default number 40px from material design menu sub-menu spec.
692 */
693 get indent() {
694 return this._indent;
695 }
696 set indent(indent) {
697 this._setIndentInput(indent);
698 }
699 constructor(_treeNode, _tree, _element, _dir) {
700 this._treeNode = _treeNode;
701 this._tree = _tree;
702 this._element = _element;
703 this._dir = _dir;
704 /** Subject that emits when the component has been destroyed. */
705 this._destroyed = new Subject();
706 /** CSS units used for the indentation value. */
707 this.indentUnits = 'px';
708 this._indent = 40;
709 this._setPadding();
710 if (_dir) {
711 _dir.change.pipe(takeUntil(this._destroyed)).subscribe(() => this._setPadding(true));
712 }
713 // In Ivy the indentation binding might be set before the tree node's data has been added,
714 // which means that we'll miss the first render. We have to subscribe to changes in the
715 // data to ensure that everything is up to date.
716 _treeNode._dataChanges.subscribe(() => this._setPadding());
717 }
718 ngOnDestroy() {
719 this._destroyed.next();
720 this._destroyed.complete();
721 }
722 /** The padding indent value for the tree node. Returns a string with px numbers if not null. */
723 _paddingIndent() {
724 const nodeLevel = this._treeNode.data && this._tree.treeControl.getLevel
725 ? this._tree.treeControl.getLevel(this._treeNode.data)
726 : null;
727 const level = this._level == null ? nodeLevel : this._level;
728 return typeof level === 'number' ? `${level * this._indent}${this.indentUnits}` : null;
729 }
730 _setPadding(forceChange = false) {
731 const padding = this._paddingIndent();
732 if (padding !== this._currentPadding || forceChange) {
733 const element = this._element.nativeElement;
734 const paddingProp = this._dir && this._dir.value === 'rtl' ? 'paddingRight' : 'paddingLeft';
735 const resetProp = paddingProp === 'paddingLeft' ? 'paddingRight' : 'paddingLeft';
736 element.style[paddingProp] = padding || '';
737 element.style[resetProp] = '';
738 this._currentPadding = padding;
739 }
740 }
741 /**
742 * This has been extracted to a util because of TS 4 and VE.
743 * View Engine doesn't support property rename inheritance.
744 * TS 4.0 doesn't allow properties to override accessors or vice-versa.
745 * @docs-private
746 */
747 _setLevelInput(value) {
748 // Set to null as the fallback value so that _setPadding can fall back to the node level if the
749 // consumer set the directive as `cdkTreeNodePadding=""`. We still want to take this value if
750 // they set 0 explicitly.
751 this._level = coerceNumberProperty(value, null);
752 this._setPadding();
753 }
754 /**
755 * This has been extracted to a util because of TS 4 and VE.
756 * View Engine doesn't support property rename inheritance.
757 * TS 4.0 doesn't allow properties to override accessors or vice-versa.
758 * @docs-private
759 */
760 _setIndentInput(indent) {
761 let value = indent;
762 let units = 'px';
763 if (typeof indent === 'string') {
764 const parts = indent.split(cssUnitPattern);
765 value = parts[0];
766 units = parts[1] || units;
767 }
768 this.indentUnits = units;
769 this._indent = coerceNumberProperty(value);
770 this._setPadding();
771 }
772 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeNodePadding, deps: [{ token: CdkTreeNode }, { token: CdkTree }, { token: i0.ElementRef }, { token: i2.Directionality, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
773 static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: CdkTreeNodePadding, selector: "[cdkTreeNodePadding]", inputs: { level: ["cdkTreeNodePadding", "level"], indent: ["cdkTreeNodePaddingIndent", "indent"] }, ngImport: i0 }); }
774}
775i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeNodePadding, decorators: [{
776 type: Directive,
777 args: [{
778 selector: '[cdkTreeNodePadding]',
779 }]
780 }], ctorParameters: function () { return [{ type: CdkTreeNode }, { type: CdkTree }, { type: i0.ElementRef }, { type: i2.Directionality, decorators: [{
781 type: Optional
782 }] }]; }, propDecorators: { level: [{
783 type: Input,
784 args: ['cdkTreeNodePadding']
785 }], indent: [{
786 type: Input,
787 args: ['cdkTreeNodePaddingIndent']
788 }] } });
789
790/**
791 * Node toggle to expand/collapse the node.
792 */
793class CdkTreeNodeToggle {
794 /** Whether expand/collapse the node recursively. */
795 get recursive() {
796 return this._recursive;
797 }
798 set recursive(value) {
799 this._recursive = coerceBooleanProperty(value);
800 }
801 constructor(_tree, _treeNode) {
802 this._tree = _tree;
803 this._treeNode = _treeNode;
804 this._recursive = false;
805 }
806 _toggle(event) {
807 this.recursive
808 ? this._tree.treeControl.toggleDescendants(this._treeNode.data)
809 : this._tree.treeControl.toggle(this._treeNode.data);
810 event.stopPropagation();
811 }
812 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeNodeToggle, deps: [{ token: CdkTree }, { token: CdkTreeNode }], target: i0.ɵɵFactoryTarget.Directive }); }
813 static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: CdkTreeNodeToggle, selector: "[cdkTreeNodeToggle]", inputs: { recursive: ["cdkTreeNodeToggleRecursive", "recursive"] }, host: { listeners: { "click": "_toggle($event)" } }, ngImport: i0 }); }
814}
815i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeNodeToggle, decorators: [{
816 type: Directive,
817 args: [{
818 selector: '[cdkTreeNodeToggle]',
819 host: {
820 '(click)': '_toggle($event)',
821 },
822 }]
823 }], ctorParameters: function () { return [{ type: CdkTree }, { type: CdkTreeNode }]; }, propDecorators: { recursive: [{
824 type: Input,
825 args: ['cdkTreeNodeToggleRecursive']
826 }] } });
827
828const EXPORTED_DECLARATIONS = [
829 CdkNestedTreeNode,
830 CdkTreeNodeDef,
831 CdkTreeNodePadding,
832 CdkTreeNodeToggle,
833 CdkTree,
834 CdkTreeNode,
835 CdkTreeNodeOutlet,
836];
837class CdkTreeModule {
838 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
839 static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeModule, declarations: [CdkNestedTreeNode,
840 CdkTreeNodeDef,
841 CdkTreeNodePadding,
842 CdkTreeNodeToggle,
843 CdkTree,
844 CdkTreeNode,
845 CdkTreeNodeOutlet], exports: [CdkNestedTreeNode,
846 CdkTreeNodeDef,
847 CdkTreeNodePadding,
848 CdkTreeNodeToggle,
849 CdkTree,
850 CdkTreeNode,
851 CdkTreeNodeOutlet] }); }
852 static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeModule }); }
853}
854i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkTreeModule, decorators: [{
855 type: NgModule,
856 args: [{
857 exports: EXPORTED_DECLARATIONS,
858 declarations: EXPORTED_DECLARATIONS,
859 }]
860 }] });
861
862/**
863 * Generated bundle index. Do not edit.
864 */
865
866export { BaseTreeControl, CDK_TREE_NODE_OUTLET_NODE, CdkNestedTreeNode, CdkTree, CdkTreeModule, CdkTreeNode, CdkTreeNodeDef, CdkTreeNodeOutlet, CdkTreeNodeOutletContext, CdkTreeNodePadding, CdkTreeNodeToggle, FlatTreeControl, NestedTreeControl, getTreeControlFunctionsMissingError, getTreeControlMissingError, getTreeMissingMatchingNodeDefError, getTreeMultipleDefaultNodeDefsError, getTreeNoValidDataSourceError };
867//# sourceMappingURL=tree.mjs.map