forked from Knockout-Contrib/KoGrid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkoGrid.debug.js
More file actions
2907 lines (2283 loc) · 96.5 KB
/
Copy pathkoGrid.debug.js
File metadata and controls
2907 lines (2283 loc) · 96.5 KB
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
* (c) Eric M. Barnard
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
* Compiled At: 12:49:53.97 Mon 08/13/2012
***********************************************/
(function(window, undefined){
/***********************************************
* 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\Labels.js
***********************************************/
kg.labels = {
};
/***********************************************
* FILE: ..\Src\Utils.js
***********************************************/
var utils = {
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);
}
}
}
};
utils.newId = (function () {
var seedId = new Date().getTime();
return function () {
return seedId += 1;
};
} ());
utils.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("");
}
};
};
kg.utils = utils;
/***********************************************
* FILE: ..\Src\Templates\GridTemplate.js
***********************************************/
kg.templates.defaultGridInnerTemplate = function () {
return '<div class="kgTopPanel" data-bind="kgSize: $data.headerDim">' +
'<div class="kgHeaderContainer" style="position: relative; overflow-x: hidden" data-bind="kgSize: $data.headerDim">' +
'<div class="kgHeaderScroller" data-bind="kgHeaderRow: $data, kgSize: $data.headerScrollerDim">' +
'</div>' +
'</div>' +
'</div>' +
'<div class="kgViewport" style="overflow: auto;" data-bind="kgSize: $data.viewportDim">' +
'<div class="kgCanvas" data-bind="kgRows: $data.rows, style: { height: $data.canvasHeight }" style="position: relative">' +
'</div>' +
'</div>' +
'<div class="kgFooterPanel" data-bind="kgFooter: $data, kgSize: $data.footerDim" style="position: relative;">' +
'</div>';
};
/***********************************************
* FILE: ..\Src\Templates\HeaderTemplate.js
***********************************************/
kg.templates.generateHeaderTemplate = function (options) {
var b = new kg.utils.StringBuilder(),
cols = options.columns,
showFilter = options.showFilter;
utils.forEach(cols, function (col, i) {
if (col.field === '__kg_selected__') {
b.append('<div class="kgSelectionCell" data-bind="kgHeader: { value: \'{0}\' }, css: { \'kgNoSort\': {1} }">', col.field, !col.allowSort);
b.append(' <input type="checkbox" data-bind="checked: $parent.toggleSelectAll, visible: $parent.config.isMultiSelect"/>');
b.append('</div>');
} else if (col.field === 'rowIndex' && showFilter) {
b.append('<div data-bind="kgHeader: { value: \'{0}\' }, css: { \'kgNoSort\': {1} }">', col.field, !col.allowSort);
b.append(' <div title="Filter Results" class="kgFilterBtn openBtn" data-bind="visible: !$data.filterVisible(), click: $parent.showFilter_Click"></div>');
b.append(' <div title="Close" class="kgFilterBtn closeBtn" data-bind="visible: $data.filterVisible, 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 data-bind="kgHeader: { value: \'{0}\' }, css: { \'kgNoSort\': {1} }">', col.field, !col.allowSort);
b.append('</div>');
}
});
return b.toString();
};
/***********************************************
* FILE: ..\Src\Templates\HeaderCellTemplate.js
***********************************************/
kg.templates.defaultHeaderCellTemplate = function () {
var b = new kg.utils.StringBuilder();
b.append('<div data-bind="click: $data.sort, css: { \'kgSorted\': !$data.noSortVisible() }">');
b.append(' <span data-bind="text: $data.displayName"></span>');
b.append(' <img class="kgSortImg" data-bind="visible: $data.allowSort() && $data.noSortVisible()" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAJCAYAAAD+WDajAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjEwMPRyoQAAAEFJREFUKFNjYICC+vp6YyDeDcSCMDEwDRRQAuK7QPwfpAAuiSYBkkQoAHLOQAVgEjB6FYrxGBy8OvHaide1+PwJAMBIWUlZ9vlNAAAAAElFTkSuQmCC"/>');
b.append(' <img class="kgSortImg" data-bind="visible: $data.sortAscVisible" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAJCAYAAAD+WDajAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwgAADsIBFShKgAAAABp0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuMTAw9HKhAAAAPElEQVQoU2NggIL6+npjIN4NxIIwMTANFFAC4rtA/B+kAC6JJgGSRCgAcs5ABWASMHoVw////3HigZAEACKmlTwMfriZAAAAAElFTkSuQmCC"/>');
b.append(' <img class="kgSortImg" data-bind="visible: $data.sortDescVisible" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAJCAYAAAD+WDajAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwgAADsIBFShKgAAAABp0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuMTAw9HKhAAAAPUlEQVQoU2P4//8/Ay6MUwKkgQJJBnygvr7+DBD/x4JXMQAFlYD4LprkbriBaAoQEjAVQAXGQLwbiAVhYgD6kIBR+tr9IgAAAABJRU5ErkJggg=="/>');
b.append('</div>');
b.append('<div data-bind="visible: $parent.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 }">');
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.getTemplateText(col.cellTemplate);
// 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 () {
return '<div class="kgTotalSelectContainer" data-bind="visible: footerVisible">' +
'<div class="kgFooterTotalItems" data-bind="css: {\'kgNoMultiSelect\': !isMultiSelect()}" >' +
'<span class="kgLabel">Total Items:</span> <span data-bind="text: maxRows"></span>' +
'</div>' +
'<div class="kgFooterSelectedItems" data-bind="visible: isMultiSelect">' +
'<span class="kgLabel">Selected Items:</span> <span data-bind="text: selectedItemCount"></span>' +
'</div>' +
'</div>' +
'<div class="kgPagerContainer" data-bind="visible: pagerVisible() && footerVisible(), css: {\'kgNoMultiSelect\': !isMultiSelect()}">' +
'<div style="float: right;">' +
'<div class="kgRowCountPicker">' +
'<span class="kgLabel">Rows:</span>' +
'<select data-bind="options: pageSizes, value: selectedPageSize">' +
'</select>' +
'</div>' +
'<div class="kgPagerControl" style="float: left; min-width: 135px;">' +
'<input class="kgPagerFirst" type="button" data-bind="click: pageToFirst, enable: canPageBackward" title="First Page"/>' +
'<input class="kgPagerPrev" type="button" data-bind="click: pageBackward, enable: canPageBackward" title="Previous Page"/>' +
'<input class="kgPagerCurrent" type="text" data-bind="value: protectedCurrentPage, enable: maxPages() > 1" />' +
'<input class="kgPagerNext" type="button" data-bind="click: pageForward, enable: canPageForward" title="Next Page"/>' +
'<input class="kgPagerLast" type="button" data-bind="click: pageToLast, enable: canPageForward" title="Last Page"/>' +
'</div>' +
'</div>' +
'</div>';
};
/***********************************************
* FILE: ..\Src\Templates\TemplateManager.js
***********************************************/
kg.templateManager = (new function () {
var self = this;
var templateExists = function (tmplId) {
var el = document.getElementById(tmplId);
return (el !== undefined && el !== null);
};
var addTemplate = function (templateText, tmplId) {
var tmpl = document.createElement("SCRIPT");
tmpl.type = "text/html";
tmpl.id = tmplId;
// 'innerText' in tmpl ? tmpl.innerText = templateText
// : tmpl.textContent = templateText;
tmpl.text = templateText;
document.body.appendChild(tmpl);
};
this.addTemplateSafe = function (tmplId, templateTextAccessor) {
if (!templateExists(tmplId)) {
addTemplate(templateTextAccessor(), tmplId);
}
};
this.ensureGridTemplates = function (options) {
var defaults = {
rowTemplate: '',
headerTemplate: '',
headerCellTemplate: '',
footerTemplate: '',
columns: null,
showFilter: true
},
config = $.extend(defaults, options);
//first ensure the koGrid template!
self.addTemplateSafe(GRID_TEMPLATE, kg.templates.defaultGridInnerTemplate);
//header row template
if (config.headerTemplate) {
self.addTemplateSafe(config.headerTemplate, function () {
return kg.templates.generateHeaderTemplate(config);
});
}
//header cell template
if (config.headerCellTemplate) {
self.addTemplateSafe(config.headerCellTemplate, kg.templates.defaultHeaderCellTemplate);
}
//row template
if (config.rowTemplate) {
self.addTemplateSafe(config.rowTemplate, function () {
return kg.templates.generateRowTemplate(config);
});
}
//footer template
if (config.footerTemplate) {
self.addTemplateSafe(config.footerTemplate, kg.templates.defaultFooterTemplate);
}
};
this.getTemplateText = function (tmplId) {
if (!templateExists(tmplId)) {
return "";
} else {
var el = document.getElementById(tmplId);
return el.text;
}
};
} ());
/***********************************************
* 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) {
this.width = ko.observable(0);
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.colIndex = 0;
this.isVisible = ko.observable(false);
this.width = ko.observable();
//sorting
if (colDef.sortable === undefined || colDef.sortable === null) {
colDef.sortable = true;
}
this.allowSort = colDef.sortable;
this.sortDirection = ko.observable("");
//filtering
this.filter = ko.observable();
//cell Template
this.cellTemplate = colDef.cellTemplate; // string of the cellTemplate script element id
this.hasCellTemplate = (this.cellTemplate ? true : false);
this.cellClass = colDef.cellClass;
this.headerClass = colDef.headerClass;
this.headerTemplate = colDef.headerTemplate
this.hasHeaderTemplate = (this.headerTemplate ? true : false);
// figure out the width
if (!colDef.width) {
colDef.width = this.displayName.length * kg.domUtility.letterW;
colDef.width += 30; //for sorting icons and padding
}
this.width(colDef.width);
};
/***********************************************
* 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
***********************************************/
/// <reference path="../utils.js" />
/// <reference path="../namespace.js" />
/// <reference path="../Grid.js" />
kg.Row = function (entity, config) {
var self = this;
var canSelectRows = config.canSelectRows;
this.entity = ko.isObservable(entity) ? entity : ko.observable(entity);
//selectify the entity
if (this.entity()['__kg_selected__'] === undefined) {
this.entity()['__kg_selected__'] = ko.observable(false);
}
this.selected = ko.dependentObservable({
read: function () {
if (!canSelectRows) {
return false;
}
var val = self.entity()['__kg_selected__']();
return val;
},
write: function (val) {
if (!canSelectRows) {
return true;
}
self.entity()['__kg_selected__'](val);
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;
} else {
if (self.selected()) {
self.selected(false);
} else {
self.selected(true);
}
}
return true;
};
this.cells = ko.observableArray([]);
this.cellMap = {};
this.rowIndex = 0;
this.offsetTop = 0;
this.rowKey = utils.newId();
this.rowDisplayIndex = 0;
this.onSelectionChanged = function () { }; //replaced in rowManager
//during row initialization, let's make all the entities properties first-class properties on the row
(function () {
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;
cell.data = row.entity()[col.field]; //could be observable or not...
cells.push(cell);
row.cellMap[col.field] = cell;
}
row.cells(cells);
return row;
};
};
/***********************************************
* FILE: ..\Src\GridClasses\HeaderCell.js
***********************************************/
kg.HeaderCell = function (col) {
var self = this;
this.colIndex = 0;
this.displayName = col.displayName;
this.field = col.field;
this.column = col;
this.headerClass = col.headerClass;
this.headerTemplate = col.headerTemplate;
this.hasHeaderTemplate = col.hasHeaderTemplate;
this.width = ko.computed(function () {
return col.width();
});
this.filter = ko.computed({
read: function () {
return self.column.filter();
},
write: function (val) {
self.column.filter(val);
}
});
this.filterVisible = ko.observable(false);
this.allowSort = ko.observable(col.allowSort);
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);
};
/***********************************************
* FILE: ..\Src\GridClasses\HeaderRow.js
***********************************************/
kg.HeaderRow = function () {
this.headerCells = [];
this.height;
this.headerCellMap = {};
this.filterVisible = ko.observable(false);
};
/***********************************************
* FILE: ..\Src\GridClasses\RowManager.js
***********************************************/
kg.RowManager = function (grid) {
var self = this,
rowCache = {}, // we cache rows when they are built, and then blow the cache away when sorting/filtering
prevMaxRows = 0, // for comparison purposes when scrolling
prevMinRows = 0, // for comparison purposes when scrolling
dataChanged = true, // flag to determine if the dataSource has been sorted, filtered, or updated
currentPage = grid.config.currentPage,
pageSize = grid.config.pageSize,
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
// short cut to sorted and filtered data
this.dataSource = grid.finalData; //observableArray
// change subscription to clear out our cache
this.dataSource.subscribe(function () {
dataChanged = true;
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
var buildRowFromEntity = function (entity, rowIndex, pagingOffset) {
var row = rowCache[rowIndex]; // first check to see if we've already built it
if (!row) {
// build the row
row = new kg.Row(entity, grid.config);
row.rowIndex = rowIndex + 1; //not a zero-based rowIndex
row.rowDisplayIndex = row.rowIndex + pagingOffset;
row.offsetTop = self.rowHeight * rowIndex;
//setup a selection change handler
row.onSelectionChanged = function () {
var ent = this.entity();
grid.changeSelectedItem(ent); // use the grid-defined callback ... yes, i know... should pub an event instead
};
//build out the cells
self.cellFactory.buildRowCells(row);
// finally cache it for the next round
rowCache[rowIndex] = row;
}
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);
utils.forEach(dataArr, function (item, i) {
row = 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
var 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 || 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);
}
if (isDif) {
//Now build out the new rendered range
rg.topRow = rg.bottomRow + minRows;
//store it for next rev
prevViewableRange = rg;
// now build the new rendered range
newRg = new kg.Range(rg.bottomRow, rg.topRow);
// make sure we are within our data constraints (can't render negative rows or rows greater than the # of data items we have)
newRg.bottomRow = Math.max(0, rg.bottomRow - self.excessRows);
newRg.topRow = Math.min(maxRows, rg.topRow + self.excessRows);
// store them for later comparison purposes
prevMaxRows = maxRows;
prevMinRows = minRows;
//one last equality check
if (prevRenderedRange.topRow !== newRg.topRow || prevRenderedRange.bottomRow !== newRg.bottomRow || dataChanged) {
dataChanged = false;
prevRenderedRange = newRg;
// now kickoff row building
self.renderedRange(newRg);
}
}
} else {
self.renderedRange(new kg.Range(0, 0));
}
};
// make sure that if any of these change, we re-fire the calc logic
self.viewableRange.subscribe(calcRenderedRange);
self.minViewportRows.subscribe(calcRenderedRange);
self.dataSource.subscribe(calcRenderedRange);
};
/***********************************************
* FILE: ..\Src\GridClasses\Footer.js
***********************************************/
kg.Footer = function (grid) {
var self = this;
this.maxRows;
if (grid.config.totalServerItems() !== null && grid.config.totalServerItems() !== undefined) {
this.maxRows = grid.config.totalServerItems; //observable
} else {
this.maxRows = grid.maxRows; //observable
}
this.isMultiSelect = ko.observable(grid.config.canSelectRows && grid.config.isMultiSelect);
this.selectedItemCount = grid.selectedItemCount; //observable
this.footerVisible = grid.config.footerVisible;
this.pagerVisible = ko.observable(grid.config.enablePaging);
this.selectedPageSize = grid.config.pageSize; //observable
this.pageSizes = ko.observableArray(grid.config.pageSizes);
this.currentPage = grid.config.currentPage; //observable
this.maxPages = ko.computed(function () {
var maxCnt = self.maxRows() || 1,
pageSize = self.selectedPageSize();
return Math.ceil(maxCnt / pageSize);
});
this.protectedCurrentPage = ko.computed({
read: function () {
return self.currentPage();
},
write: function (page) {
if (page && page <= self.maxPages() && page > 0) {
self.currentPage(page); //KO does an equality check on primitives before notifying subscriptions here
}
},
owner: self
});
this.pageForward = function () {
var page = self.currentPage();
self.currentPage(Math.min(page + 1, self.maxPages()));
}
this.pageBackward = function () {
var page = self.currentPage();
self.currentPage(Math.max(page - 1, 1));
};
this.pageToFirst = function () {
self.currentPage(1);
};
this.pageToLast = function () {
var maxPages = self.maxPages();
self.currentPage(maxPages);
};
this.canPageForward = ko.computed(function () {
var curPage = self.currentPage();
var maxPages = self.maxPages();
return curPage < maxPages;
});
this.canPageBackward = ko.computed(function () {
var curPage = self.currentPage();
return curPage > 1;
});
};
/***********************************************
* FILE: ..\Src\GridClasses\FilterManager.js
***********************************************/
kg.FilterManager = function (options) {
var self = this,
wildcard = options.filterWildcard || "*", // the wildcard character used by the user
includeDestroyed = options.includeDestroyed || false, // flag to indicate whether to include _destroy=true items in filtered data
regExCache = {}, // a cache of filterString to regex objects, eg: { 'abc%' : RegExp("abc[^\']*, "gi") }
initPhase = 0, // flag for allowing us to do initialization only once and prevent dependencies from getting improperly registered
internalFilteredData = ko.observableArray([]); // obs array that we use to manage the filtering before it updates the final data
// first check the wildcard as we only support * and % currently
if (wildcard === '*' || wildcard === '%') {
// do nothing
} else {
throw new Error("You can only declare a percent sign (%) or an asterisk (*) as a wildcard character");
}
// filters off _destroy = true items
var filterDestroyed = function (arr) {
return ko.utils.arrayFilter(arr, function (item) {
return (item['_destroy'] === true ? false : true);
});
};
// map of column.field values to filterStrings
this.filterInfo = options.filterInfo || ko.observable();
// the obs array of data that the user defined
this.data = options.data;
// the obs array of filtered data we return to the grid
this.filteredData = ko.computed(function () {
var data = internalFilteredData();
//this is a bit funky, but it prevents our options.data observable from being registered as a subscription to our grid.update bindingHandler
if (initPhase > 0) {
return data;
} else {
return filterDestroyed(self.data());
}
});
// utility function for checking data validity
var isEmpty = function (data) {
return (data === null || data === undefined || data === '');
};
// performs regex matching on data strings
var matchString = function (itemStr, filterStr) {
//first check for RegEx thats already built
var regex = regExCache[filterStr];
//if nothing, build the regex
if (!regex) {
var replacer = "";
//escape any wierd characters they might using
filterStr = filterStr.replace(/\\/g, "\\");
// build our replacer regex
if (wildcard === "*") {
replacer = /\*/g;
} else {
replacer = /\%/g;
}
//first replace all % percent signs with the true regex wildcard *
var regexStr = filterStr.replace(replacer, "[^\']*");
//ensure that we do "beginsWith" logic
if (regexStr !== "*") { // handle the asterisk logic
regexStr = "^" + regexStr;
}
// incase the user makes some nasty regex that we can't use
try{
// then create an actual regex object
regex = new RegExp(regexStr, "gi");
}
catch (e) {
// the user input something we can't parse into a valid RegExp, so just say that the data
// was a match
regex = /.*/gi;
}
// store it
regExCache[filterStr] = regex;
}
return itemStr.match(regex);
};
// the core logic for filtering data
var filterData = function () {
var filterInfo = self.filterInfo(),
data = self.data(),
keepRow = false, // flag to say if the row will be removed or kept in the viewport
match = true, // flag for matching logic
newArr = [], // the filtered array
field, // the field of the column that we are filtering
itemData, // the data from the specific row's column
itemDataStr, // the stringified version of itemData
filterStr; // the user-entered filtering criteria
// filter the destroyed items
data = filterDestroyed(data);
// make sure we even have work to do before we get started
if (!filterInfo || $.isEmptyObject(filterInfo) || options.useExternalFiltering) {
internalFilteredData(data);
return;
}
//clear out the regex cache so that we don't get improper results
regExCache = {};
// filter the data array
newArr = ko.utils.arrayFilter(data, function (item) {
var propPath,
i;
//loop through each property and filter it
for (field in filterInfo) {
if (filterInfo.hasOwnProperty(field)) {
// pull the data out of the item
propPath = field.split(".");
itemData = item;
for (i = 0; i < propPath.length && itemData !== undefined && itemData !== null; i++) {
itemData = ko.utils.unwrapObservable(itemData[propPath[i]]);
}
// grab the user-entered filter criteria
filterStr = filterInfo[field];
// make sure they didn't just enter the wildcard character
if (!isEmpty(filterStr) && filterStr !== wildcard) {
// execute regex matching
if (isEmpty(itemData)) {
match = false;
} else if (typeof itemData === "string") {
match = matchString(itemData, filterStr);
} else {
itemDataStr = itemData.toString();
match = matchString(itemDataStr, filterStr);
}
}
}
//supports "AND" filtering logic
if (keepRow && !match) {
keepRow = false;
} else if (!keepRow && match) {
keepRow = true; //should only catch on the first pass
}
//now if we catch anything thats not a match, break out of the loop
if (!match) { break; }
}