").appendTo($container);
- $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto");
+ if (!options.showHeaderRow) {
+ $headerRowScroller.hide();
+ }
- $canvas = $("
").appendTo($container);
+ $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto");
- $focusSink2 = $focusSink.clone().appendTo($container);
+ $canvas = $("
").appendTo($viewport);
- if (!options.explicitInitialization) {
- finishInitialization();
- }
- }
+ if (options.createFooterRow) {
+ $footerRowScroller = $("").appendTo($container);
+ $footerRow = $("
").appendTo($footerRowScroller);
+ $footerRowSpacer = $("
")
+ .css("width", getCanvasWidth() + scrollbarDimensions.width + "px")
+ .appendTo($footerRowScroller);
- function finishInitialization() {
- if (!initialized) {
- initialized = true;
-
- viewportW = parseFloat($.css($container[0], "width", true));
-
- // header columns and cells may have different padding/border skewing width calculations (box-sizing, hello?)
- // calculate the diff so we can set consistent sizes
- measureCellPaddingAndBorder();
-
- // for usability reasons, all text selection in SlickGrid is disabled
- // with the exception of input and textarea elements (selection must
- // be enabled there so that editors work as expected); note that
- // selection in grid cells (grid body) is already unavailable in
- // all browsers except IE
- disableSelection($headers); // disable all text selection in header (including input and textarea)
-
- if (!options.enableTextSelectionOnCells) {
- // disable text selection in grid cells except in input and textarea elements
- // (this is IE-specific, because selectstart event will only fire in IE)
- $viewport.bind("selectstart.ui", function (event) {
- return $(event.target).is("input,textarea");
- });
- }
-
- updateColumnCaches();
- createColumnHeaders();
- setupColumnSort();
- createCssRules();
- resizeCanvas();
- bindAncestorScrollEvents();
-
- $container
- .bind("resize.slickgrid", resizeCanvas);
- $viewport
- //.bind("click", handleClick)
- .bind("scroll", handleScroll);
- $headerScroller
- .bind("contextmenu", handleHeaderContextMenu)
- .bind("click", handleHeaderClick)
- .delegate(".slick-header-column", "mouseenter", handleHeaderMouseEnter)
- .delegate(".slick-header-column", "mouseleave", handleHeaderMouseLeave);
- $headerRowScroller
- .bind("scroll", handleHeaderRowScroll);
- $focusSink.add($focusSink2)
- .bind("keydown", handleKeyDown);
- $canvas
- .bind("keydown", handleKeyDown)
- .bind("click", handleClick)
- .bind("dblclick", handleDblClick)
- .bind("contextmenu", handleContextMenu)
- .bind("draginit", handleDragInit)
- .bind("dragstart", {distance: 3}, handleDragStart)
- .bind("drag", handleDrag)
- .bind("dragend", handleDragEnd)
- .delegate(".slick-cell", "mouseenter", handleMouseEnter)
- .delegate(".slick-cell", "mouseleave", handleMouseLeave);
-
- // Work around http://crbug.com/312427.
- if (navigator.userAgent.toLowerCase().match(/webkit/) &&
- navigator.userAgent.toLowerCase().match(/macintosh/)) {
- $canvas.bind("mousewheel", handleMouseWheel);
- }
- }
- }
+ if (!options.showFooterRow) {
+ $footerRowScroller.hide();
+ }
+ }
- function registerPlugin(plugin) {
- plugins.unshift(plugin);
- plugin.init(self);
- }
+ $focusSink2 = $focusSink.clone().appendTo($container);
- function unregisterPlugin(plugin) {
- for (var i = plugins.length; i >= 0; i--) {
- if (plugins[i] === plugin) {
- if (plugins[i].destroy) {
- plugins[i].destroy();
- }
- plugins.splice(i, 1);
- break;
- }
- }
- }
+ if (!options.explicitInitialization) {
+ finishInitialization();
+ }
- function setSelectionModel(model) {
- if (selectionModel) {
- selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged);
- if (selectionModel.destroy) {
- selectionModel.destroy();
+ setTimeout(function () { $('.' + uid).css('display', 'block'); },0);
}
- }
- selectionModel = model;
- if (selectionModel) {
- selectionModel.init(self);
- selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged);
- }
- }
+ function finishInitialization() {
+ if (!initialized) {
+ initialized = true;
- function getSelectionModel() {
- return selectionModel;
- }
+ viewportW = parseFloat($.css($container[0], "width", true));
- function getCanvasNode() {
- return $canvas[0];
- }
+ // header columns and cells may have different padding/border skewing width calculations (box-sizing, hello?)
+ // calculate the diff so we can set consistent sizes
+ measureCellPaddingAndBorder();
- function measureScrollbar() {
- var $c = $("
").appendTo("body");
- var dim = {
- width: $c.width() - $c[0].clientWidth,
- height: $c.height() - $c[0].clientHeight
- };
- $c.remove();
- return dim;
- }
+ // for usability reasons, all text selection in SlickGrid is disabled
+ // with the exception of input and textarea elements (selection must
+ // be enabled there so that editors work as expected); note that
+ // selection in grid cells (grid body) is already unavailable in
+ // all browsers except IE
+ disableSelection($headers); // disable all text selection in header (including input and textarea)
- function getHeadersWidth() {
- var headersWidth = 0;
- for (var i = 0, ii = columns.length; i < ii; i++) {
- var width = columns[i].width;
- headersWidth += width;
- }
- headersWidth += scrollbarDimensions.width;
- return Math.max(headersWidth, viewportW) + 1000;
- }
+ if (!options.enableTextSelectionOnCells) {
+ // disable text selection in grid cells except in input and textarea elements
+ // (this is IE-specific, because selectstart event will only fire in IE)
+ $viewport.bind("selectstart.ui", function (event) {
+ return $(event.target).is("input,textarea");
+ });
+ }
- function getCanvasWidth() {
- var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
- var rowWidth = 0;
- var i = columns.length;
- while (i--) {
- rowWidth += columns[i].width;
- }
- return options.fullWidthRows ? Math.max(rowWidth, availableWidth) : rowWidth;
- }
+ updateColumnCaches();
+ createColumnHeaders();
+ setupColumnSort();
+ createCssRules();
+ resizeCanvas();
+ bindAncestorScrollEvents();
+
+ $container
+ .bind("resize.slickgrid", resizeCanvas);
+ $viewport
+ //.bind("click", handleClick)
+ .bind("scroll", handleScroll);
+ $headerScroller
+ .bind("contextmenu", handleHeaderContextMenu)
+ .bind("click", handleHeaderClick)
+ .delegate(".slick-header-column", "mouseenter", handleHeaderMouseEnter)
+ .delegate(".slick-header-column", "mouseleave", handleHeaderMouseLeave);
+ $headerRowScroller
+ .bind("scroll", handleHeaderRowScroll);
+
+ if (options.createFooterRow) {
+ $footerRowScroller
+ .bind("scroll", handleFooterRowScroll);
+ }
- function updateCanvasWidth(forceColumnWidthsUpdate) {
- var oldCanvasWidth = canvasWidth;
- canvasWidth = getCanvasWidth();
+ $focusSink.add($focusSink2)
+ .bind("keydown", handleKeyDown)
+ .bind("focus", handleFocusSink)
+ .bind("blur", handleBlurSink);
+ $canvas
+ .bind("keydown", handleKeyDown)
+ .bind("click", handleClick)
+ .bind("dblclick", handleDblClick)
+ .bind("contextmenu", handleContextMenu)
+ .bind("draginit", handleDragInit)
+ .bind("dragstart", {distance: 3}, handleDragStart)
+ .bind("drag", handleDrag)
+ .bind("dragend", handleDragEnd)
+ .delegate(".slick-cell", "mouseenter", handleMouseEnter)
+ .delegate(".slick-cell", "mouseleave", handleMouseLeave);
+
+ // Work around http://crbug.com/312427.
+ if (navigator.userAgent.toLowerCase().match(/webkit/) &&
+ navigator.userAgent.toLowerCase().match(/macintosh/)) {
+ $canvas.bind("mousewheel", handleMouseWheel);
+ }
+ restoreCssFromHiddenInit();
+ }
+ }
- if (canvasWidth != oldCanvasWidth) {
- $canvas.width(canvasWidth);
- $headerRow.width(canvasWidth);
- $headers.width(getHeadersWidth());
- viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width);
- }
+ function cacheCssForHiddenInit() {
+ // handle display:none on container or container parents
+ $hiddenParents = $container.parents().andSelf().not(':visible');
+ $hiddenParents.each(function() {
+ var old = {};
+ for ( var name in cssShow ) {
+ old[ name ] = this.style[ name ];
+ this.style[ name ] = cssShow[ name ];
+ }
+ oldProps.push(old);
+ });
+ }
- $headerRowSpacer.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0));
+ function restoreCssFromHiddenInit() {
+ // finish handle display:none on container or container parents
+ // - put values back the way they were
+ $hiddenParents.each(function(i) {
+ var old = oldProps[i];
+ for ( var name in cssShow ) {
+ this.style[ name ] = old[ name ];
+ }
+ });
+ }
- if (canvasWidth != oldCanvasWidth || forceColumnWidthsUpdate) {
- applyColumnWidths();
- }
- }
+ function registerPlugin(plugin) {
+ plugins.unshift(plugin);
+ plugin.init(self);
+ }
- function disableSelection($target) {
- if ($target && $target.jquery) {
- $target
- .attr("unselectable", "on")
- .css("MozUserSelect", "none")
- .bind("selectstart.ui", function () {
- return false;
- }); // from jquery:ui.core.js 1.7.2
- }
- }
+ function unregisterPlugin(plugin) {
+ for (var i = plugins.length; i >= 0; i--) {
+ if (plugins[i] === plugin) {
+ if (plugins[i].destroy) {
+ plugins[i].destroy();
+ }
+ plugins.splice(i, 1);
+ break;
+ }
+ }
+ }
- function getMaxSupportedCssHeight() {
- var supportedHeight = 1000000;
- // FF reports the height back but still renders blank after ~6M px
- var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000;
- var div = $("
").appendTo(document.body);
+ function setSelectionModel(model) {
+ if (selectionModel) {
+ selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged);
+ if (selectionModel.destroy) {
+ selectionModel.destroy();
+ }
+ }
- while (true) {
- var test = supportedHeight * 2;
- div.css("height", test);
- if (test > testUpTo || div.height() !== test) {
- break;
- } else {
- supportedHeight = test;
+ selectionModel = model;
+ if (selectionModel) {
+ selectionModel.init(self);
+ selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged);
+ }
}
- }
-
- div.remove();
- return supportedHeight;
- }
- // TODO: this is static. need to handle page mutation.
- function bindAncestorScrollEvents() {
- var elem = $canvas[0];
- while ((elem = elem.parentNode) != document.body && elem != null) {
- // bind to scroll containers only
- if (elem == $viewport[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) {
- var $elem = $(elem);
- if (!$boundAncestors) {
- $boundAncestors = $elem;
- } else {
- $boundAncestors = $boundAncestors.add($elem);
- }
- $elem.bind("scroll." + uid, handleActiveCellPositionChange);
- }
- }
- }
+ function getSelectionModel() {
+ return selectionModel;
+ }
- function unbindAncestorScrollEvents() {
- if (!$boundAncestors) {
- return;
- }
- $boundAncestors.unbind("scroll." + uid);
- $boundAncestors = null;
- }
+ function getCanvasNode() {
+ return $canvas[0];
+ }
- function updateColumnHeader(columnId, title, toolTip) {
- if (!initialized) { return; }
- var idx = getColumnIndex(columnId);
- if (idx == null) {
- return;
- }
+ function measureScrollbar() {
+ var $c = $("
").appendTo("body");
+ var dim = {
+ width: $c.width() - $c[0].clientWidth,
+ height: $c.height() - $c[0].clientHeight
+ };
+ $c.remove();
+ return dim;
+ }
- var columnDef = columns[idx];
- var $header = $headers.children().eq(idx);
- if ($header) {
- if (title !== undefined) {
- columns[idx].name = title;
+ function getHeadersWidth() {
+ var headersWidth = 0;
+ for (var i = 0, ii = columns.length; i < ii; i++) {
+ var width = columns[i].width;
+ headersWidth += width;
+ }
+ headersWidth += scrollbarDimensions.width;
+ return Math.max(headersWidth, viewportW) + 1000;
}
- if (toolTip !== undefined) {
- columns[idx].toolTip = toolTip;
+
+ function getCanvasWidth() {
+ var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
+ var rowWidth = 0;
+ var i = columns.length;
+ while (i--) {
+ rowWidth += columns[i].width;
+ }
+ return options.fullWidthRows ? Math.max(rowWidth, availableWidth) : rowWidth;
}
- trigger(self.onBeforeHeaderCellDestroy, {
- "node": $header[0],
- "column": columnDef
- });
+ function updateCanvasWidth(forceColumnWidthsUpdate) {
+ var oldCanvasWidth = canvasWidth;
+ canvasWidth = getCanvasWidth();
- $header
- .attr("title", toolTip || "")
- .children().eq(0).html(title);
+ if (canvasWidth != oldCanvasWidth) {
+ $canvas.width(canvasWidth);
+ $headerRow.width(canvasWidth);
+ if (options.createFooterRow) { $footerRow.width(canvasWidth); }
+ $headers.width(getHeadersWidth());
+ viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width);
+ }
- trigger(self.onHeaderCellRendered, {
- "node": $header[0],
- "column": columnDef
- });
- }
- }
+ var w=canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0);
+ $headerRowSpacer.width(w);
+ if (options.createFooterRow) { $footerRowSpacer.width(w); }
- function getHeaderRow() {
- return $headerRow[0];
- }
+ if (canvasWidth != oldCanvasWidth || forceColumnWidthsUpdate) {
+ applyColumnWidths();
+ }
+ }
- function getHeaderRowColumn(columnId) {
- var idx = getColumnIndex(columnId);
- var $header = $headerRow.children().eq(idx);
- return $header && $header[0];
- }
+ function disableSelection($target) {
+ if ($target && $target.jquery) {
+ $target
+ .attr("unselectable", "on")
+ .css("MozUserSelect", "none")
+ .bind("selectstart.ui", function () {
+ return false;
+ }); // from jquery:ui.core.js 1.7.2
+ }
+ }
- function createColumnHeaders() {
- function onMouseEnter() {
- $(this).addClass("ui-state-hover");
- }
-
- function onMouseLeave() {
- $(this).removeClass("ui-state-hover");
- }
-
- $headers.find(".slick-header-column")
- .each(function() {
- var columnDef = $(this).data("column");
- if (columnDef) {
- trigger(self.onBeforeHeaderCellDestroy, {
- "node": this,
- "column": columnDef
- });
- }
- });
- $headers.empty();
- $headers.width(getHeadersWidth());
-
- $headerRow.find(".slick-headerrow-column")
- .each(function() {
- var columnDef = $(this).data("column");
- if (columnDef) {
- trigger(self.onBeforeHeaderRowCellDestroy, {
- "node": this,
- "column": columnDef
- });
- }
- });
- $headerRow.empty();
+ function getMaxSupportedCssHeight() {
+ var supportedHeight = 1000000;
+ // FF reports the height back but still renders blank after ~6M px
+ var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000;
+ var div = $("
").appendTo(document.body);
- for (var i = 0; i < columns.length; i++) {
- var m = columns[i];
+ while (true) {
+ var test = supportedHeight * 2;
+ div.css("height", test);
+ if (test > testUpTo || div.height() !== test) {
+ break;
+ } else {
+ supportedHeight = test;
+ }
+ }
- var header = $("
")
- .html("
" + m.name + "")
- .width(m.width - headerColumnWidthDiff)
- .attr("id", "" + uid + m.id)
- .attr("title", m.toolTip || "")
- .data("column", m)
- .addClass(m.headerCssClass || "")
- .appendTo($headers);
+ div.remove();
+ return supportedHeight;
+ }
- if (options.enableColumnReorder || m.sortable) {
- header
- .on('mouseenter', onMouseEnter)
- .on('mouseleave', onMouseLeave);
+ // TODO: this is static. need to handle page mutation.
+ function bindAncestorScrollEvents() {
+ var elem = $canvas[0];
+ while ((elem = elem.parentNode) != document.body && elem != null) {
+ // bind to scroll containers only
+ if (elem == $viewport[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) {
+ var $elem = $(elem);
+ if (!$boundAncestors) {
+ $boundAncestors = $elem;
+ } else {
+ $boundAncestors = $boundAncestors.add($elem);
+ }
+ $elem.bind("scroll." + uid, handleActiveCellPositionChange);
+ }
+ }
}
- if (m.sortable) {
- header.addClass("slick-header-sortable");
- header.append("
");
+ function unbindAncestorScrollEvents() {
+ if (!$boundAncestors) {
+ return;
+ }
+ $boundAncestors.unbind("scroll." + uid);
+ $boundAncestors = null;
}
- trigger(self.onHeaderCellRendered, {
- "node": header[0],
- "column": m
- });
+ function updateColumnHeader(columnId, title, toolTip) {
+ if (!initialized) { return; }
+ var idx = getColumnIndex(columnId);
+ if (idx == null) {
+ return;
+ }
+
+ var columnDef = columns[idx];
+ var $header = $headers.children().eq(idx);
+ if ($header) {
+ if (title !== undefined) {
+ columns[idx].name = title;
+ }
+ if (toolTip !== undefined) {
+ columns[idx].toolTip = toolTip;
+ }
- if (options.showHeaderRow) {
- var headerRowCell = $("
")
- .data("column", m)
- .appendTo($headerRow);
+ trigger(self.onBeforeHeaderCellDestroy, {
+ "node": $header[0],
+ "column": columnDef,
+ "grid": self
+ });
+
+ $header
+ .attr("title", toolTip || "")
+ .children().eq(0).html(title);
- trigger(self.onHeaderRowCellRendered, {
- "node": headerRowCell[0],
- "column": m
- });
+ trigger(self.onHeaderCellRendered, {
+ "node": $header[0],
+ "column": columnDef,
+ "grid": self
+ });
+ }
}
- }
- setSortColumns(sortColumns);
- setupColumnResize();
- if (options.enableColumnReorder) {
- setupColumnReorder();
- }
- }
+ function getHeaderRow() {
+ return $headerRow[0];
+ }
- function setupColumnSort() {
- $headers.click(function (e) {
- // temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328)
- e.metaKey = e.metaKey || e.ctrlKey;
+ function getFooterRow() {
+ return $footerRow[0];
+ }
- if ($(e.target).hasClass("slick-resizable-handle")) {
- return;
+ function getHeaderRowColumn(columnId) {
+ var idx = getColumnIndex(columnId);
+ var $header = $headerRow.children().eq(idx);
+ return $header && $header[0];
}
- var $col = $(e.target).closest(".slick-header-column");
- if (!$col.length) {
- return;
+ function getFooterRowColumn(columnId) {
+ var idx = getColumnIndex(columnId);
+ var $footer = $footerRow.children().eq(idx);
+ return $footer && $footer[0];
}
- var column = $col.data("column");
- if (column.sortable) {
- if (!getEditorLock().commitCurrentEdit()) {
- return;
- }
+ function createColumnHeaders() {
+ function onMouseEnter() {
+ $(this).addClass("ui-state-hover");
+ }
- var sortOpts = null;
- var i = 0;
- for (; i < sortColumns.length; i++) {
- if (sortColumns[i].columnId == column.id) {
- sortOpts = sortColumns[i];
- sortOpts.sortAsc = !sortOpts.sortAsc;
- break;
+ function onMouseLeave() {
+ $(this).removeClass("ui-state-hover");
}
- }
- if (e.metaKey && options.multiColumnSort) {
- if (sortOpts) {
- sortColumns.splice(i, 1);
+ $headers.find(".slick-header-column")
+ .each(function() {
+ var columnDef = $(this).data("column");
+ if (columnDef) {
+ trigger(self.onBeforeHeaderCellDestroy, {
+ "node": this,
+ "column": columnDef,
+ "grid": self
+ });
+ }
+ });
+ $headers.empty();
+ $headers.width(getHeadersWidth());
+
+ $headerRow.find(".slick-headerrow-column")
+ .each(function() {
+ var columnDef = $(this).data("column");
+ if (columnDef) {
+ trigger(self.onBeforeHeaderRowCellDestroy, {
+ "node": this,
+ "column": columnDef,
+ "grid": self
+ });
+ }
+ });
+ $headerRow.empty();
+
+ if (options.createFooterRow) {
+ $footerRow.find(".slick-footerrow-column")
+ .each(function() {
+ var columnDef = $(this).data("column");
+ if (columnDef) {
+ trigger(self.onBeforeFooterRowCellDestroy, {
+ "node": this,
+ "column": columnDef
+ });
+ }
+ });
+ $footerRow.empty();
}
- }
- else {
- if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) {
- sortColumns = [];
+
+ for (var i = 0; i < columns.length; i++) {
+ var m = columns[i];
+
+ var header = $("
")
+ .html("
" + m.name + "")
+ .width(m.width - headerColumnWidthDiff)
+ .attr("id", "" + uid + m.id)
+ .attr("title", m.toolTip || "")
+ .data("column", m)
+ .addClass(m.headerCssClass || "")
+ .appendTo($headers);
+
+ if (options.enableColumnReorder || m.sortable) {
+ header
+ .on('mouseenter', onMouseEnter)
+ .on('mouseleave', onMouseLeave);
+ }
+
+ if (m.sortable) {
+ header.addClass("slick-header-sortable");
+ header.append("
");
+ }
+
+ trigger(self.onHeaderCellRendered, {
+ "node": header[0],
+ "column": m,
+ "grid": self
+ });
+
+ if (options.showHeaderRow) {
+ var headerRowCell = $("
")
+ .data("column", m)
+ .appendTo($headerRow);
+
+ trigger(self.onHeaderRowCellRendered, {
+ "node": headerRowCell[0],
+ "column": m,
+ "grid": self
+ });
+ }
+ if (options.createFooterRow && options.showFooterRow) {
+ var footerRowCell = $("
")
+ .data("column", m)
+ .appendTo($footerRow);
+
+ trigger(self.onFooterRowCellRendered, {
+ "node": footerRowCell[0],
+ "column": m
+ });
+ }
}
- if (!sortOpts) {
- sortOpts = { columnId: column.id, sortAsc: column.defaultSortAsc };
- sortColumns.push(sortOpts);
- } else if (sortColumns.length == 0) {
- sortColumns.push(sortOpts);
+ setSortColumns(sortColumns);
+ setupColumnResize();
+ if (options.enableColumnReorder) {
+ setupColumnReorder();
}
- }
+ }
+
+ function setupColumnSort() {
+ $headers.click(function (e) {
+ // temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328)
+ e.metaKey = e.metaKey || e.ctrlKey;
+
+ if ($(e.target).hasClass("slick-resizable-handle")) {
+ return;
+ }
+
+ var $col = $(e.target).closest(".slick-header-column");
+ if (!$col.length) {
+ return;
+ }
+
+ var column = $col.data("column");
+ if (column.sortable) {
+ if (!getEditorLock().commitCurrentEdit()) {
+ return;
+ }
+
+ var sortOpts = null;
+ var i = 0;
+ for (; i < sortColumns.length; i++) {
+ if (sortColumns[i].columnId == column.id) {
+ sortOpts = sortColumns[i];
+ sortOpts.sortAsc = !sortOpts.sortAsc;
+ break;
+ }
+ }
- setSortColumns(sortColumns);
+ if (e.metaKey && options.multiColumnSort) {
+ if (sortOpts) {
+ sortColumns.splice(i, 1);
+ }
+ }
+ else {
+ if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) {
+ sortColumns = [];
+ }
+
+ if (!sortOpts) {
+ sortOpts = { columnId: column.id, sortAsc: column.defaultSortAsc };
+ sortColumns.push(sortOpts);
+ } else if (sortColumns.length == 0) {
+ sortColumns.push(sortOpts);
+ }
+ }
- if (!options.multiColumnSort) {
- trigger(self.onSort, {
- multiColumnSort: false,
- sortCol: column,
- sortAsc: sortOpts.sortAsc}, e);
- } else {
- trigger(self.onSort, {
- multiColumnSort: true,
- sortCols: $.map(sortColumns, function(col) {
- return {sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc };
- })}, e);
- }
+ setSortColumns(sortColumns);
+
+ if (!options.multiColumnSort) {
+ trigger(self.onSort, {
+ multiColumnSort: false,
+ sortCol: column,
+ sortAsc: sortOpts.sortAsc,
+ grid: self}, e);
+ } else {
+ trigger(self.onSort, {
+ multiColumnSort: true,
+ sortCols: $.map(sortColumns, function(col) {
+ return {sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc };
+ }),
+ grid: self}, e);
+ }
+ }
+ });
}
- });
- }
- function setupColumnReorder() {
- $headers.filter(":ui-sortable").sortable("destroy");
- $headers.sortable({
- containment: "parent",
- distance: 3,
- axis: "x",
- cursor: "default",
- tolerance: "intersection",
- helper: "clone",
- placeholder: "slick-sortable-placeholder ui-state-default slick-header-column",
- start: function (e, ui) {
- ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff);
- $(ui.helper).addClass("slick-header-column-active");
- },
- beforeStop: function (e, ui) {
- $(ui.helper).removeClass("slick-header-column-active");
- },
- stop: function (e) {
- if (!getEditorLock().commitCurrentEdit()) {
- $(this).sortable("cancel");
- return;
- }
-
- var reorderedIds = $headers.sortable("toArray");
- var reorderedColumns = [];
- for (var i = 0; i < reorderedIds.length; i++) {
- reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]);
- }
- setColumns(reorderedColumns);
-
- trigger(self.onColumnsReordered, {});
- e.stopPropagation();
- setupColumnResize();
- }
- });
- }
+ function setupColumnReorder() {
+ $headers.filter(":ui-sortable").sortable("destroy");
+ $headers.sortable({
+ containment: "parent",
+ distance: 3,
+ axis: "x",
+ cursor: "default",
+ tolerance: "intersection",
+ helper: "clone",
+ placeholder: "slick-sortable-placeholder ui-state-default slick-header-column",
+ start: function (e, ui) {
+ ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff);
+ $(ui.helper).addClass("slick-header-column-active");
+ },
+ beforeStop: function (e, ui) {
+ $(ui.helper).removeClass("slick-header-column-active");
+ },
+ stop: function (e) {
+ if (!getEditorLock().commitCurrentEdit()) {
+ $(this).sortable("cancel");
+ return;
+ }
- function setupColumnResize() {
- var $col, j, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable;
- columnElements = $headers.children();
- columnElements.find(".slick-resizable-handle").remove();
- columnElements.each(function (i, e) {
- if (columns[i].resizable) {
- if (firstResizable === undefined) {
- firstResizable = i;
- }
- lastResizable = i;
- }
- });
- if (firstResizable === undefined) {
- return;
- }
- columnElements.each(function (i, e) {
- if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) {
- return;
- }
- $col = $(e);
- $("
")
- .appendTo(e)
- .bind("dragstart", function (e, dd) {
- if (!getEditorLock().commitCurrentEdit()) {
- return false;
- }
- pageX = e.pageX;
- $(this).parent().addClass("slick-header-column-active");
- var shrinkLeewayOnRight = null, stretchLeewayOnRight = null;
- // lock each column's width option to current width
- columnElements.each(function (i, e) {
- columns[i].previousWidth = $(e).outerWidth();
- });
- if (options.forceFitColumns) {
- shrinkLeewayOnRight = 0;
- stretchLeewayOnRight = 0;
- // colums on right affect maxPageX/minPageX
- for (j = i + 1; j < columnElements.length; j++) {
- c = columns[j];
- if (c.resizable) {
- if (stretchLeewayOnRight !== null) {
- if (c.maxWidth) {
- stretchLeewayOnRight += c.maxWidth - c.previousWidth;
- } else {
- stretchLeewayOnRight = null;
- }
+ var reorderedIds = $headers.sortable("toArray");
+ var reorderedColumns = [];
+ for (var i = 0; i < reorderedIds.length; i++) {
+ reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]);
}
- shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
- }
+ setColumns(reorderedColumns);
+
+ trigger(self.onColumnsReordered, {grid: self});
+ e.stopPropagation();
+ setupColumnResize();
}
- }
- var shrinkLeewayOnLeft = 0, stretchLeewayOnLeft = 0;
- for (j = 0; j <= i; j++) {
- // columns on left only affect minPageX
- c = columns[j];
- if (c.resizable) {
- if (stretchLeewayOnLeft !== null) {
- if (c.maxWidth) {
- stretchLeewayOnLeft += c.maxWidth - c.previousWidth;
- } else {
- stretchLeewayOnLeft = null;
+ });
+ }
+
+ function setupColumnResize() {
+ var $col, j, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable;
+ columnElements = $headers.children();
+ columnElements.find(".slick-resizable-handle").remove();
+ columnElements.each(function (i, e) {
+ if (columns[i].resizable) {
+ if (firstResizable === undefined) {
+ firstResizable = i;
}
- }
- shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
- }
- }
- if (shrinkLeewayOnRight === null) {
- shrinkLeewayOnRight = 100000;
- }
- if (shrinkLeewayOnLeft === null) {
- shrinkLeewayOnLeft = 100000;
- }
- if (stretchLeewayOnRight === null) {
- stretchLeewayOnRight = 100000;
- }
- if (stretchLeewayOnLeft === null) {
- stretchLeewayOnLeft = 100000;
- }
- maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft);
- minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight);
- })
- .bind("drag", function (e, dd) {
- var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x;
- if (d < 0) { // shrink column
- x = d;
- for (j = i; j >= 0; j--) {
- c = columns[j];
- if (c.resizable) {
- actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
- if (x && c.previousWidth + x < actualMinWidth) {
- x += c.previousWidth - actualMinWidth;
- c.width = actualMinWidth;
- } else {
- c.width = c.previousWidth + x;
- x = 0;
+ lastResizable = i;
+ }
+ });
+ if (firstResizable === undefined) {
+ return;
+ }
+ columnElements.each(function (i, e) {
+ if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) {
+ return;
+ }
+ $col = $(e);
+ $("
")
+ .appendTo(e)
+ .bind("dragstart", function (e, dd) {
+ if (!getEditorLock().commitCurrentEdit()) {
+ return false;
+ }
+ pageX = e.pageX;
+ $(this).parent().addClass("slick-header-column-active");
+ var shrinkLeewayOnRight = null, stretchLeewayOnRight = null;
+ // lock each column's width option to current width
+ columnElements.each(function (i, e) {
+ columns[i].previousWidth = $(e).outerWidth();
+ });
+ if (options.forceFitColumns) {
+ shrinkLeewayOnRight = 0;
+ stretchLeewayOnRight = 0;
+ // colums on right affect maxPageX/minPageX
+ for (j = i + 1; j < columnElements.length; j++) {
+ c = columns[j];
+ if (c.resizable) {
+ if (stretchLeewayOnRight !== null) {
+ if (c.maxWidth) {
+ stretchLeewayOnRight += c.maxWidth - c.previousWidth;
+ } else {
+ stretchLeewayOnRight = null;
+ }
+ }
+ shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
+ }
+ }
+ }
+ var shrinkLeewayOnLeft = 0, stretchLeewayOnLeft = 0;
+ for (j = 0; j <= i; j++) {
+ // columns on left only affect minPageX
+ c = columns[j];
+ if (c.resizable) {
+ if (stretchLeewayOnLeft !== null) {
+ if (c.maxWidth) {
+ stretchLeewayOnLeft += c.maxWidth - c.previousWidth;
+ } else {
+ stretchLeewayOnLeft = null;
+ }
+ }
+ shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
+ }
+ }
+ if (shrinkLeewayOnRight === null) {
+ shrinkLeewayOnRight = 100000;
+ }
+ if (shrinkLeewayOnLeft === null) {
+ shrinkLeewayOnLeft = 100000;
+ }
+ if (stretchLeewayOnRight === null) {
+ stretchLeewayOnRight = 100000;
+ }
+ if (stretchLeewayOnLeft === null) {
+ stretchLeewayOnLeft = 100000;
+ }
+ maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft);
+ minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight);
+ })
+ .bind("drag", function (e, dd) {
+ var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x;
+ if (d < 0) { // shrink column
+ x = d;
+ for (j = i; j >= 0; j--) {
+ c = columns[j];
+ if (c.resizable) {
+ actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
+ if (x && c.previousWidth + x < actualMinWidth) {
+ x += c.previousWidth - actualMinWidth;
+ c.width = actualMinWidth;
+ } else {
+ c.width = c.previousWidth + x;
+ x = 0;
+ }
+ }
+ }
+
+ if (options.forceFitColumns) {
+ x = -d;
+ for (j = i + 1; j < columnElements.length; j++) {
+ c = columns[j];
+ if (c.resizable) {
+ if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
+ x -= c.maxWidth - c.previousWidth;
+ c.width = c.maxWidth;
+ } else {
+ c.width = c.previousWidth + x;
+ x = 0;
+ }
+ }
+ }
+ }
+ } else { // stretch column
+ x = d;
+ for (j = i; j >= 0; j--) {
+ c = columns[j];
+ if (c.resizable) {
+ if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
+ x -= c.maxWidth - c.previousWidth;
+ c.width = c.maxWidth;
+ } else {
+ c.width = c.previousWidth + x;
+ x = 0;
+ }
+ }
+ }
+
+ if (options.forceFitColumns) {
+ x = -d;
+ for (j = i + 1; j < columnElements.length; j++) {
+ c = columns[j];
+ if (c.resizable) {
+ actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
+ if (x && c.previousWidth + x < actualMinWidth) {
+ x += c.previousWidth - actualMinWidth;
+ c.width = actualMinWidth;
+ } else {
+ c.width = c.previousWidth + x;
+ x = 0;
+ }
+ }
+ }
+ }
+ }
+ applyColumnHeaderWidths();
+ if (options.syncColumnCellResize) {
+ applyColumnWidths();
+ }
+ })
+ .bind("dragend", function (e, dd) {
+ var newWidth;
+ $(this).parent().removeClass("slick-header-column-active");
+ for (j = 0; j < columnElements.length; j++) {
+ c = columns[j];
+ newWidth = $(columnElements[j]).outerWidth();
+
+ if (c.previousWidth !== newWidth && c.rerenderOnResize) {
+ invalidateAllRows();
+ }
+ }
+ updateCanvasWidth(true);
+ render();
+ trigger(self.onColumnsResized, {grid: self});
+ });
+ });
+ }
+
+ function getVBoxDelta($el) {
+ var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
+ var delta = 0;
+ $.each(p, function (n, val) {
+ delta += parseFloat($el.css(val)) || 0;
+ });
+ return delta;
+ }
+
+ function measureCellPaddingAndBorder() {
+ var el;
+ var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"];
+ var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
+
+ // jquery prior to version 1.8 handles .width setter/getter as a direct css write/read
+ // jquery 1.8 changed .width to read the true inner element width if box-sizing is set to border-box, and introduced a setter for .outerWidth
+ // so for equivalent functionality, prior to 1.8 use .width, and after use .outerWidth
+ var verArray = $.fn.jquery.split('.');
+ jQueryNewWidthBehaviour = (verArray[0]==1 && verArray[1]>=8) || verArray[0] >=2;
+
+ el = $("
-
").appendTo($headers);
+ headerColumnWidthDiff = headerColumnHeightDiff = 0;
+ if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
+ $.each(h, function (n, val) {
+ headerColumnWidthDiff += parseFloat(el.css(val)) || 0;
+ });
+ $.each(v, function (n, val) {
+ headerColumnHeightDiff += parseFloat(el.css(val)) || 0;
+ });
+ }
+ el.remove();
+
+ var r = $("
").appendTo($canvas);
+ el = $("
-
").appendTo(r);
+ cellWidthDiff = cellHeightDiff = 0;
+ if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
+ $.each(h, function (n, val) {
+ cellWidthDiff += parseFloat(el.css(val)) || 0;
+ });
+ $.each(v, function (n, val) {
+ cellHeightDiff += parseFloat(el.css(val)) || 0;
+ });
+ }
+ r.remove();
+
+ absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff);
+ }
+
+ function createCssRules() {
+ $style = $("").appendTo($("head"));
+ var rowHeight = (options.rowHeight - cellHeightDiff);
+ var rules = [
+ "." + uid + " .slick-header-column { left: 1000px; }",
+ "." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }",
+ "." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }",
+ "." + uid + " .slick-footerrow-columns { height:" + options.footerRowHeight + "px; }",
+ "." + uid + " .slick-cell { height:" + rowHeight + "px; }",
+ "." + uid + " .slick-row { height:" + options.rowHeight + "px; }"
+ ];
+
+ for (var i = 0; i < columns.length; i++) {
+ rules.push("." + uid + " .l" + i + " { }");
+ rules.push("." + uid + " .r" + i + " { }");
+ }
+
+ if ($style[0].styleSheet) { // IE
+ $style[0].styleSheet.cssText = rules.join(" ");
+ } else {
+ $style[0].appendChild(document.createTextNode(rules.join(" ")));
+ }
+ }
+
+ function getColumnCssRules(idx) {
+ if (!stylesheet) {
+ var sheets = document.styleSheets;
+ for (var i = 0; i < sheets.length; i++) {
+ if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) {
+ stylesheet = sheets[i];
+ break;
}
- }
}
- if (options.forceFitColumns) {
- x = -d;
- for (j = i + 1; j < columnElements.length; j++) {
- c = columns[j];
- if (c.resizable) {
- if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
- x -= c.maxWidth - c.previousWidth;
- c.width = c.maxWidth;
- } else {
- c.width = c.previousWidth + x;
- x = 0;
- }
+ if (!stylesheet) {
+ throw new Error("Cannot find stylesheet.");
+ }
+
+ // find and cache column CSS rules
+ columnCssRulesL = [];
+ columnCssRulesR = [];
+ var cssRules = (stylesheet.cssRules || stylesheet.rules);
+ var matches, columnIdx;
+ for (var i = 0; i < cssRules.length; i++) {
+ var selector = cssRules[i].selectorText;
+ if (matches = /\.l\d+/.exec(selector)) {
+ columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
+ columnCssRulesL[columnIdx] = cssRules[i];
+ } else if (matches = /\.r\d+/.exec(selector)) {
+ columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
+ columnCssRulesR[columnIdx] = cssRules[i];
}
- }
}
- } else { // stretch column
- x = d;
- for (j = i; j >= 0; j--) {
- c = columns[j];
- if (c.resizable) {
- if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
- x -= c.maxWidth - c.previousWidth;
- c.width = c.maxWidth;
+ }
+
+ return {
+ "left": columnCssRulesL[idx],
+ "right": columnCssRulesR[idx]
+ };
+ }
+
+ function removeCssRules() {
+ $style.remove();
+ stylesheet = null;
+ }
+
+ function destroy() {
+ getEditorLock().cancelCurrentEdit();
+
+ trigger(self.onBeforeDestroy, {grid: self});
+
+ var i = plugins.length;
+ while(i--) {
+ unregisterPlugin(plugins[i]);
+ }
+
+ if (options.enableColumnReorder) {
+ $headers.filter(":ui-sortable").sortable("destroy");
+ }
+
+ unbindAncestorScrollEvents();
+ $container.unbind(".slickgrid");
+ removeCssRules();
+
+ $canvas.unbind("draginit dragstart dragend drag");
+ $container.empty().removeClass(uid);
+ }
+
+
+ //////////////////////////////////////////////////////////////////////////////////////////////
+ // General
+
+ function trigger(evt, args, e) {
+ e = e || new Slick.EventData();
+ args = args || {};
+ args.grid = self;
+ return evt.notify(args, e, self);
+ }
+
+ function getEditorLock() {
+ return options.editorLock;
+ }
+
+ function getEditController() {
+ return editController;
+ }
+
+ function getColumnIndex(id) {
+ return columnsById[id];
+ }
+
+ function autosizeColumns() {
+ var i, c,
+ widths = [],
+ shrinkLeeway = 0,
+ total = 0,
+ prevTotal,
+ availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
+
+ for (i = 0; i < columns.length; i++) {
+ c = columns[i];
+ widths.push(c.width);
+ total += c.width;
+ if (c.resizable) {
+ shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth);
+ }
+ }
+
+ // shrink
+ prevTotal = total;
+ while (total > availWidth && shrinkLeeway) {
+ var shrinkProportion = (total - availWidth) / shrinkLeeway;
+ for (i = 0; i < columns.length && total > availWidth; i++) {
+ c = columns[i];
+ var width = widths[i];
+ if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) {
+ continue;
+ }
+ var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth);
+ var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1;
+ shrinkSize = Math.min(shrinkSize, width - absMinWidth);
+ total -= shrinkSize;
+ shrinkLeeway -= shrinkSize;
+ widths[i] -= shrinkSize;
+ }
+ if (prevTotal <= total) { // avoid infinite loop
+ break;
+ }
+ prevTotal = total;
+ }
+
+ // grow
+ prevTotal = total;
+ while (total < availWidth) {
+ var growProportion = availWidth / total;
+ for (i = 0; i < columns.length && total < availWidth; i++) {
+ c = columns[i];
+ var currentWidth = widths[i];
+ var growSize;
+
+ if (!c.resizable || c.maxWidth <= currentWidth) {
+ growSize = 0;
} else {
- c.width = c.previousWidth + x;
- x = 0;
+ growSize = Math.min(Math.floor(growProportion * currentWidth) - currentWidth, (c.maxWidth - currentWidth) || 1000000) || 1;
}
- }
+ total += growSize;
+ widths[i] += (total <= availWidth ? growSize : 0);
+ }
+ if (prevTotal >= total) { // avoid infinite loop
+ break;
}
+ prevTotal = total;
+ }
- if (options.forceFitColumns) {
- x = -d;
- for (j = i + 1; j < columnElements.length; j++) {
- c = columns[j];
- if (c.resizable) {
- actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
- if (x && c.previousWidth + x < actualMinWidth) {
- x += c.previousWidth - actualMinWidth;
- c.width = actualMinWidth;
- } else {
- c.width = c.previousWidth + x;
- x = 0;
- }
+ var reRender = false;
+ for (i = 0; i < columns.length; i++) {
+ if (columns[i].rerenderOnResize && columns[i].width != widths[i]) {
+ reRender = true;
+ }
+ columns[i].width = widths[i];
+ }
+
+ applyColumnHeaderWidths();
+ updateCanvasWidth(true);
+ if (reRender) {
+ invalidateAllRows();
+ render();
+ }
+ }
+
+ function applyColumnHeaderWidths() {
+ if (!initialized) { return; }
+ var h;
+ for (var i = 0, headers = $headers.children(), ii = headers.length; i < ii; i++) {
+ h = $(headers[i]);
+ if (jQueryNewWidthBehaviour) {
+ if (h.outerWidth() !== columns[i].width) {
+ h.outerWidth(columns[i].width);
+ }
+ } else {
+ if (h.width() !== columns[i].width - headerColumnWidthDiff) {
+ h.width(columns[i].width - headerColumnWidthDiff);
}
- }
}
- }
- applyColumnHeaderWidths();
- if (options.syncColumnCellResize) {
- applyColumnWidths();
- }
- })
- .bind("dragend", function (e, dd) {
- var newWidth;
- $(this).parent().removeClass("slick-header-column-active");
- for (j = 0; j < columnElements.length; j++) {
- c = columns[j];
- newWidth = $(columnElements[j]).outerWidth();
-
- if (c.previousWidth !== newWidth && c.rerenderOnResize) {
- invalidateAllRows();
- }
- }
- updateCanvasWidth(true);
- render();
- trigger(self.onColumnsResized, {});
+ }
+
+ updateColumnCaches();
+ }
+
+ function applyColumnWidths() {
+ var x = 0, w, rule;
+ for (var i = 0; i < columns.length; i++) {
+ w = columns[i].width;
+
+ rule = getColumnCssRules(i);
+ rule.left.style.left = x + "px";
+ rule.right.style.right = (canvasWidth - x - w) + "px";
+
+ x += columns[i].width;
+ }
+ }
+
+ function setSortColumn(columnId, ascending) {
+ setSortColumns([{ columnId: columnId, sortAsc: ascending}]);
+ }
+
+ function setSortColumns(cols) {
+ sortColumns = cols;
+
+ var headerColumnEls = $headers.children();
+ headerColumnEls
+ .removeClass("slick-header-column-sorted")
+ .find(".slick-sort-indicator")
+ .removeClass("slick-sort-indicator-asc slick-sort-indicator-desc");
+
+ $.each(sortColumns, function(i, col) {
+ if (col.sortAsc == null) {
+ col.sortAsc = true;
+ }
+ var columnIndex = getColumnIndex(col.columnId);
+ if (columnIndex != null) {
+ headerColumnEls.eq(columnIndex)
+ .addClass("slick-header-column-sorted")
+ .find(".slick-sort-indicator")
+ .addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc");
+ }
});
- });
- }
+ }
- function getVBoxDelta($el) {
- var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
- var delta = 0;
- $.each(p, function (n, val) {
- delta += parseFloat($el.css(val)) || 0;
- });
- return delta;
- }
+ function getSortColumns() {
+ return sortColumns;
+ }
- function measureCellPaddingAndBorder() {
- var el;
- var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"];
- var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
+ function handleSelectedRangesChanged(e, ranges) {
+ selectedRows = [];
+ var hash = {};
+ for (var i = 0; i < ranges.length; i++) {
+ for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) {
+ if (!hash[j]) { // prevent duplicates
+ selectedRows.push(j);
+ hash[j] = {};
+ }
+ for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) {
+ if (canCellBeSelected(j, k)) {
+ hash[j][columns[k].id] = options.selectedCellCssClass;
+ }
+ }
+ }
+ }
- el = $("
-
").appendTo($headers);
- headerColumnWidthDiff = headerColumnHeightDiff = 0;
- if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
- $.each(h, function (n, val) {
- headerColumnWidthDiff += parseFloat(el.css(val)) || 0;
- });
- $.each(v, function (n, val) {
- headerColumnHeightDiff += parseFloat(el.css(val)) || 0;
- });
- }
- el.remove();
-
- var r = $("
").appendTo($canvas);
- el = $("
-
").appendTo(r);
- cellWidthDiff = cellHeightDiff = 0;
- if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
- $.each(h, function (n, val) {
- cellWidthDiff += parseFloat(el.css(val)) || 0;
- });
- $.each(v, function (n, val) {
- cellHeightDiff += parseFloat(el.css(val)) || 0;
- });
- }
- r.remove();
+ setCellCssStyles(options.selectedCellCssClass, hash);
- absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff);
- }
+ trigger(self.onSelectedRowsChanged, {rows: getSelectedRows(), grid: self}, e);
+ }
- function createCssRules() {
- $style = $("").appendTo($("head"));
- var rowHeight = (options.rowHeight - cellHeightDiff);
- var rules = [
- "." + uid + " .slick-header-column { left: 1000px; }",
- "." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }",
- "." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }",
- "." + uid + " .slick-cell { height:" + rowHeight + "px; }",
- "." + uid + " .slick-row { height:" + options.rowHeight + "px; }"
- ];
-
- for (var i = 0; i < columns.length; i++) {
- rules.push("." + uid + " .l" + i + " { }");
- rules.push("." + uid + " .r" + i + " { }");
- }
-
- if ($style[0].styleSheet) { // IE
- $style[0].styleSheet.cssText = rules.join(" ");
- } else {
- $style[0].appendChild(document.createTextNode(rules.join(" ")));
- }
- }
+ function getColumns() {
+ return columns;
+ }
- function getColumnCssRules(idx) {
- if (!stylesheet) {
- var sheets = document.styleSheets;
- for (var i = 0; i < sheets.length; i++) {
- if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) {
- stylesheet = sheets[i];
- break;
- }
- }
-
- if (!stylesheet) {
- throw new Error("Cannot find stylesheet.");
- }
-
- // find and cache column CSS rules
- columnCssRulesL = [];
- columnCssRulesR = [];
- var cssRules = (stylesheet.cssRules || stylesheet.rules);
- var matches, columnIdx;
- for (var i = 0; i < cssRules.length; i++) {
- var selector = cssRules[i].selectorText;
- if (matches = /\.l\d+/.exec(selector)) {
- columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
- columnCssRulesL[columnIdx] = cssRules[i];
- } else if (matches = /\.r\d+/.exec(selector)) {
- columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
- columnCssRulesR[columnIdx] = cssRules[i];
- }
- }
- }
-
- return {
- "left": columnCssRulesL[idx],
- "right": columnCssRulesR[idx]
- };
- }
+ function updateColumnCaches() {
+ // Pre-calculate cell boundaries.
+ columnPosLeft = [];
+ columnPosRight = [];
+ var x = 0;
+ for (var i = 0, ii = columns.length; i < ii; i++) {
+ columnPosLeft[i] = x;
+ columnPosRight[i] = x + columns[i].width;
+ x += columns[i].width;
+ }
+ }
- function removeCssRules() {
- $style.remove();
- stylesheet = null;
- }
+ function setColumns(columnDefinitions) {
+ columns = columnDefinitions;
- function destroy() {
- getEditorLock().cancelCurrentEdit();
+ columnsById = {};
+ for (var i = 0; i < columns.length; i++) {
+ var m = columns[i] = $.extend({}, columnDefaults, columns[i]);
+ columnsById[m.id] = i;
+ if (m.minWidth && m.width < m.minWidth) {
+ m.width = m.minWidth;
+ }
+ if (m.maxWidth && m.width > m.maxWidth) {
+ m.width = m.maxWidth;
+ }
+ }
- trigger(self.onBeforeDestroy, {});
+ updateColumnCaches();
- var i = plugins.length;
- while(i--) {
- unregisterPlugin(plugins[i]);
- }
+ if (initialized) {
+ invalidateAllRows();
+ createColumnHeaders();
+ removeCssRules();
+ createCssRules();
+ resizeCanvas();
+ applyColumnWidths();
+ handleScroll();
+ }
+ }
- if (options.enableColumnReorder) {
- $headers.filter(":ui-sortable").sortable("destroy");
- }
+ function getOptions() {
+ return options;
+ }
- unbindAncestorScrollEvents();
- $container.unbind(".slickgrid");
- removeCssRules();
+ function setOptions(args) {
+ if (!getEditorLock().commitCurrentEdit()) {
+ return;
+ }
- $canvas.unbind("draginit dragstart dragend drag");
- $container.empty().removeClass(uid);
- }
+ makeActiveCellNormal();
+ if (options.enableAddRow !== args.enableAddRow) {
+ invalidateRow(getDataLength());
+ }
- //////////////////////////////////////////////////////////////////////////////////////////////
- // General
+ options = $.extend(options, args);
+ validateAndEnforceOptions();
- function trigger(evt, args, e) {
- e = e || new Slick.EventData();
- args = args || {};
- args.grid = self;
- return evt.notify(args, e, self);
- }
+ $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto");
+ render();
+ }
- function getEditorLock() {
- return options.editorLock;
- }
+ function validateAndEnforceOptions() {
+ if (options.autoHeight) {
+ options.leaveSpaceForNewRows = false;
+ }
+ }
- function getEditController() {
- return editController;
- }
+ function setData(newData, scrollToTop) {
+ data = newData;
+ invalidateAllRows();
+ updateRowCount();
+ if (scrollToTop) {
+ scrollTo(0);
+ }
+ }
- function getColumnIndex(id) {
- return columnsById[id];
- }
+ function getData() {
+ return data;
+ }
- function autosizeColumns() {
- var i, c,
- widths = [],
- shrinkLeeway = 0,
- total = 0,
- prevTotal,
- availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
-
- for (i = 0; i < columns.length; i++) {
- c = columns[i];
- widths.push(c.width);
- total += c.width;
- if (c.resizable) {
- shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth);
- }
- }
-
- // shrink
- prevTotal = total;
- while (total > availWidth && shrinkLeeway) {
- var shrinkProportion = (total - availWidth) / shrinkLeeway;
- for (i = 0; i < columns.length && total > availWidth; i++) {
- c = columns[i];
- var width = widths[i];
- if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) {
- continue;
- }
- var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth);
- var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1;
- shrinkSize = Math.min(shrinkSize, width - absMinWidth);
- total -= shrinkSize;
- shrinkLeeway -= shrinkSize;
- widths[i] -= shrinkSize;
- }
- if (prevTotal <= total) { // avoid infinite loop
- break;
- }
- prevTotal = total;
- }
-
- // grow
- prevTotal = total;
- while (total < availWidth) {
- var growProportion = availWidth / total;
- for (i = 0; i < columns.length && total < availWidth; i++) {
- c = columns[i];
- var currentWidth = widths[i];
- var growSize;
-
- if (!c.resizable || c.maxWidth <= currentWidth) {
- growSize = 0;
- } else {
- growSize = Math.min(Math.floor(growProportion * currentWidth) - currentWidth, (c.maxWidth - currentWidth) || 1000000) || 1;
- }
- total += growSize;
- widths[i] += growSize;
- }
- if (prevTotal >= total) { // avoid infinite loop
- break;
- }
- prevTotal = total;
- }
-
- var reRender = false;
- for (i = 0; i < columns.length; i++) {
- if (columns[i].rerenderOnResize && columns[i].width != widths[i]) {
- reRender = true;
- }
- columns[i].width = widths[i];
- }
-
- applyColumnHeaderWidths();
- updateCanvasWidth(true);
- if (reRender) {
- invalidateAllRows();
- render();
- }
- }
+ function getDataLength() {
+ if (data.getLength) {
+ return data.getLength();
+ } else {
+ return data.length;
+ }
+ }
- function applyColumnHeaderWidths() {
- if (!initialized) { return; }
- var h;
- for (var i = 0, headers = $headers.children(), ii = headers.length; i < ii; i++) {
- h = $(headers[i]);
- if (h.width() !== columns[i].width - headerColumnWidthDiff) {
- h.width(columns[i].width - headerColumnWidthDiff);
+ function getDataLengthIncludingAddNew() {
+ return getDataLength() + (options.enableAddRow ? 1 : 0);
}
- }
- updateColumnCaches();
- }
+ function getDataItem(i) {
+ if (data.getItem) {
+ return data.getItem(i);
+ } else {
+ return data[i];
+ }
+ }
- function applyColumnWidths() {
- var x = 0, w, rule;
- for (var i = 0; i < columns.length; i++) {
- w = columns[i].width;
+ function getTopPanel() {
+ return $topPanel[0];
+ }
- rule = getColumnCssRules(i);
- rule.left.style.left = x + "px";
- rule.right.style.right = (canvasWidth - x - w) + "px";
+ function setTopPanelVisibility(visible) {
+ if (options.showTopPanel != visible) {
+ options.showTopPanel = visible;
+ if (visible) {
+ $topPanelScroller.slideDown("fast", resizeCanvas);
+ } else {
+ $topPanelScroller.slideUp("fast", resizeCanvas);
+ }
+ }
+ }
- x += columns[i].width;
- }
- }
+ function setHeaderRowVisibility(visible) {
+ if (options.showHeaderRow != visible) {
+ options.showHeaderRow = visible;
+ if (visible) {
+ $headerRowScroller.slideDown("fast", resizeCanvas);
+ } else {
+ $headerRowScroller.slideUp("fast", resizeCanvas);
+ }
+ }
+ }
- function setSortColumn(columnId, ascending) {
- setSortColumns([{ columnId: columnId, sortAsc: ascending}]);
- }
+ function setFooterRowVisibility(visible) {
+ if (options.showFooterRow != visible) {
+ options.showFooterRow = visible;
+ if (visible) {
+ $footerRowScroller.slideDown("fast", resizeCanvas);
+ } else {
+ $footerRowScroller.slideUp("fast", resizeCanvas);
+ }
+ }
+ }
- function setSortColumns(cols) {
- sortColumns = cols;
+ function getContainerNode() {
+ return $container.get(0);
+ }
- var headerColumnEls = $headers.children();
- headerColumnEls
- .removeClass("slick-header-column-sorted")
- .find(".slick-sort-indicator")
- .removeClass("slick-sort-indicator-asc slick-sort-indicator-desc");
+ //////////////////////////////////////////////////////////////////////////////////////////////
+ // Rendering / Scrolling
- $.each(sortColumns, function(i, col) {
- if (col.sortAsc == null) {
- col.sortAsc = true;
+ function getRowTop(row) {
+ return options.rowHeight * row - offset;
}
- var columnIndex = getColumnIndex(col.columnId);
- if (columnIndex != null) {
- headerColumnEls.eq(columnIndex)
- .addClass("slick-header-column-sorted")
- .find(".slick-sort-indicator")
- .addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc");
+
+ function getRowFromPosition(y) {
+ return Math.floor((y + offset) / options.rowHeight);
}
- });
- }
- function getSortColumns() {
- return sortColumns;
- }
+ function scrollTo(y) {
+ y = Math.max(y, 0);
+ y = Math.min(y, th - viewportH + (viewportHasHScroll ? scrollbarDimensions.height : 0));
+
+ var oldOffset = offset;
- function handleSelectedRangesChanged(e, ranges) {
- selectedRows = [];
- var hash = {};
- for (var i = 0; i < ranges.length; i++) {
- for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) {
- if (!hash[j]) { // prevent duplicates
- selectedRows.push(j);
- hash[j] = {};
- }
- for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) {
- if (canCellBeSelected(j, k)) {
- hash[j][columns[k].id] = options.selectedCellCssClass;
+ page = Math.min(n - 1, Math.floor(y / ph));
+ offset = Math.round(page * cj);
+ var newScrollTop = y - offset;
+
+ if (offset != oldOffset) {
+ var range = getVisibleRange(newScrollTop);
+ cleanupRows(range);
+ updateRowPositions();
+ }
+
+ if (prevScrollTop != newScrollTop) {
+ vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1;
+ $viewport[0].scrollTop = (lastRenderedScrollTop = scrollTop = prevScrollTop = newScrollTop);
+
+ trigger(self.onViewportChanged, {grid: self});
}
- }
}
- }
- setCellCssStyles(options.selectedCellCssClass, hash);
+ function defaultFormatter(row, cell, value, columnDef, dataContext) {
+ if (value == null) {
+ return "";
+ } else {
+ return (value + "").replace(/&/g,"&").replace(//g,">");
+ }
+ }
- trigger(self.onSelectedRowsChanged, {rows: getSelectedRows()}, e);
- }
+ function getFormatter(row, column) {
+ var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
- function getColumns() {
- return columns;
- }
+ // look up by id, then index
+ var columnOverrides = rowMetadata &&
+ rowMetadata.columns &&
+ (rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]);
- function updateColumnCaches() {
- // Pre-calculate cell boundaries.
- columnPosLeft = [];
- columnPosRight = [];
- var x = 0;
- for (var i = 0, ii = columns.length; i < ii; i++) {
- columnPosLeft[i] = x;
- columnPosRight[i] = x + columns[i].width;
- x += columns[i].width;
- }
- }
+ return (columnOverrides && columnOverrides.formatter) ||
+ (rowMetadata && rowMetadata.formatter) ||
+ column.formatter ||
+ (options.formatterFactory && options.formatterFactory.getFormatter(column)) ||
+ options.defaultFormatter;
+ }
+
+ function getEditor(row, cell) {
+ var column = columns[cell];
+ var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
+ var columnMetadata = rowMetadata && rowMetadata.columns;
+
+ if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) {
+ return columnMetadata[column.id].editor;
+ }
+ if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) {
+ return columnMetadata[cell].editor;
+ }
+
+ return column.editor || (options.editorFactory && options.editorFactory.getEditor(column));
+ }
+
+ function getDataItemValueForColumn(item, columnDef) {
+ if (options.dataItemColumnValueExtractor) {
+ return options.dataItemColumnValueExtractor(item, columnDef);
+ }
+ return item[columnDef.field];
+ }
+
+ function defaultAriaAttr(row, cell, value, columnDef, dataContext) {
+ var attrValue = ""
+ if (value != null) {
+ attrValue = (value + "").replace(/&/g, "&").replace(//g, ">");
+ }
+ return { "attr": "aria-label", "value": attrValue };
+ }
+
+ function getAriaAttr(row, cell) {
+ var dataContext = getDataItem(row);
+ var columnDef = columns[cell];
+
+ if (dataContext) {
+ var value = getDataItemValueForColumn(dataContext, columnDef);
+ var ariaAttrObj = (columnDef.ariaAttr || options.defaultAriaAttr)(row, cell, value, columnDef, dataContext);
+
+ if (ariaAttrObj == null)
+ return null;
+
+ var ariaRowColHeader = ""
+
+ if (columns[cell].columnHeader != null) {
+ if (columns[cell].columnHeader === true) {
+ ariaRowColHeader = columns[cell].id + ", ";
+ } else {
+ ariaRowColHeader = columns[cell].columnHeader + ", ";
+ }
+ }
+
+ $(columns[cell].rowHeader).each(function (key, value) {
+ //ariaRowColHeader += rowsCache[row].cellValues[value] + ", ";
+ ariaRowColHeader += (rowsCache[row].cellValues[value] !== undefined ? rowsCache[row].cellValues[value] + ", " : "");
+ });
+
+ ariaAttrObj.value = ariaRowColHeader + ariaAttrObj.value;
- function setColumns(columnDefinitions) {
- columns = columnDefinitions;
+ return ariaAttrObj;
+ }
- columnsById = {};
- for (var i = 0; i < columns.length; i++) {
- var m = columns[i] = $.extend({}, columnDefaults, columns[i]);
- columnsById[m.id] = i;
- if (m.minWidth && m.width < m.minWidth) {
- m.width = m.minWidth;
+ return null;
}
- if (m.maxWidth && m.width > m.maxWidth) {
- m.width = m.maxWidth;
+
+ function appendRowHtml(stringArray, row, range, dataLength) {
+ var d = getDataItem(row);
+ var dataLoading = row < dataLength && !d;
+ var rowCss = "slick-row" +
+ (dataLoading ? " loading" : "") +
+ (row === activeRow ? " active" : "") +
+ (row % 2 == 1 ? " odd" : " even");
+
+ if (!d) {
+ rowCss += " " + options.addNewRowCssClass;
+ }
+
+ var metadata = data.getItemMetadata && data.getItemMetadata(row);
+
+ if (metadata && metadata.cssClasses) {
+ rowCss += " " + metadata.cssClasses;
+ }
+
+ stringArray.push("
");
+
+ var colspan, m;
+ for (var i = 0, ii = columns.length; i < ii; i++) {
+ m = columns[i];
+ colspan = 1;
+ if (metadata && metadata.columns) {
+ var columnData = metadata.columns[m.id] || metadata.columns[i];
+ colspan = (columnData && columnData.colspan) || 1;
+ if (colspan === "*") {
+ colspan = ii - i;
+ }
+ }
+
+ // Do not render cells outside of the viewport.
+ if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
+ if (columnPosLeft[i] > range.rightPx) {
+ // All columns to the right are outside the range.
+ break;
+ }
+
+ appendCellHtml(stringArray, row, i, colspan, d);
+ }
+
+ if (colspan > 1) {
+ i += (colspan - 1);
+ }
+ }
+
+ stringArray.push("
");
}
- }
- updateColumnCaches();
+ function appendCellHtml(stringArray, row, cell, colspan, item) {
+ // stringArray: stringBuilder containing the HTML parts
+ // row, cell: row and column index
+ // colspan: HTML colspan
+ // item: grid data for row
- if (initialized) {
- invalidateAllRows();
- createColumnHeaders();
- removeCssRules();
- createCssRules();
- resizeCanvas();
- applyColumnWidths();
- handleScroll();
- }
- }
+ var m = columns[cell];
+ var cellCss = "slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1) +
+ (m.cssClass ? " " + m.cssClass : "");
+ if (row === activeRow && cell === activeCell) {
+ cellCss += (" active");
+ }
+
+ // TODO: merge them together in the setter
+ for (var key in cellCssClasses) {
+ if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) {
+ cellCss += (" " + cellCssClasses[key][row][m.id]);
+ }
+ }
+
+ // Prepare Aria Attribute
+ var ariaAttrWrapper = getAriaAttr(row, cell);
+
+ stringArray.push("
");
+
+ // if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet)
+ if (item) {
+ var value = rowsCache[row].cellValues[cell]; // getDataItemValueForColumn(item, m);
+ stringArray.push(getFormatter(row, m)(row, cell, value, m, item));
+ }
+
+ stringArray.push("
");
+
+ rowsCache[row].cellRenderQueue.push(cell);
+ rowsCache[row].cellColSpans[cell] = colspan;
+ }
+
+
+ function cleanupRows(rangeToKeep) {
+ for (var i in rowsCache) {
+ if (((i = parseInt(i, 10)) !== activeRow) && (i < rangeToKeep.top || i > rangeToKeep.bottom)) {
+ removeRowFromCache(i);
+ }
+ }
+ if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); }
+ }
+
+ function invalidate() {
+ updateRowCount();
+ invalidateAllRows();
+ render();
+ }
+
+ function invalidateAllRows() {
+ if (currentEditor) {
+ makeActiveCellNormal();
+ }
+ for (var row in rowsCache) {
+ removeRowFromCache(row);
+ }
+ if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); }
+ }
+
+ function queuePostProcessedRowForCleanup(cacheEntry, postProcessedRow, rowIdx) {
+ postProcessgroupId++;
+
+ // store and detach node for later async cleanup
+ for (var columnIdx in postProcessedRow) {
+ if (postProcessedRow.hasOwnProperty(columnIdx)) {
+ postProcessedCleanupQueue.push({
+ actionType: 'C',
+ groupId: postProcessgroupId,
+ node: cacheEntry.cellNodesByColumnIdx[ columnIdx | 0],
+ columnIdx: columnIdx | 0,
+ rowIdx: rowIdx
+ });
+ }
+ }
+ postProcessedCleanupQueue.push({
+ actionType: 'R',
+ groupId: postProcessgroupId,
+ node: cacheEntry.rowNode
+ });
+ $(cacheEntry.rowNode).detach();
+ }
+
+ function queuePostProcessedCellForCleanup(cellnode, columnIdx, rowIdx) {
+ postProcessedCleanupQueue.push({
+ actionType: 'C',
+ groupId: postProcessgroupId,
+ node: cellnode,
+ columnIdx: columnIdx,
+ rowIdx: rowIdx
+ });
+ $(cellnode).detach();
+ }
+
+ function removeRowFromCache(row) {
+ var cacheEntry = rowsCache[row];
+ if (!cacheEntry) {
+ return;
+ }
+
+ if (rowNodeFromLastMouseWheelEvent === cacheEntry.rowNode) {
+ cacheEntry.rowNode.style.display = 'none';
+ zombieRowNodeFromLastMouseWheelEvent = rowNodeFromLastMouseWheelEvent;
+ zombieRowCacheFromLastMouseWheelEvent = cacheEntry;
+ zombieRowPostProcessedFromLastMouseWheelEvent = postProcessedRows[row];
+ // ignore post processing cleanup in this case - it will be dealt with later
+ } else {
+ if (options.enableAsyncPostRenderCleanup && postProcessedRows[row]) {
+ queuePostProcessedRowForCleanup(cacheEntry, postProcessedRows[row], row);
+ } else {
+ $canvas[0].removeChild(cacheEntry.rowNode);
+ }
+ }
+
+ delete rowsCache[row];
+ delete postProcessedRows[row];
+ renderedRows--;
+ counter_rows_removed++;
+ }
+
+ function invalidateRows(rows) {
+ var i, rl;
+ if (!rows || !rows.length) {
+ return;
+ }
+ vScrollDir = 0;
+ for (i = 0, rl = rows.length; i < rl; i++) {
+ if (currentEditor && activeRow === rows[i]) {
+ makeActiveCellNormal();
+ }
+ if (rowsCache[rows[i]]) {
+ removeRowFromCache(rows[i]);
+ }
+ }
+ if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); }
+
+ }
+
+ function invalidateRow(row) {
+ invalidateRows([row]);
+ }
+
+ function updateCell(row, cell) {
+ var cellNode = getCellNode(row, cell);
+ if (!cellNode) {
+ return;
+ }
+
+ var m = columns[cell], d = getDataItem(row);
+ if (currentEditor && activeRow === row && activeCell === cell) {
+ currentEditor.loadValue(d);
+ } else {
+ cellNode.innerHTML = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d) : "";
+ invalidatePostProcessingResults(row);
+ }
+ }
+
+ function updateRow(row) {
+ var cacheEntry = rowsCache[row];
+ if (!cacheEntry) {
+ return;
+ }
+
+ ensureCellNodesInRowsCache(row);
+ prePopulateCellValues(row);
+ var d = getDataItem(row);
+
+ for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
+ if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
+ continue;
+ }
+
+ columnIdx = columnIdx | 0;
+ var m = columns[columnIdx],
+ node = cacheEntry.cellNodesByColumnIdx[columnIdx];
+
+ if (row === activeRow && columnIdx === activeCell && currentEditor) {
+ currentEditor.loadValue(d);
+ } else if (d) {
+ node.innerHTML = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d);
+ } else {
+ node.innerHTML = "";
+ }
+
+ /**/
+ // TODO: SET ARIA LABEL AFTER EDIT
+ var ariaAttrWrapper = getAriaAttr(row, columnIdx);
+ if (ariaAttrWrapper)
+ $(node).attr(ariaAttrWrapper.attr, ariaAttrWrapper.value);
+ }
+
+ invalidatePostProcessingResults(row);
+ }
+
+ function getViewportHeight() {
+ return parseFloat($.css($container[0], "height", true)) -
+ parseFloat($.css($container[0], "paddingTop", true)) -
+ parseFloat($.css($container[0], "paddingBottom", true)) -
+ parseFloat($.css($headerScroller[0], "height")) - getVBoxDelta($headerScroller) -
+ (options.showTopPanel ? options.topPanelHeight + getVBoxDelta($topPanelScroller) : 0) -
+ (options.showHeaderRow ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0) -
+ (options.createFooterRow && options.showFooterRow ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0);
+ }
+
+ function resizeCanvas() {
+ if (!initialized) { return; }
+ if (options.autoHeight) {
+ viewportH = options.rowHeight * getDataLengthIncludingAddNew();
+ } else {
+ viewportH = getViewportHeight();
+ }
+
+ numVisibleRows = Math.ceil(viewportH / options.rowHeight);
+ viewportW = parseFloat($.css($container[0], "width", true));
+ if (!options.autoHeight) {
+ $viewport.height(viewportH);
+ }
- function getOptions() {
- return options;
- }
+ if (options.forceFitColumns) {
+ autosizeColumns();
+ }
- function setOptions(args) {
- if (!getEditorLock().commitCurrentEdit()) {
- return;
- }
+ updateRowCount();
+ handleScroll();
+ // Since the width has changed, force the render() to reevaluate virtually rendered cells.
+ lastRenderedScrollLeft = -1;
+ render();
+ }
- makeActiveCellNormal();
+ function updateRowCount() {
+ if (!initialized) { return; }
- if (options.enableAddRow !== args.enableAddRow) {
- invalidateRow(getDataLength());
- }
+ var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
+ var numberOfRows = dataLengthIncludingAddNew +
+ (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0);
- options = $.extend(options, args);
- validateAndEnforceOptions();
+ var oldViewportHasVScroll = viewportHasVScroll;
+ // with autoHeight, we do not need to accommodate the vertical scroll bar
+ viewportHasVScroll = !options.autoHeight && (numberOfRows * options.rowHeight > viewportH);
+ viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width);
- $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto");
- render();
- }
+ makeActiveCellNormal();
- function validateAndEnforceOptions() {
- if (options.autoHeight) {
- options.leaveSpaceForNewRows = false;
- }
- }
+ // remove the rows that are now outside of the data range
+ // this helps avoid redundant calls to .removeRow() when the size of the data decreased by thousands of rows
+ var l = dataLengthIncludingAddNew - 1;
+ for (var i in rowsCache) {
+ if (i > l) {
+ removeRowFromCache(i);
+ }
+ }
+ if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); }
- function setData(newData, scrollToTop) {
- data = newData;
- invalidateAllRows();
- updateRowCount();
- if (scrollToTop) {
- scrollTo(0);
- }
- }
+ if (activeCellNode && activeRow > l) {
+ resetActiveCell();
+ }
- function getData() {
- return data;
- }
+ var oldH = h;
+ th = Math.max(options.rowHeight * numberOfRows, viewportH - scrollbarDimensions.height);
+ if (th < maxSupportedCssHeight) {
+ // just one page
+ h = ph = th;
+ n = 1;
+ cj = 0;
+ } else {
+ // break into pages
+ h = maxSupportedCssHeight;
+ ph = h / 100;
+ n = Math.floor(th / ph);
+ cj = (th - h) / (n - 1);
+ }
- function getDataLength() {
- if (data.getLength) {
- return data.getLength();
- } else {
- return data.length;
- }
- }
+ if (h !== oldH) {
+ $canvas.css("height", h);
+ scrollTop = $viewport[0].scrollTop;
+ }
- function getDataLengthIncludingAddNew() {
- return getDataLength() + (options.enableAddRow ? 1 : 0);
- }
+ var oldScrollTopInRange = (scrollTop + offset <= th - viewportH);
- function getDataItem(i) {
- if (data.getItem) {
- return data.getItem(i);
- } else {
- return data[i];
- }
- }
+ if (th == 0 || scrollTop == 0) {
+ page = offset = 0;
+ } else if (oldScrollTopInRange) {
+ // maintain virtual position
+ scrollTo(scrollTop + offset);
+ } else {
+ // scroll to bottom
+ scrollTo(th - viewportH);
+ }
- function getTopPanel() {
- return $topPanel[0];
- }
+ if (h != oldH && options.autoHeight) {
+ resizeCanvas();
+ }
- function setTopPanelVisibility(visible) {
- if (options.showTopPanel != visible) {
- options.showTopPanel = visible;
- if (visible) {
- $topPanelScroller.slideDown("fast", resizeCanvas);
- } else {
- $topPanelScroller.slideUp("fast", resizeCanvas);
+ if (options.forceFitColumns && oldViewportHasVScroll != viewportHasVScroll) {
+ autosizeColumns();
+ }
+ updateCanvasWidth(false);
}
- }
- }
- function setHeaderRowVisibility(visible) {
- if (options.showHeaderRow != visible) {
- options.showHeaderRow = visible;
- if (visible) {
- $headerRowScroller.slideDown("fast", resizeCanvas);
- } else {
- $headerRowScroller.slideUp("fast", resizeCanvas);
- }
- }
- }
+ function getVisibleRange(viewportTop, viewportLeft) {
+ if (viewportTop == null) {
+ viewportTop = scrollTop;
+ }
+ if (viewportLeft == null) {
+ viewportLeft = scrollLeft;
+ }
- function getContainerNode() {
- return $container.get(0);
- }
+ return {
+ top: getRowFromPosition(viewportTop),
+ bottom: getRowFromPosition(viewportTop + viewportH) + 1,
+ leftPx: viewportLeft,
+ rightPx: viewportLeft + viewportW
+ };
+ }
+
+ function getRenderedRange(viewportTop, viewportLeft) {
+ var range = getVisibleRange(viewportTop, viewportLeft);
+ var buffer = Math.round(viewportH / options.rowHeight);
+ var minBuffer = 3;
+
+ if (vScrollDir == -1) {
+ range.top -= buffer;
+ range.bottom += minBuffer;
+ } else if (vScrollDir == 1) {
+ range.top -= minBuffer;
+ range.bottom += buffer;
+ } else {
+ range.top -= minBuffer;
+ range.bottom += minBuffer;
+ }
- //////////////////////////////////////////////////////////////////////////////////////////////
- // Rendering / Scrolling
+ range.top = Math.max(0, range.top);
+ range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom);
- function getRowTop(row) {
- return options.rowHeight * row - offset;
- }
+ range.leftPx -= viewportW;
+ range.rightPx += viewportW;
- function getRowFromPosition(y) {
- return Math.floor((y + offset) / options.rowHeight);
- }
+ range.leftPx = Math.max(0, range.leftPx);
+ range.rightPx = Math.min(canvasWidth, range.rightPx);
- function scrollTo(y) {
- y = Math.max(y, 0);
- y = Math.min(y, th - viewportH + (viewportHasHScroll ? scrollbarDimensions.height : 0));
+ return range;
+ }
- var oldOffset = offset;
+ function ensureCellNodesInRowsCache(row) {
+ var cacheEntry = rowsCache[row];
+ if (cacheEntry) {
+ if (cacheEntry.cellRenderQueue.length) {
+ var lastChild = cacheEntry.rowNode.lastChild;
+ while (cacheEntry.cellRenderQueue.length) {
+ var columnIdx = cacheEntry.cellRenderQueue.pop();
+ cacheEntry.cellNodesByColumnIdx[columnIdx] = lastChild;
+ lastChild = lastChild.previousSibling;
+ }
+ }
+ }
+ }
- page = Math.min(n - 1, Math.floor(y / ph));
- offset = Math.round(page * cj);
- var newScrollTop = y - offset;
+ function cleanUpCells(range, row) {
+ var totalCellsRemoved = 0;
+ var cacheEntry = rowsCache[row];
- if (offset != oldOffset) {
- var range = getVisibleRange(newScrollTop);
- cleanupRows(range);
- updateRowPositions();
- }
+ // Remove cells outside the range.
+ var cellsToRemove = [];
+ for (var i in cacheEntry.cellNodesByColumnIdx) {
+ // I really hate it when people mess with Array.prototype.
+ if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) {
+ continue;
+ }
- if (prevScrollTop != newScrollTop) {
- vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1;
- $viewport[0].scrollTop = (lastRenderedScrollTop = scrollTop = prevScrollTop = newScrollTop);
+ // This is a string, so it needs to be cast back to a number.
+ i = i | 0;
- trigger(self.onViewportChanged, {});
- }
- }
+ var colspan = cacheEntry.cellColSpans[i];
+ if (columnPosLeft[i] > range.rightPx ||
+ columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) {
+ if (!(row == activeRow && i == activeCell)) {
+ cellsToRemove.push(i);
+ }
+ }
+ }
- function defaultFormatter(row, cell, value, columnDef, dataContext) {
- if (value == null) {
- return "";
- } else {
- return (value + "").replace(/&/g,"&").replace(//g,">");
- }
- }
+ var cellToRemove, node;
+ postProcessgroupId++;
+ while ((cellToRemove = cellsToRemove.pop()) != null) {
+ node = cacheEntry.cellNodesByColumnIdx[cellToRemove];
+ if (options.enableAsyncPostRenderCleanup && postProcessedRows[row] && postProcessedRows[row][cellToRemove]) {
+ queuePostProcessedCellForCleanup(node, cellToRemove, row);
+ } else {
+ cacheEntry.rowNode.removeChild(node);
+ }
- function getFormatter(row, column) {
- var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
+ delete cacheEntry.cellColSpans[cellToRemove];
+ delete cacheEntry.cellNodesByColumnIdx[cellToRemove];
+ if (postProcessedRows[row]) {
+ delete postProcessedRows[row][cellToRemove];
+ }
+ totalCellsRemoved++;
+ }
+ }
- // look up by id, then index
- var columnOverrides = rowMetadata &&
- rowMetadata.columns &&
- (rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]);
+ function cleanUpAndRenderCells(range) {
+ var cacheEntry;
+ var stringArray = [];
+ var processedRows = [];
+ var cellsAdded;
+ var totalCellsAdded = 0;
+ var colspan;
- return (columnOverrides && columnOverrides.formatter) ||
- (rowMetadata && rowMetadata.formatter) ||
- column.formatter ||
- (options.formatterFactory && options.formatterFactory.getFormatter(column)) ||
- options.defaultFormatter;
- }
+ for (var row = range.top, btm = range.bottom; row <= btm; row++) {
+ cacheEntry = rowsCache[row];
+ if (!cacheEntry) {
+ continue;
+ }
- function getEditor(row, cell) {
- var column = columns[cell];
- var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
- var columnMetadata = rowMetadata && rowMetadata.columns;
+ // cellRenderQueue populated in renderRows() needs to be cleared first
+ ensureCellNodesInRowsCache(row);
- if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) {
- return columnMetadata[column.id].editor;
- }
- if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) {
- return columnMetadata[cell].editor;
- }
+ cleanUpCells(range, row);
- return column.editor || (options.editorFactory && options.editorFactory.getEditor(column));
- }
+ // Render missing cells.
+ cellsAdded = 0;
- function getDataItemValueForColumn(item, columnDef) {
- if (options.dataItemColumnValueExtractor) {
- return options.dataItemColumnValueExtractor(item, columnDef);
- }
- return item[columnDef.field];
- }
+ var metadata = data.getItemMetadata && data.getItemMetadata(row);
+ metadata = metadata && metadata.columns;
- function appendRowHtml(stringArray, row, range, dataLength) {
- var d = getDataItem(row);
- var dataLoading = row < dataLength && !d;
- var rowCss = "slick-row" +
- (dataLoading ? " loading" : "") +
- (row === activeRow ? " active" : "") +
- (row % 2 == 1 ? " odd" : " even");
+ var d = getDataItem(row);
- if (!d) {
- rowCss += " " + options.addNewRowCssClass;
- }
+ // TODO: shorten this loop (index? heuristics? binary search?)
+ for (var i = 0, ii = columns.length; i < ii; i++) {
+ // Cells to the right are outside the range.
+ if (columnPosLeft[i] > range.rightPx) {
+ break;
+ }
- var metadata = data.getItemMetadata && data.getItemMetadata(row);
+ // Already rendered.
+ if ((colspan = cacheEntry.cellColSpans[i]) != null) {
+ i += (colspan > 1 ? colspan - 1 : 0);
+ continue;
+ }
- if (metadata && metadata.cssClasses) {
- rowCss += " " + metadata.cssClasses;
- }
+ colspan = 1;
+ if (metadata) {
+ var columnData = metadata[columns[i].id] || metadata[i];
+ colspan = (columnData && columnData.colspan) || 1;
+ if (colspan === "*") {
+ colspan = ii - i;
+ }
+ }
- stringArray.push("
");
+ if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
+ appendCellHtml(stringArray, row, i, colspan, d);
+ cellsAdded++;
+ }
- var colspan, m;
- for (var i = 0, ii = columns.length; i < ii; i++) {
- m = columns[i];
- colspan = 1;
- if (metadata && metadata.columns) {
- var columnData = metadata.columns[m.id] || metadata.columns[i];
- colspan = (columnData && columnData.colspan) || 1;
- if (colspan === "*") {
- colspan = ii - i;
- }
- }
+ i += (colspan > 1 ? colspan - 1 : 0);
+ }
- // Do not render cells outside of the viewport.
- if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
- if (columnPosLeft[i] > range.rightPx) {
- // All columns to the right are outside the range.
- break;
- }
+ if (cellsAdded) {
+ totalCellsAdded += cellsAdded;
+ processedRows.push(row);
+ }
+ }
- appendCellHtml(stringArray, row, i, colspan, d);
- }
+ if (!stringArray.length) {
+ return;
+ }
- if (colspan > 1) {
- i += (colspan - 1);
+ var x = document.createElement("div");
+ x.innerHTML = stringArray.join("");
+
+ var processedRow;
+ var node;
+ while ((processedRow = processedRows.pop()) != null) {
+ cacheEntry = rowsCache[processedRow];
+ var columnIdx;
+ while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) {
+ node = x.lastChild;
+ cacheEntry.rowNode.appendChild(node);
+ cacheEntry.cellNodesByColumnIdx[columnIdx] = node;
+ }
+ }
}
- }
-
- stringArray.push("
");
- }
-
- function appendCellHtml(stringArray, row, cell, colspan, item) {
- var m = columns[cell];
- var cellCss = "slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1) +
- (m.cssClass ? " " + m.cssClass : "");
- if (row === activeRow && cell === activeCell) {
- cellCss += (" active");
- }
- // TODO: merge them together in the setter
- for (var key in cellCssClasses) {
- if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) {
- cellCss += (" " + cellCssClasses[key][row][m.id]);
+ function prePopulateCellValues(row) {
+ /* Item Value for Rows - Prepopulating to add this as row header for Aria */
+ var cellValues = [];
+ $(columns).each(function (key, value) {
+ var item = getDataItem(row);
+ if (item)
+ cellValues[key] = getDataItemValueForColumn(item, columns[key]);
+ });
+ if (rowsCache[row])
+ rowsCache[row].cellValues = cellValues;
}
- }
- stringArray.push("
");
+ function renderRows(range) {
+ var parentNode = $canvas[0],
+ stringArray = [],
+ rows = [],
+ needToReselectCell = false,
+ dataLength = getDataLength();
- // if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet)
- if (item) {
- var value = getDataItemValueForColumn(item, m);
- stringArray.push(getFormatter(row, m)(row, cell, value, m, item));
- }
+ for (var i = range.top, ii = range.bottom; i <= ii; i++) {
+ if (rowsCache[i]) {
+ continue;
+ }
+ renderedRows++;
+ rows.push(i);
+
+ ///* Item Value for Rows - Prepopulating to add this as row header for Aria */
+ //var cellValues =[];
+ //$(columns).each(function (key, value) {
+ // var item = getDataItem(i);
+ // if (item)
+ // cellValues[key] = getDataItemValueForColumn(item, columns[key]);
+ //});
+
+ // Create an entry right away so that appendRowHtml() can
+ // start populatating it.
+ rowsCache[i] = {
+ "rowNode": null,
+
+ // ColSpans of rendered cells (by column idx).
+ // Can also be used for checking whether a cell has been rendered.
+ "cellColSpans": [],
+
+ // Cell nodes (by column idx). Lazy-populated by ensureCellNodesInRowsCache().
+ "cellNodesByColumnIdx": [],
+
+ // Column indices of cell nodes that have been rendered, but not yet indexed in
+ // cellNodesByColumnIdx. These are in the same order as cell nodes added at the
+ // end of the row.
+ "cellRenderQueue": [],
+
+ "cellValues": []
+ };
+
+ prePopulateCellValues(i);
+
+ appendRowHtml(stringArray, i, range, dataLength);
+ if (activeCellNode && activeRow === i) {
+ needToReselectCell = true;
+ }
+ counter_rows_rendered++;
+ }
- stringArray.push("
");
+ if (!rows.length) { return; }
- rowsCache[row].cellRenderQueue.push(cell);
- rowsCache[row].cellColSpans[cell] = colspan;
- }
+ var x = document.createElement("div");
+ x.innerHTML = stringArray.join("");
+ for (var i = 0, ii = rows.length; i < ii; i++) {
+ rowsCache[rows[i]].rowNode = parentNode.appendChild(x.firstChild);
+ }
- function cleanupRows(rangeToKeep) {
- for (var i in rowsCache) {
- if (((i = parseInt(i, 10)) !== activeRow) && (i < rangeToKeep.top || i > rangeToKeep.bottom)) {
- removeRowFromCache(i);
+ if (needToReselectCell) {
+ activeCellNode = getCellNode(activeRow, activeCell);
+ }
}
- }
- }
- function invalidate() {
- updateRowCount();
- invalidateAllRows();
- render();
- }
-
- function invalidateAllRows() {
- if (currentEditor) {
- makeActiveCellNormal();
- }
- for (var row in rowsCache) {
- removeRowFromCache(row);
- }
- }
+ function startPostProcessing() {
+ if (!options.enableAsyncPostRender) {
+ return;
+ }
+ clearTimeout(h_postrender);
+ h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
+ }
- function removeRowFromCache(row) {
- var cacheEntry = rowsCache[row];
- if (!cacheEntry) {
- return;
- }
-
- if (rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode) {
- cacheEntry.rowNode.style.display = 'none';
- zombieRowNodeFromLastMouseWheelEvent = rowNodeFromLastMouseWheelEvent;
- } else {
- $canvas[0].removeChild(cacheEntry.rowNode);
- }
-
- delete rowsCache[row];
- delete postProcessedRows[row];
- renderedRows--;
- counter_rows_removed++;
- }
+ function startPostProcessingCleanup() {
+ if (!options.enableAsyncPostRenderCleanup) {
+ return;
+ }
+ clearTimeout(h_postrenderCleanup);
+ h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay);
+ }
- function invalidateRows(rows) {
- var i, rl;
- if (!rows || !rows.length) {
- return;
- }
- vScrollDir = 0;
- for (i = 0, rl = rows.length; i < rl; i++) {
- if (currentEditor && activeRow === rows[i]) {
- makeActiveCellNormal();
+ function invalidatePostProcessingResults(row) {
+ // change status of columns to be re-rendered
+ for (var columnIdx in postProcessedRows[row]) {
+ if (postProcessedRows[row].hasOwnProperty(columnIdx)) {
+ postProcessedRows[row][columnIdx] = 'C';
+ }
+ }
+ postProcessFromRow = Math.min(postProcessFromRow, row);
+ postProcessToRow = Math.max(postProcessToRow, row);
+ startPostProcessing();
}
- if (rowsCache[rows[i]]) {
- removeRowFromCache(rows[i]);
+
+ function updateRowPositions() {
+ for (var row in rowsCache) {
+ rowsCache[row].rowNode.style.top = getRowTop(row) + "px";
+ }
}
- }
- }
- function invalidateRow(row) {
- invalidateRows([row]);
- }
+ function render() {
+ if (!initialized) { return; }
+ var visible = getVisibleRange();
+ var rendered = getRenderedRange();
- function updateCell(row, cell) {
- var cellNode = getCellNode(row, cell);
- if (!cellNode) {
- return;
- }
-
- var m = columns[cell], d = getDataItem(row);
- if (currentEditor && activeRow === row && activeCell === cell) {
- currentEditor.loadValue(d);
- } else {
- cellNode.innerHTML = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d) : "";
- invalidatePostProcessingResults(row);
- }
- }
+ // remove rows no longer in the viewport
+ cleanupRows(rendered);
- function updateRow(row) {
- var cacheEntry = rowsCache[row];
- if (!cacheEntry) {
- return;
- }
+ // add new rows & missing cells in existing rows
+ if (lastRenderedScrollLeft != scrollLeft) {
+ cleanUpAndRenderCells(rendered);
+ }
- ensureCellNodesInRowsCache(row);
+ // render missing rows
+ renderRows(rendered);
- var d = getDataItem(row);
+ postProcessFromRow = visible.top;
+ postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom);
+ startPostProcessing();
- for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
- if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
- continue;
+ lastRenderedScrollTop = scrollTop;
+ lastRenderedScrollLeft = scrollLeft;
+ h_render = null;
}
- columnIdx = columnIdx | 0;
- var m = columns[columnIdx],
- node = cacheEntry.cellNodesByColumnIdx[columnIdx];
+ function handleHeaderRowScroll() {
+ var scrollLeft = $headerRowScroller[0].scrollLeft;
+ if (scrollLeft != $viewport[0].scrollLeft) {
+ $viewport[0].scrollLeft = scrollLeft;
+ }
+ }
- if (row === activeRow && columnIdx === activeCell && currentEditor) {
- currentEditor.loadValue(d);
- } else if (d) {
- node.innerHTML = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d);
- } else {
- node.innerHTML = "";
+ function handleFooterRowScroll() {
+ var scrollLeft = $footerRowScroller[0].scrollLeft;
+ if (scrollLeft != $viewport[0].scrollLeft) {
+ $viewport[0].scrollLeft = scrollLeft;
+ }
}
- }
- invalidatePostProcessingResults(row);
- }
+ function handleScroll() {
+ scrollTop = $viewport[0].scrollTop;
+ scrollLeft = $viewport[0].scrollLeft;
+ var vScrollDist = Math.abs(scrollTop - prevScrollTop);
+ var hScrollDist = Math.abs(scrollLeft - prevScrollLeft);
- function getViewportHeight() {
- return parseFloat($.css($container[0], "height", true)) -
- parseFloat($.css($container[0], "paddingTop", true)) -
- parseFloat($.css($container[0], "paddingBottom", true)) -
- parseFloat($.css($headerScroller[0], "height")) - getVBoxDelta($headerScroller) -
- (options.showTopPanel ? options.topPanelHeight + getVBoxDelta($topPanelScroller) : 0) -
- (options.showHeaderRow ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0);
- }
+ if (hScrollDist) {
+ prevScrollLeft = scrollLeft;
+ $headerScroller[0].scrollLeft = scrollLeft;
+ $topPanelScroller[0].scrollLeft = scrollLeft;
+ $headerRowScroller[0].scrollLeft = scrollLeft;
+ if (options.createFooterRow) {
+ $footerRowScroller[0].scrollLeft = scrollLeft;
+ }
+ }
- function resizeCanvas() {
- if (!initialized) { return; }
- if (options.autoHeight) {
- viewportH = options.rowHeight * getDataLengthIncludingAddNew();
- } else {
- viewportH = getViewportHeight();
- }
-
- numVisibleRows = Math.ceil(viewportH / options.rowHeight);
- viewportW = parseFloat($.css($container[0], "width", true));
- if (!options.autoHeight) {
- $viewport.height(viewportH);
- }
-
- if (options.forceFitColumns) {
- autosizeColumns();
- }
-
- updateRowCount();
- handleScroll();
- // Since the width has changed, force the render() to reevaluate virtually rendered cells.
- lastRenderedScrollLeft = -1;
- render();
- }
+ if (vScrollDist) {
+ vScrollDir = prevScrollTop < scrollTop ? 1 : -1;
+ prevScrollTop = scrollTop;
- function updateRowCount() {
- if (!initialized) { return; }
-
- var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
- var numberOfRows = dataLengthIncludingAddNew +
- (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0);
-
- var oldViewportHasVScroll = viewportHasVScroll;
- // with autoHeight, we do not need to accommodate the vertical scroll bar
- viewportHasVScroll = !options.autoHeight && (numberOfRows * options.rowHeight > viewportH);
-
- makeActiveCellNormal();
-
- // remove the rows that are now outside of the data range
- // this helps avoid redundant calls to .removeRow() when the size of the data decreased by thousands of rows
- var l = dataLengthIncludingAddNew - 1;
- for (var i in rowsCache) {
- if (i >= l) {
- removeRowFromCache(i);
- }
- }
-
- if (activeCellNode && activeRow > l) {
- resetActiveCell();
- }
-
- var oldH = h;
- th = Math.max(options.rowHeight * numberOfRows, viewportH - scrollbarDimensions.height);
- if (th < maxSupportedCssHeight) {
- // just one page
- h = ph = th;
- n = 1;
- cj = 0;
- } else {
- // break into pages
- h = maxSupportedCssHeight;
- ph = h / 100;
- n = Math.floor(th / ph);
- cj = (th - h) / (n - 1);
- }
-
- if (h !== oldH) {
- $canvas.css("height", h);
- scrollTop = $viewport[0].scrollTop;
- }
-
- var oldScrollTopInRange = (scrollTop + offset <= th - viewportH);
-
- if (th == 0 || scrollTop == 0) {
- page = offset = 0;
- } else if (oldScrollTopInRange) {
- // maintain virtual position
- scrollTo(scrollTop + offset);
- } else {
- // scroll to bottom
- scrollTo(th - viewportH);
- }
-
- if (h != oldH && options.autoHeight) {
- resizeCanvas();
- }
-
- if (options.forceFitColumns && oldViewportHasVScroll != viewportHasVScroll) {
- autosizeColumns();
- }
- updateCanvasWidth(false);
- }
+ // switch virtual pages if needed
+ if (vScrollDist < viewportH) {
+ scrollTo(scrollTop + offset);
+ } else {
+ var oldOffset = offset;
+ if (h == viewportH) {
+ page = 0;
+ } else {
+ page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph)));
+ }
+ offset = Math.round(page * cj);
+ if (oldOffset != offset) {
+ invalidateAllRows();
+ }
+ }
+ }
- function getVisibleRange(viewportTop, viewportLeft) {
- if (viewportTop == null) {
- viewportTop = scrollTop;
- }
- if (viewportLeft == null) {
- viewportLeft = scrollLeft;
- }
-
- return {
- top: getRowFromPosition(viewportTop),
- bottom: getRowFromPosition(viewportTop + viewportH) + 1,
- leftPx: viewportLeft,
- rightPx: viewportLeft + viewportW
- };
- }
+ if (hScrollDist || vScrollDist) {
+ if (h_render) {
+ clearTimeout(h_render);
+ }
- function getRenderedRange(viewportTop, viewportLeft) {
- var range = getVisibleRange(viewportTop, viewportLeft);
- var buffer = Math.round(viewportH / options.rowHeight);
- var minBuffer = 3;
+ if (Math.abs(lastRenderedScrollTop - scrollTop) > 20 ||
+ Math.abs(lastRenderedScrollLeft - scrollLeft) > 20) {
+ if (options.forceSyncScrolling || (
+ Math.abs(lastRenderedScrollTop - scrollTop) < viewportH &&
+ Math.abs(lastRenderedScrollLeft - scrollLeft) < viewportW)) {
+ render();
+ } else {
+ h_render = setTimeout(render, 50);
+ }
- if (vScrollDir == -1) {
- range.top -= buffer;
- range.bottom += minBuffer;
- } else if (vScrollDir == 1) {
- range.top -= minBuffer;
- range.bottom += buffer;
- } else {
- range.top -= minBuffer;
- range.bottom += minBuffer;
- }
+ trigger(self.onViewportChanged, {grid: self});
+ }
+ }
- range.top = Math.max(0, range.top);
- range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom);
+ trigger(self.onScroll, {scrollLeft: scrollLeft, scrollTop: scrollTop, grid: self});
+ }
- range.leftPx -= viewportW;
- range.rightPx += viewportW;
+ function asyncPostProcessRows() {
+ var dataLength = getDataLength();
+ while (postProcessFromRow <= postProcessToRow) {
+ var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--;
+ var cacheEntry = rowsCache[row];
+ if (!cacheEntry || row >= dataLength) {
+ continue;
+ }
- range.leftPx = Math.max(0, range.leftPx);
- range.rightPx = Math.min(canvasWidth, range.rightPx);
+ if (!postProcessedRows[row]) {
+ postProcessedRows[row] = {};
+ }
- return range;
- }
+ ensureCellNodesInRowsCache(row);
+ for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
+ if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
+ continue;
+ }
- function ensureCellNodesInRowsCache(row) {
- var cacheEntry = rowsCache[row];
- if (cacheEntry) {
- if (cacheEntry.cellRenderQueue.length) {
- var lastChild = cacheEntry.rowNode.lastChild;
- while (cacheEntry.cellRenderQueue.length) {
- var columnIdx = cacheEntry.cellRenderQueue.pop();
- cacheEntry.cellNodesByColumnIdx[columnIdx] = lastChild;
- lastChild = lastChild.previousSibling;
- }
- }
- }
- }
+ columnIdx = columnIdx | 0;
- function cleanUpCells(range, row) {
- var totalCellsRemoved = 0;
- var cacheEntry = rowsCache[row];
+ var m = columns[columnIdx];
+ var processedStatus = postProcessedRows[row][columnIdx]; // C=cleanup and re-render, R=rendered
+ if (m.asyncPostRender && processedStatus !== 'R') {
+ var node = cacheEntry.cellNodesByColumnIdx[columnIdx];
+ if (node) {
+ m.asyncPostRender(node, row, getDataItem(row), m, (processedStatus === 'C'));
+ }
+ postProcessedRows[row][columnIdx] = 'R';
+ }
+ }
- // Remove cells outside the range.
- var cellsToRemove = [];
- for (var i in cacheEntry.cellNodesByColumnIdx) {
- // I really hate it when people mess with Array.prototype.
- if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) {
- continue;
+ h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
+ return;
+ }
}
- // This is a string, so it needs to be cast back to a number.
- i = i | 0;
+ function asyncPostProcessCleanupRows() {
+ if (postProcessedCleanupQueue.length > 0) {
+ var groupId = postProcessedCleanupQueue[0].groupId;
- var colspan = cacheEntry.cellColSpans[i];
- if (columnPosLeft[i] > range.rightPx ||
- columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) {
- if (!(row == activeRow && i == activeCell)) {
- cellsToRemove.push(i);
- }
- }
- }
+ // loop through all queue members with this groupID
+ while (postProcessedCleanupQueue.length > 0 && postProcessedCleanupQueue[0].groupId == groupId) {
+ var entry = postProcessedCleanupQueue.shift();
+ if (entry.actionType == 'R') {
+ $(entry.node).remove();
+ }
+ if (entry.actionType == 'C') {
+ var column = columns[entry.columnIdx];
+ if (column.asyncPostRenderCleanup && entry.node) {
+ // cleanup must also remove element
+ column.asyncPostRenderCleanup(entry.node, entry.rowIdx, column);
+ }
+ }
+ }
- var cellToRemove;
- while ((cellToRemove = cellsToRemove.pop()) != null) {
- cacheEntry.rowNode.removeChild(cacheEntry.cellNodesByColumnIdx[cellToRemove]);
- delete cacheEntry.cellColSpans[cellToRemove];
- delete cacheEntry.cellNodesByColumnIdx[cellToRemove];
- if (postProcessedRows[row]) {
- delete postProcessedRows[row][cellToRemove];
+ // call this function again after the specified delay
+ h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay);
+ }
}
- totalCellsRemoved++;
- }
- }
- function cleanUpAndRenderCells(range) {
- var cacheEntry;
- var stringArray = [];
- var processedRows = [];
- var cellsAdded;
- var totalCellsAdded = 0;
- var colspan;
+ function updateCellCssStylesOnRenderedRows(addedHash, removedHash) {
+ var node, columnId, addedRowHash, removedRowHash;
+ for (var row in rowsCache) {
+ removedRowHash = removedHash && removedHash[row];
+ addedRowHash = addedHash && addedHash[row];
+
+ if (removedRowHash) {
+ for (columnId in removedRowHash) {
+ if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
+ node = getCellNode(row, getColumnIndex(columnId));
+ if (node) {
+ $(node).removeClass(removedRowHash[columnId]);
+ }
+ }
+ }
+ }
- for (var row = range.top, btm = range.bottom; row <= btm; row++) {
- cacheEntry = rowsCache[row];
- if (!cacheEntry) {
- continue;
+ if (addedRowHash) {
+ for (columnId in addedRowHash) {
+ if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
+ node = getCellNode(row, getColumnIndex(columnId));
+ if (node) {
+ $(node).addClass(addedRowHash[columnId]);
+ }
+ }
+ }
+ }
+ }
}
- // cellRenderQueue populated in renderRows() needs to be cleared first
- ensureCellNodesInRowsCache(row);
+ function addCellCssStyles(key, hash) {
+ if (cellCssClasses[key]) {
+ throw "addCellCssStyles: cell CSS hash with key '" + key + "' already exists.";
+ }
- cleanUpCells(range, row);
+ cellCssClasses[key] = hash;
+ updateCellCssStylesOnRenderedRows(hash, null);
- // Render missing cells.
- cellsAdded = 0;
+ trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self });
+ }
- var metadata = data.getItemMetadata && data.getItemMetadata(row);
- metadata = metadata && metadata.columns;
+ function removeCellCssStyles(key) {
+ if (!cellCssClasses[key]) {
+ return;
+ }
- var d = getDataItem(row);
+ updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]);
+ delete cellCssClasses[key];
- // TODO: shorten this loop (index? heuristics? binary search?)
- for (var i = 0, ii = columns.length; i < ii; i++) {
- // Cells to the right are outside the range.
- if (columnPosLeft[i] > range.rightPx) {
- break;
- }
+ trigger(self.onCellCssStylesChanged, { "key": key, "hash": null, "grid": self });
+ }
- // Already rendered.
- if ((colspan = cacheEntry.cellColSpans[i]) != null) {
- i += (colspan > 1 ? colspan - 1 : 0);
- continue;
- }
+ function setCellCssStyles(key, hash) {
+ var prevHash = cellCssClasses[key];
- colspan = 1;
- if (metadata) {
- var columnData = metadata[columns[i].id] || metadata[i];
- colspan = (columnData && columnData.colspan) || 1;
- if (colspan === "*") {
- colspan = ii - i;
- }
- }
+ cellCssClasses[key] = hash;
+ updateCellCssStylesOnRenderedRows(hash, prevHash);
- if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
- appendCellHtml(stringArray, row, i, colspan, d);
- cellsAdded++;
- }
+ trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self });
+ }
- i += (colspan > 1 ? colspan - 1 : 0);
+ function getCellCssStyles(key) {
+ return cellCssClasses[key];
}
- if (cellsAdded) {
- totalCellsAdded += cellsAdded;
- processedRows.push(row);
+ function flashCell(row, cell, speed) {
+ speed = speed || 100;
+ if (rowsCache[row]) {
+ var $cell = $(getCellNode(row, cell));
+
+ function toggleCellClass(times) {
+ if (!times) {
+ return;
+ }
+ setTimeout(function () {
+ $cell.queue(function () {
+ $cell.toggleClass(options.cellFlashingCssClass).dequeue();
+ toggleCellClass(times - 1);
+ });
+ },
+ speed);
+ }
+
+ toggleCellClass(4);
+ }
}
- }
- if (!stringArray.length) {
- return;
- }
+ //////////////////////////////////////////////////////////////////////////////////////////////
+ // Interactivity
- var x = document.createElement("div");
- x.innerHTML = stringArray.join("");
+ function handleMouseWheel(e) {
+ var rowNode = $(e.target).closest(".slick-row")[0];
+ if (rowNode != rowNodeFromLastMouseWheelEvent) {
+ if (zombieRowNodeFromLastMouseWheelEvent && zombieRowNodeFromLastMouseWheelEvent != rowNode) {
+ if (options.enableAsyncPostRenderCleanup && zombieRowPostProcessedFromLastMouseWheelEvent) {
+ queuePostProcessedRowForCleanup(zombieRowCacheFromLastMouseWheelEvent,
+ zombieRowPostProcessedFromLastMouseWheelEvent);
+ } else {
+ $canvas[0].removeChild(zombieRowNodeFromLastMouseWheelEvent);
+ }
+ zombieRowNodeFromLastMouseWheelEvent = null;
+ zombieRowCacheFromLastMouseWheelEvent = null;
+ zombieRowPostProcessedFromLastMouseWheelEvent = null;
- var processedRow;
- var node;
- while ((processedRow = processedRows.pop()) != null) {
- cacheEntry = rowsCache[processedRow];
- var columnIdx;
- while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) {
- node = x.lastChild;
- cacheEntry.rowNode.appendChild(node);
- cacheEntry.cellNodesByColumnIdx[columnIdx] = node;
+ if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); }
+ }
+ rowNodeFromLastMouseWheelEvent = rowNode;
+ }
}
- }
- }
- function renderRows(range) {
- var parentNode = $canvas[0],
- stringArray = [],
- rows = [],
- needToReselectCell = false,
- dataLength = getDataLength();
+ function handleDragInit(e, dd) {
+ var cell = getCellFromEvent(e);
+ if (!cell || !cellExists(cell.row, cell.cell)) {
+ return false;
+ }
+
+ var retval = trigger(self.onDragInit, dd, e);
+ if (e.isImmediatePropagationStopped()) {
+ return retval;
+ }
- for (var i = range.top, ii = range.bottom; i <= ii; i++) {
- if (rowsCache[i]) {
- continue;
+ // if nobody claims to be handling drag'n'drop by stopping immediate propagation,
+ // cancel out of it
+ return false;
}
- renderedRows++;
- rows.push(i);
- // Create an entry right away so that appendRowHtml() can
- // start populatating it.
- rowsCache[i] = {
- "rowNode": null,
+ function handleDragStart(e, dd) {
+ var cell = getCellFromEvent(e);
+ if (!cell || !cellExists(cell.row, cell.cell)) {
+ return false;
+ }
- // ColSpans of rendered cells (by column idx).
- // Can also be used for checking whether a cell has been rendered.
- "cellColSpans": [],
+ var retval = trigger(self.onDragStart, dd, e);
+ if (e.isImmediatePropagationStopped()) {
+ return retval;
+ }
- // Cell nodes (by column idx). Lazy-populated by ensureCellNodesInRowsCache().
- "cellNodesByColumnIdx": [],
+ return false;
+ }
- // Column indices of cell nodes that have been rendered, but not yet indexed in
- // cellNodesByColumnIdx. These are in the same order as cell nodes added at the
- // end of the row.
- "cellRenderQueue": []
- };
+ function handleDrag(e, dd) {
+ return trigger(self.onDrag, dd, e);
+ }
- appendRowHtml(stringArray, i, range, dataLength);
- if (activeCellNode && activeRow === i) {
- needToReselectCell = true;
+ function handleDragEnd(e, dd) {
+ trigger(self.onDragEnd, dd, e);
}
- counter_rows_rendered++;
- }
- if (!rows.length) { return; }
+ function handleKeyDown(e) {
+ var keyCode = Slick.keyCode;
+
+ if (e.altKey && e.which == keyCode.DOWN && $headers.children().eq(activeCell).find('.slick-header-menubutton') && !currentEditor) {
+ $focusSink.add($focusSink2).removeAttr('aria-owns').removeAttr('aria-activedescendant');
+ $headers.children().eq(activeCell).find('.slick-header-menubutton').click();
+ return;
+ }
- var x = document.createElement("div");
- x.innerHTML = stringArray.join("");
+ trigger(self.onKeyDown, {row: activeRow, cell: activeCell, grid: self}, e);
+ var handled = e.isImmediatePropagationStopped();
- for (var i = 0, ii = rows.length; i < ii; i++) {
- rowsCache[rows[i]].rowNode = parentNode.appendChild(x.firstChild);
- }
+ if (!handled) {
+ if (!e.shiftKey && !e.altKey && !e.ctrlKey) {
+ // editor may specify an array of keys to bubble
+ if (options.editable && currentEditor && currentEditor.keyCaptureList) {
+ if (currentEditor.keyCaptureList.indexOf( e.which ) > -1) {
+ return;
+ }
+ }
+ if (e.which == keyCode.ESCAPE) {
+ if (!getEditorLock().isActive()) {
+ return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event)
+ }
+ cancelEditAndSetFocus();
+ } else if (e.which == keyCode.PAGE_DOWN) {
+ navigatePageDown();
+ handled = true;
+ } else if (e.which == keyCode.PAGE_UP) {
+ navigatePageUp();
+ handled = true;
+ }
+ else if (e.which == 35) {
+ navigateEnd();
+ handled = true;
+ } else if (e.which == 36) {
+ navigateHome();
+ handled = true;
+ } else if (e.which == keyCode.LEFT) {
+ handled = navigateLeft();
+ } else if (e.which == keyCode.RIGHT) {
+ handled = navigateRight();
+ } else if (e.which == keyCode.UP) {
+ handled = navigateUp();
+ } else if (e.which == keyCode.DOWN) {
+ handled = navigateDown();
+ } else if (e.which == keyCode.TAB) {
+ //handled = navigateNext();
+ } else if (e.which == keyCode.ENTER) {
+ if (options.editable) {
+ if (currentEditor) {
+ // adding new row
+ if (activeRow === getDataLength()) {
+ navigateDown();
+ } else {
+ commitEditAndSetFocus();
+ }
+ } else {
+ if (getEditorLock().commitCurrentEdit()) {
+ makeActiveCellEditable();
+ }
+ }
+ }
+ handled = true;
+ }
+ } else if (e.which == keyCode.TAB && e.shiftKey && !e.ctrlKey && !e.altKey) {
+ //handled = navigatePrev();
+ }
+ else if (e.ctrlKey) {
+ if (e.which == 36) {
+ handled = navigatetoFirstCell();
+ }
+ else if (e.which == 35) {
+ handled = navigatetoLastCell();
+ }
+ else if (e.which == 38) {
+ handled = navigatetoColumnTop();
+ }
+ else if (e.which == 40) {
+ handled = navigatetoColumnBottom();
+ }
+ }
+ }
- if (needToReselectCell) {
- activeCellNode = getCellNode(activeRow, activeCell);
- }
- }
+ if (handled) {
+ // the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it
+ e.stopPropagation();
+ e.preventDefault();
+ try {
+ e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.)
+ }
+ // ignore exceptions - setting the original event's keycode throws access denied exception for "Ctrl"
+ // (hitting control key only, nothing else), "Shift" (maybe others)
+ catch (error) {
+ }
+ }
+ }
- function startPostProcessing() {
- if (!options.enableAsyncPostRender) {
- return;
- }
- clearTimeout(h_postrender);
- h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
- }
+ function handleClick(e) {
+ if (!currentEditor) {
+ // if this click resulted in some cell child node getting focus,
+ // don't steal it back - keyboard events will still bubble up
+ // IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly.
+ if (e.target != document.activeElement || $(e.target).hasClass("slick-cell")) {
+ setFocus();
+ }
+ }
- function invalidatePostProcessingResults(row) {
- delete postProcessedRows[row];
- postProcessFromRow = Math.min(postProcessFromRow, row);
- postProcessToRow = Math.max(postProcessToRow, row);
- startPostProcessing();
- }
+ var cell = getCellFromEvent(e);
+ if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
+ return;
+ }
- function updateRowPositions() {
- for (var row in rowsCache) {
- rowsCache[row].rowNode.style.top = getRowTop(row) + "px";
- }
- }
+ trigger(self.onClick, {row: cell.row, cell: cell.cell, grid: self}, e);
+ if (e.isImmediatePropagationStopped()) {
+ return;
+ }
- function render() {
- if (!initialized) { return; }
- var visible = getVisibleRange();
- var rendered = getRenderedRange();
+ if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) {
+ if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) {
+ scrollRowIntoView(cell.row, false);
+ setActiveCellInternal(getCellNode(cell.row, cell.cell));
+ }
+ }
+ }
- // remove rows no longer in the viewport
- cleanupRows(rendered);
+ function handleContextMenu(e) {
+ var $cell = $(e.target).closest(".slick-cell", $canvas);
+ if ($cell.length === 0) {
+ return;
+ }
- // add new rows & missing cells in existing rows
- if (lastRenderedScrollLeft != scrollLeft) {
- cleanUpAndRenderCells(rendered);
- }
+ // are we editing this cell?
+ if (activeCellNode === $cell[0] && currentEditor !== null) {
+ return;
+ }
- // render missing rows
- renderRows(rendered);
+ trigger(self.onContextMenu, {grid: self}, e);
+ }
- postProcessFromRow = visible.top;
- postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom);
- startPostProcessing();
+ function handleDblClick(e) {
+ var cell = getCellFromEvent(e);
+ if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
+ return;
+ }
- lastRenderedScrollTop = scrollTop;
- lastRenderedScrollLeft = scrollLeft;
- h_render = null;
- }
+ trigger(self.onDblClick, {row: cell.row, cell: cell.cell, grid: self}, e);
+ if (e.isImmediatePropagationStopped()) {
+ return;
+ }
- function handleHeaderRowScroll() {
- var scrollLeft = $headerRowScroller[0].scrollLeft;
- if (scrollLeft != $viewport[0].scrollLeft) {
- $viewport[0].scrollLeft = scrollLeft;
- }
- }
+ if (options.editable) {
+ gotoCell(cell.row, cell.cell, true);
+ }
+ }
- function handleScroll() {
- scrollTop = $viewport[0].scrollTop;
- scrollLeft = $viewport[0].scrollLeft;
- var vScrollDist = Math.abs(scrollTop - prevScrollTop);
- var hScrollDist = Math.abs(scrollLeft - prevScrollLeft);
-
- if (hScrollDist) {
- prevScrollLeft = scrollLeft;
- $headerScroller[0].scrollLeft = scrollLeft;
- $topPanelScroller[0].scrollLeft = scrollLeft;
- $headerRowScroller[0].scrollLeft = scrollLeft;
- }
-
- if (vScrollDist) {
- vScrollDir = prevScrollTop < scrollTop ? 1 : -1;
- prevScrollTop = scrollTop;
-
- // switch virtual pages if needed
- if (vScrollDist < viewportH) {
- scrollTo(scrollTop + offset);
- } else {
- var oldOffset = offset;
- if (h == viewportH) {
- page = 0;
- } else {
- page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph)));
- }
- offset = Math.round(page * cj);
- if (oldOffset != offset) {
- invalidateAllRows();
- }
+ function handleHeaderMouseEnter(e) {
+ trigger(self.onHeaderMouseEnter, {
+ "column": $(this).data("column"),
+ "grid": self
+ }, e);
}
- }
- if (hScrollDist || vScrollDist) {
- if (h_render) {
- clearTimeout(h_render);
+ function handleHeaderMouseLeave(e) {
+ trigger(self.onHeaderMouseLeave, {
+ "column": $(this).data("column"),
+ "grid": self
+ }, e);
}
- if (Math.abs(lastRenderedScrollTop - scrollTop) > 20 ||
- Math.abs(lastRenderedScrollLeft - scrollLeft) > 20) {
- if (options.forceSyncScrolling || (
- Math.abs(lastRenderedScrollTop - scrollTop) < viewportH &&
- Math.abs(lastRenderedScrollLeft - scrollLeft) < viewportW)) {
- render();
- } else {
- h_render = setTimeout(render, 50);
- }
+ function handleHeaderContextMenu(e) {
+ var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
+ var column = $header && $header.data("column");
+ trigger(self.onHeaderContextMenu, {column: column, grid: self}, e);
+ }
- trigger(self.onViewportChanged, {});
+ function handleHeaderClick(e) {
+ var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
+ var column = $header && $header.data("column");
+ if (column) {
+ trigger(self.onHeaderClick, {column: column, grid: self}, e);
+ }
}
- }
- trigger(self.onScroll, {scrollLeft: scrollLeft, scrollTop: scrollTop});
- }
+ function handleMouseEnter(e) {
+ trigger(self.onMouseEnter, {grid: self}, e);
+ }
- function asyncPostProcessRows() {
- var dataLength = getDataLength();
- while (postProcessFromRow <= postProcessToRow) {
- var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--;
- var cacheEntry = rowsCache[row];
- if (!cacheEntry || row >= dataLength) {
- continue;
+ function handleMouseLeave(e) {
+ trigger(self.onMouseLeave, {grid: self}, e);
}
- if (!postProcessedRows[row]) {
- postProcessedRows[row] = {};
+ function cellExists(row, cell) {
+ return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length);
}
- ensureCellNodesInRowsCache(row);
- for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
- if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
- continue;
- }
+ function handleFocusSink(e) {
+ clearTimeout(ariaDescriptionReadTimer);
+ console.log('handleFocusSink');
+ navigateOnFocus("down");
+ $focusSink.add($focusSink2).attr('tabindex', '-1');
+ $(activeCellNode).addClass("active");
- columnIdx = columnIdx | 0;
+ if (currentEditor)
+ currentEditor.focus();
+ //$focusSink.add($focusSink2).attr('aria-owns', $(rowsCache[activeRow].rowNode).attr('id')).attr('aria-activedescendant', $(activeCellNode).attr('id'));
- var m = columns[columnIdx];
- if (m.asyncPostRender && !postProcessedRows[row][columnIdx]) {
- var node = cacheEntry.cellNodesByColumnIdx[columnIdx];
- if (node) {
- m.asyncPostRender(node, row, getDataItem(row), m);
- }
- postProcessedRows[row][columnIdx] = true;
- }
+ setTimeout(function () {
+ if (!isAriaDescriptionRead) {
+ isAriaDescriptionRead = true;
+ $ariaLive.text($('#' + options.ariaDescribedBy).text());
+ }
+ }, 0);
}
- h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
- return;
- }
- }
+ function handleBlurSink(e) {
+ console.log('handleFocusBlur');
+ $focusSink.add($focusSink2).attr('tabindex', '0');
+ if (document.activeElement.getAttribute('hideFocus') !== "" || document.activeElement.getAttribute('hideFocus') === null)
+ $(activeCellNode).removeClass("active");
+ //$focusSink.add($focusSink2).removeAttr('aria-owns').removeAttr('aria-activedescendant');
+ ariaDescriptionReadTimer = setTimeout(function () {
+ isAriaDescriptionRead = false;
+ }, 100);
+ }
- function updateCellCssStylesOnRenderedRows(addedHash, removedHash) {
- var node, columnId, addedRowHash, removedRowHash;
- for (var row in rowsCache) {
- removedRowHash = removedHash && removedHash[row];
- addedRowHash = addedHash && addedHash[row];
+ function getCellFromPoint(x, y) {
+ var row = getRowFromPosition(y);
+ var cell = 0;
- if (removedRowHash) {
- for (columnId in removedRowHash) {
- if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
- node = getCellNode(row, getColumnIndex(columnId));
- if (node) {
- $(node).removeClass(removedRowHash[columnId]);
- }
+ var w = 0;
+ for (var i = 0; i < columns.length && w < x; i++) {
+ w += columns[i].width;
+ cell++;
}
- }
+
+ if (cell < 0) {
+ cell = 0;
+ }
+
+ return {row: row, cell: cell - 1};
}
- if (addedRowHash) {
- for (columnId in addedRowHash) {
- if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
- node = getCellNode(row, getColumnIndex(columnId));
- if (node) {
- $(node).addClass(addedRowHash[columnId]);
- }
+ function getCellFromNode(cellNode) {
+ // read column number from .l
CSS class
+ var cls = /l\d+/.exec(cellNode.className);
+ if (!cls) {
+ throw "getCellFromNode: cannot get cell - " + cellNode.className;
}
- }
+ return parseInt(cls[0].substr(1, cls[0].length - 1), 10);
}
- }
- }
- function addCellCssStyles(key, hash) {
- if (cellCssClasses[key]) {
- throw "addCellCssStyles: cell CSS hash with key '" + key + "' already exists.";
- }
+ function getRowFromNode(rowNode) {
+ for (var row in rowsCache) {
+ if (rowsCache[row].rowNode === rowNode) {
+ return row | 0;
+ }
+ }
- cellCssClasses[key] = hash;
- updateCellCssStylesOnRenderedRows(hash, null);
+ return null;
+ }
- trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash });
- }
+ function getCellFromEvent(e) {
+ var $cell = $(e.target).closest(".slick-cell", $canvas);
+ if (!$cell.length) {
+ return null;
+ }
- function removeCellCssStyles(key) {
- if (!cellCssClasses[key]) {
- return;
- }
+ var row = getRowFromNode($cell[0].parentNode);
+ var cell = getCellFromNode($cell[0]);
- updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]);
- delete cellCssClasses[key];
+ if (row == null || cell == null) {
+ return null;
+ } else {
+ return {
+ "row": row,
+ "cell": cell
+ };
+ }
+ }
- trigger(self.onCellCssStylesChanged, { "key": key, "hash": null });
- }
+ function getCellNodeBox(row, cell) {
+ if (!cellExists(row, cell)) {
+ return null;
+ }
- function setCellCssStyles(key, hash) {
- var prevHash = cellCssClasses[key];
+ var y1 = getRowTop(row);
+ var y2 = y1 + options.rowHeight - 1;
+ var x1 = 0;
+ for (var i = 0; i < cell; i++) {
+ x1 += columns[i].width;
+ }
+ var x2 = x1 + columns[cell].width;
- cellCssClasses[key] = hash;
- updateCellCssStylesOnRenderedRows(hash, prevHash);
+ return {
+ top: y1,
+ left: x1,
+ bottom: y2,
+ right: x2
+ };
+ }
- trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash });
- }
+ //////////////////////////////////////////////////////////////////////////////////////////////
+ // Cell switching
- function getCellCssStyles(key) {
- return cellCssClasses[key];
- }
+ function resetActiveCell() {
+ setActiveCellInternal(null, false);
+ }
- function flashCell(row, cell, speed) {
- speed = speed || 100;
- if (rowsCache[row]) {
- var $cell = $(getCellNode(row, cell));
-
- function toggleCellClass(times) {
- if (!times) {
- return;
- }
- setTimeout(function () {
- $cell.queue(function () {
- $cell.toggleClass(options.cellFlashingCssClass).dequeue();
- toggleCellClass(times - 1);
- });
- },
- speed);
+ function setFocus() {
+ if (tabbingDirection == -1) {
+ $focusSink[0].focus();
+ } else {
+ $focusSink2[0].focus();
+ }
}
- toggleCellClass(4);
- }
- }
+ function scrollCellIntoView(row, cell, doPaging) {
+ scrollRowIntoView(row, doPaging);
- //////////////////////////////////////////////////////////////////////////////////////////////
- // Interactivity
+ var colspan = getColspan(row, cell);
+ var left = columnPosLeft[cell],
+ right = columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)],
+ scrollRight = scrollLeft + viewportW;
- function handleMouseWheel(e) {
- var rowNode = $(e.target).closest(".slick-row")[0];
- if (rowNode != rowNodeFromLastMouseWheelEvent) {
- if (zombieRowNodeFromLastMouseWheelEvent && zombieRowNodeFromLastMouseWheelEvent != rowNode) {
- $canvas[0].removeChild(zombieRowNodeFromLastMouseWheelEvent);
- zombieRowNodeFromLastMouseWheelEvent = null;
+ if (left < scrollLeft) {
+ $viewport.scrollLeft(left);
+ handleScroll();
+ render();
+ } else if (right > scrollRight) {
+ $viewport.scrollLeft(Math.min(left, right - $viewport[0].clientWidth));
+ handleScroll();
+ render();
+ }
}
- rowNodeFromLastMouseWheelEvent = rowNode;
- }
- }
-
- function handleDragInit(e, dd) {
- var cell = getCellFromEvent(e);
- if (!cell || !cellExists(cell.row, cell.cell)) {
- return false;
- }
-
- var retval = trigger(self.onDragInit, dd, e);
- if (e.isImmediatePropagationStopped()) {
- return retval;
- }
- // if nobody claims to be handling drag'n'drop by stopping immediate propagation,
- // cancel out of it
- return false;
- }
+ function setActiveCellInternal(newCell, opt_editMode) {
+ if (activeCellNode !== null) {
+ makeActiveCellNormal();
+ $(activeCellNode).removeClass("active"); //.removeAttr('tabindex');
+ if (rowsCache[activeRow]) {
+ $(rowsCache[activeRow].rowNode).removeClass("active");
+ }
+ }
- function handleDragStart(e, dd) {
- var cell = getCellFromEvent(e);
- if (!cell || !cellExists(cell.row, cell.cell)) {
- return false;
- }
+ var activeCellChanged = (activeCellNode !== newCell);
+ activeCellNode = newCell;
- var retval = trigger(self.onDragStart, dd, e);
- if (e.isImmediatePropagationStopped()) {
- return retval;
- }
+ if (activeCellNode != null) {
+ activeRow = getRowFromNode(activeCellNode.parentNode);
+ activeCell = activePosX = getCellFromNode(activeCellNode);
- return false;
- }
+ if (opt_editMode == null) {
+ opt_editMode = (activeRow == getDataLength()) || options.autoEdit;
+ }
- function handleDrag(e, dd) {
- return trigger(self.onDrag, dd, e);
- }
+ $(activeCellNode).addClass("active"); //.attr('tabindex',0).focus();
+ $(rowsCache[activeRow].rowNode).addClass("active");
+ $focusSink.add($focusSink2).attr('aria-owns', $(rowsCache[activeRow].rowNode).attr('id')).attr('aria-activedescendant', $(activeCellNode).attr('id'));
- function handleDragEnd(e, dd) {
- trigger(self.onDragEnd, dd, e);
- }
+ if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) {
+ clearTimeout(h_editorLoader);
- function handleKeyDown(e) {
- trigger(self.onKeyDown, {row: activeRow, cell: activeCell}, e);
- var handled = e.isImmediatePropagationStopped();
-
- if (!handled) {
- if (!e.shiftKey && !e.altKey && !e.ctrlKey) {
- if (e.which == 27) {
- if (!getEditorLock().isActive()) {
- return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event)
- }
- cancelEditAndSetFocus();
- } else if (e.which == 34) {
- navigatePageDown();
- handled = true;
- } else if (e.which == 33) {
- navigatePageUp();
- handled = true;
- } else if (e.which == 37) {
- handled = navigateLeft();
- } else if (e.which == 39) {
- handled = navigateRight();
- } else if (e.which == 38) {
- handled = navigateUp();
- } else if (e.which == 40) {
- handled = navigateDown();
- } else if (e.which == 9) {
- handled = navigateNext();
- } else if (e.which == 13) {
- if (options.editable) {
- if (currentEditor) {
- // adding new row
- if (activeRow === getDataLength()) {
- navigateDown();
- } else {
- commitEditAndSetFocus();
- }
- } else {
- if (getEditorLock().commitCurrentEdit()) {
- makeActiveCellEditable();
+ if (options.asyncEditorLoading) {
+ h_editorLoader = setTimeout(function () {
+ makeActiveCellEditable();
+ }, options.asyncEditorLoadDelay);
+ } else {
+ makeActiveCellEditable();
+ }
}
- }
+ } else {
+ activeRow = activeCell = null;
}
- handled = true;
- }
- } else if (e.which == 9 && e.shiftKey && !e.ctrlKey && !e.altKey) {
- handled = navigatePrev();
- }
- }
- if (handled) {
- // the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it
- e.stopPropagation();
- e.preventDefault();
- try {
- e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.)
- }
- // ignore exceptions - setting the original event's keycode throws access denied exception for "Ctrl"
- // (hitting control key only, nothing else), "Shift" (maybe others)
- catch (error) {
+ if (activeCellChanged) {
+ trigger(self.onActiveCellChanged, getActiveCell());
+ }
}
- }
- }
- function handleClick(e) {
- if (!currentEditor) {
- // if this click resulted in some cell child node getting focus,
- // don't steal it back - keyboard events will still bubble up
- // IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly.
- if (e.target != document.activeElement || $(e.target).hasClass("slick-cell")) {
- setFocus();
+ function clearTextSelection() {
+ if (document.selection && document.selection.empty) {
+ try {
+ //IE fails here if selected element is not in dom
+ document.selection.empty();
+ } catch (e) { }
+ } else if (window.getSelection) {
+ var sel = window.getSelection();
+ if (sel && sel.removeAllRanges) {
+ sel.removeAllRanges();
+ }
+ }
}
- }
- var cell = getCellFromEvent(e);
- if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
- return;
- }
+ function isCellPotentiallyEditable(row, cell) {
+ var dataLength = getDataLength();
+ // is the data for this row loaded?
+ if (row < dataLength && !getDataItem(row)) {
+ return false;
+ }
+
+ // are we in the Add New row? can we create new from this cell?
+ if (columns[cell].cannotTriggerInsert && row >= dataLength) {
+ return false;
+ }
- trigger(self.onClick, {row: cell.row, cell: cell.cell}, e);
- if (e.isImmediatePropagationStopped()) {
- return;
- }
+ // does this cell have an editor?
+ if (!getEditor(row, cell)) {
+ return false;
+ }
- if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) {
- if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) {
- scrollRowIntoView(cell.row, false);
- setActiveCellInternal(getCellNode(cell.row, cell.cell));
+ return true;
}
- }
- }
- function handleContextMenu(e) {
- var $cell = $(e.target).closest(".slick-cell", $canvas);
- if ($cell.length === 0) {
- return;
- }
+ function makeActiveCellNormal() {
+ if (!currentEditor) {
+ return;
+ }
+ trigger(self.onBeforeCellEditorDestroy, {editor: currentEditor, grid: self});
+ currentEditor.destroy();
+ currentEditor = null;
+
+ if (activeCellNode) {
+ var d = getDataItem(activeRow);
+ $(activeCellNode).removeClass("editable invalid");
+ if (d) {
+ var column = columns[activeCell];
+ var formatter = getFormatter(activeRow, column);
+ activeCellNode.innerHTML = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d, self);
+ invalidatePostProcessingResults(activeRow);
+ }
+ }
- // are we editing this cell?
- if (activeCellNode === $cell[0] && currentEditor !== null) {
- return;
- }
+ // if there previously was text selected on a page (such as selected text in the edit cell just removed),
+ // IE can't set focus to anything else correctly
+ if (navigator.userAgent.toLowerCase().match(/msie/)) {
+ clearTextSelection();
+ }
- trigger(self.onContextMenu, {}, e);
- }
+ /////**/
+ ////// TODO: SET ARIA LABEL AFTER EDIT
+ ////var ariaAttrWrapper = getAriaAttr(activeRow, activeCell);
+ ////if (ariaAttrWrapper)
+ //// $(activeCellNode).attr(ariaAttrWrapper.attr, ariaAttrWrapper.value);
+
- function handleDblClick(e) {
- var cell = getCellFromEvent(e);
- if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
- return;
- }
+ getEditorLock().deactivate(editController);
- trigger(self.onDblClick, {row: cell.row, cell: cell.cell}, e);
- if (e.isImmediatePropagationStopped()) {
- return;
- }
+ // Set this to false so that grid description won't be read after returning from Editor
+ isAriaDescriptionRead = true;
+ }
- if (options.editable) {
- gotoCell(cell.row, cell.cell, true);
- }
- }
+ function makeActiveCellEditable(editor) {
+ if (!activeCellNode) {
+ return;
+ }
+ if (!options.editable) {
+ throw "Grid : makeActiveCellEditable : should never get called when options.editable is false";
+ }
- function handleHeaderMouseEnter(e) {
- trigger(self.onHeaderMouseEnter, {
- "column": $(this).data("column")
- }, e);
- }
+ // cancel pending async call if there is one
+ clearTimeout(h_editorLoader);
- function handleHeaderMouseLeave(e) {
- trigger(self.onHeaderMouseLeave, {
- "column": $(this).data("column")
- }, e);
- }
+ if (!isCellPotentiallyEditable(activeRow, activeCell)) {
+ return;
+ }
- function handleHeaderContextMenu(e) {
- var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
- var column = $header && $header.data("column");
- trigger(self.onHeaderContextMenu, {column: column}, e);
- }
+ var columnDef = columns[activeCell];
+ var item = getDataItem(activeRow);
- function handleHeaderClick(e) {
- var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
- var column = $header && $header.data("column");
- if (column) {
- trigger(self.onHeaderClick, {column: column}, e);
- }
- }
+ if (trigger(self.onBeforeEditCell, {row: activeRow, cell: activeCell, item: item, column: columnDef, grid: self}) === false) {
+ setFocus();
+ return;
+ }
- function handleMouseEnter(e) {
- trigger(self.onMouseEnter, {}, e);
- }
+ getEditorLock().activate(editController);
+ $(activeCellNode).addClass("editable");
- function handleMouseLeave(e) {
- trigger(self.onMouseLeave, {}, e);
- }
+ var useEditor = editor || getEditor(activeRow, activeCell);
- function cellExists(row, cell) {
- return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length);
- }
+ // don't clear the cell if a custom editor is passed through
+ if (!editor && !useEditor.suppressClearOnEdit) {
+ activeCellNode.innerHTML = "";
+ }
- function getCellFromPoint(x, y) {
- var row = getRowFromPosition(y);
- var cell = 0;
+ currentEditor = new useEditor({
+ grid: self,
+ gridPosition: absBox($container[0]),
+ position: absBox(activeCellNode),
+ container: activeCellNode,
+ column: columnDef,
+ item: item || {},
+ commitChanges: commitEditAndSetFocus,
+ cancelChanges: cancelEditAndSetFocus
+ });
- var w = 0;
- for (var i = 0; i < columns.length && w < x; i++) {
- w += columns[i].width;
- cell++;
- }
+ if (item) {
+ currentEditor.loadValue(item);
+ }
- if (cell < 0) {
- cell = 0;
- }
+ serializedEditorValue = currentEditor.serializeValue();
- return {row: row, cell: cell - 1};
- }
+ if (currentEditor.position) {
+ handleActiveCellPositionChange();
+ }
- function getCellFromNode(cellNode) {
- // read column number from .l CSS class
- var cls = /l\d+/.exec(cellNode.className);
- if (!cls) {
- throw "getCellFromNode: cannot get cell - " + cellNode.className;
- }
- return parseInt(cls[0].substr(1, cls[0].length - 1), 10);
- }
+ // clear aria-label for cell node since the editor content will implement this for sub controls
+ $(activeCellNode).removeAttr('aria-label');
+ }
- function getRowFromNode(rowNode) {
- for (var row in rowsCache) {
- if (rowsCache[row].rowNode === rowNode) {
- return row | 0;
+ function commitEditAndSetFocus() {
+ // if the commit fails, it would do so due to a validation error
+ // if so, do not steal the focus from the editor
+ if (getEditorLock().commitCurrentEdit()) {
+ setFocus();
+ if (options.autoEdit) {
+ navigateDown();
+ }
+ }
}
- }
- return null;
- }
+ function cancelEditAndSetFocus() {
+ if (getEditorLock().cancelCurrentEdit()) {
+ setFocus();
+ }
+ }
- function getCellFromEvent(e) {
- var $cell = $(e.target).closest(".slick-cell", $canvas);
- if (!$cell.length) {
- return null;
- }
-
- var row = getRowFromNode($cell[0].parentNode);
- var cell = getCellFromNode($cell[0]);
-
- if (row == null || cell == null) {
- return null;
- } else {
- return {
- "row": row,
- "cell": cell
- };
- }
- }
+ function absBox(elem) {
+ var box = {
+ top: elem.offsetTop,
+ left: elem.offsetLeft,
+ bottom: 0,
+ right: 0,
+ width: $(elem).outerWidth(),
+ height: $(elem).outerHeight(),
+ visible: true};
+ box.bottom = box.top + box.height;
+ box.right = box.left + box.width;
+
+ // walk up the tree
+ var offsetParent = elem.offsetParent;
+ while ((elem = elem.parentNode) != document.body) {
+ if (elem == null) break;
+
+ if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") {
+ box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight;
+ }
- function getCellNodeBox(row, cell) {
- if (!cellExists(row, cell)) {
- return null;
- }
-
- var y1 = getRowTop(row);
- var y2 = y1 + options.rowHeight - 1;
- var x1 = 0;
- for (var i = 0; i < cell; i++) {
- x1 += columns[i].width;
- }
- var x2 = x1 + columns[cell].width;
-
- return {
- top: y1,
- left: x1,
- bottom: y2,
- right: x2
- };
- }
+ if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") {
+ box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth;
+ }
- //////////////////////////////////////////////////////////////////////////////////////////////
- // Cell switching
+ box.left -= elem.scrollLeft;
+ box.top -= elem.scrollTop;
- function resetActiveCell() {
- setActiveCellInternal(null, false);
- }
+ if (elem === offsetParent) {
+ box.left += elem.offsetLeft;
+ box.top += elem.offsetTop;
+ offsetParent = elem.offsetParent;
+ }
- function setFocus() {
- if (tabbingDirection == -1) {
- $focusSink[0].focus();
- } else {
- $focusSink2[0].focus();
- }
- }
+ box.bottom = box.top + box.height;
+ box.right = box.left + box.width;
+ }
- function scrollCellIntoView(row, cell, doPaging) {
- scrollRowIntoView(row, doPaging);
-
- var colspan = getColspan(row, cell);
- var left = columnPosLeft[cell],
- right = columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)],
- scrollRight = scrollLeft + viewportW;
-
- if (left < scrollLeft) {
- $viewport.scrollLeft(left);
- handleScroll();
- render();
- } else if (right > scrollRight) {
- $viewport.scrollLeft(Math.min(left, right - $viewport[0].clientWidth));
- handleScroll();
- render();
- }
- }
+ return box;
+ }
+
+ function getActiveCellPosition() {
+ return absBox(activeCellNode);
+ }
- function setActiveCellInternal(newCell, opt_editMode) {
- if (activeCellNode !== null) {
- makeActiveCellNormal();
- $(activeCellNode).removeClass("active");
- if (rowsCache[activeRow]) {
- $(rowsCache[activeRow].rowNode).removeClass("active");
+ function getGridPosition() {
+ return absBox($container[0])
}
- }
- var activeCellChanged = (activeCellNode !== newCell);
- activeCellNode = newCell;
+ function handleActiveCellPositionChange() {
+ if (!activeCellNode) {
+ return;
+ }
+
+ trigger(self.onActiveCellPositionChanged, {grid: self});
- if (activeCellNode != null) {
- activeRow = getRowFromNode(activeCellNode.parentNode);
- activeCell = activePosX = getCellFromNode(activeCellNode);
+ if (currentEditor) {
+ var cellBox = getActiveCellPosition();
+ if (currentEditor.show && currentEditor.hide) {
+ if (!cellBox.visible) {
+ currentEditor.hide();
+ } else {
+ currentEditor.show();
+ }
+ }
- if (opt_editMode == null) {
- opt_editMode = (activeRow == getDataLength()) || options.autoEdit;
+ if (currentEditor.position) {
+ currentEditor.position(cellBox);
+ }
+ }
}
- $(activeCellNode).addClass("active");
- $(rowsCache[activeRow].rowNode).addClass("active");
+ function getCellEditor() {
+ return currentEditor;
+ }
- if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) {
- clearTimeout(h_editorLoader);
+ function getActiveCell() {
+ if (!activeCellNode) {
+ return null;
+ } else {
+ return {row: activeRow, cell: activeCell, grid: self};
+ }
+ }
- if (options.asyncEditorLoading) {
- h_editorLoader = setTimeout(function () {
- makeActiveCellEditable();
- }, options.asyncEditorLoadDelay);
- } else {
- makeActiveCellEditable();
- }
+ function getActiveCellNode() {
+ return activeCellNode;
}
- } else {
- activeRow = activeCell = null;
- }
- if (activeCellChanged) {
- trigger(self.onActiveCellChanged, getActiveCell());
- }
- }
+ function scrollRowIntoView(row, doPaging) {
+ var rowAtTop = row * options.rowHeight;
+ var rowAtBottom = (row + 1) * options.rowHeight - viewportH + (viewportHasHScroll ? scrollbarDimensions.height : 0);
- function clearTextSelection() {
- if (document.selection && document.selection.empty) {
- try {
- //IE fails here if selected element is not in dom
- document.selection.empty();
- } catch (e) { }
- } else if (window.getSelection) {
- var sel = window.getSelection();
- if (sel && sel.removeAllRanges) {
- sel.removeAllRanges();
- }
- }
- }
+ // need to page down?
+ if ((row + 1) * options.rowHeight > scrollTop + viewportH + offset) {
+ scrollTo(doPaging ? rowAtTop : rowAtBottom);
+ render();
+ }
+ // or page up?
+ else if (row * options.rowHeight < scrollTop + offset) {
+ scrollTo(doPaging ? rowAtBottom : rowAtTop);
+ render();
+ }
+ }
- function isCellPotentiallyEditable(row, cell) {
- var dataLength = getDataLength();
- // is the data for this row loaded?
- if (row < dataLength && !getDataItem(row)) {
- return false;
- }
+ function scrollRowToTop(row) {
+ scrollTo(row * options.rowHeight);
+ render();
+ }
- // are we in the Add New row? can we create new from this cell?
- if (columns[cell].cannotTriggerInsert && row >= dataLength) {
- return false;
- }
+ function scrollPage(dir) {
+ var deltaRows = dir * numVisibleRows;
+ scrollTo((getRowFromPosition(scrollTop) + deltaRows) * options.rowHeight);
+ render();
- // does this cell have an editor?
- if (!getEditor(row, cell)) {
- return false;
- }
+ if (options.enableCellNavigation && activeRow != null) {
+ var row = activeRow + deltaRows;
+ var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
+ if (row >= dataLengthIncludingAddNew) {
+ row = dataLengthIncludingAddNew - 1;
+ }
+ if (row < 0) {
+ row = 0;
+ }
- return true;
- }
+ var cell = 0, prevCell = null;
+ var prevActivePosX = activePosX;
+ while (cell <= activePosX) {
+ if (canCellBeActive(row, cell)) {
+ prevCell = cell;
+ }
+ cell += getColspan(row, cell);
+ }
- function makeActiveCellNormal() {
- if (!currentEditor) {
- return;
- }
- trigger(self.onBeforeCellEditorDestroy, {editor: currentEditor});
- currentEditor.destroy();
- currentEditor = null;
-
- if (activeCellNode) {
- var d = getDataItem(activeRow);
- $(activeCellNode).removeClass("editable invalid");
- if (d) {
- var column = columns[activeCell];
- var formatter = getFormatter(activeRow, column);
- activeCellNode.innerHTML = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d);
- invalidatePostProcessingResults(activeRow);
- }
- }
-
- // if there previously was text selected on a page (such as selected text in the edit cell just removed),
- // IE can't set focus to anything else correctly
- if (navigator.userAgent.toLowerCase().match(/msie/)) {
- clearTextSelection();
- }
-
- getEditorLock().deactivate(editController);
- }
+ if (prevCell !== null) {
+ setActiveCellInternal(getCellNode(row, prevCell));
+ activePosX = prevActivePosX;
+ } else {
+ resetActiveCell();
+ }
+ }
+ }
- function makeActiveCellEditable(editor) {
- if (!activeCellNode) {
- return;
- }
- if (!options.editable) {
- throw "Grid : makeActiveCellEditable : should never get called when options.editable is false";
- }
-
- // cancel pending async call if there is one
- clearTimeout(h_editorLoader);
-
- if (!isCellPotentiallyEditable(activeRow, activeCell)) {
- return;
- }
-
- var columnDef = columns[activeCell];
- var item = getDataItem(activeRow);
-
- if (trigger(self.onBeforeEditCell, {row: activeRow, cell: activeCell, item: item, column: columnDef}) === false) {
- setFocus();
- return;
- }
-
- getEditorLock().activate(editController);
- $(activeCellNode).addClass("editable");
-
- // don't clear the cell if a custom editor is passed through
- if (!editor) {
- activeCellNode.innerHTML = "";
- }
-
- currentEditor = new (editor || getEditor(activeRow, activeCell))({
- grid: self,
- gridPosition: absBox($container[0]),
- position: absBox(activeCellNode),
- container: activeCellNode,
- column: columnDef,
- item: item || {},
- commitChanges: commitEditAndSetFocus,
- cancelChanges: cancelEditAndSetFocus
- });
-
- if (item) {
- currentEditor.loadValue(item);
- }
-
- serializedEditorValue = currentEditor.serializeValue();
-
- if (currentEditor.position) {
- handleActiveCellPositionChange();
- }
- }
+ function navigatePageDown() {
+ scrollPage(1);
+ }
- function commitEditAndSetFocus() {
- // if the commit fails, it would do so due to a validation error
- // if so, do not steal the focus from the editor
- if (getEditorLock().commitCurrentEdit()) {
- setFocus();
- if (options.autoEdit) {
- navigateDown();
+ function navigatePageUp() {
+ scrollPage(-1);
}
- }
- }
- function cancelEditAndSetFocus() {
- if (getEditorLock().cancelCurrentEdit()) {
- setFocus();
- }
- }
+ function getColspan(row, cell) {
+ var metadata = data.getItemMetadata && data.getItemMetadata(row);
+ if (!metadata || !metadata.columns) {
+ return 1;
+ }
+
+ var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell];
+ var colspan = (columnData && columnData.colspan);
+ if (colspan === "*") {
+ colspan = columns.length - cell;
+ } else {
+ colspan = colspan || 1;
+ }
- function absBox(elem) {
- var box = {
- top: elem.offsetTop,
- left: elem.offsetLeft,
- bottom: 0,
- right: 0,
- width: $(elem).outerWidth(),
- height: $(elem).outerHeight(),
- visible: true};
- box.bottom = box.top + box.height;
- box.right = box.left + box.width;
+ return colspan;
+ }
- // walk up the tree
- var offsetParent = elem.offsetParent;
- while ((elem = elem.parentNode) != document.body) {
- if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") {
- box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight;
+ function findFirstFocusableCell(row) {
+ var cell = 0;
+ while (cell < columns.length) {
+ if (canCellBeActive(row, cell)) {
+ return cell;
+ }
+ cell += getColspan(row, cell);
+ }
+ return null;
}
- if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") {
- box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth;
+ function findLastFocusableCell(row) {
+ var cell = 0;
+ var lastFocusableCell = null;
+ while (cell < columns.length) {
+ if (canCellBeActive(row, cell)) {
+ lastFocusableCell = cell;
+ }
+ cell += getColspan(row, cell);
+ }
+ return lastFocusableCell;
}
- box.left -= elem.scrollLeft;
- box.top -= elem.scrollTop;
+ function gotoRight(row, cell, posX) {
+ if (cell >= columns.length) {
+ return null;
+ }
- if (elem === offsetParent) {
- box.left += elem.offsetLeft;
- box.top += elem.offsetTop;
- offsetParent = elem.offsetParent;
+ do {
+ cell += getColspan(row, cell);
+ }
+ while (cell < columns.length && !canCellBeActive(row, cell));
+
+ if (cell < columns.length) {
+ return {
+ "row": row,
+ "cell": cell,
+ "posX": cell
+ };
+ }
+ return null;
}
- box.bottom = box.top + box.height;
- box.right = box.left + box.width;
- }
+ function gotoLeft(row, cell, posX) {
+ if (cell <= 0) {
+ return null;
+ }
- return box;
- }
+ var firstFocusableCell = findFirstFocusableCell(row);
+ if (firstFocusableCell === null || firstFocusableCell >= cell) {
+ return null;
+ }
- function getActiveCellPosition() {
- return absBox(activeCellNode);
- }
+ var prev = {
+ "row": row,
+ "cell": firstFocusableCell,
+ "posX": firstFocusableCell
+ };
+ var pos;
+ while (true) {
+ pos = gotoRight(prev.row, prev.cell, prev.posX);
+ if (!pos) {
+ return null;
+ }
+ if (pos.cell >= cell) {
+ return prev;
+ }
+ prev = pos;
+ }
+ }
- function getGridPosition() {
- return absBox($container[0])
- }
+ function gotoDown(row, cell, posX) {
+ /* START Added from gotoNext -- this will be executed on tab for first time. So copied here */
+ if (row == null && cell == null) {
+ row = cell = posX = 0;
+ if (canCellBeActive(row, cell)) {
+ return {
+ "row": row,
+ "cell": cell,
+ "posX": cell
+ };
+ }
+ }
+ /* END */
- function handleActiveCellPositionChange() {
- if (!activeCellNode) {
- return;
- }
+ var prevCell;
+ var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
+ while (true) {
+ if (++row >= dataLengthIncludingAddNew) {
+ return null;
+ }
- trigger(self.onActiveCellPositionChanged, {});
+ prevCell = cell = 0;
+ while (cell <= posX) {
+ prevCell = cell;
+ cell += getColspan(row, cell);
+ }
- if (currentEditor) {
- var cellBox = getActiveCellPosition();
- if (currentEditor.show && currentEditor.hide) {
- if (!cellBox.visible) {
- currentEditor.hide();
- } else {
- currentEditor.show();
- }
+ if (canCellBeActive(row, prevCell)) {
+ return {
+ "row": row,
+ "cell": prevCell,
+ "posX": posX
+ };
+ }
+ }
}
- if (currentEditor.position) {
- currentEditor.position(cellBox);
- }
- }
- }
+ function gotoUp(row, cell, posX) {
+ var prevCell;
+ while (true) {
+ if (--row < 0) {
+ return null;
+ }
- function getCellEditor() {
- return currentEditor;
- }
+ prevCell = cell = 0;
+ while (cell <= posX) {
+ prevCell = cell;
+ cell += getColspan(row, cell);
+ }
- function getActiveCell() {
- if (!activeCellNode) {
- return null;
- } else {
- return {row: activeRow, cell: activeCell};
- }
- }
+ if (canCellBeActive(row, prevCell)) {
+ return {
+ "row": row,
+ "cell": prevCell,
+ "posX": posX
+ };
+ }
+ }
+ }
- function getActiveCellNode() {
- return activeCellNode;
- }
+ function gotoNext(row, cell, posX) {
+ if (row == null && cell == null) {
+ row = cell = posX = 0;
+ if (canCellBeActive(row, cell)) {
+ return {
+ "row": row,
+ "cell": cell,
+ "posX": cell
+ };
+ }
+ }
- function scrollRowIntoView(row, doPaging) {
- var rowAtTop = row * options.rowHeight;
- var rowAtBottom = (row + 1) * options.rowHeight - viewportH + (viewportHasHScroll ? scrollbarDimensions.height : 0);
-
- // need to page down?
- if ((row + 1) * options.rowHeight > scrollTop + viewportH + offset) {
- scrollTo(doPaging ? rowAtTop : rowAtBottom);
- render();
- }
- // or page up?
- else if (row * options.rowHeight < scrollTop + offset) {
- scrollTo(doPaging ? rowAtBottom : rowAtTop);
- render();
- }
- }
+ var pos = gotoRight(row, cell, posX);
+ if (pos) {
+ return pos;
+ }
- function scrollRowToTop(row) {
- scrollTo(row * options.rowHeight);
- render();
- }
+ var firstFocusableCell = null;
+ var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
+ while (++row < dataLengthIncludingAddNew) {
+ firstFocusableCell = findFirstFocusableCell(row);
+ if (firstFocusableCell !== null) {
+ return {
+ "row": row,
+ "cell": firstFocusableCell,
+ "posX": firstFocusableCell
+ };
+ }
+ }
+ return null;
+ }
+
+ function gotoPrev(row, cell, posX) {
+ if (row == null && cell == null) {
+ row = getDataLengthIncludingAddNew() - 1;
+ cell = posX = columns.length - 1;
+ if (canCellBeActive(row, cell)) {
+ return {
+ "row": row,
+ "cell": cell,
+ "posX": cell
+ };
+ }
+ }
- function scrollPage(dir) {
- var deltaRows = dir * numVisibleRows;
- scrollTo((getRowFromPosition(scrollTop) + deltaRows) * options.rowHeight);
- render();
+ var pos;
+ var lastSelectableCell;
+ while (!pos) {
+ pos = gotoLeft(row, cell, posX);
+ if (pos) {
+ break;
+ }
+ if (--row < 0) {
+ return null;
+ }
- if (options.enableCellNavigation && activeRow != null) {
- var row = activeRow + deltaRows;
- var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
- if (row >= dataLengthIncludingAddNew) {
- row = dataLengthIncludingAddNew - 1;
- }
- if (row < 0) {
- row = 0;
+ cell = 0;
+ lastSelectableCell = findLastFocusableCell(row);
+ if (lastSelectableCell !== null) {
+ pos = {
+ "row": row,
+ "cell": lastSelectableCell,
+ "posX": lastSelectableCell
+ };
+ }
+ }
+ return pos;
}
-
- var cell = 0, prevCell = null;
- var prevActivePosX = activePosX;
- while (cell <= activePosX) {
- if (canCellBeActive(row, cell)) {
- prevCell = cell;
- }
- cell += getColspan(row, cell);
+ function gotoHome(row, cell, posX) {
+ if (cell <= 0) {
+ return null;
}
- if (prevCell !== null) {
- setActiveCellInternal(getCellNode(row, prevCell));
- activePosX = prevActivePosX;
- } else {
- resetActiveCell();
+ var firstFocusableCell = findFirstFocusableCell(row);
+ if (firstFocusableCell === null || firstFocusableCell >= cell) {
+ return null;
}
- }
- }
- function navigatePageDown() {
- scrollPage(1);
+ var prev = {
+ "row": row,
+ "cell": firstFocusableCell,
+ "posX": firstFocusableCell
+ };
+ return prev;
}
- function navigatePageUp() {
- scrollPage(-1);
- }
+ function gotoEnd(row, cell, posX) {
+ var lastFocusableCell = findLastFocusableCell(row);
+ if (lastFocusableCell === null || lastFocusableCell<=cell) {
+ return null;
+ }
- function getColspan(row, cell) {
- var metadata = data.getItemMetadata && data.getItemMetadata(row);
- if (!metadata || !metadata.columns) {
- return 1;
- }
-
- var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell];
- var colspan = (columnData && columnData.colspan);
- if (colspan === "*") {
- colspan = columns.length - cell;
- } else {
- colspan = colspan || 1;
- }
-
- return colspan;
+ var next = {
+ "row": row,
+ "cell": lastFocusableCell,
+ "posX": lastFocusableCell
+ };
+ return next;
}
- function findFirstFocusableCell(row) {
- var cell = 0;
- while (cell < columns.length) {
- if (canCellBeActive(row, cell)) {
- return cell;
- }
- cell += getColspan(row, cell);
- }
- return null;
+ function gotoFirstCell(row, cell, posX) {
+ var first = {
+ "row": 0,
+ "cell": 0,
+ "posX": 0
+ };
+ return first;
}
- function findLastFocusableCell(row) {
- var cell = 0;
- var lastFocusableCell = null;
- while (cell < columns.length) {
- if (canCellBeActive(row, cell)) {
- lastFocusableCell = cell;
- }
- cell += getColspan(row, cell);
- }
- return lastFocusableCell;
+ function gotoLastCell(row, cell, posX) {
+ var last = {
+ "row": getDataLength() - 1,
+ "cell": columns.length - 1,
+ "posX": columns.length - 1
+ };
+ return last;
}
- function gotoRight(row, cell, posX) {
- if (cell >= columns.length) {
- return null;
- }
-
- do {
- cell += getColspan(row, cell);
- }
- while (cell < columns.length && !canCellBeActive(row, cell));
-
- if (cell < columns.length) {
- return {
- "row": row,
- "cell": cell,
- "posX": cell
+ function gotoColumnTop(row, cell, posX) {
+ var topcell = {
+ "row": 0,
+ "cell": cell,
+ "posX": posX
};
- }
- return null;
+ return topcell;
}
-
- function gotoLeft(row, cell, posX) {
- if (cell <= 0) {
- return null;
- }
-
- var firstFocusableCell = findFirstFocusableCell(row);
- if (firstFocusableCell === null || firstFocusableCell >= cell) {
- return null;
- }
-
- var prev = {
- "row": row,
- "cell": firstFocusableCell,
- "posX": firstFocusableCell
- };
- var pos;
- while (true) {
- pos = gotoRight(prev.row, prev.cell, prev.posX);
- if (!pos) {
- return null;
- }
- if (pos.cell >= cell) {
- return prev;
- }
- prev = pos;
- }
+ function gotoColumnBottom(row, cell, posX) {
+ var bottomcell = {
+ "row": getDataLength() - 1,
+ "cell": cell,
+ "posX": posX
+ };
+ return bottomcell;
}
-
- function gotoDown(row, cell, posX) {
- var prevCell;
- var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
- while (true) {
- if (++row >= dataLengthIncludingAddNew) {
- return null;
+ function navigateRight() {
+ return navigate("right");
}
- prevCell = cell = 0;
- while (cell <= posX) {
- prevCell = cell;
- cell += getColspan(row, cell);
+ function navigateLeft() {
+ return navigate("left");
}
- if (canCellBeActive(row, prevCell)) {
- return {
- "row": row,
- "cell": prevCell,
- "posX": posX
- };
+ function navigateDown() {
+ return navigate("down");
}
- }
- }
- function gotoUp(row, cell, posX) {
- var prevCell;
- while (true) {
- if (--row < 0) {
- return null;
+ function navigateUp() {
+ return navigate("up");
}
- prevCell = cell = 0;
- while (cell <= posX) {
- prevCell = cell;
- cell += getColspan(row, cell);
+ function navigateNext() {
+ return navigate("next");
}
- if (canCellBeActive(row, prevCell)) {
- return {
- "row": row,
- "cell": prevCell,
- "posX": posX
- };
+ function navigatePrev() {
+ return navigate("prev");
}
- }
- }
-
- function gotoNext(row, cell, posX) {
- if (row == null && cell == null) {
- row = cell = posX = 0;
- if (canCellBeActive(row, cell)) {
- return {
- "row": row,
- "cell": cell,
- "posX": cell
- };
- }
- }
-
- var pos = gotoRight(row, cell, posX);
- if (pos) {
- return pos;
- }
-
- var firstFocusableCell = null;
- var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
- while (++row < dataLengthIncludingAddNew) {
- firstFocusableCell = findFirstFocusableCell(row);
- if (firstFocusableCell !== null) {
- return {
- "row": row,
- "cell": firstFocusableCell,
- "posX": firstFocusableCell
- };
+ function navigateHome() {
+ return navigate("home");
}
- }
- return null;
- }
- function gotoPrev(row, cell, posX) {
- if (row == null && cell == null) {
- row = getDataLengthIncludingAddNew() - 1;
- cell = posX = columns.length - 1;
- if (canCellBeActive(row, cell)) {
- return {
- "row": row,
- "cell": cell,
- "posX": cell
- };
+ function navigateEnd() {
+ return navigate("end");
}
- }
-
- var pos;
- var lastSelectableCell;
- while (!pos) {
- pos = gotoLeft(row, cell, posX);
- if (pos) {
- break;
+ function navigatetoFirstCell() {
+ return navigate("firstcell");
}
- if (--row < 0) {
- return null;
+ function navigatetoLastCell() {
+ return navigate("lastcell");
}
-
- cell = 0;
- lastSelectableCell = findLastFocusableCell(row);
- if (lastSelectableCell !== null) {
- pos = {
- "row": row,
- "cell": lastSelectableCell,
- "posX": lastSelectableCell
- };
+ function navigatetoColumnTop() {
+ return navigate("columntop");
+ }
+ function navigatetoColumnBottom() {
+ return navigate("columnbottom");
+ }
+ function navigateOnFocus(dir) {
+ console.log('naviagateOnFocus');
+ // isNavigatedOnFocus - used to focus the first cell upon grid focus for the first time
+ if (!isNavigatedOnFocus && !activeRow && !activeCell && !activePosX) {
+ isNavigatedOnFocus = true;
+ navigate(dir);
+ }
+ else {
+ setFocus();
+ }
}
- }
- return pos;
- }
-
- function navigateRight() {
- return navigate("right");
- }
- function navigateLeft() {
- return navigate("left");
- }
+ /**
+ * @param {string} dir Navigation direction.
+ * @return {boolean} Whether navigation resulted in a change of active cell.
+ */
+ function navigate(dir) {
+ if (!options.enableCellNavigation) {
+ return false;
+ }
- function navigateDown() {
- return navigate("down");
- }
+ /*if (!activeCellNode && dir != "prev" && dir != "next") {
+ return false;
+ }*/
- function navigateUp() {
- return navigate("up");
- }
+ if (!getEditorLock().commitCurrentEdit()) {
+ return true;
+ }
+ setFocus();
+
+ var tabbingDirections = {
+ "up": -1,
+ "down": 1,
+ "left": -1,
+ "right": 1,
+ "prev": -1,
+ "next": 1,
+ "home": -1,
+ "end": 1,
+ "firstcell": -1,
+ "lastcell": 1,
+ "columntop": -1,
+ "columnbottom": 1
+ };
+ tabbingDirection = tabbingDirections[dir];
+
+ var stepFunctions = {
+ "up": gotoUp,
+ "down": gotoDown,
+ "left": gotoLeft,
+ "right": gotoRight,
+ "prev": gotoPrev,
+ "next": gotoNext,
+ "home": gotoHome,
+ "end": gotoEnd,
+ "firstcell": gotoFirstCell,
+ "lastcell": gotoLastCell,
+ "columntop": gotoColumnTop,
+ "columnbottom": gotoColumnBottom
+ };
+ var stepFn = stepFunctions[dir];
+ var pos = stepFn(activeRow, activeCell, activePosX);
+ if (pos) {
+ var isAddNewRow = (pos.row == getDataLength());
+ scrollCellIntoView(pos.row, pos.cell, !isAddNewRow);
+ setActiveCellInternal(getCellNode(pos.row, pos.cell));
+ activePosX = pos.posX;
+ return true;
+ } else {
+ setActiveCellInternal(getCellNode(activeRow, activeCell));
+ return false;
+ }
+ }
- function navigateNext() {
- return navigate("next");
- }
+ function getCellNode(row, cell) {
+ if (rowsCache[row]) {
+ ensureCellNodesInRowsCache(row);
+ return rowsCache[row].cellNodesByColumnIdx[cell];
+ }
+ return null;
+ }
- function navigatePrev() {
- return navigate("prev");
- }
+ function setActiveCell(row, cell) {
+ if (!initialized) { return; }
+ if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
+ return;
+ }
- /**
- * @param {string} dir Navigation direction.
- * @return {boolean} Whether navigation resulted in a change of active cell.
- */
- function navigate(dir) {
- if (!options.enableCellNavigation) {
- return false;
- }
-
- if (!activeCellNode && dir != "prev" && dir != "next") {
- return false;
- }
-
- if (!getEditorLock().commitCurrentEdit()) {
- return true;
- }
- setFocus();
-
- var tabbingDirections = {
- "up": -1,
- "down": 1,
- "left": -1,
- "right": 1,
- "prev": -1,
- "next": 1
- };
- tabbingDirection = tabbingDirections[dir];
-
- var stepFunctions = {
- "up": gotoUp,
- "down": gotoDown,
- "left": gotoLeft,
- "right": gotoRight,
- "prev": gotoPrev,
- "next": gotoNext
- };
- var stepFn = stepFunctions[dir];
- var pos = stepFn(activeRow, activeCell, activePosX);
- if (pos) {
- var isAddNewRow = (pos.row == getDataLength());
- scrollCellIntoView(pos.row, pos.cell, !isAddNewRow);
- setActiveCellInternal(getCellNode(pos.row, pos.cell));
- activePosX = pos.posX;
- return true;
- } else {
- setActiveCellInternal(getCellNode(activeRow, activeCell));
- return false;
- }
- }
+ if (!options.enableCellNavigation) {
+ return;
+ }
- function getCellNode(row, cell) {
- if (rowsCache[row]) {
- ensureCellNodesInRowsCache(row);
- return rowsCache[row].cellNodesByColumnIdx[cell];
- }
- return null;
- }
+ scrollCellIntoView(row, cell, false);
+ setActiveCellInternal(getCellNode(row, cell), false);
+ }
- function setActiveCell(row, cell) {
- if (!initialized) { return; }
- if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
- return;
- }
+ function canCellBeActive(row, cell) {
+ if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() ||
+ row < 0 || cell >= columns.length || cell < 0) {
+ return false;
+ }
- if (!options.enableCellNavigation) {
- return;
- }
+ var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
+ if (rowMetadata && typeof rowMetadata.focusable === "boolean") {
+ return rowMetadata.focusable;
+ }
- scrollCellIntoView(row, cell, false);
- setActiveCellInternal(getCellNode(row, cell), false);
- }
+ var columnMetadata = rowMetadata && rowMetadata.columns;
+ if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable === "boolean") {
+ return columnMetadata[columns[cell].id].focusable;
+ }
+ if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable === "boolean") {
+ return columnMetadata[cell].focusable;
+ }
- function canCellBeActive(row, cell) {
- if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() ||
- row < 0 || cell >= columns.length || cell < 0) {
- return false;
- }
-
- var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
- if (rowMetadata && typeof rowMetadata.focusable === "boolean") {
- return rowMetadata.focusable;
- }
-
- var columnMetadata = rowMetadata && rowMetadata.columns;
- if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable === "boolean") {
- return columnMetadata[columns[cell].id].focusable;
- }
- if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable === "boolean") {
- return columnMetadata[cell].focusable;
- }
-
- return columns[cell].focusable;
- }
+ return columns[cell].focusable;
+ }
- function canCellBeSelected(row, cell) {
- if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
- return false;
- }
+ function canCellBeSelected(row, cell) {
+ if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
+ return false;
+ }
- var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
- if (rowMetadata && typeof rowMetadata.selectable === "boolean") {
- return rowMetadata.selectable;
- }
+ var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
+ if (rowMetadata && typeof rowMetadata.selectable === "boolean") {
+ return rowMetadata.selectable;
+ }
- var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]);
- if (columnMetadata && typeof columnMetadata.selectable === "boolean") {
- return columnMetadata.selectable;
- }
+ var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]);
+ if (columnMetadata && typeof columnMetadata.selectable === "boolean") {
+ return columnMetadata.selectable;
+ }
- return columns[cell].selectable;
- }
+ return columns[cell].selectable;
+ }
- function gotoCell(row, cell, forceEdit) {
- if (!initialized) { return; }
- if (!canCellBeActive(row, cell)) {
- return;
- }
+ function gotoCell(row, cell, forceEdit) {
+ if (!initialized) { return; }
+ if (!canCellBeActive(row, cell)) {
+ return;
+ }
- if (!getEditorLock().commitCurrentEdit()) {
- return;
- }
+ if (!getEditorLock().commitCurrentEdit()) {
+ return;
+ }
- scrollCellIntoView(row, cell, false);
+ scrollCellIntoView(row, cell, false);
- var newCell = getCellNode(row, cell);
+ var newCell = getCellNode(row, cell);
- // if selecting the 'add new' row, start editing right away
- setActiveCellInternal(newCell, forceEdit || (row === getDataLength()) || options.autoEdit);
+ // if selecting the 'add new' row, start editing right away
+ setActiveCellInternal(newCell, forceEdit || (row === getDataLength()) || options.autoEdit);
- // if no editor was created, set the focus back on the grid
- if (!currentEditor) {
- setFocus();
- }
- }
+ // if no editor was created, set the focus back on the grid
+ if (!currentEditor) {
+ setFocus();
+ }
+ }
- //////////////////////////////////////////////////////////////////////////////////////////////
- // IEditor implementation for the editor lock
-
- function commitCurrentEdit() {
- var item = getDataItem(activeRow);
- var column = columns[activeCell];
-
- if (currentEditor) {
- if (currentEditor.isValueChanged()) {
- var validationResults = currentEditor.validate();
-
- if (validationResults.valid) {
- if (activeRow < getDataLength()) {
- var editCommand = {
- row: activeRow,
- cell: activeCell,
- editor: currentEditor,
- serializedValue: currentEditor.serializeValue(),
- prevSerializedValue: serializedEditorValue,
- execute: function () {
- this.editor.applyValue(item, this.serializedValue);
- updateRow(this.row);
- trigger(self.onCellChange, {
- row: activeRow,
- cell: activeCell,
- item: item
- });
- },
- undo: function () {
- this.editor.applyValue(item, this.prevSerializedValue);
- updateRow(this.row);
- trigger(self.onCellChange, {
- row: activeRow,
- cell: activeCell,
- item: item
- });
+ //////////////////////////////////////////////////////////////////////////////////////////////
+ // IEditor implementation for the editor lock
+
+ function commitCurrentEdit() {
+ var item = getDataItem(activeRow);
+ var column = columns[activeCell];
+
+ if (currentEditor) {
+ if (currentEditor.isValueChanged()) {
+ var validationResults = currentEditor.validate();
+
+ if (validationResults.valid) {
+ if (activeRow < getDataLength()) {
+ var editCommand = {
+ row: activeRow,
+ cell: activeCell,
+ editor: currentEditor,
+ serializedValue: currentEditor.serializeValue(),
+ prevSerializedValue: serializedEditorValue,
+ execute: function () {
+ this.editor.applyValue(item, this.serializedValue);
+ updateRow(this.row);
+ trigger(self.onCellChange, {
+ row: activeRow,
+ cell: activeCell,
+ item: item,
+ grid: self
+ });
+ },
+ undo: function () {
+ this.editor.applyValue(item, this.prevSerializedValue);
+ updateRow(this.row);
+ trigger(self.onCellChange, {
+ row: activeRow,
+ cell: activeCell,
+ item: item,
+ grid: self
+ });
+ }
+ };
+
+ if (options.editCommandHandler) {
+ makeActiveCellNormal();
+ options.editCommandHandler(item, column, editCommand);
+ } else {
+ editCommand.execute();
+ makeActiveCellNormal();
+ }
+
+ } else {
+ var newItem = {};
+ currentEditor.applyValue(newItem, currentEditor.serializeValue());
+ makeActiveCellNormal();
+ trigger(self.onAddNewRow, {item: newItem, column: column, grid: self});
+ }
+
+ // check whether the lock has been re-acquired by event handlers
+ return !getEditorLock().isActive();
+ } else {
+ // Re-add the CSS class to trigger transitions, if any.
+ $(activeCellNode).removeClass("invalid");
+ $(activeCellNode).width(); // force layout
+ $(activeCellNode).addClass("invalid");
+
+ trigger(self.onValidationError, {
+ editor: currentEditor,
+ cellNode: activeCellNode,
+ validationResults: validationResults,
+ row: activeRow,
+ cell: activeCell,
+ column: column,
+ grid: self
+ });
+
+ currentEditor.focus();
+ return false;
+ }
}
- };
- if (options.editCommandHandler) {
- makeActiveCellNormal();
- options.editCommandHandler(item, column, editCommand);
- } else {
- editCommand.execute();
makeActiveCellNormal();
- }
-
- } else {
- var newItem = {};
- currentEditor.applyValue(newItem, currentEditor.serializeValue());
- makeActiveCellNormal();
- trigger(self.onAddNewRow, {item: newItem, column: column});
- }
-
- // check whether the lock has been re-acquired by event handlers
- return !getEditorLock().isActive();
- } else {
- // Re-add the CSS class to trigger transitions, if any.
- $(activeCellNode).removeClass("invalid");
- $(activeCellNode).width(); // force layout
- $(activeCellNode).addClass("invalid");
-
- trigger(self.onValidationError, {
- editor: currentEditor,
- cellNode: activeCellNode,
- validationResults: validationResults,
- row: activeRow,
- cell: activeCell,
- column: column
- });
-
- currentEditor.focus();
- return false;
- }
+ }
+ return true;
}
- makeActiveCellNormal();
- }
- return true;
- }
-
- function cancelCurrentEdit() {
- makeActiveCellNormal();
- return true;
- }
+ function cancelCurrentEdit() {
+ makeActiveCellNormal();
+ return true;
+ }
- function rowsToRanges(rows) {
- var ranges = [];
- var lastCell = columns.length - 1;
- for (var i = 0; i < rows.length; i++) {
- ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell));
- }
- return ranges;
- }
+ function rowsToRanges(rows) {
+ var ranges = [];
+ var lastCell = columns.length - 1;
+ for (var i = 0; i < rows.length; i++) {
+ ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell));
+ }
+ return ranges;
+ }
- function getSelectedRows() {
- if (!selectionModel) {
- throw "Selection model is not set";
- }
- return selectedRows;
- }
+ function getSelectedRows() {
+ if (!selectionModel) {
+ throw "Selection model is not set";
+ }
+ return selectedRows;
+ }
- function setSelectedRows(rows) {
- if (!selectionModel) {
- throw "Selection model is not set";
- }
- selectionModel.setSelectedRanges(rowsToRanges(rows));
- }
+ function setSelectedRows(rows) {
+ if (!selectionModel) {
+ throw "Selection model is not set";
+ }
+ selectionModel.setSelectedRanges(rowsToRanges(rows));
+ }
- //////////////////////////////////////////////////////////////////////////////////////////////
- // Debug
+ //////////////////////////////////////////////////////////////////////////////////////////////
+ // Debug
- this.debug = function () {
- var s = "";
+ this.debug = function () {
+ var s = "";
- s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered);
- s += ("\n" + "counter_rows_removed: " + counter_rows_removed);
- s += ("\n" + "renderedRows: " + renderedRows);
- s += ("\n" + "numVisibleRows: " + numVisibleRows);
- s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight);
- s += ("\n" + "n(umber of pages): " + n);
- s += ("\n" + "(current) page: " + page);
- s += ("\n" + "page height (ph): " + ph);
- s += ("\n" + "vScrollDir: " + vScrollDir);
+ s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered);
+ s += ("\n" + "counter_rows_removed: " + counter_rows_removed);
+ s += ("\n" + "renderedRows: " + renderedRows);
+ s += ("\n" + "numVisibleRows: " + numVisibleRows);
+ s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight);
+ s += ("\n" + "n(umber of pages): " + n);
+ s += ("\n" + "(current) page: " + page);
+ s += ("\n" + "page height (ph): " + ph);
+ s += ("\n" + "vScrollDir: " + vScrollDir);
- alert(s);
- };
+ alert(s);
+ };
- // a debug helper to be able to access private members
- this.eval = function (expr) {
- return eval(expr);
- };
+ // a debug helper to be able to access private members
+ this.eval = function (expr) {
+ return eval(expr);
+ };
- //////////////////////////////////////////////////////////////////////////////////////////////
- // Public API
-
- $.extend(this, {
- "slickGridVersion": "2.1",
-
- // Events
- "onScroll": new Slick.Event(),
- "onSort": new Slick.Event(),
- "onHeaderMouseEnter": new Slick.Event(),
- "onHeaderMouseLeave": new Slick.Event(),
- "onHeaderContextMenu": new Slick.Event(),
- "onHeaderClick": new Slick.Event(),
- "onHeaderCellRendered": new Slick.Event(),
- "onBeforeHeaderCellDestroy": new Slick.Event(),
- "onHeaderRowCellRendered": new Slick.Event(),
- "onBeforeHeaderRowCellDestroy": new Slick.Event(),
- "onMouseEnter": new Slick.Event(),
- "onMouseLeave": new Slick.Event(),
- "onClick": new Slick.Event(),
- "onDblClick": new Slick.Event(),
- "onContextMenu": new Slick.Event(),
- "onKeyDown": new Slick.Event(),
- "onAddNewRow": new Slick.Event(),
- "onValidationError": new Slick.Event(),
- "onViewportChanged": new Slick.Event(),
- "onColumnsReordered": new Slick.Event(),
- "onColumnsResized": new Slick.Event(),
- "onCellChange": new Slick.Event(),
- "onBeforeEditCell": new Slick.Event(),
- "onBeforeCellEditorDestroy": new Slick.Event(),
- "onBeforeDestroy": new Slick.Event(),
- "onActiveCellChanged": new Slick.Event(),
- "onActiveCellPositionChanged": new Slick.Event(),
- "onDragInit": new Slick.Event(),
- "onDragStart": new Slick.Event(),
- "onDrag": new Slick.Event(),
- "onDragEnd": new Slick.Event(),
- "onSelectedRowsChanged": new Slick.Event(),
- "onCellCssStylesChanged": new Slick.Event(),
-
- // Methods
- "registerPlugin": registerPlugin,
- "unregisterPlugin": unregisterPlugin,
- "getColumns": getColumns,
- "setColumns": setColumns,
- "getColumnIndex": getColumnIndex,
- "updateColumnHeader": updateColumnHeader,
- "setSortColumn": setSortColumn,
- "setSortColumns": setSortColumns,
- "getSortColumns": getSortColumns,
- "autosizeColumns": autosizeColumns,
- "getOptions": getOptions,
- "setOptions": setOptions,
- "getData": getData,
- "getDataLength": getDataLength,
- "getDataItem": getDataItem,
- "setData": setData,
- "getSelectionModel": getSelectionModel,
- "setSelectionModel": setSelectionModel,
- "getSelectedRows": getSelectedRows,
- "setSelectedRows": setSelectedRows,
- "getContainerNode": getContainerNode,
-
- "render": render,
- "invalidate": invalidate,
- "invalidateRow": invalidateRow,
- "invalidateRows": invalidateRows,
- "invalidateAllRows": invalidateAllRows,
- "updateCell": updateCell,
- "updateRow": updateRow,
- "getViewport": getVisibleRange,
- "getRenderedRange": getRenderedRange,
- "resizeCanvas": resizeCanvas,
- "updateRowCount": updateRowCount,
- "scrollRowIntoView": scrollRowIntoView,
- "scrollRowToTop": scrollRowToTop,
- "scrollCellIntoView": scrollCellIntoView,
- "getCanvasNode": getCanvasNode,
- "focus": setFocus,
-
- "getCellFromPoint": getCellFromPoint,
- "getCellFromEvent": getCellFromEvent,
- "getActiveCell": getActiveCell,
- "setActiveCell": setActiveCell,
- "getActiveCellNode": getActiveCellNode,
- "getActiveCellPosition": getActiveCellPosition,
- "resetActiveCell": resetActiveCell,
- "editActiveCell": makeActiveCellEditable,
- "getCellEditor": getCellEditor,
- "getCellNode": getCellNode,
- "getCellNodeBox": getCellNodeBox,
- "canCellBeSelected": canCellBeSelected,
- "canCellBeActive": canCellBeActive,
- "navigatePrev": navigatePrev,
- "navigateNext": navigateNext,
- "navigateUp": navigateUp,
- "navigateDown": navigateDown,
- "navigateLeft": navigateLeft,
- "navigateRight": navigateRight,
- "navigatePageUp": navigatePageUp,
- "navigatePageDown": navigatePageDown,
- "gotoCell": gotoCell,
- "getTopPanel": getTopPanel,
- "setTopPanelVisibility": setTopPanelVisibility,
- "setHeaderRowVisibility": setHeaderRowVisibility,
- "getHeaderRow": getHeaderRow,
- "getHeaderRowColumn": getHeaderRowColumn,
- "getGridPosition": getGridPosition,
- "flashCell": flashCell,
- "addCellCssStyles": addCellCssStyles,
- "setCellCssStyles": setCellCssStyles,
- "removeCellCssStyles": removeCellCssStyles,
- "getCellCssStyles": getCellCssStyles,
-
- "init": finishInitialization,
- "destroy": destroy,
-
- // IEditor implementation
- "getEditorLock": getEditorLock,
- "getEditController": getEditController
- });
+ //////////////////////////////////////////////////////////////////////////////////////////////
+ // Public API
+
+ $.extend(this, {
+ "slickGridVersion": "2.2.4",
+
+ // Events
+ "onScroll": new Slick.Event(),
+ "onSort": new Slick.Event(),
+ "onHeaderMouseEnter": new Slick.Event(),
+ "onHeaderMouseLeave": new Slick.Event(),
+ "onHeaderContextMenu": new Slick.Event(),
+ "onHeaderClick": new Slick.Event(),
+ "onHeaderCellRendered": new Slick.Event(),
+ "onBeforeHeaderCellDestroy": new Slick.Event(),
+ "onHeaderRowCellRendered": new Slick.Event(),
+ "onFooterRowCellRendered": new Slick.Event(),
+ "onBeforeHeaderRowCellDestroy": new Slick.Event(),
+ "onBeforeFooterRowCellDestroy": new Slick.Event(),
+ "onMouseEnter": new Slick.Event(),
+ "onMouseLeave": new Slick.Event(),
+ "onClick": new Slick.Event(),
+ "onDblClick": new Slick.Event(),
+ "onContextMenu": new Slick.Event(),
+ "onKeyDown": new Slick.Event(),
+ "onAddNewRow": new Slick.Event(),
+ "onValidationError": new Slick.Event(),
+ "onViewportChanged": new Slick.Event(),
+ "onColumnsReordered": new Slick.Event(),
+ "onColumnsResized": new Slick.Event(),
+ "onCellChange": new Slick.Event(),
+ "onBeforeEditCell": new Slick.Event(),
+ "onBeforeCellEditorDestroy": new Slick.Event(),
+ "onBeforeDestroy": new Slick.Event(),
+ "onActiveCellChanged": new Slick.Event(),
+ "onActiveCellPositionChanged": new Slick.Event(),
+ "onDragInit": new Slick.Event(),
+ "onDragStart": new Slick.Event(),
+ "onDrag": new Slick.Event(),
+ "onDragEnd": new Slick.Event(),
+ "onSelectedRowsChanged": new Slick.Event(),
+ "onCellCssStylesChanged": new Slick.Event(),
+
+ // Methods
+ "registerPlugin": registerPlugin,
+ "unregisterPlugin": unregisterPlugin,
+ "getColumns": getColumns,
+ "setColumns": setColumns,
+ "getColumnIndex": getColumnIndex,
+ "updateColumnHeader": updateColumnHeader,
+ "setSortColumn": setSortColumn,
+ "setSortColumns": setSortColumns,
+ "getSortColumns": getSortColumns,
+ "autosizeColumns": autosizeColumns,
+ "getOptions": getOptions,
+ "setOptions": setOptions,
+ "getData": getData,
+ "getDataLength": getDataLength,
+ "getDataItem": getDataItem,
+ "setData": setData,
+ "getSelectionModel": getSelectionModel,
+ "setSelectionModel": setSelectionModel,
+ "getSelectedRows": getSelectedRows,
+ "setSelectedRows": setSelectedRows,
+ "getContainerNode": getContainerNode,
+
+ "render": render,
+ "invalidate": invalidate,
+ "invalidateRow": invalidateRow,
+ "invalidateRows": invalidateRows,
+ "invalidateAllRows": invalidateAllRows,
+ "updateCell": updateCell,
+ "updateRow": updateRow,
+ "getViewport": getVisibleRange,
+ "getRenderedRange": getRenderedRange,
+ "resizeCanvas": resizeCanvas,
+ "updateRowCount": updateRowCount,
+ "scrollRowIntoView": scrollRowIntoView,
+ "scrollRowToTop": scrollRowToTop,
+ "scrollCellIntoView": scrollCellIntoView,
+ "getCanvasNode": getCanvasNode,
+ "focus": setFocus,
+
+ "getCellFromPoint": getCellFromPoint,
+ "getCellFromEvent": getCellFromEvent,
+ "getActiveCell": getActiveCell,
+ "setActiveCell": setActiveCell,
+ "getActiveCellNode": getActiveCellNode,
+ "getActiveCellPosition": getActiveCellPosition,
+ "resetActiveCell": resetActiveCell,
+ "editActiveCell": makeActiveCellEditable,
+ "getCellEditor": getCellEditor,
+ "getCellNode": getCellNode,
+ "getCellNodeBox": getCellNodeBox,
+ "canCellBeSelected": canCellBeSelected,
+ "canCellBeActive": canCellBeActive,
+ "navigatePrev": navigatePrev,
+ "navigateNext": navigateNext,
+ "navigateUp": navigateUp,
+ "navigateDown": navigateDown,
+ "navigateLeft": navigateLeft,
+ "navigateRight": navigateRight,
+ "navigatePageUp": navigatePageUp,
+ "navigatePageDown": navigatePageDown,
+ "gotoCell": gotoCell,
+ "getTopPanel": getTopPanel,
+ "setTopPanelVisibility": setTopPanelVisibility,
+ "setHeaderRowVisibility": setHeaderRowVisibility,
+ "getHeaderRow": getHeaderRow,
+ "getHeaderRowColumn": getHeaderRowColumn,
+ "setFooterRowVisibility": setFooterRowVisibility,
+ "getFooterRow": getFooterRow,
+ "getFooterRowColumn": getFooterRowColumn,
+ "getGridPosition": getGridPosition,
+ "flashCell": flashCell,
+ "addCellCssStyles": addCellCssStyles,
+ "setCellCssStyles": setCellCssStyles,
+ "removeCellCssStyles": removeCellCssStyles,
+ "getCellCssStyles": getCellCssStyles,
+
+ "init": finishInitialization,
+ "destroy": destroy,
+
+ // IEditor implementation
+ "getEditorLock": getEditorLock,
+ "getEditController": getEditController
+ });
- init();
- }
+ init();
+ }
}(jQuery));