forked from andrewchilds/SlickGrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slick.grid.js
2764 lines (2372 loc) · 110 KB
/
slick.grid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* (c) 2009-2010 Michael Leibman (michael.leibman@gmail.com)
* http://github.com/mleibman/slickgrid
* Distributed under MIT license.
* All rights reserved.
*
* SlickGrid v1.4.3
*
* TODO:
* - frozen columns
* - consistent events (EventHelper? jQuery events?)
*
*
* OPTIONS:
* rowHeight - (default 25px) Row height in pixels.
* enableAddRow - (default false) If true, a blank row will be displayed at the bottom - typing values in that row will add a new one.
* leaveSpaceForNewRows - (default false)
* editable - (default false) If false, no cells will be switched into edit mode.
* autoEdit - (default true) Cell will not automatically go into edit mode when selected.
* enableCellNavigation - (default true) If false, no cells will be selectable.
* enableCellRangeSelection - (default false) If true, user will be able to select a cell range. onCellRangeSelected event will be fired.
* defaultColumnWidth - (default 80px) Default column width in pixels (if columns[cell].width is not specified).
* defaultMinWidth - (default 30px) Default column min-width in pixels (if columns[cell].minWidth is not specified).
* enableColumnReorder - (default true) Allows the user to reorder columns.
* asyncEditorLoading - (default false) Makes cell editors load asynchronously after a small delay.
* This greatly increases keyboard navigation speed.
* asyncEditorLoadDelay - (default 100msec) Delay after which cell editor is loaded. Ignored unless asyncEditorLoading is true.
* forceFitColumns - (default false) Force column sizes to fit into the viewport (avoid horizontal scrolling).
* enableAsyncPostRender - (default false) If true, async post rendering will occur and asyncPostRender delegates on columns will be called.
* asyncPostRenderDelay - (default 60msec) Delay after which async post renderer delegate is called.
* autoHeight - (default false) If true, vertically resizes to fit all rows.
* editorLock - (default Slick.GlobalEditorLock) A Slick.EditorLock instance to use for controlling concurrent data edits.
* showSecondaryHeaderRow - (default false) If true, an extra blank (to be populated externally) row will be displayed just below the header columns.
* showTotalsHeader - (default false) If true, a totals row will be displayed above the viewport.
* showTotalsFooter - (default false) If true, a totals row will be displayed below the viewport.
* secondaryHeaderRowHeight - (default 25px) The height of the secondary header row.
* syncColumnCellResize - (default false) Synchronously resize column cells when column headers are resized
* rowCssClasses - (default null) A function which (given a row's data item as an argument) returns a space-delimited string of CSS classes that will be applied to the slick-row element. Note that this should be fast, as it is called every time a row is displayed.
* cellHighlightCssClass - (default "highlighted") A CSS class to apply to cells highlighted via setHighlightedCells().
* cellFlashingCssClass - (default "flashing") A CSS class to apply to flashing cells (flashCell()).
* formatterFactory - (default null) A factory object responsible to creating a formatter for a given cell.
* Must implement getFormatter(column).
* editorFactory - (default null) A factory object responsible to creating an editor for a given cell.
* Must implement getEditor(column).
* multiSelect - (default true) Enable multiple row selection.
*
* COLUMN DEFINITION (columns) OPTIONS:
* id - Column ID.
* name - Column name to put in the header.
* toolTip - Tooltip (if different from name).
* field - Property of the data context to bind to.
* formatter - (default 'return value || ""') Function responsible for rendering the contents of a cell. Signature: function formatter(row, cell, value, columnDef, dataContext) { ... return "..."; }
* editor - An Editor class.
* validator - An extra validation function to be passed to the editor.
* unselectable - If true, the cell cannot be selected (and therefore edited).
* cannotTriggerInsert - If true, a new row cannot be created from just the value of this cell.
* width - Width of the column in pixels.
* resizable - (default true) If false, the column cannot be resized.
* sortable - (default false) If true, the column can be sorted (onSort will be called).
* minWidth - Minimum allowed column width for resizing.
* maxWidth - Maximum allowed column width for resizing.
* cssClass - A CSS class to add to the cell.
* rerenderOnResize - Rerender the column when it is resized (useful for columns relying on cell width or adaptive formatters).
* asyncPostRender - Function responsible for manipulating the cell DOM node after it has been rendered (called in the background).
* behavior - Configures the column with one of several available predefined behaviors: "select", "move", "selectAndMove".
* defaultToAscending - (default true) If false, the column sorting will default to descending.
* visible - (default true) If false, the column will be hidden by default, to be made available in a ColumnPicker or other UI element.
*
* EVENTS:
* onSort -
* onHeaderContextMenu -
* onHeaderClick -
* onClick -
* onDblClick -
* onContextMenu -
* onKeyDown -
* onAddNewRow -
* onValidationError -
* onViewportChanged -
* onSelectedRowsChanged -
* onColumnsReordered -
* onColumnsResized -
* onBeforeMoveRows -
* onMoveRows -
* onCellChange - Raised when cell has been edited. Args: row,cell,dataContext.
* onBeforeEditCell - Raised before a cell goes into edit mode. Return false to cancel. Args: row,cell,dataContext.
* onBeforeCellEditorDestroy - Raised before a cell editor is destroyed. Args: current cell editor.
* onBeforeDestroy - Raised just before the grid control is destroyed (part of the destroy() method).
* onCurrentCellChanged - Raised when the selected (active) cell changed. Args: {row:currentRow, cell:currentCell}.
* onCellRangeSelected - Raised when a user selects a range of cells. Args: {from:{row,cell}, to:{row,cell}}.
* onSetAllColumns -
*
* NOTES:
* Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods.
* This increases the speed dramatically, but can only be done safely because there are no event handlers
* or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy()
* and do proper cleanup.
*
*
* @param {Node} container Container node to create the grid in.
* @param {Array} or {Object} data An array of objects for databinding.
* @param {Array} columns An array of column definitions.
* @param {Object} options Grid options.
*/
// make sure required JavaScript modules are loaded
if (typeof jQuery === "undefined") {
throw new Error("SlickGrid requires jquery module to be loaded");
}
if (!jQuery.fn.drag) {
throw new Error("SlickGrid requires jquery.event.drag module to be loaded");
}
(function($) {
var scrollbarDimensions; // shared across all grids on this page
//////////////////////////////////////////////////////////////////////////////////////////////
// EditorLock class implementation (available as Slick.EditorLock)
/** @constructor */
function EditorLock() {
/// <summary>
/// Track currently active edit controller and ensure
/// that onle a single controller can be active at a time.
/// Edit controller is an object that is responsible for
/// gory details of looking after editor in the browser,
/// and allowing EditorLock clients to either accept
/// or cancel editor changes without knowing any of the
/// implementation details. SlickGrid instance is used
/// as edit controller for cell editors.
/// </summary>
var currentEditController = null;
this.isActive = function isActive(editController) {
/// <summary>
/// Return true if the specified editController
/// is currently active in this lock instance
/// (i.e. if that controller acquired edit lock).
/// If invoked without parameters ("editorLock.isActive()"),
/// return true if any editController is currently
/// active in this lock instance.
/// </summary>
return (editController ? currentEditController === editController : currentEditController !== null);
};
this.activate = function activate(editController) {
/// <summary>
/// Set the specified editController as the active
/// controller in this lock instance (acquire edit lock).
/// If another editController is already active,
/// an error will be thrown (i.e. before calling
/// this method isActive() must be false,
/// afterwards isActive() will be true).
/// </summary>
if (editController === currentEditController) { // already activated?
return;
}
if (currentEditController !== null) {
throw "SlickGrid.EditorLock.activate: an editController is still active, can't activate another editController";
}
if (!editController.commitCurrentEdit) {
throw "SlickGrid.EditorLock.activate: editController must implement .commitCurrentEdit()";
}
if (!editController.cancelCurrentEdit) {
throw "SlickGrid.EditorLock.activate: editController must implement .cancelCurrentEdit()";
}
currentEditController = editController;
};
this.deactivate = function deactivate(editController) {
/// <summary>
/// Unset the specified editController as the active
/// controller in this lock instance (release edit lock).
/// If the specified editController is not the editController
/// that is currently active in this lock instance,
/// an error will be thrown.
/// </summary>
if (currentEditController !== editController) {
throw "SlickGrid.EditorLock.deactivate: specified editController is not the currently active one";
}
currentEditController = null;
};
this.commitCurrentEdit = function commitCurrentEdit() {
/// <summary>
/// Invoke the "commitCurrentEdit" method on the
/// editController that is active in this lock
/// instance and return the return value of that method
/// (if no controller is active, return true).
/// "commitCurrentEdit" is expected to return true
/// to indicate successful commit, false otherwise.
/// </summary>
return (currentEditController ? currentEditController.commitCurrentEdit() : true);
};
this.cancelCurrentEdit = function cancelCurrentEdit() {
/// <summary>
/// Invoke the "cancelCurrentEdit" method on the
/// editController that is active in this lock
/// instance (if no controller is active, do nothing).
/// Returns true if the edit was succesfully cancelled.
/// </summary>
return (currentEditController ? currentEditController.cancelCurrentEdit() : true);
};
} // end of EditorLock function (class)
//////////////////////////////////////////////////////////////////////////////////////////////
// SlickGrid class implementation (available as Slick.Grid)
/** @constructor */
function SlickGrid(container,data,columns,options,totals) {
/// <summary>
/// Create and manage virtual grid in the specified $container,
/// connecting it to the specified data source. Data is presented
/// as a grid with the specified columns and data.length rows.
/// Options alter behaviour of the grid.
/// </summary>
// settings
var defaults = {
rowHeight: 25,
defaultColumnWidth: 80,
defaultMinWidth: 30,
enableAddRow: false,
leaveSpaceForNewRows: false,
editable: false,
autoEdit: true,
enableCellNavigation: true,
enableCellRangeSelection: false,
enableColumnReorder: true,
asyncEditorLoading: false,
asyncEditorLoadDelay: 100,
forceFitColumns: false,
enableAsyncPostRender: false,
asyncPostRenderDelay: 60,
autoHeight: false,
editorLock: Slick.GlobalEditorLock,
showSecondaryHeaderRow: false,
secondaryHeaderRowHeight: 25,
showTotalsHeader: false,
showTotalsFooter: false,
totalsScrollSpeed: 150,
syncColumnCellResize: false,
enableAutoTooltips: true,
toolTipMaxLength: null,
formatterFactory: null,
editorFactory: null,
cellHighlightCssClass: "highlighted",
cellFlashingCssClass: "flashing",
multiSelect: true
},
gridData, gridDataGetLength, gridDataGetItem;
var columnDefaults = {
name: "",
resizable: true,
sortable: false,
defaultToAscending: true,
visible: true
};
// scroller
var maxSupportedCssHeight; // browser's breaking point
var th; // virtual height
var h; // real scrollable height
var ph; // page height
var n; // number of pages
var cj; // "jumpiness" coefficient
var page = 0; // current page
var offset = 0; // current page offset
var scrollDir = 1;
// private
var $container;
var uid = "slickgrid_" + Math.round(1000000 * Math.random());
var self = this;
var $headerScroller;
var $headers;
var $totalScroller;
var $totals;
var $totalFooterScroller;
var $totalsFooter;
var totalsHeight = 0;
var $secondaryHeaderScroller;
var $secondaryHeaders;
var $viewport;
var $canvas;
var $style;
var stylesheet;
var viewportH, viewportW;
var viewportHasHScroll;
var headerColumnWidthDiff, headerColumnHeightDiff, cellWidthDiff, cellHeightDiff; // padding+border
var absoluteColumnMinWidth;
var hasScrollbarOffset = false;
var currentRow, currentCell;
var currentCellNode = null;
var currentEditor = null;
var serializedEditorValue;
var editController;
var rowsCache = {};
var renderedRows = 0;
var numVisibleRows;
var prevScrollTop = 0;
var scrollTop = 0;
var lastRenderedScrollTop = 0;
var prevScrollLeft = 0;
var avgRowRenderTime = 10;
var selectedRows = [];
var selectedRowsLookup = {};
var columnsById = {};
var highlightedCells;
var sortColumnId;
var sortAsc = true;
var allColumns = [];
// async call handles
var h_editorLoader = null;
var h_render = null;
var h_postrender = null;
var postProcessedRows = {};
var postProcessToRow = null;
var postProcessFromRow = null;
// perf counters
var counter_rows_rendered = 0;
var counter_rows_removed = 0;
//////////////////////////////////////////////////////////////////////////////////////////////
// Initialization
function init() {
/// <summary>
/// Initialize 'this' (self) instance of a SlickGrid.
/// This function is called by the constructor.
/// </summary>
$container = $(container);
gridData = data;
gridDataGetLength = gridData.getLength || defaultGetLength;
gridDataGetItem = gridData.getItem || defaultGetItem;
maxSupportedCssHeight = getMaxSupportedCssHeight();
scrollbarDimensions = scrollbarDimensions || measureScrollbar(); // skip measurement if already have dimensions
options = $.extend({},defaults,options);
columnDefaults.width = options.defaultColumnWidth;
columnDefaults.minWidth = options.defaultMinWidth;
for (var i = 0; i < columns.length; i++) {
columns[i] = $.extend({},columnDefaults,columns[i]);
}
allColumns = columns;
// validate loaded JavaScript modules against requested options
if (options.enableColumnReorder && !$.fn.sortable) {
throw new Error("SlickGrid's \"enableColumnReorder = true\" option requires jquery-ui.sortable module to be loaded");
}
editController = {
"commitCurrentEdit": commitCurrentEdit,
"cancelCurrentEdit": cancelCurrentEdit
};
$container
.empty()
.attr("tabIndex",0)
.attr("hideFocus",true)
.css("overflow","hidden")
.css("outline",0)
.addClass(uid)
.addClass("ui-widget");
// set up a positioning container if needed
if (!/relative|absolute|fixed/.test($container.css("position")))
$container.css("position","relative");
$headerScroller = $("<div class='slick-header ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container);
$headers = $("<div class='slick-header-columns' style='width:100000px; left:-10000px' />").appendTo($headerScroller);
$secondaryHeaderScroller = $("<div class='slick-header-secondary ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container);
$secondaryHeaders = $("<div class='slick-header-columns-secondary' style='width:100000px' />").appendTo($secondaryHeaderScroller);
if (options.showTotalsHeader) {
$totalScroller = $("<div class='slick-totals slick-totals-header ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container);
$totals = $("<div class='slick-totals-columns' style='width:100000px' />").appendTo($totalScroller);
}
$viewport = $("<div class='slick-viewport' tabIndex='0' hideFocus style='width:100%;overflow-x:auto;outline:0;position:relative;overflow-y:auto;'>").appendTo($container);
$canvas = $("<div class='grid-canvas' tabIndex='0' hideFocus />").appendTo($viewport);
if (options.showTotalsFooter) {
$totalFooterScroller = $("<div class='slick-totals slick-totals-footer ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container);
$totalsFooter = $("<div class='slick-totals-columns' style='width:100000px' />").appendTo($totalFooterScroller);
}
if (!options.showSecondaryHeaderRow) {
$secondaryHeaderScroller.hide();
}
// 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();
resizeViewportHeight();
// 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)
$viewport.bind("selectstart.ui", function (event) { return $(event.target).is("input,textarea"); }); // disable text selection in grid cells except in input and textarea elements (this is IE-specific, because selectstart event will only fire in IE)
removeInvisibleColumns();
createColumnHeaders();
setupColumnSort();
setupDragEvents();
createCssRules();
resizeAndRender();
bindAncestorScrollEvents();
$viewport.bind("scroll.slickgrid", handleScroll);
$container.bind("resize.slickgrid", resizeAndRender);
$canvas.bind("keydown.slickgrid", handleKeyDown);
$canvas.bind("click.slickgrid", handleClick);
$canvas.bind("dblclick.slickgrid", handleDblClick);
$canvas.bind("contextmenu.slickgrid", handleContextMenu);
$canvas.bind("mouseover.slickgrid", handleHover);
$headerScroller.bind("contextmenu.slickgrid", handleHeaderContextMenu);
$headerScroller.bind("click.slickgrid", handleHeaderClick);
}
function addSlickLoader() {
// $container.animate({ opacity: 0.5 }, 150);
$('<div class="slick-loader">' +
'<div class="slick-loader-text">' +
'<strong>Loading Data...</strong><br/>Please wait' +
'</div>' +
'</div>').insertAfter($container).css({
height: $container.height(),
top: $container.position().top
}).find('div.slick-loader-text').css({ top: ($container.height() / 2.5) });
}
function removeSlickLoader() {
// $container.animate({ opacity: 1 }, 150);
$('div.slick-loader').fadeOut(250, function() {
$(this).remove();
});
}
function removeInvisibleColumns() {
var tmp = [];
for (var i = 0; i < columns.length; i++) {
if (columns[i].visible == true) {
tmp.push(columns[i]);
}
}
columns = tmp;
}
function measureScrollbar() {
/// <summary>
/// Measure width of a vertical scrollbar
/// and height of a horizontal scrollbar.
/// </summary
/// <returns>
/// { width: pixelWidth, height: pixelHeight }
/// </returns>
var $c = $("<div style='position:absolute; top:-10000px; left:-10000px; width:100px; height:100px; overflow:scroll;'></div>").appendTo("body");
var dim = { width: $c.width() - $c[0].clientWidth, height: $c.height() - $c[0].clientHeight };
$c.remove();
return dim;
}
function setCanvasWidth(width) {
$canvas.width(width);
viewportHasHScroll = (width > viewportW - scrollbarDimensions.width);
}
function disableSelection($target) {
/// <summary>
/// Disable text selection (using mouse) in
/// the specified target.
/// </summary
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 defaultGetLength() {
/// <summary>
/// Default implementation of getLength method
/// returns the length of the array.
/// </summary
return gridData.length;
}
function defaultGetItem(i) {
/// <summary>
/// Default implementation of getItem method
/// returns the item at specified position in
/// the array.
/// </summary
return gridData[i];
}
function getMaxSupportedCssHeight() {
var increment = 1000000;
var supportedHeight = increment;
// FF reports the height back but still renders blank after ~6M px
var testUpTo = ($.browser.mozilla) ? 5000000 : 1000000000;
var div = $("<div style='display:none' />").appendTo(document.body);
while (supportedHeight <= testUpTo) {
div.css("height", supportedHeight + increment);
if (div.height() !== supportedHeight + increment)
break;
else
supportedHeight += increment;
}
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) {
// bind to scroll containers only
if (elem == $viewport[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight)
$(elem).bind("scroll.slickgrid", handleCurrentCellPositionChange);
}
}
function unbindAncestorScrollEvents() {
$canvas.parents().unbind("scroll.slickgrid");
}
function createColumnHeaders() {
function hoverBegin() {
$(this).addClass("ui-state-hover");
}
function hoverEnd() {
$(this).removeClass("ui-state-hover");
}
$headers.empty();
columnsById = {};
for (var i = 0; i < columns.length; i++) {
var m = columns[i];
columnsById[m.id] = i;
var header = $("<div class='ui-state-default slick-header-column' id='" + uid + m.id + "' />")
.html("<span class='slick-column-name'>" + m.name + "</span>")
.width((m.currentWidth || m.width) - headerColumnWidthDiff)
.attr("title", m.toolTip || m.name || "")
.data("fieldId", m.id)
.appendTo($headers);
if (options.enableColumnReorder || m.sortable) {
header.hover(hoverBegin, hoverEnd);
}
if (m.sortable) {
header.append("<span class='slick-sort-indicator' />");
}
}
setTotalHeaders();
setTotalHeaderHeight();
setSortColumn(sortColumnId,sortAsc);
setupColumnResize();
if (options.enableColumnReorder) {
setupColumnReorder();
}
}
function setTotalHeaders() {
if ($totals) {
$totals.empty();
}
if ($totalsFooter) {
$totalsFooter.empty();
}
for (var i = 0; i < columns.length; i++) {
var c = columns[i];
if (totals && ($totals || $totalsFooter)) {
var total = $("<div class='ui-state-default slick-totals-column c" + i + "' />")
.addClass(c.cssClass || '')
.html(totals[c.field] || '');
if ($totals) {
$totals.append(total.clone());
}
if ($totalsFooter) {
$totalsFooter.append(total.clone());
}
}
}
}
function setTotalHeaderHeight() {
if (totalsHeight == 0) {
totalsHeight += ($totals) ? $totals.outerHeight() : 0;
totalsHeight += ($totalsFooter) ? $totalsFooter.outerHeight() : 0;
}
}
function showTotals() {
if ($totals) {
if ($totals.is(':visible')) {
return;
}
$totals.slideDown(options.totalsScrollSpeed);
}
if ($totalsFooter) {
if ($totalsFooter.is(':visible')) {
return;
}
$totalsFooter.slideDown(options.totalsScrollSpeed);
}
$viewport.animate({ height: ($viewport.height() - totalsHeight) }, options.totalsScrollSpeed);
}
function hideTotals() {
if ($totals) {
if ($totals.is(':hidden')) {
return;
}
$totals.slideUp(options.totalsScrollSpeed);
}
if ($totalsFooter) {
if ($totalsFooter.is(':hidden')) {
return;
}
$totalsFooter.slideUp(options.totalsScrollSpeed);
}
$viewport.animate({ height: ($viewport.height() + totalsHeight) }, options.totalsScrollSpeed);
}
function setupColumnSort() {
$headers.click(function(e) {
if ($(e.target).hasClass("slick-resizable-handle")) {
return;
}
if (self.onSort) {
var $col = $(e.target).closest(".slick-header-column");
if (!$col.length)
return;
var column = columns[getSiblingIndex($col[0])];
if (column.sortable) {
if (!options.editorLock.commitCurrentEdit())
return;
if (column.id === sortColumnId) {
sortAsc = !sortAsc;
}
else {
sortColumnId = column.id;
sortAsc = column.defaultToAscending;
}
setSortColumn(sortColumnId,sortAsc);
self.onSort(column,sortAsc);
}
}
});
}
function setupColumnReorder() {
$headers.sortable({
containment: "parent",
axis: "x",
cursor: "default",
distance: 15,
tolerance: "pointer",
helper: "clone",
placeholder: "slick-sortable-placeholder ui-state-default slick-header-column",
forcePlaceholderSize: true,
start: function(e, ui) { $(ui.helper).addClass("slick-header-column-active"); },
beforeStop: function(e, ui) { $(ui.helper).removeClass("slick-header-column-active"); },
stop: function(e, ui) {
if (!options.editorLock.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,""))]);
}
mergeReorderedColumns(reorderedColumns, ui);
setColumns(reorderedColumns);
if (self.onColumnsReordered) {
self.onColumnsReordered();
}
e.stopPropagation();
setupColumnResize();
}
});
}
function mergeReorderedColumns(columns, ui) {
var moved = $('.slick-column-name', ui.item).text();
var prev = -1;
var newColumn = null;
for (var i = 0; i < columns.length; i++) {
if (columns[i].name == moved) {
break;
}
prev = i;
}
for (var from = 0; from < allColumns.length; from++) {
if (allColumns[from].name == moved) {
break;
}
}
for (var to = 0; to < allColumns.length; to++) {
if (prev == -1 || allColumns[to].name == columns[prev].name) {
newColumn = allColumns.splice(from, 1);
if (from > to && prev >= 0) to++;
allColumns.splice(to, 0, newColumn[0]);
break;
}
}
}
function setupColumnResize() {
var $col, j, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable, originalCanvasWidth;
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;
}
});
columnElements.each(function(i,e) {
if ((firstResizable !== undefined && i < firstResizable) || (options.forceFitColumns && i >= lastResizable)) { return; }
$col = $(e);
$("<div class='slick-resizable-handle' />")
.appendTo(e)
.bind("dragstart", function(e,dd) {
if (!options.editorLock.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;
// columns 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);
originalCanvasWidth = $canvas.width();
})
.bind("drag", function(e,dd) {
var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x, ci;
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;
styleColumnWidth(j, actualMinWidth, options.syncColumnCellResize);
} else {
styleColumnWidth(j, c.previousWidth + x, options.syncColumnCellResize);
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;
styleColumnWidth(j, c.maxWidth, options.syncColumnCellResize);
} else {
styleColumnWidth(j, c.previousWidth + x, options.syncColumnCellResize);
x = 0;
}
}
}
} else if (options.syncColumnCellResize) {
setCanvasWidth(originalCanvasWidth + d);
}
} 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;
styleColumnWidth(j, c.maxWidth, options.syncColumnCellResize);
} else {
styleColumnWidth(j, c.previousWidth + x, options.syncColumnCellResize);
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;
styleColumnWidth(j, actualMinWidth, options.syncColumnCellResize);
} else {
styleColumnWidth(j, c.previousWidth + x, options.syncColumnCellResize);
x = 0;
}
}
}
} else if (options.syncColumnCellResize) {
setCanvasWidth(originalCanvasWidth + d);
}
}
})
.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) {
removeAllRows();
}
if (options.forceFitColumns) {
c.width = Math.floor(c.width * (newWidth - c.previousWidth) / c.previousWidth) + c.width;
} else {
c.width = newWidth;
}
if (!options.syncColumnCellResize && c.previousWidth !== newWidth) {
styleColumnWidth(j, newWidth, true);
}
}
resizeCanvas();
if (self.onColumnsResized) {
self.onColumnsResized();
}
});
});
}
function setupDragEvents() {
var MOVE_ROWS = 1;
var SELECT_CELLS = 2;
function fixUpRange(range) {
var r1 = Math.min(range.start.row,range.end.row);
var c1 = Math.min(range.start.cell,range.end.cell);
var r2 = Math.max(range.start.row,range.end.row);
var c2 = Math.max(range.start.cell,range.end.cell);
return {
start: {row:r1, cell:c1},
end: {row:r2, cell:c2}
};
}
$canvas
.bind("draginit", function(e,dd) {
var $cell = $(e.target).closest(".slick-cell");
if ($cell.length === 0) { return false; }
if (parseInt($cell.parent().attr("row"), 10) >= gridDataGetLength())
return false;
var colDef = columns[getSiblingIndex($cell[0])];
if (colDef.behavior == "move" || colDef.behavior == "selectAndMove") {
dd.mode = MOVE_ROWS;
}
else if (options.enableCellRangeSelection) {
dd.mode = SELECT_CELLS;
}
else
return false;
})
.bind("dragstart", function(e,dd) {
if (!options.editorLock.commitCurrentEdit()) { return false; }
var row = parseInt($(e.target).closest(".slick-row").attr("row"), 10);
if (dd.mode == MOVE_ROWS) {
if (!selectedRowsLookup[row]) {
setSelectedRows([row]);
}
dd.selectionProxy = $("<div class='slick-reorder-proxy'/>")
.css("position", "absolute")
.css("zIndex", "99999")
.css("width", $(this).innerWidth())
.css("height", options.rowHeight*selectedRows.length)
.appendTo($viewport);
dd.guide = $("<div class='slick-reorder-guide'/>")
.css("position", "absolute")
.css("zIndex", "99998")
.css("width", $(this).innerWidth())
.css("top", -1000)
.appendTo($viewport);
dd.insertBefore = -1;
}
if (dd.mode == SELECT_CELLS) {
var start = getCellFromPoint(dd.startX - $canvas.offset().left, dd.startY - $canvas.offset().top);
if (!cellExists(start.row,start.cell))
return false;
dd.range = {start:start,end:{}};
return $("<div class='slick-selection'></div>").appendTo($canvas);
}
})
.bind("drag", function(e,dd) {
if (dd.mode == MOVE_ROWS) {
var top = e.pageY - $(this).offset().top;
dd.selectionProxy.css("top",top-5);
var insertBefore = Math.max(0,Math.min(Math.round(top/options.rowHeight),gridDataGetLength()));
if (insertBefore !== dd.insertBefore) {
if (self.onBeforeMoveRows && self.onBeforeMoveRows(getSelectedRows(),insertBefore) === false) {
dd.guide.css("top", -1000);
dd.canMove = false;
}
else {
dd.guide.css("top",insertBefore*options.rowHeight);
dd.canMove = true;
}
dd.insertBefore = insertBefore;
}
}
if (dd.mode == SELECT_CELLS) {
var end = getCellFromPoint(e.clientX - $canvas.offset().left, e.clientY - $canvas.offset().top);
if (!cellExists(end.row,end.cell))