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.value = cm.getColumnHeader(i) || "";
501 p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</) ? '' : p.value || "";
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++){
664 var w = cm.getColumnWidth(i); // make sure it's a number
665 if(!cm.isLocked(i) && locked){
670 s[i].style.left = (pos-this.splitOffset) + "px";
675 handleHiddenChange : function(colModel, colIndex, hidden){
677 this.hideColumn(colIndex);
679 this.unhideColumn(colIndex);
683 hideColumn : function(colIndex){
684 var cid = this.getColumnId(colIndex);
685 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
686 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
688 this.updateHeaders();
690 this.updateSplitters();
694 unhideColumn : function(colIndex){
695 var cid = this.getColumnId(colIndex);
696 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
697 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
700 this.updateHeaders();
702 this.updateSplitters();
706 insertRows : function(dm, firstRow, lastRow, isUpdate){
707 if(firstRow == 0 && lastRow == dm.getCount()-1){
711 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
713 var s = this.getScrollState();
714 var markup = this.renderRows(firstRow, lastRow);
715 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
716 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
717 this.restoreScroll(s);
719 this.fireEvent("rowsinserted", this, firstRow, lastRow);
720 this.syncRowHeights(firstRow, lastRow);
721 this.stripeRows(firstRow);
727 bufferRows : function(markup, target, index){
728 var before = null, trows = target.rows, tbody = target.tBodies[0];
729 if(index < trows.length){
730 before = trows[index];
732 var b = document.createElement("div");
733 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
734 var rows = b.firstChild.rows;
735 for(var i = 0, len = rows.length; i < len; i++){
737 tbody.insertBefore(rows[0], before);
739 tbody.appendChild(rows[0]);
746 deleteRows : function(dm, firstRow, lastRow){
747 if(dm.getRowCount()<1){
748 this.fireEvent("beforerefresh", this);
749 this.mainBody.update("");
750 this.lockedBody.update("");
751 this.fireEvent("refresh", this);
753 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
754 var bt = this.getBodyTable();
755 var tbody = bt.firstChild;
757 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
758 tbody.removeChild(rows[firstRow]);
760 this.stripeRows(firstRow);
761 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
765 updateRows : function(dataSource, firstRow, lastRow){
766 var s = this.getScrollState();
768 this.restoreScroll(s);
771 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
775 this.updateHeaderSortState();
778 getScrollState : function(){
780 var sb = this.scroller.dom;
781 return {left: sb.scrollLeft, top: sb.scrollTop};
784 stripeRows : function(startRow){
785 if(!this.grid.stripeRows || this.ds.getCount() < 1){
788 startRow = startRow || 0;
789 var rows = this.getBodyTable().rows;
790 var lrows = this.getLockedTable().rows;
791 var cls = ' x-grid-row-alt ';
792 for(var i = startRow, len = rows.length; i < len; i++){
793 var row = rows[i], lrow = lrows[i];
794 var isAlt = ((i+1) % 2 == 0);
795 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
800 row.className += " x-grid-row-alt";
802 row.className = row.className.replace("x-grid-row-alt", "");
805 lrow.className = row.className;
810 restoreScroll : function(state){
811 //Roo.log('GridView.restoreScroll');
812 var sb = this.scroller.dom;
813 sb.scrollLeft = state.left;
814 sb.scrollTop = state.top;
818 syncScroll : function(){
819 //Roo.log('GridView.syncScroll');
820 var sb = this.scroller.dom;
821 var sh = this.mainHd.dom;
822 var bs = this.mainBody.dom;
823 var lv = this.lockedBody.dom;
824 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
825 lv.scrollTop = bs.scrollTop = sb.scrollTop;
828 handleScroll : function(e){
830 var sb = this.scroller.dom;
831 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
835 handleWheel : function(e){
836 var d = e.getWheelDelta();
837 this.scroller.dom.scrollTop -= d*22;
838 // set this here to prevent jumpy scrolling on large tables
839 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
843 renderRows : function(startRow, endRow){
844 // pull in all the crap needed to render rows
845 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
846 var colCount = cm.getColumnCount();
848 if(ds.getCount() < 1){
852 // build a map for all the columns
854 for(var i = 0; i < colCount; i++){
855 var name = cm.getDataIndex(i);
857 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
858 renderer : cm.getRenderer(i),
859 id : cm.getColumnId(i),
860 locked : cm.isLocked(i),
861 has_editor : cm.isCellEditable(i)
865 startRow = startRow || 0;
866 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
869 var rs = ds.getRange(startRow, endRow);
871 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
874 // As much as I hate to duplicate code, this was branched because FireFox really hates
875 // [].join("") on strings. The performance difference was substantial enough to
876 // branch this function
877 doRender : Roo.isGecko ?
878 function(cs, rs, ds, startRow, colCount, stripe){
879 var ts = this.templates, ct = ts.cell, rt = ts.row;
881 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
883 var hasListener = this.grid.hasListener('rowclass');
885 for(var j = 0, len = rs.length; j < len; j++){
886 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
887 for(var i = 0; i < colCount; i++){
889 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
892 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
893 if(p.value == undefined || p.value === "") {
897 p.css += ' x-grid-editable-cell';
899 if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
900 p.css += ' x-grid-dirty-cell';
902 var markup = ct.apply(p);
910 if(stripe && ((rowIndex+1) % 2 == 0)){
911 alt.push("x-grid-row-alt")
914 alt.push( " x-grid-dirty-row");
917 if(this.getRowClass){
918 alt.push(this.getRowClass(r, rowIndex));
927 this.grid.fireEvent('rowclass', this, rowcfg);
928 alt.push(rowcfg.rowClass);
930 rp.alt = alt.join(" ");
937 function(cs, rs, ds, startRow, colCount, stripe){
938 var ts = this.templates, ct = ts.cell, rt = ts.row;
940 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
941 var hasListener = this.grid.hasListener('rowclass');
944 for(var j = 0, len = rs.length; j < len; j++){
945 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
946 for(var i = 0; i < colCount; i++){
948 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
951 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
952 if(p.value == undefined || p.value === "") {
957 p.css += ' x-grid-editable-cell';
959 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
960 p.css += ' x-grid-dirty-cell'
963 var markup = ct.apply(p);
965 cb[cb.length] = markup;
967 lcb[lcb.length] = markup;
971 if(stripe && ((rowIndex+1) % 2 == 0)){
972 alt.push( "x-grid-row-alt");
975 alt.push(" x-grid-dirty-row");
978 if(this.getRowClass){
979 alt.push( this.getRowClass(r, rowIndex));
988 this.grid.fireEvent('rowclass', this, rowcfg);
989 alt.push(rowcfg.rowClass);
992 rp.alt = alt.join(" ");
993 rp.cells = lcb.join("");
994 lbuf[lbuf.length] = rt.apply(rp);
995 rp.cells = cb.join("");
996 buf[buf.length] = rt.apply(rp);
998 return [lbuf.join(""), buf.join("")];
1001 renderBody : function(){
1002 var markup = this.renderRows();
1003 var bt = this.templates.body;
1004 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
1008 * Refreshes the grid
1009 * @param {Boolean} headersToo
1011 refresh : function(headersToo){
1012 this.fireEvent("beforerefresh", this);
1013 this.grid.stopEditing();
1014 var result = this.renderBody();
1015 this.lockedBody.update(result[0]);
1016 this.mainBody.update(result[1]);
1017 if(headersToo === true){
1018 this.updateHeaders();
1019 this.updateColumns();
1020 this.updateSplitters();
1021 this.updateHeaderSortState();
1023 this.syncRowHeights();
1025 this.fireEvent("refresh", this);
1028 handleColumnMove : function(cm, oldIndex, newIndex){
1029 this.indexMap = null;
1030 var s = this.getScrollState();
1032 this.restoreScroll(s);
1033 this.afterMove(newIndex);
1036 afterMove : function(colIndex){
1037 if(this.enableMoveAnim && Roo.enableFx){
1038 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
1040 // if multisort - fix sortOrder, and reload..
1041 if (this.grid.dataSource.multiSort) {
1042 // the we can call sort again..
1043 var dm = this.grid.dataSource;
1044 var cm = this.grid.colModel;
1046 for(var i = 0; i < cm.config.length; i++ ) {
1048 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
1049 continue; // dont' bother, it's not in sort list or being set.
1052 so.push(cm.config[i].dataIndex);
1055 dm.load(dm.lastOptions);
1062 updateCell : function(dm, rowIndex, dataIndex){
1063 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
1064 if(typeof colIndex == "undefined"){ // not present in grid
1067 var cm = this.grid.colModel;
1068 var cell = this.getCell(rowIndex, colIndex);
1069 var cellText = this.getCellText(rowIndex, colIndex);
1072 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
1073 id : cm.getColumnId(colIndex),
1074 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
1076 var renderer = cm.getRenderer(colIndex);
1077 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
1078 if(typeof val == "undefined" || val === "") {
1081 cellText.innerHTML = val;
1082 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
1083 this.syncRowHeights(rowIndex, rowIndex);
1086 calcColumnWidth : function(colIndex, maxRowsToMeasure){
1088 if(this.grid.autoSizeHeaders){
1089 var h = this.getHeaderCellMeasure(colIndex);
1090 maxWidth = Math.max(maxWidth, h.scrollWidth);
1093 if(this.cm.isLocked(colIndex)){
1094 tb = this.getLockedTable();
1097 tb = this.getBodyTable();
1098 index = colIndex - this.cm.getLockedCount();
1102 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
1103 for(var i = 0; i < stopIndex; i++){
1104 var cell = rows[i].childNodes[index].firstChild;
1105 maxWidth = Math.max(maxWidth, cell.scrollWidth);
1108 return maxWidth + /*margin for error in IE*/ 5;
1111 * Autofit a column to its content.
1112 * @param {Number} colIndex
1113 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
1115 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
1116 if(this.cm.isHidden(colIndex)){
1117 return; // can't calc a hidden column
1120 var cid = this.cm.getColumnId(colIndex);
1121 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
1122 if(this.grid.autoSizeHeaders){
1123 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
1126 var newWidth = this.calcColumnWidth(colIndex);
1127 this.cm.setColumnWidth(colIndex,
1128 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
1130 this.grid.fireEvent("columnresize", colIndex, newWidth);
1135 * Autofits all columns to their content and then expands to fit any extra space in the grid
1137 autoSizeColumns : function(){
1138 var cm = this.grid.colModel;
1139 var colCount = cm.getColumnCount();
1140 for(var i = 0; i < colCount; i++){
1141 this.autoSizeColumn(i, true, true);
1143 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
1146 this.updateColumns();
1152 * Autofits all columns to the grid's width proportionate with their current size
1153 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
1155 fitColumns : function(reserveScrollSpace){
1156 var cm = this.grid.colModel;
1157 var colCount = cm.getColumnCount();
1161 for (i = 0; i < colCount; i++){
1162 if(!cm.isHidden(i) && !cm.isFixed(i)){
1163 w = cm.getColumnWidth(i);
1169 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
1170 if(reserveScrollSpace){
1173 var frac = (avail - cm.getTotalWidth())/width;
1174 while (cols.length){
1177 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
1179 this.updateColumns();
1183 onRowSelect : function(rowIndex){
1184 var row = this.getRowComposite(rowIndex);
1185 row.addClass("x-grid-row-selected");
1188 onRowDeselect : function(rowIndex){
1189 var row = this.getRowComposite(rowIndex);
1190 row.removeClass("x-grid-row-selected");
1193 onCellSelect : function(row, col){
1194 var cell = this.getCell(row, col);
1196 Roo.fly(cell).addClass("x-grid-cell-selected");
1200 onCellDeselect : function(row, col){
1201 var cell = this.getCell(row, col);
1203 Roo.fly(cell).removeClass("x-grid-cell-selected");
1207 updateHeaderSortState : function(){
1209 // sort state can be single { field: xxx, direction : yyy}
1210 // or { xxx=>ASC , yyy : DESC ..... }
1213 if (!this.ds.multiSort) {
1214 var state = this.ds.getSortState();
1218 mstate[state.field] = state.direction;
1219 // FIXME... - this is not used here.. but might be elsewhere..
1220 this.sortState = state;
1223 mstate = this.ds.sortToggle;
1225 //remove existing sort classes..
1227 var sc = this.sortClasses;
1228 var hds = this.el.select(this.headerSelector).removeClass(sc);
1230 for(var f in mstate) {
1232 var sortColumn = this.cm.findColumnIndex(f);
1234 if(sortColumn != -1){
1235 var sortDir = mstate[f];
1236 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
1245 handleHeaderClick : function(g, index,e){
1247 Roo.log("header click");
1250 // touch events on header are handled by context
1251 this.handleHdCtx(g,index,e);
1256 if(this.headersDisabled){
1259 var dm = g.dataSource, cm = g.colModel;
1260 if(!cm.isSortable(index)){
1266 // update the sortOrder
1268 for(var i = 0; i < cm.config.length; i++ ) {
1270 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
1271 continue; // dont' bother, it's not in sort list or being set.
1274 so.push(cm.config[i].dataIndex);
1280 dm.sort(cm.getDataIndex(index));
1284 destroy : function(){
1286 this.colMenu.removeAll();
1287 Roo.menu.MenuMgr.unregister(this.colMenu);
1288 this.colMenu.getEl().remove();
1289 delete this.colMenu;
1292 this.hmenu.removeAll();
1293 Roo.menu.MenuMgr.unregister(this.hmenu);
1294 this.hmenu.getEl().remove();
1297 if(this.grid.enableColumnMove){
1298 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1301 if(!dds[dd].config.isTarget && dds[dd].dragElId){
1302 var elid = dds[dd].dragElId;
1304 Roo.get(elid).remove();
1305 } else if(dds[dd].config.isTarget){
1306 dds[dd].proxyTop.remove();
1307 dds[dd].proxyBottom.remove();
1310 if(Roo.dd.DDM.locationCache[dd]){
1311 delete Roo.dd.DDM.locationCache[dd];
1314 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1317 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
1318 this.bind(null, null);
1319 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
1322 handleLockChange : function(){
1326 onDenyColumnLock : function(){
1330 onDenyColumnHide : function(){
1334 handleHdMenuClick : function(item){
1335 var index = this.hdCtxIndex;
1336 var cm = this.cm, ds = this.ds;
1339 ds.sort(cm.getDataIndex(index), "ASC");
1342 ds.sort(cm.getDataIndex(index), "DESC");
1345 var lc = cm.getLockedCount();
1346 if(cm.getColumnCount(true) <= lc+1){
1347 this.onDenyColumnLock();
1351 cm.setLocked(index, true, true);
1352 cm.moveColumn(index, lc);
1353 this.grid.fireEvent("columnmove", index, lc);
1355 cm.setLocked(index, true);
1359 var lc = cm.getLockedCount();
1360 if((lc-1) != index){
1361 cm.setLocked(index, false, true);
1362 cm.moveColumn(index, lc-1);
1363 this.grid.fireEvent("columnmove", index, lc-1);
1365 cm.setLocked(index, false);
1368 case 'wider': // used to expand cols on touch..
1370 var cw = cm.getColumnWidth(index);
1371 cw += (item.id == 'wider' ? 1 : -1) * 50;
1372 cw = Math.max(0, cw);
1373 cw = Math.min(cw,4000);
1374 cm.setColumnWidth(index, cw);
1378 index = cm.getIndexById(item.id.substr(4));
1380 if(item.checked && cm.getColumnCount(true) <= 1){
1381 this.onDenyColumnHide();
1384 cm.setHidden(index, item.checked);
1390 beforeColMenuShow : function(){
1391 var cm = this.cm, colCount = cm.getColumnCount();
1392 this.colMenu.removeAll();
1395 for(var i = 0; i < colCount; i++){
1397 id: "col-"+cm.getColumnId(i),
1398 text: cm.getColumnHeader(i),
1399 checked: !cm.isHidden(i),
1404 if (this.grid.sortColMenu) {
1405 items.sort(function(a,b) {
1406 if (a.text == b.text) {
1409 return a.text.toUpperCase() > b.text.toUpperCase() ? 1 : -1;
1413 for(var i = 0; i < colCount; i++){
1414 this.colMenu.add(new Roo.menu.CheckItem(items[i]));
1418 handleHdCtx : function(g, index, e){
1420 var hd = this.getHeaderCell(index);
1421 this.hdCtxIndex = index;
1422 var ms = this.hmenu.items, cm = this.cm;
1423 ms.get("asc").setDisabled(!cm.isSortable(index));
1424 ms.get("desc").setDisabled(!cm.isSortable(index));
1425 if(this.grid.enableColLock !== false){
1426 ms.get("lock").setDisabled(cm.isLocked(index));
1427 ms.get("unlock").setDisabled(!cm.isLocked(index));
1429 this.hmenu.show(hd, "tl-bl");
1432 handleHdOver : function(e){
1433 var hd = this.findHeaderCell(e.getTarget());
1434 if(hd && !this.headersDisabled){
1435 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
1436 this.fly(hd).addClass("x-grid-hd-over");
1441 handleHdOut : function(e){
1442 var hd = this.findHeaderCell(e.getTarget());
1444 this.fly(hd).removeClass("x-grid-hd-over");
1448 handleSplitDblClick : function(e, t){
1449 var i = this.getCellIndex(t);
1450 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
1451 this.autoSizeColumn(i, true);
1456 render : function(){
1459 var colCount = cm.getColumnCount();
1461 if(this.grid.monitorWindowResize === true){
1462 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
1464 var header = this.renderHeaders();
1465 var body = this.templates.body.apply({rows:""});
1466 var html = this.templates.master.apply({
1469 lockedHeader: header[0],
1473 //this.updateColumns();
1475 this.grid.getGridEl().dom.innerHTML = html;
1477 this.initElements();
1479 // a kludge to fix the random scolling effect in webkit
1480 this.el.on("scroll", function() {
1481 this.el.dom.scrollTop=0; // hopefully not recursive..
1484 this.scroller.on("scroll", this.handleScroll, this);
1485 this.lockedBody.on("mousewheel", this.handleWheel, this);
1486 this.mainBody.on("mousewheel", this.handleWheel, this);
1488 this.mainHd.on("mouseover", this.handleHdOver, this);
1489 this.mainHd.on("mouseout", this.handleHdOut, this);
1490 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
1491 {delegate: "."+this.splitClass});
1493 this.lockedHd.on("mouseover", this.handleHdOver, this);
1494 this.lockedHd.on("mouseout", this.handleHdOut, this);
1495 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
1496 {delegate: "."+this.splitClass});
1498 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
1499 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1502 this.updateSplitters();
1504 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
1505 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1506 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1509 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
1510 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
1512 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
1513 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
1515 if(this.grid.enableColLock !== false){
1517 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
1518 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
1523 {id:"wider", text: this.columnsWiderText},
1524 {id:"narrow", text: this.columnsNarrowText }
1530 if(this.grid.enableColumnHide !== false){
1532 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
1533 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
1534 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
1537 {id:"columns", text: this.columnsText, menu: this.colMenu}
1540 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
1542 this.grid.on("headercontextmenu", this.handleHdCtx, this);
1545 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
1546 this.dd = new Roo.grid.GridDragZone(this.grid, {
1547 ddGroup : this.grid.ddGroup || 'GridDD'
1553 for(var i = 0; i < colCount; i++){
1557 if(cm.config[i].align){
1558 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
1559 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
1563 this.updateHeaderSortState();
1565 this.beforeInitialResize();
1568 // two part rendering gives faster view to the user
1569 this.renderPhase2.defer(1, this);
1572 renderPhase2 : function(){
1573 // render the rows now
1575 if(this.grid.autoSizeColumns){
1576 this.autoSizeColumns();
1580 beforeInitialResize : function(){
1584 onColumnSplitterMoved : function(i, w){
1585 this.userResized = true;
1586 var cm = this.grid.colModel;
1587 cm.setColumnWidth(i, w, true);
1588 var cid = cm.getColumnId(i);
1589 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1590 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1591 this.updateSplitters();
1593 this.grid.fireEvent("columnresize", i, w);
1596 syncRowHeights : function(startIndex, endIndex){
1597 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
1598 startIndex = startIndex || 0;
1599 var mrows = this.getBodyTable().rows;
1600 var lrows = this.getLockedTable().rows;
1601 var len = mrows.length-1;
1602 endIndex = Math.min(endIndex || len, len);
1603 for(var i = startIndex; i <= endIndex; i++){
1604 var m = mrows[i], l = lrows[i];
1605 var h = Math.max(m.offsetHeight, l.offsetHeight);
1606 m.style.height = l.style.height = h + "px";
1611 layout : function(initialRender, is2ndPass)
1614 var auto = g.autoHeight;
1615 var scrollOffset = 16;
1616 var c = g.getGridEl(), cm = this.cm,
1617 expandCol = g.autoExpandColumn,
1621 if(!c.dom.offsetWidth){ // display:none?
1623 this.lockedWrap.show();
1624 this.mainWrap.show();
1629 var hasLock = this.cm.isLocked(0);
1631 var tbh = this.headerPanel.getHeight();
1632 var bbh = this.footerPanel.getHeight();
1635 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
1636 var newHeight = ch + c.getBorderWidth("tb");
1638 newHeight = Math.min(g.maxHeight, newHeight);
1640 c.setHeight(newHeight);
1644 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
1647 var s = this.scroller;
1649 var csize = c.getSize(true);
1651 this.el.setSize(csize.width, csize.height);
1653 this.headerPanel.setWidth(csize.width);
1654 this.footerPanel.setWidth(csize.width);
1656 var hdHeight = this.mainHd.getHeight();
1657 var vw = csize.width;
1658 var vh = csize.height - (tbh + bbh);
1662 var bt = this.getBodyTable();
1664 if(cm.getLockedCount() == cm.config.length){
1665 bt = this.getLockedTable();
1668 var ltWidth = hasLock ?
1669 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
1671 var scrollHeight = bt.offsetHeight;
1672 var scrollWidth = ltWidth + bt.offsetWidth;
1673 var vscroll = false, hscroll = false;
1675 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
1677 var lw = this.lockedWrap, mw = this.mainWrap;
1678 var lb = this.lockedBody, mb = this.mainBody;
1680 setTimeout(function(){
1681 var t = s.dom.offsetTop;
1682 var w = s.dom.clientWidth,
1683 h = s.dom.clientHeight;
1686 lw.setSize(ltWidth, h);
1688 mw.setLeftTop(ltWidth, t);
1689 mw.setSize(w-ltWidth, h);
1691 lb.setHeight(h-hdHeight);
1692 mb.setHeight(h-hdHeight);
1694 if(is2ndPass !== true && !gv.userResized && expandCol){
1695 // high speed resize without full column calculation
1697 var ci = cm.getIndexById(expandCol);
1699 ci = cm.findColumnIndex(expandCol);
1701 ci = Math.max(0, ci); // make sure it's got at least the first col.
1702 var expandId = cm.getColumnId(ci);
1703 var tw = cm.getTotalWidth(false);
1704 var currentWidth = cm.getColumnWidth(ci);
1705 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
1706 if(currentWidth != cw){
1707 cm.setColumnWidth(ci, cw, true);
1708 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1709 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1710 gv.updateSplitters();
1711 gv.layout(false, true);
1723 onWindowResize : function(){
1724 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
1730 appendFooter : function(parentEl){
1734 sortAscText : "Sort Ascending",
1735 sortDescText : "Sort Descending",
1736 lockText : "Lock Column",
1737 unlockText : "Unlock Column",
1738 columnsText : "Columns",
1740 columnsWiderText : "Wider",
1741 columnsNarrowText : "Thinner"
1745 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
1746 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
1747 this.proxy.el.addClass('x-grid3-col-dd');
1750 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
1751 handleMouseDown : function(e){
1755 callHandleMouseDown : function(e){
1756 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);