Code coverage report for dgrid\Tree.js

Statements: 91.34% (211 / 231)      Branches: 85.71% (162 / 189)      Functions: 94.29% (33 / 35)      Lines: 91.34% (211 / 231)      Ignored: none     

All files » dgrid/ » Tree.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 5894                             4                           62                   3059                       97       97           4 93 16       97 97     97   97   97     97 97     97   97   97           97     75   75 99   99 56   99 63   63     63         99 99 85       85   14   99   75     75       75 61                       61               14 14 14             13 13         75     75           97 97     97 83 83 83     14 14 8 8 8         6 6     14 14 14             97       75       75   75 75 70 70     75       3197 3197   3197     3197     3196     3196 5     3196 1187     3196       1420   1420 1420 6         1351 1351 1351 1351 6 6 6 6 6 6 6 6   6         1351             3170           3170 72 39 78   39     72 39     72 72 72   63 52 52 52     63 1495 177   1318       72   72 39 39     72 69   3       3170       2       2           187   187               62 62   62 62   62 62           4376   4376             70 70 70   70 70 62 62 62       3199       3199   3199 3199   3199 3199 5 5     3194       62 62       70 70   65     12 12       12         12 6 3     3                 65                                               3199   3199 1188   3199               17 2   17       8   8     8         8       8 8   8       8       174 174 174   174 91     4 83 83 280 280         280       83 83                             174 174 75   99 79   20           386 386 386 12 12     386       238 87   151          
define([
	'dojo/_base/declare',
	'dojo/_base/lang',
	'dojo/_base/array',
	'dojo/aspect',
	'dojo/dom-construct',
	'dojo/dom-class',
	'dojo/on',
	'dojo/query',
	'dojo/when',
	'./util/has-css3',
	'./Grid',
	'dojo/has!touch?./util/touch'
], function (declare, lang, arrayUtil, aspect, domConstruct, domClass, on, querySelector, when, has, Grid, touchUtil) {
 
	return declare(null, {
		// collapseOnRefresh: Boolean
		//		Whether to collapse all expanded nodes any time refresh is called.
		collapseOnRefresh: false,
 
		// enableTreeTransitions: Boolean
		//		Enables/disables all expand/collapse CSS transitions.
		enableTreeTransitions: true,
 
		// treeIndentWidth: Number
		//		Width (in pixels) of each level of indentation.
		treeIndentWidth: 9,
 
		constructor: function () {
			this._treeColumnListeners = [];
		},
 
		shouldExpand: function (row, level, previouslyExpanded) {
			// summary:
			//		Function called after each row is inserted to determine whether
			//		expand(rowElement, true) should be automatically called.
			//		The default implementation re-expands any rows that were expanded
			//		the last time they were rendered (if applicable).
 
			return previouslyExpanded;
		},
 
		expand: function (target, expand, noTransition, lastRowsFirst) {
			// summary:
			//		Expands the row corresponding to the given target.
			// target: Object
			//		Row object (or something resolvable to one) to expand/collapse.
			// expand: Boolean?
			//		If specified, designates whether to expand or collapse the row;
			//		if unspecified, toggles the current state.
 
			Iif (!this._treeColumn) {
				return;
			}
 
			var grid = this,
				row = target.element ? target : this.row(target),
				isExpanded = !!this._expanded[row.id],
				hasTransitionend = has('transitionend'),
				promise;
 
			function processScroll() {
				if (!expanded) {
					grid._processScroll && grid._processScroll();
				}
			}
 
			target = row.element;
			target = target.className.indexOf('dgrid-expando-icon') > -1 ? target :
				querySelector('.dgrid-expando-icon', target)[0];
 
			noTransition = noTransition || !this.enableTreeTransitions;
 
			Eif (target && target.mayHaveChildren && (noTransition || expand !== isExpanded)) {
				// toggle or set expand/collapsed state based on optional 2nd argument
				var expanded = expand === undefined ? !this._expanded[row.id] : expand;
 
				// Update _expanded map.
				var pos = this.getScrollPosition();
				this._resetExpanded(row.id, expanded);
 
				// update the expando display
				domClass.replace(target, 'ui-icon-triangle-1-' + (expanded ? 'se' : 'e'),
					'ui-icon-triangle-1-' + (expanded ? 'e' : 'se'));
				domClass.toggle(row.element, 'dgrid-row-expanded', expanded);
 
				var rowElement = row.element,
					container = rowElement.connected,
					containerStyle,
					scrollHeight,
					options = {};
 
				if (!container) {
					// if the children have not been created, create a container, a preload node and do the
					// query for the children
					container = options.container = rowElement.connected =
						domConstruct.create('div', { className: 'dgrid-tree-container' }, rowElement, 'after');
					var query = function (options) {
						var childCollection = grid._renderedCollection.getChildren(row.data),
							results;
						if (grid.sort && grid.sort.length > 0) {
							childCollection = childCollection.sort(grid.sort);
						}
						if (childCollection.track && grid.shouldTrackCollection) {
							container._rows = options.rows = [];
 
							childCollection = childCollection.track();
 
							// remember observation handles so they can be removed when the parent row is destroyed
							container._handles = [
								childCollection.tracking,
								grid._observeCollection(childCollection, container, options)
							];
						}
						query.collection = childCollection;
						if ('start' in options) {
							var rangeArgs = {
								start: options.start,
								end: options.start + options.count
							};
							results = childCollection.fetchRange(rangeArgs);
						} else {
							results = childCollection.fetch();
						}
						return results;
					};
					Eif ('level' in target) {
						// Include level information on query for renderQuery case;
						// include on container for insertRow to detect in other cases
						container.level = query.level = target.level + 1;
					}
 
					// Add the query to the promise chain
					if (this.renderQuery) {
						Iif (lastRowsFirst) {
							promise = grid._renderedCollection.getChildren(row.data)
								.fetchRange({ start: 0, end: 1 }).totalLength.then(function (total) {
									options.start = total - grid.minRowsPerPage;
									options.end = total - 1;
									options.count = grid.minRowsPerPage;
 
									grid._previousScrollPosition = pos;
 
									return grid.renderQuery(query, options);
								});
						} else {
							promise = this.renderQuery(query, options);
						}
 
					}
					else {
						// If not using OnDemandList, we don't need preload nodes,
						// but we still need a beforeNode to pass to renderArray,
						// so create a temporary one
						var firstChild = domConstruct.create('div', null, container);
						promise = this._trackError(function () {
							return grid.renderQueryResults(
								query(options),
								firstChild,
								lang.mixin({ rows: options.rows },
									'level' in query ? { queryLevel: query.level } : null
								)
							).then(function (rows) {
								domConstruct.destroy(firstChild);
								return rows;
							});
						});
					}
 
					Eif (hasTransitionend) {
						// Update height whenever a collapse/expand transition ends.
						// (This handler is only registered when each child container is first created.)
						on(container, hasTransitionend, this._onTreeTransitionEnd);
					}
				}
 
				// Show or hide all the children.
 
				container.hidden = !expanded;
				containerStyle = container.style;
 
				// make sure it is visible so we can measure it
				if (!hasTransitionend || noTransition) {
					containerStyle.display = expanded ? 'block' : 'none';
					containerStyle.height = '';
					processScroll();
				}
				else {
					on.once(container, hasTransitionend, processScroll);
					if (expanded) {
						containerStyle.display = 'block';
						scrollHeight = container.scrollHeight;
						containerStyle.height = '0px';
					}
					else {
						// if it will be hidden we need to be able to give a full height
						// without animating it, so it has the right starting point to animate to zero
						domClass.add(container, 'dgrid-tree-resetting');
						containerStyle.height = container.scrollHeight + 'px';
					}
					// Perform a transition for the expand or collapse.
					setTimeout(function () {
						domClass.remove(container, 'dgrid-tree-resetting');
						containerStyle.height =
							expanded ? (scrollHeight ? scrollHeight + 'px' : 'auto') : '0px';
					}, 0);
				}
			}
 
			// Always return a promise
			return when(promise);
		},
 
		_configColumns: function () {
			var columnArray = this.inherited(arguments);
 
			// Set up hash to store IDs of expanded rows (here rather than in
			// _configureTreeColumn so nothing breaks if no column has renderExpando)
			this._resetExpanded();
 
			for (var i = 0, l = columnArray.length; i < l; i++) {
				if (columnArray[i].renderExpando) {
					this._configureTreeColumn(columnArray[i]);
					break; // Allow only one tree column.
				}
			}
			return columnArray;
		},
 
		insertRow: function (object, container, beforeNode, i, options) {
			options = options || {};
			var grid = this;
 
			var level = options.queryLevel = 'queryLevel' in options ? options.queryLevel :
				'level' in container ? container.level : 0;
 
			var rowElement = this.inherited(arguments);
 
			// Auto-expand (shouldExpand) considerations
			var row = this.row(rowElement),
				expanded = this.shouldExpand(row, level, this._expanded[row.id]);
 
			if (expanded) {
				this.expand(rowElement, true, true, options.scrollingUp);
			}
 
			if (expanded || (!this.collection.mayHaveChildren || this.collection.mayHaveChildren(object))) {
				domClass.add(rowElement, 'dgrid-row-expandable');
			}
 
			return rowElement; // pass return value through
		},
 
		_queueNodeForDeletion: function (node) {
			this.inherited(arguments);
 
			var connected = node.connected;
			if (connected) {
				this._deleteQueue.push(connected);
			}
		},
 
		_pruneRow: function (rowElement, removeBelow) {
			var connected = rowElement.connected;
			var preloadNode;
			var preload;
			if (connected) {
				var rowId = this.row(rowElement).id;
				Eif (this._expanded[rowId]) {
					preloadNode = querySelector('>.dgrid-preload', connected)[removeBelow ? 1 : 0];
					Eif (preloadNode) {
						preload = this._findPreload(preloadNode);
						preload = removeBelow ? preload.next : preload.previous;
						Eif (!preload.expandedContent) {
							preload.expandedContent = {};
						}
						preload.expandedContent[rowId] = connected.offsetHeight;
					}
				}
			}
 
			this.inherited(arguments, [rowElement, removeBelow, {
				treePrune: true,
				removeBelow: removeBelow
			}]);
		},
 
		removeRow: function (rowElement, preserveDom, options) {
			var connected = rowElement.connected,
				childOptions = {},
				childRows,
				preloadNodes,
				firstIndex,
				lastIndex;
			if (connected) {
				if (connected._handles) {
					arrayUtil.forEach(connected._handles, function (handle) {
						handle.remove();
					});
					delete connected._handles;
				}
 
				if (connected._rows) {
					childOptions.rows = connected._rows;
				}
 
				childRows = querySelector('>.dgrid-row', connected);
				preloadNodes = querySelector('>.dgrid-preload', connected);
				if (childRows && childRows.length) {
 
					if (this._releaseRange) {
						firstIndex = childRows[0].rowIndex;
						lastIndex = childRows[childRows.length - 1].rowIndex;
						this._releaseRange(this._findPreload(preloadNodes[0]), false, firstIndex, lastIndex);
					}
 
					childRows.forEach(function (element) {
						if (options && options.treePrune) {
							this._pruneRow(element, options.removeBelow);
						} else {
							this.removeRow(element, true, childOptions);
						}
					}, this);
				}
				this._removePreloads && this._removePreloads(preloadNodes);
 
				if (connected._rows) {
					connected._rows.length = 0;
					delete connected._rows;
				}
 
				if (preserveDom) {
					this._queueNodeForDeletion(connected);
				} else {
					domConstruct.destroy(connected);
				}
			}
 
			this.inherited(arguments);
		},
 
		_refreshCellFromItem: function (cell, item) {
			Iif (!cell.column.renderExpando) {
				return this.inherited(arguments);
			}
 
			this.inherited(arguments, [cell, item, {
				queryLevel: querySelector('.dgrid-expando-icon', cell.element)[0].level
			}]);
		},
 
		cleanup: function () {
			this.inherited(arguments);
 
			Iif (this.collapseOnRefresh) {
				// Clear out the _expanded hash on each call to cleanup
				// (which generally coincides with refreshes, as well as destroy)
				this._resetExpanded();
			}
		},
 
		_destroyColumns: function () {
			this.inherited(arguments);
			var listeners = this._treeColumnListeners;
 
			for (var i = listeners.length; i--;) {
				listeners[i].remove();
			}
			this._treeColumnListeners = [];
			this._treeColumn = null;
		},
 
		_calcRowHeight: function (rowElement) {
			// Override this method to provide row height measurements that
			// include the children of a row
			var connected = rowElement.connected;
			// if connected, need to consider this in the total row height
			return this.inherited(arguments) + (connected ? connected.offsetHeight : 0);
		},
 
		_configureTreeColumn: function (column) {
			// summary:
			//		Adds tree navigation capability to a column.
 
			var grid = this;
			var colSelector = '.dgrid-content .dgrid-column-' + column.id;
			var clicked; // tracks row that was clicked (for expand dblclick event handling)
 
			this._treeColumn = column;
			if (!column._isConfiguredTreeColumn) {
				var originalRenderCell = column.renderCell || this._defaultRenderCell;
				column._isConfiguredTreeColumn = true;
				column.renderCell = function (object, value, td, options) {
					// summary:
					//		Renders a cell that can be expanded, creating more rows
 
					var level = options && 'queryLevel' in options ? options.queryLevel : 0,
						mayHaveChildren = !grid.collection.mayHaveChildren || grid.collection.mayHaveChildren(object),
						expando, node;
 
					expando = column.renderExpando(level, mayHaveChildren,
						grid._expanded[grid.collection.getIdentity(object)], object);
					expando.level = level;
					expando.mayHaveChildren = mayHaveChildren;
 
					node = originalRenderCell.call(column, object, value, td, options);
					if (node && node.nodeType) {
						td.appendChild(expando);
						td.appendChild(node);
					}
					else {
						td.insertBefore(expando, td.firstChild);
					}
				};
 
				Eif (typeof column.renderExpando !== 'function') {
					column.renderExpando = this._defaultRenderExpando;
				}
			}
 
			var treeColumnListeners = this._treeColumnListeners;
			if (treeColumnListeners.length === 0) {
				// Set up the event listener once and use event delegation for better memory use.
				treeColumnListeners.push(this.on(column.expandOn ||
					'.dgrid-expando-icon:click,' + colSelector + ':dblclick,' + colSelector + ':keydown',
					function (event) {
						var row = grid.row(event);
						Eif ((!grid.collection.mayHaveChildren || grid.collection.mayHaveChildren(row.data)) &&
							(event.type !== 'keydown' || event.keyCode === 32) && !(event.type === 'dblclick' &&
							clicked && clicked.count > 1 && row.id === clicked.id &&
							event.target.className.indexOf('dgrid-expando-icon') > -1)) {
							grid.expand(row);
						}
 
						// If the expando icon was clicked, update clicked object to prevent
						// potential over-triggering on dblclick (all tested browsers but IE < 9).
						if (event.target.className.indexOf('dgrid-expando-icon') > -1) {
							if (clicked && clicked.id === grid.row(event).id) {
								clicked.count++;
							}
							else {
								clicked = {
									id: grid.row(event).id,
									count: 1
								};
							}
						}
					})
				);
 
				Iif (has('touch')) {
					// Also listen on double-taps of the cell.
					treeColumnListeners.push(this.on(touchUtil.selector(colSelector, touchUtil.dbltap),
						function () {
							grid.expand(this);
						}));
				}
			}
		},
 
		_defaultRenderExpando: function (level, hasChildren, expanded) {
			// summary:
			//		Default implementation for column.renderExpando.
			//		NOTE: Called in context of the column definition object.
			// level: Number
			//		Level of indentation for this row (0 for top-level)
			// hasChildren: Boolean
			//		Whether this item may have children (in most cases this determines
			//		whether an expando icon should be rendered)
			// expanded: Boolean
			//		Whether this item is currently in expanded state
			// object: Object
			//		The item that this expando pertains to
 
			var dir = this.grid.isRTL ? 'right' : 'left',
				cls = 'dgrid-expando-icon';
			if (hasChildren) {
				cls += ' ui-icon ui-icon-triangle-1-' + (expanded ? 'se' : 'e');
			}
			return domConstruct.create('div', {
				className: cls,
				innerHTML: '&nbsp;',
				style: 'margin-' + dir + ': ' + (level * this.grid.treeIndentWidth) + 'px; float: ' + dir + ';'
			});
		},
 
		_onNotification: function (rows, event) {
			if (event.type === 'delete') {
				this._resetExpanded(event.id);
			}
			this.inherited(arguments);
		},
 
		_onTreeTransitionEnd: function (event) {
			var container = this,
				height = this.style.height;
			Eif (height) {
				// After expansion, ensure display is correct;
				// after collapse, set display to none to improve performance
				this.style.display = height === '0px' ? 'none' : 'block';
			}
 
			// Reset height to be auto, so future height changes (from children
			// expansions, for example), will expand to the right height.
			Eif (event) {
				// For browsers with CSS transition support, setting the height to
				// auto or "" will cause an animation to zero height for some
				// reason, so temporarily set the transition to be zero duration
				domClass.add(this, 'dgrid-tree-resetting');
				setTimeout(function () {
					// Turn off the zero duration transition after we have let it render
					domClass.remove(container, 'dgrid-tree-resetting');
				}, 0);
			}
			// Now set the height to auto
			this.style.height = '';
		},
 
		_resetPlaceHolder: function (rowId) {
			var headPreload = this._getHeadPreload && this._getHeadPreload();
			var preload;
			var grid = this;
 
			if (!headPreload) {
				return;
			}
 
			function remove(rowId) {
				var preload = headPreload;
				while (preload) {
					var expandedContent = preload.expandedContent;
					Iif (expandedContent && expandedContent[rowId]) {
						delete expandedContent[rowId];
						grid._adjustPreloadHeight(preload);
						return;
					}
					preload = preload.next;
				}
			}
 
			Eif (rowId != null) {
				remove(rowId);
			} else {
				preload = headPreload;
				while (preload) {
					if (preload.expandedContent) {
						delete preload.expandedContent;
						grid._adjustPreloadHeight(preload);
					}
					preload = preload.next;
				}
			}
		},
 
		_resetExpanded: function (rowId, expanded) {
			// Always remove the place holder(s).
			this._resetPlaceHolder(rowId);
			if (rowId == null) {
				this._expanded = {};
			} else {
				if (expanded) {
					this._expanded[rowId] = true;
				} else {
					delete this._expanded[rowId];
				}
			}
		},
 
		_calculatePreloadHeight: function (preload) {
			var newHeight = this.inherited(arguments);
			var expandedContent = preload.expandedContent;
			if (expandedContent) {
				Object.keys(expandedContent).forEach(function (key) {
					newHeight += expandedContent[key];
				});
			}
			return newHeight;
		},
 
		_getRenderedCollection: function (preload) {
			if (preload.level) {
				return preload.query.collection;
			} else {
				return this.inherited(arguments);
			}
		}
	});
});