4 * Copyright(c) 2006-2007, Ext JS, LLC.
6 * Originally Released Under LGPL - original licence link has changed is not relivant.
9 * <script type="text/javascript">
13 * @class Roo.grid.GridView
14 * @extends Roo.util.Observable
17 * @param {Object} config
19 Roo.grid.GridView = function(config){
20 Roo.grid.GridView.superclass.constructor.call(this);
23 Roo.apply(this, config);
26 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
28 unselectable : 'unselectable="on"',
29 unselectableCls : 'x-unselectable',
32 rowClass : "x-grid-row",
34 cellClass : "x-grid-col",
36 tdClass : "x-grid-td",
38 hdClass : "x-grid-hd",
40 splitClass : "x-grid-split",
42 sortClasses : ["sort-asc", "sort-desc"],
44 enableMoveAnim : false,
50 fly : Roo.Element.fly,
60 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
62 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
64 bind : function(ds, cm){
66 this.ds.un("load", this.onLoad, this);
67 this.ds.un("datachanged", this.onDataChange, this);
68 this.ds.un("add", this.onAdd, this);
69 this.ds.un("remove", this.onRemove, this);
70 this.ds.un("update", this.onUpdate, this);
71 this.ds.un("clear", this.onClear, this);
74 ds.on("load", this.onLoad, this);
75 ds.on("datachanged", this.onDataChange, this);
76 ds.on("add", this.onAdd, this);
77 ds.on("remove", this.onRemove, this);
78 ds.on("update", this.onUpdate, this);
79 ds.on("clear", this.onClear, this);
84 this.cm.un("widthchange", this.onColWidthChange, this);
85 this.cm.un("headerchange", this.onHeaderChange, this);
86 this.cm.un("hiddenchange", this.onHiddenChange, this);
87 this.cm.un("columnmoved", this.onColumnMove, this);
88 this.cm.un("columnlockchange", this.onColumnLock, this);
91 this.generateRules(cm);
92 cm.on("widthchange", this.onColWidthChange, this);
93 cm.on("headerchange", this.onHeaderChange, this);
94 cm.on("hiddenchange", this.onHiddenChange, this);
95 cm.on("columnmoved", this.onColumnMove, this);
96 cm.on("columnlockchange", this.onColumnLock, this);
101 init: function(grid){
102 Roo.grid.GridView.superclass.init.call(this, grid);
104 this.bind(grid.dataSource, grid.colModel);
106 grid.on("headerclick", this.handleHeaderClick, this);
108 if(grid.trackMouseOver){
109 grid.on("mouseover", this.onRowOver, this);
110 grid.on("mouseout", this.onRowOut, this);
112 grid.cancelTextSelection = function(){};
113 this.gridId = grid.id;
115 var tpls = this.templates || {};
118 tpls.master = new Roo.Template(
119 '<div class="x-grid" hidefocus="true">',
120 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
121 '<div class="x-grid-topbar"></div>',
122 '<div class="x-grid-scroller"><div></div></div>',
123 '<div class="x-grid-locked">',
124 '<div class="x-grid-header">{lockedHeader}</div>',
125 '<div class="x-grid-body">{lockedBody}</div>',
127 '<div class="x-grid-viewport">',
128 '<div class="x-grid-header">{header}</div>',
129 '<div class="x-grid-body">{body}</div>',
131 '<div class="x-grid-bottombar"></div>',
133 '<div class="x-grid-resize-proxy"> </div>',
136 tpls.master.disableformats = true;
140 tpls.header = new Roo.Template(
141 '<table border="0" cellspacing="0" cellpadding="0">',
142 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
145 tpls.header.disableformats = true;
147 tpls.header.compile();
150 tpls.hcell = new Roo.Template(
151 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
152 '<div class="x-grid-hd-text ' + this.unselectableCls + '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
155 tpls.hcell.disableFormats = true;
157 tpls.hcell.compile();
160 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
161 this.unselectableCls + '" ' + this.unselectable +'> </div>');
162 tpls.hsplit.disableFormats = true;
164 tpls.hsplit.compile();
167 tpls.body = new Roo.Template(
168 '<table border="0" cellspacing="0" cellpadding="0">',
169 "<tbody>{rows}</tbody>",
172 tpls.body.disableFormats = true;
177 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
178 tpls.row.disableFormats = true;
183 tpls.cell = new Roo.Template(
184 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
185 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
186 this.unselectableCls + '" ' + this.unselectable +'" {attr}>{value}</div></div>',
189 tpls.cell.disableFormats = true;
193 this.templates = tpls;
196 // remap these for backwards compat
197 onColWidthChange : function(){
198 this.updateColumns.apply(this, arguments);
200 onHeaderChange : function(){
201 this.updateHeaders.apply(this, arguments);
203 onHiddenChange : function(){
204 this.handleHiddenChange.apply(this, arguments);
206 onColumnMove : function(){
207 this.handleColumnMove.apply(this, arguments);
209 onColumnLock : function(){
210 this.handleLockChange.apply(this, arguments);
213 onDataChange : function(){
215 this.updateHeaderSortState();
218 onClear : function(){
222 onUpdate : function(ds, record){
223 this.refreshRow(record);
226 refreshRow : function(record){
227 var ds = this.ds, index;
228 if(typeof record == 'number'){
230 record = ds.getAt(index);
232 index = ds.indexOf(record);
234 this.insertRows(ds, index, index, true);
235 this.onRemove(ds, record, index+1, true);
236 this.syncRowHeights(index, index);
238 this.fireEvent("rowupdated", this, index, record);
241 onAdd : function(ds, records, index){
242 this.insertRows(ds, index, index + (records.length-1));
245 onRemove : function(ds, record, index, isUpdate){
246 if(isUpdate !== true){
247 this.fireEvent("beforerowremoved", this, index, record);
249 var bt = this.getBodyTable(), lt = this.getLockedTable();
251 bt.firstChild.removeChild(bt.rows[index]);
254 lt.firstChild.removeChild(lt.rows[index]);
256 if(isUpdate !== true){
257 this.stripeRows(index);
258 this.syncRowHeights(index, index);
260 this.fireEvent("rowremoved", this, index, record);
269 * Scrolls the grid to the top
271 scrollToTop : function(){
273 this.scroller.dom.scrollTop = 0;
279 * Gets a panel in the header of the grid that can be used for toolbars etc.
280 * After modifying the contents of this panel a call to grid.autoSize() may be
281 * required to register any changes in size.
282 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
283 * @return Roo.Element
285 getHeaderPanel : function(doShow){
287 this.headerPanel.show();
289 return this.headerPanel;
293 * Gets a panel in the footer of the grid that can be used for toolbars etc.
294 * After modifying the contents of this panel a call to grid.autoSize() may be
295 * required to register any changes in size.
296 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
297 * @return Roo.Element
299 getFooterPanel : function(doShow){
301 this.footerPanel.show();
303 return this.footerPanel;
306 initElements : function(){
308 var el = this.grid.getGridEl().dom.firstChild;
309 var cs = el.childNodes;
313 this.focusEl = new E(el.firstChild);
314 this.focusEl.swallowEvent("click", true);
316 this.headerPanel = new E(cs[1]);
317 this.headerPanel.enableDisplayMode("block");
319 this.scroller = new E(cs[2]);
320 this.scrollSizer = new E(this.scroller.dom.firstChild);
322 this.lockedWrap = new E(cs[3]);
323 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
324 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
326 this.mainWrap = new E(cs[4]);
327 this.mainHd = new E(this.mainWrap.dom.firstChild);
328 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
330 this.footerPanel = new E(cs[5]);
331 this.footerPanel.enableDisplayMode("block");
333 this.resizeProxy = new E(cs[6]);
335 this.headerSelector = String.format(
336 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
337 this.lockedHd.id, this.mainHd.id
340 this.splitterSelector = String.format(
341 '#{0} div.x-grid-split, #{1} div.x-grid-split',
342 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
345 idToCssName : function(s)
347 return s.replace(/[^a-z0-9]+/ig, '-');
350 getHeaderCell : function(index){
351 return Roo.DomQuery.select(this.headerSelector)[index];
354 getHeaderCellMeasure : function(index){
355 return this.getHeaderCell(index).firstChild;
358 getHeaderCellText : function(index){
359 return this.getHeaderCell(index).firstChild.firstChild;
362 getLockedTable : function(){
363 return this.lockedBody.dom.firstChild;
366 getBodyTable : function(){
367 return this.mainBody.dom.firstChild;
370 getLockedRow : function(index){
371 return this.getLockedTable().rows[index];
374 getRow : function(index){
375 return this.getBodyTable().rows[index];
378 getRowComposite : function(index){
380 this.rowEl = new Roo.CompositeElementLite();
382 var els = [], lrow, mrow;
383 if(lrow = this.getLockedRow(index)){
386 if(mrow = this.getRow(index)){
389 this.rowEl.elements = els;
393 * Gets the 'td' of the cell
395 * @param {Integer} rowIndex row to select
396 * @param {Integer} colIndex column to select
400 getCell : function(rowIndex, colIndex){
401 var locked = this.cm.getLockedCount();
403 if(colIndex < locked){
404 source = this.lockedBody.dom.firstChild;
406 source = this.mainBody.dom.firstChild;
409 return source.rows[rowIndex].childNodes[colIndex];
412 getCellText : function(rowIndex, colIndex){
413 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
416 getCellBox : function(cell){
417 var b = this.fly(cell).getBox();
418 if(Roo.isOpera){ // opera fails to report the Y
419 b.y = cell.offsetTop + this.mainBody.getY();
424 getCellIndex : function(cell){
425 var id = String(cell.className).match(this.cellRE);
427 return parseInt(id[1], 10);
432 findHeaderIndex : function(n){
433 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
434 return r ? this.getCellIndex(r) : false;
437 findHeaderCell : function(n){
438 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
439 return r ? r : false;
442 findRowIndex : function(n){
446 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
447 return r ? r.rowIndex : false;
450 findCellIndex : function(node){
451 var stop = this.el.dom;
452 while(node && node != stop){
453 if(this.findRE.test(node.className)){
454 return this.getCellIndex(node);
456 node = node.parentNode;
461 getColumnId : function(index){
462 return this.cm.getColumnId(index);
465 getSplitters : function()
467 if(this.splitterSelector){
468 return Roo.DomQuery.select(this.splitterSelector);
474 getSplitter : function(index){
475 return this.getSplitters()[index];
478 onRowOver : function(e, t){
480 if((row = this.findRowIndex(t)) !== false){
481 this.getRowComposite(row).addClass("x-grid-row-over");
485 onRowOut : function(e, t){
487 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
488 this.getRowComposite(row).removeClass("x-grid-row-over");
492 renderHeaders : function(){
494 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
495 var cb = [], lb = [], sb = [], lsb = [], p = {};
496 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
497 p.cellId = "x-grid-hd-0-" + i;
498 p.splitId = "x-grid-csplit-0-" + i;
499 p.id = cm.getColumnId(i);
500 p.title = cm.getColumnTooltip(i) || "";
501 p.value = cm.getColumnHeader(i) || "";
502 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
504 cb[cb.length] = ct.apply(p);
505 sb[sb.length] = st.apply(p);
507 lb[lb.length] = ct.apply(p);
508 lsb[lsb.length] = st.apply(p);
511 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
512 ht.apply({cells: cb.join(""), splits:sb.join("")})];
515 updateHeaders : function(){
516 var html = this.renderHeaders();
517 this.lockedHd.update(html[0]);
518 this.mainHd.update(html[1]);
522 * Focuses the specified row.
523 * @param {Number} row The row index
525 focusRow : function(row)
527 //Roo.log('GridView.focusRow');
528 var x = this.scroller.dom.scrollLeft;
529 this.focusCell(row, 0, false);
530 this.scroller.dom.scrollLeft = x;
534 * Focuses the specified cell.
535 * @param {Number} row The row index
536 * @param {Number} col The column index
537 * @param {Boolean} hscroll false to disable horizontal scrolling
539 focusCell : function(row, col, hscroll)
541 //Roo.log('GridView.focusCell');
542 var el = this.ensureVisible(row, col, hscroll);
543 this.focusEl.alignTo(el, "tl-tl");
545 this.focusEl.focus();
547 this.focusEl.focus.defer(1, this.focusEl);
552 * Scrolls the specified cell into view
553 * @param {Number} row The row index
554 * @param {Number} col The column index
555 * @param {Boolean} hscroll false to disable horizontal scrolling
557 ensureVisible : function(row, col, hscroll)
559 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
560 //return null; //disable for testing.
561 if(typeof row != "number"){
564 if(row < 0 && row >= this.ds.getCount()){
567 col = (col !== undefined ? col : 0);
568 var cm = this.grid.colModel;
569 while(cm.isHidden(col)){
573 var el = this.getCell(row, col);
577 var c = this.scroller.dom;
579 var ctop = parseInt(el.offsetTop, 10);
580 var cleft = parseInt(el.offsetLeft, 10);
581 var cbot = ctop + el.offsetHeight;
582 var cright = cleft + el.offsetWidth;
584 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
585 var stop = parseInt(c.scrollTop, 10);
586 var sleft = parseInt(c.scrollLeft, 10);
587 var sbot = stop + ch;
588 var sright = sleft + c.clientWidth;
590 Roo.log('GridView.ensureVisible:' +
592 ' c.clientHeight:' + c.clientHeight +
593 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
602 //Roo.log("set scrolltop to ctop DISABLE?");
603 }else if(cbot > sbot){
604 //Roo.log("set scrolltop to cbot-ch");
605 c.scrollTop = cbot-ch;
608 if(hscroll !== false){
610 c.scrollLeft = cleft;
611 }else if(cright > sright){
612 c.scrollLeft = cright-c.clientWidth;
619 updateColumns : function(){
620 this.grid.stopEditing();
621 var cm = this.grid.colModel, colIds = this.getColumnIds();
622 //var totalWidth = cm.getTotalWidth();
624 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
625 //if(cm.isHidden(i)) continue;
626 var w = cm.getColumnWidth(i);
627 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
628 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
630 this.updateSplitters();
633 generateRules : function(cm){
634 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
635 Roo.util.CSS.removeStyleSheet(rulesId);
636 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
637 var cid = cm.getColumnId(i);
639 if(cm.config[i].align){
640 align = 'text-align:'+cm.config[i].align+';';
644 hidden = 'display:none;';
646 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
648 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
649 this.hdSelector, cid, " {\n", align, width, "}\n",
650 this.tdSelector, cid, " {\n",hidden,"\n}\n",
651 this.splitSelector, cid, " {\n", hidden , "\n}\n");
653 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
656 updateSplitters : function(){
657 var cm = this.cm, s = this.getSplitters();
658 if(s){ // splitters not created yet
659 var pos = 0, locked = true;
660 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
661 if(cm.isHidden(i)) continue;
662 var w = cm.getColumnWidth(i); // make sure it's a number
663 if(!cm.isLocked(i) && locked){
668 s[i].style.left = (pos-this.splitOffset) + "px";
673 handleHiddenChange : function(colModel, colIndex, hidden){
675 this.hideColumn(colIndex);
677 this.unhideColumn(colIndex);
681 hideColumn : function(colIndex){
682 var cid = this.getColumnId(colIndex);
683 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
684 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
686 this.updateHeaders();
688 this.updateSplitters();
692 unhideColumn : function(colIndex){
693 var cid = this.getColumnId(colIndex);
694 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
695 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
698 this.updateHeaders();
700 this.updateSplitters();
704 insertRows : function(dm, firstRow, lastRow, isUpdate){
705 if(firstRow == 0 && lastRow == dm.getCount()-1){
709 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
711 var s = this.getScrollState();
712 var markup = this.renderRows(firstRow, lastRow);
713 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
714 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
715 this.restoreScroll(s);
717 this.fireEvent("rowsinserted", this, firstRow, lastRow);
718 this.syncRowHeights(firstRow, lastRow);
719 this.stripeRows(firstRow);
725 bufferRows : function(markup, target, index){
726 var before = null, trows = target.rows, tbody = target.tBodies[0];
727 if(index < trows.length){
728 before = trows[index];
730 var b = document.createElement("div");
731 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
732 var rows = b.firstChild.rows;
733 for(var i = 0, len = rows.length; i < len; i++){
735 tbody.insertBefore(rows[0], before);
737 tbody.appendChild(rows[0]);
744 deleteRows : function(dm, firstRow, lastRow){
745 if(dm.getRowCount()<1){
746 this.fireEvent("beforerefresh", this);
747 this.mainBody.update("");
748 this.lockedBody.update("");
749 this.fireEvent("refresh", this);
751 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
752 var bt = this.getBodyTable();
753 var tbody = bt.firstChild;
755 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
756 tbody.removeChild(rows[firstRow]);
758 this.stripeRows(firstRow);
759 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
763 updateRows : function(dataSource, firstRow, lastRow){
764 var s = this.getScrollState();
766 this.restoreScroll(s);
769 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
773 this.updateHeaderSortState();
776 getScrollState : function(){
778 var sb = this.scroller.dom;
779 return {left: sb.scrollLeft, top: sb.scrollTop};
782 stripeRows : function(startRow){
783 if(!this.grid.stripeRows || this.ds.getCount() < 1){
786 startRow = startRow || 0;
787 var rows = this.getBodyTable().rows;
788 var lrows = this.getLockedTable().rows;
789 var cls = ' x-grid-row-alt ';
790 for(var i = startRow, len = rows.length; i < len; i++){
791 var row = rows[i], lrow = lrows[i];
792 var isAlt = ((i+1) % 2 == 0);
793 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
798 row.className += " x-grid-row-alt";
800 row.className = row.className.replace("x-grid-row-alt", "");
803 lrow.className = row.className;
808 restoreScroll : function(state){
809 //Roo.log('GridView.restoreScroll');
810 var sb = this.scroller.dom;
811 sb.scrollLeft = state.left;
812 sb.scrollTop = state.top;
816 syncScroll : function(){
817 //Roo.log('GridView.syncScroll');
818 var sb = this.scroller.dom;
819 var sh = this.mainHd.dom;
820 var bs = this.mainBody.dom;
821 var lv = this.lockedBody.dom;
822 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
823 lv.scrollTop = bs.scrollTop = sb.scrollTop;
826 handleScroll : function(e){
828 var sb = this.scroller.dom;
829 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
833 handleWheel : function(e){
834 var d = e.getWheelDelta();
835 this.scroller.dom.scrollTop -= d*22;
836 // set this here to prevent jumpy scrolling on large tables
837 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
841 renderRows : function(startRow, endRow){
842 // pull in all the crap needed to render rows
843 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
844 var colCount = cm.getColumnCount();
846 if(ds.getCount() < 1){
850 // build a map for all the columns
852 for(var i = 0; i < colCount; i++){
853 var name = cm.getDataIndex(i);
855 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
856 renderer : cm.getRenderer(i),
857 id : cm.getColumnId(i),
858 locked : cm.isLocked(i)
862 startRow = startRow || 0;
863 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
866 var rs = ds.getRange(startRow, endRow);
868 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
871 // As much as I hate to duplicate code, this was branched because FireFox really hates
872 // [].join("") on strings. The performance difference was substantial enough to
873 // branch this function
874 doRender : Roo.isGecko ?
875 function(cs, rs, ds, startRow, colCount, stripe){
876 var ts = this.templates, ct = ts.cell, rt = ts.row;
878 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
880 var hasListener = this.grid.hasListener('rowclass');
882 for(var j = 0, len = rs.length; j < len; j++){
883 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
884 for(var i = 0; i < colCount; i++){
886 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
889 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
890 if(p.value == undefined || p.value === "") p.value = " ";
891 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
892 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
894 var markup = ct.apply(p);
902 if(stripe && ((rowIndex+1) % 2 == 0)){
903 alt.push("x-grid-row-alt")
906 alt.push( " x-grid-dirty-row");
909 if(this.getRowClass){
910 alt.push(this.getRowClass(r, rowIndex));
919 this.grid.fireEvent('rowclass', this, rowcfg);
920 alt.push(rowcfg.rowClass);
922 rp.alt = alt.join(" ");
929 function(cs, rs, ds, startRow, colCount, stripe){
930 var ts = this.templates, ct = ts.cell, rt = ts.row;
932 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
933 var hasListener = this.grid.hasListener('rowclass');
936 for(var j = 0, len = rs.length; j < len; j++){
937 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
938 for(var i = 0; i < colCount; i++){
940 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
943 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
944 if(p.value == undefined || p.value === "") p.value = " ";
945 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
946 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
949 var markup = ct.apply(p);
951 cb[cb.length] = markup;
953 lcb[lcb.length] = markup;
957 if(stripe && ((rowIndex+1) % 2 == 0)){
958 alt.push( "x-grid-row-alt");
961 alt.push(" x-grid-dirty-row");
964 if(this.getRowClass){
965 alt.push( this.getRowClass(r, rowIndex));
974 this.grid.fireEvent('rowclass', this, rowcfg);
975 alt.push(rowcfg.rowClass);
977 rp.alt = alt.join(" ");
978 rp.cells = lcb.join("");
979 lbuf[lbuf.length] = rt.apply(rp);
980 rp.cells = cb.join("");
981 buf[buf.length] = rt.apply(rp);
983 return [lbuf.join(""), buf.join("")];
986 renderBody : function(){
987 var markup = this.renderRows();
988 var bt = this.templates.body;
989 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
994 * @param {Boolean} headersToo
996 refresh : function(headersToo){
997 this.fireEvent("beforerefresh", this);
998 this.grid.stopEditing();
999 var result = this.renderBody();
1000 this.lockedBody.update(result[0]);
1001 this.mainBody.update(result[1]);
1002 if(headersToo === true){
1003 this.updateHeaders();
1004 this.updateColumns();
1005 this.updateSplitters();
1006 this.updateHeaderSortState();
1008 this.syncRowHeights();
1010 this.fireEvent("refresh", this);
1013 handleColumnMove : function(cm, oldIndex, newIndex){
1014 this.indexMap = null;
1015 var s = this.getScrollState();
1017 this.restoreScroll(s);
1018 this.afterMove(newIndex);
1021 afterMove : function(colIndex){
1022 if(this.enableMoveAnim && Roo.enableFx){
1023 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
1025 // if multisort - fix sortOrder, and reload..
1026 if (this.grid.dataSource.multiSort) {
1027 // the we can call sort again..
1028 var dm = this.grid.dataSource;
1029 var cm = this.grid.colModel;
1031 for(var i = 0; i < cm.config.length; i++ ) {
1033 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
1034 continue; // dont' bother, it's not in sort list or being set.
1037 so.push(cm.config[i].dataIndex);
1040 dm.load(dm.lastOptions);
1047 updateCell : function(dm, rowIndex, dataIndex){
1048 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
1049 if(typeof colIndex == "undefined"){ // not present in grid
1052 var cm = this.grid.colModel;
1053 var cell = this.getCell(rowIndex, colIndex);
1054 var cellText = this.getCellText(rowIndex, colIndex);
1057 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
1058 id : cm.getColumnId(colIndex),
1059 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
1061 var renderer = cm.getRenderer(colIndex);
1062 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
1063 if(typeof val == "undefined" || val === "") val = " ";
1064 cellText.innerHTML = val;
1065 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
1066 this.syncRowHeights(rowIndex, rowIndex);
1069 calcColumnWidth : function(colIndex, maxRowsToMeasure){
1071 if(this.grid.autoSizeHeaders){
1072 var h = this.getHeaderCellMeasure(colIndex);
1073 maxWidth = Math.max(maxWidth, h.scrollWidth);
1076 if(this.cm.isLocked(colIndex)){
1077 tb = this.getLockedTable();
1080 tb = this.getBodyTable();
1081 index = colIndex - this.cm.getLockedCount();
1085 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
1086 for(var i = 0; i < stopIndex; i++){
1087 var cell = rows[i].childNodes[index].firstChild;
1088 maxWidth = Math.max(maxWidth, cell.scrollWidth);
1091 return maxWidth + /*margin for error in IE*/ 5;
1094 * Autofit a column to its content.
1095 * @param {Number} colIndex
1096 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
1098 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
1099 if(this.cm.isHidden(colIndex)){
1100 return; // can't calc a hidden column
1103 var cid = this.cm.getColumnId(colIndex);
1104 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
1105 if(this.grid.autoSizeHeaders){
1106 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
1109 var newWidth = this.calcColumnWidth(colIndex);
1110 this.cm.setColumnWidth(colIndex,
1111 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
1113 this.grid.fireEvent("columnresize", colIndex, newWidth);
1118 * Autofits all columns to their content and then expands to fit any extra space in the grid
1120 autoSizeColumns : function(){
1121 var cm = this.grid.colModel;
1122 var colCount = cm.getColumnCount();
1123 for(var i = 0; i < colCount; i++){
1124 this.autoSizeColumn(i, true, true);
1126 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
1129 this.updateColumns();
1135 * Autofits all columns to the grid's width proportionate with their current size
1136 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
1138 fitColumns : function(reserveScrollSpace){
1139 var cm = this.grid.colModel;
1140 var colCount = cm.getColumnCount();
1144 for (i = 0; i < colCount; i++){
1145 if(!cm.isHidden(i) && !cm.isFixed(i)){
1146 w = cm.getColumnWidth(i);
1152 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
1153 if(reserveScrollSpace){
1156 var frac = (avail - cm.getTotalWidth())/width;
1157 while (cols.length){
1160 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
1162 this.updateColumns();
1166 onRowSelect : function(rowIndex){
1167 var row = this.getRowComposite(rowIndex);
1168 row.addClass("x-grid-row-selected");
1171 onRowDeselect : function(rowIndex){
1172 var row = this.getRowComposite(rowIndex);
1173 row.removeClass("x-grid-row-selected");
1176 onCellSelect : function(row, col){
1177 var cell = this.getCell(row, col);
1179 Roo.fly(cell).addClass("x-grid-cell-selected");
1183 onCellDeselect : function(row, col){
1184 var cell = this.getCell(row, col);
1186 Roo.fly(cell).removeClass("x-grid-cell-selected");
1190 updateHeaderSortState : function(){
1192 // sort state can be single { field: xxx, direction : yyy}
1193 // or { xxx=>ASC , yyy : DESC ..... }
1196 if (!this.ds.multiSort) {
1197 var state = this.ds.getSortState();
1201 mstate[state.field] = state.direction;
1202 // FIXME... - this is not used here.. but might be elsewhere..
1203 this.sortState = state;
1206 mstate = this.ds.sortToggle;
1208 //remove existing sort classes..
1210 var sc = this.sortClasses;
1211 var hds = this.el.select(this.headerSelector).removeClass(sc);
1213 for(var f in mstate) {
1215 var sortColumn = this.cm.findColumnIndex(f);
1217 if(sortColumn != -1){
1218 var sortDir = mstate[f];
1219 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
1228 handleHeaderClick : function(g, index,e){
1230 Roo.log("header click");
1233 // touch events on header are handled by context
1234 this.handleHdCtx(g,index,e);
1239 if(this.headersDisabled){
1242 var dm = g.dataSource, cm = g.colModel;
1243 if(!cm.isSortable(index)){
1249 // update the sortOrder
1251 for(var i = 0; i < cm.config.length; i++ ) {
1253 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
1254 continue; // dont' bother, it's not in sort list or being set.
1257 so.push(cm.config[i].dataIndex);
1263 dm.sort(cm.getDataIndex(index));
1267 destroy : function(){
1269 this.colMenu.removeAll();
1270 Roo.menu.MenuMgr.unregister(this.colMenu);
1271 this.colMenu.getEl().remove();
1272 delete this.colMenu;
1275 this.hmenu.removeAll();
1276 Roo.menu.MenuMgr.unregister(this.hmenu);
1277 this.hmenu.getEl().remove();
1280 if(this.grid.enableColumnMove){
1281 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1284 if(!dds[dd].config.isTarget && dds[dd].dragElId){
1285 var elid = dds[dd].dragElId;
1287 Roo.get(elid).remove();
1288 } else if(dds[dd].config.isTarget){
1289 dds[dd].proxyTop.remove();
1290 dds[dd].proxyBottom.remove();
1293 if(Roo.dd.DDM.locationCache[dd]){
1294 delete Roo.dd.DDM.locationCache[dd];
1297 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1300 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
1301 this.bind(null, null);
1302 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
1305 handleLockChange : function(){
1309 onDenyColumnLock : function(){
1313 onDenyColumnHide : function(){
1317 handleHdMenuClick : function(item){
1318 var index = this.hdCtxIndex;
1319 var cm = this.cm, ds = this.ds;
1322 ds.sort(cm.getDataIndex(index), "ASC");
1325 ds.sort(cm.getDataIndex(index), "DESC");
1328 var lc = cm.getLockedCount();
1329 if(cm.getColumnCount(true) <= lc+1){
1330 this.onDenyColumnLock();
1334 cm.setLocked(index, true, true);
1335 cm.moveColumn(index, lc);
1336 this.grid.fireEvent("columnmove", index, lc);
1338 cm.setLocked(index, true);
1342 var lc = cm.getLockedCount();
1343 if((lc-1) != index){
1344 cm.setLocked(index, false, true);
1345 cm.moveColumn(index, lc-1);
1346 this.grid.fireEvent("columnmove", index, lc-1);
1348 cm.setLocked(index, false);
1351 case 'wider': // used to expand cols on touch..
1353 var cw = cm.getColumnWidth(index);
1354 cw += (item.id == 'wider' ? 1 : -1) * 50;
1355 cw = Math.max(0, cw);
1356 cw = Math.min(cw,4000);
1357 cm.setColumnWidth(index, cw);
1361 index = cm.getIndexById(item.id.substr(4));
1363 if(item.checked && cm.getColumnCount(true) <= 1){
1364 this.onDenyColumnHide();
1367 cm.setHidden(index, item.checked);
1373 beforeColMenuShow : function(){
1374 var cm = this.cm, colCount = cm.getColumnCount();
1375 this.colMenu.removeAll();
1376 for(var i = 0; i < colCount; i++){
1377 this.colMenu.add(new Roo.menu.CheckItem({
1378 id: "col-"+cm.getColumnId(i),
1379 text: cm.getColumnHeader(i),
1380 checked: !cm.isHidden(i),
1386 handleHdCtx : function(g, index, e){
1388 var hd = this.getHeaderCell(index);
1389 this.hdCtxIndex = index;
1390 var ms = this.hmenu.items, cm = this.cm;
1391 ms.get("asc").setDisabled(!cm.isSortable(index));
1392 ms.get("desc").setDisabled(!cm.isSortable(index));
1393 if(this.grid.enableColLock !== false){
1394 ms.get("lock").setDisabled(cm.isLocked(index));
1395 ms.get("unlock").setDisabled(!cm.isLocked(index));
1397 this.hmenu.show(hd, "tl-bl");
1400 handleHdOver : function(e){
1401 var hd = this.findHeaderCell(e.getTarget());
1402 if(hd && !this.headersDisabled){
1403 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
1404 this.fly(hd).addClass("x-grid-hd-over");
1409 handleHdOut : function(e){
1410 var hd = this.findHeaderCell(e.getTarget());
1412 this.fly(hd).removeClass("x-grid-hd-over");
1416 handleSplitDblClick : function(e, t){
1417 var i = this.getCellIndex(t);
1418 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
1419 this.autoSizeColumn(i, true);
1424 render : function(){
1427 var colCount = cm.getColumnCount();
1429 if(this.grid.monitorWindowResize === true){
1430 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
1432 var header = this.renderHeaders();
1433 var body = this.templates.body.apply({rows:""});
1434 var html = this.templates.master.apply({
1437 lockedHeader: header[0],
1441 //this.updateColumns();
1443 this.grid.getGridEl().dom.innerHTML = html;
1445 this.initElements();
1447 // a kludge to fix the random scolling effect in webkit
1448 this.el.on("scroll", function() {
1449 this.el.dom.scrollTop=0; // hopefully not recursive..
1452 this.scroller.on("scroll", this.handleScroll, this);
1453 this.lockedBody.on("mousewheel", this.handleWheel, this);
1454 this.mainBody.on("mousewheel", this.handleWheel, this);
1456 this.mainHd.on("mouseover", this.handleHdOver, this);
1457 this.mainHd.on("mouseout", this.handleHdOut, this);
1458 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
1459 {delegate: "."+this.splitClass});
1461 this.lockedHd.on("mouseover", this.handleHdOver, this);
1462 this.lockedHd.on("mouseout", this.handleHdOut, this);
1463 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
1464 {delegate: "."+this.splitClass});
1466 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
1467 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1470 this.updateSplitters();
1472 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
1473 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1474 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1477 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
1478 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
1480 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
1481 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
1483 if(this.grid.enableColLock !== false){
1485 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
1486 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
1491 {id:"wider", text: this.columnsWiderText},
1492 {id:"narrow", text: this.columnsNarrowText }
1498 if(this.grid.enableColumnHide !== false){
1500 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
1501 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
1502 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
1505 {id:"columns", text: this.columnsText, menu: this.colMenu}
1508 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
1510 this.grid.on("headercontextmenu", this.handleHdCtx, this);
1513 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
1514 this.dd = new Roo.grid.GridDragZone(this.grid, {
1515 ddGroup : this.grid.ddGroup || 'GridDD'
1521 for(var i = 0; i < colCount; i++){
1525 if(cm.config[i].align){
1526 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
1527 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
1531 this.updateHeaderSortState();
1533 this.beforeInitialResize();
1536 // two part rendering gives faster view to the user
1537 this.renderPhase2.defer(1, this);
1540 renderPhase2 : function(){
1541 // render the rows now
1543 if(this.grid.autoSizeColumns){
1544 this.autoSizeColumns();
1548 beforeInitialResize : function(){
1552 onColumnSplitterMoved : function(i, w){
1553 this.userResized = true;
1554 var cm = this.grid.colModel;
1555 cm.setColumnWidth(i, w, true);
1556 var cid = cm.getColumnId(i);
1557 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1558 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1559 this.updateSplitters();
1561 this.grid.fireEvent("columnresize", i, w);
1564 syncRowHeights : function(startIndex, endIndex){
1565 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
1566 startIndex = startIndex || 0;
1567 var mrows = this.getBodyTable().rows;
1568 var lrows = this.getLockedTable().rows;
1569 var len = mrows.length-1;
1570 endIndex = Math.min(endIndex || len, len);
1571 for(var i = startIndex; i <= endIndex; i++){
1572 var m = mrows[i], l = lrows[i];
1573 var h = Math.max(m.offsetHeight, l.offsetHeight);
1574 m.style.height = l.style.height = h + "px";
1579 layout : function(initialRender, is2ndPass){
1581 var auto = g.autoHeight;
1582 var scrollOffset = 16;
1583 var c = g.getGridEl(), cm = this.cm,
1584 expandCol = g.autoExpandColumn,
1588 if(!c.dom.offsetWidth){ // display:none?
1590 this.lockedWrap.show();
1591 this.mainWrap.show();
1596 var hasLock = this.cm.isLocked(0);
1598 var tbh = this.headerPanel.getHeight();
1599 var bbh = this.footerPanel.getHeight();
1602 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
1603 var newHeight = ch + c.getBorderWidth("tb");
1605 newHeight = Math.min(g.maxHeight, newHeight);
1607 c.setHeight(newHeight);
1611 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
1614 var s = this.scroller;
1616 var csize = c.getSize(true);
1618 this.el.setSize(csize.width, csize.height);
1620 this.headerPanel.setWidth(csize.width);
1621 this.footerPanel.setWidth(csize.width);
1623 var hdHeight = this.mainHd.getHeight();
1624 var vw = csize.width;
1625 var vh = csize.height - (tbh + bbh);
1629 var bt = this.getBodyTable();
1630 var ltWidth = hasLock ?
1631 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
1633 var scrollHeight = bt.offsetHeight;
1634 var scrollWidth = ltWidth + bt.offsetWidth;
1635 var vscroll = false, hscroll = false;
1637 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
1639 var lw = this.lockedWrap, mw = this.mainWrap;
1640 var lb = this.lockedBody, mb = this.mainBody;
1642 setTimeout(function(){
1643 var t = s.dom.offsetTop;
1644 var w = s.dom.clientWidth,
1645 h = s.dom.clientHeight;
1648 lw.setSize(ltWidth, h);
1650 mw.setLeftTop(ltWidth, t);
1651 mw.setSize(w-ltWidth, h);
1653 lb.setHeight(h-hdHeight);
1654 mb.setHeight(h-hdHeight);
1656 if(is2ndPass !== true && !gv.userResized && expandCol){
1657 // high speed resize without full column calculation
1659 var ci = cm.getIndexById(expandCol);
1661 ci = cm.findColumnIndex(expandCol);
1663 ci = Math.max(0, ci); // make sure it's got at least the first col.
1664 var expandId = cm.getColumnId(ci);
1665 var tw = cm.getTotalWidth(false);
1666 var currentWidth = cm.getColumnWidth(ci);
1667 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
1668 if(currentWidth != cw){
1669 cm.setColumnWidth(ci, cw, true);
1670 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1671 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1672 gv.updateSplitters();
1673 gv.layout(false, true);
1685 onWindowResize : function(){
1686 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
1692 appendFooter : function(parentEl){
1696 sortAscText : "Sort Ascending",
1697 sortDescText : "Sort Descending",
1698 lockText : "Lock Column",
1699 unlockText : "Unlock Column",
1700 columnsText : "Columns",
1702 columnsWiderText : "Wider",
1703 columnsNarrowText : "Thinner"
1707 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
1708 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
1709 this.proxy.el.addClass('x-grid3-col-dd');
1712 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
1713 handleMouseDown : function(e){
1717 callHandleMouseDown : function(e){
1718 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);