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"',
30 rowClass : "x-grid-row",
32 cellClass : "x-grid-col",
34 tdClass : "x-grid-td",
36 hdClass : "x-grid-hd",
38 splitClass : "x-grid-split",
40 sortClasses : ["sort-asc", "sort-desc"],
42 enableMoveAnim : false,
48 fly : Roo.Element.fly,
58 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
60 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
62 bind : function(ds, cm){
64 this.ds.un("load", this.onLoad, this);
65 this.ds.un("datachanged", this.onDataChange, this);
66 this.ds.un("add", this.onAdd, this);
67 this.ds.un("remove", this.onRemove, this);
68 this.ds.un("update", this.onUpdate, this);
69 this.ds.un("clear", this.onClear, this);
72 ds.on("load", this.onLoad, this);
73 ds.on("datachanged", this.onDataChange, this);
74 ds.on("add", this.onAdd, this);
75 ds.on("remove", this.onRemove, this);
76 ds.on("update", this.onUpdate, this);
77 ds.on("clear", this.onClear, this);
82 this.cm.un("widthchange", this.onColWidthChange, this);
83 this.cm.un("headerchange", this.onHeaderChange, this);
84 this.cm.un("hiddenchange", this.onHiddenChange, this);
85 this.cm.un("columnmoved", this.onColumnMove, this);
86 this.cm.un("columnlockchange", this.onColumnLock, this);
89 this.generateRules(cm);
90 cm.on("widthchange", this.onColWidthChange, this);
91 cm.on("headerchange", this.onHeaderChange, this);
92 cm.on("hiddenchange", this.onHiddenChange, this);
93 cm.on("columnmoved", this.onColumnMove, this);
94 cm.on("columnlockchange", this.onColumnLock, this);
100 Roo.grid.GridView.superclass.init.call(this, grid);
102 this.bind(grid.dataSource, grid.colModel);
104 grid.on("headerclick", this.handleHeaderClick, this);
106 if(grid.trackMouseOver){
107 grid.on("mouseover", this.onRowOver, this);
108 grid.on("mouseout", this.onRowOut, this);
110 grid.cancelTextSelection = function(){};
111 this.gridId = grid.id;
113 var tpls = this.templates || {};
116 tpls.master = new Roo.Template(
117 '<div class="x-grid" hidefocus="true">',
118 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
119 '<div class="x-grid-topbar"></div>',
120 '<div class="x-grid-scroller"><div></div></div>',
121 '<div class="x-grid-locked">',
122 '<div class="x-grid-header">{lockedHeader}</div>',
123 '<div class="x-grid-body">{lockedBody}</div>',
125 '<div class="x-grid-viewport">',
126 '<div class="x-grid-header">{header}</div>',
127 '<div class="x-grid-body">{body}</div>',
129 '<div class="x-grid-bottombar"></div>',
131 '<div class="x-grid-resize-proxy"> </div>',
134 tpls.master.disableformats = true;
138 tpls.header = new Roo.Template(
139 '<table border="0" cellspacing="0" cellpadding="0">',
140 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
143 tpls.header.disableformats = true;
145 tpls.header.compile();
148 tpls.hcell = new Roo.Template(
149 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
150 '<div class="x-grid-hd-text" unselectable="on">{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
153 tpls.hcell.disableFormats = true;
155 tpls.hcell.compile();
158 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style}" unselectable="on"> </div>');
159 tpls.hsplit.disableFormats = true;
161 tpls.hsplit.compile();
164 tpls.body = new Roo.Template(
165 '<table border="0" cellspacing="0" cellpadding="0">',
166 "<tbody>{rows}</tbody>",
169 tpls.body.disableFormats = true;
174 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
175 tpls.row.disableFormats = true;
180 tpls.cell = new Roo.Template(
181 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
182 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text" unselectable="on" {attr}>{value}</div></div>',
185 tpls.cell.disableFormats = true;
189 this.templates = tpls;
192 // remap these for backwards compat
193 onColWidthChange : function(){
194 this.updateColumns.apply(this, arguments);
196 onHeaderChange : function(){
197 this.updateHeaders.apply(this, arguments);
199 onHiddenChange : function(){
200 this.handleHiddenChange.apply(this, arguments);
202 onColumnMove : function(){
203 this.handleColumnMove.apply(this, arguments);
205 onColumnLock : function(){
206 this.handleLockChange.apply(this, arguments);
209 onDataChange : function(){
211 this.updateHeaderSortState();
214 onClear : function(){
218 onUpdate : function(ds, record){
219 this.refreshRow(record);
222 refreshRow : function(record){
223 var ds = this.ds, index;
224 if(typeof record == 'number'){
226 record = ds.getAt(index);
228 index = ds.indexOf(record);
230 this.insertRows(ds, index, index, true);
231 this.onRemove(ds, record, index+1, true);
232 this.syncRowHeights(index, index);
234 this.fireEvent("rowupdated", this, index, record);
237 onAdd : function(ds, records, index){
238 this.insertRows(ds, index, index + (records.length-1));
241 onRemove : function(ds, record, index, isUpdate){
242 if(isUpdate !== true){
243 this.fireEvent("beforerowremoved", this, index, record);
245 var bt = this.getBodyTable(), lt = this.getLockedTable();
247 bt.firstChild.removeChild(bt.rows[index]);
250 lt.firstChild.removeChild(lt.rows[index]);
252 if(isUpdate !== true){
253 this.stripeRows(index);
254 this.syncRowHeights(index, index);
256 this.fireEvent("rowremoved", this, index, record);
265 * Scrolls the grid to the top
267 scrollToTop : function(){
269 this.scroller.dom.scrollTop = 0;
275 * Gets a panel in the header of the grid that can be used for toolbars etc.
276 * After modifying the contents of this panel a call to grid.autoSize() may be
277 * required to register any changes in size.
278 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
279 * @return Roo.Element
281 getHeaderPanel : function(doShow){
283 this.headerPanel.show();
285 return this.headerPanel;
289 * Gets a panel in the footer of the grid that can be used for toolbars etc.
290 * After modifying the contents of this panel a call to grid.autoSize() may be
291 * required to register any changes in size.
292 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
293 * @return Roo.Element
295 getFooterPanel : function(doShow){
297 this.footerPanel.show();
299 return this.footerPanel;
302 initElements : function(){
304 var el = this.grid.getGridEl().dom.firstChild;
305 var cs = el.childNodes;
309 this.focusEl = new E(el.firstChild);
310 this.focusEl.swallowEvent("click", true);
312 this.headerPanel = new E(cs[1]);
313 this.headerPanel.enableDisplayMode("block");
315 this.scroller = new E(cs[2]);
316 this.scrollSizer = new E(this.scroller.dom.firstChild);
318 this.lockedWrap = new E(cs[3]);
319 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
320 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
322 this.mainWrap = new E(cs[4]);
323 this.mainHd = new E(this.mainWrap.dom.firstChild);
324 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
326 this.footerPanel = new E(cs[5]);
327 this.footerPanel.enableDisplayMode("block");
329 this.resizeProxy = new E(cs[6]);
331 this.headerSelector = String.format(
332 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
333 this.lockedHd.id, this.mainHd.id
336 this.splitterSelector = String.format(
337 '#{0} div.x-grid-split, #{1} div.x-grid-split',
338 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
341 idToCssName : function(s)
343 return s.replace(/[^a-z0-9]+/ig, '-');
346 getHeaderCell : function(index){
347 return Roo.DomQuery.select(this.headerSelector)[index];
350 getHeaderCellMeasure : function(index){
351 return this.getHeaderCell(index).firstChild;
354 getHeaderCellText : function(index){
355 return this.getHeaderCell(index).firstChild.firstChild;
358 getLockedTable : function(){
359 return this.lockedBody.dom.firstChild;
362 getBodyTable : function(){
363 return this.mainBody.dom.firstChild;
366 getLockedRow : function(index){
367 return this.getLockedTable().rows[index];
370 getRow : function(index){
371 return this.getBodyTable().rows[index];
374 getRowComposite : function(index){
376 this.rowEl = new Roo.CompositeElementLite();
378 var els = [], lrow, mrow;
379 if(lrow = this.getLockedRow(index)){
382 if(mrow = this.getRow(index)){
385 this.rowEl.elements = els;
389 * Gets the 'td' of the cell
391 * @param {Integer} rowIndex row to select
392 * @param {Integer} colIndex column to select
396 getCell : function(rowIndex, colIndex){
397 var locked = this.cm.getLockedCount();
399 if(colIndex < locked){
400 source = this.lockedBody.dom.firstChild;
402 source = this.mainBody.dom.firstChild;
405 return source.rows[rowIndex].childNodes[colIndex];
408 getCellText : function(rowIndex, colIndex){
409 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
412 getCellBox : function(cell){
413 var b = this.fly(cell).getBox();
414 if(Roo.isOpera){ // opera fails to report the Y
415 b.y = cell.offsetTop + this.mainBody.getY();
420 getCellIndex : function(cell){
421 var id = String(cell.className).match(this.cellRE);
423 return parseInt(id[1], 10);
428 findHeaderIndex : function(n){
429 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
430 return r ? this.getCellIndex(r) : false;
433 findHeaderCell : function(n){
434 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
435 return r ? r : false;
438 findRowIndex : function(n){
442 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
443 return r ? r.rowIndex : false;
446 findCellIndex : function(node){
447 var stop = this.el.dom;
448 while(node && node != stop){
449 if(this.findRE.test(node.className)){
450 return this.getCellIndex(node);
452 node = node.parentNode;
457 getColumnId : function(index){
458 return this.cm.getColumnId(index);
461 getSplitters : function()
463 if(this.splitterSelector){
464 return Roo.DomQuery.select(this.splitterSelector);
470 getSplitter : function(index){
471 return this.getSplitters()[index];
474 onRowOver : function(e, t){
476 if((row = this.findRowIndex(t)) !== false){
477 this.getRowComposite(row).addClass("x-grid-row-over");
481 onRowOut : function(e, t){
483 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
484 this.getRowComposite(row).removeClass("x-grid-row-over");
488 renderHeaders : function(){
490 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
491 var cb = [], lb = [], sb = [], lsb = [], p = {};
492 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
493 p.cellId = "x-grid-hd-0-" + i;
494 p.splitId = "x-grid-csplit-0-" + i;
495 p.id = cm.getColumnId(i);
496 p.title = cm.getColumnTooltip(i) || "";
497 p.value = cm.getColumnHeader(i) || "";
498 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
500 cb[cb.length] = ct.apply(p);
501 sb[sb.length] = st.apply(p);
503 lb[lb.length] = ct.apply(p);
504 lsb[lsb.length] = st.apply(p);
507 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
508 ht.apply({cells: cb.join(""), splits:sb.join("")})];
511 updateHeaders : function(){
512 var html = this.renderHeaders();
513 this.lockedHd.update(html[0]);
514 this.mainHd.update(html[1]);
518 * Focuses the specified row.
519 * @param {Number} row The row index
521 focusRow : function(row)
523 //Roo.log('GridView.focusRow');
524 var x = this.scroller.dom.scrollLeft;
525 this.focusCell(row, 0, false);
526 this.scroller.dom.scrollLeft = x;
530 * Focuses the specified cell.
531 * @param {Number} row The row index
532 * @param {Number} col The column index
533 * @param {Boolean} hscroll false to disable horizontal scrolling
535 focusCell : function(row, col, hscroll)
537 //Roo.log('GridView.focusCell');
538 var el = this.ensureVisible(row, col, hscroll);
539 this.focusEl.alignTo(el, "tl-tl");
541 this.focusEl.focus();
543 this.focusEl.focus.defer(1, this.focusEl);
548 * Scrolls the specified cell into view
549 * @param {Number} row The row index
550 * @param {Number} col The column index
551 * @param {Boolean} hscroll false to disable horizontal scrolling
553 ensureVisible : function(row, col, hscroll)
555 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
556 //return null; //disable for testing.
557 if(typeof row != "number"){
560 if(row < 0 && row >= this.ds.getCount()){
563 col = (col !== undefined ? col : 0);
564 var cm = this.grid.colModel;
565 while(cm.isHidden(col)){
569 var el = this.getCell(row, col);
573 var c = this.scroller.dom;
575 var ctop = parseInt(el.offsetTop, 10);
576 var cleft = parseInt(el.offsetLeft, 10);
577 var cbot = ctop + el.offsetHeight;
578 var cright = cleft + el.offsetWidth;
580 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
581 var stop = parseInt(c.scrollTop, 10);
582 var sleft = parseInt(c.scrollLeft, 10);
583 var sbot = stop + ch;
584 var sright = sleft + c.clientWidth;
586 Roo.log('GridView.ensureVisible:' +
588 ' c.clientHeight:' + c.clientHeight +
589 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
598 //Roo.log("set scrolltop to ctop DISABLE?");
599 }else if(cbot > sbot){
600 //Roo.log("set scrolltop to cbot-ch");
601 c.scrollTop = cbot-ch;
604 if(hscroll !== false){
606 c.scrollLeft = cleft;
607 }else if(cright > sright){
608 c.scrollLeft = cright-c.clientWidth;
615 updateColumns : function(){
616 this.grid.stopEditing();
617 var cm = this.grid.colModel, colIds = this.getColumnIds();
618 //var totalWidth = cm.getTotalWidth();
620 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
621 //if(cm.isHidden(i)) continue;
622 var w = cm.getColumnWidth(i);
623 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
624 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
626 this.updateSplitters();
629 generateRules : function(cm){
630 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
631 Roo.util.CSS.removeStyleSheet(rulesId);
632 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
633 var cid = cm.getColumnId(i);
635 if(cm.config[i].align){
636 align = 'text-align:'+cm.config[i].align+';';
640 hidden = 'display:none;';
642 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
644 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
645 this.hdSelector, cid, " {\n", align, width, "}\n",
646 this.tdSelector, cid, " {\n",hidden,"\n}\n",
647 this.splitSelector, cid, " {\n", hidden , "\n}\n");
649 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
652 updateSplitters : function(){
653 var cm = this.cm, s = this.getSplitters();
654 if(s){ // splitters not created yet
655 var pos = 0, locked = true;
656 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
657 if(cm.isHidden(i)) continue;
658 var w = cm.getColumnWidth(i); // make sure it's a number
659 if(!cm.isLocked(i) && locked){
664 s[i].style.left = (pos-this.splitOffset) + "px";
669 handleHiddenChange : function(colModel, colIndex, hidden){
671 this.hideColumn(colIndex);
673 this.unhideColumn(colIndex);
677 hideColumn : function(colIndex){
678 var cid = this.getColumnId(colIndex);
679 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
680 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
682 this.updateHeaders();
684 this.updateSplitters();
688 unhideColumn : function(colIndex){
689 var cid = this.getColumnId(colIndex);
690 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
691 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
694 this.updateHeaders();
696 this.updateSplitters();
700 insertRows : function(dm, firstRow, lastRow, isUpdate){
701 if(firstRow == 0 && lastRow == dm.getCount()-1){
705 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
707 var s = this.getScrollState();
708 var markup = this.renderRows(firstRow, lastRow);
709 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
710 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
711 this.restoreScroll(s);
713 this.fireEvent("rowsinserted", this, firstRow, lastRow);
714 this.syncRowHeights(firstRow, lastRow);
715 this.stripeRows(firstRow);
721 bufferRows : function(markup, target, index){
722 var before = null, trows = target.rows, tbody = target.tBodies[0];
723 if(index < trows.length){
724 before = trows[index];
726 var b = document.createElement("div");
727 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
728 var rows = b.firstChild.rows;
729 for(var i = 0, len = rows.length; i < len; i++){
731 tbody.insertBefore(rows[0], before);
733 tbody.appendChild(rows[0]);
740 deleteRows : function(dm, firstRow, lastRow){
741 if(dm.getRowCount()<1){
742 this.fireEvent("beforerefresh", this);
743 this.mainBody.update("");
744 this.lockedBody.update("");
745 this.fireEvent("refresh", this);
747 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
748 var bt = this.getBodyTable();
749 var tbody = bt.firstChild;
751 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
752 tbody.removeChild(rows[firstRow]);
754 this.stripeRows(firstRow);
755 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
759 updateRows : function(dataSource, firstRow, lastRow){
760 var s = this.getScrollState();
762 this.restoreScroll(s);
765 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
769 this.updateHeaderSortState();
772 getScrollState : function(){
774 var sb = this.scroller.dom;
775 return {left: sb.scrollLeft, top: sb.scrollTop};
778 stripeRows : function(startRow){
779 if(!this.grid.stripeRows || this.ds.getCount() < 1){
782 startRow = startRow || 0;
783 var rows = this.getBodyTable().rows;
784 var lrows = this.getLockedTable().rows;
785 var cls = ' x-grid-row-alt ';
786 for(var i = startRow, len = rows.length; i < len; i++){
787 var row = rows[i], lrow = lrows[i];
788 var isAlt = ((i+1) % 2 == 0);
789 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
794 row.className += " x-grid-row-alt";
796 row.className = row.className.replace("x-grid-row-alt", "");
799 lrow.className = row.className;
804 restoreScroll : function(state){
805 //Roo.log('GridView.restoreScroll');
806 var sb = this.scroller.dom;
807 sb.scrollLeft = state.left;
808 sb.scrollTop = state.top;
812 syncScroll : function(){
813 //Roo.log('GridView.syncScroll');
814 var sb = this.scroller.dom;
815 var sh = this.mainHd.dom;
816 var bs = this.mainBody.dom;
817 var lv = this.lockedBody.dom;
818 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
819 lv.scrollTop = bs.scrollTop = sb.scrollTop;
822 handleScroll : function(e){
824 var sb = this.scroller.dom;
825 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
829 handleWheel : function(e){
830 var d = e.getWheelDelta();
831 this.scroller.dom.scrollTop -= d*22;
832 // set this here to prevent jumpy scrolling on large tables
833 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
837 renderRows : function(startRow, endRow){
838 // pull in all the crap needed to render rows
839 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
840 var colCount = cm.getColumnCount();
842 if(ds.getCount() < 1){
846 // build a map for all the columns
848 for(var i = 0; i < colCount; i++){
849 var name = cm.getDataIndex(i);
851 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
852 renderer : cm.getRenderer(i),
853 id : cm.getColumnId(i),
854 locked : cm.isLocked(i)
858 startRow = startRow || 0;
859 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
862 var rs = ds.getRange(startRow, endRow);
864 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
867 // As much as I hate to duplicate code, this was branched because FireFox really hates
868 // [].join("") on strings. The performance difference was substantial enough to
869 // branch this function
870 doRender : Roo.isGecko ?
871 function(cs, rs, ds, startRow, colCount, stripe){
872 var ts = this.templates, ct = ts.cell, rt = ts.row;
874 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
876 var hasListener = this.grid.hasListener('rowclass');
878 for(var j = 0, len = rs.length; j < len; j++){
879 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
880 for(var i = 0; i < colCount; i++){
882 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
885 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
886 if(p.value == undefined || p.value === "") p.value = " ";
887 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
888 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
890 var markup = ct.apply(p);
898 if(stripe && ((rowIndex+1) % 2 == 0)){
899 alt.push("x-grid-row-alt")
902 alt.push( " x-grid-dirty-row");
905 if(this.getRowClass){
906 alt.push(this.getRowClass(r, rowIndex));
915 this.grid.fireEvent('rowclass', this, rowcfg);
916 alt.push(rowcfg.rowClass);
918 rp.alt = alt.join(" ");
925 function(cs, rs, ds, startRow, colCount, stripe){
926 var ts = this.templates, ct = ts.cell, rt = ts.row;
928 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
929 var hasListener = this.grid.hasListener('rowclass');
932 for(var j = 0, len = rs.length; j < len; j++){
933 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
934 for(var i = 0; i < colCount; i++){
936 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
939 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
940 if(p.value == undefined || p.value === "") p.value = " ";
941 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
942 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
945 var markup = ct.apply(p);
947 cb[cb.length] = markup;
949 lcb[lcb.length] = markup;
953 if(stripe && ((rowIndex+1) % 2 == 0)){
954 alt.push( "x-grid-row-alt");
957 alt.push(" x-grid-dirty-row");
960 if(this.getRowClass){
961 alt.push( this.getRowClass(r, rowIndex));
970 this.grid.fireEvent('rowclass', this, rowcfg);
971 alt.push(rowcfg.rowClass);
973 rp.alt = alt.join(" ");
974 rp.cells = lcb.join("");
975 lbuf[lbuf.length] = rt.apply(rp);
976 rp.cells = cb.join("");
977 buf[buf.length] = rt.apply(rp);
979 return [lbuf.join(""), buf.join("")];
982 renderBody : function(){
983 var markup = this.renderRows();
984 var bt = this.templates.body;
985 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
990 * @param {Boolean} headersToo
992 refresh : function(headersToo){
993 this.fireEvent("beforerefresh", this);
994 this.grid.stopEditing();
995 var result = this.renderBody();
996 this.lockedBody.update(result[0]);
997 this.mainBody.update(result[1]);
998 if(headersToo === true){
999 this.updateHeaders();
1000 this.updateColumns();
1001 this.updateSplitters();
1002 this.updateHeaderSortState();
1004 this.syncRowHeights();
1006 this.fireEvent("refresh", this);
1009 handleColumnMove : function(cm, oldIndex, newIndex){
1010 this.indexMap = null;
1011 var s = this.getScrollState();
1013 this.restoreScroll(s);
1014 this.afterMove(newIndex);
1017 afterMove : function(colIndex){
1018 if(this.enableMoveAnim && Roo.enableFx){
1019 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
1021 // if multisort - fix sortOrder, and reload..
1022 if (this.grid.dataSource.multiSort) {
1023 // the we can call sort again..
1024 var dm = this.grid.dataSource;
1025 var cm = this.grid.colModel;
1027 for(var i = 0; i < cm.config.length; i++ ) {
1029 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
1030 continue; // dont' bother, it's not in sort list or being set.
1033 so.push(cm.config[i].dataIndex);
1036 dm.load(dm.lastOptions);
1043 updateCell : function(dm, rowIndex, dataIndex){
1044 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
1045 if(typeof colIndex == "undefined"){ // not present in grid
1048 var cm = this.grid.colModel;
1049 var cell = this.getCell(rowIndex, colIndex);
1050 var cellText = this.getCellText(rowIndex, colIndex);
1053 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
1054 id : cm.getColumnId(colIndex),
1055 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
1057 var renderer = cm.getRenderer(colIndex);
1058 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
1059 if(typeof val == "undefined" || val === "") val = " ";
1060 cellText.innerHTML = val;
1061 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
1062 this.syncRowHeights(rowIndex, rowIndex);
1065 calcColumnWidth : function(colIndex, maxRowsToMeasure){
1067 if(this.grid.autoSizeHeaders){
1068 var h = this.getHeaderCellMeasure(colIndex);
1069 maxWidth = Math.max(maxWidth, h.scrollWidth);
1072 if(this.cm.isLocked(colIndex)){
1073 tb = this.getLockedTable();
1076 tb = this.getBodyTable();
1077 index = colIndex - this.cm.getLockedCount();
1081 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
1082 for(var i = 0; i < stopIndex; i++){
1083 var cell = rows[i].childNodes[index].firstChild;
1084 maxWidth = Math.max(maxWidth, cell.scrollWidth);
1087 return maxWidth + /*margin for error in IE*/ 5;
1090 * Autofit a column to its content.
1091 * @param {Number} colIndex
1092 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
1094 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
1095 if(this.cm.isHidden(colIndex)){
1096 return; // can't calc a hidden column
1099 var cid = this.cm.getColumnId(colIndex);
1100 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
1101 if(this.grid.autoSizeHeaders){
1102 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
1105 var newWidth = this.calcColumnWidth(colIndex);
1106 this.cm.setColumnWidth(colIndex,
1107 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
1109 this.grid.fireEvent("columnresize", colIndex, newWidth);
1114 * Autofits all columns to their content and then expands to fit any extra space in the grid
1116 autoSizeColumns : function(){
1117 var cm = this.grid.colModel;
1118 var colCount = cm.getColumnCount();
1119 for(var i = 0; i < colCount; i++){
1120 this.autoSizeColumn(i, true, true);
1122 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
1125 this.updateColumns();
1131 * Autofits all columns to the grid's width proportionate with their current size
1132 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
1134 fitColumns : function(reserveScrollSpace){
1135 var cm = this.grid.colModel;
1136 var colCount = cm.getColumnCount();
1140 for (i = 0; i < colCount; i++){
1141 if(!cm.isHidden(i) && !cm.isFixed(i)){
1142 w = cm.getColumnWidth(i);
1148 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
1149 if(reserveScrollSpace){
1152 var frac = (avail - cm.getTotalWidth())/width;
1153 while (cols.length){
1156 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
1158 this.updateColumns();
1162 onRowSelect : function(rowIndex){
1163 var row = this.getRowComposite(rowIndex);
1164 row.addClass("x-grid-row-selected");
1167 onRowDeselect : function(rowIndex){
1168 var row = this.getRowComposite(rowIndex);
1169 row.removeClass("x-grid-row-selected");
1172 onCellSelect : function(row, col){
1173 var cell = this.getCell(row, col);
1175 Roo.fly(cell).addClass("x-grid-cell-selected");
1179 onCellDeselect : function(row, col){
1180 var cell = this.getCell(row, col);
1182 Roo.fly(cell).removeClass("x-grid-cell-selected");
1186 updateHeaderSortState : function(){
1188 // sort state can be single { field: xxx, direction : yyy}
1189 // or { xxx=>ASC , yyy : DESC ..... }
1192 if (!this.ds.multiSort) {
1193 var state = this.ds.getSortState();
1197 mstate[state.field] = state.direction;
1198 // FIXME... - this is not used here.. but might be elsewhere..
1199 this.sortState = state;
1202 mstate = this.ds.sortToggle;
1204 //remove existing sort classes..
1206 var sc = this.sortClasses;
1207 var hds = this.el.select(this.headerSelector).removeClass(sc);
1209 for(var f in mstate) {
1211 var sortColumn = this.cm.findColumnIndex(f);
1213 if(sortColumn != -1){
1214 var sortDir = mstate[f];
1215 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
1224 handleHeaderClick : function(g, index){
1225 if(this.headersDisabled){
1228 var dm = g.dataSource, cm = g.colModel;
1229 if(!cm.isSortable(index)){
1235 // update the sortOrder
1237 for(var i = 0; i < cm.config.length; i++ ) {
1239 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
1240 continue; // dont' bother, it's not in sort list or being set.
1243 so.push(cm.config[i].dataIndex);
1249 dm.sort(cm.getDataIndex(index));
1253 destroy : function(){
1255 this.colMenu.removeAll();
1256 Roo.menu.MenuMgr.unregister(this.colMenu);
1257 this.colMenu.getEl().remove();
1258 delete this.colMenu;
1261 this.hmenu.removeAll();
1262 Roo.menu.MenuMgr.unregister(this.hmenu);
1263 this.hmenu.getEl().remove();
1266 if(this.grid.enableColumnMove){
1267 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1270 if(!dds[dd].config.isTarget && dds[dd].dragElId){
1271 var elid = dds[dd].dragElId;
1273 Roo.get(elid).remove();
1274 } else if(dds[dd].config.isTarget){
1275 dds[dd].proxyTop.remove();
1276 dds[dd].proxyBottom.remove();
1279 if(Roo.dd.DDM.locationCache[dd]){
1280 delete Roo.dd.DDM.locationCache[dd];
1283 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1286 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
1287 this.bind(null, null);
1288 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
1291 handleLockChange : function(){
1295 onDenyColumnLock : function(){
1299 onDenyColumnHide : function(){
1303 handleHdMenuClick : function(item){
1304 var index = this.hdCtxIndex;
1305 var cm = this.cm, ds = this.ds;
1308 ds.sort(cm.getDataIndex(index), "ASC");
1311 ds.sort(cm.getDataIndex(index), "DESC");
1314 var lc = cm.getLockedCount();
1315 if(cm.getColumnCount(true) <= lc+1){
1316 this.onDenyColumnLock();
1320 cm.setLocked(index, true, true);
1321 cm.moveColumn(index, lc);
1322 this.grid.fireEvent("columnmove", index, lc);
1324 cm.setLocked(index, true);
1328 var lc = cm.getLockedCount();
1329 if((lc-1) != index){
1330 cm.setLocked(index, false, true);
1331 cm.moveColumn(index, lc-1);
1332 this.grid.fireEvent("columnmove", index, lc-1);
1334 cm.setLocked(index, false);
1338 index = cm.getIndexById(item.id.substr(4));
1340 if(item.checked && cm.getColumnCount(true) <= 1){
1341 this.onDenyColumnHide();
1344 cm.setHidden(index, item.checked);
1350 beforeColMenuShow : function(){
1351 var cm = this.cm, colCount = cm.getColumnCount();
1352 this.colMenu.removeAll();
1353 for(var i = 0; i < colCount; i++){
1354 this.colMenu.add(new Roo.menu.CheckItem({
1355 id: "col-"+cm.getColumnId(i),
1356 text: cm.getColumnHeader(i),
1357 checked: !cm.isHidden(i),
1363 handleHdCtx : function(g, index, e){
1365 var hd = this.getHeaderCell(index);
1366 this.hdCtxIndex = index;
1367 var ms = this.hmenu.items, cm = this.cm;
1368 ms.get("asc").setDisabled(!cm.isSortable(index));
1369 ms.get("desc").setDisabled(!cm.isSortable(index));
1370 if(this.grid.enableColLock !== false){
1371 ms.get("lock").setDisabled(cm.isLocked(index));
1372 ms.get("unlock").setDisabled(!cm.isLocked(index));
1374 this.hmenu.show(hd, "tl-bl");
1377 handleHdOver : function(e){
1378 var hd = this.findHeaderCell(e.getTarget());
1379 if(hd && !this.headersDisabled){
1380 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
1381 this.fly(hd).addClass("x-grid-hd-over");
1386 handleHdOut : function(e){
1387 var hd = this.findHeaderCell(e.getTarget());
1389 this.fly(hd).removeClass("x-grid-hd-over");
1393 handleSplitDblClick : function(e, t){
1394 var i = this.getCellIndex(t);
1395 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
1396 this.autoSizeColumn(i, true);
1401 render : function(){
1404 var colCount = cm.getColumnCount();
1406 if(this.grid.monitorWindowResize === true){
1407 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
1409 var header = this.renderHeaders();
1410 var body = this.templates.body.apply({rows:""});
1411 var html = this.templates.master.apply({
1414 lockedHeader: header[0],
1418 //this.updateColumns();
1420 this.grid.getGridEl().dom.innerHTML = html;
1422 this.initElements();
1424 // a kludge to fix the random scolling effect in webkit
1425 this.el.on("scroll", function() {
1426 this.el.dom.scrollTop=0; // hopefully not recursive..
1429 this.scroller.on("scroll", this.handleScroll, this);
1430 this.lockedBody.on("mousewheel", this.handleWheel, this);
1431 this.mainBody.on("mousewheel", this.handleWheel, this);
1433 this.mainHd.on("mouseover", this.handleHdOver, this);
1434 this.mainHd.on("mouseout", this.handleHdOut, this);
1435 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
1436 {delegate: "."+this.splitClass});
1438 this.lockedHd.on("mouseover", this.handleHdOver, this);
1439 this.lockedHd.on("mouseout", this.handleHdOut, this);
1440 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
1441 {delegate: "."+this.splitClass});
1443 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
1444 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1447 this.updateSplitters();
1449 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
1450 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1451 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1454 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
1455 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
1457 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
1458 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
1460 if(this.grid.enableColLock !== false){
1462 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
1463 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
1466 if(this.grid.enableColumnHide !== false){
1468 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
1469 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
1470 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
1473 {id:"columns", text: this.columnsText, menu: this.colMenu}
1476 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
1478 this.grid.on("headercontextmenu", this.handleHdCtx, this);
1481 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
1482 this.dd = new Roo.grid.GridDragZone(this.grid, {
1483 ddGroup : this.grid.ddGroup || 'GridDD'
1489 for(var i = 0; i < colCount; i++){
1493 if(cm.config[i].align){
1494 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
1495 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
1499 this.updateHeaderSortState();
1501 this.beforeInitialResize();
1504 // two part rendering gives faster view to the user
1505 this.renderPhase2.defer(1, this);
1508 renderPhase2 : function(){
1509 // render the rows now
1511 if(this.grid.autoSizeColumns){
1512 this.autoSizeColumns();
1516 beforeInitialResize : function(){
1520 onColumnSplitterMoved : function(i, w){
1521 this.userResized = true;
1522 var cm = this.grid.colModel;
1523 cm.setColumnWidth(i, w, true);
1524 var cid = cm.getColumnId(i);
1525 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1526 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1527 this.updateSplitters();
1529 this.grid.fireEvent("columnresize", i, w);
1532 syncRowHeights : function(startIndex, endIndex){
1533 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
1534 startIndex = startIndex || 0;
1535 var mrows = this.getBodyTable().rows;
1536 var lrows = this.getLockedTable().rows;
1537 var len = mrows.length-1;
1538 endIndex = Math.min(endIndex || len, len);
1539 for(var i = startIndex; i <= endIndex; i++){
1540 var m = mrows[i], l = lrows[i];
1541 var h = Math.max(m.offsetHeight, l.offsetHeight);
1542 m.style.height = l.style.height = h + "px";
1547 layout : function(initialRender, is2ndPass){
1549 var auto = g.autoHeight;
1550 var scrollOffset = 16;
1551 var c = g.getGridEl(), cm = this.cm,
1552 expandCol = g.autoExpandColumn,
1556 if(!c.dom.offsetWidth){ // display:none?
1558 this.lockedWrap.show();
1559 this.mainWrap.show();
1564 var hasLock = this.cm.isLocked(0);
1566 var tbh = this.headerPanel.getHeight();
1567 var bbh = this.footerPanel.getHeight();
1570 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
1571 var newHeight = ch + c.getBorderWidth("tb");
1573 newHeight = Math.min(g.maxHeight, newHeight);
1575 c.setHeight(newHeight);
1579 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
1582 var s = this.scroller;
1584 var csize = c.getSize(true);
1586 this.el.setSize(csize.width, csize.height);
1588 this.headerPanel.setWidth(csize.width);
1589 this.footerPanel.setWidth(csize.width);
1591 var hdHeight = this.mainHd.getHeight();
1592 var vw = csize.width;
1593 var vh = csize.height - (tbh + bbh);
1597 var bt = this.getBodyTable();
1598 var ltWidth = hasLock ?
1599 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
1601 var scrollHeight = bt.offsetHeight;
1602 var scrollWidth = ltWidth + bt.offsetWidth;
1603 var vscroll = false, hscroll = false;
1605 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
1607 var lw = this.lockedWrap, mw = this.mainWrap;
1608 var lb = this.lockedBody, mb = this.mainBody;
1610 setTimeout(function(){
1611 var t = s.dom.offsetTop;
1612 var w = s.dom.clientWidth,
1613 h = s.dom.clientHeight;
1616 lw.setSize(ltWidth, h);
1618 mw.setLeftTop(ltWidth, t);
1619 mw.setSize(w-ltWidth, h);
1621 lb.setHeight(h-hdHeight);
1622 mb.setHeight(h-hdHeight);
1624 if(is2ndPass !== true && !gv.userResized && expandCol){
1625 // high speed resize without full column calculation
1627 var ci = cm.getIndexById(expandCol);
1629 ci = cm.findColumnIndex(expandCol);
1631 ci = Math.max(0, ci); // make sure it's got at least the first col.
1632 var expandId = cm.getColumnId(ci);
1633 var tw = cm.getTotalWidth(false);
1634 var currentWidth = cm.getColumnWidth(ci);
1635 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
1636 if(currentWidth != cw){
1637 cm.setColumnWidth(ci, cw, true);
1638 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1639 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1640 gv.updateSplitters();
1641 gv.layout(false, true);
1653 onWindowResize : function(){
1654 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
1660 appendFooter : function(parentEl){
1664 sortAscText : "Sort Ascending",
1665 sortDescText : "Sort Descending",
1666 lockText : "Lock Column",
1667 unlockText : "Unlock Column",
1668 columnsText : "Columns"
1672 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
1673 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
1674 this.proxy.el.addClass('x-grid3-col-dd');
1677 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
1678 handleMouseDown : function(e){
1682 callHandleMouseDown : function(e){
1683 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);