Debian Codegraph @

dojox/grid/TreeGrid.js

raw symbols SCIP
1 define([
2 "dojo/_base/kernel",
3 "../main",
4 "dojo/_base/declare",
5 "dojo/_base/array",
6 "dojo/_base/lang",
7 "dojo/_base/event",
8 "dojo/dom-attr",
9 "dojo/dom-class",
10 "dojo/query",
11 "dojo/keys",
12 "dijit/tree/ForestStoreModel",
13 "./DataGrid",
14 "./_Layout",
15 "./_FocusManager",
16 "./_RowManager",
17 "./_EditManager",
18 "./TreeSelection",
19 "./cells/tree",
20 "./_TreeView"
21 ], function(dojo, dojox, declare, array, lang, event, domAttr, domClass, query, keys, ForestStoreModel,
22 DataGrid, _Layout, _FocusManager, _RowManager, _EditManager, TreeSelection, TreeCell){
23
24 dojo.experimental("dojox.grid.TreeGrid");
25
26 var _TreeAggregator = declare("dojox.grid._TreeAggregator", null, {
27 cells: [],
28 grid: null,
29 childFields: [],
30
31 constructor: function(kwArgs){
32 this.cells = kwArgs.cells || [];
33 this.childFields = kwArgs.childFields || [];
34 this.grid = kwArgs.grid;
35 this.store = this.grid.store;
36 },
37 _cacheValue: function(cache, id, value){
38 cache[id] = value;
39 return value;
40 },
41 clearSubtotalCache: function(){
42 // summary:
43 // Clears the subtotal cache so that we are forced to recalc it
44 // (or reread it) again. This is needed, for example, when
45 // column order is changed.
46 if(this.store){
47 delete this.store._cachedAggregates;
48 }
49 },
50
51 cnt: function(cell, level, item){
52 // summary:
53 // calculates the count of the children of item at the given level
54 var total = 0;
55 var store = this.store;
56 var childFields = this.childFields;
57 if(childFields[level]){
58 var children = store.getValues(item, childFields[level]);
59 if (cell.index <= level + 1){
60 total = children.length;
61 }else{
62 array.forEach(children, function(c){
63 total += this.getForCell(cell, level + 1, c, "cnt");
64 }, this);
65 }
66 }else{
67 total = 1;
68 }
69 return total;
70 },
71 sum: function(cell, level, item){
72 // summary:
73 // calculates the sum of the children of item at the given level
74 var total = 0;
75 var store = this.store;
76 var childFields = this.childFields;
77 if(childFields[level]){
78 array.forEach(store.getValues(item, childFields[level]), function(c){
79 total += this.getForCell(cell, level + 1, c, "sum");
80 }, this);
81 }else{
82 total += store.getValue(item, cell.field);
83 }
84 return total;
85 },
86 value: function(cell, level, item){
87 // summary:
88 // Empty function so that we can set "aggregate='value'" to
89 // force loading from the data - and bypass calculating
90 },
91 getForCell: function(cell, level, item, type){
92 // summary:
93 // Gets the value of the given cell at the given level and type.
94 // type can be one of "sum", "cnt", or "value". If itemAggregates
95 // is set and can be used, it is used instead. Values are also
96 // cached to prevent calculating them too often.
97 var store = this.store;
98 if(!store || !item || !store.isItem(item)){ return ""; }
99 var storeCache = store._cachedAggregates = store._cachedAggregates || {};
100 var id = store.getIdentity(item);
101 var itemCache = storeCache[id] = storeCache[id] || [];
102 if(!cell.getOpenState){
103 cell = this.grid.getCell(cell.layoutIndex + level + 1);
104 }
105 var idx = cell.index;
106 var idxCache = itemCache[idx] = itemCache[idx] || {};
107 type = (type || (cell.parentCell ? cell.parentCell.aggregate : "sum"))||"sum";
108 var attr = cell.field;
109 if(attr == store.getLabelAttributes()[0]){
110 // If our attribute is one of the label attributes, we should
111 // use cnt instead (since it makes no sense to do a sum of labels)
112 type = "cnt";
113 }
114 var typeCache = idxCache[type] = idxCache[type] || [];
115
116 // See if we have it in our cache immediately for easy returning
117 if(typeCache[level] != undefined){
118 return typeCache[level];
119 }
120
121 // See if they have specified a valid field
122 var field = ((cell.parentCell && cell.parentCell.itemAggregates) ?
123 cell.parentCell.itemAggregates[cell.idxInParent] : "")||"";
124 if(field && store.hasAttribute(item, field)){
125 return this._cacheValue(typeCache, level, store.getValue(item, field));
126 }else if(field){
127 return this._cacheValue(typeCache, level, 0);
128 }
129
130 // Calculate it
131 return this._cacheValue(typeCache, level, this[type](cell, level, item));
132 }
133 });
134
135 var _TreeLayout = declare("dojox.grid._TreeLayout", _Layout, {
136 // Whether or not we are collapsable - this is calculated when we
137 // set our structure.
138 _isCollapsable: false,
139
140 _getInternalStructure: function(inStructure){
141 // Create a "Tree View" with 1 row containing references for
142 // each column (recursively)
143 var g = this.grid;
144
145 var s = inStructure;
146 var cells = s[0].cells[0];
147 var tree = {
148 type: "dojox.grid._TreeView",
149 cells: [[]]
150 };
151 var cFields = [];
152 var maxLevels = 0;
153 var getTreeCells = function(parentCell, level){
154 var children = parentCell.children;
155 var cloneTreeCell = function(originalCell, idx){
156 var k, n = {};
157 for(k in originalCell){
158 n[k] = originalCell[k];
159 }
160 n = lang.mixin(n, {
161 level: level,
162 idxInParent: level > 0 ? idx : -1,
163 parentCell: level > 0 ? parentCell : null
164 });
165 return n;
166 };
167 var ret = [];
168 array.forEach(children, function(c, idx){
169 if("children" in c){
170 cFields.push(c.field);
171 var last = ret[ret.length - 1];
172 last.isCollapsable = true;
173 c.level = level;
174 ret = ret.concat(getTreeCells(c, level + 1));
175 }else{
176 ret.push(cloneTreeCell(c, idx));
177 }
178 });
179 maxLevels = Math.max(maxLevels, level);
180 return ret;
181 };
182 var tCell = {children: cells, itemAggregates: []};
183 tree.cells[0] = getTreeCells(tCell, 0);
184 g.aggregator = new _TreeAggregator({cells: tree.cells[0],
185 grid: g,
186 childFields: cFields});
187 if(g.scroller && g.defaultOpen){
188 g.scroller.defaultRowHeight = g.scroller._origDefaultRowHeight * (2 * maxLevels + 1);
189 }
190 return [ tree ];
191 },
192
193 setStructure: function(inStructure){
194 // Mangle the structure a bit and make it work as desired
195 var s = inStructure;
196 var g = this.grid;
197 // Only supporting single-view, single row or else we
198 // are not collapsable
199 if(g && g.treeModel && !array.every(s, function(i){
200 return ("cells" in i);
201 })){
202 s = arguments[0] = [{cells:[s]}];
203 }
204 if(s.length == 1 && s[0].cells.length == 1){
205 if(g && g.treeModel){
206 s[0].type = "dojox.grid._TreeView";
207 this._isCollapsable = true;
208 s[0].cells[0][(this.grid.treeModel?this.grid.expandoCell:0)].isCollapsable = true;
209 }else{
210 var childCells = array.filter(s[0].cells[0], function(c){
211 return ("children" in c);
212 });
213 if(childCells.length === 1){
214 this._isCollapsable = true;
215 }
216 }
217 }
218 if(this._isCollapsable && (!g || !g.treeModel)){
219 arguments[0] = this._getInternalStructure(s);
220 }
221 this.inherited(arguments);
222 },
223
224 addCellDef: function(inRowIndex, inCellIndex, inDef){
225 var obj = this.inherited(arguments);
226 return lang.mixin(obj, TreeCell);
227 }
228 });
229
230 var TreePath = declare("dojox.grid.TreePath", null, {
231 level: 0,
232 _str: "",
233 _arr: null,
234 grid: null,
235 store: null,
236 cell: null,
237
238 constructor: function(/*String|Integer[]|Integer|dojox.grid.TreePath*/ path, /*dojox.grid.TreeGrid*/ grid){
239 if(lang.isString(path)){
240 this._str = path;
241 this._arr = array.map(path.split('/'), function(item){ return parseInt(item, 10); });
242 }else if(lang.isArray(path)){
243 this._str = path.join('/');
244 this._arr = path.slice(0);
245 }else if(typeof path == "number"){
246 this._str = String(path);
247 this._arr = [path];
248 }else{
249 this._str = path._str;
250 this._arr = path._arr.slice(0);
251 }
252 this.level = this._arr.length-1;
253 this.grid = grid;
254 this.store = this.grid.store;
255 if(grid.treeModel){
256 this.cell = grid.layout.cells[grid.expandoCell];
257 }else{
258 this.cell = grid.layout.cells[this.level];
259 }
260 },
261 item: function(){
262 // summary:
263 // gets the dojo.data item associated with this path
264 if(!this._item){
265 this._item = this.grid.getItem(this._arr);
266 }
267 return this._item;
268 },
269 compare: function(path /*dojox.grid.TreePath|String|Array*/){
270 // summary:
271 // compares two paths
272 if(lang.isString(path) || lang.isArray(path)){
273 if(this._str == path){ return 0; }
274 if(path.join && this._str == path.join('/')){ return 0; }
275 path = new TreePath(path, this.grid);
276 }else if(path instanceof TreePath){
277 if(this._str == path._str){ return 0; }
278 }
279 for(var i=0, l=(this._arr.length < path._arr.length ? this._arr.length : path._arr.length); i<l; i++){
280 if(this._arr[i]<path._arr[i]){ return -1; }
281 if(this._arr[i]>path._arr[i]){ return 1; }
282 }
283 if(this._arr.length<path._arr.length){ return -1; }
284 if(this._arr.length>path._arr.length){ return 1; }
285 return 0;
286 },
287 isOpen: function(){
288 // summary:
289 // Returns the open state of this cell.
290 return this.cell.openStates && this.cell.getOpenState(this.item());
291 },
292 previous: function(){
293 // summary:
294 // Returns the path that is before this path in the
295 // grid. If no path is found, returns null.
296 var new_path = this._arr.slice(0);
297
298 if(this._str == "0"){
299 return null;
300 }
301
302 var last = new_path.length-1;
303
304 if(new_path[last] === 0){
305 new_path.pop();
306 return new TreePath(new_path, this.grid);
307 }
308
309 new_path[last]--;
310 var path = new TreePath(new_path, this.grid);
311 return path.lastChild(true);
312 },
313 next: function(){
314 // summary:
315 // Returns the next path in the grid. If no path
316 // is found, returns null.
317 var new_path = this._arr.slice(0);
318
319 if(this.isOpen()){
320 new_path.push(0);
321 }else{
322 new_path[new_path.length-1]++;
323 for(var i=this.level; i>=0; i--){
324 var item = this.grid.getItem(new_path.slice(0, i+1));
325 if(i>0){
326 if(!item){
327 new_path.pop();
328 new_path[i-1]++;
329 }
330 }else{
331 if(!item){
332 return null;
333 }
334 }
335 }
336 }
337
338 return new TreePath(new_path, this.grid);
339 },
340 children: function(alwaysReturn){
341 // summary:
342 // Returns the child data items of this row. If this
343 // row isn't open and alwaysReturn is falsey, returns null.
344 if(!this.isOpen()&&!alwaysReturn){
345 return null;
346 }
347 var items = [];
348 var model = this.grid.treeModel;
349 if(model){
350 var item = this.item();
351 var store = model.store;
352 if(!model.mayHaveChildren(item)){
353 return null;
354 }
355 array.forEach(model.childrenAttrs, function(attr){
356 items = items.concat(store.getValues(item, attr));
357 });
358 }else{
359 items = this.store.getValues(this.item(), this.grid.layout.cells[this.cell.level+1].parentCell.field);
360 if(items.length>1&&this.grid.sortChildItems){
361 var sortProps = this.grid.getSortProps();
362 if(sortProps&&sortProps.length){
363 var attr = sortProps[0].attribute,
364 grid = this.grid;
365 if(attr&&items[0][attr]){
366 var desc = !!sortProps[0].descending;
367 items = items.slice(0); // don't touch the array in the store, make a copy
368 items.sort(function(a, b){
369 return grid._childItemSorter(a, b, attr, desc);
370 });
371 }
372 }
373 }
374 }
375 return items;
376 },
377 childPaths: function(){
378 var childItems = this.children();
379 if(!childItems){
380 return [];
381 }
382 return array.map(childItems, function(item, index){
383 return new TreePath(this._str + '/' + index, this.grid);
384 }, this);
385 },
386 parent: function(){
387 // summary:
388 // Returns the parent path of this path. If this is a
389 // top-level row, returns null.
390 if(this.level === 0){
391 return null;
392 }
393 return new TreePath(this._arr.slice(0, this.level), this.grid);
394 },
395 lastChild: function(/*Boolean?*/ traverse){
396 // summary:
397 // Returns the last child row below this path. If traverse
398 // is true, will traverse down to find the last child row
399 // of this branch. If there are no children, returns itself.
400 var children = this.children();
401 if(!children || !children.length){
402 return this;
403 }
404 var path = new TreePath(this._str + "/" + String(children.length-1), this.grid);
405 if(!traverse){
406 return path;
407 }
408 return path.lastChild(true);
409 },
410 toString: function(){
411 return this._str;
412 }
413 });
414
415 var _TreeFocusManager = declare("dojox.grid._TreeFocusManager", _FocusManager, {
416 setFocusCell: function(inCell, inRowIndex){
417 if(inCell && inCell.getNode(inRowIndex)){
418 this.inherited(arguments);
419 }
420 },
421 isLastFocusCell: function(){
422 if(this.cell && this.cell.index == this.grid.layout.cellCount-1){
423 var path = new TreePath(this.grid.rowCount-1, this.grid);
424 path = path.lastChild(true);
425 return this.rowIndex == path._str;
426 }
427 return false;
428 },
429 next: function(){
430 // summary:
431 // focus next grid cell
432 if(this.cell){
433 var row=this.rowIndex, col=this.cell.index+1, cc=this.grid.layout.cellCount-1;
434 var path = new TreePath(this.rowIndex, this.grid);
435 if(col > cc){
436 var new_path = path.next();
437 if(!new_path){
438 col--;
439 }else{
440 col = 0;
441 path = new_path;
442 }
443 }
444 if(this.grid.edit.isEditing()){ //when editing, only navigate to editable cells
445 var nextCell = this.grid.getCell(col);
446 if (!this.isLastFocusCell() && !nextCell.editable){
447 this._focusifyCellNode(false);
448 this.cell=nextCell;
449 this.rowIndex=path._str;
450 this.next();
451 return;
452 }
453 }
454 this.setFocusIndex(path._str, col);
455 }
456 },
457 previous: function(){
458 // summary:
459 // focus previous grid cell
460 if(this.cell){
461 var row=(this.rowIndex || 0), col=(this.cell.index || 0) - 1;
462 var path = new TreePath(row, this.grid);
463 if(col < 0){
464 var new_path = path.previous();
465 if(!new_path){
466 col = 0;
467 }else{
468 col = this.grid.layout.cellCount-1;
469 path = new_path;
470 }
471 }
472 if(this.grid.edit.isEditing()){ //when editing, only navigate to editable cells
473 var prevCell = this.grid.getCell(col);
474 if (!this.isFirstFocusCell() && !prevCell.editable){
475 this._focusifyCellNode(false);
476 this.cell=prevCell;
477 this.rowIndex=path._str;
478 this.previous();
479 return;
480 }
481 }
482 this.setFocusIndex(path._str, col);
483 }
484 },
485 move: function(inRowDelta, inColDelta){
486 if(this.isNavHeader()){
487 this.inherited(arguments);
488 return;
489 }
490 if(!this.cell){ return; }
491 // Handle grid proper.
492 var sc = this.grid.scroller,
493 r = this.rowIndex,
494 rc = this.grid.rowCount-1,
495 path = new TreePath(this.rowIndex, this.grid);
496 if(inRowDelta){
497 var row;
498 if(inRowDelta>0){
499 path = path.next();
500 row = path._arr[0];
501 if(row > sc.getLastPageRow(sc.page)){
502 //need to load additional data, let scroller do that
503 this.grid.setScrollTop(this.grid.scrollTop+sc.findScrollTop(row)-sc.findScrollTop(r));
504 }
505 }else if(inRowDelta<0){
506 path = path.previous();
507 row = path._arr[0];
508 if(row <= sc.getPageRow(sc.page)){
509 //need to load additional data, let scroller do that
510 this.grid.setScrollTop(this.grid.scrollTop-sc.findScrollTop(r)-sc.findScrollTop(row));
511 }
512 }
513 }
514 var cc = this.grid.layout.cellCount-1,
515 i = this.cell.index,
516 col = Math.min(cc, Math.max(0, i+inColDelta));
517 var cell = this.grid.getCell(col);
518 var colDir = inColDelta < 0 ? -1 : 1;
519 while(col>=0 && col < cc && cell && cell.hidden === true){
520 // skip hidden cells
521 col += colDir;
522 cell = this.grid.getCell(col);
523 }
524 if (!cell || cell.hidden === true){
525 // don't change col if would move to hidden
526 col = i;
527 }
528 if(inRowDelta){
529 this.grid.updateRow(r);
530 }
531 this.setFocusIndex(path._str, col);
532 }
533 });
534
535 var TreeGrid = declare("dojox.grid.TreeGrid", DataGrid, {
536 // summary:
537 // A grid that supports nesting rows - it provides an expando function
538 // similar to dijit.Tree. It also provides mechanisms for aggregating
539 // the values of subrows
540 // description:
541 // TreeGrid currently only works on "simple" structures. That is,
542 // single-view structures with a single row in them.
543 //
544 // The TreeGrid works using the concept of "levels" - level 0 are the
545 // top-level items.
546
547 // defaultOpen: Boolean
548 // Whether or not we default to open (all levels). This defaults to
549 // false for grids with a treeModel.
550 defaultOpen: true,
551
552 // sortChildItems: Boolean
553 // If true, child items will be returned sorted according to the sorting
554 // properties of the grid.
555 sortChildItems: false,
556
557 // openAtLevels: Array
558 // Which levels we are open at (overrides defaultOpen for the values
559 // that exist here). Its values can be a boolean (true/false) or an
560 // integer (for the # of children to be closed if there are more than
561 // that)
562 openAtLevels: [],
563
564 // treeModel: dijit.tree.ForestStoreModel
565 // A dijit.Tree model that will be used instead of using aggregates.
566 // Setting this value will make the TreeGrid behave like a columnar
567 // tree. When setting this value, defaultOpen will default to false,
568 // and openAtLevels will be ignored.
569 treeModel: null,
570
571 // expandoCell: Integer
572 // When used in conjunction with a treeModel (see above), this is a 0-based
573 // index of the cell in which to place the actual expando
574 expandoCell: 0,
575
576 // aggregator: Object
577 // The aggregator class - it will be populated automatically if we
578 // are a collapsible grid
579 aggregator: null,
580
581
582 // Override this to get our "magic" layout
583 _layoutClass: _TreeLayout,
584
585 createSelection: function(){
586 this.selection = new TreeSelection(this);
587 },
588
589 _childItemSorter: function(a, b, attribute, descending){
590 var av = this.store.getValue(a, attribute);
591 var bv = this.store.getValue(b, attribute);
592 if(av != bv){
593 return av < bv == descending ? 1 : -1;
594 }
595 return 0;
596 },
597
598 _onNew: function(item, parentInfo){
599 if(!parentInfo || !parentInfo.item){
600 this.inherited(arguments);
601 }else{
602 var idx = this.getItemIndex(parentInfo.item);
603 if(typeof idx == "string"){
604 this.updateRow(idx.split('/')[0]);
605 }else if(idx > -1){
606 this.updateRow(idx);
607 }
608 }
609 },
610
611 _onSet: function(item, attribute, oldValue, newValue){
612 this._checkUpdateStatus();
613 if(this.aggregator){
614 this.aggregator.clearSubtotalCache();
615 }
616 var idx = this.getItemIndex(item);
617 if(typeof idx == "string"){
618 this.updateRow(idx.split('/')[0]);
619 }else if(idx > -1){
620 this.updateRow(idx);
621 }
622 },
623
624 _onDelete: function(item){
625 this._cleanupExpandoCache(this._getItemIndex(item, true), this.store.getIdentity(item), item);
626 this.inherited(arguments);
627 },
628
629 _clearData: function() {
630 this.inherited(arguments);
631 this._by_idty_paths = {};
632 },
633
634 _cleanupExpandoCache: function(index, identity, item){},
635
636 _addItem: function(item, index, noUpdate, dontUpdateRoot){
637 // add our root items to the root of the model's children
638 // list since we don't query the model
639 if(!dontUpdateRoot && this.model && array.indexOf(this.model.root.children, item) == -1){
640 this.model.root.children[index] = item;
641 }
642 this.inherited(arguments);
643 },
644
645 getItem: function(/*integer|Array|String*/ idx){
646 // summary:
647 // overridden so that you can pass in a '/' delimited string of indexes to get the
648 // item based off its path...that is, passing in "1/3/2" will get the
649 // 3rd (0-based) child from the 4th child of the 2nd top-level item.
650 var isArray = lang.isArray(idx);
651 if(lang.isString(idx) && idx.indexOf('/')){
652 idx = idx.split('/');
653 isArray = true;
654 }
655 if(isArray && idx.length == 1){
656 idx = idx[0];
657 isArray = false;
658 }
659 if(!isArray){
660 return DataGrid.prototype.getItem.call(this, idx);
661 }
662 var s = this.store;
663 var itm = DataGrid.prototype.getItem.call(this, idx[0]);
664 var cf, i, j;
665 if(this.aggregator){
666 cf = this.aggregator.childFields||[];
667 if(cf){
668 for(i = 0; i < idx.length - 1 && itm; i++){
669 if(cf[i]){
670 itm = (s.getValues(itm, cf[i])||[])[idx[i + 1]];
671 }else{
672 itm = null;
673 }
674 }
675 }
676 }else if(this.treeModel){
677 cf = this.treeModel.childrenAttrs||[];
678 if(cf&&itm){
679 for(i=1, il=idx.length; (i<il) && itm; i++) {
680 for(j=0, jl=cf.length; j<jl; j++) {
681 if(cf[j]){
682 itm = (s.getValues(itm, cf[j])||[])[idx[i]];
683 }else{
684 itm = null;
685 }
686 if(itm){ break; }
687 }
688 }
689 }
690 }
691 return itm || null;
692 },
693
694 _getItemIndex: function(item, isDeleted){
695 if(!isDeleted && !this.store.isItem(item)){
696 return -1;
697 }
698 var idx = this.inherited(arguments);
699 if(idx == -1){
700 var idty = this.store.getIdentity(item);
701 return this._by_idty_paths[idty] || -1;
702 }
703 return idx;
704 },
705
706 postMixInProperties: function(){
707 if(this.treeModel && !("defaultOpen" in this.params)){
708 // Default open to false for tree models, true for other tree
709 // grids.
710 this.defaultOpen = false;
711 }
712 var def = this.defaultOpen;
713 this.openAtLevels = array.map(this.openAtLevels, function(l){
714 if(typeof l == "string"){
715 switch(l.toLowerCase()){
716 case "true":
717 return true;
718 break;
719 case "false":
720 return false;
721 break;
722 default:
723 var r = parseInt(l, 10);
724 if(isNaN(r)){
725 return def;
726 }
727 return r;
728 break;
729 }
730 }
731 return l;
732 });
733 this._by_idty_paths = {};
734 this.inherited(arguments);
735 },
736
737 postCreate: function(){
738 this.inherited(arguments);
739 if(this.treeModel){
740 this._setModel(this.treeModel);
741 }
742 },
743
744 setModel: function(treeModel){
745 this._setModel(treeModel);
746 this._refresh(true);
747 },
748
749 _setModel: function(treeModel){
750 if(treeModel && (!ForestStoreModel || !(treeModel instanceof ForestStoreModel))){
751 throw new Error("dojox.grid.TreeGrid: treeModel must be an instance of dijit.tree.ForestStoreModel");
752 }
753 this.treeModel = treeModel;
754 domClass.toggle(this.domNode, "dojoxGridTreeModel", this.treeModel ? true : false);
755 this._setQuery(treeModel ? treeModel.query : null);
756 this._setStore(treeModel ? treeModel.store : null);
757 },
758
759 createScroller: function(){
760 this.inherited(arguments);
761 this.scroller._origDefaultRowHeight = this.scroller.defaultRowHeight;
762 },
763
764 createManagers: function(){
765 // summary:
766 // create grid managers for various tasks including rows, focus, selection, editing
767
768 // row manager
769 this.rows = new _RowManager(this);
770 // focus manager
771 this.focus = new _TreeFocusManager(this);
772 // edit manager
773 this.edit = new _EditManager(this);
774 },
775
776 _setStore: function(store){
777 this.inherited(arguments);
778 if(this.treeModel&&!this.treeModel.root.children){
779 this.treeModel.root.children = [];
780 }
781 if(this.aggregator){
782 this.aggregator.store = store;
783 }
784 },
785
786 getDefaultOpenState: function(cellDef, item){
787 // summary:
788 // Returns the default open state for the given definition and item
789 // It reads from the openAtLevels and defaultOpen values of the
790 // grid to calculate if the given item should default to open or
791 // not.
792 var cf;
793 var store = this.store;
794 if(this.treeModel){ return this.defaultOpen; }
795 if(!cellDef || !store || !store.isItem(item) ||
796 !(cf = this.aggregator.childFields[cellDef.level])){
797 return this.defaultOpen;
798 }
799 if(this.openAtLevels.length > cellDef.level){
800 var dVal = this.openAtLevels[cellDef.level];
801 if(typeof dVal == "boolean"){
802 return dVal;
803 }else if(typeof dVal == "number"){
804 return (store.getValues(item, cf).length <= dVal);
805 }
806 }
807 return this.defaultOpen;
808 },
809 onStyleRow: function(row){
810 if(!this.layout._isCollapsable){
811 this.inherited(arguments);
812 return;
813 }
814 var base = domAttr.get(row.node, 'dojoxTreeGridBaseClasses');
815 if(base){
816 row.customClasses = base;
817 }
818 var i = row;
819 var tagName = i.node.tagName.toLowerCase();
820 i.customClasses += (i.odd?" dojoxGridRowOdd":"") +
821 (i.selected&&tagName=='tr'?" dojoxGridRowSelected":"") +
822 (i.over&&tagName=='tr'?" dojoxGridRowOver":"");
823 this.focus.styleRow(i);
824 this.edit.styleRow(i);
825 },
826 styleRowNode: function(inRowIndex, inRowNode){
827 if(inRowNode){
828 if(inRowNode.tagName.toLowerCase() == 'div' && this.aggregator){
829 query("tr[dojoxTreeGridPath]", inRowNode).forEach(function(rowNode){
830 this.rows.styleRowNode(domAttr.get(rowNode, 'dojoxTreeGridPath'), rowNode);
831 },this);
832 }
833 this.rows.styleRowNode(inRowIndex, inRowNode);
834 }
835 },
836 onCanSelect: function(inRowIndex){
837 var nodes = query("tr[dojoxTreeGridPath='" + inRowIndex + "']", this.domNode);
838 if(nodes.length){
839 if(domClass.contains(nodes[0], 'dojoxGridSummaryRow')){
840 return false;
841 }
842 }
843 return this.inherited(arguments);
844 },
845 onKeyDown: function(e){
846 if(e.altKey || e.metaKey){
847 return;
848 }
849 switch(e.keyCode){
850 case keys.UP_ARROW:
851 if(!this.edit.isEditing() && this.focus.rowIndex != "0"){
852 event.stop(e);
853 this.focus.move(-1, 0);
854 }
855 break;
856 case keys.DOWN_ARROW:
857 var currPath = new TreePath(this.focus.rowIndex, this);
858 var lastPath = new TreePath(this.rowCount-1, this);
859 lastPath = lastPath.lastChild(true);
860 if(!this.edit.isEditing() && currPath.toString() != lastPath.toString()){
861 event.stop(e);
862 this.focus.move(1, 0);
863 }
864 break;
865 default:
866 this.inherited(arguments);
867 break;
868 }
869 },
870 canEdit: function(inCell, inRowIndex){
871 var node = inCell.getNode(inRowIndex);
872 return node && this._canEdit;
873 },
874 doApplyCellEdit: function(inValue, inRowIndex, inAttrName){
875 var item = this.getItem(inRowIndex);
876 var oldValue = this.store.getValue(item, inAttrName);
877 if(typeof oldValue == 'number'){
878 inValue = isNaN(inValue) ? inValue : parseFloat(inValue);
879 }else if(typeof oldValue == 'boolean'){
880 inValue = inValue == 'true' ? true : inValue == 'false' ? false : inValue;
881 }else if(oldValue instanceof Date){
882 var asDate = new Date(inValue);
883 inValue = isNaN(asDate.getTime()) ? inValue : asDate;
884 }
885 this.store.setValue(item, inAttrName, inValue);
886 this.onApplyCellEdit(inValue, inRowIndex, inAttrName);
887 }
888 });
889 TreeGrid.markupFactory = function(props, node, ctor, cellFunc){
890 var widthFromAttr = function(n){
891 var w = domAttr.get(n, "width")||"auto";
892 if((w != "auto")&&(w.slice(-2) != "em")&&(w.slice(-1) != "%")){
893 w = parseInt(w, 10)+"px";
894 }
895 return w;
896 };
897
898 var cellsFromMarkup = function(table){
899 var rows;
900 // Don't support colgroup on our grid - single view, single row only
901 if(table.nodeName.toLowerCase() == "table" &&
902 query("> colgroup", table).length === 0 &&
903 (rows = query("> thead > tr", table)).length == 1){
904 var tr = rows[0];
905 return query("> th", rows[0]).map(function(th){
906 // Grab type and field (the only ones that are shared
907 var cell = {
908 type: lang.trim(domAttr.get(th, "cellType")||""),
909 field: lang.trim(domAttr.get(th, "field")||"")
910 };
911 if(cell.type){
912 cell.type = lang.getObject(cell.type);
913 }
914
915 var subTable = query("> table", th)[0];
916 if(subTable){
917 // If we have a subtable, we are an aggregate and a summary cell
918 cell.name = "";
919 cell.children = cellsFromMarkup(subTable);
920 if(domAttr.has(th, "itemAggregates")){
921 cell.itemAggregates = array.map(domAttr.get(th, "itemAggregates").split(","), function(v){
922 return lang.trim(v);
923 });
924 }else{
925 cell.itemAggregates = [];
926 }
927 if(domAttr.has(th, "aggregate")){
928 cell.aggregate = domAttr.get(th, "aggregate");
929 }
930 cell.type = cell.type || dojox.grid.cells.SubtableCell;
931 }else{
932 // Grab our other stuff we need (mostly what's in the normal
933 // Grid)
934 cell.name = lang.trim(domAttr.get(th, "name")||th.innerHTML);
935 if(domAttr.has(th, "width")){
936 cell.width = widthFromAttr(th);
937 }
938 if(domAttr.has(th, "relWidth")){
939 cell.relWidth = window.parseInt(domAttr.get(th, "relWidth"), 10);
940 }
941 if(domAttr.has(th, "hidden")){
942 cell.hidden = domAttr.get(th, "hidden") == "true";
943 }
944 cell.field = cell.field||cell.name;
945 DataGrid.cell_markupFactory(cellFunc, th, cell);
946 cell.type = cell.type || dojox.grid.cells.Cell;
947 }
948 if(cell.type && cell.type.markupFactory){
949 cell.type.markupFactory(th, cell);
950 }
951 return cell;
952 });
953 }
954 return [];
955 };
956
957 var rows;
958 if( !props.structure ){
959 var row = cellsFromMarkup(node);
960 if(row.length){
961 // Set our structure here - so that we don't try and set it in the
962 // markup factory
963 props.structure = [{__span: Infinity, cells:[row]}];
964 }
965 }
966 return DataGrid.markupFactory(props, node, ctor, cellFunc);
967 };
968
969 return TreeGrid;
970
971 });