tree.mjs 39 KB

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