forked from Knockout-Contrib/KoGrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KoGrid-1.2.4.debug.js
3314 lines (2762 loc) · 118 KB
/
KoGrid-1.2.4.debug.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
/***********************************************
* koGrid JavaScript Library
* Authors: https://github.com/ericmbarnard/KoGrid/blob/master/README.md
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
* Compiled At: 11/02/2012 16:53:22
***********************************************/
/***********************************************
* FILE: ..\Src\Namespace.js
***********************************************/
var kg = window['kg'] = {};
kg.templates = {};
/***********************************************
* FILE: ..\Src\Constants.js
***********************************************/
var SELECTED_PROP = '__kg_selected__';
var GRID_TEMPLATE = 'koGridTmpl';
/***********************************************
* FILE: ..\src\Navigation.js
***********************************************/
//set event binding on the grid so we can select using the up/down keys
kg.moveSelectionHandler = function (grid, evt) {
// null checks
if (grid === null || grid === undefined)
return true;
if (grid.config.selectedItems() === undefined)
return true;
var offset,
charCode = (evt.which) ? evt.which : event.keyCode,
ROW_KEY = '__kg_rowIndex__'; // constant for the entity's row's rowIndex
// detect which direction for arrow keys to navigate the grid
switch (charCode) {
case 38:
// up - select previous
offset = -1;
break;
case 40:
// down - select next
offset = 1;
break;
default:
return true;
}
var items = grid.finalData(),
n = items.length,
index = ko.utils.arrayIndexOf(items, grid.config.lastClickedRow().entity()) + offset,
rowCache = grid.rowManager.rowCache,
rowHeight = grid.config.rowHeight,
currScroll = grid.$viewport.scrollTop(),
row = null,
selected = null,
itemToView = null;
// now find the item we arrowed to, and select it
if (index >= 0 && index < n) {
selected = items[index];
row = rowCache[selected[ROW_KEY]];
// fire the selection
row.toggleSelected(null, evt);
itemtoView = kg.utils.getElementsByClassName("kgSelected");
// finally scroll it into view as we arrow through
if (!Element.prototype.scrollIntoViewIfNeeded) {
itemtoView[0].scrollIntoView(false);
grid.$viewport.focus();
} else {
itemtoView[0].scrollIntoViewIfNeeded();
}
//grid.$viewport.scrollTop(currScroll + (offset * rowHeight));
return false;
}
};
/***********************************************
* FILE: ..\Src\Labels.js
***********************************************/
kg.labels = {
};
/***********************************************
* FILE: ..\Src\Utils.js
***********************************************/
kg.utils = {
visualLength: function (string) {
var elem = document.getElementById('testDataLength');
if (!elem) {
elem = document.createElement('SPAN');
elem.id = "testDataLength";
elem.style.visibility = "hidden";
document.body.appendChild(elem);
}
elem.innerHTML = string;
return elem.offsetWidth;
},
forEach: function (arr, action) {
var len = arr.length,
i = 0;
for (; i < len; i++) {
if (arr[i] !== undefined) {
action(arr[i], i);
}
}
},
forIn: function (obj, action) {
var prop;
for (prop in obj) {
if(obj.hasOwnProperty(prop)){
action(obj[prop], prop);
}
}
},
endsWith: function (str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
},
StringBuilder: function () {
var strArr = [];
this.append = function (str, data) {
var len = arguments.length,
intMatch = 0,
strMatch = '{0}',
i = 1;
if (len > 1) { // they provided data
while (i < len) {
//apparently string.replace only works on one match at a time
//so, loop through the string and hit all matches
while (str.indexOf(strMatch) !== -1) {
str = str.replace(strMatch, arguments[i]);
}
i++;
intMatch = i - 1;
strMatch = "{" + intMatch.toString() + "}";
}
}
strArr.push(str);
};
this.toString = function () {
var separator = arguments[0];
if (separator !== null && separator !== undefined) {
return strArr.join(separator);
} else {
return strArr.join("");
}
};
},
getElementsByClassName: function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = document.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) retnode.push(elem[i]);
}
return retnode;
},
unwrapPropertyPath: function(path, entity){
var propPath = path.split('.');
var tempProp = entity[propPath[0]];
for (var j = 1; j < propPath.length; j++){
tempProp = ko.utils.unwrapObservable(tempProp)[propPath[j]];
}
return tempProp;
},
newId: (function () {
var seedId = new Date().getTime();
return function () {
return seedId += 1;
};
})(),
// we copy KO's ie detection here bc it isn't exported in the min versions of KO
// Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
ieVersion: (function () {
var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
// Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
while (
div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
iElems[0]
);
return version > 4 ? version : undefined;
})(),
makeTemplate: function (templId, templText) {
var template = document.createElement('script');
$(template).attr('type', 'text/html');
$(template).attr('id', templId);
$(template).html(templText);
return template;
}
};
$.extend(kg.utils, {
isIe6: (function(){
return kg.utils.ieVersion === 6}
)(),
isIe7: (function(){
return kg.utils.ieVersion === 7}
)(),
isIe: (function () {
return kg.utils.ieVersion !== undefined;
})()
});
/***********************************************
* FILE: ..\Src\Templates\GridTemplate.js
***********************************************/
kg.templates.defaultGridInnerTemplate = function (options) {
var b = new kg.utils.StringBuilder();
b.append('<div class="kgTopPanel" data-bind="kgSize: $data.headerDim">');
b.append( '<div class="kgHeaderContainer" data-bind="kgSize: $data.headerDim">');
b.append( '<div class="kgHeaderScroller" data-bind="kgHeaderRow: $data, kgSize: $data.headerScrollerDim">');
b.append( '</div>');
b.append( '</div>');
b.append('</div>');
b.append('<div class="kgViewport {0}" data-bind="kgSize: $data.viewportDim">', options.disableTextSelection ? "kgNoSelect": "");
b.append( '<div class="kgCanvas" data-bind="kgRows: $data.rows, style: { height: $data.canvasHeight, width: $data.totalRowWidth }" style="position: relative">');
b.append( '</div>');
b.append('</div>');
b.append('<div class="kgFooterPanel" data-bind="kgFooter: $data, kgSize: $data.footerDim">');
b.append('</div>');
return b.toString();
};
/***********************************************
* FILE: ..\Src\Templates\HeaderTemplate.js
***********************************************/
kg.templates.generateHeaderTemplate = function (options) {
var b = new kg.utils.StringBuilder(),
cols = options.columns;
var hasHeaderGroups = false;
var headerGroups = { };
var leftMargin = 0;
var prevHeaderGroup;
kg.utils.forEach(cols, function (col, i) {
if (col.headerGroup) {
if (!headerGroups[col.headerGroup]) {
var newGroup = {
width: ko.computed(function () {
var hgs = options.headerGroups();
if (!hgs || !hgs[col.headerGroup]) return 0;
var arr = hgs[col.headerGroup].columns;
var width = 0;
kg.utils.forEach(arr, function (column) {
width += column.width();
});
return width - 1;
}),
columns: [],
margin: ko.observable(leftMargin),
rightHeaderGroup: "",
parent: headerGroups
};
headerGroups[col.headerGroup] = newGroup;
if (prevHeaderGroup) headerGroups[prevHeaderGroup].rightHeaderGroup = col.headerGroup;
prevHeaderGroup = col.headerGroup;
hasHeaderGroups = true;
}
headerGroups[col.headerGroup].columns.push(col);
} else {
if (prevHeaderGroup) headerGroups[prevHeaderGroup].rightHeaderGroup = col.headerGroup;
if ((options.displayRowIndex && options.displaySelectionCheckbox && i > 1) ||
(options.displayRowIndex && !options.displaySelectionCheckbox && i > 0) ||
(options.displaySelectionCheckbox && !options.displayRowIndex && i > 0)) {
if (!headerGroups[i]) {
headerGroups[i] = {
width: ko.computed(function () {
var hgs = options.headerGroups();
if (!hgs || !hgs[col.headerGroup]) return 0;
var arr = hgs[col.headerGroup].columns;
var width = 0;
kg.utils.forEach(arr, function (column) {
width += column.width();
});
return width - 1;
}),
columns: [],
margin: ko.observable(leftMargin),
rightHeaderGroup: "",
parent: headerGroups
};
}
if (!prevHeaderGroup) prevHeaderGroup = i;
}
}
leftMargin += col.width();
});
if (hasHeaderGroups) {
options.headerGroups(headerGroups);
b.append('<div style="position: absolute; line-height: 30px; height: 30px; top: 0px; left:0px; right: 17px; ">');
kg.utils.forIn(headerGroups, function (group) {
if (group.columns.length > 0) {
b.append('<div class="kgHeaderGroupContainer" data-bind="style: { width: $parent.headerGroups()[\'{0}\'].width() + \'px\', left: $parent.headerGroups()[\'{0}\'].margin() + \'px\' }" style="position: absolute; text-align: center;">{0}</div>',group.columns[0].headerGroup ? group.columns[0].headerGroup : "");
}
});
b.append('</div>');
b.append('<div style="position: absolute; line-height: 30px; height 30px; top: 31px; ">');
}
kg.utils.forEach(cols, function (col) {
if (col.field === '__kg_selected__') {
b.append('<div class="kgSelectionCell" data-bind="kgHeader: { value: \'{0}\' }, style: { width: $parent.columns()[{2}].width() + \'px\'}, css: { \'kgNoSort\': {1} }">', col.field, !col.allowSort, col.index);
b.append(' <input type="checkbox" data-bind="visible: $parent.isMultiSelect, checked: $parent.toggleSelectAll"/>');
b.append('</div>');
} else if (col.field === 'rowIndex' && options.showFilter) {
b.append('<div data-bind="kgHeader: { value: \'{0}\' }, css: { \'kgNoSort\': {1} }, style: { width: $parent.columns()[{2}].width() + \'px\'},">', col.field, !col.allowSort, col.index);
b.append('<div title="Toggle Filter" class="kgFilterBtn" data-bind="css:{\'closeBtn\' : $data.filterVisible() == true, \'openBtn\' : $data.filterVisible() == false }, click: $parent.showFilter_Click"></div>');
b.append('<div title="Clear Filters" class="kgFilterBtn clearBtn" data-bind="visible: $data.filterVisible, click: $parent.clearFilter_Click"></div>');
b.append('</div>');
} else {
b.append('<div style="height: 30px; border-right: {3}; " data-bind="kgHeader: { value: \'{0}\' }, style: { width: $parent.columns()[{1}].width() + \'px\'}, css: { \'kgNoSort\': {2} }">', col.field, col.index, !col.allowSort, col.index === (cols.length - 1) ? '1px solid black': '0');
b.append('</div>');
}
});
if (hasHeaderGroups) {
b.append('</div>');
}
return b.toString();
};
/***********************************************
* FILE: ..\Src\Templates\HeaderCellTemplate.js
***********************************************/
kg.templates.defaultHeaderCellTemplate = function (options) {
var b = new kg.utils.StringBuilder();
b.append('<div data-bind="click: $data.sort, css: { \'kgSorted\': !$data.noSortVisible() }" class="kgHeaderCellGroup">');
b.append(' <span data-bind="text: $data.displayName" class="kgHeaderText"></span>');
b.append(' <div class="kgSortButtonDown" data-bind="visible: $data.allowSort() ? $data.sortAscVisible() : $data.allowSort()"></div>');
b.append(' <div class="kgSortButtonUp" data-bind="visible: $data.allowSort() ? $data.sortDescVisible() : $data.allowSort()"></div>');
b.append('</div>');
if (!options.autogenerateColumns && options.enableColumnResize){
b.append('<div class="kgHeaderGrip" data-bind="visible: $data.allowResize, click: $data.gripClick ,mouseEvents: { mouseDown: $data.gripOnMouseDown }"></div>');
}
b.append('<div data-bind="visible: $data._filterVisible">');
b.append(' <input type="text" data-bind="value: $data.column.filter, valueUpdate: \'afterkeydown\'" style="width: 80%" tabindex="1" />');
b.append('</div>');
return b.toString();
};
/***********************************************
* FILE: ..\Src\Templates\RowTemplate.js
***********************************************/
kg.templates.generateRowTemplate = function (options) {
var b = new kg.utils.StringBuilder(),
cols = options.columns;
b.append('<div data-bind="kgRow: $data, click: $data.toggleSelected, css: { \'kgSelected\': $data.selected }">');
kg.utils.forEach(cols, function (col, i) {
// check for the Selection Column
if (col.field === '__kg_selected__') {
b.append('<div class="kgSelectionCell" data-bind="kgCell: { value: \'{0}\' } ">', col.field);
b.append(' <input type="checkbox" data-bind="checked: $data.selected" />');
b.append('</div>');
}
// check for RowIndex Column
else if (col.field === 'rowIndex') {
b.append('<div class="kgRowIndexCell" data-bind="kgCell: { value: \'{0}\' } "></div>', col.field);
}
// check for a Column with a Cell Template
else if (col.hasCellTemplate) {
// first pull the template
var tmpl = kg.templateManager.getTemplate(col.cellTemplate).innerHTML;
// build the replacement text
var replacer = "{ value: '" + col.field + "' }";
// run any changes on the template for re-usable templates
tmpl = tmpl.replace(/\$cellClass/g, col.cellClass || 'kgEmpty');
tmpl = tmpl.replace(/\$cellValue/g, "$data." + col.field);
tmpl = tmpl.replace(/\$cell/g, replacer);
b.append(tmpl);
}
// finally just use a basic template for the cell
else {
b.append(' <div class="{0}" data-bind="kgCell: { value: \'{1}\' } "></div>', col.cellClass || 'kgEmpty', col.field);
}
});
b.append('</div>');
return b.toString();
};
/***********************************************
* FILE: ..\Src\Templates\FooterTemplate.js
***********************************************/
kg.templates.defaultFooterTemplate = function (options) {
var b = new kg.utils.StringBuilder();
b.append('<div class="kgTotalSelectContainer" data-bind="visible: footerVisible">');
b.append( '<div class="kgFooterTotalItems" data-bind="css: {\'kgNoMultiSelect\': !isMultiSelect()}" >');
b.append( '<span class="kgLabel">Total Items:</span> <span data-bind="text: maxRows"></span>');
b.append( '</div>');
b.append( '<div class="kgFooterSelectedItems" data-bind="visible: isMultiSelect">');
b.append( '<span class="kgLabel">Selected Items:</span> <span data-bind="text: selectedItemCount"></span>');
b.append( '</div>');
b.append('</div>');
b.append('<div class="kgPagerContainer" data-bind="visible: pagerVisible() && footerVisible(), css: {\'kgNoMultiSelect\': !isMultiSelect()}">');
b.append( '<div style="float: right;">');
b.append( '<div class="kgRowCountPicker">');
b.append( '<span class="kgLabel">Rows:</span>');
b.append( '<select data-bind="options: pageSizes, value: selectedPageSize">');
b.append( '</select>');
b.append( '</div>');
b.append( '<div class="kgPagerControl" style="float: left; min-width: 135px;">');
b.append( '<input class="kgPagerFirst" type="button" data-bind="click: pageToFirst, enable: canPageBackward" title="First Page"/>');
b.append( '<input class="kgPagerPrev" type="button" data-bind="click: pageBackward, enable: canPageBackward" title="Previous Page"/>');
b.append( '<input class="kgPagerCurrent" type="text" data-bind="value: protectedCurrentPage, enable: maxPages() > 1" />');
b.append( '<input class="kgPagerNext" type="button" data-bind="click: pageForward, enable: canPageForward" title="Next Page"/>');
b.append( '<input class="kgPagerLast" type="button" data-bind="click: pageToLast, enable: canPageForward" title="Last Page"/>');
b.append( '</div>');
b.append( '</div>');
b.append('</div>');
return b.toString();
};
/***********************************************
* FILE: ..\Src\Templates\TemplateManager.js
***********************************************/
kg.templateManager = (new function () {
var self = this;
self.templateCache = {};
self.templateExists = function (tmplId) {
var el = self.templateCache[tmplId];
return (el !== undefined && el !== null);
};
self.addTemplate = function (templateText, tmplId) {
self.templateCache[tmplId] = kg.utils.makeTemplate(tmplId, templateText);
};
this.removeTemplate = function (tmplId){
delete self.templateCache[tmplId];
};
this.addTemplateSafe = function (tmplId, templateText) {
if (!self.templateExists(tmplId)) {
self.addTemplate(templateText , tmplId);
}
};
this.ensureGridTemplates = function (options) {
//first ensure the koGrid template!
self.addTemplateSafe(GRID_TEMPLATE, kg.templates.defaultGridInnerTemplate(options));
//header row template
var template;
if (options.headerTemplate) {
template = self.getTemplateFromDom(options.headerTemplate) || kg.templates.generateHeaderTemplate(options);
self.addTemplateSafe(options.headerTemplate, template);
}
//header cell template
if (options.headerCellTemplate) {
template = self.getTemplateFromDom(options.headerCellTemplate) || kg.templates.defaultHeaderCellTemplate(options);
self.addTemplateSafe(options.headerCellTemplate, template);
}
//row template
if (options.rowTemplate) {
template = self.getTemplateFromDom(options.rowTemplate) || kg.templates.generateRowTemplate(options);
self.addTemplateSafe(options.rowTemplate, template);
}
//footer template
if (options.footerTemplate) {
template = self.getTemplateFromDom(options.footerTemplate) || kg.templates.defaultFooterTemplate(options);
self.addTemplateSafe(options.footerTemplate, template);
}
};
this.getTemplate = function (tmplId) {
return self.templateCache[tmplId] || "";
};
this.getTemplateFromDom = function(templId){
var temp = document.getElementById(templId);
return temp ? temp.innerHTML : undefined;
};
} ());
/***********************************************
* FILE: ..\Src\GridClasses\Dimension.js
***********************************************/
kg.Dimension = function (options) {
this.innerHeight = null;
this.innerWidth = null;
this.outerHeight = null;
this.outerWidth = null;
this.widthDiff = null;
this.heightDiff = null;
this.autoFitHeight = false; //tells it to just fit to the wrapping container
this.autoFitWidth = false;
$.extend(this, options);
};
/***********************************************
* FILE: ..\Src\GridClasses\Cell.js
***********************************************/
kg.Cell = function (col) {
this.data = '';
this.column = col;
this.row = null;
};
/***********************************************
* FILE: ..\Src\GridClasses\Column.js
***********************************************/
kg.Column = function (colDef, index) {
var self = this;
var minWisOb = ko.isObservable(colDef.minWidth);
var maxWisOb = ko.isObservable(colDef.maxWidth);
this.width = ko.observable(colDef.width);
this.widthIsConfigured = false;
this.autoWidthSubscription = undefined;
this.headerGroup = colDef.headerGroup;
// don't want the width to be smaller than this
this.minWidth = minWisOb ? colDef.minWidth : (!colDef.minWidth ? ko.observable(50) : ko.observable(colDef.minWidth));
// default max is OVER 9000!
this.maxWidth = maxWisOb ? colDef.maxWidth : ( !colDef.maxWidth ? ko.observable(9001) : ko.observable(colDef.maxWidth));
this.field = colDef.field;
if (colDef.displayName === undefined || colDef.displayName === null) {
// Allow empty column names -- do not check for empty string
colDef.displayName = colDef.field;
}
this.displayName = colDef.displayName;
this.index = index;
this.isVisible = ko.observable(false);
//sorting
if (colDef.sortable === undefined || colDef.sortable === null) {
colDef.sortable = true;
}
//resizing
if (colDef.resizable === undefined || colDef.resizable === null) {
colDef.resizable = true;
}
//resizing
if (colDef.filterable === undefined || colDef.filterable === null) {
colDef.filterable = true;
}
this.allowSort = colDef.sortable;
this.allowResize = colDef.resizable;
this.allowFilter = colDef.filterable;
this.sortDirection = ko.observable("");
this.sortingAlgorithm = colDef.sortFn;
//filtering
this.filter = ko.observable();
//cell Template
this.cellTemplate = colDef.cellTemplate; // string of the cellTemplate script element id
this.hasCellTemplate = (this.cellTemplate ? true : false);
if (self.hasCellTemplate){
var elem = document.getElementById(self.cellTemplate);
var templText = elem ? elem.innerHTML : undefined;
kg.templateManager.addTemplateSafe(self.cellTemplate, templText);
}
this.cellClass = colDef.cellClass;
this.headerClass = colDef.headerClass;
this.headerTemplate = colDef.headerTemplate;
this.hasHeaderTemplate = (this.headerTemplate ? true : false);
};
/***********************************************
* FILE: ..\Src\GridClasses\ColumnCollection.js
***********************************************/
kg.ColumnCollection = function () {
var obs = ko.observableArray([]);
ko.utils.extend(obs, kg.ColumnCollection.fn);
return obs;
};
kg.ColumnCollection.fn = {
};
/***********************************************
* FILE: ..\Src\GridClasses\Row.js
***********************************************/
kg.Row = function (entity, config, selectionManager) {
var self = this,
KEY = '__kg_selected__', // constant for the selection property that we add to each data item
canSelectRows = config.canSelectRows;
this.selectedItems = config.selectedItems;
this.entity = ko.isObservable(entity) ? entity : ko.observable(entity);
this.selectionManager = selectionManager;
//selectify the entity
if (this.entity()[KEY] === undefined) {
this.entity()[KEY] = ko.observable(false);
}
this.selected = ko.dependentObservable({
read: function () {
if (!canSelectRows) {
return false;
}
var val = self.entity()[KEY]();
return val;
},
write: function (val, evt) {
if (!canSelectRows) {
return true;
}
self.beforeSelectionChange();
self.entity()[KEY](val);
self.selectionManager.changeSelection(self, evt);
self.afterSelectionChange();
self.onSelectionChanged();
}
});
this.toggleSelected = function (data, event) {
if (!canSelectRows) {
return true;
}
var element = event.target;
//check and make sure its not the bubbling up of our checked 'click' event
if (element.type == "checkbox" && element.parentElement.className.indexOf("kgSelectionCell" !== -1)) {
return true;
}
if (config.selectWithCheckboxOnly && element.type != "checkbox"){
return true;
} else {
self.selected() ? self.selected(false, event) : self.selected(true, event);
}
};
this.toggle = function(item) {
if (item.selected()) {
item.selected(false);
self.selectedItems.remove(item.entity());
} else {
item.selected(true);
if (self.selectedItems.indexOf(item.entity()) === -1) {
self.selectedItems.push(item.entity());
}
}
};
this.cells = ko.observableArray([]);
this.cellMap = {};
this.rowIndex = 0;
this.offsetTop = 0;
this.rowKey = kg.utils.newId();
this.rowDisplayIndex = 0;
this.onSelectionChanged = function () { }; //replaced in rowManager
this.beforeSelectionChange = function () { };
this.afterSelectionChange = function () { };
//during row initialization, let's make all the entities properties first-class properties on the row
(function () {
kg.utils.forIn(entity, function (prop, propName) {
self[propName] = prop;
});
} ());
};
/***********************************************
* FILE: ..\Src\GridClasses\Range.js
***********************************************/
kg.Range = function (bottom, top) {
this.topRow = top;
this.bottomRow = bottom;
};
/***********************************************
* FILE: ..\Src\GridClasses\CellFactory.js
***********************************************/
kg.CellFactory = function (cols) {
var colCache = cols,
len = colCache.length;
this.buildRowCells = function (row) {
var cell,
cells = [],
col,
i = 0;
for (; i < len; i++) {
col = colCache[i];
cell = new kg.Cell(col);
cell.row = row;
//enabling nested property values in a viewmodel
cell.data = kg.utils.unwrapPropertyPath(col.field, row.entity());
cells.push(cell);
row.cellMap[col.field] = cell;
}
row.cells(cells);
return row;
};
};
/***********************************************
* FILE: ..\Src\GridClasses\HeaderCell.js
***********************************************/
kg.HeaderCell = function (col, rightHeaderGroup, resizeOnDataCallback) {
var self = this;
this.colIndex = col.colIndex;
this.displayName = col.displayName;
this.field = col.field;
this.column = col;
this.rightHeaderGroup = rightHeaderGroup;
this.headerClass = col.headerClass;
this.headerTemplate = col.headerTemplate;
this.hasHeaderTemplate = col.hasHeaderTemplate;
this.allowSort = ko.observable(col.allowSort);
this.allowFilter = col.allowFilter;
this.allowResize = ko.observable(col.allowResize);
this.width = col.width;
this.minWidth = col.minWidth;
this.maxWidth = col.maxWidth;
this.filter = ko.computed({
read: function () {
return self.column.filter();
},
write: function (val) {
self.column.filter(val);
}
});
this.filterVisible = ko.observable(false);
this._filterVisible = ko.computed({
read: function () {
return self.allowFilter;
},
write: function (val) {
self.filterVisible(val);
}
});
this.sortAscVisible = ko.computed(function () {
return self.column.sortDirection() === "asc";
});
this.sortDescVisible = ko.computed(function () {
return self.column.sortDirection() === "desc";
});
this.noSortVisible = ko.computed(function () {
var sortDir = self.column.sortDirection();
return sortDir !== "asc" && sortDir !== "desc";
});
this.sort = function () {
if (!self.allowSort()) {
return; // column sorting is disabled, do nothing
}
var dir = self.column.sortDirection() === "asc" ? "desc" : "asc";
self.column.sortDirection(dir);
};
this.filterHasFocus = ko.observable(false);
this.startMousePosition = 0;
this.origWidth = 0;
this.origMargin = 0;
var DELAY = 500,
clicks = 0,
timer = null;
this.gripClick = function(event) {
clicks++; //count clicks
if(clicks === 1) {
timer = setTimeout(function () {
//Here you can add a single click action.
clicks = 0; //after action performed, reset counter
}, DELAY);
} else {
clearTimeout(timer); //prevent single-click action
resizeOnDataCallback(self.column); //perform double-click action
clicks = 0; //after action performed, reset counter
}
};
this.gripOnMouseUp = function () {
$(document).off('mousemove');
$(document).off('mouseup');
document.body.style.cursor = 'default';
return false;
};
this.onMouseMove = function (event) {
var diff = event.clientX - self.startMousePosition;
var newWidth = diff + self.origWidth;
var setMargins = function(hg, nd) {
if (hg) {
var nm = nd + hg.origMargin;
hg.margin(nm);
if (hg.rightHeaderGroup) setMargins(hg.parent[hg.rightHeaderGroup], nd);
}
};
setMargins(self.rightHeaderGroup, diff),
self.width(newWidth < self.minWidth() ? self.minWidth() : (newWidth > self.maxWidth() ? self.maxWidth() : newWidth));
return false;
};
this.gripOnMouseDown = function (event) {
self.startMousePosition = event.clientX;
self.origWidth = self.width();
var setOrigMargins = function (hg) {
if (hg) {
hg.origMargin = hg.margin();
if (hg.rightHeaderGroup) setOrigMargins(hg.parent[hg.rightHeaderGroup]);
}
};
setOrigMargins(self.rightHeaderGroup);
$(document).mousemove(self.onMouseMove);
$(document).mouseup(self.gripOnMouseUp);
document.body.style.cursor = 'col-resize';
event.target.parentElement.style.cursor = 'col-resize';
return false;
};
};
/***********************************************
* FILE: ..\Src\GridClasses\HeaderRow.js
***********************************************/
kg.HeaderRow = function () {
this.headerCells = [];
this.height;
this.headerCellMap = {};
this.filterVisible = ko.observable(false);
this.headerGroups = { };
};
/***********************************************
* FILE: ..\Src\GridClasses\RowManager.js
***********************************************/
kg.RowManager = function (grid) {
var self = this,
prevMaxRows = 0, // for comparison purposes when scrolling
prevMinRows = 0, // for comparison purposes when scrolling
currentPage = grid.config.currentPage,
pageSize = grid.config.pageSize,
ROW_KEY = '__kg_rowIndex__', // constant for the entity's rowCache rowIndex
prevRenderedRange = new kg.Range(0, 1), // for comparison purposes to help throttle re-calcs when scrolling
prevViewableRange = new kg.Range(0, 1), // for comparison purposes to help throttle re-calcs when scrolling
internalRenderedRange = ko.observable(prevRenderedRange); // for comparison purposes to help throttle re-calcs when scrolling
this.dataChanged = true;
// we cache rows when they are built, and then blow the cache away when sorting/filtering
this.rowCache = [];
// short cut to sorted and filtered data
this.dataSource = grid.finalData; //observableArray
// change subscription to clear out our cache
this.dataSource.subscribe(function () {
self.dataChanged = true;
self.rowCache = []; //if data source changes, kill this!
});
// shortcut to the calculated minimum viewport rows
this.minViewportRows = grid.minRowsToRender; //observable
// the # of rows we want to add to the top and bottom of the rendered grid rows
this.excessRows = 8;
// height of each row
this.rowHeight = grid.config.rowHeight;
// the logic that builds cell objects
this.cellFactory = new kg.CellFactory(grid.columns());
// the actual range the user can see in the viewport
this.viewableRange = ko.observable(prevViewableRange);
// the range of rows that we actually render on the canvas ... essentially 'viewableRange' + 'excessRows' on top and bottom
this.renderedRange = ko.observable(prevRenderedRange);
// the array of rows that we've rendered
this.rows = ko.observableArray([]);
// change handler subscriptions for disposal purposes (used heavily by the 'rows' binding)
this.rowSubscriptions = {};
// Builds rows for each data item in the 'dataSource'
// @entity - the data item
// @rowIndex - the index of the row
// @pagingOffset - the # of rows to add the the rowIndex in case server-side paging is happening
this.buildRowFromEntity = function (entity, rowIndex, pagingOffset) {
var row = self.rowCache[rowIndex]; // first check to see if we've already built it
if (!row) {
// build the row
row = new kg.Row(entity, grid.config, grid.selectionManager);
row.rowIndex = rowIndex + 1; //not a zero-based rowIndex
row.rowDisplayIndex = row.rowIndex + pagingOffset;
row.offsetTop = self.rowHeight * rowIndex;
//build out the cells
self.cellFactory.buildRowCells(row);
// finally cache it for the next round
self.rowCache[rowIndex] = row;
}
// store the row's index on the entity for future ref
entity[ROW_KEY] = rowIndex;
return row;
};
// core logic here - anytime we updated the renderedRange, we need to update the 'rows' array
this.renderedRange.subscribe(function (rg) {
var rowArr = [],
row,
pagingOffset = (pageSize() * (currentPage() - 1)),
dataArr = self.dataSource().slice(rg.bottomRow, rg.topRow);
kg.utils.forEach(dataArr, function (item, i) {
row = self.buildRowFromEntity(item, rg.bottomRow + i, pagingOffset);
//add the row to our return array
rowArr.push(row);
//null the row pointer for next iteration
row = null;
});
self.rows(rowArr);
});
// core logic that intelligently figures out the rendered range given all the contraints that we have
this.calcRenderedRange = function () {
var rg = self.viewableRange(),
minRows = self.minViewportRows(),
maxRows = self.dataSource().length,
isDif = false, // flag to help us see if the viewableRange or data has changed "enough" to warrant re-building our rows
newRg; // variable to hold our newly-calc'd rendered range
if (rg) {
isDif = (rg.bottomRow !== prevViewableRange.bottomRow || rg.topRow !== prevViewableRange.topRow || self.dataChanged)
if (!isDif && prevMaxRows !== maxRows) {
isDif = true;
rg = new kg.Range(prevViewableRange.bottomRow, prevViewableRange.topRow);
}
if (!isDif && prevMinRows !== minRows) {
isDif = true;
rg = new kg.Range(prevViewableRange.bottomRow, prevViewableRange.topRow);
}