/*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 2.8.2r1
*/
/**
* Mechanism to execute a series of callbacks in a non-blocking queue. Each callback is executed via setTimout unless configured with a negative timeout, in which case it is run in blocking mode in the same execution thread as the previous callback. Callbacks can be function references or object literals with the following keys:
*
* method
- {Function} REQUIRED the callback function.
* scope
- {Object} the scope from which to execute the callback. Default is the global window scope.
* argument
- {Array} parameters to be passed to method as individual arguments.
* timeout
- {number} millisecond delay to wait after previous callback completion before executing this callback. Negative values cause immediate blocking execution. Default 0.
* until
- {Function} boolean function executed before each iteration. Return true to indicate completion and proceed to the next callback.
* iterations
- {Number} number of times to execute the callback before proceeding to the next callback in the chain. Incompatible with until
.
*
*
* @namespace YAHOO.util
* @class Chain
* @constructor
* @param callback* {Function|Object} Any number of callbacks to initialize the queue
*/
YAHOO.util.Chain = function () {
/**
* The callback queue
* @property q
* @type {Array}
* @private
*/
this.q = [].slice.call(arguments);
/**
* Event fired when the callback queue is emptied via execution (not via
* a call to chain.stop().
* @event end
*/
this.createEvent('end');
};
YAHOO.util.Chain.prototype = {
/**
* Timeout id used to pause or stop execution and indicate the execution state of the Chain. 0 indicates paused or stopped, -1 indicates blocking execution, and any positive number indicates non-blocking execution.
* @property id
* @type {number}
* @private
*/
id : 0,
/**
* Begin executing the chain, or resume execution from the last paused position.
* @method run
* @return {Chain} the Chain instance
*/
run : function () {
// Grab the first callback in the queue
var c = this.q[0],
fn;
// If there is no callback in the queue or the Chain is currently
// in an execution mode, return
if (!c) {
this.fireEvent('end');
return this;
} else if (this.id) {
return this;
}
fn = c.method || c;
if (typeof fn === 'function') {
var o = c.scope || {},
args = c.argument || [],
ms = c.timeout || 0,
me = this;
if (!(args instanceof Array)) {
args = [args];
}
// Execute immediately if the callback timeout is negative.
if (ms < 0) {
this.id = ms;
if (c.until) {
for (;!c.until();) {
// Execute the callback from scope, with argument
fn.apply(o,args);
}
} else if (c.iterations) {
for (;c.iterations-- > 0;) {
fn.apply(o,args);
}
} else {
fn.apply(o,args);
}
this.q.shift();
this.id = 0;
return this.run();
} else {
// If the until condition is set, check if we're done
if (c.until) {
if (c.until()) {
// Shift this callback from the queue and execute the next
// callback
this.q.shift();
return this.run();
}
// Otherwise if either iterations is not set or we're
// executing the last iteration, shift callback from the queue
} else if (!c.iterations || !--c.iterations) {
this.q.shift();
}
// Otherwise set to execute after the configured timeout
this.id = setTimeout(function () {
// Execute the callback from scope, with argument
fn.apply(o,args);
// Check if the Chain was not paused from inside the callback
if (me.id) {
// Indicate ready to run state
me.id = 0;
// Start the fun all over again
me.run();
}
},ms);
}
}
return this;
},
/**
* Add a callback to the end of the queue
* @method add
* @param c {Function|Object} the callback function ref or object literal
* @return {Chain} the Chain instance
*/
add : function (c) {
this.q.push(c);
return this;
},
/**
* Pause the execution of the Chain after the current execution of the
* current callback completes. If called interstitially, clears the
* timeout for the pending callback. Paused Chains can be restarted with
* chain.run()
* @method pause
* @return {Chain} the Chain instance
*/
pause: function () {
// Conditional added for Caja compatibility
if (this.id > 0) {
clearTimeout(this.id);
}
this.id = 0;
return this;
},
/**
* Stop and clear the Chain's queue after the current execution of the
* current callback completes.
* @method stop
* @return {Chain} the Chain instance
*/
stop : function () {
this.pause();
this.q = [];
return this;
}
};
YAHOO.lang.augmentProto(YAHOO.util.Chain,YAHOO.util.EventProvider);
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* The ColumnSet class defines and manages a DataTable's Columns,
* including nested hierarchies and access to individual Column instances.
*
* @namespace YAHOO.widget
* @class ColumnSet
* @uses YAHOO.util.EventProvider
* @constructor
* @param aDefinitions {Object[]} Array of object literals that define cells in
* the THEAD.
*/
YAHOO.widget.ColumnSet = function(aDefinitions) {
this._sId = "yui-cs" + YAHOO.widget.ColumnSet._nCount;
// First clone the defs
aDefinitions = YAHOO.widget.DataTable._cloneObject(aDefinitions);
this._init(aDefinitions);
YAHOO.widget.ColumnSet._nCount++;
};
/////////////////////////////////////////////////////////////////////////////
//
// Private member variables
//
/////////////////////////////////////////////////////////////////////////////
/**
* Internal class variable to index multiple ColumnSet instances.
*
* @property ColumnSet._nCount
* @type Number
* @private
* @static
*/
YAHOO.widget.ColumnSet._nCount = 0;
YAHOO.widget.ColumnSet.prototype = {
/**
* Unique instance name.
*
* @property _sId
* @type String
* @private
*/
_sId : null,
/**
* Array of object literal Column definitions passed to the constructor.
*
* @property _aDefinitions
* @type Object[]
* @private
*/
_aDefinitions : null,
/////////////////////////////////////////////////////////////////////////////
//
// Public member variables
//
/////////////////////////////////////////////////////////////////////////////
/**
* Top-down tree representation of Column hierarchy.
*
* @property tree
* @type YAHOO.widget.Column[]
*/
tree : null,
/**
* Flattened representation of all Columns.
*
* @property flat
* @type YAHOO.widget.Column[]
* @default []
*/
flat : null,
/**
* Array of Columns that map one-to-one to a table column.
*
* @property keys
* @type YAHOO.widget.Column[]
* @default []
*/
keys : null,
/**
* ID index of nested parent hierarchies for HEADERS accessibility attribute.
*
* @property headers
* @type String[]
* @default []
*/
headers : null,
/////////////////////////////////////////////////////////////////////////////
//
// Private methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Initializes ColumnSet instance with data from Column definitions.
*
* @method _init
* @param aDefinitions {Object[]} Array of object literals that define cells in
* the THEAD .
* @private
*/
_init : function(aDefinitions) {
// DOM tree representation of all Columns
var tree = [];
// Flat representation of all Columns
var flat = [];
// Flat representation of only Columns that are meant to display data
var keys = [];
// Array of HEADERS attribute values for all keys in the "keys" array
var headers = [];
// Tracks current node list depth being tracked
var nodeDepth = -1;
// Internal recursive function to define Column instances
var parseColumns = function(nodeList, parent) {
// One level down
nodeDepth++;
// Create corresponding tree node if not already there for this depth
if(!tree[nodeDepth]) {
tree[nodeDepth] = [];
}
// Parse each node at this depth for attributes and any children
for(var j=0; j maxRowDepth) {
maxRowDepth = tmpRowDepth;
}
}
}
};
// Count max row depth for each row
for(var m=0; m-1; i--) {
if(allColumns[i]._sId === column) {
return allColumns[i];
}
}
}
return null;
},
/**
* Returns Column instance with given key or ColumnSet key index.
*
* @method getColumn
* @param column {String | Number} Column key or ColumnSet key index.
* @return {YAHOO.widget.Column} Column instance.
*/
getColumn : function(column) {
if(YAHOO.lang.isNumber(column) && this.keys[column]) {
return this.keys[column];
}
else if(YAHOO.lang.isString(column)) {
var allColumns = this.flat;
var aColumns = [];
for(var i=0; i 1) {
return aColumns;
}
}
return null;
},
/**
* Public accessor returns array of given Column's desendants (if any), including itself.
*
* @method getDescendants
* @parem {YAHOO.widget.Column} Column instance.
* @return {Array} Array including the Column itself and all descendants (if any).
*/
getDescendants : function(oColumn) {
var oSelf = this;
var allDescendants = [];
var i;
// Recursive function to loop thru all children
var parse = function(oParent) {
allDescendants.push(oParent);
// This Column has children
if(oParent.children) {
for(i=0; i b) {
return (desc) ? -1 : 1;
}
else {
return 0;
}
}
};
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* ColumnDD subclasses DragDrop to support rearrangeable Columns.
*
* @namespace YAHOO.util
* @class ColumnDD
* @extends YAHOO.util.DDProxy
* @constructor
* @param oDataTable {YAHOO.widget.DataTable} DataTable instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param elTh {HTMLElement} TH element reference.
* @param elTarget {HTMLElement} Drag target element.
*/
YAHOO.widget.ColumnDD = function(oDataTable, oColumn, elTh, elTarget) {
if(oDataTable && oColumn && elTh && elTarget) {
this.datatable = oDataTable;
this.table = oDataTable.getTableEl();
this.column = oColumn;
this.headCell = elTh;
this.pointer = elTarget;
this.newIndex = null;
this.init(elTh);
this.initFrame(); // Needed for DDProxy
this.invalidHandleTypes = {};
// Set top/bottom padding to account for children of nested columns
this.setPadding(10, 0, (this.datatable.getTheadEl().offsetHeight + 10) , 0);
YAHOO.util.Event.on(window, 'resize', function() {
this.initConstraints();
}, this, true);
}
else {
}
};
if(YAHOO.util.DDProxy) {
YAHOO.extend(YAHOO.widget.ColumnDD, YAHOO.util.DDProxy, {
initConstraints: function() {
//Get the top, right, bottom and left positions
var region = YAHOO.util.Dom.getRegion(this.table),
//Get the element we are working on
el = this.getEl(),
//Get the xy position of it
xy = YAHOO.util.Dom.getXY(el),
//Get the width and height
width = parseInt(YAHOO.util.Dom.getStyle(el, 'width'), 10),
height = parseInt(YAHOO.util.Dom.getStyle(el, 'height'), 10),
//Set left to x minus left
left = ((xy[0] - region.left) + 15), //Buffer of 15px
//Set right to right minus x minus width
right = ((region.right - xy[0] - width) + 15);
//Set the constraints based on the above calculations
this.setXConstraint(left, right);
this.setYConstraint(10, 10);
},
_resizeProxy: function() {
YAHOO.widget.ColumnDD.superclass._resizeProxy.apply(this, arguments);
var dragEl = this.getDragEl(),
el = this.getEl();
YAHOO.util.Dom.setStyle(this.pointer, 'height', (this.table.parentNode.offsetHeight + 10) + 'px');
YAHOO.util.Dom.setStyle(this.pointer, 'display', 'block');
var xy = YAHOO.util.Dom.getXY(el);
YAHOO.util.Dom.setXY(this.pointer, [xy[0], (xy[1] - 5)]);
YAHOO.util.Dom.setStyle(dragEl, 'height', this.datatable.getContainerEl().offsetHeight + "px");
YAHOO.util.Dom.setStyle(dragEl, 'width', (parseInt(YAHOO.util.Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
YAHOO.util.Dom.setXY(this.dragEl, xy);
},
onMouseDown: function() {
this.initConstraints();
this.resetConstraints();
},
clickValidator: function(e) {
if(!this.column.hidden) {
var target = YAHOO.util.Event.getTarget(e);
return ( this.isValidHandleChild(target) &&
(this.id == this.handleElId ||
this.DDM.handleWasClicked(target, this.id)) );
}
},
onDragOver: function(ev, id) {
// Validate target as a Column
var target = this.datatable.getColumn(id);
if(target) {
// Validate target as a top-level parent
var targetIndex = target.getTreeIndex();
while((targetIndex === null) && target.getParent()) {
target = target.getParent();
targetIndex = target.getTreeIndex();
}
if(targetIndex !== null) {
// Are we placing to left or right of target?
var elTarget = target.getThEl();
var newIndex = targetIndex;
var mouseX = YAHOO.util.Event.getPageX(ev),
targetX = YAHOO.util.Dom.getX(elTarget),
midX = targetX + ((YAHOO.util.Dom.get(elTarget).offsetWidth)/2),
currentIndex = this.column.getTreeIndex();
if (mouseX < midX) {
YAHOO.util.Dom.setX(this.pointer, targetX);
} else {
var targetWidth = parseInt(elTarget.offsetWidth, 10);
YAHOO.util.Dom.setX(this.pointer, (targetX + targetWidth));
newIndex++;
}
if (targetIndex > currentIndex) {
newIndex--;
}
if(newIndex < 0) {
newIndex = 0;
}
else if(newIndex > this.datatable.getColumnSet().tree[0].length) {
newIndex = this.datatable.getColumnSet().tree[0].length;
}
this.newIndex = newIndex;
}
}
},
onDragDrop: function() {
this.datatable.reorderColumn(this.column, this.newIndex);
},
endDrag: function() {
this.newIndex = null;
YAHOO.util.Dom.setStyle(this.pointer, 'display', 'none');
}
});
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* ColumnResizer subclasses DragDrop to support resizeable Columns.
*
* @namespace YAHOO.util
* @class ColumnResizer
* @extends YAHOO.util.DDProxy
* @constructor
* @param oDataTable {YAHOO.widget.DataTable} DataTable instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param elTh {HTMLElement} TH element reference.
* @param sHandleElId {String} DOM ID of the handle element that causes the resize.
* @param elProxy {HTMLElement} Resizer proxy element.
*/
YAHOO.util.ColumnResizer = function(oDataTable, oColumn, elTh, sHandleId, elProxy) {
if(oDataTable && oColumn && elTh && sHandleId) {
this.datatable = oDataTable;
this.column = oColumn;
this.headCell = elTh;
this.headCellLiner = oColumn.getThLinerEl();
this.resizerLiner = elTh.firstChild;
this.init(sHandleId, sHandleId, {dragOnly:true, dragElId: elProxy.id});
this.initFrame(); // Needed for proxy
this.resetResizerEl(); // Needed when rowspan > 0
// Set right padding for bug 1858462
this.setPadding(0, 1, 0, 0);
}
else {
}
};
if(YAHOO.util.DD) {
YAHOO.extend(YAHOO.util.ColumnResizer, YAHOO.util.DDProxy, {
/////////////////////////////////////////////////////////////////////////////
//
// Public methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Resets resizer element.
*
* @method resetResizerEl
*/
resetResizerEl : function() {
var resizerStyle = YAHOO.util.Dom.get(this.handleElId).style;
resizerStyle.left = "auto";
resizerStyle.right = 0;
resizerStyle.top = "auto";
resizerStyle.bottom = 0;
resizerStyle.height = this.headCell.offsetHeight+"px";
},
/////////////////////////////////////////////////////////////////////////////
//
// Public DOM event handlers
//
/////////////////////////////////////////////////////////////////////////////
/**
* Handles mouseup events on the Column resizer.
*
* @method onMouseUp
* @param e {string} The mouseup event
*/
onMouseUp : function(e) {
// Reset height of all resizer els in case TH's have changed height
var allKeys = this.datatable.getColumnSet().keys,
col;
for(var i=0, len=allKeys.length; i YAHOO.util.Dom.getX(this.headCellLiner)) {
var offsetX = newX - this.startX;
var newWidth = this.startWidth + offsetX - this.nLinerPadding;
if(newWidth > 0) {
this.datatable.setColumnWidth(this.column, newWidth);
}
}
}
});
}
/////////////////////////////////////////////////////////////////////////////
//
// Deprecated
//
/////////////////////////////////////////////////////////////////////////////
/**
* @property editorOptions
* @deprecated Pass configs directly to CellEditor constructor.
*/
(function () {
var lang = YAHOO.lang,
util = YAHOO.util,
widget = YAHOO.widget,
Dom = util.Dom,
Ev = util.Event,
DT = widget.DataTable;
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* A RecordSet defines and manages a set of Records.
*
* @namespace YAHOO.widget
* @class RecordSet
* @param data {Object || Object[]} An object literal or an array of data.
* @constructor
*/
YAHOO.widget.RecordSet = function(data) {
// Internal variables
this._sId = "yui-rs" + widget.RecordSet._nCount;
widget.RecordSet._nCount++;
this._records = [];
//this._length = 0;
if(data) {
if(lang.isArray(data)) {
this.addRecords(data);
}
else if(lang.isObject(data)) {
this.addRecord(data);
}
}
};
var RS = widget.RecordSet;
/**
* Internal class variable to name multiple Recordset instances.
*
* @property RecordSet._nCount
* @type Number
* @private
* @static
*/
RS._nCount = 0;
RS.prototype = {
/////////////////////////////////////////////////////////////////////////////
//
// Private member variables
//
/////////////////////////////////////////////////////////////////////////////
/**
* Unique String identifier assigned at instantiation.
*
* @property _sId
* @type String
* @private
*/
_sId : null,
/**
* Internal counter of how many Records are in the RecordSet.
*
* @property _length
* @type Number
* @private
* @deprecated No longer used
*/
//_length : null,
/////////////////////////////////////////////////////////////////////////////
//
// Private methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Adds one Record to the RecordSet at the given index. If index is null,
* then adds the Record to the end of the RecordSet.
*
* @method _addRecord
* @param oData {Object} An object literal of data.
* @param index {Number} (optional) Position index.
* @return {YAHOO.widget.Record} A Record instance.
* @private
*/
_addRecord : function(oData, index) {
var oRecord = new YAHOO.widget.Record(oData);
if(YAHOO.lang.isNumber(index) && (index > -1)) {
this._records.splice(index,0,oRecord);
}
else {
//index = this.getLength();
//this._records[index] = oRecord;
this._records[this._records.length] = oRecord;
}
//this._length++;
return oRecord;
},
/**
* Sets/replaces one Record to the RecordSet at the given index. Existing
* Records with higher indexes are not shifted. If no index specified, the
* Record is added to the end of the RecordSet.
*
* @method _setRecord
* @param oData {Object} An object literal of data.
* @param index {Number} (optional) Position index.
* @return {YAHOO.widget.Record} A Record instance.
* @private
*/
_setRecord : function(oData, index) {
if (!lang.isNumber(index) || index < 0) {
index = this._records.length;
}
return (this._records[index] = new widget.Record(oData));
/*
if(lang.isNumber(index) && (index > -1)) {
this._records[index] = oRecord;
if((index+1) > this.getLength()) {
this._length = index+1;
}
}
else {
this._records[this.getLength()] = oRecord;
this._length++;
}
return oRecord;
*/
},
/**
* Deletes Records from the RecordSet at the given index. If range is null,
* then only one Record is deleted.
*
* @method _deleteRecord
* @param index {Number} Position index.
* @param range {Number} (optional) How many Records to delete
* @private
*/
_deleteRecord : function(index, range) {
if(!lang.isNumber(range) || (range < 0)) {
range = 1;
}
this._records.splice(index, range);
//this._length = this._length - range;
},
/////////////////////////////////////////////////////////////////////////////
//
// Public methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Returns unique name of the RecordSet instance.
*
* @method getId
* @return {String} Unique name of the RecordSet instance.
*/
getId : function() {
return this._sId;
},
/**
* Public accessor to the unique name of the RecordSet instance.
*
* @method toString
* @return {String} Unique name of the RecordSet instance.
*/
toString : function() {
return "RecordSet instance " + this._sId;
},
/**
* Returns the number of Records held in the RecordSet.
*
* @method getLength
* @return {Number} Number of records in the RecordSet.
*/
getLength : function() {
//return this._length;
return this._records.length;
},
/**
* Returns Record by ID or RecordSet position index.
*
* @method getRecord
* @param record {YAHOO.widget.Record | Number | String} Record instance,
* RecordSet position index, or Record ID.
* @return {YAHOO.widget.Record} Record object.
*/
getRecord : function(record) {
var i;
if(record instanceof widget.Record) {
for(i=0; i -1) && (record < this.getLength())) {
return this._records[record];
}
}
else if(lang.isString(record)) {
for(i=0; i-1; i--) {
if(this._records[i] && oRecord.getId() === this._records[i].getId()) {
return i;
}
}
}
return null;
},
/**
* Adds one Record to the RecordSet at the given index. If index is null,
* then adds the Record to the end of the RecordSet.
*
* @method addRecord
* @param oData {Object} An object literal of data.
* @param index {Number} (optional) Position index.
* @return {YAHOO.widget.Record} A Record instance.
*/
addRecord : function(oData, index) {
if(lang.isObject(oData)) {
var oRecord = this._addRecord(oData, index);
this.fireEvent("recordAddEvent",{record:oRecord,data:oData});
return oRecord;
}
else {
return null;
}
},
/**
* Adds multiple Records at once to the RecordSet at the given index with the
* given object literal data. If index is null, then the new Records are
* added to the end of the RecordSet.
*
* @method addRecords
* @param aData {Object[]} An object literal data or an array of data object literals.
* @param index {Number} (optional) Position index.
* @return {YAHOO.widget.Record[]} An array of Record instances.
*/
addRecords : function(aData, index) {
if(lang.isArray(aData)) {
var newRecords = [],
idx,i,len;
index = lang.isNumber(index) ? index : this._records.length;
idx = index;
// Can't go backwards bc we need to preserve order
for(i=0,len=aData.length; i 1 ? added : added[0];
},
/**
* Updates given Record with given data.
*
* @method updateRecord
* @param record {YAHOO.widget.Record | Number | String} A Record instance,
* a RecordSet position index, or a Record ID.
* @param oData {Object} Object literal of new data.
* @return {YAHOO.widget.Record} Updated Record, or null.
*/
updateRecord : function(record, oData) {
var oRecord = this.getRecord(record);
if(oRecord && lang.isObject(oData)) {
// Copy data from the Record for the event that gets fired later
var oldData = {};
for(var key in oRecord._oData) {
if(lang.hasOwnProperty(oRecord._oData, key)) {
oldData[key] = oRecord._oData[key];
}
}
oRecord._oData = oData;
this.fireEvent("recordUpdateEvent",{record:oRecord,newData:oData,oldData:oldData});
return oRecord;
}
else {
return null;
}
},
/**
* @method updateKey
* @deprecated Use updateRecordValue
*/
updateKey : function(record, sKey, oData) {
this.updateRecordValue(record, sKey, oData);
},
/**
* Sets given Record at given key to given data.
*
* @method updateRecordValue
* @param record {YAHOO.widget.Record | Number | String} A Record instance,
* a RecordSet position index, or a Record ID.
* @param sKey {String} Key name.
* @param oData {Object} New data.
*/
updateRecordValue : function(record, sKey, oData) {
var oRecord = this.getRecord(record);
if(oRecord) {
var oldData = null;
var keyValue = oRecord._oData[sKey];
// Copy data from the Record for the event that gets fired later
if(keyValue && lang.isObject(keyValue)) {
oldData = {};
for(var key in keyValue) {
if(lang.hasOwnProperty(keyValue, key)) {
oldData[key] = keyValue[key];
}
}
}
// Copy by value
else {
oldData = keyValue;
}
oRecord._oData[sKey] = oData;
this.fireEvent("keyUpdateEvent",{record:oRecord,key:sKey,newData:oData,oldData:oldData});
this.fireEvent("recordValueUpdateEvent",{record:oRecord,key:sKey,newData:oData,oldData:oldData});
}
else {
}
},
/**
* Replaces all Records in RecordSet with new object literal data.
*
* @method replaceRecords
* @param data {Object || Object[]} An object literal of data or an array of
* data object literals.
* @return {YAHOO.widget.Record || YAHOO.widget.Record[]} A Record instance or
* an array of Records.
*/
replaceRecords : function(data) {
this.reset();
return this.addRecords(data);
},
/**
* Sorts all Records by given function. Records keep their unique IDs but will
* have new RecordSet position indexes.
*
* @method sortRecords
* @param fnSort {Function} Reference to a sort function.
* @param desc {Boolean} True if sort direction is descending, false if sort
* direction is ascending.
* @param field {String} The field to sort by, from sortOptions.field
* @return {YAHOO.widget.Record[]} Sorted array of Records.
*/
sortRecords : function(fnSort, desc, field) {
return this._records.sort(function(a, b) {return fnSort(a, b, desc, field);});
},
/**
* Reverses all Records, so ["one", "two", "three"] becomes ["three", "two", "one"].
*
* @method reverseRecords
* @return {YAHOO.widget.Record[]} Reverse-sorted array of Records.
*/
reverseRecords : function() {
return this._records.reverse();
},
/**
* Removes the Record at the given position index from the RecordSet. If a range
* is also provided, removes that many Records, starting from the index. Length
* of RecordSet is correspondingly shortened.
*
* @method deleteRecord
* @param index {Number} Record's RecordSet position index.
* @param range {Number} (optional) How many Records to delete.
* @return {Object} A copy of the data held by the deleted Record.
*/
deleteRecord : function(index) {
if(lang.isNumber(index) && (index > -1) && (index < this.getLength())) {
// Copy data from the Record for the event that gets fired later
var oData = widget.DataTable._cloneObject(this.getRecord(index).getData());
this._deleteRecord(index);
this.fireEvent("recordDeleteEvent",{data:oData,index:index});
return oData;
}
else {
return null;
}
},
/**
* Removes the Record at the given position index from the RecordSet. If a range
* is also provided, removes that many Records, starting from the index. Length
* of RecordSet is correspondingly shortened.
*
* @method deleteRecords
* @param index {Number} Record's RecordSet position index.
* @param range {Number} (optional) How many Records to delete.
* @return {Object[]} An array of copies of the data held by the deleted Records.
*/
deleteRecords : function(index, range) {
if(!lang.isNumber(range)) {
range = 1;
}
if(lang.isNumber(index) && (index > -1) && (index < this.getLength())) {
var recordsToDelete = this.getRecords(index, range);
// Copy data from each Record for the event that gets fired later
var deletedData = [];
for(var i=0; i" + sValue + "";
//}
},
/**
* Formats a CHECKBOX element.
*
* @method DataTable.formatCheckbox
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object | Boolean} Data value for the cell. Can be a simple
* Boolean to indicate whether checkbox is checked or not. Can be object literal
* {checked:bBoolean, label:sLabel}. Other forms of oData require a custom
* formatter.
* @static
*/
formatCheckbox : function(el, oRecord, oColumn, oData) {
var bChecked = oData;
bChecked = (bChecked) ? " checked=\"checked\"" : "";
el.innerHTML = " ";
},
/**
* Formats currency. Default unit is USD.
*
* @method DataTable.formatCurrency
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Number} Data value for the cell.
* @static
*/
formatCurrency : function(el, oRecord, oColumn, oData) {
el.innerHTML = util.Number.format(oData, oColumn.currencyOptions || this.get("currencyOptions"));
},
/**
* Formats JavaScript Dates.
*
* @method DataTable.formatDate
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object} Data value for the cell, or null.
* @static
*/
formatDate : function(el, oRecord, oColumn, oData) {
var oConfig = oColumn.dateOptions || this.get("dateOptions");
el.innerHTML = util.Date.format(oData, oConfig, oConfig.locale);
},
/**
* Formats SELECT elements.
*
* @method DataTable.formatDropdown
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object} Data value for the cell, or null.
* @static
*/
formatDropdown : function(el, oRecord, oColumn, oData) {
var selectedValue = (lang.isValue(oData)) ? oData : oRecord.getData(oColumn.field),
options = (lang.isArray(oColumn.dropdownOptions)) ?
oColumn.dropdownOptions : null,
selectEl,
collection = el.getElementsByTagName("select");
// Create the form element only once, so we can attach the onChange listener
if(collection.length === 0) {
// Create SELECT element
selectEl = document.createElement("select");
selectEl.className = DT.CLASS_DROPDOWN;
selectEl = el.appendChild(selectEl);
// Add event listener
Ev.addListener(selectEl,"change",this._onDropdownChange,this);
}
selectEl = collection[0];
// Update the form element
if(selectEl) {
// Clear out previous options
selectEl.innerHTML = "";
// We have options to populate
if(options) {
// Create OPTION elements
for(var i=0; i" + selectedValue + "";
}
}
else {
el.innerHTML = lang.isValue(oData) ? oData : "";
}
},
/**
* Formats emails.
*
* @method DataTable.formatEmail
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object} Data value for the cell, or null.
* @static
*/
formatEmail : function(el, oRecord, oColumn, oData) {
if(lang.isString(oData)) {
el.innerHTML = "" + oData + " ";
}
else {
el.innerHTML = lang.isValue(oData) ? oData : "";
}
},
/**
* Formats links.
*
* @method DataTable.formatLink
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object} Data value for the cell, or null.
* @static
*/
formatLink : function(el, oRecord, oColumn, oData) {
if(lang.isString(oData)) {
el.innerHTML = "" + oData + " ";
}
else {
el.innerHTML = lang.isValue(oData) ? oData : "";
}
},
/**
* Formats numbers.
*
* @method DataTable.formatNumber
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object} Data value for the cell, or null.
* @static
*/
formatNumber : function(el, oRecord, oColumn, oData) {
el.innerHTML = util.Number.format(oData, oColumn.numberOptions || this.get("numberOptions"));
},
/**
* Formats INPUT TYPE=RADIO elements.
*
* @method DataTable.formatRadio
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object} (Optional) Data value for the cell.
* @static
*/
formatRadio : function(el, oRecord, oColumn, oData) {
var bChecked = oData;
bChecked = (bChecked) ? " checked=\"checked\"" : "";
el.innerHTML = " ";
},
/**
* Formats text strings.
*
* @method DataTable.formatText
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object} (Optional) Data value for the cell.
* @static
*/
formatText : function(el, oRecord, oColumn, oData) {
var value = (lang.isValue(oData)) ? oData : "";
//TODO: move to util function
el.innerHTML = value.toString().replace(/&/g, "&").replace(//g, ">");
},
/**
* Formats TEXTAREA elements.
*
* @method DataTable.formatTextarea
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object} (Optional) Data value for the cell.
* @static
*/
formatTextarea : function(el, oRecord, oColumn, oData) {
var value = (lang.isValue(oData)) ? oData : "",
markup = "";
el.innerHTML = markup;
},
/**
* Formats INPUT TYPE=TEXT elements.
*
* @method DataTable.formatTextbox
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object} (Optional) Data value for the cell.
* @static
*/
formatTextbox : function(el, oRecord, oColumn, oData) {
var value = (lang.isValue(oData)) ? oData : "",
markup = " ";
el.innerHTML = markup;
},
/**
* Default cell formatter
*
* @method DataTable.formatDefault
* @param el {HTMLElement} The element to format with markup.
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param oData {Object} (Optional) Data value for the cell.
* @static
*/
formatDefault : function(el, oRecord, oColumn, oData) {
el.innerHTML = oData === undefined ||
oData === null ||
(typeof oData === 'number' && isNaN(oData)) ?
" " : oData.toString();
},
/**
* Validates data value to type Number, doing type conversion as
* necessary. A valid Number value is return, else null is returned
* if input value does not validate.
*
*
* @method DataTable.validateNumber
* @param oData {Object} Data to validate.
* @static
*/
validateNumber : function(oData) {
//Convert to number
var number = oData * 1;
// Validate
if(lang.isNumber(number)) {
return number;
}
else {
return undefined;
}
}
});
// Done in separate step so referenced functions are defined.
/**
* Cell formatting functions.
* @property DataTable.Formatter
* @type Object
* @static
*/
DT.Formatter = {
button : DT.formatButton,
checkbox : DT.formatCheckbox,
currency : DT.formatCurrency,
"date" : DT.formatDate,
dropdown : DT.formatDropdown,
email : DT.formatEmail,
link : DT.formatLink,
"number" : DT.formatNumber,
radio : DT.formatRadio,
text : DT.formatText,
textarea : DT.formatTextarea,
textbox : DT.formatTextbox,
defaultFormatter : DT.formatDefault
};
lang.extend(DT, util.Element, {
/////////////////////////////////////////////////////////////////////////////
//
// Superclass methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Implementation of Element's abstract method. Sets up config values.
*
* @method initAttributes
* @param oConfigs {Object} (Optional) Object literal definition of configuration values.
* @private
*/
initAttributes : function(oConfigs) {
oConfigs = oConfigs || {};
DT.superclass.initAttributes.call(this, oConfigs);
/**
* @attribute summary
* @description Value for the SUMMARY attribute.
* @type String
* @default ""
*/
this.setAttributeConfig("summary", {
value: "",
validator: lang.isString,
method: function(sSummary) {
if(this._elTable) {
this._elTable.summary = sSummary;
}
}
});
/**
* @attribute selectionMode
* @description Specifies row or cell selection mode. Accepts the following strings:
*
* "standard"
* Standard row selection with support for modifier keys to enable
* multiple selections.
*
* "single"
* Row selection with modifier keys disabled to not allow
* multiple selections.
*
* "singlecell"
* Cell selection with modifier keys disabled to not allow
* multiple selections.
*
* "cellblock"
* Cell selection with support for modifier keys to enable multiple
* selections in a block-fashion, like a spreadsheet.
*
* "cellrange"
* Cell selection with support for modifier keys to enable multiple
* selections in a range-fashion, like a calendar.
*
*
* @default "standard"
* @type String
*/
this.setAttributeConfig("selectionMode", {
value: "standard",
validator: lang.isString
});
/**
* @attribute sortedBy
* @description Object literal provides metadata for initial sort values if
* data will arrive pre-sorted:
*
* sortedBy.key
* {String} Key of sorted Column
* sortedBy.dir
* {String} Initial sort direction, either YAHOO.widget.DataTable.CLASS_ASC or YAHOO.widget.DataTable.CLASS_DESC
*
* @type Object | null
*/
this.setAttributeConfig("sortedBy", {
value: null,
// TODO: accepted array for nested sorts
validator: function(oNewSortedBy) {
if(oNewSortedBy) {
return (lang.isObject(oNewSortedBy) && oNewSortedBy.key);
}
else {
return (oNewSortedBy === null);
}
},
method: function(oNewSortedBy) {
// Stash the previous value
var oOldSortedBy = this.get("sortedBy");
// Workaround for bug 1827195
this._configs.sortedBy.value = oNewSortedBy;
// Remove ASC/DESC from TH
var oOldColumn,
nOldColumnKeyIndex,
oNewColumn,
nNewColumnKeyIndex;
if(this._elThead) {
if(oOldSortedBy && oOldSortedBy.key && oOldSortedBy.dir) {
oOldColumn = this._oColumnSet.getColumn(oOldSortedBy.key);
nOldColumnKeyIndex = oOldColumn.getKeyIndex();
// Remove previous UI from THEAD
var elOldTh = oOldColumn.getThEl();
Dom.removeClass(elOldTh, oOldSortedBy.dir);
this.formatTheadCell(oOldColumn.getThLinerEl().firstChild, oOldColumn, oNewSortedBy);
}
if(oNewSortedBy) {
oNewColumn = (oNewSortedBy.column) ? oNewSortedBy.column : this._oColumnSet.getColumn(oNewSortedBy.key);
nNewColumnKeyIndex = oNewColumn.getKeyIndex();
// Update THEAD with new UI
var elNewTh = oNewColumn.getThEl();
// Backward compatibility
if(oNewSortedBy.dir && ((oNewSortedBy.dir == "asc") || (oNewSortedBy.dir == "desc"))) {
var newClass = (oNewSortedBy.dir == "desc") ?
DT.CLASS_DESC :
DT.CLASS_ASC;
Dom.addClass(elNewTh, newClass);
}
else {
var sortClass = oNewSortedBy.dir || DT.CLASS_ASC;
Dom.addClass(elNewTh, sortClass);
}
this.formatTheadCell(oNewColumn.getThLinerEl().firstChild, oNewColumn, oNewSortedBy);
}
}
if(this._elTbody) {
// Update TBODY UI
this._elTbody.style.display = "none";
var allRows = this._elTbody.rows,
allCells;
for(var i=allRows.length-1; i>-1; i--) {
allCells = allRows[i].childNodes;
if(allCells[nOldColumnKeyIndex]) {
Dom.removeClass(allCells[nOldColumnKeyIndex], oOldSortedBy.dir);
}
if(allCells[nNewColumnKeyIndex]) {
Dom.addClass(allCells[nNewColumnKeyIndex], oNewSortedBy.dir);
}
}
this._elTbody.style.display = "";
}
this._clearTrTemplateEl();
}
});
/**
* @attribute paginator
* @description An instance of YAHOO.widget.Paginator.
* @default null
* @type {Object|YAHOO.widget.Paginator}
*/
this.setAttributeConfig("paginator", {
value : null,
validator : function (val) {
return val === null || val instanceof widget.Paginator;
},
method : function () { this._updatePaginator.apply(this,arguments); }
});
/**
* @attribute caption
* @description Value for the CAPTION element. NB: Not supported in
* ScrollingDataTable.
* @type String
*/
this.setAttributeConfig("caption", {
value: null,
validator: lang.isString,
method: function(sCaption) {
this._initCaptionEl(sCaption);
}
});
/**
* @attribute draggableColumns
* @description True if Columns are draggable to reorder, false otherwise.
* The Drag & Drop Utility is required to enable this feature. Only top-level
* and non-nested Columns are draggable. Write once.
* @default false
* @type Boolean
*/
this.setAttributeConfig("draggableColumns", {
value: false,
validator: lang.isBoolean,
method: function(oParam) {
if(this._elThead) {
if(oParam) {
this._initDraggableColumns();
}
else {
this._destroyDraggableColumns();
}
}
}
});
/**
* @attribute renderLoopSize
* @description A value greater than 0 enables DOM rendering of rows to be
* executed from a non-blocking timeout queue and sets how many rows to be
* rendered per timeout. Recommended for very large data sets.
* @type Number
* @default 0
*/
this.setAttributeConfig("renderLoopSize", {
value: 0,
validator: lang.isNumber
});
/**
* @attribute formatRow
* @description A function that accepts a TR element and its associated Record
* for custom formatting. The function must return TRUE in order to automatically
* continue formatting of child TD elements, else TD elements will not be
* automatically formatted.
* @type function
* @default null
*/
this.setAttributeConfig("formatRow", {
value: null,
validator: lang.isFunction
});
/**
* @attribute generateRequest
* @description A function that converts an object literal of desired DataTable
* states into a request value which is then passed to the DataSource's
* sendRequest method in order to retrieve data for those states. This
* function is passed an object literal of state data and a reference to the
* DataTable instance:
*
*
* pagination
*
* offsetRecord
* {Number} Index of the first Record of the desired page
* rowsPerPage
* {Number} Number of rows per page
*
* sortedBy
*
* key
* {String} Key of sorted Column
* dir
* {String} Sort direction, either YAHOO.widget.DataTable.CLASS_ASC or YAHOO.widget.DataTable.CLASS_DESC
*
* self
* The DataTable instance
*
*
* and by default returns a String of syntax:
* "sort={sortColumn}&dir={sortDir}&startIndex={pageStartIndex}&results={rowsPerPage}"
* @type function
* @default HTMLFunction
*/
this.setAttributeConfig("generateRequest", {
value: function(oState, oSelf) {
// Set defaults
oState = oState || {pagination:null, sortedBy:null};
var sort = encodeURIComponent((oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey());
var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
// Build the request
return "sort=" + sort +
"&dir=" + dir +
"&startIndex=" + startIndex +
((results !== null) ? "&results=" + results : "");
},
validator: lang.isFunction
});
/**
* @attribute initialRequest
* @description Defines the initial request that gets sent to the DataSource
* during initialization. Value is ignored if initialLoad is set to any value
* other than true.
* @type MIXED
* @default null
*/
this.setAttributeConfig("initialRequest", {
value: null
});
/**
* @attribute initialLoad
* @description Determines whether or not to load data at instantiation. By
* default, will trigger a sendRequest() to the DataSource and pass in the
* request defined by initialRequest. If set to false, data will not load
* at instantiation. Alternatively, implementers who wish to work with a
* custom payload may pass in an object literal with the following values:
*
*
* request (MIXED)
* Request value.
*
* argument (MIXED)
* Custom data that will be passed through to the callback function.
*
*
*
* @type Boolean | Object
* @default true
*/
this.setAttributeConfig("initialLoad", {
value: true
});
/**
* @attribute dynamicData
* @description If true, sorting and pagination are relegated to the DataSource
* for handling, using the request returned by the "generateRequest" function.
* Each new DataSource response blows away all previous Records. False by default, so
* sorting and pagination will be handled directly on the client side, without
* causing any new requests for data from the DataSource.
* @type Boolean
* @default false
*/
this.setAttributeConfig("dynamicData", {
value: false,
validator: lang.isBoolean
});
/**
* @attribute MSG_EMPTY
* @description Message to display if DataTable has no data.
* @type String
* @default "No records found."
*/
this.setAttributeConfig("MSG_EMPTY", {
value: "No records found.",
validator: lang.isString
});
/**
* @attribute MSG_LOADING
* @description Message to display while DataTable is loading data.
* @type String
* @default "Loading..."
*/
this.setAttributeConfig("MSG_LOADING", {
value: "Loading...",
validator: lang.isString
});
/**
* @attribute MSG_ERROR
* @description Message to display while DataTable has data error.
* @type String
* @default "Data error."
*/
this.setAttributeConfig("MSG_ERROR", {
value: "Data error.",
validator: lang.isString
});
/**
* @attribute MSG_SORTASC
* @description Message to display in tooltip to sort Column in ascending order.
* @type String
* @default "Click to sort ascending"
*/
this.setAttributeConfig("MSG_SORTASC", {
value: "Click to sort ascending",
validator: lang.isString,
method: function(sParam) {
if(this._elThead) {
for(var i=0, allKeys=this.getColumnSet().keys, len=allKeys.length; i aKeyIndexes[aKeyIndexes.length-1])) {
var i,
tmpCols = [];
// Remove COL
for(i=aKeyIndexes.length-1; i>-1; i--) {
tmpCols.push(this._elColgroup.removeChild(this._elColgroup.childNodes[aKeyIndexes[i]]));
}
// Insert COL
var nextSibling = this._elColgroup.childNodes[newIndex] || null;
for(i=tmpCols.length-1; i>-1; i--) {
this._elColgroup.insertBefore(tmpCols[i], nextSibling);
}
}
},
/**
* Destroy's the DataTable THEAD element, if available.
*
* @method _destroyTheadEl
* @private
*/
_destroyTheadEl : function() {
var elThead = this._elThead;
if(elThead) {
var elTable = elThead.parentNode;
Ev.purgeElement(elThead, true);
this._destroyColumnHelpers();
elTable.removeChild(elThead);
this._elThead = null;
}
},
/**
* Initializes THEAD element.
*
* @method _initTheadEl
* @param elTable {HTMLElement} TABLE element into which to create COLGROUP.
* @param {HTMLElement} Initialized THEAD element.
* @private
*/
_initTheadEl : function(elTable) {
elTable = elTable || this._elTable;
if(elTable) {
// Destroy previous
this._destroyTheadEl();
//TODO: append to DOM later for performance
var elThead = (this._elColgroup) ?
elTable.insertBefore(document.createElement("thead"), this._elColgroup.nextSibling) :
elTable.appendChild(document.createElement("thead"));
// Set up DOM events for THEAD
Ev.addListener(elThead, "focus", this._onTheadFocus, this);
Ev.addListener(elThead, "keydown", this._onTheadKeydown, this);
Ev.addListener(elThead, "mouseover", this._onTableMouseover, this);
Ev.addListener(elThead, "mouseout", this._onTableMouseout, this);
Ev.addListener(elThead, "mousedown", this._onTableMousedown, this);
Ev.addListener(elThead, "mouseup", this._onTableMouseup, this);
Ev.addListener(elThead, "click", this._onTheadClick, this);
// Since we can't listen for click and dblclick on the same element...
// Attach separately to THEAD and TBODY
///Ev.addListener(elThead, "dblclick", this._onTableDblclick, this);
var oColumnSet = this._oColumnSet,
oColumn, i,j, l;
// Add TRs to the THEAD
var colTree = oColumnSet.tree;
var elTh;
for(i=0; i" + sLabel + "";
}
// Just display the label for non-sortable Columns
else {
elCellLabel.innerHTML = sLabel;
}
},
/**
* Disables DD from top-level Column TH elements.
*
* @method _destroyDraggableColumns
* @private
*/
_destroyDraggableColumns : function() {
var oColumn, elTh;
for(var i=0, len=this._oColumnSet.tree[0].length; i 1
// Create a separate resizer liner with position:relative
elThResizerLiner = elTh.appendChild(document.createElement("div"));
elThResizerLiner.className = DT.CLASS_RESIZERLINER;
// Move TH contents into the new resizer liner
elThResizerLiner.appendChild(elThLiner);
// Create the resizer
elThResizer = elThResizerLiner.appendChild(document.createElement("div"));
elThResizer.id = elTh.id + "-resizer"; // Needed for ColumnResizer
elThResizer.className = DT.CLASS_RESIZER;
oColumn._elResizer = elThResizer;
// Create the resizer proxy, once globally
elResizerProxy = DT._initColumnResizerProxyEl();
oColumn._ddResizer = new YAHOO.util.ColumnResizer(
this, oColumn, elTh, elThResizer, elResizerProxy);
cancelClick = function(e) {
Ev.stopPropagation(e);
};
Ev.addListener(elThResizer,"click",cancelClick);
}
}
}
else {
}
},
/**
* Destroys elements associated with Column functionality: ColumnDD and ColumnResizers.
*
* @method _destroyColumnHelpers
* @private
*/
_destroyColumnHelpers : function() {
this._destroyDraggableColumns();
this._destroyResizeableColumns();
},
/**
* Initializes elements associated with Column functionality: ColumnDD and ColumnResizers.
*
* @method _initColumnHelpers
* @private
*/
_initColumnHelpers : function() {
if(this.get("draggableColumns")) {
this._initDraggableColumns();
}
this._initResizeableColumns();
},
/**
* Destroy's the DataTable TBODY element, if available.
*
* @method _destroyTbodyEl
* @private
*/
_destroyTbodyEl : function() {
var elTbody = this._elTbody;
if(elTbody) {
var elTable = elTbody.parentNode;
Ev.purgeElement(elTbody, true);
elTable.removeChild(elTbody);
this._elTbody = null;
}
},
/**
* Initializes TBODY element for data.
*
* @method _initTbodyEl
* @param elTable {HTMLElement} TABLE element into which to create TBODY .
* @private
*/
_initTbodyEl : function(elTable) {
if(elTable) {
// Destroy previous
this._destroyTbodyEl();
// Create TBODY
var elTbody = elTable.appendChild(document.createElement("tbody"));
elTbody.tabIndex = 0;
elTbody.className = DT.CLASS_DATA;
// Set up DOM events for TBODY
Ev.addListener(elTbody, "focus", this._onTbodyFocus, this);
Ev.addListener(elTbody, "mouseover", this._onTableMouseover, this);
Ev.addListener(elTbody, "mouseout", this._onTableMouseout, this);
Ev.addListener(elTbody, "mousedown", this._onTableMousedown, this);
Ev.addListener(elTbody, "mouseup", this._onTableMouseup, this);
Ev.addListener(elTbody, "keydown", this._onTbodyKeydown, this);
Ev.addListener(elTbody, "keypress", this._onTableKeypress, this);
Ev.addListener(elTbody, "click", this._onTbodyClick, this);
// Since we can't listen for click and dblclick on the same element...
// Attach separately to THEAD and TBODY
///Ev.addListener(elTbody, "dblclick", this._onTableDblclick, this);
// IE puts focus outline in the wrong place
if(ua.ie) {
elTbody.hideFocus=true;
}
this._elTbody = elTbody;
}
},
/**
* Destroy's the DataTable message TBODY element, if available.
*
* @method _destroyMsgTbodyEl
* @private
*/
_destroyMsgTbodyEl : function() {
var elMsgTbody = this._elMsgTbody;
if(elMsgTbody) {
var elTable = elMsgTbody.parentNode;
Ev.purgeElement(elMsgTbody, true);
elTable.removeChild(elMsgTbody);
this._elTbody = null;
}
},
/**
* Initializes TBODY element for messaging.
*
* @method _initMsgTbodyEl
* @param elTable {HTMLElement} TABLE element into which to create TBODY
* @private
*/
_initMsgTbodyEl : function(elTable) {
if(elTable) {
var elMsgTbody = document.createElement("tbody");
elMsgTbody.className = DT.CLASS_MESSAGE;
var elMsgTr = elMsgTbody.appendChild(document.createElement("tr"));
elMsgTr.className = DT.CLASS_FIRST + " " + DT.CLASS_LAST;
this._elMsgTr = elMsgTr;
var elMsgTd = elMsgTr.appendChild(document.createElement("td"));
elMsgTd.colSpan = this._oColumnSet.keys.length || 1;
elMsgTd.className = DT.CLASS_FIRST + " " + DT.CLASS_LAST;
this._elMsgTd = elMsgTd;
elMsgTbody = elTable.insertBefore(elMsgTbody, this._elTbody);
var elMsgLiner = elMsgTd.appendChild(document.createElement("div"));
elMsgLiner.className = DT.CLASS_LINER;
this._elMsgTbody = elMsgTbody;
// Set up DOM events for TBODY
Ev.addListener(elMsgTbody, "focus", this._onTbodyFocus, this);
Ev.addListener(elMsgTbody, "mouseover", this._onTableMouseover, this);
Ev.addListener(elMsgTbody, "mouseout", this._onTableMouseout, this);
Ev.addListener(elMsgTbody, "mousedown", this._onTableMousedown, this);
Ev.addListener(elMsgTbody, "mouseup", this._onTableMouseup, this);
Ev.addListener(elMsgTbody, "keydown", this._onTbodyKeydown, this);
Ev.addListener(elMsgTbody, "keypress", this._onTableKeypress, this);
Ev.addListener(elMsgTbody, "click", this._onTbodyClick, this);
}
},
/**
* Initialize internal event listeners
*
* @method _initEvents
* @private
*/
_initEvents : function () {
// Initialize Column sort
this._initColumnSort();
// Add the document level click listener
YAHOO.util.Event.addListener(document, "click", this._onDocumentClick, this);
// Paginator integration
this.subscribe("paginatorChange",function () {
this._handlePaginatorChange.apply(this,arguments);
});
this.subscribe("initEvent",function () {
this.renderPaginator();
});
// Initialize CellEditor integration
this._initCellEditing();
},
/**
* Initializes Column sorting.
*
* @method _initColumnSort
* @private
*/
_initColumnSort : function() {
this.subscribe("theadCellClickEvent", this.onEventSortColumn);
// Backward compatibility
var oSortedBy = this.get("sortedBy");
if(oSortedBy) {
if(oSortedBy.dir == "desc") {
this._configs.sortedBy.value.dir = DT.CLASS_DESC;
}
else if(oSortedBy.dir == "asc") {
this._configs.sortedBy.value.dir = DT.CLASS_ASC;
}
}
},
/**
* Initializes CellEditor integration.
*
* @method _initCellEditing
* @private
*/
_initCellEditing : function() {
this.subscribe("editorBlurEvent",function () {
this.onEditorBlurEvent.apply(this,arguments);
});
this.subscribe("editorBlockEvent",function () {
this.onEditorBlockEvent.apply(this,arguments);
});
this.subscribe("editorUnblockEvent",function () {
this.onEditorUnblockEvent.apply(this,arguments);
});
},
// DOM MUTATION FUNCTIONS
/**
* Retruns classnames to represent current Column states.
* @method _getColumnClassnames
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param aAddClasses {String[]} An array of additional classnames to add to the
* return value.
* @return {String} A String of classnames to be assigned to TH or TD elements
* for given Column.
* @private
*/
_getColumnClassNames : function (oColumn, aAddClasses) {
var allClasses;
// Add CSS classes
if(lang.isString(oColumn.className)) {
// Single custom class
allClasses = [oColumn.className];
}
else if(lang.isArray(oColumn.className)) {
// Array of custom classes
allClasses = oColumn.className;
}
else {
// no custom classes
allClasses = [];
}
// Hook for setting width with via dynamic style uses key since ID is too disposable
allClasses[allClasses.length] = this.getId() + "-col-" +oColumn.getSanitizedKey();
// Column key - minus any chars other than "A-Z", "a-z", "0-9", "_", "-", ".", or ":"
allClasses[allClasses.length] = "yui-dt-col-" +oColumn.getSanitizedKey();
var isSortedBy = this.get("sortedBy") || {};
// Sorted
if(oColumn.key === isSortedBy.key) {
allClasses[allClasses.length] = isSortedBy.dir || '';
}
// Hidden
if(oColumn.hidden) {
allClasses[allClasses.length] = DT.CLASS_HIDDEN;
}
// Selected
if(oColumn.selected) {
allClasses[allClasses.length] = DT.CLASS_SELECTED;
}
// Sortable
if(oColumn.sortable) {
allClasses[allClasses.length] = DT.CLASS_SORTABLE;
}
// Resizeable
if(oColumn.resizeable) {
allClasses[allClasses.length] = DT.CLASS_RESIZEABLE;
}
// Editable
if(oColumn.editor) {
allClasses[allClasses.length] = DT.CLASS_EDITABLE;
}
// Addtnl classes, including First/Last
if(aAddClasses) {
allClasses = allClasses.concat(aAddClasses);
}
return allClasses.join(' ');
},
/**
* Clears TR element template in response to any Column state change.
* @method _clearTrTemplateEl
* @private
*/
_clearTrTemplateEl : function () {
this._elTrTemplate = null;
},
/**
* Returns a new TR element template with TD elements classed with current
* Column states.
* @method _getTrTemplateEl
* @return {HTMLElement} A TR element to be cloned and added to the DOM.
* @private
*/
_getTrTemplateEl : function (oRecord, index) {
// Template is already available
if(this._elTrTemplate) {
return this._elTrTemplate;
}
// Template needs to be created
else {
var d = document,
tr = d.createElement('tr'),
td = d.createElement('td'),
div = d.createElement('div');
// Append the liner element
td.appendChild(div);
// Create TD elements into DOCUMENT FRAGMENT
var df = document.createDocumentFragment(),
allKeys = this._oColumnSet.keys,
elTd;
// Set state for each TD;
var aAddClasses;
for(var i=0, keysLen=allKeys.length; i -2) && (rowIndex < this._elTbody.rows.length)) {
// Cannot use tbody.deleteRow due to IE6 instability
//return this._elTbody.deleteRow(rowIndex);
return this._elTbody.removeChild(this.getTrEl(row));
}
else {
return null;
}
},
// CSS/STATE FUNCTIONS
/**
* Removes the class YAHOO.widget.DataTable.CLASS_FIRST from the first TR element
* of the DataTable page and updates internal tracker.
*
* @method _unsetFirstRow
* @private
*/
_unsetFirstRow : function() {
// Remove FIRST
if(this._sFirstTrId) {
Dom.removeClass(this._sFirstTrId, DT.CLASS_FIRST);
this._sFirstTrId = null;
}
},
/**
* Assigns the class YAHOO.widget.DataTable.CLASS_FIRST to the first TR element
* of the DataTable page and updates internal tracker.
*
* @method _setFirstRow
* @private
*/
_setFirstRow : function() {
this._unsetFirstRow();
var elTr = this.getFirstTrEl();
if(elTr) {
// Set FIRST
Dom.addClass(elTr, DT.CLASS_FIRST);
this._sFirstTrId = elTr.id;
}
},
/**
* Removes the class YAHOO.widget.DataTable.CLASS_LAST from the last TR element
* of the DataTable page and updates internal tracker.
*
* @method _unsetLastRow
* @private
*/
_unsetLastRow : function() {
// Unassign previous class
if(this._sLastTrId) {
Dom.removeClass(this._sLastTrId, DT.CLASS_LAST);
this._sLastTrId = null;
}
},
/**
* Assigns the class YAHOO.widget.DataTable.CLASS_LAST to the last TR element
* of the DataTable page and updates internal tracker.
*
* @method _setLastRow
* @private
*/
_setLastRow : function() {
this._unsetLastRow();
var elTr = this.getLastTrEl();
if(elTr) {
// Assign class
Dom.addClass(elTr, DT.CLASS_LAST);
this._sLastTrId = elTr.id;
}
},
/**
* Assigns the classes DT.CLASS_EVEN and DT.CLASS_ODD to one, many, or all TR elements.
*
* @method _setRowStripes
* @param row {HTMLElement | String | Number} (optional) HTML TR element reference
* or string ID, or page row index of where to start striping.
* @param range {Number} (optional) If given, how many rows to stripe, otherwise
* stripe all the rows until the end.
* @private
*/
_setRowStripes : function(row, range) {
// Default values stripe all rows
var allRows = this._elTbody.rows,
nStartIndex = 0,
nEndIndex = allRows.length,
aOdds = [], nOddIdx = 0,
aEvens = [], nEvenIdx = 0;
// Stripe a subset
if((row !== null) && (row !== undefined)) {
// Validate given start row
var elStartRow = this.getTrEl(row);
if(elStartRow) {
nStartIndex = elStartRow.sectionRowIndex;
// Validate given range
if(lang.isNumber(range) && (range > 1)) {
nEndIndex = nStartIndex + range;
}
}
}
for(var i=nStartIndex; i0) || (allSelectedCells.length > 0)) {
var oColumnSet = this._oColumnSet,
el;
// Loop over each row
for(var i=0; i
* pagination
* Instance of YAHOO.widget.Paginator
*
* sortedBy
*
*
* sortedBy.key
* {String} Key of sorted Column
* sortedBy.dir
* {String} Initial sort direction, either YAHOO.widget.DataTable.CLASS_ASC or YAHOO.widget.DataTable.CLASS_DESC
*
*
*
* selectedRows
* Array of selected rows by Record ID.
*
* selectedCells
* Selected cells as an array of object literals:
* {recordId:sRecordId, columnKey:sColumnKey}
*
*
* @method getState
* @return {Object} DataTable instance state object literal values.
*/
getState : function() {
return {
totalRecords: this.get('paginator') ? this.get('paginator').get("totalRecords") : this._oRecordSet.getLength(),
pagination: this.get("paginator") ? this.get("paginator").getState() : null,
sortedBy: this.get("sortedBy"),
selectedRows: this.getSelectedRows(),
selectedCells: this.getSelectedCells()
};
},
// DOM ACCESSORS
/**
* Returns DOM reference to the DataTable's container element.
*
* @method getContainerEl
* @return {HTMLElement} Reference to DIV element.
*/
getContainerEl : function() {
return this._elContainer;
},
/**
* Returns DOM reference to the DataTable's TABLE element.
*
* @method getTableEl
* @return {HTMLElement} Reference to TABLE element.
*/
getTableEl : function() {
return this._elTable;
},
/**
* Returns DOM reference to the DataTable's THEAD element.
*
* @method getTheadEl
* @return {HTMLElement} Reference to THEAD element.
*/
getTheadEl : function() {
return this._elThead;
},
/**
* Returns DOM reference to the DataTable's primary TBODY element.
*
* @method getTbodyEl
* @return {HTMLElement} Reference to TBODY element.
*/
getTbodyEl : function() {
return this._elTbody;
},
/**
* Returns DOM reference to the DataTable's secondary TBODY element that is
* used to display messages.
*
* @method getMsgTbodyEl
* @return {HTMLElement} Reference to TBODY element.
*/
getMsgTbodyEl : function() {
return this._elMsgTbody;
},
/**
* Returns DOM reference to the TD element within the secondary TBODY that is
* used to display messages.
*
* @method getMsgTdEl
* @return {HTMLElement} Reference to TD element.
*/
getMsgTdEl : function() {
return this._elMsgTd;
},
/**
* Returns the corresponding TR reference for a given DOM element, ID string or
* directly page row index. If the given identifier is a child of a TR element,
* then DOM tree is traversed until a parent TR element is returned, otherwise
* null.
*
* @method getTrEl
* @param row {HTMLElement | String | Number | YAHOO.widget.Record} Which row to
* get: by element reference, ID string, page row index, or Record.
* @return {HTMLElement} Reference to TR element, or null.
*/
getTrEl : function(row) {
// By Record
if(row instanceof YAHOO.widget.Record) {
return document.getElementById(row.getId());
}
// By page row index
else if(lang.isNumber(row)) {
var allRows = this._elTbody.rows;
return ((row > -1) && (row < allRows.length)) ? allRows[row] : null;
}
// By ID string or element reference
else {
var elRow = (lang.isString(row)) ? document.getElementById(row) : row;
// Validate HTML element
if(elRow && (elRow.ownerDocument == document)) {
// Validate TR element
if(elRow.nodeName.toLowerCase() != "tr") {
// Traverse up the DOM to find the corresponding TR element
elRow = Dom.getAncestorByTagName(elRow,"tr");
}
return elRow;
}
}
return null;
},
/**
* Returns DOM reference to the first TR element in the DataTable page, or null.
*
* @method getFirstTrEl
* @return {HTMLElement} Reference to TR element.
*/
getFirstTrEl : function() {
return this._elTbody.rows[0] || null;
},
/**
* Returns DOM reference to the last TR element in the DataTable page, or null.
*
* @method getLastTrEl
* @return {HTMLElement} Reference to last TR element.
*/
getLastTrEl : function() {
var allRows = this._elTbody.rows;
if(allRows.length > 0) {
return allRows[allRows.length-1] || null;
}
},
/**
* Returns DOM reference to the next TR element from the given TR element, or null.
*
* @method getNextTrEl
* @param row {HTMLElement | String | Number | YAHOO.widget.Record} Element
* reference, ID string, page row index, or Record from which to get next TR element.
* @return {HTMLElement} Reference to next TR element.
*/
getNextTrEl : function(row) {
var nThisTrIndex = this.getTrIndex(row);
if(nThisTrIndex !== null) {
var allRows = this._elTbody.rows;
if(nThisTrIndex < allRows.length-1) {
return allRows[nThisTrIndex+1];
}
}
return null;
},
/**
* Returns DOM reference to the previous TR element from the given TR element, or null.
*
* @method getPreviousTrEl
* @param row {HTMLElement | String | Number | YAHOO.widget.Record} Element
* reference, ID string, page row index, or Record from which to get previous TR element.
* @return {HTMLElement} Reference to previous TR element.
*/
getPreviousTrEl : function(row) {
var nThisTrIndex = this.getTrIndex(row);
if(nThisTrIndex !== null) {
var allRows = this._elTbody.rows;
if(nThisTrIndex > 0) {
return allRows[nThisTrIndex-1];
}
}
return null;
},
/**
* Returns DOM reference to a TD liner element.
*
* @method getTdLinerEl
* @param cell {HTMLElement | Object} TD element or child of a TD element, or
* object literal of syntax {record:oRecord, column:oColumn}.
* @return {HTMLElement} Reference to TD liner element.
*/
getTdLinerEl : function(cell) {
var elCell = this.getTdEl(cell);
return elCell.firstChild || null;
},
/**
* Returns DOM reference to a TD element.
*
* @method getTdEl
* @param cell {HTMLElement | String | Object} TD element or child of a TD element, or
* object literal of syntax {record:oRecord, column:oColumn}.
* @return {HTMLElement} Reference to TD element.
*/
getTdEl : function(cell) {
var elCell;
var el = Dom.get(cell);
// Validate HTML element
if(el && (el.ownerDocument == document)) {
// Validate TD element
if(el.nodeName.toLowerCase() != "td") {
// Traverse up the DOM to find the corresponding TR element
elCell = Dom.getAncestorByTagName(el, "td");
}
else {
elCell = el;
}
// Make sure the TD is in this TBODY
// Bug 2527707 and bug 2263558
if(elCell && ((elCell.parentNode.parentNode == this._elTbody) || (elCell.parentNode.parentNode === null))) {
// Now we can return the TD element
return elCell;
}
}
else if(cell) {
var oRecord, nColKeyIndex;
if(lang.isString(cell.columnKey) && lang.isString(cell.recordId)) {
oRecord = this.getRecord(cell.recordId);
var oColumn = this.getColumn(cell.columnKey);
if(oColumn) {
nColKeyIndex = oColumn.getKeyIndex();
}
}
if(cell.record && cell.column && cell.column.getKeyIndex) {
oRecord = cell.record;
nColKeyIndex = cell.column.getKeyIndex();
}
var elRow = this.getTrEl(oRecord);
if((nColKeyIndex !== null) && elRow && elRow.cells && elRow.cells.length > 0) {
return elRow.cells[nColKeyIndex] || null;
}
}
return null;
},
/**
* Returns DOM reference to the first TD element in the DataTable page (by default),
* the first TD element of the optionally given row, or null.
*
* @method getFirstTdEl
* @param row {HTMLElement} (optional) row from which to get first TD
* @return {HTMLElement} Reference to TD element.
*/
getFirstTdEl : function(row) {
var elRow = this.getTrEl(row) || this.getFirstTrEl();
if(elRow && (elRow.cells.length > 0)) {
return elRow.cells[0];
}
return null;
},
/**
* Returns DOM reference to the last TD element in the DataTable page (by default),
* the first TD element of the optionally given row, or null.
*
* @method getLastTdEl
* @return {HTMLElement} Reference to last TD element.
*/
getLastTdEl : function(row) {
var elRow = this.getTrEl(row) || this.getLastTrEl();
if(elRow && (elRow.cells.length > 0)) {
return elRow.cells[elRow.cells.length-1];
}
return null;
},
/**
* Returns DOM reference to the next TD element from the given cell, or null.
*
* @method getNextTdEl
* @param cell {HTMLElement | String | Object} DOM element reference or string ID, or
* object literal of syntax {record:oRecord, column:oColumn} from which to get next TD element.
* @return {HTMLElement} Reference to next TD element, or null.
*/
getNextTdEl : function(cell) {
var elCell = this.getTdEl(cell);
if(elCell) {
var nThisTdIndex = elCell.cellIndex;
var elRow = this.getTrEl(elCell);
if(nThisTdIndex < elRow.cells.length-1) {
return elRow.cells[nThisTdIndex+1];
}
else {
var elNextRow = this.getNextTrEl(elRow);
if(elNextRow) {
return elNextRow.cells[0];
}
}
}
return null;
},
/**
* Returns DOM reference to the previous TD element from the given cell, or null.
*
* @method getPreviousTdEl
* @param cell {HTMLElement | String | Object} DOM element reference or string ID, or
* object literal of syntax {record:oRecord, column:oColumn} from which to get previous TD element.
* @return {HTMLElement} Reference to previous TD element, or null.
*/
getPreviousTdEl : function(cell) {
var elCell = this.getTdEl(cell);
if(elCell) {
var nThisTdIndex = elCell.cellIndex;
var elRow = this.getTrEl(elCell);
if(nThisTdIndex > 0) {
return elRow.cells[nThisTdIndex-1];
}
else {
var elPreviousRow = this.getPreviousTrEl(elRow);
if(elPreviousRow) {
return this.getLastTdEl(elPreviousRow);
}
}
}
return null;
},
/**
* Returns DOM reference to the above TD element from the given cell, or null.
*
* @method getAboveTdEl
* @param cell {HTMLElement | String | Object} DOM element reference or string ID, or
* object literal of syntax {record:oRecord, column:oColumn} from which to get next TD element.
* @return {HTMLElement} Reference to next TD element, or null.
*/
getAboveTdEl : function(cell) {
var elCell = this.getTdEl(cell);
if(elCell) {
var elPreviousRow = this.getPreviousTrEl(elCell);
if(elPreviousRow) {
return elPreviousRow.cells[elCell.cellIndex];
}
}
return null;
},
/**
* Returns DOM reference to the below TD element from the given cell, or null.
*
* @method getBelowTdEl
* @param cell {HTMLElement | String | Object} DOM element reference or string ID, or
* object literal of syntax {record:oRecord, column:oColumn} from which to get previous TD element.
* @return {HTMLElement} Reference to previous TD element, or null.
*/
getBelowTdEl : function(cell) {
var elCell = this.getTdEl(cell);
if(elCell) {
var elNextRow = this.getNextTrEl(elCell);
if(elNextRow) {
return elNextRow.cells[elCell.cellIndex];
}
}
return null;
},
/**
* Returns DOM reference to a TH liner element. Needed to normalize for resizeable
* Columns, which have an additional resizer liner DIV element between the TH
* element and the liner DIV element.
*
* @method getThLinerEl
* @param theadCell {YAHOO.widget.Column | HTMLElement | String} Column instance,
* DOM element reference, or string ID.
* @return {HTMLElement} Reference to TH liner element.
*/
getThLinerEl : function(theadCell) {
var oColumn = this.getColumn(theadCell);
return (oColumn) ? oColumn.getThLinerEl() : null;
},
/**
* Returns DOM reference to a TH element.
*
* @method getThEl
* @param theadCell {YAHOO.widget.Column | HTMLElement | String} Column instance,
* DOM element reference, or string ID.
* @return {HTMLElement} Reference to TH element.
*/
getThEl : function(theadCell) {
var elTh;
// Validate Column instance
if(theadCell instanceof YAHOO.widget.Column) {
var oColumn = theadCell;
elTh = oColumn.getThEl();
if(elTh) {
return elTh;
}
}
// Validate HTML element
else {
var el = Dom.get(theadCell);
if(el && (el.ownerDocument == document)) {
// Validate TH element
if(el.nodeName.toLowerCase() != "th") {
// Traverse up the DOM to find the corresponding TR element
elTh = Dom.getAncestorByTagName(el,"th");
}
else {
elTh = el;
}
return elTh;
}
}
return null;
},
/**
* Returns the page row index of given row. Returns null if the row is not on the
* current DataTable page.
*
* @method getTrIndex
* @param row {HTMLElement | String | YAHOO.widget.Record | Number} DOM or ID
* string reference to an element within the DataTable page, a Record instance,
* or a Record's RecordSet index.
* @return {Number} Page row index, or null if row does not exist or is not on current page.
*/
getTrIndex : function(row) {
var nRecordIndex;
// By Record
if(row instanceof YAHOO.widget.Record) {
nRecordIndex = this._oRecordSet.getRecordIndex(row);
if(nRecordIndex === null) {
// Not a valid Record
return null;
}
}
// Calculate page row index from Record index
else if(lang.isNumber(row)) {
nRecordIndex = row;
}
if(lang.isNumber(nRecordIndex)) {
// Validate the number
if((nRecordIndex > -1) && (nRecordIndex < this._oRecordSet.getLength())) {
// DataTable is paginated
var oPaginator = this.get('paginator');
if(oPaginator) {
// Check the record index is within the indices of the
// current page
var rng = oPaginator.getPageRecords();
if (rng && nRecordIndex >= rng[0] && nRecordIndex <= rng[1]) {
// This Record is on current page
return nRecordIndex - rng[0];
}
// This Record is not on current page
else {
return null;
}
}
// Not paginated, just return the Record index
else {
return nRecordIndex;
}
}
// RecordSet index is out of range
else {
return null;
}
}
// By element reference or ID string
else {
// Validate TR element
var elRow = this.getTrEl(row);
if(elRow && (elRow.ownerDocument == document) &&
(elRow.parentNode == this._elTbody)) {
return elRow.sectionRowIndex;
}
}
return null;
},
// TABLE FUNCTIONS
/**
* Resets a RecordSet with the given data and populates the page view
* with the new data. Any previous data, and selection and sort states are
* cleared. New data should be added as a separate step.
*
* @method initializeTable
*/
initializeTable : function() {
// Reset init flag
this._bInit = true;
// Clear the RecordSet
this._oRecordSet.reset();
// Clear the Paginator's totalRecords if paginating
var pag = this.get('paginator');
if (pag) {
pag.set('totalRecords',0);
}
// Clear selections
this._unselectAllTrEls();
this._unselectAllTdEls();
this._aSelections = null;
this._oAnchorRecord = null;
this._oAnchorCell = null;
// Clear sort
this.set("sortedBy", null);
},
/**
* Internal wrapper calls run() on render Chain instance.
*
* @method _runRenderChain
* @private
*/
_runRenderChain : function() {
this._oChainRender.run();
},
/**
* Renders the view with existing Records from the RecordSet while
* maintaining sort, pagination, and selection states. For performance, reuses
* existing DOM elements when possible while deleting extraneous elements.
*
* @method render
*/
render : function() {
//YAHOO.example.Performance.trialStart = new Date();
this._oChainRender.stop();
this.fireEvent("beforeRenderEvent");
var i, j, k, len, allRecords;
var oPaginator = this.get('paginator');
// Paginator is enabled, show a subset of Records and update Paginator UI
if(oPaginator) {
allRecords = this._oRecordSet.getRecords(
oPaginator.getStartIndex(),
oPaginator.getRowsPerPage());
}
// Not paginated, show all records
else {
allRecords = this._oRecordSet.getRecords();
}
// From the top, update in-place existing rows, so as to reuse DOM elements
var elTbody = this._elTbody,
loopN = this.get("renderLoopSize"),
nRecordsLength = allRecords.length;
// Table has rows
if(nRecordsLength > 0) {
elTbody.style.display = "none";
while(elTbody.lastChild) {
elTbody.removeChild(elTbody.lastChild);
}
elTbody.style.display = "";
// Set up the loop Chain to render rows
this._oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId) {
var i = oArg.nCurrentRecord,
endRecordIndex = ((oArg.nCurrentRecord+oArg.nLoopLength) > nRecordsLength) ?
nRecordsLength : (oArg.nCurrentRecord+oArg.nLoopLength),
elRow, nextSibling;
elTbody.style.display = "none";
for(; i 0) ? Math.ceil(nRecordsLength/loopN) : 1,
argument: {
nCurrentRecord: 0,//nRecordsLength-1, // Start at first Record
nLoopLength: (loopN > 0) ? loopN : nRecordsLength
},
timeout: (loopN > 0) ? 0 : -1
});
// Post-render tasks
this._oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId) {
while(elTbody.rows.length > nRecordsLength) {
elTbody.removeChild(elTbody.lastChild);
}
this._setFirstRow();
this._setLastRow();
this._setRowStripes();
this._setSelections();
}
},
scope: this,
timeout: (loopN > 0) ? 0 : -1
});
}
// Table has no rows
else {
// Set up the loop Chain to delete rows
var nTotal = elTbody.rows.length;
if(nTotal > 0) {
this._oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId) {
var i = oArg.nCurrent,
loopN = oArg.nLoopLength,
nIterEnd = (i - loopN < 0) ? -1 : i - loopN;
elTbody.style.display = "none";
for(; i>nIterEnd; i--) {
elTbody.deleteRow(-1);
}
elTbody.style.display = "";
// Set up for the next loop
oArg.nCurrent = i;
}
},
scope: this,
iterations: (loopN > 0) ? Math.ceil(nTotal/loopN) : 1,
argument: {
nCurrent: nTotal,
nLoopLength: (loopN > 0) ? loopN : nTotal
},
timeout: (loopN > 0) ? 0 : -1
});
}
}
this._runRenderChain();
},
/**
* Disables DataTable UI.
*
* @method disable
*/
disable : function() {
var elTable = this._elTable;
var elMask = this._elMask;
elMask.style.width = elTable.offsetWidth + "px";
elMask.style.height = elTable.offsetHeight + "px";
elMask.style.display = "";
this.fireEvent("disableEvent");
},
/**
* Undisables DataTable UI.
*
* @method undisable
*/
undisable : function() {
this._elMask.style.display = "none";
this.fireEvent("undisableEvent");
},
/**
* Nulls out the entire DataTable instance and related objects, removes attached
* event listeners, and clears out DOM elements inside the container. After
* calling this method, the instance reference should be expliclitly nulled by
* implementer, as in myDataTable = null. Use with caution!
*
* @method destroy
*/
destroy : function() {
// Store for later
var instanceName = this.toString();
this._oChainRender.stop();
// Destroy static resizer proxy and column proxy
DT._destroyColumnDragTargetEl();
DT._destroyColumnResizerProxyEl();
// Destroy ColumnDD and ColumnResizers
this._destroyColumnHelpers();
// Destroy all CellEditors
var oCellEditor;
for(var i=0, len=this._oColumnSet.flat.length; i oColumn.minWidth) ? nWidth : oColumn.minWidth;
// Save state
oColumn.width = nWidth;
// Resize the DOM elements
this._setColumnWidth(oColumn, nWidth+"px");
this.fireEvent("columnSetWidthEvent",{column:oColumn,width:nWidth});
}
// Unsets a width to auto-size
else if(nWidth === null) {
// Save state
oColumn.width = nWidth;
// Resize the DOM elements
this._setColumnWidth(oColumn, "auto");
this.validateColumnWidths(oColumn);
this.fireEvent("columnUnsetWidthEvent",{column:oColumn});
}
// Bug 2339454: resize then sort misaligment
this._clearTrTemplateEl();
}
else {
}
},
/**
* Sets liner DIV elements of given Column to given width. When value should be
* auto-calculated to fit content overflow is set to visible, otherwise overflow
* is set to hidden. No validations against minimum width and no updating
* Column.width value.
*
* @method _setColumnWidth
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param sWidth {String} New width value.
* @param sOverflow {String} Should be "hidden" when Column width is explicitly
* being set to a value, but should be "visible" when Column is meant to auto-fit content.
* @private
*/
_setColumnWidth : function(oColumn, sWidth, sOverflow) {
if(oColumn && (oColumn.getKeyIndex() !== null)) {
sOverflow = sOverflow || (((sWidth === '') || (sWidth === 'auto')) ? 'visible' : 'hidden');
// Dynamic style algorithm
if(!DT._bDynStylesFallback) {
this._setColumnWidthDynStyles(oColumn, sWidth, sOverflow);
}
// Dynamic function algorithm
else {
this._setColumnWidthDynFunction(oColumn, sWidth, sOverflow);
}
}
else {
}
},
/**
* Updates width of a Column's liner DIV elements by dynamically creating a
* STYLE node and writing and updating CSS style rules to it. If this fails during
* runtime, the fallback method _setColumnWidthDynFunction() will be called.
* Notes: This technique is not performant in IE6. IE7 crashes if DataTable is
* nested within another TABLE element. For these cases, it is recommended to
* use the method _setColumnWidthDynFunction by setting _bDynStylesFallback to TRUE.
*
* @method _setColumnWidthDynStyles
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param sWidth {String} New width value.
* @private
*/
_setColumnWidthDynStyles : function(oColumn, sWidth, sOverflow) {
var s = DT._elDynStyleNode,
rule;
// Create a new STYLE node
if(!s) {
s = document.createElement('style');
s.type = 'text/css';
s = document.getElementsByTagName('head').item(0).appendChild(s);
DT._elDynStyleNode = s;
}
// We have a STYLE node to update
if(s) {
// Use unique classname for this Column instance as a hook for resizing
var sClassname = "." + this.getId() + "-col-" + oColumn.getSanitizedKey() + " ." + DT.CLASS_LINER;
// Hide for performance
if(this._elTbody) {
this._elTbody.style.display = 'none';
}
rule = DT._oDynStyles[sClassname];
// The Column does not yet have a rule
if(!rule) {
if(s.styleSheet && s.styleSheet.addRule) {
s.styleSheet.addRule(sClassname,"overflow:"+sOverflow);
s.styleSheet.addRule(sClassname,'width:'+sWidth);
rule = s.styleSheet.rules[s.styleSheet.rules.length-1];
DT._oDynStyles[sClassname] = rule;
}
else if(s.sheet && s.sheet.insertRule) {
s.sheet.insertRule(sClassname+" {overflow:"+sOverflow+";width:"+sWidth+";}",s.sheet.cssRules.length);
rule = s.sheet.cssRules[s.sheet.cssRules.length-1];
DT._oDynStyles[sClassname] = rule;
}
}
// We have a rule to update
else {
rule.style.overflow = sOverflow;
rule.style.width = sWidth;
}
// Unhide
if(this._elTbody) {
this._elTbody.style.display = '';
}
}
// That was not a success, we must call the fallback routine
if(!rule) {
DT._bDynStylesFallback = true;
this._setColumnWidthDynFunction(oColumn, sWidth);
}
},
/**
* Updates width of a Column's liner DIV elements by dynamically creating a
* function to update all element style properties in one pass. Note: This
* technique is not supported in sandboxed environments that prohibit EVALs.
*
* @method _setColumnWidthDynFunction
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param sWidth {String} New width value.
* @private
*/
_setColumnWidthDynFunction : function(oColumn, sWidth, sOverflow) {
// TODO: why is this here?
if(sWidth == 'auto') {
sWidth = '';
}
// Create one function for each value of rows.length
var rowslen = this._elTbody ? this._elTbody.rows.length : 0;
// Dynamically create the function
if (!this._aDynFunctions[rowslen]) {
//Compile a custom function to do all the liner div width
//assignments at the same time. A unique function is required
//for each unique number of rows in _elTbody. This will
//result in a function declaration like:
//function (oColumn,sWidth,sOverflow) {
// var colIdx = oColumn.getKeyIndex();
// oColumn.getThLinerEl().style.overflow =
// this._elTbody.rows[0].cells[colIdx].firstChild.style.overflow =
// this._elTbody.rows[1].cells[colIdx].firstChild.style.overflow =
// ... (for all row indices in this._elTbody.rows.length - 1)
// this._elTbody.rows[99].cells[colIdx].firstChild.style.overflow =
// sOverflow;
// oColumn.getThLinerEl().style.width =
// this._elTbody.rows[0].cells[colIdx].firstChild.style.width =
// this._elTbody.rows[1].cells[colIdx].firstChild.style.width =
// ... (for all row indices in this._elTbody.rows.length - 1)
// this._elTbody.rows[99].cells[colIdx].firstChild.style.width =
// sWidth;
//}
var i,j,k;
var resizerDef = [
'var colIdx=oColumn.getKeyIndex();',
'oColumn.getThLinerEl().style.overflow='
];
for (i=rowslen-1, j=2; i >= 0; --i) {
resizerDef[j++] = 'this._elTbody.rows[';
resizerDef[j++] = i;
resizerDef[j++] = '].cells[colIdx].firstChild.style.overflow=';
}
resizerDef[j] = 'sOverflow;';
resizerDef[j+1] = 'oColumn.getThLinerEl().style.width=';
for (i=rowslen-1, k=j+2; i >= 0; --i) {
resizerDef[k++] = 'this._elTbody.rows[';
resizerDef[k++] = i;
resizerDef[k++] = '].cells[colIdx].firstChild.style.width=';
}
resizerDef[k] = 'sWidth;';
this._aDynFunctions[rowslen] =
new Function('oColumn','sWidth','sOverflow',resizerDef.join(''));
}
// Get the function to execute
var resizerFn = this._aDynFunctions[rowslen];
// TODO: Hide TBODY for performance in _setColumnWidthDynFunction?
if (resizerFn) {
resizerFn.call(this,oColumn,sWidth,sOverflow);
}
},
/**
* For one or all Columns, when Column is not hidden, width is not set, and minWidth
* and/or maxAutoWidth is set, validates auto-width against minWidth and maxAutoWidth.
*
* @method validateColumnWidths
* @param oArg.column {YAHOO.widget.Column} (optional) One Column to validate. If null, all Columns' widths are validated.
*/
validateColumnWidths : function(oColumn) {
var elColgroup = this._elColgroup;
var elColgroupClone = elColgroup.cloneNode(true);
var bNeedsValidation = false;
var allKeys = this._oColumnSet.keys;
var elThLiner;
// Validate just one Column's minWidth and/or maxAutoWidth
if(oColumn && !oColumn.hidden && !oColumn.width && (oColumn.getKeyIndex() !== null)) {
elThLiner = oColumn.getThLinerEl();
if((oColumn.minWidth > 0) && (elThLiner.offsetWidth < oColumn.minWidth)) {
elColgroupClone.childNodes[oColumn.getKeyIndex()].style.width =
oColumn.minWidth +
(parseInt(Dom.getStyle(elThLiner,"paddingLeft"),10)|0) +
(parseInt(Dom.getStyle(elThLiner,"paddingRight"),10)|0) + "px";
bNeedsValidation = true;
}
else if((oColumn.maxAutoWidth > 0) && (elThLiner.offsetWidth > oColumn.maxAutoWidth)) {
this._setColumnWidth(oColumn, oColumn.maxAutoWidth+"px", "hidden");
}
}
// Validate all Columns
else {
for(var i=0, len=allKeys.length; i 0) && (elThLiner.offsetWidth < oColumn.minWidth)) {
elColgroupClone.childNodes[i].style.width =
oColumn.minWidth +
(parseInt(Dom.getStyle(elThLiner,"paddingLeft"),10)|0) +
(parseInt(Dom.getStyle(elThLiner,"paddingRight"),10)|0) + "px";
bNeedsValidation = true;
}
else if((oColumn.maxAutoWidth > 0) && (elThLiner.offsetWidth > oColumn.maxAutoWidth)) {
this._setColumnWidth(oColumn, oColumn.maxAutoWidth+"px", "hidden");
}
}
}
}
if(bNeedsValidation) {
elColgroup.parentNode.replaceChild(elColgroupClone, elColgroup);
this._elColgroup = elColgroupClone;
}
},
/**
* Clears minWidth.
*
* @method _clearMinWidth
* @param oColumn {YAHOO.widget.Column} Which Column.
* @private
*/
_clearMinWidth : function(oColumn) {
if(oColumn.getKeyIndex() !== null) {
this._elColgroup.childNodes[oColumn.getKeyIndex()].style.width = '';
}
},
/**
* Restores minWidth.
*
* @method _restoreMinWidth
* @param oColumn {YAHOO.widget.Column} Which Column.
* @private
*/
_restoreMinWidth : function(oColumn) {
if(oColumn.minWidth && (oColumn.getKeyIndex() !== null)) {
this._elColgroup.childNodes[oColumn.getKeyIndex()].style.width = oColumn.minWidth + 'px';
}
},
/**
* Hides given Column. NOTE: You cannot hide/show nested Columns. You can only
* hide/show non-nested Columns, and top-level parent Columns (which will
* hide/show all children Columns).
*
* @method hideColumn
* @param oColumn {YAHOO.widget.Column} Column instance.
*/
hideColumn : function(oColumn) {
if(!(oColumn instanceof YAHOO.widget.Column)) {
oColumn = this.getColumn(oColumn);
}
// Only top-level Columns can get hidden due to issues in FF2 and SF3
if(oColumn && !oColumn.hidden && oColumn.getTreeIndex() !== null) {
var allrows = this.getTbodyEl().rows;
var l = allrows.length;
var allDescendants = this._oColumnSet.getDescendants(oColumn);
// Hide each nested Column
for(var i=0; i 0) {
aKeyIndexes = descKeyIndexes;
}
}
// Must be a key Column
else {
aKeyIndexes = [aKeyIndexes];
}
if(aKeyIndexes !== null) {
// Sort the indexes so we can remove from the right
aKeyIndexes.sort(function(a, b) {return YAHOO.util.Sort.compare(a, b);});
// Destroy previous THEAD
this._destroyTheadEl();
// Create new THEAD
var aOrigColumnDefs = this._oColumnSet.getDefinitions();
oColumn = aOrigColumnDefs.splice(nColTreeIndex,1)[0];
this._initColumnSet(aOrigColumnDefs);
this._initTheadEl();
// Remove COL
for(i=aKeyIndexes.length-1; i>-1; i--) {
this._removeColgroupColEl(aKeyIndexes[i]);
}
// Remove TD
var allRows = this._elTbody.rows;
if(allRows.length > 0) {
var loopN = this.get("renderLoopSize"),
loopEnd = allRows.length;
this._oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId) {
var i = oArg.nCurrentRow,
len = loopN > 0 ? Math.min(i + loopN,allRows.length) : allRows.length,
aIndexes = oArg.aIndexes,
j;
for(; i < len; ++i) {
for(j = aIndexes.length-1; j>-1; j--) {
allRows[i].removeChild(allRows[i].childNodes[aIndexes[j]]);
}
}
oArg.nCurrentRow = i;
}
},
iterations: (loopN > 0) ? Math.ceil(loopEnd/loopN) : 1,
argument: {nCurrentRow:0, aIndexes:aKeyIndexes},
scope: this,
timeout: (loopN > 0) ? 0 : -1
});
this._runRenderChain();
}
this.fireEvent("columnRemoveEvent",{column:oColumn});
return oColumn;
}
}
}
},
/**
* Inserts given Column at the index if given, otherwise at the end. NOTE: You
* can only add non-nested Columns and top-level parent Columns. You cannot add
* a nested Column to an existing parent.
*
* @method insertColumn
* @param oColumn {Object | YAHOO.widget.Column} Object literal Column
* definition or a Column instance.
* @param index {Number} (optional) New tree index.
* @return oColumn {YAHOO.widget.Column} Inserted Column instance.
*/
insertColumn : function(oColumn, index) {
// Validate Column
if(oColumn instanceof YAHOO.widget.Column) {
oColumn = oColumn.getDefinition();
}
else if(oColumn.constructor !== Object) {
return;
}
// Validate index or append new Column to the end of the ColumnSet
var oColumnSet = this._oColumnSet;
if(!lang.isValue(index) || !lang.isNumber(index)) {
index = oColumnSet.tree[0].length;
}
// Destroy previous THEAD
this._destroyTheadEl();
// Create new THEAD
var aNewColumnDefs = this._oColumnSet.getDefinitions();
aNewColumnDefs.splice(index, 0, oColumn);
this._initColumnSet(aNewColumnDefs);
this._initTheadEl();
// Need to refresh the reference
oColumnSet = this._oColumnSet;
var oNewColumn = oColumnSet.tree[0][index];
// Get key index(es) for new Column
var i, len,
descKeyIndexes = [];
var allDescendants = oColumnSet.getDescendants(oNewColumn);
for(i=0, len=allDescendants.length; i 0) {
// Sort the indexes
var newIndex = descKeyIndexes.sort(function(a, b) {return YAHOO.util.Sort.compare(a, b);})[0];
// Add COL
for(i=descKeyIndexes.length-1; i>-1; i--) {
this._insertColgroupColEl(descKeyIndexes[i]);
}
// Add TD
var allRows = this._elTbody.rows;
if(allRows.length > 0) {
var loopN = this.get("renderLoopSize"),
loopEnd = allRows.length;
// Get templates for each new TD
var aTdTemplates = [],
elTdTemplate;
for(i=0, len=descKeyIndexes.length; i 0 ? Math.min(i + loopN,allRows.length) : allRows.length,
nextSibling;
for(; i < len; ++i) {
nextSibling = allRows[i].childNodes[newIndex] || null;
for(j=descKeyIndexes.length-1; j>-1; j--) {
allRows[i].insertBefore(oArg.aTdTemplates[descKeyIndexes[j]].cloneNode(true), nextSibling);
}
}
oArg.nCurrentRow = i;
}
},
iterations: (loopN > 0) ? Math.ceil(loopEnd/loopN) : 1,
argument: {nCurrentRow:0,aTdTemplates:aTdTemplates,descKeyIndexes:descKeyIndexes},
scope: this,
timeout: (loopN > 0) ? 0 : -1
});
this._runRenderChain();
}
this.fireEvent("columnInsertEvent",{column:oColumn,index:index});
return oNewColumn;
}
},
/**
* Removes given Column and inserts into given tree index. NOTE: You
* can only reorder non-nested Columns and top-level parent Columns. You cannot
* reorder a nested Column to an existing parent.
*
* @method reorderColumn
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param index {Number} New tree index.
* @return oColumn {YAHOO.widget.Column} Reordered Column instance.
*/
reorderColumn : function(oColumn, index) {
// Validate Column and new index
if(!(oColumn instanceof YAHOO.widget.Column)) {
oColumn = this.getColumn(oColumn);
}
if(oColumn && YAHOO.lang.isNumber(index)) {
var nOrigTreeIndex = oColumn.getTreeIndex();
if((nOrigTreeIndex !== null) && (nOrigTreeIndex !== index)) {
// Which key index(es)
var i, len,
aOrigKeyIndexes = oColumn.getKeyIndex(),
allDescendants,
descKeyIndexes = [],
thisKey;
// Must be a parent Column...
if(aOrigKeyIndexes === null) {
allDescendants = this._oColumnSet.getDescendants(oColumn);
for(i=0, len=allDescendants.length; i 0) {
aOrigKeyIndexes = descKeyIndexes;
}
}
// ...or else must be a key Column
else {
aOrigKeyIndexes = [aOrigKeyIndexes];
}
if(aOrigKeyIndexes !== null) {
// Sort the indexes
aOrigKeyIndexes.sort(function(a, b) {return YAHOO.util.Sort.compare(a, b);});
// Destroy previous THEAD
this._destroyTheadEl();
// Create new THEAD
var aColumnDefs = this._oColumnSet.getDefinitions();
var oColumnDef = aColumnDefs.splice(nOrigTreeIndex,1)[0];
aColumnDefs.splice(index, 0, oColumnDef);
this._initColumnSet(aColumnDefs);
this._initTheadEl();
// Need to refresh the reference
var oNewColumn = this._oColumnSet.tree[0][index];
// What are new key index(es)
var aNewKeyIndexes = oNewColumn.getKeyIndex();
// Must be a parent Column
if(aNewKeyIndexes === null) {
descKeyIndexes = [];
allDescendants = this._oColumnSet.getDescendants(oNewColumn);
for(i=0, len=allDescendants.length; i 0) {
aNewKeyIndexes = descKeyIndexes;
}
}
// Must be a key Column
else {
aNewKeyIndexes = [aNewKeyIndexes];
}
// Sort the new indexes and grab the first one for the new location
var newIndex = aNewKeyIndexes.sort(function(a, b) {return YAHOO.util.Sort.compare(a, b);})[0];
// Reorder COL
this._reorderColgroupColEl(aOrigKeyIndexes, newIndex);
// Reorder TD
var allRows = this._elTbody.rows;
if(allRows.length > 0) {
var loopN = this.get("renderLoopSize"),
loopEnd = allRows.length;
this._oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId) {
var i = oArg.nCurrentRow, j, tmpTds, nextSibling,
len = loopN > 0 ? Math.min(i + loopN,allRows.length) : allRows.length,
aIndexes = oArg.aIndexes, thisTr;
// For each row
for(; i < len; ++i) {
tmpTds = [];
thisTr = allRows[i];
// Remove each TD
for(j=aIndexes.length-1; j>-1; j--) {
tmpTds.push(thisTr.removeChild(thisTr.childNodes[aIndexes[j]]));
}
// Insert each TD
nextSibling = thisTr.childNodes[newIndex] || null;
for(j=tmpTds.length-1; j>-1; j--) {
thisTr.insertBefore(tmpTds[j], nextSibling);
}
}
oArg.nCurrentRow = i;
}
},
iterations: (loopN > 0) ? Math.ceil(loopEnd/loopN) : 1,
argument: {nCurrentRow:0, aIndexes:aOrigKeyIndexes},
scope: this,
timeout: (loopN > 0) ? 0 : -1
});
this._runRenderChain();
}
this.fireEvent("columnReorderEvent",{column:oNewColumn});
return oNewColumn;
}
}
}
},
/**
* Selects given Column. NOTE: You cannot select/unselect nested Columns. You can only
* select/unselect non-nested Columns, and bottom-level key Columns.
*
* @method selectColumn
* @param column {HTMLElement | String | Number} DOM reference or ID string to a
* TH/TD element (or child of a TH/TD element), a Column key, or a ColumnSet key index.
*/
selectColumn : function(oColumn) {
oColumn = this.getColumn(oColumn);
if(oColumn && !oColumn.selected) {
// Only bottom-level Columns can get hidden
if(oColumn.getKeyIndex() !== null) {
oColumn.selected = true;
// Update head cell
var elTh = oColumn.getThEl();
Dom.addClass(elTh,DT.CLASS_SELECTED);
// Update body cells
var allRows = this.getTbodyEl().rows;
var oChainRender = this._oChainRender;
oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId && allRows[oArg.rowIndex] && allRows[oArg.rowIndex].cells[oArg.cellIndex]) {
Dom.addClass(allRows[oArg.rowIndex].cells[oArg.cellIndex],DT.CLASS_SELECTED);
}
oArg.rowIndex++;
},
scope: this,
iterations: allRows.length,
argument: {rowIndex:0,cellIndex:oColumn.getKeyIndex()}
});
this._clearTrTemplateEl();
this._elTbody.style.display = "none";
this._runRenderChain();
this._elTbody.style.display = "";
this.fireEvent("columnSelectEvent",{column:oColumn});
}
else {
}
}
},
/**
* Unselects given Column. NOTE: You cannot select/unselect nested Columns. You can only
* select/unselect non-nested Columns, and bottom-level key Columns.
*
* @method unselectColumn
* @param column {HTMLElement | String | Number} DOM reference or ID string to a
* TH/TD element (or child of a TH/TD element), a Column key, or a ColumnSet key index.
*/
unselectColumn : function(oColumn) {
oColumn = this.getColumn(oColumn);
if(oColumn && oColumn.selected) {
// Only bottom-level Columns can get hidden
if(oColumn.getKeyIndex() !== null) {
oColumn.selected = false;
// Update head cell
var elTh = oColumn.getThEl();
Dom.removeClass(elTh,DT.CLASS_SELECTED);
// Update body cells
var allRows = this.getTbodyEl().rows;
var oChainRender = this._oChainRender;
oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId && allRows[oArg.rowIndex] && allRows[oArg.rowIndex].cells[oArg.cellIndex]) {
Dom.removeClass(allRows[oArg.rowIndex].cells[oArg.cellIndex],DT.CLASS_SELECTED);
}
oArg.rowIndex++;
},
scope: this,
iterations:allRows.length,
argument: {rowIndex:0,cellIndex:oColumn.getKeyIndex()}
});
this._clearTrTemplateEl();
this._elTbody.style.display = "none";
this._runRenderChain();
this._elTbody.style.display = "";
this.fireEvent("columnUnselectEvent",{column:oColumn});
}
else {
}
}
},
/**
* Returns an array selected Column instances.
*
* @method getSelectedColumns
* @return {YAHOO.widget.Column[]} Array of Column instances.
*/
getSelectedColumns : function(oColumn) {
var selectedColumns = [];
var aKeys = this._oColumnSet.keys;
for(var i=0,len=aKeys.length; i this._oRecordSet.getLength())) {
return;
}
if(oData && lang.isObject(oData)) {
var oRecord = this._oRecordSet.addRecord(oData, index);
if(oRecord) {
var recIndex;
var oPaginator = this.get('paginator');
// Paginated
if (oPaginator) {
// Update the paginator's totalRecords
var totalRecords = oPaginator.get('totalRecords');
if (totalRecords !== widget.Paginator.VALUE_UNLIMITED) {
oPaginator.set('totalRecords',totalRecords + 1);
}
recIndex = this.getRecordIndex(oRecord);
var endRecIndex = (oPaginator.getPageRecords())[1];
// New record affects the view
if (recIndex <= endRecIndex) {
// Defer UI updates to the render method
this.render();
}
this.fireEvent("rowAddEvent", {record:oRecord});
return;
}
// Not paginated
else {
recIndex = this.getTrIndex(oRecord);
if(lang.isNumber(recIndex)) {
// Add the TR element
this._oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId) {
var oRecord = oArg.record;
var recIndex = oArg.recIndex;
var elNewTr = this._addTrEl(oRecord);
if(elNewTr) {
var elNext = (this._elTbody.rows[recIndex]) ? this._elTbody.rows[recIndex] : null;
this._elTbody.insertBefore(elNewTr, elNext);
// Set FIRST/LAST
if(recIndex === 0) {
this._setFirstRow();
}
if(elNext === null) {
this._setLastRow();
}
// Set EVEN/ODD
this._setRowStripes();
this.hideTableMessage();
this.fireEvent("rowAddEvent", {record:oRecord});
}
}
},
argument: {record: oRecord, recIndex: recIndex},
scope: this,
timeout: (this.get("renderLoopSize") > 0) ? 0 : -1
});
this._runRenderChain();
return;
}
}
}
}
},
/**
* Convenience method to add multiple rows.
*
* @method addRows
* @param aData {Object[]} Array of object literal data for the rows.
* @param index {Number} (optional) RecordSet position index at which to add data.
*/
addRows : function(aData, index) {
if(lang.isNumber(index) && (index < 0 || index > this._oRecordSet.getLength())) {
return;
}
if(lang.isArray(aData)) {
var aRecords = this._oRecordSet.addRecords(aData, index);
if(aRecords) {
var recIndex = this.getRecordIndex(aRecords[0]);
// Paginated
var oPaginator = this.get('paginator');
if (oPaginator) {
// Update the paginator's totalRecords
var totalRecords = oPaginator.get('totalRecords');
if (totalRecords !== widget.Paginator.VALUE_UNLIMITED) {
oPaginator.set('totalRecords',totalRecords + aRecords.length);
}
var endRecIndex = (oPaginator.getPageRecords())[1];
// At least one of the new records affects the view
if (recIndex <= endRecIndex) {
this.render();
}
this.fireEvent("rowsAddEvent", {records:aRecords});
return;
}
// Not paginated
else {
// Add the TR elements
var loopN = this.get("renderLoopSize");
var loopEnd = recIndex + aData.length;
var nRowsNeeded = (loopEnd - recIndex); // how many needed
var isLast = (recIndex >= this._elTbody.rows.length);
this._oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId) {
var aRecords = oArg.aRecords,
i = oArg.nCurrentRow,
j = oArg.nCurrentRecord,
len = loopN > 0 ? Math.min(i + loopN,loopEnd) : loopEnd,
df = document.createDocumentFragment(),
elNext = (this._elTbody.rows[i]) ? this._elTbody.rows[i] : null;
for(; i < len; i++, j++) {
df.appendChild(this._addTrEl(aRecords[j]));
}
this._elTbody.insertBefore(df, elNext);
oArg.nCurrentRow = i;
oArg.nCurrentRecord = j;
}
},
iterations: (loopN > 0) ? Math.ceil(loopEnd/loopN) : 1,
argument: {nCurrentRow:recIndex,nCurrentRecord:0,aRecords:aRecords},
scope: this,
timeout: (loopN > 0) ? 0 : -1
});
this._oChainRender.add({
method: function(oArg) {
var recIndex = oArg.recIndex;
// Set FIRST/LAST
if(recIndex === 0) {
this._setFirstRow();
}
if(oArg.isLast) {
this._setLastRow();
}
// Set EVEN/ODD
this._setRowStripes();
this.fireEvent("rowsAddEvent", {records:aRecords});
},
argument: {recIndex: recIndex, isLast: isLast},
scope: this,
timeout: -1 // Needs to run immediately after the DOM insertions above
});
this._runRenderChain();
this.hideTableMessage();
return;
}
}
}
},
/**
* For the given row, updates the associated Record with the given data. If the
* row is on current page, the corresponding DOM elements are also updated.
*
* @method updateRow
* @param row {YAHOO.widget.Record | Number | HTMLElement | String}
* Which row to update: By Record instance, by Record's RecordSet
* position index, by HTMLElement reference to the TR element, or by ID string
* of the TR element.
* @param oData {Object} Object literal of data for the row.
*/
updateRow : function(row, oData) {
var index = row;
if (!lang.isNumber(index)) {
index = this.getRecordIndex(row);
}
// Update the Record
if(lang.isNumber(index) && (index >= 0)) {
var oRecordSet = this._oRecordSet,
oldRecord = oRecordSet.getRecord(index);
if(oldRecord) {
var updatedRecord = this._oRecordSet.setRecord(oData, index),
elRow = this.getTrEl(oldRecord),
// Copy data from the Record for the event that gets fired later
oldData = oldRecord ? oldRecord.getData() : null;
if(updatedRecord) {
// Update selected rows as necessary
var tracker = this._aSelections || [],
i=0,
oldId = oldRecord.getId(),
newId = updatedRecord.getId();
for(; i= pageStartIndex) || (index <= pageLastIndex)) {
this.render();
}
}
else {
if(elRow) {
this._updateTrEl(elRow, updatedRecord);
}
else {
this.getTbodyEl().appendChild(this._addTrEl(updatedRecord));
}
}
this.fireEvent("rowUpdateEvent", {record:updatedRecord, oldData:oldData});
}
},
scope: this,
timeout: (this.get("renderLoopSize") > 0) ? 0 : -1
});
this._runRenderChain();
return;
}
}
}
return;
},
/**
* Starting with the given row, updates associated Records with the given data.
* The number of rows to update are determined by the array of data provided.
* Undefined data (i.e., not an object literal) causes a row to be skipped. If
* any of the rows are on current page, the corresponding DOM elements are also
* updated.
*
* @method updateRows
* @param startrow {YAHOO.widget.Record | Number | HTMLElement | String}
* Starting row to update: By Record instance, by Record's RecordSet
* position index, by HTMLElement reference to the TR element, or by ID string
* of the TR element.
* @param aData {Object[]} Array of object literal of data for the rows.
*/
updateRows : function(startrow, aData) {
if(lang.isArray(aData)) {
var startIndex = startrow,
oRecordSet = this._oRecordSet;
if (!lang.isNumber(startrow)) {
startIndex = this.getRecordIndex(startrow);
}
if(lang.isNumber(startIndex) && (startIndex >= 0) && (startIndex < oRecordSet.getLength())) {
var lastIndex = startIndex + aData.length,
aOldRecords = oRecordSet.getRecords(startIndex, aData.length),
aNewRecords = oRecordSet.setRecords(aData, startIndex);
if(aNewRecords) {
// Update selected rows as necessary
var tracker = this._aSelections || [],
i=0, j, newId, oldId;
for(; i= pageStartIndex) || (lastIndex <= pageLastIndex)) {
this.render();
}
this.fireEvent("rowsAddEvent", {newRecords:aNewRecords, oldRecords:aOldRecords});
return;
}
// Not paginated
else {
// Update the TR elements
var loopN = this.get("renderLoopSize"),
rowCount = aData.length, // how many needed
lastRowIndex = this._elTbody.rows.length,
isLast = (lastIndex >= lastRowIndex),
isAdding = (lastIndex > lastRowIndex);
this._oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId) {
var aRecords = oArg.aRecords,
i = oArg.nCurrentRow,
j = oArg.nDataPointer,
len = loopN > 0 ? Math.min(i+loopN, startIndex+aRecords.length) : startIndex+aRecords.length;
for(; i < len; i++,j++) {
if(isAdding && (i>=lastRowIndex)) {
this._elTbody.appendChild(this._addTrEl(aRecords[j]));
}
else {
this._updateTrEl(this._elTbody.rows[i], aRecords[j]);
}
}
oArg.nCurrentRow = i;
oArg.nDataPointer = j;
}
},
iterations: (loopN > 0) ? Math.ceil(rowCount/loopN) : 1,
argument: {nCurrentRow:startIndex,aRecords:aNewRecords,nDataPointer:0,isAdding:isAdding},
scope: this,
timeout: (loopN > 0) ? 0 : -1
});
this._oChainRender.add({
method: function(oArg) {
var recIndex = oArg.recIndex;
// Set FIRST/LAST
if(recIndex === 0) {
this._setFirstRow();
}
if(oArg.isLast) {
this._setLastRow();
}
// Set EVEN/ODD
this._setRowStripes();
this.fireEvent("rowsAddEvent", {newRecords:aNewRecords, oldRecords:aOldRecords});
},
argument: {recIndex: startIndex, isLast: isLast},
scope: this,
timeout: -1 // Needs to run immediately after the DOM insertions above
});
this._runRenderChain();
this.hideTableMessage();
return;
}
}
}
}
},
/**
* Deletes the given row's Record from the RecordSet. If the row is on current page,
* the corresponding DOM elements are also deleted.
*
* @method deleteRow
* @param row {HTMLElement | String | Number} DOM element reference or ID string
* to DataTable page element or RecordSet index.
*/
deleteRow : function(row) {
var nRecordIndex = (lang.isNumber(row)) ? row : this.getRecordIndex(row);
if(lang.isNumber(nRecordIndex)) {
var oRecord = this.getRecord(nRecordIndex);
if(oRecord) {
var nTrIndex = this.getTrIndex(nRecordIndex);
// Remove from selection tracker if there
var sRecordId = oRecord.getId();
var tracker = this._aSelections || [];
for(var j=tracker.length-1; j>-1; j--) {
if((lang.isString(tracker[j]) && (tracker[j] === sRecordId)) ||
(lang.isObject(tracker[j]) && (tracker[j].recordId === sRecordId))) {
tracker.splice(j,1);
}
}
// Delete Record from RecordSet
var oData = this._oRecordSet.deleteRecord(nRecordIndex);
// Update the UI
if(oData) {
// If paginated and the deleted row was on this or a prior page, just
// re-render
var oPaginator = this.get('paginator');
if (oPaginator) {
// Update the paginator's totalRecords
var totalRecords = oPaginator.get('totalRecords'),
// must capture before the totalRecords change because
// Paginator shifts to previous page automatically
rng = oPaginator.getPageRecords();
if (totalRecords !== widget.Paginator.VALUE_UNLIMITED) {
oPaginator.set('totalRecords',totalRecords - 1);
}
// The deleted record was on this or a prior page, re-render
if (!rng || nRecordIndex <= rng[1]) {
this.render();
}
this._oChainRender.add({
method: function() {
if((this instanceof DT) && this._sId) {
this.fireEvent("rowDeleteEvent", {recordIndex:nRecordIndex, oldData:oData, trElIndex:nTrIndex});
}
},
scope: this,
timeout: (this.get("renderLoopSize") > 0) ? 0 : -1
});
this._runRenderChain();
}
// Not paginated
else {
if(lang.isNumber(nTrIndex)) {
this._oChainRender.add({
method: function() {
if((this instanceof DT) && this._sId) {
var isLast = (nRecordIndex === this._oRecordSet.getLength());//(nTrIndex == this.getLastTrEl().sectionRowIndex);
this._deleteTrEl(nTrIndex);
// Post-delete tasks
if(this._elTbody.rows.length > 0) {
// Set FIRST/LAST
if(nTrIndex === 0) {
this._setFirstRow();
}
if(isLast) {
this._setLastRow();
}
// Set EVEN/ODD
if(nTrIndex != this._elTbody.rows.length) {
this._setRowStripes(nTrIndex);
}
}
this.fireEvent("rowDeleteEvent", {recordIndex:nRecordIndex,oldData:oData, trElIndex:nTrIndex});
}
},
scope: this,
timeout: (this.get("renderLoopSize") > 0) ? 0 : -1
});
this._runRenderChain();
return;
}
}
}
}
}
return null;
},
/**
* Convenience method to delete multiple rows.
*
* @method deleteRows
* @param row {HTMLElement | String | Number} DOM element reference or ID string
* to DataTable page element or RecordSet index.
* @param count {Number} (optional) How many rows to delete. A negative value
* will delete towards the beginning.
*/
deleteRows : function(row, count) {
var nRecordIndex = (lang.isNumber(row)) ? row : this.getRecordIndex(row);
if(lang.isNumber(nRecordIndex)) {
var oRecord = this.getRecord(nRecordIndex);
if(oRecord) {
var nTrIndex = this.getTrIndex(nRecordIndex);
// Remove from selection tracker if there
var sRecordId = oRecord.getId();
var tracker = this._aSelections || [];
for(var j=tracker.length-1; j>-1; j--) {
if((lang.isString(tracker[j]) && (tracker[j] === sRecordId)) ||
(lang.isObject(tracker[j]) && (tracker[j].recordId === sRecordId))) {
tracker.splice(j,1);
}
}
// Delete Record from RecordSet
var highIndex = nRecordIndex;
var lowIndex = nRecordIndex;
// Validate count and account for negative value
if(count && lang.isNumber(count)) {
highIndex = (count > 0) ? nRecordIndex + count -1 : nRecordIndex;
lowIndex = (count > 0) ? nRecordIndex : nRecordIndex + count + 1;
count = (count > 0) ? count : count*-1;
if(lowIndex < 0) {
lowIndex = 0;
count = highIndex - lowIndex + 1;
}
}
else {
count = 1;
}
var aData = this._oRecordSet.deleteRecords(lowIndex, count);
// Update the UI
if(aData) {
var oPaginator = this.get('paginator'),
loopN = this.get("renderLoopSize");
// If paginated and the deleted row was on this or a prior page, just
// re-render
if (oPaginator) {
// Update the paginator's totalRecords
var totalRecords = oPaginator.get('totalRecords'),
// must capture before the totalRecords change because
// Paginator shifts to previous page automatically
rng = oPaginator.getPageRecords();
if (totalRecords !== widget.Paginator.VALUE_UNLIMITED) {
oPaginator.set('totalRecords',totalRecords - aData.length);
}
// The records were on this or a prior page, re-render
if (!rng || lowIndex <= rng[1]) {
this.render();
}
this._oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId) {
this.fireEvent("rowsDeleteEvent", {recordIndex:lowIndex, oldData:aData, count:count});
}
},
scope: this,
timeout: (loopN > 0) ? 0 : -1
});
this._runRenderChain();
return;
}
// Not paginated
else {
if(lang.isNumber(nTrIndex)) {
// Delete the TR elements starting with highest index
var loopEnd = lowIndex;
var nRowsNeeded = count; // how many needed
this._oChainRender.add({
method: function(oArg) {
if((this instanceof DT) && this._sId) {
var i = oArg.nCurrentRow,
len = (loopN > 0) ? (Math.max(i - loopN,loopEnd)-1) : loopEnd-1;
for(; i>len; --i) {
this._deleteTrEl(i);
}
oArg.nCurrentRow = i;
}
},
iterations: (loopN > 0) ? Math.ceil(count/loopN) : 1,
argument: {nCurrentRow:highIndex},
scope: this,
timeout: (loopN > 0) ? 0 : -1
});
this._oChainRender.add({
method: function() {
// Post-delete tasks
if(this._elTbody.rows.length > 0) {
this._setFirstRow();
this._setLastRow();
this._setRowStripes();
}
this.fireEvent("rowsDeleteEvent", {recordIndex:lowIndex, oldData:aData, count:count});
},
scope: this,
timeout: -1 // Needs to run immediately after the DOM deletions above
});
this._runRenderChain();
return;
}
}
}
}
}
return null;
},
// CELL FUNCTIONS
/**
* Outputs markup into the given TD based on given Record.
*
* @method formatCell
* @param elLiner {HTMLElement} The liner DIV element within the TD.
* @param oRecord {YAHOO.widget.Record} (Optional) Record instance.
* @param oColumn {YAHOO.widget.Column} (Optional) Column instance.
*/
formatCell : function(elLiner, oRecord, oColumn) {
if(!oRecord) {
oRecord = this.getRecord(elLiner);
}
if(!oColumn) {
oColumn = this.getColumn(elLiner.parentNode.cellIndex);
}
if(oRecord && oColumn) {
var sField = oColumn.field;
var oData = oRecord.getData(sField);
var fnFormatter = typeof oColumn.formatter === 'function' ?
oColumn.formatter :
DT.Formatter[oColumn.formatter+''] ||
DT.Formatter.defaultFormatter;
// Apply special formatter
if(fnFormatter) {
fnFormatter.call(this, elLiner, oRecord, oColumn, oData);
}
else {
elLiner.innerHTML = oData;
}
this.fireEvent("cellFormatEvent", {record:oRecord, column:oColumn, key:oColumn.key, el:elLiner});
}
else {
}
},
/**
* For the given row and column, updates the Record with the given data. If the
* cell is on current page, the corresponding DOM elements are also updated.
*
* @method updateCell
* @param oRecord {YAHOO.widget.Record} Record instance.
* @param oColumn {YAHOO.widget.Column | String | Number} A Column key, or a ColumnSet key index.
* @param oData {Object} New data value for the cell.
*/
updateCell : function(oRecord, oColumn, oData) {
// Validate Column and Record
oColumn = (oColumn instanceof YAHOO.widget.Column) ? oColumn : this.getColumn(oColumn);
if(oColumn && oColumn.getField() && (oRecord instanceof YAHOO.widget.Record)) {
var sKey = oColumn.getField(),
// Copy data from the Record for the event that gets fired later
//var oldData = YAHOO.widget.DataTable._cloneObject(oRecord.getData());
oldData = oRecord.getData(sKey);
// Update Record with new data
this._oRecordSet.updateRecordValue(oRecord, sKey, oData);
// Update the TD only if row is on current page
var elTd = this.getTdEl({record: oRecord, column: oColumn});
if(elTd) {
this._oChainRender.add({
method: function() {
if((this instanceof DT) && this._sId) {
this.formatCell(elTd.firstChild);
this.fireEvent("cellUpdateEvent", {record:oRecord, column: oColumn, oldData:oldData});
}
},
scope: this,
timeout: (this.get("renderLoopSize") > 0) ? 0 : -1
});
this._runRenderChain();
}
else {
this.fireEvent("cellUpdateEvent", {record:oRecord, column: oColumn, oldData:oldData});
}
}
},
// PAGINATION
/**
* Method executed during set() operation for the "paginator" attribute.
* Adds and/or severs event listeners between DataTable and Paginator
*
* @method _updatePaginator
* @param newPag {Paginator} Paginator instance (or null) for DataTable to use
* @private
*/
_updatePaginator : function (newPag) {
var oldPag = this.get('paginator');
if (oldPag && newPag !== oldPag) {
oldPag.unsubscribe('changeRequest', this.onPaginatorChangeRequest, this, true);
}
if (newPag) {
newPag.subscribe('changeRequest', this.onPaginatorChangeRequest, this, true);
}
},
/**
* Update the UI infrastructure in response to a "paginator" attribute change.
*
* @method _handlePaginatorChange
* @param e {Object} Change event object containing keys 'type','newValue',
* and 'prevValue'
* @private
*/
_handlePaginatorChange : function (e) {
if (e.prevValue === e.newValue) { return; }
var newPag = e.newValue,
oldPag = e.prevValue,
containers = this._defaultPaginatorContainers();
if (oldPag) {
if (oldPag.getContainerNodes()[0] == containers[0]) {
oldPag.set('containers',[]);
}
oldPag.destroy();
// Convenience: share the default containers if possible.
// Otherwise, remove the default containers from the DOM.
if (containers[0]) {
if (newPag && !newPag.getContainerNodes().length) {
newPag.set('containers',containers);
} else {
// No new Paginator to use existing containers, OR new
// Paginator has configured containers.
for (var i = containers.length - 1; i >= 0; --i) {
if (containers[i]) {
containers[i].parentNode.removeChild(containers[i]);
}
}
}
}
}
if (!this._bInit) {
this.render();
}
if (newPag) {
this.renderPaginator();
}
},
/**
* Returns the default containers used for Paginators. If create param is
* passed, the containers will be created and added to the DataTable container.
*
* @method _defaultPaginatorContainers
* @param create {boolean} Create the default containers if not found
* @private
*/
_defaultPaginatorContainers : function (create) {
var above_id = this._sId + '-paginator0',
below_id = this._sId + '-paginator1',
above = Dom.get(above_id),
below = Dom.get(below_id);
if (create && (!above || !below)) {
// One above and one below the table
if (!above) {
above = document.createElement('div');
above.id = above_id;
Dom.addClass(above, DT.CLASS_PAGINATOR);
this._elContainer.insertBefore(above,this._elContainer.firstChild);
}
if (!below) {
below = document.createElement('div');
below.id = below_id;
Dom.addClass(below, DT.CLASS_PAGINATOR);
this._elContainer.appendChild(below);
}
}
return [above,below];
},
/**
* Calls Paginator's destroy() method
*
* @method _destroyPaginator
* @private
*/
_destroyPaginator : function () {
var oldPag = this.get('paginator');
if (oldPag) {
oldPag.destroy();
}
},
/**
* Renders the Paginator to the DataTable UI
*
* @method renderPaginator
*/
renderPaginator : function () {
var pag = this.get("paginator");
if (!pag) { return; }
// Add the containers if the Paginator is not configured with containers
if (!pag.getContainerNodes().length) {
pag.set('containers',this._defaultPaginatorContainers(true));
}
pag.render();
},
/**
* Overridable method gives implementers a hook to show loading message before
* changing Paginator value.
*
* @method doBeforePaginatorChange
* @param oPaginatorState {Object} An object literal describing the proposed pagination state.
* @return {Boolean} Return true to continue changing Paginator value.
*/
doBeforePaginatorChange : function(oPaginatorState) {
this.showTableMessage(this.get("MSG_LOADING"), DT.CLASS_LOADING);
return true;
},
/**
* Responds to new Pagination states. By default, updates the UI to reflect the
* new state. If "dynamicData" is true, current selections are purged before
* a request is sent to the DataSource for data for the new state (using the
* request returned by "generateRequest()").
*
* @method onPaginatorChangeRequest
* @param oPaginatorState {Object} An object literal describing the proposed pagination state.
*/
onPaginatorChangeRequest : function (oPaginatorState) {
var ok = this.doBeforePaginatorChange(oPaginatorState);
if(ok) {
// Server-side pagination
if(this.get("dynamicData")) {
// Get the current state
var oState = this.getState();
// Update pagination values
oState.pagination = oPaginatorState;
// Get the request for the new state
var request = this.get("generateRequest")(oState, this);
// Purge selections
this.unselectAllRows();
this.unselectAllCells();
// Get the new data from the server
var callback = {
success : this.onDataReturnSetRows,
failure : this.onDataReturnSetRows,
argument : oState, // Pass along the new state to the callback
scope : this
};
this._oDataSource.sendRequest(request, callback);
}
// Client-side pagination
else {
// Set the core pagination values silently (the second param)
// to avoid looping back through the changeRequest mechanism
oPaginatorState.paginator.setStartIndex(oPaginatorState.recordOffset,true);
oPaginatorState.paginator.setRowsPerPage(oPaginatorState.rowsPerPage,true);
// Update the UI
this.render();
}
}
else {
}
},
// SELECTION/HIGHLIGHTING
/*
* Reference to last highlighted cell element
*
* @property _elLastHighlightedTd
* @type HTMLElement
* @private
*/
_elLastHighlightedTd : null,
/*
* ID string of last highlighted row element
*
* @property _sLastHighlightedTrElId
* @type String
* @private
*/
//_sLastHighlightedTrElId : null,
/**
* Array to track row selections (by sRecordId) and/or cell selections
* (by {recordId:sRecordId, columnKey:sColumnKey})
*
* @property _aSelections
* @type Object[]
* @private
*/
_aSelections : null,
/**
* Record instance of the row selection anchor.
*
* @property _oAnchorRecord
* @type YAHOO.widget.Record
* @private
*/
_oAnchorRecord : null,
/**
* Object literal representing cell selection anchor:
* {recordId:sRecordId, columnKey:sColumnKey}.
*
* @property _oAnchorCell
* @type Object
* @private
*/
_oAnchorCell : null,
/**
* Convenience method to remove the class YAHOO.widget.DataTable.CLASS_SELECTED
* from all TR elements on the page.
*
* @method _unselectAllTrEls
* @private
*/
_unselectAllTrEls : function() {
var selectedRows = Dom.getElementsByClassName(DT.CLASS_SELECTED,"tr",this._elTbody);
Dom.removeClass(selectedRows, DT.CLASS_SELECTED);
},
/**
* Returns object literal of values that represent the selection trigger. Used
* to determine selection behavior resulting from a key event.
*
* @method _getSelectionTrigger
* @private
*/
_getSelectionTrigger : function() {
var sMode = this.get("selectionMode");
var oTrigger = {};
var oTriggerCell, oTriggerRecord, nTriggerRecordIndex, elTriggerRow, nTriggerTrIndex;
// Cell mode
if((sMode == "cellblock") || (sMode == "cellrange") || (sMode == "singlecell")) {
oTriggerCell = this.getLastSelectedCell();
// No selected cells found
if(!oTriggerCell) {
return null;
}
else {
oTriggerRecord = this.getRecord(oTriggerCell.recordId);
nTriggerRecordIndex = this.getRecordIndex(oTriggerRecord);
elTriggerRow = this.getTrEl(oTriggerRecord);
nTriggerTrIndex = this.getTrIndex(elTriggerRow);
// Selected cell not found on this page
if(nTriggerTrIndex === null) {
return null;
}
else {
oTrigger.record = oTriggerRecord;
oTrigger.recordIndex = nTriggerRecordIndex;
oTrigger.el = this.getTdEl(oTriggerCell);
oTrigger.trIndex = nTriggerTrIndex;
oTrigger.column = this.getColumn(oTriggerCell.columnKey);
oTrigger.colKeyIndex = oTrigger.column.getKeyIndex();
oTrigger.cell = oTriggerCell;
return oTrigger;
}
}
}
// Row mode
else {
oTriggerRecord = this.getLastSelectedRecord();
// No selected rows found
if(!oTriggerRecord) {
return null;
}
else {
// Selected row found, but is it on current page?
oTriggerRecord = this.getRecord(oTriggerRecord);
nTriggerRecordIndex = this.getRecordIndex(oTriggerRecord);
elTriggerRow = this.getTrEl(oTriggerRecord);
nTriggerTrIndex = this.getTrIndex(elTriggerRow);
// Selected row not found on this page
if(nTriggerTrIndex === null) {
return null;
}
else {
oTrigger.record = oTriggerRecord;
oTrigger.recordIndex = nTriggerRecordIndex;
oTrigger.el = elTriggerRow;
oTrigger.trIndex = nTriggerTrIndex;
return oTrigger;
}
}
}
},
/**
* Returns object literal of values that represent the selection anchor. Used
* to determine selection behavior resulting from a user event.
*
* @method _getSelectionAnchor
* @param oTrigger {Object} (Optional) Object literal of selection trigger values
* (for key events).
* @private
*/
_getSelectionAnchor : function(oTrigger) {
var sMode = this.get("selectionMode");
var oAnchor = {};
var oAnchorRecord, nAnchorRecordIndex, nAnchorTrIndex;
// Cell mode
if((sMode == "cellblock") || (sMode == "cellrange") || (sMode == "singlecell")) {
// Validate anchor cell
var oAnchorCell = this._oAnchorCell;
if(!oAnchorCell) {
if(oTrigger) {
oAnchorCell = this._oAnchorCell = oTrigger.cell;
}
else {
return null;
}
}
oAnchorRecord = this._oAnchorCell.record;
nAnchorRecordIndex = this._oRecordSet.getRecordIndex(oAnchorRecord);
nAnchorTrIndex = this.getTrIndex(oAnchorRecord);
// If anchor cell is not on this page...
if(nAnchorTrIndex === null) {
// ...set TR index equal to top TR
if(nAnchorRecordIndex < this.getRecordIndex(this.getFirstTrEl())) {
nAnchorTrIndex = 0;
}
// ...set TR index equal to bottom TR
else {
nAnchorTrIndex = this.getRecordIndex(this.getLastTrEl());
}
}
oAnchor.record = oAnchorRecord;
oAnchor.recordIndex = nAnchorRecordIndex;
oAnchor.trIndex = nAnchorTrIndex;
oAnchor.column = this._oAnchorCell.column;
oAnchor.colKeyIndex = oAnchor.column.getKeyIndex();
oAnchor.cell = oAnchorCell;
return oAnchor;
}
// Row mode
else {
oAnchorRecord = this._oAnchorRecord;
if(!oAnchorRecord) {
if(oTrigger) {
oAnchorRecord = this._oAnchorRecord = oTrigger.record;
}
else {
return null;
}
}
nAnchorRecordIndex = this.getRecordIndex(oAnchorRecord);
nAnchorTrIndex = this.getTrIndex(oAnchorRecord);
// If anchor row is not on this page...
if(nAnchorTrIndex === null) {
// ...set TR index equal to top TR
if(nAnchorRecordIndex < this.getRecordIndex(this.getFirstTrEl())) {
nAnchorTrIndex = 0;
}
// ...set TR index equal to bottom TR
else {
nAnchorTrIndex = this.getRecordIndex(this.getLastTrEl());
}
}
oAnchor.record = oAnchorRecord;
oAnchor.recordIndex = nAnchorRecordIndex;
oAnchor.trIndex = nAnchorTrIndex;
return oAnchor;
}
},
/**
* Determines selection behavior resulting from a mouse event when selection mode
* is set to "standard".
*
* @method _handleStandardSelectionByMouse
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
* @private
*/
_handleStandardSelectionByMouse : function(oArgs) {
var elTarget = oArgs.target;
// Validate target row
var elTargetRow = this.getTrEl(elTarget);
if(elTargetRow) {
var e = oArgs.event;
var bSHIFT = e.shiftKey;
var bCTRL = e.ctrlKey || ((navigator.userAgent.toLowerCase().indexOf("mac") != -1) && e.metaKey);
var oTargetRecord = this.getRecord(elTargetRow);
var nTargetRecordIndex = this._oRecordSet.getRecordIndex(oTargetRecord);
var oAnchor = this._getSelectionAnchor();
var i;
// Both SHIFT and CTRL
if(bSHIFT && bCTRL) {
// Validate anchor
if(oAnchor) {
if(this.isSelected(oAnchor.record)) {
// Select all rows between anchor row and target row, including target row
if(oAnchor.recordIndex < nTargetRecordIndex) {
for(i=oAnchor.recordIndex+1; i<=nTargetRecordIndex; i++) {
if(!this.isSelected(i)) {
this.selectRow(i);
}
}
}
// Select all rows between target row and anchor row, including target row
else {
for(i=oAnchor.recordIndex-1; i>=nTargetRecordIndex; i--) {
if(!this.isSelected(i)) {
this.selectRow(i);
}
}
}
}
else {
// Unselect all rows between anchor row and target row
if(oAnchor.recordIndex < nTargetRecordIndex) {
for(i=oAnchor.recordIndex+1; i<=nTargetRecordIndex-1; i++) {
if(this.isSelected(i)) {
this.unselectRow(i);
}
}
}
// Unselect all rows between target row and anchor row
else {
for(i=nTargetRecordIndex+1; i<=oAnchor.recordIndex-1; i++) {
if(this.isSelected(i)) {
this.unselectRow(i);
}
}
}
// Select the target row
this.selectRow(oTargetRecord);
}
}
// Invalid anchor
else {
// Set anchor
this._oAnchorRecord = oTargetRecord;
// Toggle selection of target
if(this.isSelected(oTargetRecord)) {
this.unselectRow(oTargetRecord);
}
else {
this.selectRow(oTargetRecord);
}
}
}
// Only SHIFT
else if(bSHIFT) {
this.unselectAllRows();
// Validate anchor
if(oAnchor) {
// Select all rows between anchor row and target row,
// including the anchor row and target row
if(oAnchor.recordIndex < nTargetRecordIndex) {
for(i=oAnchor.recordIndex; i<=nTargetRecordIndex; i++) {
this.selectRow(i);
}
}
// Select all rows between target row and anchor row,
// including the target row and anchor row
else {
for(i=oAnchor.recordIndex; i>=nTargetRecordIndex; i--) {
this.selectRow(i);
}
}
}
// Invalid anchor
else {
// Set anchor
this._oAnchorRecord = oTargetRecord;
// Select target row only
this.selectRow(oTargetRecord);
}
}
// Only CTRL
else if(bCTRL) {
// Set anchor
this._oAnchorRecord = oTargetRecord;
// Toggle selection of target
if(this.isSelected(oTargetRecord)) {
this.unselectRow(oTargetRecord);
}
else {
this.selectRow(oTargetRecord);
}
}
// Neither SHIFT nor CTRL
else {
this._handleSingleSelectionByMouse(oArgs);
return;
}
}
},
/**
* Determines selection behavior resulting from a key event when selection mode
* is set to "standard".
*
* @method _handleStandardSelectionByKey
* @param e {HTMLEvent} Event object.
* @private
*/
_handleStandardSelectionByKey : function(e) {
var nKey = Ev.getCharCode(e);
if((nKey == 38) || (nKey == 40)) {
var bSHIFT = e.shiftKey;
// Validate trigger
var oTrigger = this._getSelectionTrigger();
// Arrow selection only works if last selected row is on current page
if(!oTrigger) {
return null;
}
Ev.stopEvent(e);
// Validate anchor
var oAnchor = this._getSelectionAnchor(oTrigger);
// Determine which direction we're going to
if(bSHIFT) {
// Selecting down away from anchor row
if((nKey == 40) && (oAnchor.recordIndex <= oTrigger.trIndex)) {
this.selectRow(this.getNextTrEl(oTrigger.el));
}
// Selecting up away from anchor row
else if((nKey == 38) && (oAnchor.recordIndex >= oTrigger.trIndex)) {
this.selectRow(this.getPreviousTrEl(oTrigger.el));
}
// Unselect trigger
else {
this.unselectRow(oTrigger.el);
}
}
else {
this._handleSingleSelectionByKey(e);
}
}
},
/**
* Determines selection behavior resulting from a mouse event when selection mode
* is set to "single".
*
* @method _handleSingleSelectionByMouse
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
* @private
*/
_handleSingleSelectionByMouse : function(oArgs) {
var elTarget = oArgs.target;
// Validate target row
var elTargetRow = this.getTrEl(elTarget);
if(elTargetRow) {
var oTargetRecord = this.getRecord(elTargetRow);
// Set anchor
this._oAnchorRecord = oTargetRecord;
// Select only target
this.unselectAllRows();
this.selectRow(oTargetRecord);
}
},
/**
* Determines selection behavior resulting from a key event when selection mode
* is set to "single".
*
* @method _handleSingleSelectionByKey
* @param e {HTMLEvent} Event object.
* @private
*/
_handleSingleSelectionByKey : function(e) {
var nKey = Ev.getCharCode(e);
if((nKey == 38) || (nKey == 40)) {
// Validate trigger
var oTrigger = this._getSelectionTrigger();
// Arrow selection only works if last selected row is on current page
if(!oTrigger) {
return null;
}
Ev.stopEvent(e);
// Determine the new row to select
var elNew;
if(nKey == 38) { // arrow up
elNew = this.getPreviousTrEl(oTrigger.el);
// Validate new row
if(elNew === null) {
//TODO: wrap around to last tr on current page
//elNew = this.getLastTrEl();
//TODO: wrap back to last tr of previous page
// Top row selection is sticky
elNew = this.getFirstTrEl();
}
}
else if(nKey == 40) { // arrow down
elNew = this.getNextTrEl(oTrigger.el);
// Validate new row
if(elNew === null) {
//TODO: wrap around to first tr on current page
//elNew = this.getFirstTrEl();
//TODO: wrap forward to first tr of previous page
// Bottom row selection is sticky
elNew = this.getLastTrEl();
}
}
// Unselect all rows
this.unselectAllRows();
// Select the new row
this.selectRow(elNew);
// Set new anchor
this._oAnchorRecord = this.getRecord(elNew);
}
},
/**
* Determines selection behavior resulting from a mouse event when selection mode
* is set to "cellblock".
*
* @method _handleCellBlockSelectionByMouse
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
* @private
*/
_handleCellBlockSelectionByMouse : function(oArgs) {
var elTarget = oArgs.target;
// Validate target cell
var elTargetCell = this.getTdEl(elTarget);
if(elTargetCell) {
var e = oArgs.event;
var bSHIFT = e.shiftKey;
var bCTRL = e.ctrlKey || ((navigator.userAgent.toLowerCase().indexOf("mac") != -1) && e.metaKey);
var elTargetRow = this.getTrEl(elTargetCell);
var nTargetTrIndex = this.getTrIndex(elTargetRow);
var oTargetColumn = this.getColumn(elTargetCell);
var nTargetColKeyIndex = oTargetColumn.getKeyIndex();
var oTargetRecord = this.getRecord(elTargetRow);
var nTargetRecordIndex = this._oRecordSet.getRecordIndex(oTargetRecord);
var oTargetCell = {record:oTargetRecord, column:oTargetColumn};
var oAnchor = this._getSelectionAnchor();
var allRows = this.getTbodyEl().rows;
var startIndex, endIndex, currentRow, i, j;
// Both SHIFT and CTRL
if(bSHIFT && bCTRL) {
// Validate anchor
if(oAnchor) {
// Anchor is selected
if(this.isSelected(oAnchor.cell)) {
// All cells are on the same row
if(oAnchor.recordIndex === nTargetRecordIndex) {
// Select all cells between anchor cell and target cell, including target cell
if(oAnchor.colKeyIndex < nTargetColKeyIndex) {
for(i=oAnchor.colKeyIndex+1; i<=nTargetColKeyIndex; i++) {
this.selectCell(elTargetRow.cells[i]);
}
}
// Select all cells between target cell and anchor cell, including target cell
else if(nTargetColKeyIndex < oAnchor.colKeyIndex) {
for(i=nTargetColKeyIndex; i=nTargetTrIndex; i--) {
for(j=endIndex; j>=startIndex; j--) {
this.selectCell(allRows[i].cells[j]);
}
}
}
}
// Anchor cell is unselected
else {
// All cells are on the same row
if(oAnchor.recordIndex === nTargetRecordIndex) {
// Unselect all cells between anchor cell and target cell
if(oAnchor.colKeyIndex < nTargetColKeyIndex) {
for(i=oAnchor.colKeyIndex+1; ioAnchor.colKeyIndex) {
this.unselectCell(currentRow.cells[j]);
}
}
// This is the target row, only unelect cells before the target cell
else if(currentRow.sectionRowIndex === nTargetTrIndex) {
if(jnTargetColKeyIndex) {
this.unselectCell(currentRow.cells[j]);
}
}
// This is the anchor row, only unselect cells before the anchor cell
else if(currentRow.sectionRowIndex == oAnchor.trIndex) {
if(j 36) && (nKey < 41)) {
// Validate trigger
var oTrigger = this._getSelectionTrigger();
// Arrow selection only works if last selected row is on current page
if(!oTrigger) {
return null;
}
Ev.stopEvent(e);
// Validate anchor
var oAnchor = this._getSelectionAnchor(oTrigger);
var i, startIndex, endIndex, elNew, elNewRow;
var allRows = this.getTbodyEl().rows;
var elThisRow = oTrigger.el.parentNode;
// Determine which direction we're going to
if(nKey == 40) { // arrow down
// Selecting away from anchor cell
if(oAnchor.recordIndex <= oTrigger.recordIndex) {
// Select the horiz block on the next row...
// ...making sure there is room below the trigger row
elNewRow = this.getNextTrEl(oTrigger.el);
if(elNewRow) {
startIndex = oAnchor.colKeyIndex;
endIndex = oTrigger.colKeyIndex;
// ...going left
if(startIndex > endIndex) {
for(i=startIndex; i>=endIndex; i--) {
elNew = elNewRow.cells[i];
this.selectCell(elNew);
}
}
// ... going right
else {
for(i=startIndex; i<=endIndex; i++) {
elNew = elNewRow.cells[i];
this.selectCell(elNew);
}
}
}
}
// Unselecting towards anchor cell
else {
startIndex = Math.min(oAnchor.colKeyIndex, oTrigger.colKeyIndex);
endIndex = Math.max(oAnchor.colKeyIndex, oTrigger.colKeyIndex);
// Unselect the horiz block on this row towards the next row
for(i=startIndex; i<=endIndex; i++) {
this.unselectCell(elThisRow.cells[i]);
}
}
}
// Arrow up
else if(nKey == 38) {
// Selecting away from anchor cell
if(oAnchor.recordIndex >= oTrigger.recordIndex) {
// Select the horiz block on the previous row...
// ...making sure there is room
elNewRow = this.getPreviousTrEl(oTrigger.el);
if(elNewRow) {
// Select in order from anchor to trigger...
startIndex = oAnchor.colKeyIndex;
endIndex = oTrigger.colKeyIndex;
// ...going left
if(startIndex > endIndex) {
for(i=startIndex; i>=endIndex; i--) {
elNew = elNewRow.cells[i];
this.selectCell(elNew);
}
}
// ... going right
else {
for(i=startIndex; i<=endIndex; i++) {
elNew = elNewRow.cells[i];
this.selectCell(elNew);
}
}
}
}
// Unselecting towards anchor cell
else {
startIndex = Math.min(oAnchor.colKeyIndex, oTrigger.colKeyIndex);
endIndex = Math.max(oAnchor.colKeyIndex, oTrigger.colKeyIndex);
// Unselect the horiz block on this row towards the previous row
for(i=startIndex; i<=endIndex; i++) {
this.unselectCell(elThisRow.cells[i]);
}
}
}
// Arrow right
else if(nKey == 39) {
// Selecting away from anchor cell
if(oAnchor.colKeyIndex <= oTrigger.colKeyIndex) {
// Select the next vert block to the right...
// ...making sure there is room
if(oTrigger.colKeyIndex < elThisRow.cells.length-1) {
// Select in order from anchor to trigger...
startIndex = oAnchor.trIndex;
endIndex = oTrigger.trIndex;
// ...going up
if(startIndex > endIndex) {
for(i=startIndex; i>=endIndex; i--) {
elNew = allRows[i].cells[oTrigger.colKeyIndex+1];
this.selectCell(elNew);
}
}
// ... going down
else {
for(i=startIndex; i<=endIndex; i++) {
elNew = allRows[i].cells[oTrigger.colKeyIndex+1];
this.selectCell(elNew);
}
}
}
}
// Unselecting towards anchor cell
else {
// Unselect the vert block on this column towards the right
startIndex = Math.min(oAnchor.trIndex, oTrigger.trIndex);
endIndex = Math.max(oAnchor.trIndex, oTrigger.trIndex);
for(i=startIndex; i<=endIndex; i++) {
this.unselectCell(allRows[i].cells[oTrigger.colKeyIndex]);
}
}
}
// Arrow left
else if(nKey == 37) {
// Selecting away from anchor cell
if(oAnchor.colKeyIndex >= oTrigger.colKeyIndex) {
//Select the previous vert block to the left
if(oTrigger.colKeyIndex > 0) {
// Select in order from anchor to trigger...
startIndex = oAnchor.trIndex;
endIndex = oTrigger.trIndex;
// ...going up
if(startIndex > endIndex) {
for(i=startIndex; i>=endIndex; i--) {
elNew = allRows[i].cells[oTrigger.colKeyIndex-1];
this.selectCell(elNew);
}
}
// ... going down
else {
for(i=startIndex; i<=endIndex; i++) {
elNew = allRows[i].cells[oTrigger.colKeyIndex-1];
this.selectCell(elNew);
}
}
}
}
// Unselecting towards anchor cell
else {
// Unselect the vert block on this column towards the left
startIndex = Math.min(oAnchor.trIndex, oTrigger.trIndex);
endIndex = Math.max(oAnchor.trIndex, oTrigger.trIndex);
for(i=startIndex; i<=endIndex; i++) {
this.unselectCell(allRows[i].cells[oTrigger.colKeyIndex]);
}
}
}
}
},
/**
* Determines selection behavior resulting from a mouse event when selection mode
* is set to "cellrange".
*
* @method _handleCellRangeSelectionByMouse
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
* @private
*/
_handleCellRangeSelectionByMouse : function(oArgs) {
var elTarget = oArgs.target;
// Validate target cell
var elTargetCell = this.getTdEl(elTarget);
if(elTargetCell) {
var e = oArgs.event;
var bSHIFT = e.shiftKey;
var bCTRL = e.ctrlKey || ((navigator.userAgent.toLowerCase().indexOf("mac") != -1) && e.metaKey);
var elTargetRow = this.getTrEl(elTargetCell);
var nTargetTrIndex = this.getTrIndex(elTargetRow);
var oTargetColumn = this.getColumn(elTargetCell);
var nTargetColKeyIndex = oTargetColumn.getKeyIndex();
var oTargetRecord = this.getRecord(elTargetRow);
var nTargetRecordIndex = this._oRecordSet.getRecordIndex(oTargetRecord);
var oTargetCell = {record:oTargetRecord, column:oTargetColumn};
var oAnchor = this._getSelectionAnchor();
var allRows = this.getTbodyEl().rows;
var currentRow, i, j;
// Both SHIFT and CTRL
if(bSHIFT && bCTRL) {
// Validate anchor
if(oAnchor) {
// Anchor is selected
if(this.isSelected(oAnchor.cell)) {
// All cells are on the same row
if(oAnchor.recordIndex === nTargetRecordIndex) {
// Select all cells between anchor cell and target cell, including target cell
if(oAnchor.colKeyIndex < nTargetColKeyIndex) {
for(i=oAnchor.colKeyIndex+1; i<=nTargetColKeyIndex; i++) {
this.selectCell(elTargetRow.cells[i]);
}
}
// Select all cells between target cell and anchor cell, including target cell
else if(nTargetColKeyIndex < oAnchor.colKeyIndex) {
for(i=nTargetColKeyIndex; ioAnchor.colKeyIndex) {
this.unselectCell(currentRow.cells[j]);
}
}
// This is the target row, only unelect cells before the target cell
else if(currentRow.sectionRowIndex === nTargetTrIndex) {
if(jnTargetColKeyIndex) {
this.unselectCell(currentRow.cells[j]);
}
}
// This is the anchor row, only unselect cells before the anchor cell
else if(currentRow.sectionRowIndex == oAnchor.trIndex) {
if(j=oAnchor.colKeyIndex) {
this.selectCell(currentRow.cells[j]);
}
}
// This is the target row, only select the target cell and before
else if(currentRow.sectionRowIndex == nTargetTrIndex) {
if(j<=nTargetColKeyIndex) {
this.selectCell(currentRow.cells[j]);
}
}
// Select all cells on this row
else {
this.selectCell(currentRow.cells[j]);
}
}
}
}
// Anchor row is below target row
else {
// Select all cells from target cell to anchor cell,
// including the target cell and anchor cell
for(i=nTargetTrIndex; i<=oAnchor.trIndex; i++) {
currentRow = allRows[i];
for(j=0; j=nTargetColKeyIndex) {
this.selectCell(currentRow.cells[j]);
}
}
// This is the anchor row, only select the anchor cell and before
else if(currentRow.sectionRowIndex == oAnchor.trIndex) {
if(j<=oAnchor.colKeyIndex) {
this.selectCell(currentRow.cells[j]);
}
}
// Select all cells on this row
else {
this.selectCell(currentRow.cells[j]);
}
}
}
}
}
// Invalid anchor
else {
// Set anchor
this._oAnchorCell = oTargetCell;
// Select target only
this.selectCell(oTargetCell);
}
}
// Only CTRL
else if(bCTRL) {
// Set anchor
this._oAnchorCell = oTargetCell;
// Toggle selection of target
if(this.isSelected(oTargetCell)) {
this.unselectCell(oTargetCell);
}
else {
this.selectCell(oTargetCell);
}
}
// Neither SHIFT nor CTRL
else {
this._handleSingleCellSelectionByMouse(oArgs);
}
}
},
/**
* Determines selection behavior resulting from a key event when selection mode
* is set to "cellrange".
*
* @method _handleCellRangeSelectionByKey
* @param e {HTMLEvent} Event object.
* @private
*/
_handleCellRangeSelectionByKey : function(e) {
var nKey = Ev.getCharCode(e);
var bSHIFT = e.shiftKey;
if((nKey == 9) || !bSHIFT) {
this._handleSingleCellSelectionByKey(e);
return;
}
if((nKey > 36) && (nKey < 41)) {
// Validate trigger
var oTrigger = this._getSelectionTrigger();
// Arrow selection only works if last selected row is on current page
if(!oTrigger) {
return null;
}
Ev.stopEvent(e);
// Validate anchor
var oAnchor = this._getSelectionAnchor(oTrigger);
var i, elNewRow, elNew;
var allRows = this.getTbodyEl().rows;
var elThisRow = oTrigger.el.parentNode;
// Arrow down
if(nKey == 40) {
elNewRow = this.getNextTrEl(oTrigger.el);
// Selecting away from anchor cell
if(oAnchor.recordIndex <= oTrigger.recordIndex) {
// Select all cells to the end of this row
for(i=oTrigger.colKeyIndex+1; i= oTrigger.recordIndex) {
// Select all the cells to the beginning of this row
for(i=oTrigger.colKeyIndex-1; i>-1; i--){
elNew = elThisRow.cells[i];
this.selectCell(elNew);
}
// Select some of the cells from the end of the previous row
if(elNewRow) {
for(i=elThisRow.cells.length-1; i>=oTrigger.colKeyIndex; i--){
elNew = elNewRow.cells[i];
this.selectCell(elNew);
}
}
}
// Unselecting towards anchor cell
else {
// Unselect all the cells to the beginning of this row
for(i=oTrigger.colKeyIndex; i>-1; i--){
this.unselectCell(elThisRow.cells[i]);
}
// Unselect some of the cells from the end of the previous row
if(elNewRow) {
for(i=elThisRow.cells.length-1; i>oTrigger.colKeyIndex; i--){
this.unselectCell(elNewRow.cells[i]);
}
}
}
}
// Arrow right
else if(nKey == 39) {
elNewRow = this.getNextTrEl(oTrigger.el);
// Selecting away from anchor cell
if(oAnchor.recordIndex < oTrigger.recordIndex) {
// Select the next cell to the right
if(oTrigger.colKeyIndex < elThisRow.cells.length-1) {
elNew = elThisRow.cells[oTrigger.colKeyIndex+1];
this.selectCell(elNew);
}
// Select the first cell of the next row
else if(elNewRow) {
elNew = elNewRow.cells[0];
this.selectCell(elNew);
}
}
// Unselecting towards anchor cell
else if(oAnchor.recordIndex > oTrigger.recordIndex) {
this.unselectCell(elThisRow.cells[oTrigger.colKeyIndex]);
// Unselect this cell towards the right
if(oTrigger.colKeyIndex < elThisRow.cells.length-1) {
}
// Unselect this cells towards the first cell of the next row
else {
}
}
// Anchor is on this row
else {
// Selecting away from anchor
if(oAnchor.colKeyIndex <= oTrigger.colKeyIndex) {
// Select the next cell to the right
if(oTrigger.colKeyIndex < elThisRow.cells.length-1) {
elNew = elThisRow.cells[oTrigger.colKeyIndex+1];
this.selectCell(elNew);
}
// Select the first cell on the next row
else if(oTrigger.trIndex < allRows.length-1){
elNew = elNewRow.cells[0];
this.selectCell(elNew);
}
}
// Unselecting towards anchor
else {
// Unselect this cell towards the right
this.unselectCell(elThisRow.cells[oTrigger.colKeyIndex]);
}
}
}
// Arrow left
else if(nKey == 37) {
elNewRow = this.getPreviousTrEl(oTrigger.el);
// Unselecting towards the anchor
if(oAnchor.recordIndex < oTrigger.recordIndex) {
this.unselectCell(elThisRow.cells[oTrigger.colKeyIndex]);
// Unselect this cell towards the left
if(oTrigger.colKeyIndex > 0) {
}
// Unselect this cell towards the last cell of the previous row
else {
}
}
// Selecting towards the anchor
else if(oAnchor.recordIndex > oTrigger.recordIndex) {
// Select the next cell to the left
if(oTrigger.colKeyIndex > 0) {
elNew = elThisRow.cells[oTrigger.colKeyIndex-1];
this.selectCell(elNew);
}
// Select the last cell of the previous row
else if(oTrigger.trIndex > 0){
elNew = elNewRow.cells[elNewRow.cells.length-1];
this.selectCell(elNew);
}
}
// Anchor is on this row
else {
// Selecting away from anchor cell
if(oAnchor.colKeyIndex >= oTrigger.colKeyIndex) {
// Select the next cell to the left
if(oTrigger.colKeyIndex > 0) {
elNew = elThisRow.cells[oTrigger.colKeyIndex-1];
this.selectCell(elNew);
}
// Select the last cell of the previous row
else if(oTrigger.trIndex > 0){
elNew = elNewRow.cells[elNewRow.cells.length-1];
this.selectCell(elNew);
}
}
// Unselecting towards anchor cell
else {
this.unselectCell(elThisRow.cells[oTrigger.colKeyIndex]);
// Unselect this cell towards the left
if(oTrigger.colKeyIndex > 0) {
}
// Unselect this cell towards the last cell of the previous row
else {
}
}
}
}
}
},
/**
* Determines selection behavior resulting from a mouse event when selection mode
* is set to "singlecell".
*
* @method _handleSingleCellSelectionByMouse
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
* @private
*/
_handleSingleCellSelectionByMouse : function(oArgs) {
var elTarget = oArgs.target;
// Validate target cell
var elTargetCell = this.getTdEl(elTarget);
if(elTargetCell) {
var elTargetRow = this.getTrEl(elTargetCell);
var oTargetRecord = this.getRecord(elTargetRow);
var oTargetColumn = this.getColumn(elTargetCell);
var oTargetCell = {record:oTargetRecord, column:oTargetColumn};
// Set anchor
this._oAnchorCell = oTargetCell;
// Select only target
this.unselectAllCells();
this.selectCell(oTargetCell);
}
},
/**
* Determines selection behavior resulting from a key event when selection mode
* is set to "singlecell".
*
* @method _handleSingleCellSelectionByKey
* @param e {HTMLEvent} Event object.
* @private
*/
_handleSingleCellSelectionByKey : function(e) {
var nKey = Ev.getCharCode(e);
if((nKey == 9) || ((nKey > 36) && (nKey < 41))) {
var bSHIFT = e.shiftKey;
// Validate trigger
var oTrigger = this._getSelectionTrigger();
// Arrow selection only works if last selected row is on current page
if(!oTrigger) {
return null;
}
// Determine the new cell to select
var elNew;
if(nKey == 40) { // Arrow down
elNew = this.getBelowTdEl(oTrigger.el);
// Validate new cell
if(elNew === null) {
//TODO: wrap around to first tr on current page
//TODO: wrap forward to first tr of next page
// Bottom selection is sticky
elNew = oTrigger.el;
}
}
else if(nKey == 38) { // Arrow up
elNew = this.getAboveTdEl(oTrigger.el);
// Validate new cell
if(elNew === null) {
//TODO: wrap around to last tr on current page
//TODO: wrap back to last tr of previous page
// Top selection is sticky
elNew = oTrigger.el;
}
}
else if((nKey == 39) || (!bSHIFT && (nKey == 9))) { // Arrow right or tab
elNew = this.getNextTdEl(oTrigger.el);
// Validate new cell
if(elNew === null) {
//TODO: wrap around to first td on current page
//TODO: wrap forward to first td of next page
// Top-left selection is sticky, and release TAB focus
//elNew = oTrigger.el;
return;
}
}
else if((nKey == 37) || (bSHIFT && (nKey == 9))) { // Arrow left or shift-tab
elNew = this.getPreviousTdEl(oTrigger.el);
// Validate new cell
if(elNew === null) {
//TODO: wrap around to last td on current page
//TODO: wrap back to last td of previous page
// Bottom-right selection is sticky, and release TAB focus
//elNew = oTrigger.el;
return;
}
}
Ev.stopEvent(e);
// Unselect all cells
this.unselectAllCells();
// Select the new cell
this.selectCell(elNew);
// Set new anchor
this._oAnchorCell = {record:this.getRecord(elNew), column:this.getColumn(elNew)};
}
},
/**
* Returns array of selected TR elements on the page.
*
* @method getSelectedTrEls
* @return {HTMLElement[]} Array of selected TR elements.
*/
getSelectedTrEls : function() {
return Dom.getElementsByClassName(DT.CLASS_SELECTED,"tr",this._elTbody);
},
/**
* Sets given row to the selected state.
*
* @method selectRow
* @param row {HTMLElement | String | YAHOO.widget.Record | Number} HTML element
* reference or ID string, Record instance, or RecordSet position index.
*/
selectRow : function(row) {
var oRecord, elRow;
if(row instanceof YAHOO.widget.Record) {
oRecord = this._oRecordSet.getRecord(row);
elRow = this.getTrEl(oRecord);
}
else if(lang.isNumber(row)) {
oRecord = this.getRecord(row);
elRow = this.getTrEl(oRecord);
}
else {
elRow = this.getTrEl(row);
oRecord = this.getRecord(elRow);
}
if(oRecord) {
// Update selection trackers
var tracker = this._aSelections || [];
var sRecordId = oRecord.getId();
var index = -1;
// Remove if already there:
// Use Array.indexOf if available...
/*if(tracker.indexOf && (tracker.indexOf(sRecordId) > -1)) {
tracker.splice(tracker.indexOf(sRecordId),1);
}*/
if(tracker.indexOf) {
index = tracker.indexOf(sRecordId);
}
// ...or do it the old-fashioned way
else {
for(var j=tracker.length-1; j>-1; j--) {
if(tracker[j] === sRecordId){
index = j;
break;
}
}
}
if(index > -1) {
tracker.splice(index,1);
}
// Add to the end
tracker.push(sRecordId);
this._aSelections = tracker;
// Update trackers
if(!this._oAnchorRecord) {
this._oAnchorRecord = oRecord;
}
// Update UI
if(elRow) {
Dom.addClass(elRow, DT.CLASS_SELECTED);
}
this.fireEvent("rowSelectEvent", {record:oRecord, el:elRow});
}
else {
}
},
/**
* Sets given row to the unselected state.
*
* @method unselectRow
* @param row {HTMLElement | String | YAHOO.widget.Record | Number} HTML element
* reference or ID string, Record instance, or RecordSet position index.
*/
unselectRow : function(row) {
var elRow = this.getTrEl(row);
var oRecord;
if(row instanceof YAHOO.widget.Record) {
oRecord = this._oRecordSet.getRecord(row);
}
else if(lang.isNumber(row)) {
oRecord = this.getRecord(row);
}
else {
oRecord = this.getRecord(elRow);
}
if(oRecord) {
// Update selection trackers
var tracker = this._aSelections || [];
var sRecordId = oRecord.getId();
var index = -1;
// Use Array.indexOf if available...
if(tracker.indexOf) {
index = tracker.indexOf(sRecordId);
}
// ...or do it the old-fashioned way
else {
for(var j=tracker.length-1; j>-1; j--) {
if(tracker[j] === sRecordId){
index = j;
break;
}
}
}
if(index > -1) {
// Update tracker
tracker.splice(index,1);
this._aSelections = tracker;
// Update the UI
Dom.removeClass(elRow, DT.CLASS_SELECTED);
this.fireEvent("rowUnselectEvent", {record:oRecord, el:elRow});
return;
}
}
},
/**
* Clears out all row selections.
*
* @method unselectAllRows
*/
unselectAllRows : function() {
// Remove all rows from tracker
var tracker = this._aSelections || [],
recId,
removed = [];
for(var j=tracker.length-1; j>-1; j--) {
if(lang.isString(tracker[j])){
recId = tracker.splice(j,1);
removed[removed.length] = this.getRecord(lang.isArray(recId) ? recId[0] : recId);
}
}
// Update tracker
this._aSelections = tracker;
// Update UI
this._unselectAllTrEls();
this.fireEvent("unselectAllRowsEvent", {records: removed});
},
/**
* Convenience method to remove the class YAHOO.widget.DataTable.CLASS_SELECTED
* from all TD elements in the internal tracker.
*
* @method _unselectAllTdEls
* @private
*/
_unselectAllTdEls : function() {
var selectedCells = Dom.getElementsByClassName(DT.CLASS_SELECTED,"td",this._elTbody);
Dom.removeClass(selectedCells, DT.CLASS_SELECTED);
},
/**
* Returns array of selected TD elements on the page.
*
* @method getSelectedTdEls
* @return {HTMLElement[]} Array of selected TD elements.
*/
getSelectedTdEls : function() {
return Dom.getElementsByClassName(DT.CLASS_SELECTED,"td",this._elTbody);
},
/**
* Sets given cell to the selected state.
*
* @method selectCell
* @param cell {HTMLElement | String} DOM element reference or ID string
* to DataTable page element or RecordSet index.
*/
selectCell : function(cell) {
//TODO: accept {record} in selectCell()
var elCell = this.getTdEl(cell);
if(elCell) {
var oRecord = this.getRecord(elCell);
var sColumnKey = this.getColumn(elCell.cellIndex).getKey();
if(oRecord && sColumnKey) {
// Get Record ID
var tracker = this._aSelections || [];
var sRecordId = oRecord.getId();
// Remove if there
for(var j=tracker.length-1; j>-1; j--) {
if((tracker[j].recordId === sRecordId) && (tracker[j].columnKey === sColumnKey)){
tracker.splice(j,1);
break;
}
}
// Add to the end
tracker.push({recordId:sRecordId, columnKey:sColumnKey});
// Update trackers
this._aSelections = tracker;
if(!this._oAnchorCell) {
this._oAnchorCell = {record:oRecord, column:this.getColumn(sColumnKey)};
}
// Update the UI
Dom.addClass(elCell, DT.CLASS_SELECTED);
this.fireEvent("cellSelectEvent", {record:oRecord, column:this.getColumn(elCell.cellIndex), key: this.getColumn(elCell.cellIndex).getKey(), el:elCell});
return;
}
}
},
/**
* Sets given cell to the unselected state.
*
* @method unselectCell
* @param cell {HTMLElement | String} DOM element reference or ID string
* to DataTable page element or RecordSet index.
*/
unselectCell : function(cell) {
var elCell = this.getTdEl(cell);
if(elCell) {
var oRecord = this.getRecord(elCell);
var sColumnKey = this.getColumn(elCell.cellIndex).getKey();
if(oRecord && sColumnKey) {
// Get Record ID
var tracker = this._aSelections || [];
var id = oRecord.getId();
// Is it selected?
for(var j=tracker.length-1; j>-1; j--) {
if((tracker[j].recordId === id) && (tracker[j].columnKey === sColumnKey)){
// Remove from tracker
tracker.splice(j,1);
// Update tracker
this._aSelections = tracker;
// Update the UI
Dom.removeClass(elCell, DT.CLASS_SELECTED);
this.fireEvent("cellUnselectEvent", {record:oRecord, column: this.getColumn(elCell.cellIndex), key:this.getColumn(elCell.cellIndex).getKey(), el:elCell});
return;
}
}
}
}
},
/**
* Clears out all cell selections.
*
* @method unselectAllCells
*/
unselectAllCells : function() {
// Remove all cells from tracker
var tracker = this._aSelections || [];
for(var j=tracker.length-1; j>-1; j--) {
if(lang.isObject(tracker[j])){
tracker.splice(j,1);
}
}
// Update tracker
this._aSelections = tracker;
// Update UI
this._unselectAllTdEls();
//TODO: send data to unselectAllCellsEvent handler
this.fireEvent("unselectAllCellsEvent");
},
/**
* Returns true if given item is selected, false otherwise.
*
* @method isSelected
* @param o {String | HTMLElement | YAHOO.widget.Record | Number
* {record:YAHOO.widget.Record, column:YAHOO.widget.Column} } TR or TD element by
* reference or ID string, a Record instance, a RecordSet position index,
* or an object literal representation
* of a cell.
* @return {Boolean} True if item is selected.
*/
isSelected : function(o) {
if(o && (o.ownerDocument == document)) {
return (Dom.hasClass(this.getTdEl(o),DT.CLASS_SELECTED) || Dom.hasClass(this.getTrEl(o),DT.CLASS_SELECTED));
}
else {
var oRecord, sRecordId, j;
var tracker = this._aSelections;
if(tracker && tracker.length > 0) {
// Looking for a Record?
if(o instanceof YAHOO.widget.Record) {
oRecord = o;
}
else if(lang.isNumber(o)) {
oRecord = this.getRecord(o);
}
if(oRecord) {
sRecordId = oRecord.getId();
// Is it there?
// Use Array.indexOf if available...
if(tracker.indexOf) {
if(tracker.indexOf(sRecordId) > -1) {
return true;
}
}
// ...or do it the old-fashioned way
else {
for(j=tracker.length-1; j>-1; j--) {
if(tracker[j] === sRecordId){
return true;
}
}
}
}
// Looking for a cell
else if(o.record && o.column){
sRecordId = o.record.getId();
var sColumnKey = o.column.getKey();
for(j=tracker.length-1; j>-1; j--) {
if((tracker[j].recordId === sRecordId) && (tracker[j].columnKey === sColumnKey)){
return true;
}
}
}
}
}
return false;
},
/**
* Returns selected rows as an array of Record IDs.
*
* @method getSelectedRows
* @return {String[]} Array of selected rows by Record ID.
*/
getSelectedRows : function() {
var aSelectedRows = [];
var tracker = this._aSelections || [];
for(var j=0; j 0) {
for(var i=tracker.length-1; i>-1; i--) {
if(lang.isString(tracker[i])){
return tracker[i];
}
}
}
},
/**
* Returns last selected cell as an object literal:
* {recordId:sRecordId, columnKey:sColumnKey}.
*
* @method getLastSelectedCell
* @return {Object} Object literal representation of a cell.
*/
getLastSelectedCell : function() {
var tracker = this._aSelections;
if(tracker && tracker.length > 0) {
for(var i=tracker.length-1; i>-1; i--) {
if(tracker[i].recordId && tracker[i].columnKey){
return tracker[i];
}
}
}
},
/**
* Assigns the class YAHOO.widget.DataTable.CLASS_HIGHLIGHTED to the given row.
*
* @method highlightRow
* @param row {HTMLElement | String} DOM element reference or ID string.
*/
highlightRow : function(row) {
var elRow = this.getTrEl(row);
if(elRow) {
// Make sure previous row is unhighlighted
/* if(this._sLastHighlightedTrElId) {
Dom.removeClass(this._sLastHighlightedTrElId,DT.CLASS_HIGHLIGHTED);
}*/
var oRecord = this.getRecord(elRow);
Dom.addClass(elRow,DT.CLASS_HIGHLIGHTED);
//this._sLastHighlightedTrElId = elRow.id;
this.fireEvent("rowHighlightEvent", {record:oRecord, el:elRow});
return;
}
},
/**
* Removes the class YAHOO.widget.DataTable.CLASS_HIGHLIGHTED from the given row.
*
* @method unhighlightRow
* @param row {HTMLElement | String} DOM element reference or ID string.
*/
unhighlightRow : function(row) {
var elRow = this.getTrEl(row);
if(elRow) {
var oRecord = this.getRecord(elRow);
Dom.removeClass(elRow,DT.CLASS_HIGHLIGHTED);
this.fireEvent("rowUnhighlightEvent", {record:oRecord, el:elRow});
return;
}
},
/**
* Assigns the class YAHOO.widget.DataTable.CLASS_HIGHLIGHTED to the given cell.
*
* @method highlightCell
* @param cell {HTMLElement | String} DOM element reference or ID string.
*/
highlightCell : function(cell) {
var elCell = this.getTdEl(cell);
if(elCell) {
// Make sure previous cell is unhighlighted
if(this._elLastHighlightedTd) {
this.unhighlightCell(this._elLastHighlightedTd);
}
var oRecord = this.getRecord(elCell);
var sColumnKey = this.getColumn(elCell.cellIndex).getKey();
Dom.addClass(elCell,DT.CLASS_HIGHLIGHTED);
this._elLastHighlightedTd = elCell;
this.fireEvent("cellHighlightEvent", {record:oRecord, column:this.getColumn(elCell.cellIndex), key:this.getColumn(elCell.cellIndex).getKey(), el:elCell});
return;
}
},
/**
* Removes the class YAHOO.widget.DataTable.CLASS_HIGHLIGHTED from the given cell.
*
* @method unhighlightCell
* @param cell {HTMLElement | String} DOM element reference or ID string.
*/
unhighlightCell : function(cell) {
var elCell = this.getTdEl(cell);
if(elCell) {
var oRecord = this.getRecord(elCell);
Dom.removeClass(elCell,DT.CLASS_HIGHLIGHTED);
this._elLastHighlightedTd = null;
this.fireEvent("cellUnhighlightEvent", {record:oRecord, column:this.getColumn(elCell.cellIndex), key:this.getColumn(elCell.cellIndex).getKey(), el:elCell});
return;
}
},
// INLINE EDITING
/**
* Returns current CellEditor instance, or null.
* @method getCellEditor
* @return {YAHOO.widget.CellEditor} CellEditor instance.
*/
getCellEditor : function() {
return this._oCellEditor;
},
/**
* Activates and shows CellEditor instance for the given cell while deactivating and
* canceling previous CellEditor. It is baked into DataTable that only one CellEditor
* can be active at any given time.
*
* @method showCellEditor
* @param elCell {HTMLElement | String} Cell to edit.
*/
showCellEditor : function(elCell, oRecord, oColumn) {
// Get a particular CellEditor
elCell = this.getTdEl(elCell);
if(elCell) {
oColumn = this.getColumn(elCell);
if(oColumn && oColumn.editor) {
var oCellEditor = this._oCellEditor;
// Clean up active CellEditor
if(oCellEditor) {
if(this._oCellEditor.cancel) {
this._oCellEditor.cancel();
}
else if(oCellEditor.isActive) {
this.cancelCellEditor();
}
}
if(oColumn.editor instanceof YAHOO.widget.BaseCellEditor) {
// Get CellEditor
oCellEditor = oColumn.editor;
var ok = oCellEditor.attach(this, elCell);
if(ok) {
oCellEditor.move();
ok = this.doBeforeShowCellEditor(oCellEditor);
if(ok) {
oCellEditor.show();
this._oCellEditor = oCellEditor;
}
}
}
// Backward compatibility
else {
if(!oRecord || !(oRecord instanceof YAHOO.widget.Record)) {
oRecord = this.getRecord(elCell);
}
if(!oColumn || !(oColumn instanceof YAHOO.widget.Column)) {
oColumn = this.getColumn(elCell);
}
if(oRecord && oColumn) {
if(!this._oCellEditor || this._oCellEditor.container) {
this._initCellEditorEl();
}
// Update Editor values
oCellEditor = this._oCellEditor;
oCellEditor.cell = elCell;
oCellEditor.record = oRecord;
oCellEditor.column = oColumn;
oCellEditor.validator = (oColumn.editorOptions &&
lang.isFunction(oColumn.editorOptions.validator)) ?
oColumn.editorOptions.validator : null;
oCellEditor.value = oRecord.getData(oColumn.key);
oCellEditor.defaultValue = null;
// Move Editor
var elContainer = oCellEditor.container;
var x = Dom.getX(elCell);
var y = Dom.getY(elCell);
// SF doesn't get xy for cells in scrolling table
// when tbody display is set to block
if(isNaN(x) || isNaN(y)) {
x = elCell.offsetLeft + // cell pos relative to table
Dom.getX(this._elTbody.parentNode) - // plus table pos relative to document
this._elTbody.scrollLeft; // minus tbody scroll
y = elCell.offsetTop + // cell pos relative to table
Dom.getY(this._elTbody.parentNode) - // plus table pos relative to document
this._elTbody.scrollTop + // minus tbody scroll
this._elThead.offsetHeight; // account for fixed THEAD cells
}
elContainer.style.left = x + "px";
elContainer.style.top = y + "px";
// Hook to customize the UI
this.doBeforeShowCellEditor(this._oCellEditor);
//TODO: This is temporarily up here due so elements can be focused
// Show Editor
elContainer.style.display = "";
// Handle ESC key
Ev.addListener(elContainer, "keydown", function(e, oSelf) {
// ESC hides Cell Editor
if((e.keyCode == 27)) {
oSelf.cancelCellEditor();
oSelf.focusTbodyEl();
}
else {
oSelf.fireEvent("editorKeydownEvent", {editor:oSelf._oCellEditor, event:e});
}
}, this);
// Render Editor markup
var fnEditor;
if(lang.isString(oColumn.editor)) {
switch(oColumn.editor) {
case "checkbox":
fnEditor = DT.editCheckbox;
break;
case "date":
fnEditor = DT.editDate;
break;
case "dropdown":
fnEditor = DT.editDropdown;
break;
case "radio":
fnEditor = DT.editRadio;
break;
case "textarea":
fnEditor = DT.editTextarea;
break;
case "textbox":
fnEditor = DT.editTextbox;
break;
default:
fnEditor = null;
}
}
else if(lang.isFunction(oColumn.editor)) {
fnEditor = oColumn.editor;
}
if(fnEditor) {
// Create DOM input elements
fnEditor(this._oCellEditor, this);
// Show Save/Cancel buttons
if(!oColumn.editorOptions || !oColumn.editorOptions.disableBtns) {
this.showCellEditorBtns(elContainer);
}
oCellEditor.isActive = true;
//TODO: verify which args to pass
this.fireEvent("editorShowEvent", {editor:oCellEditor});
return;
}
}
}
}
}
},
/**
* Backward compatibility.
*
* @method _initCellEditorEl
* @private
* @deprecated
*/
_initCellEditorEl : function() {
// Attach Cell Editor container element as first child of body
var elCellEditor = document.createElement("div");
elCellEditor.id = this._sId + "-celleditor";
elCellEditor.style.display = "none";
elCellEditor.tabIndex = 0;
Dom.addClass(elCellEditor, DT.CLASS_EDITOR);
var elFirstChild = Dom.getFirstChild(document.body);
if(elFirstChild) {
elCellEditor = Dom.insertBefore(elCellEditor, elFirstChild);
}
else {
elCellEditor = document.body.appendChild(elCellEditor);
}
// Internal tracker of Cell Editor values
var oCellEditor = {};
oCellEditor.container = elCellEditor;
oCellEditor.value = null;
oCellEditor.isActive = false;
this._oCellEditor = oCellEditor;
},
/**
* Overridable abstract method to customize CellEditor before showing.
*
* @method doBeforeShowCellEditor
* @param oCellEditor {YAHOO.widget.CellEditor} The CellEditor instance.
* @return {Boolean} Return true to continue showing CellEditor.
*/
doBeforeShowCellEditor : function(oCellEditor) {
return true;
},
/**
* Saves active CellEditor input to Record and upates DOM UI.
*
* @method saveCellEditor
*/
saveCellEditor : function() {
if(this._oCellEditor) {
if(this._oCellEditor.save) {
this._oCellEditor.save();
}
// Backward compatibility
else if(this._oCellEditor.isActive) {
var newData = this._oCellEditor.value;
// Copy the data to pass to the event
//var oldData = YAHOO.widget.DataTable._cloneObject(this._oCellEditor.record.getData(this._oCellEditor.column.key));
var oldData = this._oCellEditor.record.getData(this._oCellEditor.column.key);
// Validate input data
if(this._oCellEditor.validator) {
newData = this._oCellEditor.value = this._oCellEditor.validator.call(this, newData, oldData, this._oCellEditor);
if(newData === null ) {
this.resetCellEditor();
this.fireEvent("editorRevertEvent",
{editor:this._oCellEditor, oldData:oldData, newData:newData});
return;
}
}
// Update the Record
this._oRecordSet.updateRecordValue(this._oCellEditor.record, this._oCellEditor.column.key, this._oCellEditor.value);
// Update the UI
this.formatCell(this._oCellEditor.cell.firstChild);
// Bug fix 1764044
this._oChainRender.add({
method: function() {
this.validateColumnWidths();
},
scope: this
});
this._oChainRender.run();
// Clear out the Cell Editor
this.resetCellEditor();
this.fireEvent("editorSaveEvent",
{editor:this._oCellEditor, oldData:oldData, newData:newData});
}
}
},
/**
* Cancels active CellEditor.
*
* @method cancelCellEditor
*/
cancelCellEditor : function() {
if(this._oCellEditor) {
if(this._oCellEditor.cancel) {
this._oCellEditor.cancel();
}
// Backward compatibility
else if(this._oCellEditor.isActive) {
this.resetCellEditor();
//TODO: preserve values for the event?
this.fireEvent("editorCancelEvent", {editor:this._oCellEditor});
}
}
},
/**
* Destroys active CellEditor instance and UI.
*
* @method destroyCellEditor
*/
destroyCellEditor : function() {
if(this._oCellEditor) {
this._oCellEditor.destroy();
this._oCellEditor = null;
}
},
/**
* Passes through showEvent of the active CellEditor.
*
* @method _onEditorShowEvent
* @param oArgs {Object} Custom Event args.
* @private
*/
_onEditorShowEvent : function(oArgs) {
this.fireEvent("editorShowEvent", oArgs);
},
/**
* Passes through keydownEvent of the active CellEditor.
* @param oArgs {Object} Custom Event args.
*
* @method _onEditorKeydownEvent
* @private
*/
_onEditorKeydownEvent : function(oArgs) {
this.fireEvent("editorKeydownEvent", oArgs);
},
/**
* Passes through revertEvent of the active CellEditor.
*
* @method _onEditorRevertEvent
* @param oArgs {Object} Custom Event args.
* @private
*/
_onEditorRevertEvent : function(oArgs) {
this.fireEvent("editorRevertEvent", oArgs);
},
/**
* Passes through saveEvent of the active CellEditor.
*
* @method _onEditorSaveEvent
* @param oArgs {Object} Custom Event args.
* @private
*/
_onEditorSaveEvent : function(oArgs) {
this.fireEvent("editorSaveEvent", oArgs);
},
/**
* Passes through cancelEvent of the active CellEditor.
*
* @method _onEditorCancelEvent
* @param oArgs {Object} Custom Event args.
* @private
*/
_onEditorCancelEvent : function(oArgs) {
this.fireEvent("editorCancelEvent", oArgs);
},
/**
* Passes through blurEvent of the active CellEditor.
*
* @method _onEditorBlurEvent
* @param oArgs {Object} Custom Event args.
* @private
*/
_onEditorBlurEvent : function(oArgs) {
this.fireEvent("editorBlurEvent", oArgs);
},
/**
* Passes through blockEvent of the active CellEditor.
*
* @method _onEditorBlockEvent
* @param oArgs {Object} Custom Event args.
* @private
*/
_onEditorBlockEvent : function(oArgs) {
this.fireEvent("editorBlockEvent", oArgs);
},
/**
* Passes through unblockEvent of the active CellEditor.
*
* @method _onEditorUnblockEvent
* @param oArgs {Object} Custom Event args.
* @private
*/
_onEditorUnblockEvent : function(oArgs) {
this.fireEvent("editorUnblockEvent", oArgs);
},
/**
* Public handler of the editorBlurEvent. By default, saves on blur if
* disableBtns is true, otherwise cancels on blur.
*
* @method onEditorBlurEvent
* @param oArgs {Object} Custom Event args.
*/
onEditorBlurEvent : function(oArgs) {
if(oArgs.editor.disableBtns) {
// Save on blur
if(oArgs.editor.save) { // Backward incompatible
oArgs.editor.save();
}
}
else if(oArgs.editor.cancel) { // Backward incompatible
// Cancel on blur
oArgs.editor.cancel();
}
},
/**
* Public handler of the editorBlockEvent. By default, disables DataTable UI.
*
* @method onEditorBlockEvent
* @param oArgs {Object} Custom Event args.
*/
onEditorBlockEvent : function(oArgs) {
this.disable();
},
/**
* Public handler of the editorUnblockEvent. By default, undisables DataTable UI.
*
* @method onEditorUnblockEvent
* @param oArgs {Object} Custom Event args.
*/
onEditorUnblockEvent : function(oArgs) {
this.undisable();
},
// ABSTRACT METHODS
/**
* Overridable method gives implementers a hook to access data before
* it gets added to RecordSet and rendered to the TBODY.
*
* @method doBeforeLoadData
* @param sRequest {String} Original request.
* @param oResponse {Object} Response object.
* @param oPayload {MIXED} additional arguments
* @return {Boolean} Return true to continue loading data into RecordSet and
* updating DataTable with new Records, false to cancel.
*/
doBeforeLoadData : function(sRequest, oResponse, oPayload) {
return true;
},
/////////////////////////////////////////////////////////////////////////////
//
// Public Custom Event Handlers
//
/////////////////////////////////////////////////////////////////////////////
/**
* Overridable custom event handler to sort Column.
*
* @method onEventSortColumn
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventSortColumn : function(oArgs) {
//TODO: support form elements in sortable columns
var evt = oArgs.event;
var target = oArgs.target;
var el = this.getThEl(target) || this.getTdEl(target);
if(el) {
var oColumn = this.getColumn(el);
if(oColumn.sortable) {
Ev.stopEvent(evt);
this.sortColumn(oColumn);
}
}
else {
}
},
/**
* Overridable custom event handler to select Column.
*
* @method onEventSelectColumn
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventSelectColumn : function(oArgs) {
this.selectColumn(oArgs.target);
},
/**
* Overridable custom event handler to highlight Column. Accounts for spurious
* caused-by-child events.
*
* @method onEventHighlightColumn
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventHighlightColumn : function(oArgs) {
//TODO: filter for all spurious events at a lower level
if(!Dom.isAncestor(oArgs.target,Ev.getRelatedTarget(oArgs.event))) {
this.highlightColumn(oArgs.target);
}
},
/**
* Overridable custom event handler to unhighlight Column. Accounts for spurious
* caused-by-child events.
*
* @method onEventUnhighlightColumn
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventUnhighlightColumn : function(oArgs) {
//TODO: filter for all spurious events at a lower level
if(!Dom.isAncestor(oArgs.target,Ev.getRelatedTarget(oArgs.event))) {
this.unhighlightColumn(oArgs.target);
}
},
/**
* Overridable custom event handler to manage selection according to desktop paradigm.
*
* @method onEventSelectRow
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventSelectRow : function(oArgs) {
var sMode = this.get("selectionMode");
if(sMode == "single") {
this._handleSingleSelectionByMouse(oArgs);
}
else {
this._handleStandardSelectionByMouse(oArgs);
}
},
/**
* Overridable custom event handler to select cell.
*
* @method onEventSelectCell
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventSelectCell : function(oArgs) {
var sMode = this.get("selectionMode");
if(sMode == "cellblock") {
this._handleCellBlockSelectionByMouse(oArgs);
}
else if(sMode == "cellrange") {
this._handleCellRangeSelectionByMouse(oArgs);
}
else {
this._handleSingleCellSelectionByMouse(oArgs);
}
},
/**
* Overridable custom event handler to highlight row. Accounts for spurious
* caused-by-child events.
*
* @method onEventHighlightRow
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventHighlightRow : function(oArgs) {
//TODO: filter for all spurious events at a lower level
if(!Dom.isAncestor(oArgs.target,Ev.getRelatedTarget(oArgs.event))) {
this.highlightRow(oArgs.target);
}
},
/**
* Overridable custom event handler to unhighlight row. Accounts for spurious
* caused-by-child events.
*
* @method onEventUnhighlightRow
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventUnhighlightRow : function(oArgs) {
//TODO: filter for all spurious events at a lower level
if(!Dom.isAncestor(oArgs.target,Ev.getRelatedTarget(oArgs.event))) {
this.unhighlightRow(oArgs.target);
}
},
/**
* Overridable custom event handler to highlight cell. Accounts for spurious
* caused-by-child events.
*
* @method onEventHighlightCell
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventHighlightCell : function(oArgs) {
//TODO: filter for all spurious events at a lower level
if(!Dom.isAncestor(oArgs.target,Ev.getRelatedTarget(oArgs.event))) {
this.highlightCell(oArgs.target);
}
},
/**
* Overridable custom event handler to unhighlight cell. Accounts for spurious
* caused-by-child events.
*
* @method onEventUnhighlightCell
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventUnhighlightCell : function(oArgs) {
//TODO: filter for all spurious events at a lower level
if(!Dom.isAncestor(oArgs.target,Ev.getRelatedTarget(oArgs.event))) {
this.unhighlightCell(oArgs.target);
}
},
/**
* Overridable custom event handler to format cell.
*
* @method onEventFormatCell
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventFormatCell : function(oArgs) {
var target = oArgs.target;
var elCell = this.getTdEl(target);
if(elCell) {
var oColumn = this.getColumn(elCell.cellIndex);
this.formatCell(elCell.firstChild, this.getRecord(elCell), oColumn);
}
else {
}
},
/**
* Overridable custom event handler to edit cell.
*
* @method onEventShowCellEditor
* @param oArgs.event {HTMLEvent} Event object.
* @param oArgs.target {HTMLElement} Target element.
*/
onEventShowCellEditor : function(oArgs) {
this.showCellEditor(oArgs.target);
},
/**
* Overridable custom event handler to save active CellEditor input.
*
* @method onEventSaveCellEditor
*/
onEventSaveCellEditor : function(oArgs) {
if(this._oCellEditor) {
if(this._oCellEditor.save) {
this._oCellEditor.save();
}
// Backward compatibility
else {
this.saveCellEditor();
}
}
},
/**
* Overridable custom event handler to cancel active CellEditor.
*
* @method onEventCancelCellEditor
*/
onEventCancelCellEditor : function(oArgs) {
if(this._oCellEditor) {
if(this._oCellEditor.cancel) {
this._oCellEditor.cancel();
}
// Backward compatibility
else {
this.cancelCellEditor();
}
}
},
/**
* Callback function receives data from DataSource and populates an entire
* DataTable with Records and TR elements, clearing previous Records, if any.
*
* @method onDataReturnInitializeTable
* @param sRequest {String} Original request.
* @param oResponse {Object} Response object.
* @param oPayload {MIXED} (optional) Additional argument(s)
*/
onDataReturnInitializeTable : function(sRequest, oResponse, oPayload) {
if((this instanceof DT) && this._sId) {
this.initializeTable();
this.onDataReturnSetRows(sRequest,oResponse,oPayload);
}
},
/**
* Callback function receives reponse from DataSource, replaces all existing
* Records in RecordSet, updates TR elements with new data, and updates state
* UI for pagination and sorting from payload data, if necessary.
*
* @method onDataReturnReplaceRows
* @param oRequest {MIXED} Original generated request.
* @param oResponse {Object} Response object.
* @param oPayload {MIXED} (optional) Additional argument(s)
*/
onDataReturnReplaceRows : function(oRequest, oResponse, oPayload) {
if((this instanceof DT) && this._sId) {
this.fireEvent("dataReturnEvent", {request:oRequest,response:oResponse,payload:oPayload});
// Pass data through abstract method for any transformations
var ok = this.doBeforeLoadData(oRequest, oResponse, oPayload),
pag = this.get('paginator'),
index = 0;
// Data ok to set
if(ok && oResponse && !oResponse.error && lang.isArray(oResponse.results)) {
// Update Records
this._oRecordSet.reset();
if (this.get('dynamicData')) {
if (oPayload && oPayload.pagination &&
lang.isNumber(oPayload.pagination.recordOffset)) {
index = oPayload.pagination.recordOffset;
} else if (pag) {
index = pag.getStartIndex();
}
}
this._oRecordSet.setRecords(oResponse.results, index | 0);
// Update state
this._handleDataReturnPayload(oRequest, oResponse, oPayload);
// Update UI
this.render();
}
// Error
else if(ok && oResponse.error) {
this.showTableMessage(this.get("MSG_ERROR"), DT.CLASS_ERROR);
}
}
},
/**
* Callback function receives data from DataSource and appends to an existing
* DataTable new Records and, if applicable, creates or updates
* corresponding TR elements.
*
* @method onDataReturnAppendRows
* @param sRequest {String} Original request.
* @param oResponse {Object} Response object.
* @param oPayload {MIXED} (optional) Additional argument(s)
*/
onDataReturnAppendRows : function(sRequest, oResponse, oPayload) {
if((this instanceof DT) && this._sId) {
this.fireEvent("dataReturnEvent", {request:sRequest,response:oResponse,payload:oPayload});
// Pass data through abstract method for any transformations
var ok = this.doBeforeLoadData(sRequest, oResponse, oPayload);
// Data ok to append
if(ok && oResponse && !oResponse.error && lang.isArray(oResponse.results)) {
// Append rows
this.addRows(oResponse.results);
// Update state
this._handleDataReturnPayload(sRequest, oResponse, oPayload);
}
// Error
else if(ok && oResponse.error) {
this.showTableMessage(this.get("MSG_ERROR"), DT.CLASS_ERROR);
}
}
},
/**
* Callback function receives data from DataSource and inserts new records
* starting at the index specified in oPayload.insertIndex. The value for
* oPayload.insertIndex can be populated when sending the request to the DataSource,
* or by accessing oPayload.insertIndex with the doBeforeLoadData() method at runtime.
* If applicable, creates or updates corresponding TR elements.
*
* @method onDataReturnInsertRows
* @param sRequest {String} Original request.
* @param oResponse {Object} Response object.
* @param oPayload {MIXED} Argument payload, looks in oPayload.insertIndex.
*/
onDataReturnInsertRows : function(sRequest, oResponse, oPayload) {
if((this instanceof DT) && this._sId) {
this.fireEvent("dataReturnEvent", {request:sRequest,response:oResponse,payload:oPayload});
// Pass data through abstract method for any transformations
var ok = this.doBeforeLoadData(sRequest, oResponse, oPayload);
// Data ok to append
if(ok && oResponse && !oResponse.error && lang.isArray(oResponse.results)) {
// Insert rows
this.addRows(oResponse.results, (oPayload ? oPayload.insertIndex : 0));
// Update state
this._handleDataReturnPayload(sRequest, oResponse, oPayload);
}
// Error
else if(ok && oResponse.error) {
this.showTableMessage(this.get("MSG_ERROR"), DT.CLASS_ERROR);
}
}
},
/**
* Callback function receives data from DataSource and incrementally updates Records
* starting at the index specified in oPayload.updateIndex. The value for
* oPayload.updateIndex can be populated when sending the request to the DataSource,
* or by accessing oPayload.updateIndex with the doBeforeLoadData() method at runtime.
* If applicable, creates or updates corresponding TR elements.
*
* @method onDataReturnUpdateRows
* @param sRequest {String} Original request.
* @param oResponse {Object} Response object.
* @param oPayload {MIXED} Argument payload, looks in oPayload.updateIndex.
*/
onDataReturnUpdateRows : function(sRequest, oResponse, oPayload) {
if((this instanceof DT) && this._sId) {
this.fireEvent("dataReturnEvent", {request:sRequest,response:oResponse,payload:oPayload});
// Pass data through abstract method for any transformations
var ok = this.doBeforeLoadData(sRequest, oResponse, oPayload);
// Data ok to append
if(ok && oResponse && !oResponse.error && lang.isArray(oResponse.results)) {
// Insert rows
this.updateRows((oPayload ? oPayload.updateIndex : 0), oResponse.results);
// Update state
this._handleDataReturnPayload(sRequest, oResponse, oPayload);
}
// Error
else if(ok && oResponse.error) {
this.showTableMessage(this.get("MSG_ERROR"), DT.CLASS_ERROR);
}
}
},
/**
* Callback function receives reponse from DataSource and populates the
* RecordSet with the results.
*
* @method onDataReturnSetRows
* @param oRequest {MIXED} Original generated request.
* @param oResponse {Object} Response object.
* @param oPayload {MIXED} (optional) Additional argument(s)
*/
onDataReturnSetRows : function(oRequest, oResponse, oPayload) {
if((this instanceof DT) && this._sId) {
this.fireEvent("dataReturnEvent", {request:oRequest,response:oResponse,payload:oPayload});
// Pass data through abstract method for any transformations
var ok = this.doBeforeLoadData(oRequest, oResponse, oPayload),
pag = this.get('paginator'),
index = 0;
// Data ok to set
if(ok && oResponse && !oResponse.error && lang.isArray(oResponse.results)) {
// Update Records
if (this.get('dynamicData')) {
if (oPayload && oPayload.pagination &&
lang.isNumber(oPayload.pagination.recordOffset)) {
index = oPayload.pagination.recordOffset;
} else if (pag) {
index = pag.getStartIndex();
}
this._oRecordSet.reset(); // Bug 2290604: dyanmic data shouldn't keep accumulating by default
}
this._oRecordSet.setRecords(oResponse.results, index | 0);
// Update state
this._handleDataReturnPayload(oRequest, oResponse, oPayload);
// Update UI
this.render();
}
// Error
else if(ok && oResponse.error) {
this.showTableMessage(this.get("MSG_ERROR"), DT.CLASS_ERROR);
}
}
else {
}
},
/**
* Hook to update oPayload before consumption.
*
* @method handleDataReturnPayload
* @param oRequest {MIXED} Original generated request.
* @param oResponse {Object} Response object.
* @param oPayload {MIXED} State values.
* @return oPayload {MIXED} State values.
*/
handleDataReturnPayload : function (oRequest, oResponse, oPayload) {
return oPayload;
},
/**
* Updates the DataTable with state data sent in an onDataReturn* payload.
*
* @method handleDataReturnPayload
* @param oRequest {MIXED} Original generated request.
* @param oResponse {Object} Response object.
* @param oPayload {MIXED} State values
*/
_handleDataReturnPayload : function (oRequest, oResponse, oPayload) {
oPayload = this.handleDataReturnPayload(oRequest, oResponse, oPayload);
if(oPayload) {
// Update pagination
var oPaginator = this.get('paginator');
if (oPaginator) {
// Update totalRecords
if(this.get("dynamicData")) {
if (widget.Paginator.isNumeric(oPayload.totalRecords)) {
oPaginator.set('totalRecords',oPayload.totalRecords);
}
}
else {
oPaginator.set('totalRecords',this._oRecordSet.getLength());
}
// Update other paginator values
if (lang.isObject(oPayload.pagination)) {
oPaginator.set('rowsPerPage',oPayload.pagination.rowsPerPage);
oPaginator.set('recordOffset',oPayload.pagination.recordOffset);
}
}
// Update sorting
if (oPayload.sortedBy) {
// Set the sorting values in preparation for refresh
this.set('sortedBy', oPayload.sortedBy);
}
// Backwards compatibility for sorting
else if (oPayload.sorting) {
// Set the sorting values in preparation for refresh
this.set('sortedBy', oPayload.sorting);
}
}
},
/////////////////////////////////////////////////////////////////////////////
//
// Custom Events
//
/////////////////////////////////////////////////////////////////////////////
/**
* Fired when the DataTable's rows are rendered from an initialized state.
*
* @event initEvent
*/
/**
* Fired before the DataTable's DOM is rendered or modified.
*
* @event beforeRenderEvent
*/
/**
* Fired when the DataTable's DOM is rendered or modified.
*
* @event renderEvent
*/
/**
* Fired when the DataTable's post-render routine is complete, including
* Column width validations.
*
* @event postRenderEvent
*/
/**
* Fired when the DataTable is disabled.
*
* @event disableEvent
*/
/**
* Fired when the DataTable is undisabled.
*
* @event undisableEvent
*/
/**
* Fired when data is returned from DataSource but before it is consumed by
* DataTable.
*
* @event dataReturnEvent
* @param oArgs.request {String} Original request.
* @param oArgs.response {Object} Response object.
*/
/**
* Fired when the DataTable has a focus event.
*
* @event tableFocusEvent
*/
/**
* Fired when the DataTable THEAD element has a focus event.
*
* @event theadFocusEvent
*/
/**
* Fired when the DataTable TBODY element has a focus event.
*
* @event tbodyFocusEvent
*/
/**
* Fired when the DataTable has a blur event.
*
* @event tableBlurEvent
*/
/*TODO implement theadBlurEvent
* Fired when the DataTable THEAD element has a blur event.
*
* @event theadBlurEvent
*/
/*TODO: implement tbodyBlurEvent
* Fired when the DataTable TBODY element has a blur event.
*
* @event tbodyBlurEvent
*/
/**
* Fired when the DataTable has a key event.
*
* @event tableKeyEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The DataTable's TABLE element.
*/
/**
* Fired when the DataTable THEAD element has a key event.
*
* @event theadKeyEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The DataTable's TABLE element.
*/
/**
* Fired when the DataTable TBODY element has a key event.
*
* @event tbodyKeyEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The DataTable's TABLE element.
*/
/**
* Fired when the DataTable has a mouseover.
*
* @event tableMouseoverEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The DataTable's TABLE element.
*
*/
/**
* Fired when the DataTable has a mouseout.
*
* @event tableMouseoutEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The DataTable's TABLE element.
*
*/
/**
* Fired when the DataTable has a mousedown.
*
* @event tableMousedownEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The DataTable's TABLE element.
*
*/
/**
* Fired when the DataTable has a mouseup.
*
* @event tableMouseupEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The DataTable's TABLE element.
*
*/
/**
* Fired when the DataTable has a click.
*
* @event tableClickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The DataTable's TABLE element.
*
*/
/**
* Fired when the DataTable has a dblclick.
*
* @event tableDblclickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The DataTable's TABLE element.
*
*/
/**
* Fired when a message is shown in the DataTable's message element.
*
* @event tableMsgShowEvent
* @param oArgs.html {String} The HTML displayed.
* @param oArgs.className {String} The className assigned.
*
*/
/**
* Fired when the DataTable's message element is hidden.
*
* @event tableMsgHideEvent
*/
/**
* Fired when a THEAD row has a mouseover.
*
* @event theadRowMouseoverEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a THEAD row has a mouseout.
*
* @event theadRowMouseoutEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a THEAD row has a mousedown.
*
* @event theadRowMousedownEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a THEAD row has a mouseup.
*
* @event theadRowMouseupEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a THEAD row has a click.
*
* @event theadRowClickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a THEAD row has a dblclick.
*
* @event theadRowDblclickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a THEAD cell has a mouseover.
*
* @event theadCellMouseoverEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TH element.
*
*/
/**
* Fired when a THEAD cell has a mouseout.
*
* @event theadCellMouseoutEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TH element.
*
*/
/**
* Fired when a THEAD cell has a mousedown.
*
* @event theadCellMousedownEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TH element.
*/
/**
* Fired when a THEAD cell has a mouseup.
*
* @event theadCellMouseupEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TH element.
*/
/**
* Fired when a THEAD cell has a click.
*
* @event theadCellClickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TH element.
*/
/**
* Fired when a THEAD cell has a dblclick.
*
* @event theadCellDblclickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TH element.
*/
/**
* Fired when a THEAD label has a mouseover.
*
* @event theadLabelMouseoverEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The SPAN element.
*
*/
/**
* Fired when a THEAD label has a mouseout.
*
* @event theadLabelMouseoutEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The SPAN element.
*
*/
/**
* Fired when a THEAD label has a mousedown.
*
* @event theadLabelMousedownEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The SPAN element.
*/
/**
* Fired when a THEAD label has a mouseup.
*
* @event theadLabelMouseupEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The SPAN element.
*/
/**
* Fired when a THEAD label has a click.
*
* @event theadLabelClickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The SPAN element.
*/
/**
* Fired when a THEAD label has a dblclick.
*
* @event theadLabelDblclickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The SPAN element.
*/
/**
* Fired when a column is sorted.
*
* @event columnSortEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
* @param oArgs.dir {String} Sort direction: YAHOO.widget.DataTable.CLASS_ASC
* or YAHOO.widget.DataTable.CLASS_DESC.
*/
/**
* Fired when a column width is set.
*
* @event columnSetWidthEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
* @param oArgs.width {Number} The width in pixels.
*/
/**
* Fired when a column width is unset.
*
* @event columnUnsetWidthEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
*/
/**
* Fired when a column is drag-resized.
*
* @event columnResizeEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
* @param oArgs.target {HTMLElement} The TH element.
* @param oArgs.width {Number} Width in pixels.
*/
/**
* Fired when a Column is moved to a new index.
*
* @event columnReorderEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
* @param oArgs.oldIndex {Number} The previous index position.
*/
/**
* Fired when a column is hidden.
*
* @event columnHideEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
*/
/**
* Fired when a column is shown.
*
* @event columnShowEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
*/
/**
* Fired when a column is selected.
*
* @event columnSelectEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
*/
/**
* Fired when a column is unselected.
*
* @event columnUnselectEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
*/
/**
* Fired when a column is removed.
*
* @event columnRemoveEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
*/
/**
* Fired when a column is inserted.
*
* @event columnInsertEvent
* @param oArgs.column {YAHOO.widget.Column} The Column instance.
* @param oArgs.index {Number} The index position.
*/
/**
* Fired when a column is highlighted.
*
* @event columnHighlightEvent
* @param oArgs.column {YAHOO.widget.Column} The highlighted Column.
*/
/**
* Fired when a column is unhighlighted.
*
* @event columnUnhighlightEvent
* @param oArgs.column {YAHOO.widget.Column} The unhighlighted Column.
*/
/**
* Fired when a row has a mouseover.
*
* @event rowMouseoverEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a row has a mouseout.
*
* @event rowMouseoutEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a row has a mousedown.
*
* @event rowMousedownEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a row has a mouseup.
*
* @event rowMouseupEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a row has a click.
*
* @event rowClickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a row has a dblclick.
*
* @event rowDblclickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TR element.
*/
/**
* Fired when a row is added.
*
* @event rowAddEvent
* @param oArgs.record {YAHOO.widget.Record} The added Record.
*/
/**
* Fired when rows are added.
*
* @event rowsAddEvent
* @param oArgs.record {YAHOO.widget.Record[]} The added Records.
*/
/**
* Fired when a row is updated.
*
* @event rowUpdateEvent
* @param oArgs.record {YAHOO.widget.Record} The updated Record.
* @param oArgs.oldData {Object} Object literal of the old data.
*/
/**
* Fired when a row is deleted.
*
* @event rowDeleteEvent
* @param oArgs.oldData {Object} Object literal of the deleted data.
* @param oArgs.recordIndex {Number} Index of the deleted Record.
* @param oArgs.trElIndex {Number} Index of the deleted TR element, if on current page.
*/
/**
* Fired when rows are deleted.
*
* @event rowsDeleteEvent
* @param oArgs.oldData {Object[]} Array of object literals of the deleted data.
* @param oArgs.recordIndex {Number} Index of the first deleted Record.
* @param oArgs.count {Number} Number of deleted Records.
*/
/**
* Fired when a row is selected.
*
* @event rowSelectEvent
* @param oArgs.el {HTMLElement} The selected TR element, if applicable.
* @param oArgs.record {YAHOO.widget.Record} The selected Record.
*/
/**
* Fired when a row is unselected.
*
* @event rowUnselectEvent
* @param oArgs.el {HTMLElement} The unselected TR element, if applicable.
* @param oArgs.record {YAHOO.widget.Record} The unselected Record.
*/
/**
* Fired when all row selections are cleared.
*
* @event unselectAllRowsEvent
*/
/**
* Fired when a row is highlighted.
*
* @event rowHighlightEvent
* @param oArgs.el {HTMLElement} The highlighted TR element.
* @param oArgs.record {YAHOO.widget.Record} The highlighted Record.
*/
/**
* Fired when a row is unhighlighted.
*
* @event rowUnhighlightEvent
* @param oArgs.el {HTMLElement} The highlighted TR element.
* @param oArgs.record {YAHOO.widget.Record} The highlighted Record.
*/
/**
* Fired when a cell is updated.
*
* @event cellUpdateEvent
* @param oArgs.record {YAHOO.widget.Record} The updated Record.
* @param oArgs.column {YAHOO.widget.Column} The updated Column.
* @param oArgs.oldData {Object} Original data value of the updated cell.
*/
/**
* Fired when a cell has a mouseover.
*
* @event cellMouseoverEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TD element.
*/
/**
* Fired when a cell has a mouseout.
*
* @event cellMouseoutEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TD element.
*/
/**
* Fired when a cell has a mousedown.
*
* @event cellMousedownEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TD element.
*/
/**
* Fired when a cell has a mouseup.
*
* @event cellMouseupEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TD element.
*/
/**
* Fired when a cell has a click.
*
* @event cellClickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TD element.
*/
/**
* Fired when a cell has a dblclick.
*
* @event cellDblclickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The TD element.
*/
/**
* Fired when a cell is formatted.
*
* @event cellFormatEvent
* @param oArgs.el {HTMLElement} The formatted TD element.
* @param oArgs.record {YAHOO.widget.Record} The associated Record instance.
* @param oArgs.column {YAHOO.widget.Column} The associated Column instance.
* @param oArgs.key {String} (deprecated) The key of the formatted cell.
*/
/**
* Fired when a cell is selected.
*
* @event cellSelectEvent
* @param oArgs.el {HTMLElement} The selected TD element.
* @param oArgs.record {YAHOO.widget.Record} The associated Record instance.
* @param oArgs.column {YAHOO.widget.Column} The associated Column instance.
* @param oArgs.key {String} (deprecated) The key of the selected cell.
*/
/**
* Fired when a cell is unselected.
*
* @event cellUnselectEvent
* @param oArgs.el {HTMLElement} The unselected TD element.
* @param oArgs.record {YAHOO.widget.Record} The associated Record.
* @param oArgs.column {YAHOO.widget.Column} The associated Column instance.
* @param oArgs.key {String} (deprecated) The key of the unselected cell.
*/
/**
* Fired when a cell is highlighted.
*
* @event cellHighlightEvent
* @param oArgs.el {HTMLElement} The highlighted TD element.
* @param oArgs.record {YAHOO.widget.Record} The associated Record instance.
* @param oArgs.column {YAHOO.widget.Column} The associated Column instance.
* @param oArgs.key {String} (deprecated) The key of the highlighted cell.
*/
/**
* Fired when a cell is unhighlighted.
*
* @event cellUnhighlightEvent
* @param oArgs.el {HTMLElement} The unhighlighted TD element.
* @param oArgs.record {YAHOO.widget.Record} The associated Record instance.
* @param oArgs.column {YAHOO.widget.Column} The associated Column instance.
* @param oArgs.key {String} (deprecated) The key of the unhighlighted cell.
*/
/**
* Fired when all cell selections are cleared.
*
* @event unselectAllCellsEvent
*/
/**
* Fired when a CellEditor is shown.
*
* @event editorShowEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
*/
/**
* Fired when a CellEditor has a keydown.
*
* @event editorKeydownEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
* @param oArgs.event {HTMLEvent} The event object.
*/
/**
* Fired when a CellEditor input is reverted.
*
* @event editorRevertEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
* @param oArgs.newData {Object} New data value from form input field.
* @param oArgs.oldData {Object} Old data value.
*/
/**
* Fired when a CellEditor input is saved.
*
* @event editorSaveEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
* @param oArgs.newData {Object} New data value from form input field.
* @param oArgs.oldData {Object} Old data value.
*/
/**
* Fired when a CellEditor input is canceled.
*
* @event editorCancelEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
*/
/**
* Fired when a CellEditor has a blur event.
*
* @event editorBlurEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
*/
/**
* Fired when a CellEditor is blocked.
*
* @event editorBlockEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
*/
/**
* Fired when a CellEditor is unblocked.
*
* @event editorUnblockEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
*/
/**
* Fired when a link is clicked.
*
* @event linkClickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The A element.
*/
/**
* Fired when a BUTTON element or INPUT element of type "button", "image",
* "submit", "reset" is clicked.
*
* @event buttonClickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The BUTTON element.
*/
/**
* Fired when a CHECKBOX element is clicked.
*
* @event checkboxClickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The CHECKBOX element.
*/
/**
* Fired when a SELECT element is changed.
*
* @event dropdownChangeEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The SELECT element.
*/
/**
* Fired when a RADIO element is clicked.
*
* @event radioClickEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The RADIO element.
*/
/////////////////////////////////////////////////////////////////////////////
//
// Deprecated APIs
//
/////////////////////////////////////////////////////////////////////////////
/*
* @method showCellEditorBtns
* @deprecated Use CellEditor.renderBtns()
*/
showCellEditorBtns : function(elContainer) {
// Buttons
var elBtnsDiv = elContainer.appendChild(document.createElement("div"));
Dom.addClass(elBtnsDiv, DT.CLASS_BUTTON);
// Save button
var elSaveBtn = elBtnsDiv.appendChild(document.createElement("button"));
Dom.addClass(elSaveBtn, DT.CLASS_DEFAULT);
elSaveBtn.innerHTML = "OK";
Ev.addListener(elSaveBtn, "click", function(oArgs, oSelf) {
oSelf.onEventSaveCellEditor(oArgs, oSelf);
oSelf.focusTbodyEl();
}, this, true);
// Cancel button
var elCancelBtn = elBtnsDiv.appendChild(document.createElement("button"));
elCancelBtn.innerHTML = "Cancel";
Ev.addListener(elCancelBtn, "click", function(oArgs, oSelf) {
oSelf.onEventCancelCellEditor(oArgs, oSelf);
oSelf.focusTbodyEl();
}, this, true);
},
/**
* @method resetCellEditor
* @deprecated Use destroyCellEditor
*/
resetCellEditor : function() {
var elContainer = this._oCellEditor.container;
elContainer.style.display = "none";
Ev.purgeElement(elContainer, true);
elContainer.innerHTML = "";
this._oCellEditor.value = null;
this._oCellEditor.isActive = false;
},
/**
* @event editorUpdateEvent
* @deprecated Use CellEditor class.
*/
/**
* @method getBody
* @deprecated Use getTbodyEl().
*/
getBody : function() {
// Backward compatibility
return this.getTbodyEl();
},
/**
* @method getCell
* @deprecated Use getTdEl().
*/
getCell : function(index) {
// Backward compatibility
return this.getTdEl(index);
},
/**
* @method getRow
* @deprecated Use getTrEl().
*/
getRow : function(index) {
// Backward compatibility
return this.getTrEl(index);
},
/**
* @method refreshView
* @deprecated Use render.
*/
refreshView : function() {
// Backward compatibility
this.render();
},
/**
* @method select
* @deprecated Use selectRow.
*/
select : function(els) {
// Backward compatibility
if(!lang.isArray(els)) {
els = [els];
}
for(var i=0; i 0) ?
"-"+this._elTbody.offsetTop+"px" : 0;
},
/**
* Sets focus on the given element.
*
* @method _focusEl
* @param el {HTMLElement} Element.
* @private
*/
_focusEl : function(el) {
el = el || this._elTbody;
var oSelf = this;
this._storeScrollPositions();
// http://developer.mozilla.org/en/docs/index.php?title=Key-navigable_custom_DHTML_widgets
// The timeout is necessary in both IE and Firefox 1.5, to prevent scripts from doing
// strange unexpected things as the user clicks on buttons and other controls.
// Bug 1921135: Wrap the whole thing in a setTimeout
setTimeout(function() {
setTimeout(function() {
try {
el.focus();
oSelf._restoreScrollPositions();
}
catch(e) {
}
},0);
}, 0);
},
/**
* Internal wrapper calls run() on render Chain instance.
*
* @method _runRenderChain
* @private
*/
_runRenderChain : function() {
this._storeScrollPositions();
this._oChainRender.run();
},
/**
* Stores scroll positions so they can be restored after a render.
*
* @method _storeScrollPositions
* @private
*/
_storeScrollPositions : function() {
this._nScrollTop = this._elBdContainer.scrollTop;
this._nScrollLeft = this._elBdContainer.scrollLeft;
},
/**
* Clears stored scroll positions to interrupt the automatic restore mechanism.
* Useful for setting scroll positions programmatically rather than as part of
* the post-render cleanup process.
*
* @method clearScrollPositions
* @private
*/
clearScrollPositions : function() {
this._nScrollTop = 0;
this._nScrollLeft = 0;
},
/**
* Restores scroll positions to stored value.
*
* @method _retoreScrollPositions
* @private
*/
_restoreScrollPositions : function() {
// Reset scroll positions
if(this._nScrollTop) {
this._elBdContainer.scrollTop = this._nScrollTop;
this._nScrollTop = null;
}
if(this._nScrollLeft) {
this._elBdContainer.scrollLeft = this._nScrollLeft;
this._nScrollLeft = null;
}
},
/**
* Helper function calculates and sets a validated width for a Column in a ScrollingDataTable.
*
* @method _validateColumnWidth
* @param oColumn {YAHOO.widget.Column} Column instance.
* @param elTd {HTMLElement} TD element to validate against.
* @private
*/
_validateColumnWidth : function(oColumn, elTd) {
// Only Columns without widths that are not hidden
if(!oColumn.width && !oColumn.hidden) {
var elTh = oColumn.getThEl();
// Unset a calculated auto-width
if(oColumn._calculatedWidth) {
this._setColumnWidth(oColumn, "auto", "visible");
}
// Compare auto-widths
if(elTh.offsetWidth !== elTd.offsetWidth) {
var elWider = (elTh.offsetWidth > elTd.offsetWidth) ?
oColumn.getThLinerEl() : elTd.firstChild;
// Grab the wider liner width, unless the minWidth is wider
var newWidth = Math.max(0,
(elWider.offsetWidth -(parseInt(Dom.getStyle(elWider,"paddingLeft"),10)|0) - (parseInt(Dom.getStyle(elWider,"paddingRight"),10)|0)),
oColumn.minWidth);
var sOverflow = 'visible';
// Now validate against maxAutoWidth
if((oColumn.maxAutoWidth > 0) && (newWidth > oColumn.maxAutoWidth)) {
newWidth = oColumn.maxAutoWidth;
sOverflow = "hidden";
}
// Set to the wider auto-width
this._elTbody.style.display = "none";
this._setColumnWidth(oColumn, newWidth+'px', sOverflow);
oColumn._calculatedWidth = newWidth;
this._elTbody.style.display = "";
}
}
},
/**
* For one or all Columns of a ScrollingDataTable, when Column is not hidden,
* and width is not set, syncs widths of header and body cells and
* validates that width against minWidth and/or maxAutoWidth as necessary.
*
* @method validateColumnWidths
* @param oArg.column {YAHOO.widget.Column} (optional) One Column to validate. If null, all Columns' widths are validated.
*/
validateColumnWidths : function(oColumn) {
// Validate there is at least one TR with proper TDs
var allKeys = this._oColumnSet.keys,
allKeysLength = allKeys.length,
elRow = this.getFirstTrEl();
// Reset overhang for IE
if(ua.ie) {
this._setOverhangValue(1);
}
if(allKeys && elRow && (elRow.childNodes.length === allKeysLength)) {
// Temporarily unsnap container since it causes inaccurate calculations
var sWidth = this.get("width");
if(sWidth) {
this._elHdContainer.style.width = "";
this._elBdContainer.style.width = "";
}
this._elContainer.style.width = "";
//Validate just one Column
if(oColumn && lang.isNumber(oColumn.getKeyIndex())) {
this._validateColumnWidth(oColumn, elRow.childNodes[oColumn.getKeyIndex()]);
}
// Iterate through all Columns to unset calculated widths in one pass
else {
var elTd, todos = [], thisTodo, i, len;
for(i=0; i elTd.offsetWidth) ?
oColumn.getThLinerEl() : elTd.firstChild;
// Grab the wider liner width, unless the minWidth is wider
var newWidth = Math.max(0,
(elWider.offsetWidth -(parseInt(Dom.getStyle(elWider,"paddingLeft"),10)|0) - (parseInt(Dom.getStyle(elWider,"paddingRight"),10)|0)),
oColumn.minWidth);
var sOverflow = 'visible';
// Now validate against maxAutoWidth
if((oColumn.maxAutoWidth > 0) && (newWidth > oColumn.maxAutoWidth)) {
newWidth = oColumn.maxAutoWidth;
sOverflow = "hidden";
}
todos[todos.length] = [oColumn, newWidth, sOverflow];
}
}
}
this._elTbody.style.display = "none";
for(i=0, len=todos.length; i elBdContainer.clientHeight) ?
// but account for y-scrollbar since it is visible
(elTbody.parentNode.clientWidth + 19) + "px" :
// no y-scrollbar, just borders
(elTbody.parentNode.clientWidth + 2) + "px";
}
},
/**
* Snaps container height for x-scrolling tables in IE. Syncs message TBODY width.
*
* @method _syncScrollX
* @private
*/
_syncScrollX : function() {
var elTbody = this._elTbody,
elBdContainer = this._elBdContainer;
// IE 6 and 7 only when y-scrolling not enabled
if(!this.get("height") && (ua.ie)) {
// Snap outer container height to content
elBdContainer.style.height =
// but account for x-scrollbar if it is visible
(elBdContainer.scrollWidth > elBdContainer.offsetWidth ) ?
(elTbody.parentNode.offsetHeight + 18) + "px" :
elTbody.parentNode.offsetHeight + "px";
}
// Sync message tbody
if(this._elTbody.rows.length === 0) {
this._elMsgTbody.parentNode.style.width = this.getTheadEl().parentNode.offsetWidth + "px";
}
else {
this._elMsgTbody.parentNode.style.width = "";
}
},
/**
* Adds/removes Column header overhang as necesary.
*
* @method _syncScrollOverhang
* @private
*/
_syncScrollOverhang : function() {
var elBdContainer = this._elBdContainer,
// Overhang should be either 1 (default) or 18px, depending on the location of the right edge of the table
nPadding = 1;
// Y-scrollbar is visible, which is when the overhang needs to jut out
if((elBdContainer.scrollHeight > elBdContainer.clientHeight) &&
// X-scrollbar is also visible, which means the right is jagged, not flush with the Column
(elBdContainer.scrollWidth > elBdContainer.clientWidth)) {
nPadding = 18;
}
this._setOverhangValue(nPadding);
},
/**
* Sets Column header overhang to given width.
*
* @method _setOverhangValue
* @param nBorderWidth {Number} Value of new border for overhang.
* @private
*/
_setOverhangValue : function(nBorderWidth) {
var aLastHeaders = this._oColumnSet.headers[this._oColumnSet.headers.length-1] || [],
len = aLastHeaders.length,
sPrefix = this._sId+"-fixedth-",
sValue = nBorderWidth + "px solid " + this.get("COLOR_COLUMNFILLER");
this._elThead.style.display = "none";
for(var i=0; i oColumn.minWidth) ? nWidth : oColumn.minWidth;
// Save state
oColumn.width = nWidth;
// Resize the DOM elements
this._setColumnWidth(oColumn, nWidth+"px");
this._syncScroll();
this.fireEvent("columnSetWidthEvent",{column:oColumn,width:nWidth});
}
// Unsets a width to auto-size
else if(nWidth === null) {
// Save state
oColumn.width = nWidth;
// Resize the DOM elements
this._setColumnWidth(oColumn, "auto");
this.validateColumnWidths(oColumn);
this.fireEvent("columnUnsetWidthEvent",{column:oColumn});
}
// Bug 2339454: resize then sort misaligment
this._clearTrTemplateEl();
}
else {
}
},
/**
* Scrolls to given row or cell
*
* @method scrollTo
* @param to {YAHOO.widget.Record | HTMLElement } Itme to scroll to.
*/
scrollTo : function(to) {
var td = this.getTdEl(to);
if(td) {
this.clearScrollPositions();
this.getBdContainerEl().scrollLeft = td.offsetLeft;
this.getBdContainerEl().scrollTop = td.parentNode.offsetTop;
}
else {
var tr = this.getTrEl(to);
if(tr) {
this.clearScrollPositions();
this.getBdContainerEl().scrollTop = tr.offsetTop;
}
}
},
/**
* Displays message within secondary TBODY.
*
* @method showTableMessage
* @param sHTML {String} (optional) Value for innerHTMlang.
* @param sClassName {String} (optional) Classname.
*/
showTableMessage : function(sHTML, sClassName) {
var elCell = this._elMsgTd;
if(lang.isString(sHTML)) {
elCell.firstChild.innerHTML = sHTML;
}
if(lang.isString(sClassName)) {
Dom.addClass(elCell.firstChild, sClassName);
}
// Needed for SDT only
var elThead = this.getTheadEl();
var elTable = elThead.parentNode;
var newWidth = elTable.offsetWidth;
this._elMsgTbody.parentNode.style.width = this.getTheadEl().parentNode.offsetWidth + "px";
this._elMsgTbody.style.display = "";
this.fireEvent("tableMsgShowEvent", {html:sHTML, className:sClassName});
},
/////////////////////////////////////////////////////////////////////////////
//
// Private Custom Event Handlers
//
/////////////////////////////////////////////////////////////////////////////
/**
* Handles Column mutations
*
* @method onColumnChange
* @param oArgs {Object} Custom Event data.
*/
_onColumnChange : function(oArg) {
// Figure out which Column changed
var oColumn = (oArg.column) ? oArg.column :
(oArg.editor) ? oArg.editor.column : null;
this._storeScrollPositions();
this.validateColumnWidths(oColumn);
},
/////////////////////////////////////////////////////////////////////////////
//
// Private DOM Event Handlers
//
/////////////////////////////////////////////////////////////////////////////
/**
* Syncs scrolltop and scrollleft of all TABLEs.
*
* @method _onScroll
* @param e {HTMLEvent} The scroll event.
* @param oSelf {YAHOO.widget.ScrollingDataTable} ScrollingDataTable instance.
* @private
*/
_onScroll : function(e, oSelf) {
oSelf._elHdContainer.scrollLeft = oSelf._elBdContainer.scrollLeft;
if(oSelf._oCellEditor && oSelf._oCellEditor.isActive) {
oSelf.fireEvent("editorBlurEvent", {editor:oSelf._oCellEditor});
oSelf.cancelCellEditor();
}
var elTarget = Ev.getTarget(e);
var elTag = elTarget.nodeName.toLowerCase();
oSelf.fireEvent("tableScrollEvent", {event:e, target:elTarget});
},
/**
* Handles keydown events on the THEAD element.
*
* @method _onTheadKeydown
* @param e {HTMLEvent} The key event.
* @param oSelf {YAHOO.widget.ScrollingDataTable} ScrollingDataTable instance.
* @private
*/
_onTheadKeydown : function(e, oSelf) {
// If tabbing to next TH label link causes THEAD to scroll,
// need to sync scrollLeft with TBODY
if(Ev.getCharCode(e) === 9) {
setTimeout(function() {
if((oSelf instanceof SDT) && oSelf._sId) {
oSelf._elBdContainer.scrollLeft = oSelf._elHdContainer.scrollLeft;
}
},0);
}
var elTarget = Ev.getTarget(e);
var elTag = elTarget.nodeName.toLowerCase();
var bKeepBubbling = true;
while(elTarget && (elTag != "table")) {
switch(elTag) {
case "body":
return;
case "input":
case "textarea":
// TODO: implement textareaKeyEvent
break;
case "thead":
bKeepBubbling = oSelf.fireEvent("theadKeyEvent",{target:elTarget,event:e});
break;
default:
break;
}
if(bKeepBubbling === false) {
return;
}
else {
elTarget = elTarget.parentNode;
if(elTarget) {
elTag = elTarget.nodeName.toLowerCase();
}
}
}
oSelf.fireEvent("tableKeyEvent",{target:(elTarget || oSelf._elContainer),event:e});
}
/**
* Fired when a fixed scrolling DataTable has a scroll.
*
* @event tableScrollEvent
* @param oArgs.event {HTMLEvent} The event object.
* @param oArgs.target {HTMLElement} The DataTable's CONTAINER element (in IE)
* or the DataTable's TBODY element (everyone else).
*
*/
});
})();
(function () {
var lang = YAHOO.lang,
util = YAHOO.util,
widget = YAHOO.widget,
ua = YAHOO.env.ua,
Dom = util.Dom,
Ev = util.Event,
DT = widget.DataTable;
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* The BaseCellEditor class provides base functionality common to all inline cell
* editors for a DataTable widget.
*
* @namespace YAHOO.widget
* @class BaseCellEditor
* @uses YAHOO.util.EventProvider
* @constructor
* @param sType {String} Type indicator, to map to YAHOO.widget.DataTable.Editors.
* @param oConfigs {Object} (Optional) Object literal of configs.
*/
widget.BaseCellEditor = function(sType, oConfigs) {
this._sId = this._sId || "yui-ceditor" + YAHOO.widget.BaseCellEditor._nCount++;
this._sType = sType;
// Validate inputs
this._initConfigs(oConfigs);
// Create Custom Events
this._initEvents();
// Draw UI
this.render();
};
var BCE = widget.BaseCellEditor;
/////////////////////////////////////////////////////////////////////////////
//
// Static members
//
/////////////////////////////////////////////////////////////////////////////
lang.augmentObject(BCE, {
/**
* Global instance counter.
*
* @property CellEditor._nCount
* @type Number
* @static
* @default 0
* @private
*/
_nCount : 0,
/**
* Class applied to CellEditor container.
*
* @property CellEditor.CLASS_CELLEDITOR
* @type String
* @static
* @default "yui-ceditor"
*/
CLASS_CELLEDITOR : "yui-ceditor"
});
BCE.prototype = {
/////////////////////////////////////////////////////////////////////////////
//
// Private members
//
/////////////////////////////////////////////////////////////////////////////
/**
* Unique id assigned to instance "yui-ceditorN", useful prefix for generating unique
* DOM ID strings and log messages.
*
* @property _sId
* @type String
* @private
*/
_sId : null,
/**
* Editor type.
*
* @property _sType
* @type String
* @private
*/
_sType : null,
/**
* DataTable instance.
*
* @property _oDataTable
* @type YAHOO.widget.DataTable
* @private
*/
_oDataTable : null,
/**
* Column instance.
*
* @property _oColumn
* @type YAHOO.widget.Column
* @default null
* @private
*/
_oColumn : null,
/**
* Record instance.
*
* @property _oRecord
* @type YAHOO.widget.Record
* @default null
* @private
*/
_oRecord : null,
/**
* TD element.
*
* @property _elTd
* @type HTMLElement
* @default null
* @private
*/
_elTd : null,
/**
* Container for inline editor.
*
* @property _elContainer
* @type HTMLElement
* @private
*/
_elContainer : null,
/**
* Reference to Cancel button, if available.
*
* @property _elCancelBtn
* @type HTMLElement
* @default null
* @private
*/
_elCancelBtn : null,
/**
* Reference to Save button, if available.
*
* @property _elSaveBtn
* @type HTMLElement
* @default null
* @private
*/
_elSaveBtn : null,
/////////////////////////////////////////////////////////////////////////////
//
// Private methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Initialize configs.
*
* @method _initConfigs
* @private
*/
_initConfigs : function(oConfigs) {
// Object literal defines CellEditor configs
if(oConfigs && YAHOO.lang.isObject(oConfigs)) {
for(var sConfig in oConfigs) {
if(sConfig) {
this[sConfig] = oConfigs[sConfig];
}
}
}
},
/**
* Initialize Custom Events.
*
* @method _initEvents
* @private
*/
_initEvents : function() {
this.createEvent("showEvent");
this.createEvent("keydownEvent");
this.createEvent("invalidDataEvent");
this.createEvent("revertEvent");
this.createEvent("saveEvent");
this.createEvent("cancelEvent");
this.createEvent("blurEvent");
this.createEvent("blockEvent");
this.createEvent("unblockEvent");
},
/////////////////////////////////////////////////////////////////////////////
//
// Public properties
//
/////////////////////////////////////////////////////////////////////////////
/**
* Implementer defined function that can submit the input value to a server. This
* function must accept the arguments fnCallback and oNewValue. When the submission
* is complete, the function must also call fnCallback(bSuccess, oNewValue) to
* finish the save routine in the CellEditor. This function can also be used to
* perform extra validation or input value manipulation.
*
* @property asyncSubmitter
* @type HTMLFunction
*/
asyncSubmitter : null,
/**
* Current value.
*
* @property value
* @type MIXED
*/
value : null,
/**
* Default value in case Record data is undefined. NB: Null values will not trigger
* the default value.
*
* @property defaultValue
* @type MIXED
* @default null
*/
defaultValue : null,
/**
* Validator function for input data, called from the DataTable instance scope,
* receives the arguments (inputValue, currentValue, editorInstance) and returns
* either the validated (or type-converted) value or undefined.
*
* @property validator
* @type HTMLFunction
* @default null
*/
validator : null,
/**
* If validation is enabled, resets input field of invalid data.
*
* @property resetInvalidData
* @type Boolean
* @default true
*/
resetInvalidData : true,
/**
* True if currently active.
*
* @property isActive
* @type Boolean
*/
isActive : false,
/**
* Text to display on Save button.
*
* @property LABEL_SAVE
* @type String
* @default "Save"
*/
LABEL_SAVE : "Save",
/**
* Text to display on Cancel button.
*
* @property LABEL_CANCEL
* @type String
* @default "Cancel"
*/
LABEL_CANCEL : "Cancel",
/**
* True if Save/Cancel buttons should not be displayed in the CellEditor.
*
* @property disableBtns
* @type Boolean
* @default false
*/
disableBtns : false,
/////////////////////////////////////////////////////////////////////////////
//
// Public methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* CellEditor instance name, for logging.
*
* @method toString
* @return {String} Unique name of the CellEditor instance.
*/
toString : function() {
return "CellEditor instance " + this._sId;
},
/**
* CellEditor unique ID.
*
* @method getId
* @return {String} Unique ID of the CellEditor instance.
*/
getId : function() {
return this._sId;
},
/**
* Returns reference to associated DataTable instance.
*
* @method getDataTable
* @return {YAHOO.widget.DataTable} DataTable instance.
*/
getDataTable : function() {
return this._oDataTable;
},
/**
* Returns reference to associated Column instance.
*
* @method getColumn
* @return {YAHOO.widget.Column} Column instance.
*/
getColumn : function() {
return this._oColumn;
},
/**
* Returns reference to associated Record instance.
*
* @method getRecord
* @return {YAHOO.widget.Record} Record instance.
*/
getRecord : function() {
return this._oRecord;
},
/**
* Returns reference to associated TD element.
*
* @method getTdEl
* @return {HTMLElement} TD element.
*/
getTdEl : function() {
return this._elTd;
},
/**
* Returns container element.
*
* @method getContainerEl
* @return {HTMLElement} Reference to container element.
*/
getContainerEl : function() {
return this._elContainer;
},
/**
* Nulls out the entire CellEditor instance and related objects, removes attached
* event listeners, and clears out DOM elements inside the container, removes
* container from the DOM.
*
* @method destroy
*/
destroy : function() {
this.unsubscribeAll();
// Column is late-binding in attach()
var oColumn = this.getColumn();
if(oColumn) {
oColumn.editor = null;
}
var elContainer = this.getContainerEl();
Ev.purgeElement(elContainer, true);
elContainer.parentNode.removeChild(elContainer);
},
/**
* Renders DOM elements and attaches event listeners.
*
* @method render
*/
render : function() {
if(this._elContainer) {
YAHOO.util.Event.purgeElement(this._elContainer, true);
this._elContainer.innerHTML = "";
}
// Render Cell Editor container element as first child of body
var elContainer = document.createElement("div");
elContainer.id = this.getId() + "-container"; // Needed for tracking blur event
elContainer.style.display = "none";
elContainer.tabIndex = 0;
elContainer.className = DT.CLASS_EDITOR;
document.body.insertBefore(elContainer, document.body.firstChild);
this._elContainer = elContainer;
// Handle ESC key
Ev.addListener(elContainer, "keydown", function(e, oSelf) {
// ESC cancels Cell Editor
if((e.keyCode == 27)) {
var target = Ev.getTarget(e);
// workaround for Mac FF3 bug that disabled clicks when ESC hit when
// select is open. [bug 2273056]
if (target.nodeName && target.nodeName.toLowerCase() === 'select') {
target.blur();
}
oSelf.cancel();
}
// Pass through event
oSelf.fireEvent("keydownEvent", {editor:this, event:e});
}, this);
this.renderForm();
// Show Save/Cancel buttons
if(!this.disableBtns) {
this.renderBtns();
}
this.doAfterRender();
},
/**
* Renders Save/Cancel buttons.
*
* @method renderBtns
*/
renderBtns : function() {
// Buttons
var elBtnsDiv = this.getContainerEl().appendChild(document.createElement("div"));
elBtnsDiv.className = DT.CLASS_BUTTON;
// Save button
var elSaveBtn = elBtnsDiv.appendChild(document.createElement("button"));
elSaveBtn.className = DT.CLASS_DEFAULT;
elSaveBtn.innerHTML = this.LABEL_SAVE;
Ev.addListener(elSaveBtn, "click", function(oArgs) {
this.save();
}, this, true);
this._elSaveBtn = elSaveBtn;
// Cancel button
var elCancelBtn = elBtnsDiv.appendChild(document.createElement("button"));
elCancelBtn.innerHTML = this.LABEL_CANCEL;
Ev.addListener(elCancelBtn, "click", function(oArgs) {
this.cancel();
}, this, true);
this._elCancelBtn = elCancelBtn;
},
/**
* Attach CellEditor for a new interaction.
*
* @method attach
* @param oDataTable {YAHOO.widget.DataTable} Associated DataTable instance.
* @param elCell {HTMLElement} Cell to edit.
*/
attach : function(oDataTable, elCell) {
// Validate
if(oDataTable instanceof YAHOO.widget.DataTable) {
this._oDataTable = oDataTable;
// Validate cell
elCell = oDataTable.getTdEl(elCell);
if(elCell) {
this._elTd = elCell;
// Validate Column
var oColumn = oDataTable.getColumn(elCell);
if(oColumn) {
this._oColumn = oColumn;
// Validate Record
var oRecord = oDataTable.getRecord(elCell);
if(oRecord) {
this._oRecord = oRecord;
var value = oRecord.getData(this.getColumn().getField());
this.value = (value !== undefined) ? value : this.defaultValue;
return true;
}
}
}
}
return false;
},
/**
* Moves container into position for display.
*
* @method move
*/
move : function() {
// Move Editor
var elContainer = this.getContainerEl(),
elTd = this.getTdEl(),
x = Dom.getX(elTd),
y = Dom.getY(elTd);
//TODO: remove scrolling logic
// SF doesn't get xy for cells in scrolling table
// when tbody display is set to block
if(isNaN(x) || isNaN(y)) {
var elTbody = this.getDataTable().getTbodyEl();
x = elTd.offsetLeft + // cell pos relative to table
Dom.getX(elTbody.parentNode) - // plus table pos relative to document
elTbody.scrollLeft; // minus tbody scroll
y = elTd.offsetTop + // cell pos relative to table
Dom.getY(elTbody.parentNode) - // plus table pos relative to document
elTbody.scrollTop + // minus tbody scroll
this.getDataTable().getTheadEl().offsetHeight; // account for fixed THEAD cells
}
elContainer.style.left = x + "px";
elContainer.style.top = y + "px";
},
/**
* Displays CellEditor UI in the correct position.
*
* @method show
*/
show : function() {
this.resetForm();
this.isActive = true;
this.getContainerEl().style.display = "";
this.focus();
this.fireEvent("showEvent", {editor:this});
},
/**
* Fires blockEvent
*
* @method block
*/
block : function() {
this.fireEvent("blockEvent", {editor:this});
},
/**
* Fires unblockEvent
*
* @method unblock
*/
unblock : function() {
this.fireEvent("unblockEvent", {editor:this});
},
/**
* Saves value of CellEditor and hides UI.
*
* @method save
*/
save : function() {
// Get new value
var inputValue = this.getInputValue();
var validValue = inputValue;
// Validate new value
if(this.validator) {
validValue = this.validator.call(this.getDataTable(), inputValue, this.value, this);
if(validValue === undefined ) {
if(this.resetInvalidData) {
this.resetForm();
}
this.fireEvent("invalidDataEvent",
{editor:this, oldData:this.value, newData:inputValue});
return;
}
}
var oSelf = this;
var finishSave = function(bSuccess, oNewValue) {
var oOrigValue = oSelf.value;
if(bSuccess) {
// Update new value
oSelf.value = oNewValue;
oSelf.getDataTable().updateCell(oSelf.getRecord(), oSelf.getColumn(), oNewValue);
// Hide CellEditor
oSelf.getContainerEl().style.display = "none";
oSelf.isActive = false;
oSelf.getDataTable()._oCellEditor = null;
oSelf.fireEvent("saveEvent",
{editor:oSelf, oldData:oOrigValue, newData:oSelf.value});
}
else {
oSelf.resetForm();
oSelf.fireEvent("revertEvent",
{editor:oSelf, oldData:oOrigValue, newData:oNewValue});
}
oSelf.unblock();
};
this.block();
if(lang.isFunction(this.asyncSubmitter)) {
this.asyncSubmitter.call(this, finishSave, validValue);
}
else {
finishSave(true, validValue);
}
},
/**
* Cancels CellEditor input and hides UI.
*
* @method cancel
*/
cancel : function() {
if(this.isActive) {
this.getContainerEl().style.display = "none";
this.isActive = false;
this.getDataTable()._oCellEditor = null;
this.fireEvent("cancelEvent", {editor:this});
}
else {
}
},
/**
* Renders form elements.
*
* @method renderForm
*/
renderForm : function() {
// To be implemented by subclass
},
/**
* Access to add additional event listeners.
*
* @method doAfterRender
*/
doAfterRender : function() {
// To be implemented by subclass
},
/**
* After rendering form, if disabledBtns is set to true, then sets up a mechanism
* to save input without them.
*
* @method handleDisabledBtns
*/
handleDisabledBtns : function() {
// To be implemented by subclass
},
/**
* Resets CellEditor UI to initial state.
*
* @method resetForm
*/
resetForm : function() {
// To be implemented by subclass
},
/**
* Sets focus in CellEditor.
*
* @method focus
*/
focus : function() {
// To be implemented by subclass
},
/**
* Retrieves input value from CellEditor.
*
* @method getInputValue
*/
getInputValue : function() {
// To be implemented by subclass
}
};
lang.augmentProto(BCE, util.EventProvider);
/////////////////////////////////////////////////////////////////////////////
//
// Custom Events
//
/////////////////////////////////////////////////////////////////////////////
/**
* Fired when a CellEditor is shown.
*
* @event showEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
*/
/**
* Fired when a CellEditor has a keydown.
*
* @event keydownEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
* @param oArgs.event {HTMLEvent} The event object.
*/
/**
* Fired when a CellEditor input is reverted due to invalid data.
*
* @event invalidDataEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
* @param oArgs.newData {Object} New data value from form input field.
* @param oArgs.oldData {Object} Old data value.
*/
/**
* Fired when a CellEditor input is reverted due to asyncSubmitter failure.
*
* @event revertEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
* @param oArgs.newData {Object} New data value from form input field.
* @param oArgs.oldData {Object} Old data value.
*/
/**
* Fired when a CellEditor input is saved.
*
* @event saveEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
* @param oArgs.newData {Object} New data value from form input field.
* @param oArgs.oldData {Object} Old data value.
*/
/**
* Fired when a CellEditor input is canceled.
*
* @event cancelEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
*/
/**
* Fired when a CellEditor has a blur event.
*
* @event blurEvent
* @param oArgs.editor {YAHOO.widget.CellEditor} The CellEditor instance.
*/
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* The CheckboxCellEditor class provides functionality for inline editing
* DataTable cell data with checkboxes.
*
* @namespace YAHOO.widget
* @class CheckboxCellEditor
* @extends YAHOO.widget.BaseCellEditor
* @constructor
* @param oConfigs {Object} (Optional) Object literal of configs.
*/
widget.CheckboxCellEditor = function(oConfigs) {
this._sId = "yui-checkboxceditor" + YAHOO.widget.BaseCellEditor._nCount++;
widget.CheckboxCellEditor.superclass.constructor.call(this, "checkbox", oConfigs);
};
// CheckboxCellEditor extends BaseCellEditor
lang.extend(widget.CheckboxCellEditor, BCE, {
/////////////////////////////////////////////////////////////////////////////
//
// CheckboxCellEditor public properties
//
/////////////////////////////////////////////////////////////////////////////
/**
* Array of checkbox values. Can either be a simple array (e.g., ["red","green","blue"])
* or a an array of objects (e.g., [{label:"red", value:"#FF0000"},
* {label:"green", value:"#00FF00"}, {label:"blue", value:"#0000FF"}]).
*
* @property checkboxOptions
* @type String[] | Object[]
*/
checkboxOptions : null,
/**
* Reference to the checkbox elements.
*
* @property checkboxes
* @type HTMLElement[]
*/
checkboxes : null,
/**
* Array of checked values
*
* @property value
* @type String[]
*/
value : null,
/////////////////////////////////////////////////////////////////////////////
//
// CheckboxCellEditor public methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Render a form with input(s) type=checkbox.
*
* @method renderForm
*/
renderForm : function() {
if(lang.isArray(this.checkboxOptions)) {
var checkboxOption, checkboxValue, checkboxId, elLabel, j, len;
// Create the checkbox buttons in an IE-friendly way...
for(j=0,len=this.checkboxOptions.length; j ";
// Create the labels in an IE-friendly way
elLabel = this.getContainerEl().appendChild(document.createElement("label"));
elLabel.htmlFor = checkboxId;
elLabel.innerHTML = lang.isValue(checkboxOption.label) ?
checkboxOption.label : checkboxOption;
}
// Store the reference to the checkbox elements
var allCheckboxes = [];
for(j=0; j "; // Needed for label
// Create the labels in an IE-friendly way
elLabel = this.getContainerEl().appendChild(document.createElement("label"));
elLabel.htmlFor = radioId;
elLabel.innerHTML = (lang.isValue(radioOption.label)) ?
radioOption.label : radioOption;
}
// Store the reference to the checkbox elements
var allRadios = [],
elRadio;
for(var j=0; j420) {
elTextbox = this.getContainerEl().appendChild(document.createElement("form")).appendChild(document.createElement("input"));
}
else {
elTextbox = this.getContainerEl().appendChild(document.createElement("input"));
}
elTextbox.type = "text";
this.textbox = elTextbox;
// Save on enter by default
// Bug: 1802582 Set up a listener on each textbox to track on keypress
// since SF/OP can't preventDefault on keydown
Ev.addListener(elTextbox, "keypress", function(v){
if((v.keyCode === 13)) {
// Prevent form submit
YAHOO.util.Event.preventDefault(v);
this.save();
}
}, this, true);
if(this.disableBtns) {
// By default this is no-op since enter saves by default
this.handleDisabledBtns();
}
},
/**
* Moves TextboxCellEditor UI to a cell.
*
* @method move
*/
move : function() {
this.textbox.style.width = this.getTdEl().offsetWidth + "px";
widget.TextboxCellEditor.superclass.move.call(this);
},
/**
* Resets TextboxCellEditor UI to initial state.
*
* @method resetForm
*/
resetForm : function() {
this.textbox.value = lang.isValue(this.value) ? this.value.toString() : "";
},
/**
* Sets focus in TextboxCellEditor.
*
* @method focus
*/
focus : function() {
// Bug 2303181, Bug 2263600
this.getDataTable()._focusEl(this.textbox);
this.textbox.select();
},
/**
* Returns new value for TextboxCellEditor.
*
* @method getInputValue
*/
getInputValue : function() {
return this.textbox.value;
}
});
// Copy static members to TextboxCellEditor class
lang.augmentObject(widget.TextboxCellEditor, BCE);
/////////////////////////////////////////////////////////////////////////////
//
// DataTable extension
//
/////////////////////////////////////////////////////////////////////////////
/**
* CellEditor subclasses.
* @property DataTable.Editors
* @type Object
* @static
*/
DT.Editors = {
checkbox : widget.CheckboxCellEditor,
"date" : widget.DateCellEditor,
dropdown : widget.DropdownCellEditor,
radio : widget.RadioCellEditor,
textarea : widget.TextareaCellEditor,
textbox : widget.TextboxCellEditor
};
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* Factory class for instantiating a BaseCellEditor subclass.
*
* @namespace YAHOO.widget
* @class CellEditor
* @extends YAHOO.widget.BaseCellEditor
* @constructor
* @param sType {String} Type indicator, to map to YAHOO.widget.DataTable.Editors.
* @param oConfigs {Object} (Optional) Object literal of configs.
*/
widget.CellEditor = function(sType, oConfigs) {
// Point to one of the subclasses
if(sType && DT.Editors[sType]) {
lang.augmentObject(BCE, DT.Editors[sType]);
return new DT.Editors[sType](oConfigs);
}
else {
return new BCE(null, oConfigs);
}
};
var CE = widget.CellEditor;
// Copy static members to CellEditor class
lang.augmentObject(CE, BCE);
})();
YAHOO.register("datatable", YAHOO.widget.DataTable, {version: "2.8.2r1", build: "7"});