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();
404 if(colIndex < locked){
405 source = this.lockedBody.dom.firstChild;
407 source = this.mainBody.dom.firstChild;
412 return source.rows[rowIndex].childNodes[colIndex];
415 getCellText : function(rowIndex, colIndex){
416 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
419 getCellBox : function(cell){
420 var b = this.fly(cell).getBox();
421 if(Roo.isOpera){ // opera fails to report the Y
422 b.y = cell.offsetTop + this.mainBody.getY();
427 getCellIndex : function(cell){
428 var id = String(cell.className).match(this.cellRE);
430 return parseInt(id[1], 10);
435 findHeaderIndex : function(n){
436 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
437 return r ? this.getCellIndex(r) : false;
440 findHeaderCell : function(n){
441 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
442 return r ? r : false;
445 findRowIndex : function(n){
449 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
450 return r ? r.rowIndex : false;
453 findCellIndex : function(node){
454 var stop = this.el.dom;
455 while(node && node != stop){
456 if(this.findRE.test(node.className)){
457 return this.getCellIndex(node);
459 node = node.parentNode;
464 getColumnId : function(index){
465 return this.cm.getColumnId(index);
468 getSplitters : function()
470 if(this.splitterSelector){
471 return Roo.DomQuery.select(this.splitterSelector);
477 getSplitter : function(index){
478 return this.getSplitters()[index];
481 onRowOver : function(e, t){
483 if((row = this.findRowIndex(t)) !== false){
484 this.getRowComposite(row).addClass("x-grid-row-over");
488 onRowOut : function(e, t){
490 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
491 this.getRowComposite(row).removeClass("x-grid-row-over");
495 renderHeaders : function(){
497 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
498 var cb = [], lb = [], sb = [], lsb = [], p = {};
499 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
500 p.cellId = "x-grid-hd-0-" + i;
501 p.splitId = "x-grid-csplit-0-" + i;
502 p.id = cm.getColumnId(i);
503 p.title = cm.getColumnTooltip(i) || cm.getColumnHeader(i) || "";
504 p.value = cm.getColumnHeader(i) || "";
505 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
507 cb[cb.length] = ct.apply(p);
508 sb[sb.length] = st.apply(p);
510 lb[lb.length] = ct.apply(p);
511 lsb[lsb.length] = st.apply(p);
514 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
515 ht.apply({cells: cb.join(""), splits:sb.join("")})];
518 updateHeaders : function(){
519 var html = this.renderHeaders();
520 this.lockedHd.update(html[0]);
521 this.mainHd.update(html[1]);
525 * Focuses the specified row.
526 * @param {Number} row The row index
528 focusRow : function(row)
530 //Roo.log('GridView.focusRow');
531 var x = this.scroller.dom.scrollLeft;
532 this.focusCell(row, 0, false);
533 this.scroller.dom.scrollLeft = x;
537 * Focuses the specified cell.
538 * @param {Number} row The row index
539 * @param {Number} col The column index
540 * @param {Boolean} hscroll false to disable horizontal scrolling
542 focusCell : function(row, col, hscroll)
544 //Roo.log('GridView.focusCell');
545 var el = this.ensureVisible(row, col, hscroll);
546 this.focusEl.alignTo(el, "tl-tl");
548 this.focusEl.focus();
550 this.focusEl.focus.defer(1, this.focusEl);
555 * Scrolls the specified cell into view
556 * @param {Number} row The row index
557 * @param {Number} col The column index
558 * @param {Boolean} hscroll false to disable horizontal scrolling
560 ensureVisible : function(row, col, hscroll)
562 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
563 //return null; //disable for testing.
564 if(typeof row != "number"){
567 if(row < 0 && row >= this.ds.getCount()){
570 col = (col !== undefined ? col : 0);
571 var cm = this.grid.colModel;
572 while(cm.isHidden(col)){
575 Roo.log(['view : ', row, col]);
576 var el = this.getCell(row, col);
581 var c = this.scroller.dom;
583 var ctop = parseInt(el.offsetTop, 10);
584 var cleft = parseInt(el.offsetLeft, 10);
585 var cbot = ctop + el.offsetHeight;
586 var cright = cleft + el.offsetWidth;
588 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
589 var stop = parseInt(c.scrollTop, 10);
590 var sleft = parseInt(c.scrollLeft, 10);
591 var sbot = stop + ch;
592 var sright = sleft + c.clientWidth;
594 Roo.log('GridView.ensureVisible:' +
596 ' c.clientHeight:' + c.clientHeight +
597 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
606 //Roo.log("set scrolltop to ctop DISABLE?");
607 }else if(cbot > sbot){
608 //Roo.log("set scrolltop to cbot-ch");
609 c.scrollTop = cbot-ch;
612 if(hscroll !== false){
614 c.scrollLeft = cleft;
615 }else if(cright > sright){
616 c.scrollLeft = cright-c.clientWidth;
623 updateColumns : function(){
624 this.grid.stopEditing();
625 var cm = this.grid.colModel, colIds = this.getColumnIds();
626 //var totalWidth = cm.getTotalWidth();
628 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
629 //if(cm.isHidden(i)) continue;
630 var w = cm.getColumnWidth(i);
631 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
632 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
634 this.updateSplitters();
637 generateRules : function(cm){
638 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
639 Roo.util.CSS.removeStyleSheet(rulesId);
640 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
641 var cid = cm.getColumnId(i);
643 if(cm.config[i].align){
644 align = 'text-align:'+cm.config[i].align+';';
648 hidden = 'display:none;';
650 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
652 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
653 this.hdSelector, cid, " {\n", align, width, "}\n",
654 this.tdSelector, cid, " {\n",hidden,"\n}\n",
655 this.splitSelector, cid, " {\n", hidden , "\n}\n");
657 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
660 updateSplitters : function(){
661 var cm = this.cm, s = this.getSplitters();
662 if(s){ // splitters not created yet
663 var pos = 0, locked = true;
664 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
668 var w = cm.getColumnWidth(i); // make sure it's a number
669 if(!cm.isLocked(i) && locked){
674 s[i].style.left = (pos-this.splitOffset) + "px";
679 handleHiddenChange : function(colModel, colIndex, hidden){
681 this.hideColumn(colIndex);
683 this.unhideColumn(colIndex);
687 hideColumn : function(colIndex){
688 var cid = this.getColumnId(colIndex);
689 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
690 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
692 this.updateHeaders();
694 this.updateSplitters();
698 unhideColumn : function(colIndex){
699 var cid = this.getColumnId(colIndex);
700 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
701 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
704 this.updateHeaders();
706 this.updateSplitters();
710 insertRows : function(dm, firstRow, lastRow, isUpdate){
711 if(firstRow == 0 && lastRow == dm.getCount()-1){
715 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
717 var s = this.getScrollState();
718 var markup = this.renderRows(firstRow, lastRow);
719 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
720 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
721 this.restoreScroll(s);
723 this.fireEvent("rowsinserted", this, firstRow, lastRow);
724 this.syncRowHeights(firstRow, lastRow);
725 this.stripeRows(firstRow);
731 bufferRows : function(markup, target, index){
732 var before = null, trows = target.rows, tbody = target.tBodies[0];
733 if(index < trows.length){
734 before = trows[index];
736 var b = document.createElement("div");
737 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
738 var rows = b.firstChild.rows;
739 for(var i = 0, len = rows.length; i < len; i++){
741 tbody.insertBefore(rows[0], before);
743 tbody.appendChild(rows[0]);
750 deleteRows : function(dm, firstRow, lastRow){
751 if(dm.getRowCount()<1){
752 this.fireEvent("beforerefresh", this);
753 this.mainBody.update("");
754 this.lockedBody.update("");
755 this.fireEvent("refresh", this);
757 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
758 var bt = this.getBodyTable();
759 var tbody = bt.firstChild;
761 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
762 tbody.removeChild(rows[firstRow]);
764 this.stripeRows(firstRow);
765 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
769 updateRows : function(dataSource, firstRow, lastRow){
770 var s = this.getScrollState();
772 this.restoreScroll(s);
775 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
779 this.updateHeaderSortState();
782 getScrollState : function(){
784 var sb = this.scroller.dom;
785 return {left: sb.scrollLeft, top: sb.scrollTop};
788 stripeRows : function(startRow){
789 if(!this.grid.stripeRows || this.ds.getCount() < 1){
792 startRow = startRow || 0;
793 var rows = this.getBodyTable().rows;
794 var lrows = this.getLockedTable().rows;
795 var cls = ' x-grid-row-alt ';
796 for(var i = startRow, len = rows.length; i < len; i++){
797 var row = rows[i], lrow = lrows[i];
798 var isAlt = ((i+1) % 2 == 0);
799 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
804 row.className += " x-grid-row-alt";
806 row.className = row.className.replace("x-grid-row-alt", "");
809 lrow.className = row.className;
814 restoreScroll : function(state){
815 //Roo.log('GridView.restoreScroll');
816 var sb = this.scroller.dom;
817 sb.scrollLeft = state.left;
818 sb.scrollTop = state.top;
822 syncScroll : function(){
823 //Roo.log('GridView.syncScroll');
824 var sb = this.scroller.dom;
825 var sh = this.mainHd.dom;
826 var bs = this.mainBody.dom;
827 var lv = this.lockedBody.dom;
828 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
829 lv.scrollTop = bs.scrollTop = sb.scrollTop;
832 handleScroll : function(e){
834 var sb = this.scroller.dom;
835 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
839 handleWheel : function(e){
840 var d = e.getWheelDelta();
841 this.scroller.dom.scrollTop -= d*22;
842 // set this here to prevent jumpy scrolling on large tables
843 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
847 renderRows : function(startRow, endRow){
848 // pull in all the crap needed to render rows
849 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
850 var colCount = cm.getColumnCount();
852 if(ds.getCount() < 1){
856 // build a map for all the columns
858 for(var i = 0; i < colCount; i++){
859 var name = cm.getDataIndex(i);
861 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
862 renderer : cm.getRenderer(i),
863 id : cm.getColumnId(i),
864 locked : cm.isLocked(i),
865 has_editor : cm.isCellEditable(i)
869 startRow = startRow || 0;
870 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
873 var rs = ds.getRange(startRow, endRow);
875 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
878 // As much as I hate to duplicate code, this was branched because FireFox really hates
879 // [].join("") on strings. The performance difference was substantial enough to
880 // branch this function
881 doRender : Roo.isGecko ?
882 function(cs, rs, ds, startRow, colCount, stripe){
883 var ts = this.templates, ct = ts.cell, rt = ts.row;
885 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
887 var hasListener = this.grid.hasListener('rowclass');
889 for(var j = 0, len = rs.length; j < len; j++){
890 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
891 for(var i = 0; i < colCount; i++){
893 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
896 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
897 if(p.value == undefined || p.value === "") {
901 p.css += ' x-grid-editable-cell';
903 if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
904 p.css += ' x-grid-dirty-cell';
906 var markup = ct.apply(p);
914 if(stripe && ((rowIndex+1) % 2 == 0)){
915 alt.push("x-grid-row-alt")
918 alt.push( " x-grid-dirty-row");
921 if(this.getRowClass){
922 alt.push(this.getRowClass(r, rowIndex));
931 this.grid.fireEvent('rowclass', this, rowcfg);
932 alt.push(rowcfg.rowClass);
934 rp.alt = alt.join(" ");
941 function(cs, rs, ds, startRow, colCount, stripe){
942 var ts = this.templates, ct = ts.cell, rt = ts.row;
944 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
945 var hasListener = this.grid.hasListener('rowclass');
948 for(var j = 0, len = rs.length; j < len; j++){
949 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
950 for(var i = 0; i < colCount; i++){
952 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
955 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
956 if(p.value == undefined || p.value === "") {
961 p.css += ' x-grid-editable-cell';
963 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
964 p.css += ' x-grid-dirty-cell'
967 var markup = ct.apply(p);
969 cb[cb.length] = markup;
971 lcb[lcb.length] = markup;
975 if(stripe && ((rowIndex+1) % 2 == 0)){
976 alt.push( "x-grid-row-alt");
979 alt.push(" x-grid-dirty-row");
982 if(this.getRowClass){
983 alt.push( this.getRowClass(r, rowIndex));
992 this.grid.fireEvent('rowclass', this, rowcfg);
993 alt.push(rowcfg.rowClass);
996 rp.alt = alt.join(" ");
997 rp.cells = lcb.join("");
998 lbuf[lbuf.length] = rt.apply(rp);
999 rp.cells = cb.join("");
1000 buf[buf.length] = rt.apply(rp);
1002 return [lbuf.join(""), buf.join("")];
1005 renderBody : function(){
1006 var markup = this.renderRows();
1007 var bt = this.templates.body;
1008 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
1012 * Refreshes the grid
1013 * @param {Boolean} headersToo
1015 refresh : function(headersToo){
1016 this.fireEvent("beforerefresh", this);
1017 this.grid.stopEditing();
1018 var result = this.renderBody();
1019 this.lockedBody.update(result[0]);
1020 this.mainBody.update(result[1]);
1021 if(headersToo === true){
1022 this.updateHeaders();
1023 this.updateColumns();
1024 this.updateSplitters();
1025 this.updateHeaderSortState();
1027 this.syncRowHeights();
1029 this.fireEvent("refresh", this);
1032 handleColumnMove : function(cm, oldIndex, newIndex){
1033 this.indexMap = null;
1034 var s = this.getScrollState();
1036 this.restoreScroll(s);
1037 this.afterMove(newIndex);
1040 afterMove : function(colIndex){
1041 if(this.enableMoveAnim && Roo.enableFx){
1042 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
1044 // if multisort - fix sortOrder, and reload..
1045 if (this.grid.dataSource.multiSort) {
1046 // the we can call sort again..
1047 var dm = this.grid.dataSource;
1048 var cm = this.grid.colModel;
1050 for(var i = 0; i < cm.config.length; i++ ) {
1052 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
1053 continue; // dont' bother, it's not in sort list or being set.
1056 so.push(cm.config[i].dataIndex);
1059 dm.load(dm.lastOptions);
1066 updateCell : function(dm, rowIndex, dataIndex){
1067 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
1068 if(typeof colIndex == "undefined"){ // not present in grid
1071 var cm = this.grid.colModel;
1072 var cell = this.getCell(rowIndex, colIndex);
1073 var cellText = this.getCellText(rowIndex, colIndex);
1076 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
1077 id : cm.getColumnId(colIndex),
1078 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
1080 var renderer = cm.getRenderer(colIndex);
1081 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
1082 if(typeof val == "undefined" || val === "") {
1085 cellText.innerHTML = val;
1086 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
1087 this.syncRowHeights(rowIndex, rowIndex);
1090 calcColumnWidth : function(colIndex, maxRowsToMeasure){
1092 if(this.grid.autoSizeHeaders){
1093 var h = this.getHeaderCellMeasure(colIndex);
1094 maxWidth = Math.max(maxWidth, h.scrollWidth);
1097 if(this.cm.isLocked(colIndex)){
1098 tb = this.getLockedTable();
1101 tb = this.getBodyTable();
1102 index = colIndex - this.cm.getLockedCount();
1106 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
1107 for(var i = 0; i < stopIndex; i++){
1108 var cell = rows[i].childNodes[index].firstChild;
1109 maxWidth = Math.max(maxWidth, cell.scrollWidth);
1112 return maxWidth + /*margin for error in IE*/ 5;
1115 * Autofit a column to its content.
1116 * @param {Number} colIndex
1117 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
1119 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
1120 if(this.cm.isHidden(colIndex)){
1121 return; // can't calc a hidden column
1124 var cid = this.cm.getColumnId(colIndex);
1125 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
1126 if(this.grid.autoSizeHeaders){
1127 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
1130 var newWidth = this.calcColumnWidth(colIndex);
1131 this.cm.setColumnWidth(colIndex,
1132 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
1134 this.grid.fireEvent("columnresize", colIndex, newWidth);
1139 * Autofits all columns to their content and then expands to fit any extra space in the grid
1141 autoSizeColumns : function(){
1142 var cm = this.grid.colModel;
1143 var colCount = cm.getColumnCount();
1144 for(var i = 0; i < colCount; i++){
1145 this.autoSizeColumn(i, true, true);
1147 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
1150 this.updateColumns();
1156 * Autofits all columns to the grid's width proportionate with their current size
1157 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
1159 fitColumns : function(reserveScrollSpace){
1160 var cm = this.grid.colModel;
1161 var colCount = cm.getColumnCount();
1165 for (i = 0; i < colCount; i++){
1166 if(!cm.isHidden(i) && !cm.isFixed(i)){
1167 w = cm.getColumnWidth(i);
1173 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
1174 if(reserveScrollSpace){
1177 var frac = (avail - cm.getTotalWidth())/width;
1178 while (cols.length){
1181 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
1183 this.updateColumns();
1187 onRowSelect : function(rowIndex){
1188 var row = this.getRowComposite(rowIndex);
1189 row.addClass("x-grid-row-selected");
1192 onRowDeselect : function(rowIndex){
1193 var row = this.getRowComposite(rowIndex);
1194 row.removeClass("x-grid-row-selected");
1197 onCellSelect : function(row, col){
1198 var cell = this.getCell(row, col);
1200 Roo.fly(cell).addClass("x-grid-cell-selected");
1204 onCellDeselect : function(row, col){
1205 var cell = this.getCell(row, col);
1207 Roo.fly(cell).removeClass("x-grid-cell-selected");
1211 updateHeaderSortState : function(){
1213 // sort state can be single { field: xxx, direction : yyy}
1214 // or { xxx=>ASC , yyy : DESC ..... }
1217 if (!this.ds.multiSort) {
1218 var state = this.ds.getSortState();
1222 mstate[state.field] = state.direction;
1223 // FIXME... - this is not used here.. but might be elsewhere..
1224 this.sortState = state;
1227 mstate = this.ds.sortToggle;
1229 //remove existing sort classes..
1231 var sc = this.sortClasses;
1232 var hds = this.el.select(this.headerSelector).removeClass(sc);
1234 for(var f in mstate) {
1236 var sortColumn = this.cm.findColumnIndex(f);
1238 if(sortColumn != -1){
1239 var sortDir = mstate[f];
1240 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
1249 handleHeaderClick : function(g, index,e){
1251 Roo.log("header click");
1254 // touch events on header are handled by context
1255 this.handleHdCtx(g,index,e);
1260 if(this.headersDisabled){
1263 var dm = g.dataSource, cm = g.colModel;
1264 if(!cm.isSortable(index)){
1270 // update the sortOrder
1272 for(var i = 0; i < cm.config.length; i++ ) {
1274 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
1275 continue; // dont' bother, it's not in sort list or being set.
1278 so.push(cm.config[i].dataIndex);
1284 dm.sort(cm.getDataIndex(index));
1288 destroy : function(){
1290 this.colMenu.removeAll();
1291 Roo.menu.MenuMgr.unregister(this.colMenu);
1292 this.colMenu.getEl().remove();
1293 delete this.colMenu;
1296 this.hmenu.removeAll();
1297 Roo.menu.MenuMgr.unregister(this.hmenu);
1298 this.hmenu.getEl().remove();
1301 if(this.grid.enableColumnMove){
1302 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1305 if(!dds[dd].config.isTarget && dds[dd].dragElId){
1306 var elid = dds[dd].dragElId;
1308 Roo.get(elid).remove();
1309 } else if(dds[dd].config.isTarget){
1310 dds[dd].proxyTop.remove();
1311 dds[dd].proxyBottom.remove();
1314 if(Roo.dd.DDM.locationCache[dd]){
1315 delete Roo.dd.DDM.locationCache[dd];
1318 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1321 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
1322 this.bind(null, null);
1323 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
1326 handleLockChange : function(){
1330 onDenyColumnLock : function(){
1334 onDenyColumnHide : function(){
1338 handleHdMenuClick : function(item){
1339 var index = this.hdCtxIndex;
1340 var cm = this.cm, ds = this.ds;
1343 ds.sort(cm.getDataIndex(index), "ASC");
1346 ds.sort(cm.getDataIndex(index), "DESC");
1349 var lc = cm.getLockedCount();
1350 if(cm.getColumnCount(true) <= lc+1){
1351 this.onDenyColumnLock();
1355 cm.setLocked(index, true, true);
1356 cm.moveColumn(index, lc);
1357 this.grid.fireEvent("columnmove", index, lc);
1359 cm.setLocked(index, true);
1363 var lc = cm.getLockedCount();
1364 if((lc-1) != index){
1365 cm.setLocked(index, false, true);
1366 cm.moveColumn(index, lc-1);
1367 this.grid.fireEvent("columnmove", index, lc-1);
1369 cm.setLocked(index, false);
1372 case 'wider': // used to expand cols on touch..
1374 var cw = cm.getColumnWidth(index);
1375 cw += (item.id == 'wider' ? 1 : -1) * 50;
1376 cw = Math.max(0, cw);
1377 cw = Math.min(cw,4000);
1378 cm.setColumnWidth(index, cw);
1382 index = cm.getIndexById(item.id.substr(4));
1384 if(item.checked && cm.getColumnCount(true) <= 1){
1385 this.onDenyColumnHide();
1388 cm.setHidden(index, item.checked);
1394 beforeColMenuShow : function(){
1395 var cm = this.cm, colCount = cm.getColumnCount();
1396 this.colMenu.removeAll();
1397 for(var i = 0; i < colCount; i++){
1398 this.colMenu.add(new Roo.menu.CheckItem({
1399 id: "col-"+cm.getColumnId(i),
1400 text: cm.getColumnHeader(i),
1401 checked: !cm.isHidden(i),
1407 handleHdCtx : function(g, index, e){
1409 var hd = this.getHeaderCell(index);
1410 this.hdCtxIndex = index;
1411 var ms = this.hmenu.items, cm = this.cm;
1412 ms.get("asc").setDisabled(!cm.isSortable(index));
1413 ms.get("desc").setDisabled(!cm.isSortable(index));
1414 if(this.grid.enableColLock !== false){
1415 ms.get("lock").setDisabled(cm.isLocked(index));
1416 ms.get("unlock").setDisabled(!cm.isLocked(index));
1418 this.hmenu.show(hd, "tl-bl");
1421 handleHdOver : function(e){
1422 var hd = this.findHeaderCell(e.getTarget());
1423 if(hd && !this.headersDisabled){
1424 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
1425 this.fly(hd).addClass("x-grid-hd-over");
1430 handleHdOut : function(e){
1431 var hd = this.findHeaderCell(e.getTarget());
1433 this.fly(hd).removeClass("x-grid-hd-over");
1437 handleSplitDblClick : function(e, t){
1438 var i = this.getCellIndex(t);
1439 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
1440 this.autoSizeColumn(i, true);
1445 render : function(){
1448 var colCount = cm.getColumnCount();
1450 if(this.grid.monitorWindowResize === true){
1451 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
1453 var header = this.renderHeaders();
1454 var body = this.templates.body.apply({rows:""});
1455 var html = this.templates.master.apply({
1458 lockedHeader: header[0],
1462 //this.updateColumns();
1464 this.grid.getGridEl().dom.innerHTML = html;
1466 this.initElements();
1468 // a kludge to fix the random scolling effect in webkit
1469 this.el.on("scroll", function() {
1470 this.el.dom.scrollTop=0; // hopefully not recursive..
1473 this.scroller.on("scroll", this.handleScroll, this);
1474 this.lockedBody.on("mousewheel", this.handleWheel, this);
1475 this.mainBody.on("mousewheel", this.handleWheel, this);
1477 this.mainHd.on("mouseover", this.handleHdOver, this);
1478 this.mainHd.on("mouseout", this.handleHdOut, this);
1479 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
1480 {delegate: "."+this.splitClass});
1482 this.lockedHd.on("mouseover", this.handleHdOver, this);
1483 this.lockedHd.on("mouseout", this.handleHdOut, this);
1484 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
1485 {delegate: "."+this.splitClass});
1487 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
1488 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1491 this.updateSplitters();
1493 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
1494 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1495 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1498 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
1499 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
1501 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
1502 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
1504 if(this.grid.enableColLock !== false){
1506 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
1507 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
1512 {id:"wider", text: this.columnsWiderText},
1513 {id:"narrow", text: this.columnsNarrowText }
1519 if(this.grid.enableColumnHide !== false){
1521 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
1522 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
1523 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
1526 {id:"columns", text: this.columnsText, menu: this.colMenu}
1529 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
1531 this.grid.on("headercontextmenu", this.handleHdCtx, this);
1534 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
1535 this.dd = new Roo.grid.GridDragZone(this.grid, {
1536 ddGroup : this.grid.ddGroup || 'GridDD'
1542 for(var i = 0; i < colCount; i++){
1546 if(cm.config[i].align){
1547 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
1548 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
1552 this.updateHeaderSortState();
1554 this.beforeInitialResize();
1557 // two part rendering gives faster view to the user
1558 this.renderPhase2.defer(1, this);
1561 renderPhase2 : function(){
1562 // render the rows now
1564 if(this.grid.autoSizeColumns){
1565 this.autoSizeColumns();
1569 beforeInitialResize : function(){
1573 onColumnSplitterMoved : function(i, w){
1574 this.userResized = true;
1575 var cm = this.grid.colModel;
1576 cm.setColumnWidth(i, w, true);
1577 var cid = cm.getColumnId(i);
1578 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1579 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1580 this.updateSplitters();
1582 this.grid.fireEvent("columnresize", i, w);
1585 syncRowHeights : function(startIndex, endIndex){
1586 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
1587 startIndex = startIndex || 0;
1588 var mrows = this.getBodyTable().rows;
1589 var lrows = this.getLockedTable().rows;
1590 var len = mrows.length-1;
1591 endIndex = Math.min(endIndex || len, len);
1592 for(var i = startIndex; i <= endIndex; i++){
1593 var m = mrows[i], l = lrows[i];
1594 var h = Math.max(m.offsetHeight, l.offsetHeight);
1595 m.style.height = l.style.height = h + "px";
1600 layout : function(initialRender, is2ndPass){
1602 var auto = g.autoHeight;
1603 var scrollOffset = 16;
1604 var c = g.getGridEl(), cm = this.cm,
1605 expandCol = g.autoExpandColumn,
1609 if(!c.dom.offsetWidth){ // display:none?
1611 this.lockedWrap.show();
1612 this.mainWrap.show();
1617 var hasLock = this.cm.isLocked(0);
1619 var tbh = this.headerPanel.getHeight();
1620 var bbh = this.footerPanel.getHeight();
1623 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
1624 var newHeight = ch + c.getBorderWidth("tb");
1626 newHeight = Math.min(g.maxHeight, newHeight);
1628 c.setHeight(newHeight);
1632 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
1635 var s = this.scroller;
1637 var csize = c.getSize(true);
1639 this.el.setSize(csize.width, csize.height);
1641 this.headerPanel.setWidth(csize.width);
1642 this.footerPanel.setWidth(csize.width);
1644 var hdHeight = this.mainHd.getHeight();
1645 var vw = csize.width;
1646 var vh = csize.height - (tbh + bbh);
1650 var bt = this.getBodyTable();
1651 var ltWidth = hasLock ?
1652 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
1654 var scrollHeight = bt.offsetHeight;
1655 var scrollWidth = ltWidth + bt.offsetWidth;
1656 var vscroll = false, hscroll = false;
1658 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
1660 var lw = this.lockedWrap, mw = this.mainWrap;
1661 var lb = this.lockedBody, mb = this.mainBody;
1663 setTimeout(function(){
1664 var t = s.dom.offsetTop;
1665 var w = s.dom.clientWidth,
1666 h = s.dom.clientHeight;
1669 lw.setSize(ltWidth, h);
1671 mw.setLeftTop(ltWidth, t);
1672 mw.setSize(w-ltWidth, h);
1674 lb.setHeight(h-hdHeight);
1675 mb.setHeight(h-hdHeight);
1677 if(is2ndPass !== true && !gv.userResized && expandCol){
1678 // high speed resize without full column calculation
1680 var ci = cm.getIndexById(expandCol);
1682 ci = cm.findColumnIndex(expandCol);
1684 ci = Math.max(0, ci); // make sure it's got at least the first col.
1685 var expandId = cm.getColumnId(ci);
1686 var tw = cm.getTotalWidth(false);
1687 var currentWidth = cm.getColumnWidth(ci);
1688 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
1689 if(currentWidth != cw){
1690 cm.setColumnWidth(ci, cw, true);
1691 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1692 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1693 gv.updateSplitters();
1694 gv.layout(false, true);
1706 onWindowResize : function(){
1707 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
1713 appendFooter : function(parentEl){
1717 sortAscText : "Sort Ascending",
1718 sortDescText : "Sort Descending",
1719 lockText : "Lock Column",
1720 unlockText : "Unlock Column",
1721 columnsText : "Columns",
1723 columnsWiderText : "Wider",
1724 columnsNarrowText : "Thinner"
1728 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
1729 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
1730 this.proxy.el.addClass('x-grid3-col-dd');
1733 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
1734 handleMouseDown : function(e){
1738 callHandleMouseDown : function(e){
1739 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);