forked from Knockout-Contrib/KoGrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
koGrid-2.1.1.debug.js
2237 lines (2173 loc) · 90.7 KB
/
koGrid-2.1.1.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: 01/11/2013 15:58:36
***********************************************/
(function (window) {
'use strict';
/***********************************************
* FILE: ..\src\namespace.js
***********************************************/
if (!window.kg) {
window.kg = {};
}
window.kg.numberOfGrids = 0;
window.kg.eventStorage = {};
/***********************************************
* FILE: ..\src\constants.js
***********************************************/
var SELECTED_PROP = '__kg_selected__',
GRID_KEY = '__koGrid__',
// the # of rows we want to add to the top and bottom of the rendered grid rows
EXCESS_ROWS = 8,
SCROLL_THRESHOLD = 6,
ASC = "asc", // constant for sorting direction
DESC = "desc", // constant for sorting direction
KG_FIELD = '_kg_field_',
KG_DEPTH = '_kg_depth_',
KG_HIDDEN = '_kg_hidden_',
KG_COLUMN = '_kg_column_',
TEMPLATE_REGEXP = /<.+>/;
/***********************************************
* FILE: ..\src\navigation.js
***********************************************/
//set event binding on the grid so we can select using the up/down keys
window.kg.moveSelectionHandler = function(grid, evt) {
// null checks
if (window.kg.utils.isNullOrUndefined(grid) || window.kg.utils.isNullOrUndefined(grid.config.selectedItems)) {
return true;
}
var charCode = evt.which || evt.keyCode,
// detect which direction for arrow keys to navigate the grid
offset = (charCode === 38 ? -1 : (charCode === 40 ? 1 : null));
if (!offset) {
return true;
}
var items = grid.renderedRows(),
index = items.indexOf(grid.selectionService.lastClickedRow) + offset;
if (index < 0 || index >= items.length) {
return true;
}
grid.selectionService.ChangeSelection(items[index], evt);
if (index > items.length - EXCESS_ROWS) {
grid.$viewport.scrollTop(grid.$viewport.scrollTop() + (grid.config.rowHeight * EXCESS_ROWS));
} else if (index < EXCESS_ROWS) {
grid.$viewport.scrollTop(grid.$viewport.scrollTop() - (grid.config.rowHeight * EXCESS_ROWS));
}
return false;
};
/***********************************************
* FILE: ..\src\utils.js
***********************************************/
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from += len;
}
for (; from < len; from++) {
if (from in this && this[from] === elt) {
return from;
}
}
return -1;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp */) {
"use strict";
var t = Object(this),
len = t.length >>> 0;
if (typeof fun !== "function") {
throw new TypeError();
}
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
window.kg.utils = {
visualLength: function(node) {
var elem = document.getElementById('testDataLength');
if (!elem) {
elem = document.createElement('SPAN');
elem.id = "testDataLength";
elem.style.visibility = "hidden";
document.body.appendChild(elem);
}
$(elem).css('font', $(node).css('font'));
elem.innerHTML = $(node).text();
return elem.offsetWidth;
},
forIn: function(obj, action) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
action(obj[prop], prop);
}
}
},
evalProperty: function(entity, path) {
var e = ko.utils.unwrapObservable(entity);
var propPath = path.split('.'), i = 0;
var tempProp = ko.utils.unwrapObservable(e[propPath[i]]), links = propPath.length;
i++;
while (tempProp && i < links) {
tempProp = ko.utils.unwrapObservable(tempProp[propPath[i]]);
i++;
}
return tempProp;
},
endsWith: function(str, suffix) {
if (!str || !suffix || typeof str != "string") {
return false;
}
return str.indexOf(suffix, str.length - suffix.length) !== -1;
},
isNullOrUndefined: function(obj) {
if (obj === undefined || obj === null) {
return true;
}
return false;
},
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;
},
getTemplatePromise: function(path) {
return $.ajax(path);
},
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 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;
})()
};
$.extend(window.kg.utils, {
isIe6: (function() {
return window.kg.utils.ieVersion === 6;
})(),
isIe7: (function() {
return window.kg.utils.ieVersion === 7;
})(),
isIe: (function() {
return window.kg.utils.ieVersion !== undefined;
})()
});
/***********************************************
* FILE: ..\src\templates\gridTemplate.html
***********************************************/
window.kg.defaultGridTemplate = function(){ return '<div data-bind="css: {\'ui-widget\': jqueryUITheme, \'kgNoSelect\' : disableTextSelection}"><div class="kgTopPanel" data-bind="css: {\'ui-widget-header\':jqueryUITheme, \'ui-corner-top\': jqueryUITheme}, style: $data.topPanelStyle"><div class="kgGroupPanel" data-bind="visible: $data.showGroupPanel, style: headerStyle"><div class="kgGroupPanelDescription" data-bind="visible: configGroups().length == 0">Drag a column header here and drop it to group by that column</div><ul data-bind="visible: configGroups().length > 0, foreach: configGroups" class="kgGroupList"><li class="kgGroupItem"><span class="kgGroupElement"><div class="kgGroupName"><span data-bind="text: displayName"></span><span data-bind="click: function(data) { $root.removeGroup($index()) }" class="kgRemoveGroup">x</span></div><span data-bind="visible: $index() < ($root.configGroups().length - 1)" class="kgGroupArrow"></span></span></li></ul></div><div class="kgHeaderContainer" data-bind="style: headerStyle"><div class="kgHeaderScroller" data-bind="style: headerScrollerStyle, kgHeaderRow: $data" ></div></div><div class="kgHeaderButton" data-bind="visible: ($data.showColumnMenu || $data.showFilter), click: toggleShowMenu"><div class="kgHeaderButtonArrow"></div></div><div data-bind="visible: showMenu" class="kgColMenu"><div data-bind="visible: showFilter"><input placeholder="Seach Field:Value" type="text" data-bind="value: filterText, valueUpdate: \'afterkeydown\'"/></div><div data-bind="visible: showColumnMenu"><span class="kgMenuText">Choose Columns:</span><ul class="kgColList" data-bind="foreach: nonAggColumns"><li class="kgColListItem"><label style="position: relative;"><input type="checkbox" class="kgColListCheckbox" data-bind="checked: visible"/><span data-bind="text: displayName, click: toggleVisible"></span><a title="Group By" data-bind="attr: {\'class\': groupedByClass }, visible: (field != \'\u2714\'), click: $parent.groupBy"></a><span class="kgGroupingNumber" data-bind="visible: groupIndex() > 0, text: groupIndex"></span></label></li></ul></div></div></div><div class="kgViewport" data-bind="css: {\'ui-widget-content\': jqueryUITheme}, style: viewportStyle"><div class="kgCanvas" data-bind="style: canvasStyle"><div data-bind="foreach: renderedRows" style="position: absolute;"><div data-bind="style: { \'top\': offsetTop, \'height\': $parent.rowHeight + \'px\' }, click: toggleSelected, css: {\'selected\': selected, \'even\': isEven , \'odd\': isOdd, \'ui-state-default\': $parent.jqueryUITheme && isOdd, \'ui-state-active\':$parent.jqueryUITheme && isEven}, kgRow: $data" class="kgRow"></div></div></div></div><div class="kgFooterPanel" data-bind="css: {\'ui-widget-content\': jqueryUITheme, \'ui-corner-bottom\': jqueryUITheme}, style: footerStyle"><div class="kgTotalSelectContainer" data-bind="visible: footerVisible"><div class="kgFooterTotalItems" data-bind="css: {\'kgNoMultiSelect\': !multiSelect}" ><span class="kgLabel">Total Items: <span data-bind="text: maxRowsDisplay"></span></span><span data-bind="visible: filterText().length > 0" class="kgLabel">(Showing: <span data-bind="text: totalFilteredItemsLength"></span>)</span></div><div class="kgFooterSelectedItems" data-bind="visible: multiSelect"><span class="kgLabel">Selected Items: <span data-bind="text: selectedItemCount"></span></span></div></div><div class="kgPagerContainer" style="float: right; margin-top: 10px;" data-bind="visible: (footerVisible && enablePaging), css: {\'kgNoMultiSelect\': !multiSelect}"><div style="float:left; margin-right: 10px;" class="kgRowCountPicker"><span style="float: left; margin-top: 3px;" class="kgLabel">Page Size:</span><select style="float: left;height: 27px; width: 100px" data-bind="value: pagingOptions.pageSize, options: pagingOptions.pageSizes"></select></div><div style="float:left; margin-right: 10px; line-height:25px;" class="kgPagerControl" style="float: left; min-width: 135px;"><button class="kgPagerButton" data-bind="click: pageToFirst, disable: cantPageBackward()" title="First Page"><div class="kgPagerFirstTriangle"><div class="kgPagerFirstBar"></div></div></button><button class="kgPagerButton" data-bind="click: pageBackward, disable: cantPageBackward()" title="Previous Page"><div class="kgPagerFirstTriangle kgPagerPrevTriangle"></div></button><input class="kgPagerCurrent" type="number" style="width:50px; height: 24px; margin-top: 1px; padding: 0px 4px;" data-bind="value: pagingOptions.currentPage, valueUpdate: \'afterkeydown\'"/><button class="kgPagerButton" data-bind="click: pageForward, disable: cantPageForward()" title="Next Page"><div class="kgPagerLastTriangle kgPagerNextTriangle"></div></button><button class="kgPagerButton" data-bind="click: pageToLast, disable: cantPageForward()" title="Last Page"><div class="kgPagerLastTriangle"><div class="kgPagerLastBar"></div></div></button></div></div></div></div>';};
/***********************************************
* FILE: ..\src\templates\rowTemplate.html
***********************************************/
window.kg.defaultRowTemplate = function(){ return '<div data-bind="style: { cursor : canSelectRows ? \'pointer\' : \'default\' }, foreach: $grid.visibleColumns, css: { \'ui-widget-content\': $grid.jqueryUITheme }"><div data-bind="attr: { \'class\': cellClass() + \' kgCell col\' + $index() }, kgCell: $data"></div></div>';};
/***********************************************
* FILE: ..\src\templates\cellTemplate.html
***********************************************/
window.kg.defaultCellTemplate = function(){ return '<div data-bind="attr: { \'class\': \'kgCellText colt\' + $index()}, html: $data.getProperty($parent)"></div>';};
/***********************************************
* FILE: ..\src\templates\aggregateTemplate.html
***********************************************/
window.kg.aggregateTemplate = function(){ return '<div data-bind="click: toggleExpand, style: {\'left\': offsetLeft()}" class="kgAggregate"><span class="kgAggregateText" data-bind="html: $data.label">(<span data-bind="html: totalChildren"></span> Items)</span><div data-bind="attr: {\'class\' : aggClass }"></div></div>';};
/***********************************************
* FILE: ..\src\templates\headerRowTemplate.html
***********************************************/
window.kg.defaultHeaderRowTemplate = function(){ return '<div data-bind="foreach: visibleColumns"><div data-bind="kgHeaderCell: $data, attr: { \'class\': \'kgHeaderCell col\' + $index() }"></div></div>';};
/***********************************************
* FILE: ..\src\templates\headerCellTemplate.html
***********************************************/
window.kg.defaultHeaderCellTemplate = function(){ return '<div data-bind="style: { cursor : sortable() ? \'pointer\' : \'default\' }, click: sort, css: {\'kgSorted\': !noSortVisible }, attr: {\'class\': \'kgHeaderSortColumn \' + headerClass()}"><div data-bind="attr: { \'class\': \'colt\' + $index() + \' kgHeaderText\' }, html: displayName"></div><div class="kgSortButtonDown" data-bind="visible: showSortButtonDown"></div><div class="kgSortButtonUp" data-bind="visible: showSortButtonUp"></div><div data-bind="visible: resizable, click: gripClick, mouseEvents: { mouseDown: gripOnMouseDown }" class="kgHeaderGrip" ></div></div>';};
/***********************************************
* FILE: ..\src\bindingHandlers\ko-grid.js
***********************************************/
ko.bindingHandlers['koGrid'] = (function () {
return {
'init': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = valueAccessor();
var elem = $(element);
options.gridDim = new window.kg.Dimension({ outerHeight: ko.observable(elem.height()), outerWidth: ko.observable(elem.width()) });
var grid = new window.kg.Grid(options);
var gridElem = $(window.kg.defaultGridTemplate());
// if it is a string we can watch for data changes. otherwise you won't be able to update the grid data
options.data.subscribe(function () {
if (grid.$$selectionPhase) {
return;
}
grid.searchProvider.evalFilter();
grid.refreshDomSizes();
});
// if columndefs are observable watch for changes and rebuild columns.
if (ko.isObservable(options.columnDefs)) {
options.columnDefs.subscribe(function (newDefs) {
grid.columns([]);
grid.config.columnDefs = newDefs;
grid.buildColumns();
grid.configureColumnWidths();
});
}
//set the right styling on the container
elem.addClass("koGrid").addClass(grid.gridId.toString());
elem.append(gridElem);
grid.$userViewModel = bindingContext.$data;
ko.applyBindings(grid, gridElem[0]);
//walk the element's graph and the correct properties on the grid
window.kg.domUtilityService.AssignGridContainers(elem, grid);
grid.configureColumnWidths();
grid.refreshDomSizes();
//now use the manager to assign the event handlers
grid.eventProvider = new window.kg.EventProvider(grid);
//initialize plugins.
$.each(grid.config.plugins, function (i, p) {
if (typeof p.onGridInit === 'function') {
p.onGridInit(grid);
}
});
window.kg.domUtilityService.BuildStyles(grid);
return { controlsDescendantBindings: true };
}
};
}());
/***********************************************
* FILE: ..\src\bindingHandlers\kg-row.js
***********************************************/
ko.bindingHandlers['kgRow'] = (function () {
return {
'init': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var row = valueAccessor();
var grid = row.$grid = bindingContext.$parent;
var source;
if (row.isAggRow) {
source = window.kg.aggregateTemplate();
} else {
source = grid.rowTemplate;
}
var compile = function(html) {
var rowElem = $(html);
row.$userViewModel = bindingContext.$parent.$userViewModel;
ko.applyBindings(row, rowElem[0]);
$(element).html(rowElem);
};
if (source.then) {
source.then(function (p) {
compile(p);
});
} else {
compile(source);
}
return { controlsDescendantBindings: true };
}
};
}());
/***********************************************
* FILE: ..\src\bindingHandlers\kg-cell.js
***********************************************/
ko.bindingHandlers['kgCell'] = (function () {
return {
'init': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
bindingContext.$userViewModel = bindingContext.$parent.$userViewModel;
var compile = function (html) {
var cell = $(html);
ko.applyBindings(bindingContext, cell[0]);
$(element).html(cell);
};
if (viewModel.cellTemplate.then) {
viewModel.cellTemplate.then(function(p) {
compile(p);
});
} else {
compile(viewModel.cellTemplate);
}
return { controlsDescendantBindings: true };
}
};
}());
/***********************************************
* FILE: ..\src\bindingHandlers\kg-header-row.js
***********************************************/
ko.bindingHandlers['kgHeaderRow'] = (function () {
return {
'init': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
bindingContext.$userViewModel = bindingContext.$data.$userViewModel;
var compile = function(html) {
var headerRow = $(html);
ko.applyBindings(bindingContext, headerRow[0]);
$(element).html(headerRow);
};
if (viewModel.headerRowTemplate.then) {
viewModel.headerRowTemplate.then(function (p) {
compile(p);
});
} else {
compile(viewModel.headerRowTemplate);
}
return { controlsDescendantBindings: true };
}
};
}());
/***********************************************
* FILE: ..\src\bindingHandlers\kg-header-cell.js
***********************************************/
ko.bindingHandlers['kgHeaderCell'] = (function () {
return {
'init': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var newContext = bindingContext.extend({ $grid: bindingContext.$parent, $userViewModel: bindingContext.$parent.$userViewModel });
var compile = function (html) {
var headerCell = $(html);
ko.applyBindings(newContext, headerCell[0]);
$(element).html(headerCell);
};
if (viewModel.headerCellTemplate.then) {
viewModel.headerCellTemplate.then(function (p) {
compile(p);
});
} else {
compile(viewModel.headerCellTemplate);
}
return { controlsDescendantBindings: true };
}
};
}());
/***********************************************
* FILE: ..\src\bindingHandlers\kg-mouse-events.js
***********************************************/
ko.bindingHandlers['mouseEvents'] = (function () {
return {
'init': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var eFuncs = valueAccessor();
if (eFuncs.mouseDown) {
$(element).mousedown(eFuncs.mouseDown);
}
}
};
}());
/***********************************************
* FILE: ..\src\classes\aggregate.js
***********************************************/
window.kg.Aggregate = function (aggEntity, rowFactory) {
var self = this;
self.index = 0;
self.offsetTop = ko.observable(0);
self.entity = aggEntity;
self.label = ko.observable(aggEntity.gLabel);
self.field = aggEntity.gField;
self.depth = aggEntity.gDepth;
self.parent = aggEntity.parent;
self.children = aggEntity.children;
self.aggChildren = aggEntity.aggChildren;
self.aggIndex = aggEntity.aggIndex;
self.collapsed = ko.observable(true);
self.isAggRow = true;
self.offsetLeft = ko.observable((aggEntity.gDepth * 25).toString() + 'px');
self.aggLabelFilter = aggEntity.aggLabelFilter;
self.toggleExpand = function() {
var c = self.collapsed();
self.collapsed(!c);
self.notifyChildren();
};
self.setExpand = function (state) {
self.collapsed(state);
self.notifyChildren();
};
self.notifyChildren = function() {
$.each(self.aggChildren, function (i, child) {
child.entity[KG_HIDDEN] = self.collapsed();
if (self.collapsed()) {
var c = self.collapsed();
child.setExpand(c);
}
});
$.each(self.children, function (i, child) {
child[KG_HIDDEN] = self.collapsed();
});
rowFactory.rowCache = [];
var foundMyself = false;
$.each(rowFactory.aggCache, function (i, agg) {
if (foundMyself) {
var offset = (30 * self.children.length);
var c = self.collapsed();
agg.offsetTop(c ? agg.offsetTop() - offset : agg.offsetTop() + offset);
} else {
if (i == self.aggIndex) {
foundMyself = true;
}
}
});
rowFactory.renderedChange();
};
self.aggClass = ko.computed(function() {
return self.collapsed() ? "kgAggArrowCollapsed" : "kgAggArrowExpanded";
});
self.totalChildren = ko.computed(function() {
if (self.aggChildren.length > 0) {
var i = 0;
var recurse = function (cur) {
if (cur.aggChildren.length > 0) {
$.each(cur.aggChildren, function (x, a) {
recurse(a);
});
} else {
i += cur.children.length;
}
};
recurse(self);
return i;
} else {
return self.children.length;
}
});
self.selected = ko.observable(false);
self.isEven = ko.observable(false);
self.isOdd = ko.observable(false);
self.toggleSelected = function () { return true; };
};
/***********************************************
* FILE: ..\src\classes\column.js
***********************************************/
window.kg.Column = function (config, grid) {
var self = this,
colDef = config.colDef,
delay = 500,
clicks = 0,
timer = null;
self.eventTaget = undefined;
self.width = colDef.width;
self.groupIndex = ko.observable(0);
self.isGroupedBy = ko.observable(false);
self.groupedByClass = ko.computed(function(){ return self.isGroupedBy() ? "kgGroupedByIcon": "kgGroupIcon";});
self.sortable = ko.observable(false);
self.resizable = ko.observable(false);
self.minWidth = !colDef.minWidth ? 50 : colDef.minWidth;
self.maxWidth = !colDef.maxWidth ? 9000 : colDef.maxWidth;
self.headerRowHeight = config.headerRowHeight;
self.displayName = ko.observable(colDef.displayName || colDef.field);
self.index = config.index;
self.isAggCol = config.isAggCol;
self.cellClass = ko.observable(colDef.cellClass || "");
self.cellFilter = colDef.cellFilter || colDef.cellFormatter;
self.field = colDef.field;
self.aggLabelFilter = colDef.cellFilter || colDef.cellFormatter || colDef.aggLabelFilter || colDef.aggLabelFormatter;
self._visible = ko.observable(window.kg.utils.isNullOrUndefined(colDef.visible) || colDef.visible);
self.visible = ko.computed({
read: function() {
return self._visible();
},
write: function(val) {
self.toggleVisible(val);
}
});
if (config.enableSort) {
self.sortable(window.kg.utils.isNullOrUndefined(colDef.sortable) || colDef.sortable);
}
if (config.enableResize) {
self.resizable(window.kg.utils.isNullOrUndefined(colDef.resizable) || colDef.resizable);
}
self.sortDirection = ko.observable(undefined);
self.sortingAlgorithm = colDef.sortFn;
self.headerClass = ko.observable(colDef.headerClass);
self.headerCellTemplate = colDef.headerCellTemplate || window.kg.defaultHeaderCellTemplate();
self.cellTemplate = colDef.cellTemplate || window.kg.defaultCellTemplate();
if (colDef.cellTemplate && !TEMPLATE_REGEXP.test(colDef.cellTemplate)) {
self.cellTemplate = window.kg.utils.getTemplatePromise(colDef.cellTemplate);
}
if (colDef.headerCellTemplate && !TEMPLATE_REGEXP.test(colDef.headerCellTemplate)) {
self.headerCellTemplate = window.kg.utils.getTemplatePromise(colDef.headerCellTemplate);
}
self.getProperty = function (row) {
var ret;
if (self.cellFilter) {
ret = self.cellFilter(row.getProperty(self.field));
} else {
ret = row.getProperty(self.field);
}
return ret;
};
self.toggleVisible = function (val) {
var v;
if (window.kg.utils.isNullOrUndefined(val) || typeof val == "object") {
v = !self._visible();
} else {
v = val;
}
self._visible(v);
window.kg.domUtilityService.BuildStyles(grid);
};
self.showSortButtonUp = ko.computed(function () {
return self.sortable ? self.sortDirection() === DESC : self.sortable;
});
self.showSortButtonDown = ko.computed(function () {
return self.sortable ? self.sortDirection() === ASC : self.sortable;
});
self.noSortVisible = ko.computed(function () {
return !self.sortDirection();
});
self.sort = function () {
if (!self.sortable()) {
return true; // column sorting is disabled, do nothing
}
var dir = self.sortDirection() === ASC ? DESC : ASC;
self.sortDirection(dir);
config.sortCallback(self, dir);
return false;
};
self.gripClick = function (data, event) {
event.stopPropagation();
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
config.resizeOnDataCallback(self); //perform double-click action
clicks = 0; //after action performed, reset counter
}
};
self.gripOnMouseDown = function (event) {
event.stopPropagation();
if (event.ctrlKey) {
self.toggleVisible();
window.kg.domUtilityService.BuildStyles(grid);
grid.config.columnsChanged(grid.columns.peek());
return true;
}
self.eventTaget = event.target.parentElement;
self.eventTaget.style.cursor = 'col-resize';
self.startMousePosition = event.clientX;
self.origWidth = self.width;
$(document).mousemove(self.onMouseMove);
$(document).mouseup(self.gripOnMouseUp);
return false;
};
self.onMouseMove = function (event) {
event.stopPropagation();
var diff = event.clientX - self.startMousePosition;
var newWidth = diff + self.origWidth;
self.width = (newWidth < self.minWidth ? self.minWidth : (newWidth > self.maxWidth ? self.maxWidth : newWidth));
window.kg.domUtilityService.BuildStyles(grid);
return false;
};
self.gripOnMouseUp = function (event) {
event.stopPropagation();
$(document).off('mousemove');
$(document).off('mouseup');
self.eventTaget.style.cursor = self.sortable() ? 'pointer' : 'default';
self.eventTaget = undefined;
grid.config.columnsChanged(grid.columns.peek());
return false;
};
};
/***********************************************
* FILE: ..\src\classes\dimension.js
***********************************************/
window.kg.Dimension = function (options) {
this.outerHeight = null;
this.outerWidth = null;
$.extend(this, options);
};
/***********************************************
* FILE: ..\src\classes\eventProvider.js
***********************************************/
window.kg.EventProvider = function (grid) {
var self = this;
// The init method gets called during the ng-grid directive execution.
self.colToMove = undefined;
self.groupToMove = undefined;
self.assignEvents = function () {
// Here we set the onmousedown event handler to the header container.
if(grid.config.jqueryUIDraggable){
grid.$groupPanel.droppable({
addClasses: false,
drop: function(event) {
self.onGroupDrop(event);
}
});
$(document).ready(self.setDraggables);
} else {
grid.$groupPanel.on('mousedown', self.onGroupMouseDown).on('dragover', self.dragOver).on('drop', self.onGroupDrop);
grid.$headerScroller.on('mousedown', self.onHeaderMouseDown).on('dragover', self.dragOver).on('drop', self.onHeaderDrop);
if (grid.config.enableRowReordering) {
grid.$viewport.on('mousedown', self.onRowMouseDown).on('dragover', self.dragOver).on('drop', self.onRowDrop);
}
self.setDraggables();
}
grid.columns.subscribe(self.setDraggables);
};
self.dragOver = function(evt) {
evt.preventDefault();
};
//For JQueryUI
self.setDraggables = function(){
if(!grid.config.jqueryUIDraggable){
grid.$root.find('.kgHeaderSortColumn').attr('draggable', 'true');
if (navigator.userAgent.indexOf("MSIE") != -1)
{
//call native IE dragDrop() to start dragging
grid.$root.find('.kgHeaderSortColumn').bind('selectstart', function () { this.dragDrop(); return false; });
}
} else {
grid.$root.find('.kgHeaderSortColumn').draggable({
helper: 'clone',
appendTo: 'body',
stack: 'div',
addClasses: false,
start: function(event){
self.onHeaderMouseDown(event);
}
}).droppable({
drop: function(event) {
self.onHeaderDrop(event);
}
});
}
};
self.onGroupMouseDown = function(event) {
var groupItem = $(event.target);
// Get the scope from the header container
if(groupItem[0].className !='kgRemoveGroup'){
var groupItemScope = ko.dataFor(groupItem[0]);
if (groupItemScope) {
// set draggable events
if(!grid.config.jqueryUIDraggable){
groupItem.attr('draggable', 'true');
}
// Save the column for later.
self.groupToMove = { header: groupItem, groupName: groupItemScope, index: groupItemScope.groupIndex() - 1 };
}
} else {
self.groupToMove = undefined;
}
};
self.onGroupDrop = function(event) {
// clear out the colToMove object
var groupContainer;
var groupScope;
if (self.groupToMove) {
// Get the closest header to where we dropped
groupContainer = $(event.target).closest('.kgGroupElement'); // Get the scope from the header.
if (groupContainer.context.className =='kgGroupPanel') {
grid.configGroups.splice(self.groupToMove.index, 1);
grid.configGroups.push(self.groupToMove.groupName);
} else {
groupScope = ko.dataFor(groupContainer[0]);
if (groupScope) {
// If we have the same column, do nothing.
if (self.groupToMove.index != groupScope.groupIndex()) {
// Splice the columns
grid.configGroups.splice(self.groupToMove.index, 1);
grid.configGroups.splice(groupScope.groupIndex(), 0, self.groupToMove.groupName);
}
}
}
self.groupToMove = undefined;
grid.fixGroupIndexes();
} else {
if (grid.configGroups.indexOf(self.colToMove.col) == -1) {
groupContainer = $(event.target).closest('.kgGroupElement'); // Get the scope from the header.
if (groupContainer.context.className =='kgGroupPanel' || groupContainer.context.className =='kgGroupPanelDescription') {
grid.groupBy(self.colToMove.col);
} else {
groupScope = ko.dataFor(groupContainer[0]);
if (groupScope) {
// Splice the columns
grid.removeGroup(groupScope.groupIndex());
}
}
}
self.colToMove = undefined;
}
};
//Header functions
self.onHeaderMouseDown = function (event) {
// Get the closest header container from where we clicked.
var headerContainer = $(event.target).closest('.kgHeaderSortColumn');
if (!headerContainer[0]) {
return true;
}
// Get the scope from the header container
var headerScope = ko.dataFor(headerContainer[0]);
if (headerScope) {
// Save the column for later.
self.colToMove = { header: headerContainer, col: headerScope };
}
return true;
};
self.onHeaderDrop = function (event) {
if (!self.colToMove) {
return true;
}
// Get the closest header to where we dropped
var headerContainer = $(event.target).closest('.kgHeaderSortColumn');
if (!headerContainer[0]) {
return true;
}
// Get the scope from the header.
var headerScope = ko.dataFor(headerContainer[0]);
if (headerScope) {
// If we have the same column, do nothing.
if (self.colToMove.col == headerScope) {
return true;
}
// Splice the columns
var cols = grid.columns.peek();
cols.splice(self.colToMove.col.index, 1);
cols.splice(headerScope.index, 0, self.colToMove.col);
grid.fixColumnIndexes();
grid.columns(cols);
// Finally, rebuild the CSS styles.
window.kg.domUtilityService.BuildStyles(grid);
// clear out the colToMove object
self.colToMove = undefined;
}
return true;
};
// Row functions
self.onRowMouseDown = function (event) {
// Get the closest row element from where we clicked.
var targetRow = $(event.target).closest('.kgRow');
if (!targetRow[0]) {
return;
}
// Get the scope from the row element
var rowScope = ko.dataFor(targetRow[0]);
if (rowScope) {
// set draggable events
targetRow.attr('draggable', 'true');
// Save the row for later.
window.kg.eventStorage.rowToMove = { targetRow: targetRow, scope: rowScope };
}
};
self.onRowDrop = function (event) {
// Get the closest row to where we dropped
var targetRow = $(event.target).closest('.kgRow');
// Get the scope from the row element.
var rowScope = ko.dataFor(targetRow[0]);
if (rowScope) {
// If we have the same Row, do nothing.
var prevRow = window.kg.eventStorage.rowToMove;
if (prevRow.scope == rowScope) {
return;
}
// Splice the Rows via the actual datasource
var sd = grid.sortedData();
var i = sd.indexOf(prevRow.scope.entity);
var j = sd.indexOf(rowScope.entity);
grid.sortedData.splice(i, 1);
grid.sortedData.splice(j, 0, prevRow.scope.entity);
grid.searchProvider.evalFilter();
// clear out the rowToMove object
window.kg.eventStorage.rowToMove = undefined;
// if there isn't an apply already in progress lets start one
}
};
self.assignGridEventHandlers = function() {
grid.$viewport.scroll(function(e) {
var scrollLeft = e.target.scrollLeft,
scrollTop = e.target.scrollTop;
grid.adjustScrollLeft(scrollLeft);
grid.adjustScrollTop(scrollTop);
});
grid.$viewport.off('keydown');
grid.$viewport.on('keydown', function(e) {
return window.kg.moveSelectionHandler(grid, e);
});
//Chrome and firefox both need a tab index so the grid can recieve focus.
//need to give the grid a tabindex if it doesn't already have one so
//we'll just give it a tab index of the corresponding gridcache index
//that way we'll get the same result every time it is run.
//configurable within the options.
if (grid.config.tabIndex === -1) {
grid.$viewport.attr('tabIndex', window.kg.numberOfGrids);
window.kg.numberOfGrids++;
} else {
grid.$viewport.attr('tabIndex', grid.config.tabIndex);
}
$(window).resize(function() {
window.kg.domUtilityService.UpdateGridLayout(grid);
if (grid.config.maintainColumnRatios) {
grid.configureColumnWidths();
}
});
};
self.assignGridEventHandlers();
// In this example we want to assign grid events.
self.assignEvents();
};
/***********************************************
* FILE: ..\src\classes\rowFactory.js
***********************************************/
window.kg.RowFactory = function (grid) {
var self = this;
// we cache rows when they are built, and then blow the cache away when sorting
self.rowCache = [];
self.aggCache = {};
self.parentCache = []; // Used for grouping and is cleared each time groups are calulated.
self.dataChanged = true;
self.parsedData = [];
self.rowConfig = {};
self.selectionService = grid.selectionService;
self.rowHeight = 30;
self.numberOfAggregates = 0;
self.groupedData = undefined;
self.rowHeight = grid.config.rowHeight;
self.rowConfig = {
canSelectRows: grid.config.canSelectRows,
rowClasses: grid.config.rowClasses,
selectedItems: grid.config.selectedItems,
selectWithCheckboxOnly: grid.config.selectWithCheckboxOnly,
beforeSelectionChangeCallback: grid.config.beforeSelectionChange,
afterSelectionChangeCallback: grid.config.afterSelectionChange
};
self.renderedRange = new window.kg.Range(0, grid.minRowsToRender() + EXCESS_ROWS);
// Builds rows for each data item in the 'filteredData'
// @entity - the data item
// @rowIndex - the index of the row
self.buildEntityRow = function(entity, rowIndex) {
var row = self.rowCache[rowIndex]; // first check to see if we've already built it
if (!row) {
// build the row
row = new window.kg.Row(entity, self.rowConfig, self.selectionService);
row.rowIndex(rowIndex + 1); //not a zero-based rowIndex
row.offsetTop((self.rowHeight * rowIndex).toString() + 'px');
row.selected(entity[SELECTED_PROP]);
// finally cache it for the next round
self.rowCache[rowIndex] = row;
}
return row;
};
self.buildAggregateRow = function(aggEntity, rowIndex) {
var agg = self.aggCache[aggEntity.aggIndex]; // first check to see if we've already built it
if (!agg) {
// build the row
agg = new window.kg.Aggregate(aggEntity, self);
self.aggCache[aggEntity.aggIndex] = agg;
}
agg.index = rowIndex + 1; //not a zero-based rowIndex
agg.offsetTop((self.rowHeight * rowIndex).toString() + 'px');
return agg;
};
self.UpdateViewableRange = function(newRange) {
self.renderedRange = newRange;
self.renderedChange();
};
self.filteredDataChanged = function() {
// check for latebound autogenerated columns
if (grid.lateBoundColumns && grid.filteredData().length > 1) {
grid.config.columnDefs = undefined;
grid.buildColumns();
grid.lateBoundColumns = false;
}
self.dataChanged = true;
self.rowCache = []; //if data source changes, kill this!
if (grid.config.groups.length > 0) {
self.getGrouping(grid.config.groups);
}
self.UpdateViewableRange(self.renderedRange);
};
self.renderedChange = function() {
if (!self.groupedData || grid.config.groups.length < 1) {
self.renderedChangeNoGroups();
grid.refreshDomSizes();
return;
}
self.parentCache = [];
var rowArr = [];
var dataArray = self.parsedData.filter(function(e) {
return e[KG_HIDDEN] === false;
}).slice(self.renderedRange.topRow, self.renderedRange.bottomRow);
$.each(dataArray, function (indx, item) {
var row;
if (item.isAggRow) {
row = self.buildAggregateRow(item, self.renderedRange.topRow + indx);
} else {
row = self.buildEntityRow(item, self.renderedRange.topRow + indx);
}
//add the row to our return array
rowArr.push(row);
});
grid.setRenderedRows(rowArr);
grid.refreshDomSizes();
};
self.renderedChangeNoGroups = function() {
var rowArr = [];
var dataArr = grid.filteredData.slice(self.renderedRange.topRow, self.renderedRange.bottomRow);
$.each(dataArr, function (i, item) {
var row = self.buildEntityRow(item, self.renderedRange.topRow + i);
//add the row to our return array
rowArr.push(row);
});
grid.setRenderedRows(rowArr);
};
//magical recursion. it works. I swear it. I figured it out in the shower one day.
self.parseGroupData = function(g) {
if (g.values) {
$.each(g.values, function (i, item) {
// get the last parent in the array because that's where our children want to be
self.parentCache[self.parentCache.length - 1].children.push(item);
//add the row to our return array
self.parsedData.push(item);
});
} else {
for (var prop in g) {
// exclude the meta properties.
if (prop == KG_FIELD || prop == KG_DEPTH || prop == KG_COLUMN) {
continue;
} else if (g.hasOwnProperty(prop)) {
//build the aggregate row
var agg = self.buildAggregateRow({
gField: g[KG_FIELD],
gLabel: prop,
gDepth: g[KG_DEPTH],
isAggRow: true,
'_kg_hidden_': false,
children: [],
aggChildren: [],
aggIndex: self.numberOfAggregates,
aggLabelFilter: g[KG_COLUMN].aggLabelFilter
}, 0);
self.numberOfAggregates++;