forked from mleibman/SlickGrid
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathslick.grid.js
8774 lines (7811 loc) · 312 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-2013 Michael Leibman
* michael{dot}leibman{at}gmail{dot}com
* http://github.com/mleibman/slickgrid
*
* Distributed under MIT license.
* All rights reserved.
*
* SlickGrid v2.2
*
* 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.
*/
// 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");
}
if (typeof Slick === "undefined") {
throw new Error("slick.core.js not loaded");
}
(function ($) {
// Slick.Grid
$.extend(true, window, {
Slick: {
Grid: SlickGrid
}
});
// Helper function to aid Chrome/V8 optimizer: for...in loops prevent a function to become JIT compiled so we separate out this bit of code here:
function __extend_support(dst, src) {
for (var i in src) {
dst[i] = src[i];
}
}
// Helper function: a quick & dirty faster version of $.extend() for our purposes...
function __extend(dst, dotdotdot) {
var a = arguments;
var len = a.length;
for (var i = 1; i < len; i++) {
var src = arguments[i];
if (!src) continue;
__extend_support(dst, src);
}
return dst;
}
// shared across all grids on the page
var scrollbarDimensions;
var maxSupportedCssHeight; // browser's breaking point
var isBrowser; // browser info to be used for those very special browser quirks & ditto hacks where feature detection doesn't cut it
/* @const */ var MAX_INT = 2147483647;
/* @const */ var NAVIGATE_PREV = 1;
/* @const */ var NAVIGATE_NEXT = 2;
/* @const */ var NAVIGATE_LEFT = 3;
/* @const */ var NAVIGATE_RIGHT = 4;
/* @const */ var NAVIGATE_UP = 5;
/* @const */ var NAVIGATE_DOWN = 6;
/* @const */ var NAVIGATE_HOME = 7;
/* @const */ var NAVIGATE_END = 8;
/* @const */ var HEADER_ROW_WIDTH_CORRECTION = 2000;
//////////////////////////////////////////////////////////////////////////////////////////////
// SlickGrid class implementation (available as Slick.Grid)
/**
* Creates a new instance of the grid.
* @class SlickGrid
* @constructor
* @param {Node} container Container node to create the grid in.
* @param {Array,Object} data An array of objects for databinding.
* @param {Array} columns An array of column definitions.
* @param {Object} options Grid options.
*
* [KCPT] SlickGrid 2.1
* data: Array of data items or an object which implements the data-access functions
* {Array} of data items, each item has the following:
* id: {String} A unique ID for the item
* Other properties as indicated by the `field` entries of the columns array.
* For instance, if one of the columns specifies a field value of `name`,
* then each item of the data array should have a `name` property.
* {Object} implementing the data-access functions:
* getLength() Returns the number of data items (analogous to data.length)
* getItem(i) Returns the i-th data item (analogous to data[i])
* getItemMetadata(row, cell)
* Returns the metadata for the given row index.
* `cell` may be FALSE or an index number of the cell currently
* receiving attention -- this is handy when the metadata is
* generated on the fly and the grid is very large/complex,
* i.e. it is costly to cache all row/column metadata.
* Slick.DataView is an example of an Object which provides this API. It is essentially
* a wrapper around an {Array} of data items which provides additional data manipulation
* features, such as filtering and sorting.
*
* columns: Array of objects which specify details about the columns
* id: {String} A unique ID for the column
* name: {String} The name of the column, displayed in column header cell
* field: {String} The name of the data item property to be displayed in this column
* width: {Number} The width of the column in pixels
* minWidth: {Number} The minimum width of the column in pixels
* maxWidth: {Number} The maximum width of the column in pixels
* minHeight: {Number} The minimum height of the grid in pixels
* maxHeight: {Number} The maximum height of the grid in pixels
* cssClass: {String} The name of the CSS class to use for cells in this column
* formatter: {Function} formatter(rowIndex, colIndex, cellValue, colInfo, rowDataItem, cellMetaInfo) for grid cells
* headerFormatter: {Function} formatter(rowIndex, colIndex, cellValue, colInfo, rowDataItem, cellMetaInfo) for header cells
* headerRowFormatter: {Function} formatter(rowIndex, colIndex, cellValue, colInfo, rowDataItem, cellMetaInfo) for headerRow cells (option.showHeaderRow)
* editor: {Function} The constructor function for the class to use for editing of grid cells
* validator: {Function} A function to be called when validating user-entered values
* cannotTriggerInsert: {Boolean}
* resizable: {Boolean} Whether this column can be resized
* selectable: {Boolean} Whether this column can be selected
* sortable: {Boolean} Whether the grid rows can be sorted by this column
* children: {Array} An optional array of columns which are the children of this parent.
*
* options: Object with additional customization options
* explicitInitialization:
* {Boolean} Defers initialization until the client calls the
* grid.init() method explicitly. Supports situations in
* which SlickGrid containers may not be in the DOM at creation.
* rowHeight: {Number} Height of each row in pixels
* autoHeight: {Boolean} (?) Don't need vertical scroll bar
* defaultColumnWidth: {Number} Default column width for columns that don't specify a width
* enableColumnReorder: {Boolean} Can columns be reordered?
* enableAddRow: {Boolean} Can rows be added?
* showTopPanel: {Boolean} Should the top panel be shown?
* topPanelHeight: {Number} Height of the top panel in pixels
* headerHeight: {Number} Height of each column header row in pixels (*not the "extra header row"*)
* showHeaderRow: {Boolean} Should the extra header row be shown?
* headerRowHeight: {Number} Height of the extra header row in pixels
* showFooterRow: {Boolean} Should the extra footer row be shown?
* footerRowHeight: {Number} Height of the extra footer row in pixels
* enableCellNavigation: {Boolean} Should arrow keys navigate between cells?
* enableTextSelectionOnCells:
* {Boolean} Should text selection be allowed in cells? (This is MSIE specific; other browsers always assume `true`)
* forceFitColumns: {Boolean} Should column widths be automatically resized to fit?
* resizeOnlyDraggedColumn
* {Boolean} Only resize the column being resized, instead of resizing any preceding columns as well when the user drags far left
* dataItemColumnValueExtractor(item, columnDef, rowMetadata, columnMetadata):
* {Function} If present, will be called to retrieve a data value from the
* specified item for the corresponding column.
* Analogous to item[columnDef.field], where item is analogous to data[i].
* formatterFactory: {Object} If present, its getFormatter(columnInfo, row, cell, rowMetadata, columnMetadata) method will be called
* to retrieve a formatter for the specified cell
* selectedCellCssClass: {Object?} (?)Object used to specify CSS class for selected cells
* cellFlashingCssClass: {Object?} (?)Object used to specify CSS class for flashing cells
* enableAsyncPostRender: {Boolean}
* asyncPostRenderDelay: {Number} Delay passed to setTimeout in milliseconds before
* the PostRender queue is executed in slices of `asyncPostRenderSlice`
* each with a gap of `asyncPostRenderDelay`.
* asyncPostRenderSlice: {Number} Time slice available for each round of async rendering.
* Note that the probably-worst case is where the sync render process
* takes about twice this amount of time -- that is assuming
* each individual cell's async render action takes that amount
* of time or *less*.
* editable: {Boolean} Is editing table cells supported?
* autoEdit: {Boolean} (?)Should editing be initiated automatically on click in cell?
* editorFactory: {Object} If present, its getEditor(columnInfo, row, cell, rowMetadata, columnMetadata) method will be called
* to retrieve an editor for the specified cell,
* unless column.editor is specified, which will be used.
* editorLock: {Object} a Slick.EditorLock instance; the default NULL will make SlickGrid use the Slick.GlobalEditorLock singleton
* asyncEditorLoading: {Boolean} Should editors be loaded asynchronously?
* asyncEditorLoadDelay: {Number} Delay passed to setTimeout in milliseconds
* editCommandHandler: {Function} editCommandHandler(item, column, editCommand) is called from
* the commitCurrentEdit() function, where it can be used to
* implement undo/redo, for instance.
* fullWidthRows: {Boolean} If true, rows are sized to take up the available grid width.
* multiColumnSort: {Boolean} If true, rows can be sorted by multiple columns.
* defaultFormatter: {Function} Default function for converting cell values to strings.
* defaultEditor: {Function} Default function for editing cell values.
* defaultRowFormatter: {Function} Default function for formatting each grid row container.
* defaultHeaderFormatter:
* {Function} The Slick.Formatters compatible cell formatter used to render the header cell.
* defaultHeaderRowFormatter:
* {Function} The Slick.Formatters compatible cell formatter used to render the headerRow cell.
* The "headerRow" is the header row shown by SlickGrid when the `option.showHeaderRow` is enabled.
* scrollHoldoffX: {Number | Function}
* Specify the number of columns away from the edge where keyboard navigation
* should scroll the view; when specified as a single number, than all four edges
* (top/bottom/left/right) will "hold off" this amount; otherwise you may specify
* a function which should return the number of rows/cells to hold off, depending on
* the input arguments.
* scrollHoldoffY: {Number | Function}
* Specify the number of rows away from the edge where keyboard navigation
* should scroll the view; when specified as a single number, than all four edges
* (top/bottom/left/right) will "hold off" this amount; otherwise you may specify
* a function which should return the number of rows/cells to hold off, depending on
* the input arguments.
* smoothScrolling: {Boolean} When set, slickgrid will scroll the view 1 line/cell at a time, rather than an entire page.
* forceSyncScrolling: {Boolean} If true, renders more frequently during scrolling, rather than
* deferring rendering until default scroll thresholds are met (asyncRenderDelay).
* asyncRenderDelay: {Number} Delay passed to setTimeout in milliseconds before view update is actually rendered.
* addNewRowCssClass: {String} specifies CSS class for the extra bottom row: "add new row"
* [/KCPT]
**/
function SlickGrid(container, data, columnDefinitions, options) {
// settings
var defaults = {
explicitInitialization: false,
rowHeight: 25,
defaultColumnWidth: 80,
enableAddRow: false,
editable: false,
autoEdit: true,
enableCellNavigation: true,
enableColumnReorder: true,
asyncEditorLoading: false,
asyncEditorLoadDelay: 100,
forceFitColumns: false,
resizeOnlyDraggedColumn: false,
enableAsyncPostRender: false,
asyncPostRenderDelay: 50,
asyncPostRenderSlice: 50,
autoHeight: false,
editorLock: Slick.GlobalEditorLock,
headerHeight: 25,
showHeaderRow: false,
headerRowHeight: 25,
showFooterRow: false,
footerRowHeight: 25,
showTopPanel: false,
topPanelHeight: 25,
formatterFactory: null,
editorFactory: null,
formatterOptions: {},
editorOptions: {},
cellFlashingCssClass: "flashing",
selectedCellCssClass: "selected",
multiSelect: true,
enableTextSelectionOnCells: true,
dataItemColumnValueExtractor: null,
dataItemColumnValueSetter: null,
fullWidthRows: false,
multiColumnSort: false,
defaultFormatter: defaultFormatter,
defaultEditor: null,
defaultRowFormatter: defaultRowFormatter,
defaultHeaderFormatter: defaultHeaderFormatter,
defaultHeaderRowFormatter: defaultHeaderRowFormatter,
minBufferSize: 3,
maxBufferSize: 50,
scrollHoldoffX: 2,
scrollHoldoffY: 3,
smoothScrolling: true,
forceSyncScrolling: false,
asyncRenderDelay: 45, // this value is picked to 'catch' typematic key repeat rates as low as 12-per-second:
// keep your navigator keys depressed to see the delayed render + mandatory mini-cell-renders kicking in.
asyncRenderSlice: 50,
asyncRenderInterleave: 20,
addNewRowCssClass: "new-row",
editCommandHandler: null,
clearCellBeforeEdit: true,
createCssRulesCallback: null
};
var columnDefaults = {
name: "",
resizable: true,
sortable: false,
minWidth: 30,
rerenderOnResize: false,
headerCssClass: null,
defaultSortAsc: true,
focusable: true,
selectable: true,
reorderable: true,
dataItemColumnValueExtractor: null
// childrenFirstIndex: <N> set to the first flattened column index covered by this column when this column is a parent (forming an inclusive range)
// childrenLastIndex: <N> set to the last flattened column index covered by this column when this column is a parent (forming an inclusive range)
};
// scroller
var virtualTotalHeight; // virtual height
var scrollableHeight; // real scrollable height
var pageHeight; // page height
var numberOfPages; // number of pages
var jumpinessCoefficient; // "jumpiness" coefficient
var page = 0; // current page
var pageOffset = 0; // current page offset
var vScrollDir = 1;
// private
var initialized = 0; // 0/1/2: 2 = fully initialized
var $container;
var uid = "slickgrid_" + Math.round(1000000 * Math.random());
var self = this;
var $focusSink, $focusSink2;
var $headerScroller;
var $headers;
var $headerRow, $headerRowScroller;
var $footerRow, $footerRowScroller;
var $topPanelScroller;
var $topPanel;
var $viewport;
var $canvas;
var $style;
var $boundAncestors;
var stylesheet, columnCssRulesL, columnCssRulesR, columnCssRulesHL, columnCssRulesHR;
var viewportH, viewportW;
var canvasWidth, totalColumnsWidth;
var viewportHasHScroll, viewportHasVScroll;
var headerColumnWidthDiff = 0, headerColumnHeightDiff = 0, // border+padding
cellWidthDiff = 0, cellHeightDiff = 0;
var absoluteColumnMinWidth;
var tabbingDirection = 1;
var activePosY;
var activePosX;
var activeRow, activeCell;
var activeCellNode = null;
var currentEditor = null;
var serializedEditorValue;
var editController = null;
// It turned out that focusin / focusout events fired by jQuery also occur when we call
// $el.focus() on any element inside slickgrid. To prevent very weird event sequences
// from thus occurring we *block* these events from firing any SlickGrid event (onFocusIn/onFocusOut)
// or any other slickgrid-internal activity while we are fully in control of the situation
// already while we are calling jQuery's $el.focus() on a cell of ours (movingFocusLock > 0)
var movingFocusLock = 0;
var movingFocusLockData = [];
// To prevent mouseenter/leave events from misfiring while a header/column drag is commencing
// we introduce yet another lock:
var headerDragCommencingLock = null;
// Monitor focus; when it is in a cell (or a child thereof) and that cell is destroyed due to cache invalidation,
// then switch focus over to the focusSink so that keyboard events do not get lost during the interim
// while the cells are rerendered.
var focusMustBeReacquired = false;
var cssRulesHashtable = {};
var cssRulesCount = 0;
var rowsCache = [];
// var deletedRowsCache = [];
var rowPositionCache = [];
var rowsCacheStartIndex = MAX_INT;
// var deletedRowsCacheStartIndex = MAX_INT;
var cellSpans = [];
var renderedRows = 0;
// var previousRenderWasIncomplete = false;
var prevScrollTop = 0;
var scrollTop = 0;
var lastRenderedScrollTop = 0;
var lastRenderedScrollLeft = 0;
var prevScrollLeft = 0;
var scrollLeft = 0;
var selectionModel;
var selectedRows = [];
var plugins = [];
var cellCssClasses = {};
var columnsById = {};
var columns = null;
var columnsDefTree = null;
var sortColumns = [];
var columnPosLeft = []; // this cache array length is +1 longer than columns[] itself as we store the 'right edge + 1 pixel' as the 'left edge' of the first column beyond the grid width just as it would have been anyway. This simplifies the rest of the code.
//var columnPosRight = [];
// async call handles
var h_retry_init = null;
var h_editorLoader = null;
var h_render = null;
var h_postrender = null;
var postprocess_perftimer = null;
var render_perftimer = null;
var postProcessedRows = [];
var postProcessToRow = 0;
var postProcessFromRow = MAX_INT;
// perf counters
var counter_rows_rendered = 0;
var counter_rows_removed = 0;
var hasNestedColumns = false;
var nestedColumns = null; // 2D array: [depth][h_index] -> column reference
// These two variables work around a bug with inertial scrolling in Webkit/Blink on Mac.
// See http://crbug.com/312427.
var rowNodeFromLastMouseWheelEvent; // this node must not be deleted while inertial scrolling
var zombieRowNodeFromLastMouseWheelEvent; // node that was hidden instead of getting deleted
//////////////////////////////////////////////////////////////////////////////////////////////
// Constants: lookup tables
/* @const */ var tabbingDirections = LU(
NAVIGATE_UP, -1,
NAVIGATE_DOWN, 1,
NAVIGATE_LEFT, -1,
NAVIGATE_RIGHT, 1,
NAVIGATE_PREV, -1,
NAVIGATE_NEXT, 1,
NAVIGATE_HOME, -1,
NAVIGATE_END, 1
);
/* @const */ var stepFunctions = LU(
NAVIGATE_UP, gotoUp,
NAVIGATE_DOWN, gotoDown,
NAVIGATE_LEFT, gotoLeft,
NAVIGATE_RIGHT, gotoRight,
NAVIGATE_PREV, gotoPrev,
NAVIGATE_NEXT, gotoNext,
NAVIGATE_HOME, gotoHome,
NAVIGATE_END, gotoEnd
);
// Internal use: generate a lookup table for a key,value set.
function LU(/* ... */) {
var lu = [];
for (var a = arguments, i = 0, l = a.length; i < l; i += 2) {
lu[a[i]] = a[i + 1];
}
return lu;
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Initialization
function init() {
$container = $(container);
if ($container.length < 1) {
throw new Error("SlickGrid requires a valid container, " + container + " does not exist in the DOM.");
}
if (columns) {
throw new Error("SlickGrid setColumns or updateColumnWidths have been called before the instance has been properly initialized.");
}
if (!columnDefinitions || !columnDefinitions.length) {
columnDefinitions = [{}];
}
if (typeof get_browser_info === "undefined") {
throw new Error("SlickGrid requires detect_browser.js to be loaded.");
}
if (!isBrowser) {
isBrowser = get_browser_info();
isBrowser.safari = /safari/i.test(isBrowser.browser);
isBrowser.safari605 = isBrowser.safari && /6\.0/.test(isBrowser.version);
isBrowser.msie = /msie/i.test(isBrowser.browser);
}
// calculate these only once and share between grid instances
maxSupportedCssHeight = maxSupportedCssHeight || getMaxSupportedCssHeight();
scrollbarDimensions = scrollbarDimensions || measureScrollbar();
options = __extend({}, defaults, options);
validateAndEnforceOptions();
assert(options.defaultColumnWidth > 0);
columnDefaults.width = options.defaultColumnWidth;
parseColumns(columnDefinitions);
assert(columns);
updateColumnCaches();
// 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()
.addClass("slickgrid-container ui-widget " + uid)
.attr("role", "grid")
.attr("tabIndex", 0)
.attr("hideFocus", "true");
// set up a positioning container if needed
if (!/relative|absolute|fixed/.test($container.css("position"))) {
$container.css("position", "relative");
}
$focusSink = $("<div tabIndex='0' hideFocus='true' style='position:absolute;width:0;height:0;top:0;left:0;outline:0;'></div>").appendTo($container);
$headerScroller = $("<div class='slick-header ui-state-default' />").appendTo($container);
$headers = $("<div class='slick-header-columns' role='header-row' />").appendTo($headerScroller);
$headerRowScroller = $("<div class='slick-headerrow ui-state-default' />").appendTo($container);
$headerRow = $("<div class='slick-headerrow-columns' />").appendTo($headerRowScroller);
$topPanelScroller = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($container);
$topPanel = $("<div class='slick-top-panel' />").appendTo($topPanelScroller);
if (!options.showTopPanel) {
$topPanelScroller.hide();
}
if (!options.showHeaderRow) {
$headerRowScroller.hide();
}
$viewport = $("<div class='slick-viewport' >").appendTo($container);
//$viewport.css("overflow-y", (options.autoHeight && !clippedAutoSize) ? "auto" : "auto");
$canvas = $("<div class='grid-canvas' />").appendTo($viewport);
$footerRowScroller = $("<div class='slick-footerrow' />").appendTo($container);
$footerRow = $("<div class='slick-footerrow-columns' />").appendTo($footerRowScroller);
if (!options.showFooterRow) {
$footerRowScroller.hide();
}
assert(!initialized);
setViewportWidth();
var rv = updateCanvasWidth(); // note that this call MUST NOT fire the onCanvasChanged event!
$focusSink2 = $focusSink.clone().appendTo($container);
if (!options.explicitInitialization) {
rv &= finishInitializationUntilDone();
}
return rv;
}
// Stubbornly keep at it until the init is really completely done.
function finishInitializationUntilDone() {
clearTimeout(h_retry_init);
h_retry_init = null;
// Only execute the initialization when it hasn't run to completion yet:
if (initialized < 3) {
if (!finishInitialization()) {
// When the initialization didn't complete entirely, we have to poll the browser to
// get to a state where we get the initialization done -- the culprit is almost always
// a delay in the stylesheet node becoming available.
assert(initialized < 3);
assert(!stylesheet);
h_retry_init = setTimeout(finishInitializationUntilDone, 100);
return false;
}
}
return true;
}
function finishInitialization() {
if (initialized < 2) {
initialized = 1;
setViewportWidth();
// 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");
});
}
calcCanvasWidth();
updateColumnCaches();
createColumnHeaders();
setupColumnSort();
createCssRules();
cacheRowPositions();
resizeCanvas();
bindAncestorScrollEvents();
$container
.bind("resize.slickgrid", function (e) {
resizeCanvas();
})
.bind("focus.slickgrid", function (e) {
var $target = $(e.target);
var newFocusNode = document.activeElement;
var focusMovingFrom = $.contains($container[0], e.target);
var focusMovingInto = $.contains($container[0], newFocusNode);
var focusMovingInside = focusMovingFrom && focusMovingInto;
// console.log("container EVT FOCUS: ", [this, arguments, $target, newFocusNode],
// focusMovingFrom ? "FROM" : "-", focusMovingInto ? "INTO" : "-", focusMovingInside ? "INSIDE" : "-", movingFocusLock ? "@FOCUS" : "-real-");
})
.bind("blur.slickgrid", function (e) {
var $target = $(e.target);
var newFocusNode = document.activeElement;
var focusMovingFrom = $.contains($container[0], e.target);
var focusMovingInto = $.contains($container[0], newFocusNode);
var focusMovingInside = focusMovingFrom && focusMovingInto;
// console.log("container EVT BLUR: ", [this, arguments, $target, newFocusNode],
// focusMovingFrom ? "FROM" : "-", focusMovingInto ? "INTO" : "-", focusMovingInside ? "INSIDE" : "-", movingFocusLock ? "@FOCUS" : "-real-");
})
.bind("focusin.slickgrid", function (e) {
var fromNode = e.target;
if (movingFocusLock) {
// we MAY see a sequence of focusout+focusin, where in the latter we want to know who really was the previous focus
fromNode = movingFocusLockData[movingFocusLock - 1].oldNode;
}
var $target = $(fromNode);
var newFocusNode = document.activeElement;
var focusMovingFrom = $.contains($container[0], fromNode);
var focusMovingInto = $.contains($container[0], newFocusNode);
var focusMovingInside = focusMovingFrom && focusMovingInto;
// console.log("container GOT FOCUS: ", [this, arguments, e.target, fromNode, newFocusNode],
// focusMovingFrom ? "FROM" : "-", focusMovingInto ? "INTO" : "-", focusMovingInside ? "INSIDE" : "-", movingFocusLock ? "@FOCUS" : "-real-", movingFocusLockData);
var handled;
var evt = new Slick.EventData(e);
if (movingFocusLock) {
trigger(self.onFocusMoved, {
from: movingFocusLockData[movingFocusLock - 1].oldNodeInfo,
to: getCellFromElement(newFocusNode),
fromNode: movingFocusLockData[movingFocusLock - 1].oldNode,
toNode: newFocusNode
}, evt);
handled = evt.isHandled();
if (handled) {
return;
}
} else {
trigger(self.onFocusIn, {}, evt);
handled = evt.isHandled();
if (handled) {
return;
}
// var lock = getEditorLock();
// if (!lock.isActive(editController) && lock.commitCurrentEdit()) {
// lock.activate(editController);
// }
// // else: jump back to previously focused element... but we don't know what it is so this is all we can do now...
}
})
.bind("focusout.slickgrid", function (e) {
var $target = $(e.target);
var newFocusNode = document.activeElement;
var focusMovingFrom = $.contains($container[0], e.target);
var focusMovingInto = $.contains($container[0], newFocusNode);
var focusMovingInside = focusMovingFrom && focusMovingInto;
// console.log("container LOST FOCUS = autoCOMMIT: ", [this, arguments, e.target, newFocusNode],
// focusMovingFrom ? "FROM" : "-", focusMovingInto ? "INTO" : "-", focusMovingInside ? "INSIDE" : "-", movingFocusLock ? "@FOCUS" : "-real-", {
// event: e,
// newNode: newFocusNode,
// oldNode: e.target,
// oldNodeInfo: getCellFromElement(e.target)
// });
if (movingFocusLock) {
// we MAY see a sequence of focusout+focusin, where by the time focusin fires, document.activeElement is BODY.
// movingFocusLockData[movingFocusLock - 1] = {
// event: e,
// newNode: newFocusNode,
// oldNode: e.target,
// oldNodeInfo: getCellFromElement(e.target)
// };
return;
}
var evt = new Slick.EventData(e);
trigger(self.onFocusOut, {}, evt);
var handled = evt.isHandled();
if (handled) {
return;
}
// var lock = getEditorLock();
// if (lock.isActive(editController) && !lock.commitCurrentEdit()) {
// // commit failed, jump back to edited field so user can edit it and make sure it passes the next time through
// assert(currentEditor);
// currentEditor.focus();
// assert(document.activeElement !== document.body);
// }
})
.fixClick(handleContainerClickEvent, handleContainerDblClickEvent)
.bind("contextmenu.slickgrid", handleContainerContextMenu)
.bind("keydown.slickgrid", handleContainerKeyDown);
$viewport
.bind("scroll", handleScrollEvent);
$headerScroller
.bind("contextmenu", handleHeaderContextMenu)
.fixClick(handleHeaderClick, handleHeaderDblClick)
.delegate(".slick-header-column", "mouseenter", handleHeaderMouseEnter)
.delegate(".slick-header-column", "mouseleave", handleHeaderMouseLeave)
.bind("draginit", handleHeaderDragInit)
.bind("dragstart", {distance: 3}, handleHeaderDragStart)
.bind("drag", handleHeaderDrag)
.bind("dragend", handleHeaderDragEnd);
$headerRowScroller
.bind("scroll", handleHeaderRowScroll);
$footerRowScroller
.bind("scroll", handleFooterRowScroll);
$focusSink.add($focusSink2)
.bind("keydown", handleKeyDown);
$canvas
.bind("keydown", handleKeyDown)
.fixClick(handleClick, 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);
}
initialized = 2;
} else if (!stylesheet && initialized > 1) {
// when a previous `init` run did not yet use the run-time stylesheet data,
// we have to adjust the canvas while waiting for the browser to actually
// parse that style.
resizeCanvas();
}
// Only fire the onAfterInit event when we really have done it all:
if (stylesheet && initialized === 2) {
initialized = 3;
trigger(self.onAfterInit, {});
}
// report the user whether we are a complete success (truthy) or not (falsey):
return !!stylesheet;
}
function isInitialized() {
return initialized;
}
function registerPlugin(plugin) {
plugins.unshift(plugin);
plugin.init(self);
}
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 setSelectionModel(model) {
if (selectionModel) {
selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged);
if (selectionModel.destroy) {
selectionModel.destroy();
}
}
selectionModel = model;
if (selectionModel) {
selectionModel.init(self);
selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged);
}
}
function getSelectionModel() {
return selectionModel;
}
function getCanvasNode() {
return $canvas[0];
}
function measureScrollbar() {
var $c = $("<div style='position:absolute; top:-10000px; left:-10000px; width:100px; height:100px; overflow:scroll;'></div>").appendTo("body");
var dim = {
width: $c.outerWidth() - $c[0].clientWidth,
height: $c.outerHeight() - $c[0].clientHeight
};
$c.remove();
return dim;
}
// Return the pixel positions of the left and right edge of the column, relative to the left edge of the entire grid.
function getColumnOffset(cell) {
var l = columns.length;
// Is the cache ready? If not, update it.
if (columnPosLeft.length <= l) {
updateColumnCaches();
assert(columnPosLeft.length === l + 1);
}
assert(cell >= 0);
assert(cell < columnPosLeft.length);
return columnPosLeft[cell];
}
function calcCanvasWidth() {
var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
totalColumnsWidth = getColumnOffset(columns.length);
canvasWidth = (options.fullWidthRows ? Math.max(totalColumnsWidth, availableWidth) : totalColumnsWidth);
// see https://github.com/mleibman/SlickGrid/issues/477
viewportHasHScroll = (canvasWidth >= viewportW - scrollbarDimensions.width);
}
var oldViewportW, oldCanvasWidth, oldTotalColumnsWidth;
function updateCanvasWidth() {
calcCanvasWidth();
var cached = false;
if (canvasWidth !== oldCanvasWidth) {
$canvas.outerWidth(canvasWidth);
cached = true;
}
if (oldTotalColumnsWidth !== totalColumnsWidth) {
$topPanel.outerWidth(totalColumnsWidth + HEADER_ROW_WIDTH_CORRECTION);
$headerRow.outerWidth(totalColumnsWidth + HEADER_ROW_WIDTH_CORRECTION);
$footerRow.outerWidth(totalColumnsWidth + HEADER_ROW_WIDTH_CORRECTION);
$headers.outerWidth(totalColumnsWidth + HEADER_ROW_WIDTH_CORRECTION);
cached = true;
}
if (oldViewportW !== viewportW) {
$topPanelScroller.outerWidth(viewportW);
$headerRowScroller.outerWidth(viewportW);
$footerRowScroller.outerWidth(viewportW);
$headerScroller.outerWidth(viewportW);
cached = true;
}
// When `stylesheet` has not been set yet, it means that any previous call to
// applyColumnWidths() did not use up to date values yet as the run-time generated
// stylesheet wasn't parsed in time.
if (canvasWidth !== oldCanvasWidth || !stylesheet || !initialized) {
if (!applyColumnWidths()) {
return false;
}
}
// Only fire the event when there's actual change *and* we're past the initialization phase.
if (cached && initialized) {
trigger(self.onCanvasWidthChanged, {
width: canvasWidth,
oldWidth: oldCanvasWidth || 0,
oldTotalColumnsWidth: oldTotalColumnsWidth || 0,
totalColumnsWidth: totalColumnsWidth,
oldViewportW: oldViewportW || 0,
viewportW: viewportW
});
}
// only update the 'previous/old' markers when we can be sure that the new values are actually sound:
if (stylesheet && initialized) {
oldViewportW = viewportW;
oldCanvasWidth = canvasWidth;
oldTotalColumnsWidth = totalColumnsWidth;
// and (re)render the affected columns
render();
return true;
}
return false;
}
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 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 = $("<div style='display:none' />").appendTo(document.body);
while (true) {
var test = supportedHeight * 2;
div.css("height", test);
if (test > testUpTo || div.outerHeight() !== test) {
break;
} else {
supportedHeight = test;
}
}
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 unbindAncestorScrollEvents() {
if (!$boundAncestors) {
return;
}
$boundAncestors.unbind("scroll." + uid);
$boundAncestors = null;
}
// tile may be NULL: this is similar to specifying an empty title.
// ditto for toolTip.
function updateColumnHeader(columnId, title, toolTip) {
if (!initialized) { return false; }
var idx = getColumnIndex(columnId);
if (idx == null) {
return false;
}
var columnDef = columns[idx];
var headerNode = getHeadersColumn(columnDef.id);
if (headerNode) {
if (title !== undefined) {
columnDef.name = title;
}
if (toolTip !== undefined) {
columnDef.toolTip = toolTip;
}
var e = new Slick.EventData();
trigger(self.onBeforeHeaderCellDestroy, {
node: headerNode,
column: columnDef,
cell: idx
}, e);
if (e.isHandled()) {
return false;
}
// The userland event handler(s) may have patched this column's name and/or tooltip, so
// fetch it now instead of before.
title = columnDef.name;
toolTip = columnDef.toolTip || null;
var $header = $(headerNode);
// TODO: RISK: when formatter produces more than *ONE* HTML element, we're toast with nuking the .eq(0) element down here:
$header
.attr("title", toolTip)
.attr("data-title", toolTip)
.children().eq(0).html(title || "");
trigger(self.onHeaderCellRendered, {
node: headerNode,
column: columnDef,
cell: idx
});
return true;
}
return false;
}
function getHeaderRow() {
return $headerRow[0];
}