tree.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. /**
  2. * @license
  3. * Copyright Google LLC All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. import { SelectionModel, isDataSource } from '@angular/cdk/collections';
  9. import { Observable, BehaviorSubject, of, Subject } from 'rxjs';
  10. import { take, filter, takeUntil } from 'rxjs/operators';
  11. import { Directive, Inject, InjectionToken, Optional, ViewContainerRef, TemplateRef, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, Input, IterableDiffers, ViewChild, ViewEncapsulation, Renderer2, HostListener, NgModule } from '@angular/core';
  12. import { Directionality } from '@angular/cdk/bidi';
  13. import { coerceNumberProperty, coerceBooleanProperty } from '@angular/cdk/coercion';
  14. import { FocusMonitor } from '@angular/cdk/a11y';
  15. import { CommonModule } from '@angular/common';
  16. /**
  17. * @fileoverview added by tsickle
  18. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  19. */
  20. /**
  21. * Base tree control. It has basic toggle/expand/collapse operations on a single data node.
  22. * @abstract
  23. * @template T
  24. */
  25. class BaseTreeControl {
  26. constructor() {
  27. /**
  28. * A selection model with multi-selection to track expansion status.
  29. */
  30. this.expansionModel = new SelectionModel(true);
  31. }
  32. /**
  33. * Toggles one single data node's expanded/collapsed state.
  34. * @param {?} dataNode
  35. * @return {?}
  36. */
  37. toggle(dataNode) {
  38. this.expansionModel.toggle(dataNode);
  39. }
  40. /**
  41. * Expands one single data node.
  42. * @param {?} dataNode
  43. * @return {?}
  44. */
  45. expand(dataNode) {
  46. this.expansionModel.select(dataNode);
  47. }
  48. /**
  49. * Collapses one single data node.
  50. * @param {?} dataNode
  51. * @return {?}
  52. */
  53. collapse(dataNode) {
  54. this.expansionModel.deselect(dataNode);
  55. }
  56. /**
  57. * Whether a given data node is expanded or not. Returns true if the data node is expanded.
  58. * @param {?} dataNode
  59. * @return {?}
  60. */
  61. isExpanded(dataNode) {
  62. return this.expansionModel.isSelected(dataNode);
  63. }
  64. /**
  65. * Toggles a subtree rooted at `node` recursively.
  66. * @param {?} dataNode
  67. * @return {?}
  68. */
  69. toggleDescendants(dataNode) {
  70. this.expansionModel.isSelected(dataNode)
  71. ? this.collapseDescendants(dataNode)
  72. : this.expandDescendants(dataNode);
  73. }
  74. /**
  75. * Collapse all dataNodes in the tree.
  76. * @return {?}
  77. */
  78. collapseAll() {
  79. this.expansionModel.clear();
  80. }
  81. /**
  82. * Expands a subtree rooted at given data node recursively.
  83. * @param {?} dataNode
  84. * @return {?}
  85. */
  86. expandDescendants(dataNode) {
  87. /** @type {?} */
  88. let toBeProcessed = [dataNode];
  89. toBeProcessed.push(...this.getDescendants(dataNode));
  90. this.expansionModel.select(...toBeProcessed);
  91. }
  92. /**
  93. * Collapses a subtree rooted at given data node recursively.
  94. * @param {?} dataNode
  95. * @return {?}
  96. */
  97. collapseDescendants(dataNode) {
  98. /** @type {?} */
  99. let toBeProcessed = [dataNode];
  100. toBeProcessed.push(...this.getDescendants(dataNode));
  101. this.expansionModel.deselect(...toBeProcessed);
  102. }
  103. }
  104. /**
  105. * @fileoverview added by tsickle
  106. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  107. */
  108. /**
  109. * Flat tree control. Able to expand/collapse a subtree recursively for flattened tree.
  110. * @template T
  111. */
  112. class FlatTreeControl extends BaseTreeControl {
  113. /**
  114. * Construct with flat tree data node functions getLevel and isExpandable.
  115. * @param {?} getLevel
  116. * @param {?} isExpandable
  117. */
  118. constructor(getLevel, isExpandable) {
  119. super();
  120. this.getLevel = getLevel;
  121. this.isExpandable = isExpandable;
  122. }
  123. /**
  124. * Gets a list of the data node's subtree of descendent data nodes.
  125. *
  126. * To make this working, the `dataNodes` of the TreeControl must be flattened tree nodes
  127. * with correct levels.
  128. * @param {?} dataNode
  129. * @return {?}
  130. */
  131. getDescendants(dataNode) {
  132. /** @type {?} */
  133. const startIndex = this.dataNodes.indexOf(dataNode);
  134. /** @type {?} */
  135. const results = [];
  136. // Goes through flattened tree nodes in the `dataNodes` array, and get all descendants.
  137. // The level of descendants of a tree node must be greater than the level of the given
  138. // tree node.
  139. // If we reach a node whose level is equal to the level of the tree node, we hit a sibling.
  140. // If we reach a node whose level is greater than the level of the tree node, we hit a
  141. // sibling of an ancestor.
  142. for (let i = startIndex + 1; i < this.dataNodes.length && this.getLevel(dataNode) < this.getLevel(this.dataNodes[i]); i++) {
  143. results.push(this.dataNodes[i]);
  144. }
  145. return results;
  146. }
  147. /**
  148. * Expands all data nodes in the tree.
  149. *
  150. * To make this working, the `dataNodes` variable of the TreeControl must be set to all flattened
  151. * data nodes of the tree.
  152. * @return {?}
  153. */
  154. expandAll() {
  155. this.expansionModel.select(...this.dataNodes);
  156. }
  157. }
  158. /**
  159. * @fileoverview added by tsickle
  160. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  161. */
  162. /**
  163. * Nested tree control. Able to expand/collapse a subtree recursively for NestedNode type.
  164. * @template T
  165. */
  166. class NestedTreeControl extends BaseTreeControl {
  167. /**
  168. * Construct with nested tree function getChildren.
  169. * @param {?} getChildren
  170. */
  171. constructor(getChildren) {
  172. super();
  173. this.getChildren = getChildren;
  174. }
  175. /**
  176. * Expands all dataNodes in the tree.
  177. *
  178. * To make this working, the `dataNodes` variable of the TreeControl must be set to all root level
  179. * data nodes of the tree.
  180. * @return {?}
  181. */
  182. expandAll() {
  183. this.expansionModel.clear();
  184. /** @type {?} */
  185. const allNodes = this.dataNodes.reduce((/**
  186. * @param {?} accumulator
  187. * @param {?} dataNode
  188. * @return {?}
  189. */
  190. (accumulator, dataNode) => [...accumulator, ...this.getDescendants(dataNode), dataNode]), []);
  191. this.expansionModel.select(...allNodes);
  192. }
  193. /**
  194. * Gets a list of descendant dataNodes of a subtree rooted at given data node recursively.
  195. * @param {?} dataNode
  196. * @return {?}
  197. */
  198. getDescendants(dataNode) {
  199. /** @type {?} */
  200. const descendants = [];
  201. this._getDescendants(descendants, dataNode);
  202. // Remove the node itself
  203. return descendants.splice(1);
  204. }
  205. /**
  206. * A helper function to get descendants recursively.
  207. * @protected
  208. * @param {?} descendants
  209. * @param {?} dataNode
  210. * @return {?}
  211. */
  212. _getDescendants(descendants, dataNode) {
  213. descendants.push(dataNode);
  214. /** @type {?} */
  215. const childrenNodes = this.getChildren(dataNode);
  216. if (Array.isArray(childrenNodes)) {
  217. childrenNodes.forEach((/**
  218. * @param {?} child
  219. * @return {?}
  220. */
  221. (child) => this._getDescendants(descendants, child)));
  222. }
  223. else if (childrenNodes instanceof Observable) {
  224. // TypeScript as of version 3.5 doesn't seem to treat `Boolean` like a function that
  225. // returns a `boolean` specifically in the context of `filter`, so we manually clarify that.
  226. childrenNodes.pipe(take(1), filter((/** @type {?} */ (Boolean))))
  227. .subscribe((/**
  228. * @param {?} children
  229. * @return {?}
  230. */
  231. children => {
  232. for (const child of children) {
  233. this._getDescendants(descendants, child);
  234. }
  235. }));
  236. }
  237. }
  238. }
  239. /**
  240. * @fileoverview added by tsickle
  241. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  242. */
  243. /**
  244. * @fileoverview added by tsickle
  245. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  246. */
  247. /**
  248. * Injection token used to provide a `CdkTreeNode` to its outlet.
  249. * Used primarily to avoid circular imports.
  250. * \@docs-private
  251. * @type {?}
  252. */
  253. const CDK_TREE_NODE_OUTLET_NODE = new InjectionToken('CDK_TREE_NODE_OUTLET_NODE');
  254. /**
  255. * Outlet for nested CdkNode. Put `[cdkTreeNodeOutlet]` on a tag to place children dataNodes
  256. * inside the outlet.
  257. */
  258. class CdkTreeNodeOutlet {
  259. /**
  260. * @param {?} viewContainer
  261. * @param {?=} _node
  262. */
  263. constructor(viewContainer, _node) {
  264. this.viewContainer = viewContainer;
  265. this._node = _node;
  266. }
  267. }
  268. CdkTreeNodeOutlet.decorators = [
  269. { type: Directive, args: [{
  270. selector: '[cdkTreeNodeOutlet]'
  271. },] },
  272. ];
  273. /** @nocollapse */
  274. CdkTreeNodeOutlet.ctorParameters = () => [
  275. { type: ViewContainerRef },
  276. { type: undefined, decorators: [{ type: Inject, args: [CDK_TREE_NODE_OUTLET_NODE,] }, { type: Optional }] }
  277. ];
  278. /**
  279. * @fileoverview added by tsickle
  280. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  281. */
  282. /**
  283. * Context provided to the tree node component.
  284. * @template T
  285. */
  286. class CdkTreeNodeOutletContext {
  287. /**
  288. * @param {?} data
  289. */
  290. constructor(data) {
  291. this.$implicit = data;
  292. }
  293. }
  294. /**
  295. * Data node definition for the CdkTree.
  296. * Captures the node's template and a when predicate that describes when this node should be used.
  297. * @template T
  298. */
  299. class CdkTreeNodeDef {
  300. /**
  301. * \@docs-private
  302. * @param {?} template
  303. */
  304. constructor(template) {
  305. this.template = template;
  306. }
  307. }
  308. CdkTreeNodeDef.decorators = [
  309. { type: Directive, args: [{
  310. selector: '[cdkTreeNodeDef]',
  311. inputs: [
  312. 'when: cdkTreeNodeDefWhen'
  313. ],
  314. },] },
  315. ];
  316. /** @nocollapse */
  317. CdkTreeNodeDef.ctorParameters = () => [
  318. { type: TemplateRef }
  319. ];
  320. /**
  321. * @fileoverview added by tsickle
  322. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  323. */
  324. /**
  325. * Returns an error to be thrown when there is no usable data.
  326. * \@docs-private
  327. * @return {?}
  328. */
  329. function getTreeNoValidDataSourceError() {
  330. return Error(`A valid data source must be provided.`);
  331. }
  332. /**
  333. * Returns an error to be thrown when there are multiple nodes that are missing a when function.
  334. * \@docs-private
  335. * @return {?}
  336. */
  337. function getTreeMultipleDefaultNodeDefsError() {
  338. return Error(`There can only be one default row without a when predicate function.`);
  339. }
  340. /**
  341. * Returns an error to be thrown when there are no matching node defs for a particular set of data.
  342. * \@docs-private
  343. * @return {?}
  344. */
  345. function getTreeMissingMatchingNodeDefError() {
  346. return Error(`Could not find a matching node definition for the provided node data.`);
  347. }
  348. /**
  349. * Returns an error to be thrown when there are tree control.
  350. * \@docs-private
  351. * @return {?}
  352. */
  353. function getTreeControlMissingError() {
  354. return Error(`Could not find a tree control for the tree.`);
  355. }
  356. /**
  357. * Returns an error to be thrown when tree control did not implement functions for flat/nested node.
  358. * \@docs-private
  359. * @return {?}
  360. */
  361. function getTreeControlFunctionsMissingError() {
  362. return Error(`Could not find functions for nested/flat tree in tree control.`);
  363. }
  364. /**
  365. * @fileoverview added by tsickle
  366. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  367. */
  368. /**
  369. * CDK tree component that connects with a data source to retrieve data of type `T` and renders
  370. * dataNodes with hierarchy. Updates the dataNodes when new data is provided by the data source.
  371. * @template T
  372. */
  373. class CdkTree {
  374. /**
  375. * @param {?} _differs
  376. * @param {?} _changeDetectorRef
  377. */
  378. constructor(_differs, _changeDetectorRef) {
  379. this._differs = _differs;
  380. this._changeDetectorRef = _changeDetectorRef;
  381. /**
  382. * Subject that emits when the component has been destroyed.
  383. */
  384. this._onDestroy = new Subject();
  385. /**
  386. * Level of nodes
  387. */
  388. this._levels = new Map();
  389. // TODO(tinayuangao): Setup a listener for scrolling, emit the calculated view to viewChange.
  390. // Remove the MAX_VALUE in viewChange
  391. /**
  392. * Stream containing the latest information on what rows are being displayed on screen.
  393. * Can be used by the data source to as a heuristic of what data should be provided.
  394. */
  395. this.viewChange = new BehaviorSubject({ start: 0, end: Number.MAX_VALUE });
  396. }
  397. /**
  398. * Provides a stream containing the latest data array to render. Influenced by the tree's
  399. * stream of view window (what dataNodes are currently on screen).
  400. * Data source can be an observable of data array, or a data array to render.
  401. * @return {?}
  402. */
  403. get dataSource() { return this._dataSource; }
  404. /**
  405. * @param {?} dataSource
  406. * @return {?}
  407. */
  408. set dataSource(dataSource) {
  409. if (this._dataSource !== dataSource) {
  410. this._switchDataSource(dataSource);
  411. }
  412. }
  413. /**
  414. * @return {?}
  415. */
  416. ngOnInit() {
  417. this._dataDiffer = this._differs.find([]).create(this.trackBy);
  418. if (!this.treeControl) {
  419. throw getTreeControlMissingError();
  420. }
  421. }
  422. /**
  423. * @return {?}
  424. */
  425. ngOnDestroy() {
  426. this._nodeOutlet.viewContainer.clear();
  427. this._onDestroy.next();
  428. this._onDestroy.complete();
  429. if (this._dataSource && typeof ((/** @type {?} */ (this._dataSource))).disconnect === 'function') {
  430. ((/** @type {?} */ (this.dataSource))).disconnect(this);
  431. }
  432. if (this._dataSubscription) {
  433. this._dataSubscription.unsubscribe();
  434. this._dataSubscription = null;
  435. }
  436. }
  437. /**
  438. * @return {?}
  439. */
  440. ngAfterContentChecked() {
  441. /** @type {?} */
  442. const defaultNodeDefs = this._nodeDefs.filter((/**
  443. * @param {?} def
  444. * @return {?}
  445. */
  446. def => !def.when));
  447. if (defaultNodeDefs.length > 1) {
  448. throw getTreeMultipleDefaultNodeDefsError();
  449. }
  450. this._defaultNodeDef = defaultNodeDefs[0];
  451. if (this.dataSource && this._nodeDefs && !this._dataSubscription) {
  452. this._observeRenderChanges();
  453. }
  454. }
  455. // TODO(tinayuangao): Work on keyboard traversal and actions, make sure it's working for RTL
  456. // and nested trees.
  457. /**
  458. * Switch to the provided data source by resetting the data and unsubscribing from the current
  459. * render change subscription if one exists. If the data source is null, interpret this by
  460. * clearing the node outlet. Otherwise start listening for new data.
  461. * @private
  462. * @param {?} dataSource
  463. * @return {?}
  464. */
  465. _switchDataSource(dataSource) {
  466. if (this._dataSource && typeof ((/** @type {?} */ (this._dataSource))).disconnect === 'function') {
  467. ((/** @type {?} */ (this.dataSource))).disconnect(this);
  468. }
  469. if (this._dataSubscription) {
  470. this._dataSubscription.unsubscribe();
  471. this._dataSubscription = null;
  472. }
  473. // Remove the all dataNodes if there is now no data source
  474. if (!dataSource) {
  475. this._nodeOutlet.viewContainer.clear();
  476. }
  477. this._dataSource = dataSource;
  478. if (this._nodeDefs) {
  479. this._observeRenderChanges();
  480. }
  481. }
  482. /**
  483. * Set up a subscription for the data provided by the data source.
  484. * @private
  485. * @return {?}
  486. */
  487. _observeRenderChanges() {
  488. /** @type {?} */
  489. let dataStream;
  490. if (isDataSource(this._dataSource)) {
  491. dataStream = this._dataSource.connect(this);
  492. }
  493. else if (this._dataSource instanceof Observable) {
  494. dataStream = this._dataSource;
  495. }
  496. else if (Array.isArray(this._dataSource)) {
  497. dataStream = of(this._dataSource);
  498. }
  499. if (dataStream) {
  500. this._dataSubscription = dataStream.pipe(takeUntil(this._onDestroy))
  501. .subscribe((/**
  502. * @param {?} data
  503. * @return {?}
  504. */
  505. data => this.renderNodeChanges(data)));
  506. }
  507. else {
  508. throw getTreeNoValidDataSourceError();
  509. }
  510. }
  511. /**
  512. * Check for changes made in the data and render each change (node added/removed/moved).
  513. * @param {?} data
  514. * @param {?=} dataDiffer
  515. * @param {?=} viewContainer
  516. * @param {?=} parentData
  517. * @return {?}
  518. */
  519. renderNodeChanges(data, dataDiffer = this._dataDiffer, viewContainer = this._nodeOutlet.viewContainer, parentData) {
  520. /** @type {?} */
  521. const changes = dataDiffer.diff(data);
  522. if (!changes) {
  523. return;
  524. }
  525. changes.forEachOperation((/**
  526. * @param {?} item
  527. * @param {?} adjustedPreviousIndex
  528. * @param {?} currentIndex
  529. * @return {?}
  530. */
  531. (item, adjustedPreviousIndex, currentIndex) => {
  532. if (item.previousIndex == null) {
  533. this.insertNode(data[(/** @type {?} */ (currentIndex))], (/** @type {?} */ (currentIndex)), viewContainer, parentData);
  534. }
  535. else if (currentIndex == null) {
  536. viewContainer.remove((/** @type {?} */ (adjustedPreviousIndex)));
  537. this._levels.delete(item.item);
  538. }
  539. else {
  540. /** @type {?} */
  541. const view = viewContainer.get((/** @type {?} */ (adjustedPreviousIndex)));
  542. viewContainer.move((/** @type {?} */ (view)), currentIndex);
  543. }
  544. }));
  545. this._changeDetectorRef.detectChanges();
  546. }
  547. /**
  548. * Finds the matching node definition that should be used for this node data. If there is only
  549. * one node definition, it is returned. Otherwise, find the node definition that has a when
  550. * predicate that returns true with the data. If none return true, return the default node
  551. * definition.
  552. * @param {?} data
  553. * @param {?} i
  554. * @return {?}
  555. */
  556. _getNodeDef(data, i) {
  557. if (this._nodeDefs.length === 1) {
  558. return this._nodeDefs.first;
  559. }
  560. /** @type {?} */
  561. const nodeDef = this._nodeDefs.find((/**
  562. * @param {?} def
  563. * @return {?}
  564. */
  565. def => def.when && def.when(i, data))) || this._defaultNodeDef;
  566. if (!nodeDef) {
  567. throw getTreeMissingMatchingNodeDefError();
  568. }
  569. return nodeDef;
  570. }
  571. /**
  572. * Create the embedded view for the data node template and place it in the correct index location
  573. * within the data node view container.
  574. * @param {?} nodeData
  575. * @param {?} index
  576. * @param {?=} viewContainer
  577. * @param {?=} parentData
  578. * @return {?}
  579. */
  580. insertNode(nodeData, index, viewContainer, parentData) {
  581. /** @type {?} */
  582. const node = this._getNodeDef(nodeData, index);
  583. // Node context that will be provided to created embedded view
  584. /** @type {?} */
  585. const context = new CdkTreeNodeOutletContext(nodeData);
  586. // If the tree is flat tree, then use the `getLevel` function in flat tree control
  587. // Otherwise, use the level of parent node.
  588. if (this.treeControl.getLevel) {
  589. context.level = this.treeControl.getLevel(nodeData);
  590. }
  591. else if (typeof parentData !== 'undefined' && this._levels.has(parentData)) {
  592. context.level = (/** @type {?} */ (this._levels.get(parentData))) + 1;
  593. }
  594. else {
  595. context.level = 0;
  596. }
  597. this._levels.set(nodeData, context.level);
  598. // Use default tree nodeOutlet, or nested node's nodeOutlet
  599. /** @type {?} */
  600. const container = viewContainer ? viewContainer : this._nodeOutlet.viewContainer;
  601. container.createEmbeddedView(node.template, context, index);
  602. // Set the data to just created `CdkTreeNode`.
  603. // The `CdkTreeNode` created from `createEmbeddedView` will be saved in static variable
  604. // `mostRecentTreeNode`. We get it from static variable and pass the node data to it.
  605. if (CdkTreeNode.mostRecentTreeNode) {
  606. CdkTreeNode.mostRecentTreeNode.data = nodeData;
  607. }
  608. }
  609. }
  610. CdkTree.decorators = [
  611. { type: Component, args: [{selector: 'cdk-tree',
  612. exportAs: 'cdkTree',
  613. template: `<ng-container cdkTreeNodeOutlet></ng-container>`,
  614. host: {
  615. 'class': 'cdk-tree',
  616. 'role': 'tree',
  617. },
  618. encapsulation: ViewEncapsulation.None,
  619. // The "OnPush" status for the `CdkTree` component is effectively a noop, so we are removing it.
  620. // The view for `CdkTree` consists entirely of templates declared in other views. As they are
  621. // declared elsewhere, they are checked when their declaration points are checked.
  622. // tslint:disable-next-line:validate-decorators
  623. changeDetection: ChangeDetectionStrategy.Default
  624. },] },
  625. ];
  626. /** @nocollapse */
  627. CdkTree.ctorParameters = () => [
  628. { type: IterableDiffers },
  629. { type: ChangeDetectorRef }
  630. ];
  631. CdkTree.propDecorators = {
  632. dataSource: [{ type: Input }],
  633. treeControl: [{ type: Input }],
  634. trackBy: [{ type: Input }],
  635. _nodeOutlet: [{ type: ViewChild, args: [CdkTreeNodeOutlet, { static: true },] }],
  636. _nodeDefs: [{ type: ContentChildren, args: [CdkTreeNodeDef,] }]
  637. };
  638. /**
  639. * Tree node for CdkTree. It contains the data in the tree node.
  640. * @template T
  641. */
  642. class CdkTreeNode {
  643. /**
  644. * @param {?} _elementRef
  645. * @param {?} _tree
  646. */
  647. constructor(_elementRef, _tree) {
  648. this._elementRef = _elementRef;
  649. this._tree = _tree;
  650. /**
  651. * Subject that emits when the component has been destroyed.
  652. */
  653. this._destroyed = new Subject();
  654. /**
  655. * Emits when the node's data has changed.
  656. */
  657. this._dataChanges = new Subject();
  658. /**
  659. * The role of the node should be 'group' if it's an internal node,
  660. * and 'treeitem' if it's a leaf node.
  661. */
  662. this.role = 'treeitem';
  663. CdkTreeNode.mostRecentTreeNode = (/** @type {?} */ (this));
  664. }
  665. /**
  666. * The tree node's data.
  667. * @return {?}
  668. */
  669. get data() { return this._data; }
  670. /**
  671. * @param {?} value
  672. * @return {?}
  673. */
  674. set data(value) {
  675. if (value !== this._data) {
  676. this._data = value;
  677. this._setRoleFromData();
  678. this._dataChanges.next();
  679. }
  680. }
  681. /**
  682. * @return {?}
  683. */
  684. get isExpanded() {
  685. return this._tree.treeControl.isExpanded(this._data);
  686. }
  687. /**
  688. * @return {?}
  689. */
  690. get level() {
  691. return this._tree.treeControl.getLevel ? this._tree.treeControl.getLevel(this._data) : 0;
  692. }
  693. /**
  694. * @return {?}
  695. */
  696. ngOnDestroy() {
  697. // If this is the last tree node being destroyed,
  698. // clear out the reference to avoid leaking memory.
  699. if (CdkTreeNode.mostRecentTreeNode === this) {
  700. CdkTreeNode.mostRecentTreeNode = null;
  701. }
  702. this._dataChanges.complete();
  703. this._destroyed.next();
  704. this._destroyed.complete();
  705. }
  706. /**
  707. * Focuses the menu item. Implements for FocusableOption.
  708. * @return {?}
  709. */
  710. focus() {
  711. this._elementRef.nativeElement.focus();
  712. }
  713. /**
  714. * @protected
  715. * @return {?}
  716. */
  717. _setRoleFromData() {
  718. if (this._tree.treeControl.isExpandable) {
  719. this.role = this._tree.treeControl.isExpandable(this._data) ? 'group' : 'treeitem';
  720. }
  721. else {
  722. if (!this._tree.treeControl.getChildren) {
  723. throw getTreeControlFunctionsMissingError();
  724. }
  725. /** @type {?} */
  726. const childrenNodes = this._tree.treeControl.getChildren(this._data);
  727. if (Array.isArray(childrenNodes)) {
  728. this._setRoleFromChildren((/** @type {?} */ (childrenNodes)));
  729. }
  730. else if (childrenNodes instanceof Observable) {
  731. childrenNodes.pipe(takeUntil(this._destroyed))
  732. .subscribe((/**
  733. * @param {?} children
  734. * @return {?}
  735. */
  736. children => this._setRoleFromChildren(children)));
  737. }
  738. }
  739. }
  740. /**
  741. * @protected
  742. * @param {?} children
  743. * @return {?}
  744. */
  745. _setRoleFromChildren(children) {
  746. this.role = children && children.length ? 'group' : 'treeitem';
  747. }
  748. }
  749. /**
  750. * The most recently created `CdkTreeNode`. We save it in static variable so we can retrieve it
  751. * in `CdkTree` and set the data to it.
  752. */
  753. CdkTreeNode.mostRecentTreeNode = null;
  754. CdkTreeNode.decorators = [
  755. { type: Directive, args: [{
  756. selector: 'cdk-tree-node',
  757. exportAs: 'cdkTreeNode',
  758. host: {
  759. '[attr.aria-expanded]': 'isExpanded',
  760. '[attr.aria-level]': 'role === "treeitem" ? level : null',
  761. '[attr.role]': 'role',
  762. 'class': 'cdk-tree-node',
  763. },
  764. },] },
  765. ];
  766. /** @nocollapse */
  767. CdkTreeNode.ctorParameters = () => [
  768. { type: ElementRef },
  769. { type: CdkTree }
  770. ];
  771. CdkTreeNode.propDecorators = {
  772. role: [{ type: Input }]
  773. };
  774. /**
  775. * @fileoverview added by tsickle
  776. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  777. */
  778. /**
  779. * Nested node is a child of `<cdk-tree>`. It works with nested tree.
  780. * By using `cdk-nested-tree-node` component in tree node template, children of the parent node will
  781. * be added in the `cdkTreeNodeOutlet` in tree node template.
  782. * For example:
  783. * ```html
  784. * <cdk-nested-tree-node>
  785. * {{node.name}}
  786. * <ng-template cdkTreeNodeOutlet></ng-template>
  787. * </cdk-nested-tree-node>
  788. * ```
  789. * The children of node will be automatically added to `cdkTreeNodeOutlet`, the result dom will be
  790. * like this:
  791. * ```html
  792. * <cdk-nested-tree-node>
  793. * {{node.name}}
  794. * <cdk-nested-tree-node>{{child1.name}}</cdk-nested-tree-node>
  795. * <cdk-nested-tree-node>{{child2.name}}</cdk-nested-tree-node>
  796. * </cdk-nested-tree-node>
  797. * ```
  798. * @template T
  799. */
  800. class CdkNestedTreeNode extends CdkTreeNode {
  801. /**
  802. * @param {?} _elementRef
  803. * @param {?} _tree
  804. * @param {?} _differs
  805. */
  806. constructor(_elementRef, _tree, _differs) {
  807. super(_elementRef, _tree);
  808. this._elementRef = _elementRef;
  809. this._tree = _tree;
  810. this._differs = _differs;
  811. }
  812. /**
  813. * @return {?}
  814. */
  815. ngAfterContentInit() {
  816. this._dataDiffer = this._differs.find([]).create(this._tree.trackBy);
  817. if (!this._tree.treeControl.getChildren) {
  818. throw getTreeControlFunctionsMissingError();
  819. }
  820. /** @type {?} */
  821. const childrenNodes = this._tree.treeControl.getChildren(this.data);
  822. if (Array.isArray(childrenNodes)) {
  823. this.updateChildrenNodes((/** @type {?} */ (childrenNodes)));
  824. }
  825. else if (childrenNodes instanceof Observable) {
  826. childrenNodes.pipe(takeUntil(this._destroyed))
  827. .subscribe((/**
  828. * @param {?} result
  829. * @return {?}
  830. */
  831. result => this.updateChildrenNodes(result)));
  832. }
  833. this.nodeOutlet.changes.pipe(takeUntil(this._destroyed))
  834. .subscribe((/**
  835. * @return {?}
  836. */
  837. () => this.updateChildrenNodes()));
  838. }
  839. /**
  840. * @return {?}
  841. */
  842. ngOnDestroy() {
  843. this._clear();
  844. super.ngOnDestroy();
  845. }
  846. /**
  847. * Add children dataNodes to the NodeOutlet
  848. * @protected
  849. * @param {?=} children
  850. * @return {?}
  851. */
  852. updateChildrenNodes(children) {
  853. /** @type {?} */
  854. const outlet = this._getNodeOutlet();
  855. if (children) {
  856. this._children = children;
  857. }
  858. if (outlet && this._children) {
  859. /** @type {?} */
  860. const viewContainer = outlet.viewContainer;
  861. this._tree.renderNodeChanges(this._children, this._dataDiffer, viewContainer, this._data);
  862. }
  863. else {
  864. // Reset the data differ if there's no children nodes displayed
  865. this._dataDiffer.diff([]);
  866. }
  867. }
  868. /**
  869. * Clear the children dataNodes.
  870. * @protected
  871. * @return {?}
  872. */
  873. _clear() {
  874. /** @type {?} */
  875. const outlet = this._getNodeOutlet();
  876. if (outlet) {
  877. outlet.viewContainer.clear();
  878. this._dataDiffer.diff([]);
  879. }
  880. }
  881. /**
  882. * Gets the outlet for the current node.
  883. * @private
  884. * @return {?}
  885. */
  886. _getNodeOutlet() {
  887. /** @type {?} */
  888. const outlets = this.nodeOutlet;
  889. // Note that since we use `descendants: true` on the query, we have to ensure
  890. // that we don't pick up the outlet of a child node by accident.
  891. return outlets && outlets.find((/**
  892. * @param {?} outlet
  893. * @return {?}
  894. */
  895. outlet => !outlet._node || outlet._node === this));
  896. }
  897. }
  898. CdkNestedTreeNode.decorators = [
  899. { type: Directive, args: [{
  900. selector: 'cdk-nested-tree-node',
  901. exportAs: 'cdkNestedTreeNode',
  902. host: {
  903. '[attr.aria-expanded]': 'isExpanded',
  904. '[attr.role]': 'role',
  905. 'class': 'cdk-tree-node cdk-nested-tree-node',
  906. },
  907. providers: [
  908. { provide: CdkTreeNode, useExisting: CdkNestedTreeNode },
  909. { provide: CDK_TREE_NODE_OUTLET_NODE, useExisting: CdkNestedTreeNode }
  910. ]
  911. },] },
  912. ];
  913. /** @nocollapse */
  914. CdkNestedTreeNode.ctorParameters = () => [
  915. { type: ElementRef },
  916. { type: CdkTree },
  917. { type: IterableDiffers }
  918. ];
  919. CdkNestedTreeNode.propDecorators = {
  920. nodeOutlet: [{ type: ContentChildren, args: [CdkTreeNodeOutlet, {
  921. // We need to use `descendants: true`, because Ivy will no longer match
  922. // indirect descendants if it's left as false.
  923. descendants: true
  924. },] }]
  925. };
  926. /**
  927. * @fileoverview added by tsickle
  928. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  929. */
  930. /**
  931. * Regex used to split a string on its CSS units.
  932. * @type {?}
  933. */
  934. const cssUnitPattern = /([A-Za-z%]+)$/;
  935. /**
  936. * Indent for the children tree dataNodes.
  937. * This directive will add left-padding to the node to show hierarchy.
  938. * @template T
  939. */
  940. class CdkTreeNodePadding {
  941. /**
  942. * @param {?} _treeNode
  943. * @param {?} _tree
  944. * @param {?} _renderer
  945. * @param {?} _element
  946. * @param {?} _dir
  947. */
  948. constructor(_treeNode, _tree, _renderer, _element, _dir) {
  949. this._treeNode = _treeNode;
  950. this._tree = _tree;
  951. this._renderer = _renderer;
  952. this._element = _element;
  953. this._dir = _dir;
  954. /**
  955. * Subject that emits when the component has been destroyed.
  956. */
  957. this._destroyed = new Subject();
  958. /**
  959. * CSS units used for the indentation value.
  960. */
  961. this.indentUnits = 'px';
  962. this._indent = 40;
  963. this._setPadding();
  964. if (_dir) {
  965. _dir.change.pipe(takeUntil(this._destroyed)).subscribe((/**
  966. * @return {?}
  967. */
  968. () => this._setPadding(true)));
  969. }
  970. // In Ivy the indentation binding might be set before the tree node's data has been added,
  971. // which means that we'll miss the first render. We have to subscribe to changes in the
  972. // data to ensure that everything is up to date.
  973. _treeNode._dataChanges.subscribe((/**
  974. * @return {?}
  975. */
  976. () => this._setPadding()));
  977. }
  978. /**
  979. * The level of depth of the tree node. The padding will be `level * indent` pixels.
  980. * @return {?}
  981. */
  982. get level() { return this._level; }
  983. /**
  984. * @param {?} value
  985. * @return {?}
  986. */
  987. set level(value) {
  988. // Set to null as the fallback value so that _setPadding can fall back to the node level if the
  989. // consumer set the directive as `cdkTreeNodePadding=""`. We still want to take this value if
  990. // they set 0 explicitly.
  991. this._level = (/** @type {?} */ (coerceNumberProperty(value, null)));
  992. this._setPadding();
  993. }
  994. /**
  995. * The indent for each level. Can be a number or a CSS string.
  996. * Default number 40px from material design menu sub-menu spec.
  997. * @return {?}
  998. */
  999. get indent() { return this._indent; }
  1000. /**
  1001. * @param {?} indent
  1002. * @return {?}
  1003. */
  1004. set indent(indent) {
  1005. /** @type {?} */
  1006. let value = indent;
  1007. /** @type {?} */
  1008. let units = 'px';
  1009. if (typeof indent === 'string') {
  1010. /** @type {?} */
  1011. const parts = indent.split(cssUnitPattern);
  1012. value = parts[0];
  1013. units = parts[1] || units;
  1014. }
  1015. this.indentUnits = units;
  1016. this._indent = coerceNumberProperty(value);
  1017. this._setPadding();
  1018. }
  1019. /**
  1020. * @return {?}
  1021. */
  1022. ngOnDestroy() {
  1023. this._destroyed.next();
  1024. this._destroyed.complete();
  1025. }
  1026. /**
  1027. * The padding indent value for the tree node. Returns a string with px numbers if not null.
  1028. * @return {?}
  1029. */
  1030. _paddingIndent() {
  1031. /** @type {?} */
  1032. const nodeLevel = (this._treeNode.data && this._tree.treeControl.getLevel)
  1033. ? this._tree.treeControl.getLevel(this._treeNode.data)
  1034. : null;
  1035. /** @type {?} */
  1036. const level = this._level == null ? nodeLevel : this._level;
  1037. return typeof level === 'number' ? `${level * this._indent}${this.indentUnits}` : null;
  1038. }
  1039. /**
  1040. * @param {?=} forceChange
  1041. * @return {?}
  1042. */
  1043. _setPadding(forceChange = false) {
  1044. /** @type {?} */
  1045. const padding = this._paddingIndent();
  1046. if (padding !== this._currentPadding || forceChange) {
  1047. /** @type {?} */
  1048. const element = this._element.nativeElement;
  1049. /** @type {?} */
  1050. const paddingProp = this._dir && this._dir.value === 'rtl' ? 'paddingRight' : 'paddingLeft';
  1051. /** @type {?} */
  1052. const resetProp = paddingProp === 'paddingLeft' ? 'paddingRight' : 'paddingLeft';
  1053. this._renderer.setStyle(element, paddingProp, padding);
  1054. this._renderer.setStyle(element, resetProp, null);
  1055. this._currentPadding = padding;
  1056. }
  1057. }
  1058. }
  1059. CdkTreeNodePadding.decorators = [
  1060. { type: Directive, args: [{
  1061. selector: '[cdkTreeNodePadding]',
  1062. },] },
  1063. ];
  1064. /** @nocollapse */
  1065. CdkTreeNodePadding.ctorParameters = () => [
  1066. { type: CdkTreeNode },
  1067. { type: CdkTree },
  1068. { type: Renderer2 },
  1069. { type: ElementRef },
  1070. { type: Directionality, decorators: [{ type: Optional }] }
  1071. ];
  1072. CdkTreeNodePadding.propDecorators = {
  1073. level: [{ type: Input, args: ['cdkTreeNodePadding',] }],
  1074. indent: [{ type: Input, args: ['cdkTreeNodePaddingIndent',] }]
  1075. };
  1076. /**
  1077. * @fileoverview added by tsickle
  1078. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1079. */
  1080. /**
  1081. * Node toggle to expand/collapse the node.
  1082. * @template T
  1083. */
  1084. class CdkTreeNodeToggle {
  1085. /**
  1086. * @param {?} _tree
  1087. * @param {?} _treeNode
  1088. */
  1089. constructor(_tree, _treeNode) {
  1090. this._tree = _tree;
  1091. this._treeNode = _treeNode;
  1092. this._recursive = false;
  1093. }
  1094. /**
  1095. * Whether expand/collapse the node recursively.
  1096. * @return {?}
  1097. */
  1098. get recursive() { return this._recursive; }
  1099. /**
  1100. * @param {?} value
  1101. * @return {?}
  1102. */
  1103. set recursive(value) { this._recursive = coerceBooleanProperty(value); }
  1104. // We have to use a `HostListener` here in order to support both Ivy and ViewEngine.
  1105. // In Ivy the `host` bindings will be merged when this class is extended, whereas in
  1106. // ViewEngine they're overwritten.
  1107. // TODO(crisbeto): we move this back into `host` once Ivy is turned on by default.
  1108. // tslint:disable-next-line:no-host-decorator-in-concrete
  1109. /**
  1110. * @param {?} event
  1111. * @return {?}
  1112. */
  1113. _toggle(event) {
  1114. this.recursive
  1115. ? this._tree.treeControl.toggleDescendants(this._treeNode.data)
  1116. : this._tree.treeControl.toggle(this._treeNode.data);
  1117. event.stopPropagation();
  1118. }
  1119. }
  1120. CdkTreeNodeToggle.decorators = [
  1121. { type: Directive, args: [{ selector: '[cdkTreeNodeToggle]' },] },
  1122. ];
  1123. /** @nocollapse */
  1124. CdkTreeNodeToggle.ctorParameters = () => [
  1125. { type: CdkTree },
  1126. { type: CdkTreeNode }
  1127. ];
  1128. CdkTreeNodeToggle.propDecorators = {
  1129. recursive: [{ type: Input, args: ['cdkTreeNodeToggleRecursive',] }],
  1130. _toggle: [{ type: HostListener, args: ['click', ['$event'],] }]
  1131. };
  1132. /**
  1133. * @fileoverview added by tsickle
  1134. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1135. */
  1136. /** @type {?} */
  1137. const EXPORTED_DECLARATIONS = [
  1138. CdkNestedTreeNode,
  1139. CdkTreeNodeDef,
  1140. CdkTreeNodePadding,
  1141. CdkTreeNodeToggle,
  1142. CdkTree,
  1143. CdkTreeNode,
  1144. CdkTreeNodeOutlet,
  1145. ];
  1146. class CdkTreeModule {
  1147. }
  1148. CdkTreeModule.decorators = [
  1149. { type: NgModule, args: [{
  1150. imports: [CommonModule],
  1151. exports: EXPORTED_DECLARATIONS,
  1152. declarations: EXPORTED_DECLARATIONS,
  1153. providers: [FocusMonitor, CdkTreeNodeDef]
  1154. },] },
  1155. ];
  1156. /**
  1157. * @fileoverview added by tsickle
  1158. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1159. */
  1160. /**
  1161. * @fileoverview added by tsickle
  1162. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1163. */
  1164. export { BaseTreeControl, FlatTreeControl, NestedTreeControl, CdkNestedTreeNode, CdkTreeNodeOutletContext, CdkTreeNodeDef, CdkTreeNodePadding, CDK_TREE_NODE_OUTLET_NODE, CdkTreeNodeOutlet, CdkTree, CdkTreeNode, getTreeNoValidDataSourceError, getTreeMultipleDefaultNodeDefsError, getTreeMissingMatchingNodeDefError, getTreeControlMissingError, getTreeControlFunctionsMissingError, CdkTreeModule, CdkTreeNodeToggle };
  1165. //# sourceMappingURL=tree.js.map