head.js revision 201232b90752c6d505c32c25b94ba1c66e41f256
5462N/A/**
5462N/AView class responsible for rendering the `<thead>` section of a table. Used as
5462N/Athe default `headerView` for `Y.DataTable.Base` and `Y.DataTable` classes.
5462N/A
5462N/ATranslates the provided array of column configuration objects into a rendered
5462N/A`<thead>` based on the data in those objects.
5462N/A
5462N/A
5462N/AThe structure of the column data is expected to be a single array of objects,
5462N/Awhere each object corresponds to a `<th>`. Those objects may contain a
5462N/A`children` property containing a similarly structured array to indicate the
5462N/Anested cells should be grouped under the parent column's colspan in a separate
5462N/Arow of header cells. E.g.
5462N/A
5462N/A<pre><code>
5462N/Anew Y.DataTable.HeaderView({
5462N/A container: tableNode,
5462N/A columns: [
5462N/A { key: 'id' }, // no nesting
5462N/A { key: 'name', children: [
5462N/A { key: 'firstName', label: 'First' },
5462N/A { key: 'lastName', label: 'Last' } ] }
5462N/A ]
5462N/A}).render();
5462N/A</code></pre>
5462N/A
5462N/AThis would translate to the following visualization:
5462N/A
5462N/A<pre>
5462N/A---------------------
5462N/A| | name |
5462N/A| |---------------
5462N/A| id | First | Last |
5462N/A---------------------
5462N/A</pre>
5462N/A
5462N/ASupported properties of the column objects include:
5462N/A
5462N/A * `label` - The HTML content of the header cell.
5462N/A * `key` - If `label` is not specified, the `key` is used for content.
5462N/A * `children` - Array of columns to appear below this column in the next
5462N/A row.
5462N/A * `abbr` - The content of the 'abbr' attribute of the `<th>`
5462N/A
5462N/AThrough the life of instantiation and rendering, the column objects will have
5462N/Athe following properties added to them:
5462N/A
5462N/A * `colspan` - To supply the `<th>` attribute
5462N/A * `rowspan` - To supply the `<th>` attribute
5462N/A * `parent` - If the column is a child of another column, this points to
5462N/A its parent column
5462N/A * `_yuid` - A unique YUI generated id used as the `<th>`'s 'id' for
5462N/A reference in the data `<td>`'s 'headers' attribute.
5462N/A
5462N/AThe column object is also used to provide values for {placeholder} tokens in the
5462N/Ainstance's `CELL_TEMPLATE`, so you can modify the template and include other
5462N/Acolumn object properties to populate them.
5462N/A
5462N/A@module datatable-head
5462N/A@class HeaderView
5462N/A@namespace DataTable
5462N/A@extends View
5462N/A**/
5462N/Avar Lang = Y.Lang,
5462N/A fromTemplate = Lang.sub,
5462N/A isArray = Lang.isArray,
5462N/A toArray = Y.Array,
5462N/A
5462N/A ClassNameManager = Y.ClassNameManager,
5462N/A _getClassName = ClassNameManager.getClassName;
5462N/A
5462N/AY.namespace('DataTable').HeaderView = Y.Base.create('tableHeader', Y.View, [], {
5462N/A // -- Instance properties -------------------------------------------------
5462N/A
5462N/A /**
5462N/A Template used to create the table's header cell markup. Override this to
5462N/A customize how these cells' markup is created.
5462N/A
5462N/A @property CELL_TEMPLATE
5462N/A @type {HTML}
5462N/A @default '<th id="{_yuid}" abbr="{abbr} colspan="{colspan}" rowspan="{rowspan}">{content}</th>'
5462N/A **/
5462N/A CELL_TEMPLATE :
5462N/A '<th id="{_yuid}" abbr="{abbr}" colspan="{colspan}" rowspan="{rowspan}">{content}</th>',
5462N/A
5462N/A /**
5462N/A The data representation of the header rows to render. This is assigned by
5462N/A parsing the `columns` configuration array, and is used by the render()
5462N/A method.
5462N/A
5462N/A @property columns
5462N/A @type {Array[]}
5462N/A @default (initially unset)
5462N/A **/
5462N/A //TODO: should this be protected?
5462N/A //columns: null,
5462N/A
5462N/A /**
5462N/A The object that serves as the source of truth for column and row data.
5462N/A This property is assigned at instantiation from the `source` property of
5462N/A the configuration object passed to the constructor.
5462N/A
5462N/A @property source
5462N/A @type {Object}
5462N/A @default (initially unset)
5462N/A **/
5462N/A //TODO: should this be protected?
5462N/A //source: null,
5462N/A
5462N/A /**
5462N/A Template used to create the table's header row markup. Override this to
5462N/A customize the row markup.
5462N/A
5462N/A @property ROW_TEMPLATE
5462N/A @type {HTML}
5462N/A @default '<tr>{content}</tr>'
5462N/A **/
5462N/A ROW_TEMPLATE:
5462N/A '<tr>{content}</tr>',
5462N/A
5462N/A
5462N/A // -- Public methods ------------------------------------------------------
5462N/A
5462N/A /**
5462N/A Builds a CSS class name from the provided tokens. If the instance is
5462N/A created with `cssPrefix` or `source` in the configuration, it will use this
5462N/A prefix (the `_cssPrefix` of the `source` object) as the base token. This
5462N/A allows class instances to generate markup with class names that correspond
5462N/A to the parent class that is consuming them.
5462N/A
5462N/A @method getClassName
5462N/A @param {String} token* Any number of tokens to include in the class name
5462N/A @return {String} The generated class name
5462N/A **/
5462N/A getClassName: function () {
5462N/A var args = toArray(arguments);
5462N/A args.unshift(this._cssPrefix);
5462N/A args.push(true);
5462N/A
5462N/A return _getClassName.apply(ClassNameManager, args);
5462N/A },
5462N/A
5462N/A /**
5462N/A Creates the `<thead>` Node content by assembling markup generated by
5462N/A populating the `ROW_TEMPLATE` and `CELL_TEMPLATE` templates with content
5462N/A from the `columns` property.
5462N/A
5462N/A @method render
5462N/A @return {HeaderView} The instance
5462N/A @chainable
5462N/A **/
5462N/A render: function () {
5462N/A var thead = this.get('container'),
5462N/A columns = this.columns,
5462N/A defaults = {
5462N/A abbr: '',
5462N/A colspan: 1,
5462N/A rowspan: 1
5462N/A },
5462N/A i, len, j, jlen, col, html, content;
5462N/A
5462N/A if (thead && columns) {
5462N/A html = '';
5462N/A
5462N/A if (columns.length) {
5462N/A for (i = 0, len = columns.length; i < len; ++i) {
5462N/A content = '';
5462N/A
5462N/A for (j = 0, jlen = columns[i].length; j < jlen; ++j) {
5462N/A col = columns[i][j];
5462N/A content += fromTemplate(this.CELL_TEMPLATE,
5462N/A Y.merge(
5462N/A defaults,
5462N/A col, {
5462N/A content: col.label ||
5462N/A col.key ||
5462N/A ("Column " + (j + 1))
5462N/A }
5462N/A ));
5462N/A }
5462N/A
5462N/A html += fromTemplate(this.ROW_TEMPLATE, {
5462N/A content: content
5462N/A });
5462N/A }
5462N/A }
5462N/A
5462N/A thead.setContent(html);
5462N/A }
5462N/A
5462N/A this.bindUI();
return this;
},
// -- Protected and private properties and methods ------------------------
/**
The base token for classes created with the `getClassName` method.
@property _cssPrefix
@type {String}
@default 'yui3-table'
@protected
**/
_cssPrefix: ClassNameManager.getClassName('table'),
/**
Handles changes in the source's columns attribute. Redraws the headers.
@method _afterColumnsChange
@param {EventFacade} e The `columnsChange` event object
@protected
**/
_afterColumnsChange: function (e) {
this.columns = this._parseColumns(e.newVal);
this.render();
},
/**
Binds event subscriptions from the UI and the source (if assigned).
@method bindUI
@protected
**/
bindUI: function () {
if (this.source && !this._eventHandles.columnsChange) {
// TODO: How best to decouple this?
this._eventHandles.columnsChange =
this.source.after('columnsChange',
Y.bind('_afterColumnsChange', this));
}
},
/**
Destroys the instance.
@method destructor
@protected
**/
destructor: function () {
(new Y.EventHandle(Y.Object.values(this._eventHandles))).detach();
},
/**
Holds the event subscriptions needing to be detached when the instance is
`destroy()`ed.
@property _eventHandles
@type {Object}
@default undefined (initially unset)
@protected
**/
//_eventHandles: null,
/**
Initializes the instance. Reads the following configuration properties:
* `columns` - (REQUIRED) The initial column information
* `cssPrefix` - The base string for classes generated by `getClassName`
* `source` - The object to serve as source of truth for column info
@method initializer
@param {Object} config Configuration data
@protected
**/
initializer: function (config) {
config || (config = {});
var cssPrefix = config.cssPrefix || (config.source || {}).cssPrefix;
this.source = config.source;
this.columns = this._parseColumns(config.columns);
this._eventHandles = [];
if (cssPrefix) {
this._cssPrefix = cssPrefix;
}
},
/**
Translate the input column format into a structure useful for rendering a
`<thead>`, rows, and cells. The structure of the input is expected to be a
single array of objects, where each object corresponds to a `<th>`. Those
objects may contain a `children` property containing a similarly structured
array to indicate the nested cells should be grouped under the parent
column's colspan in a separate row of header cells. E.g.
<pre><code>
[
{ key: 'id' }, // no nesting
{ key: 'name', children: [
{ key: 'firstName', label: 'First' },
{ key: 'lastName', label: 'Last' } ] }
]
</code></pre>
would indicate two header rows with the first column 'id' being assigned a
`rowspan` of `2`, the 'name' column appearing in the first row with a
`colspan` of `2`, and the 'firstName' and 'lastName' columns appearing in
the second row, below the 'name' column.
<pre>
---------------------
| | name |
| |---------------
| id | First | Last |
---------------------
</pre>
Supported properties of the column objects include:
* `label` - The HTML content of the header cell.
* `key` - If `label` is not specified, the `key` is used for content.
* `children` - Array of columns to appear below this column in the next
row.
* `abbr` - The content of the 'abbr' attribute of the `<th>`
The output structure is basically a simulation of the `<thead>` structure
with arrays for rows and objects for cells. Column objects have the
following properties added to them:
* `colspan` - Per the `<th>` attribute
* `rowspan` - Per the `<th>` attribute
* `parent` - If the column is a child of another column, this points to
its parent column
* `_yuid` - A unique YUI generated id used as the `<th>`'s 'id' for
reference in the data `<td>`'s 'headers' attribute.
The column object is also used to provide values for {placeholder}
replacement in the `CELL_TEMPLATE`, so you can modify the template and
include other column object properties to populate them.
@method _parseColumns
@param {Object[]} data Array of column object data
@return {Array[]} An array of arrays corresponding to the header row
structure to render
@protected
**/
_parseColumns: function (data) {
var columns = [],
stack = [],
rowSpan = 1,
entry, row, col, children, parent, i, len, j;
if (isArray(data) && data.length) {
// First pass, assign colspans and calculate row count for
// non-nested headers' rowspan
stack.push([data, -1]);
while (stack.length) {
entry = stack[stack.length - 1];
row = entry[0];
i = entry[1] + 1;
for (len = row.length; i < len; ++i) {
col = row[i];
children = col.children;
Y.stamp(col);
if (isArray(children) && children.length) {
stack.push([children, -1]);
entry[1] = i;
rowSpan = Math.max(rowSpan, stack.length);
// break to let the while loop process the children
break;
} else {
col.colspan = 1;
}
}
if (i >= len) {
// All columns in this row are processed
if (stack.length > 1) {
entry = stack[stack.length - 2];
parent = entry[0][entry[1]];
parent.colspan = 0;
for (i = 0, len = row.length; i < len; ++i) {
// Can't use .length because in 3+ rows, colspan
// needs to aggregate the colspans of children
parent.colspan += row[i].colspan;
// Assign the parent column for ease of navigation
row[i].parent = parent;
}
}
stack.pop();
}
}
// Second pass, build row arrays and assign rowspan
for (i = 0; i < rowSpan; ++i) {
columns.push([]);
}
stack.push([data, -1]);
while (stack.length) {
entry = stack[stack.length - 1];
row = entry[0];
i = entry[1] + 1;
for (len = row.length; i < len; ++i) {
col = row[i];
children = col.children;
columns[stack.length - 1].push(col);
entry[1] = i;
if (children && children.length) {
// parent cells must assume rowspan 1 (long story)
// break to let the while loop process the children
stack.push([children, -1]);
break;
} else {
// collect the IDs of parent cols
col.headers = [col._yuid];
for (j = stack.length - 2; j >= 0; --j) {
parent = stack[j][0][stack[j][1]];
col.headers.unshift(parent._yuid);
}
col.rowspan = rowSpan - stack.length + 1;
}
}
if (i >= len) {
// All columns in this row are processed
stack.pop();
}
}
}
return columns;
}
});