forked from MoonStorm/trNgGrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrNgGrid.js
1343 lines (1342 loc) · 75 KB
/
trNgGrid.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
"use strict";
var TrNgGrid;
(function (TrNgGrid) {
TrNgGrid.version = "3.1.4";
(function (SelectionMode) {
SelectionMode[SelectionMode["None"] = 0] = "None";
SelectionMode[SelectionMode["SingleRow"] = 1] = "SingleRow";
SelectionMode[SelectionMode["MultiRow"] = 2] = "MultiRow";
SelectionMode[SelectionMode["MultiRowWithKeyModifiers"] = 3] = "MultiRowWithKeyModifiers";
})(TrNgGrid.SelectionMode || (TrNgGrid.SelectionMode = {}));
var SelectionMode = TrNgGrid.SelectionMode;
// it's important to assign all the default column options, so we can match them with the column attributes in the markup
TrNgGrid.defaultColumnOptionsTemplate = {
cellWidth: null,
cellHeight: null,
displayAlign: null,
displayFormat: null,
displayName: null,
filter: null,
enableFiltering: null,
enableSorting: null
};
TrNgGrid.defaultColumnOptions = {};
TrNgGrid.translations = {};
TrNgGrid.debugMode = false;
var templatesConfigured = false;
var tableDirective = "trNgGrid";
TrNgGrid.sortFilter = tableDirective + "SortFilter";
TrNgGrid.dataPagingFilter = tableDirective + "DataPagingFilter";
TrNgGrid.translateFilter = tableDirective + "TranslateFilter";
TrNgGrid.translationDateFormat = tableDirective + "DateFormat";
TrNgGrid.dataFormattingFilter = tableDirective + "DataFormatFilter";
//var headerDirective="trNgGridHeader";
//var headerDirectiveAttribute = "tr-ng-grid-header";
var bodyDirective = "trNgGridBody";
var bodyDirectiveAttribute = "tr-ng-grid-body";
var fieldNameAttribute = "field-name";
var altFieldNameAttribute = "data-field-name";
var isCustomizedAttribute = "is-customized";
var cellFooterDirective = "trNgGridFooterCell";
var cellFooterDirectiveAttribute = "tr-ng-grid-footer-cell";
var cellFooterTemplateDirective = "trNgGridFooterCellTemplate";
var cellFooterTemplateDirectiveAttribute = "tr-ng-grid-footer-cell-template";
TrNgGrid.cellFooterTemplateId = cellFooterTemplateDirective + ".html";
var globalFilterDirective = "trNgGridGlobalFilter";
TrNgGrid.globalFilterDirectiveAttribute = "tr-ng-grid-global-filter";
TrNgGrid.footerGlobalFilterTemplateId = globalFilterDirective + ".html";
var pagerDirective = "trNgGridPager";
TrNgGrid.pagerDirectiveAttribute = "tr-ng-grid-pager";
TrNgGrid.footerPagerTemplateId = pagerDirective + ".html";
var cellHeaderDirective = "trNgGridHeaderCell";
var cellHeaderDirectiveAttribute = "tr-ng-grid-header-cell";
var cellHeaderTemplateDirective = "trNgGridHeaderCellTemplate";
var cellHeaderTemplateDirectiveAttribute = "tr-ng-grid-header-cell-template";
TrNgGrid.cellHeaderTemplateId = cellHeaderTemplateDirective + ".html";
var cellBodyDirective = "trNgGridBodyCell";
var cellBodyDirectiveAttribute = "tr-ng-grid-body-cell";
var cellBodyTemplateDirective = "trNgGridBodyCellTemplate";
var cellBodyTemplateDirectiveAttribute = "tr-ng-grid-body-cell-template";
TrNgGrid.cellBodyTemplateId = cellBodyTemplateDirective + ".html";
var columnSortDirective = "trNgGridColumnSort";
TrNgGrid.columnSortDirectiveAttribute = "tr-ng-grid-column-sort";
TrNgGrid.columnSortTemplateId = columnSortDirective + ".html";
var columnFilterDirective = "trNgGridColumnFilter";
TrNgGrid.columnFilterDirectiveAttribute = "tr-ng-grid-column-filter";
TrNgGrid.columnFilterTemplateId = columnFilterDirective + ".html";
var findChildByTagName = function (parent, childTag) {
childTag = childTag.toUpperCase();
var children = parent.children();
for (var childIndex = 0; childIndex < children.length; childIndex++) {
var childElement = children[childIndex];
if (childElement.tagName == childTag) {
return angular.element(childElement);
}
}
return null;
};
var findChildrenByTagName = function (parent, childTag) {
childTag = childTag.toUpperCase();
var retChildren = [];
var children = parent.children();
for (var childIndex = 0; childIndex < children.length; childIndex++) {
var childElement = children[childIndex];
if (childElement.tagName === childTag) {
retChildren.push(angular.element(childElement));
}
}
return retChildren;
};
/**
* Combines two sets of cell infos. The first set will take precedence in the checks but the combined items will contain items from the second set if they match.
*/
var combineGridCellInfos = function (firstSet, secondSet, addExtraFieldItemsSecondSet, addExtraNonFieldItemsSecondSet) {
var combinedSet = [];
var secondTempSet = secondSet.slice(0);
angular.forEach(firstSet, function (firstSetColumn) {
// find a correspondence in the second set
var foundSecondSetColumn = null;
for (var secondSetColumnIndex = 0; !foundSecondSetColumn && secondSetColumnIndex < secondTempSet.length; secondSetColumnIndex++) {
foundSecondSetColumn = secondTempSet[secondSetColumnIndex];
if (foundSecondSetColumn.fieldName === firstSetColumn.fieldName) {
secondTempSet.splice(secondSetColumnIndex, 1);
}
else {
foundSecondSetColumn = null;
}
}
if (foundSecondSetColumn) {
combinedSet.push(foundSecondSetColumn);
}
else {
combinedSet.push(firstSetColumn);
}
});
// add the remaining items from the second set in the combined set
if (addExtraFieldItemsSecondSet || addExtraNonFieldItemsSecondSet) {
angular.forEach(secondTempSet, function (secondSetColumn) {
if ((addExtraFieldItemsSecondSet && secondSetColumn.fieldName) || (addExtraNonFieldItemsSecondSet && !secondSetColumn.fieldName)) {
combinedSet.push(secondSetColumn);
}
});
}
return combinedSet;
};
var wrapTemplatedCell = function (templateElement, tAttrs, isCustomized, cellTemplateDirective) {
if (isCustomized) {
var childrenElements = templateElement.children();
var firstChildElement = angular.element(childrenElements[0]);
if (childrenElements.length !== 1 || !firstChildElement.attr(cellTemplateDirective)) {
// wrap the children of the custom template cell
templateElement.empty();
var templateWrapElement = angular.element("<div></div>").attr(cellTemplateDirective, "");
templateElement.append(templateWrapElement);
angular.forEach(childrenElements, function (childElement) {
templateWrapElement.append(angular.element(childElement));
});
}
}
else {
templateElement.empty();
templateElement.append(angular.element("<div></div>").attr(cellTemplateDirective, ""));
}
};
var TemplatedCell = (function () {
function TemplatedCell(parent, cellElement) {
this.parent = parent;
this.cellElement = cellElement;
this.fieldName = cellElement.attr(fieldNameAttribute) || cellElement.attr(altFieldNameAttribute);
var customContent = cellElement.children();
this.isStandardColumn = customContent.length === 0;
}
return TemplatedCell;
})();
var TemplatedSection = (function () {
function TemplatedSection(sectionTagName, sectionDirectiveAttribute, rowDirectiveAttribute, cellTagName, cellDirectiveAttribute) {
this.sectionTagName = sectionTagName;
this.sectionDirectiveAttribute = sectionDirectiveAttribute;
this.rowDirectiveAttribute = rowDirectiveAttribute;
this.cellTagName = cellTagName;
this.cellDirectiveAttribute = cellDirectiveAttribute;
this.cellTagName = this.cellTagName.toUpperCase();
this.cells = null;
}
TemplatedSection.prototype.configureSection = function (gridElement, columnDefs) {
var _this = this;
var sectionElement = this.getSectionElement(gridElement, true);
sectionElement.empty();
sectionElement.removeAttr("ng-non-bindable");
// add the elements in order
var rowElementDefinitions = combineGridCellInfos(columnDefs, this.cells, false, false);
// grab the templated row
var templatedRowElement = this.getTemplatedRowElement(sectionElement, true);
angular.forEach(rowElementDefinitions, function (gridCell, index) {
var gridCellElement;
var templatedCell = gridCell;
// it might not be a templated cell, beware
if (templatedCell.parent === _this && templatedCell.cellElement) {
gridCellElement = templatedCell.cellElement.clone(true);
}
else {
gridCellElement = angular.element("<table><" + _this.cellTagName + "></" + _this.cellTagName + "></table>").find(_this.cellTagName);
}
// set it up
if (_this.cellDirectiveAttribute) {
gridCellElement.attr(_this.cellDirectiveAttribute, index);
}
if (!gridCell.isStandardColumn) {
gridCellElement.attr(isCustomizedAttribute, "true");
}
if (gridCell.fieldName) {
gridCellElement.attr(fieldNameAttribute, gridCell.fieldName);
}
gridCellElement.attr("ng-style", "{\'width\':columnOptions.cellWidth,\'height\':columnOptions.cellHeight}");
// finally add it to the parent
templatedRowElement.append(gridCellElement);
});
return sectionElement;
};
TemplatedSection.prototype.extractPartialColumnDefinitions = function () {
return this.cells;
};
TemplatedSection.prototype.discoverTemplates = function (gridElement) {
var _this = this;
this.cells = [];
this.cellRow = null;
var templatedRow = this.getTemplatedRowElement(this.getSectionElement(gridElement, false), false);
if (templatedRow) {
this.cellRow = angular.element(templatedRow.clone());
this.cellRow.empty();
angular.forEach(templatedRow.children(), function (childElement, childIndex) {
childElement = angular.element(childElement);
if (childElement[0].tagName === _this.cellTagName.toUpperCase()) {
var templateElement = childElement.clone();
_this.cells.push(new TemplatedCell(_this, templateElement));
}
});
}
};
TemplatedSection.prototype.getSectionElement = function (gridElement, ensurePresent) {
var sectionElement = null;
if (gridElement) {
sectionElement = findChildByTagName(gridElement, this.sectionTagName);
}
if (!sectionElement && ensurePresent) {
// angular strikes again: https://groups.google.com/forum/#!topic/angular/7poFynsguNw
sectionElement = angular.element("<table><" + this.sectionTagName + "></" + this.sectionTagName + "></table>").find(this.sectionTagName);
if (gridElement) {
gridElement.append(sectionElement);
}
}
if (sectionElement && ensurePresent && this.sectionDirectiveAttribute) {
sectionElement.attr(this.sectionDirectiveAttribute, "");
}
return sectionElement;
};
TemplatedSection.prototype.getTemplatedRowElement = function (sectionElement, ensurePresent) {
var rowElement = null;
if (sectionElement) {
rowElement = findChildByTagName(sectionElement, "tr");
}
if (!rowElement && ensurePresent) {
rowElement = this.cellRow ? angular.element(this.cellRow.clone()) : angular.element("<table><tr></tr></table>").find("tr");
if (sectionElement) {
sectionElement.append(rowElement);
}
}
if (rowElement && ensurePresent && this.rowDirectiveAttribute) {
rowElement.attr(this.rowDirectiveAttribute, "");
}
return rowElement;
};
return TemplatedSection;
})();
var GridController = (function () {
// Update: These two might not be needed after all, due to evalasync/applyasync patterns
//private temporarilyIgnorePageIndexChangeForDataRetrievals:boolean;
//private temporarilyIgnorePageIndexChangeForDataFiltering: boolean;
function GridController($compile, $parse, $timeout, $templateCache) {
this.$compile = $compile;
this.$parse = $parse;
this.$timeout = $timeout;
if (!templatesConfigured) {
configureTemplates($templateCache);
templatesConfigured = true;
}
}
GridController.prototype.setupGrid = function (gridScope, gridOptions, isInServerSideMode) {
this.gridOptions = gridOptions;
this.isInServerSideMode = isInServerSideMode;
gridScope.gridOptions = gridOptions;
gridScope.TrNgGrid = TrNgGrid;
// set some defaults
gridOptions.gridColumnDefs = [];
if (gridOptions.locale === undefined) {
gridOptions.locale = "en";
}
if (gridOptions.selectionMode === undefined) {
gridOptions.selectionMode = SelectionMode[2 /* MultiRow */];
}
if (gridOptions.filterByFields === undefined) {
gridOptions.filterByFields = {};
}
if (gridOptions.enableFiltering === undefined) {
gridOptions.enableFiltering = true;
}
if (gridOptions.enableSorting === undefined) {
gridOptions.enableSorting = true;
}
if (gridOptions.onDataRequiredDelay === undefined) {
gridOptions.onDataRequiredDelay = 1000; //ms
}
if (gridOptions.autoLoad === undefined) {
gridOptions.autoLoad = false;
}
if (gridOptions.selectedItems === undefined) {
gridOptions.selectedItems = [];
}
if (gridOptions.currentPage === undefined) {
gridOptions.currentPage = 0;
}
//set up watchers
this.setupServerSideModeTriggers(gridScope);
this.setupDataFilteringTriggers(gridScope);
this.setupDataFormattingTriggers(gridScope);
this.setupDataSelectionTriggers(gridScope);
return gridScope;
};
GridController.prototype.setupDataFilteringTriggers = function (gridScope) {
var _this = this;
var scheduledForCurrentCycle = false;
this.scheduleDataFiltering = function () {
if (scheduledForCurrentCycle) {
return;
}
gridScope.$evalAsync(function () {
scheduledForCurrentCycle = false;
_this.computeFilteredItems(gridScope);
});
scheduledForCurrentCycle = true;
};
if (!this.isInServerSideMode) {
var initCycle = true;
gridScope.$watchCollection("[" + "gridOptions.filterBy," + "gridOptions.filterByFields," + "gridOptions.orderBy," + "gridOptions.orderByReverse," + "gridOptions.pageItems" + "]", function (newValue, oldValue) {
if (initCycle) {
initCycle = false;
}
else {
// any of these values will reset the current page
_this.gridOptions.currentPage = 0;
_this.scheduleDataFiltering();
}
});
gridScope.$watch("gridOptions.currentPage", function (newValue, oldValue) {
if (newValue !== oldValue) {
{
_this.scheduleDataFiltering();
}
}
});
}
};
GridController.prototype.setupDataFormattingTriggers = function (gridScope) {
var _this = this;
var scheduledForCurrentCycle = false;
this.scheduleDataFormatting = function () {
if (scheduledForCurrentCycle) {
return;
}
gridScope.$evalAsync(function () {
scheduledForCurrentCycle = false;
_this.computeFormattedItems(gridScope);
});
scheduledForCurrentCycle = true;
};
var watchExpression = "[gridOptions.items,gridOptions.gridColumnDefs.length";
angular.forEach(gridScope.gridOptions.gridColumnDefs, function (gridColumnDef) {
if (gridColumnDef.displayFormat && gridColumnDef.displayFormat[0] != '.') {
// watch the parameters
var displayfilters = gridColumnDef.displayFormat.split('|');
angular.forEach(displayfilters, function (displayFilter) {
var displayFilterParams = displayFilter.split(':');
if (displayFilterParams.length > 1) {
angular.forEach(displayFilterParams.slice(1), function (displayFilterParam) {
displayFilterParam = displayFilterParam.trim();
if (displayFilterParam && displayFilterParam !== "gridItem" && displayFilterParam !== "gridDisplayItem") {
watchExpression += "," + displayFilterParam;
}
});
}
});
}
});
watchExpression += "]";
TrNgGrid.debugMode && this.log("re-formatting is set to watch for changes in " + watchExpression);
gridScope.$watch(watchExpression, function () { return _this.scheduleDataFormatting(); }, true);
};
GridController.prototype.setupServerSideModeTriggers = function (gridScope) {
var _this = this;
if (this.isInServerSideMode) {
var dataRequestPromise = null;
var scheduledForCurrentCycle = false;
var fastNextSchedule = false;
var pageIndexResetRequired = false;
var cancelDataRequestPromise = function () {
if (dataRequestPromise) {
_this.$timeout.cancel(dataRequestPromise);
dataRequestPromise = null;
}
};
var retrieveDataCallback = function () {
TrNgGrid.debugMode && _this.log("Preparing to request data - server side mode");
cancelDataRequestPromise();
// queue the operations in the eval and apply async queues
// apply queue flush -> digest cycle -> async queue flush -> dirty checks/watcher -> end digest cycle
var requestData = function () {
gridScope.$applyAsync(function () {
scheduledForCurrentCycle = false;
try {
TrNgGrid.debugMode && _this.log("Requesting data - server side mode");
if (!_this.gridOptions.autoLoad)
_this.gridOptions.autoLoad = true;
else
_this.gridOptions.onDataRequired(_this.gridOptions);
}
catch (ex) {
TrNgGrid.debugMode && _this.log("Data retrieval failed " + ex);
throw ex;
}
});
};
if (pageIndexResetRequired) {
gridScope.$evalAsync(function () {
TrNgGrid.debugMode && _this.log("Resetting the page index - server side mode");
gridScope.gridOptions.currentPage = 0;
pageIndexResetRequired = false;
requestData();
});
}
else {
requestData();
}
};
this.scheduleServerSideModeDataRetrieval = function () {
if (scheduledForCurrentCycle) {
// it's gonna happen anyway, sooner than we expected
return;
}
cancelDataRequestPromise();
dataRequestPromise = _this.$timeout(function () {
dataRequestPromise = null;
scheduledForCurrentCycle = true;
retrieveDataCallback();
}, _this.gridOptions.onDataRequiredDelay, true);
if (fastNextSchedule) {
_this.speedUpServerSideModeDataRetrieval();
}
};
this.speedUpServerSideModeDataRetrieval = function ($event) {
if (!$event || $event.keyCode == 13) {
if (dataRequestPromise) {
// speed up the request
fastNextSchedule = false;
cancelDataRequestPromise();
scheduledForCurrentCycle = true;
retrieveDataCallback();
}
else {
fastNextSchedule = true;
}
}
};
// the current page must be monitored separately, as it's being adjusted by logic fired by various watchers
gridScope.$watch("gridOptions.currentPage", function (newValue, oldValue) {
if (newValue !== oldValue) {
{
TrNgGrid.debugMode && _this.log("Changes detected in the current page index in server-side mode. Scheduling data retrieval...");
_this.scheduleServerSideModeDataRetrieval();
}
}
});
var initCycle = true;
gridScope.$watchCollection("[" + "gridOptions.filterBy, " + "gridOptions.filterByFields, " + "gridOptions.orderBy, " + "gridOptions.orderByReverse, " + "gridOptions.pageItems" + "]", function (newValues, oldValues) {
if (initCycle) {
initCycle = false;
}
else {
// everything will reset the page index, with the exception of a page index change
if (_this.gridOptions.currentPage !== 0) {
// Update: turned off for the time being
// don't allow for a second data retrieval to occur for the change of page
//this.temporarilyIgnorePageIndexChangeForDataRetrievals = true;
TrNgGrid.debugMode && _this.log("Changes detected in parameters in server-side mode. Requesting a page index reset...");
pageIndexResetRequired = true;
}
TrNgGrid.debugMode && _this.log("Changes detected in parameters in server-side mode. Scheduling data retrieval...");
_this.scheduleServerSideModeDataRetrieval();
}
});
// as this is the first time, schedule an immediate retrieval of data
this.scheduleServerSideModeDataRetrieval();
this.speedUpServerSideModeDataRetrieval();
}
else {
// non server side mode => nothing to do
this.speedUpServerSideModeDataRetrieval = function ($event) {
};
}
gridScope.speedUpAsyncDataRetrieval = function ($event) { return _this.speedUpServerSideModeDataRetrieval($event); };
};
GridController.prototype.setupDataSelectionTriggers = function (gridScope) {
var _this = this;
// the new settings
gridScope.$watch("gridOptions.selectionMode", function (newValue, oldValue) {
if (newValue !== oldValue) {
switch (newValue) {
case SelectionMode[0 /* None */]:
_this.gridOptions.selectedItems.splice(0);
break;
case SelectionMode[1 /* SingleRow */]:
if (_this.gridOptions.selectedItems.length > 1) {
_this.gridOptions.selectedItems.splice(1);
}
break;
}
}
});
};
GridController.prototype.setColumnOptions = function (columnIndex, columnOptions) {
var originalOptions = this.gridOptions.gridColumnDefs[columnIndex];
if (!originalOptions) {
throw "Invalid grid column options found for column index " + columnIndex + ". Please report this error.";
}
// copy a couple of options onto the incoming set of options
columnOptions = angular.extend(columnOptions, originalOptions);
// replace the original options
this.gridOptions.gridColumnDefs[columnIndex] = columnOptions;
};
GridController.prototype.toggleSorting = function (propertyName) {
if (this.gridOptions.orderBy != propertyName) {
// the column has changed
this.gridOptions.orderBy = propertyName;
}
else {
// the sort direction has changed
this.gridOptions.orderByReverse = !this.gridOptions.orderByReverse;
}
this.speedUpServerSideModeDataRetrieval();
};
GridController.prototype.toggleItemSelection = function (filteredItems, item, $event) {
if (this.gridOptions.selectionMode === SelectionMode[0 /* None */])
return;
switch (this.gridOptions.selectionMode) {
case SelectionMode[3 /* MultiRowWithKeyModifiers */]:
if (!$event.ctrlKey && !$event.shiftKey && !$event.metaKey) {
// if neither key modifiers are pressed, clear the selection and start fresh
var itemIndex = this.gridOptions.selectedItems.indexOf(item);
this.gridOptions.selectedItems.splice(0);
if (itemIndex < 0) {
this.gridOptions.selectedItems.push(item);
}
}
else {
if ($event.ctrlKey || $event.metaKey) {
// the ctrl key deselects or selects the item
var itemIndex = this.gridOptions.selectedItems.indexOf(item);
if (itemIndex >= 0) {
this.gridOptions.selectedItems.splice(itemIndex, 1);
}
else {
this.gridOptions.selectedItems.push(item);
}
}
else if ($event.shiftKey) {
// clear undesired selections, if the styles are not applied
if (document.selection && document.selection.empty) {
document.selection.empty();
}
else if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
// the shift key will always select items from the last selected item
var firstItemIndex;
var lastSelectedItem = this.gridOptions.selectedItems[this.gridOptions.selectedItems.length - 1];
for (firstItemIndex = 0; firstItemIndex < filteredItems.length && filteredItems[firstItemIndex].$$_gridItem !== lastSelectedItem; firstItemIndex++)
;
if (firstItemIndex >= filteredItems.length) {
firstItemIndex = 0;
}
var lastItemIndex;
for (lastItemIndex = 0; lastItemIndex < filteredItems.length && filteredItems[lastItemIndex].$$_gridItem !== item; lastItemIndex++)
;
if (lastItemIndex >= filteredItems.length) {
throw "Invalid selection on a key modifier selection mode";
}
if (lastItemIndex < firstItemIndex) {
var tempIndex = firstItemIndex;
firstItemIndex = lastItemIndex;
lastItemIndex = tempIndex;
}
for (var currentItemIndex = firstItemIndex; currentItemIndex <= lastItemIndex; currentItemIndex++) {
var currentItem = filteredItems[currentItemIndex].$$_gridItem;
if (this.gridOptions.selectedItems.indexOf(currentItem) < 0) {
this.gridOptions.selectedItems.push(currentItem);
}
}
}
}
break;
case SelectionMode[1 /* SingleRow */]:
var itemIndex = this.gridOptions.selectedItems.indexOf(item);
this.gridOptions.selectedItems.splice(0);
if (itemIndex < 0) {
this.gridOptions.selectedItems.push(item);
}
break;
case SelectionMode[2 /* MultiRow */]:
var itemIndex = this.gridOptions.selectedItems.indexOf(item);
if (itemIndex >= 0) {
this.gridOptions.selectedItems.splice(itemIndex, 1);
}
else {
this.gridOptions.selectedItems.push(item);
}
break;
}
};
GridController.prototype.discoverTemplates = function (gridElement) {
this.templatedHeader = new TemplatedSection("thead", null, null, "th", cellHeaderDirectiveAttribute);
this.templatedBody = new TemplatedSection("tbody", bodyDirectiveAttribute, null, "td", cellBodyDirectiveAttribute);
this.templatedFooter = new TemplatedSection("tfoot", null, null, "td", cellFooterDirectiveAttribute);
this.templatedHeader.discoverTemplates(gridElement);
this.templatedFooter.discoverTemplates(gridElement);
this.templatedBody.discoverTemplates(gridElement);
};
GridController.prototype.getSafeFieldName = function (fieldName) {
return fieldName.replace(/[^a-zA-Z]/g, "_");
};
GridController.prototype.configureTableStructure = function (parentScope, gridElement, oldScope) {
var _this = this;
try {
gridElement.empty();
if (oldScope) {
// not allowed to destroy the old scope in the same cycle
var scopeToBeDestroyed = oldScope;
this.$timeout(function () {
scopeToBeDestroyed.$destroy();
});
oldScope = null;
}
var scope = parentScope.$new();
// make sure we're no longer watching for column defs
if (this.columnDefsItemsWatcherDeregistration) {
this.columnDefsItemsWatcherDeregistration();
this.columnDefsItemsWatcherDeregistration = null;
}
if (this.columnDefsFieldsWatcherDeregistration) {
this.columnDefsFieldsWatcherDeregistration();
this.columnDefsFieldsWatcherDeregistration = null;
}
// watch for a change in field values
// don't be tempted to use watchcollection, it always returns same values which can't be compared
// https://github.com/angular/angular.js/issues/2621
// which causes us the recompile even if we don't have to
this.columnDefsFieldsWatcherDeregistration = scope.$watch("gridOptions.fields", function (newValue, oldValue) {
if (!angular.equals(newValue, oldValue)) {
_this.configureTableStructure(parentScope, gridElement, scope);
}
}, true);
// prepare a partial list of column definitions
var templatedHeaderPartialGridColumnDefs = this.templatedHeader.extractPartialColumnDefinitions();
var templatedBodyPartialGridColumnDefs = this.templatedBody.extractPartialColumnDefinitions();
var templatedFooterPartialGridColumnDefs = this.templatedFooter.extractPartialColumnDefinitions();
var finalPartialGridColumnDefs = [];
var fieldsEnforced = this.gridOptions.fields;
if (fieldsEnforced) {
// the fields bound to the options will take precedence
angular.forEach(this.gridOptions.fields, function (fieldName) {
if (fieldName) {
finalPartialGridColumnDefs.push({
isStandardColumn: true,
fieldName: fieldName
});
}
});
finalPartialGridColumnDefs = combineGridCellInfos(finalPartialGridColumnDefs, templatedHeaderPartialGridColumnDefs, false, true);
finalPartialGridColumnDefs = combineGridCellInfos(finalPartialGridColumnDefs, templatedBodyPartialGridColumnDefs, false, true);
}
else {
// check for the header markup
if (templatedHeaderPartialGridColumnDefs.length > 0) {
// header and body will be used for fishing out the field names
finalPartialGridColumnDefs = combineGridCellInfos(templatedHeaderPartialGridColumnDefs, templatedBodyPartialGridColumnDefs, true, true);
}
else {
// the object itself will provide the field names
if (!this.gridOptions.items || this.gridOptions.items.length == 0) {
// register our interest for when we do have something to look at
this.columnDefsItemsWatcherDeregistration = scope.$watch("gridOptions.items.length", function (newValue, oldValue) {
if (newValue) {
_this.configureTableStructure(parentScope, gridElement, scope);
}
});
return;
}
for (var propName in this.gridOptions.items[0]) {
{
finalPartialGridColumnDefs.push({
isStandardColumn: true,
fieldName: propName
});
}
}
// combine with the body template
finalPartialGridColumnDefs = combineGridCellInfos(finalPartialGridColumnDefs, templatedBodyPartialGridColumnDefs, true, true);
}
}
// it's time to make final tweaks to the instances and recompile
if (templatedFooterPartialGridColumnDefs.length == 0) {
templatedFooterPartialGridColumnDefs.push({ isStandardColumn: true });
}
// compute the formatted field names and field exctraction expressions
angular.forEach(finalPartialGridColumnDefs, function (columnDefs) {
if (columnDefs.fieldName) {
var fieldName = columnDefs.fieldName;
columnDefs.displayFieldName = _this.getSafeFieldName(fieldName);
// create the field extraction expression
// cope with special symbols in the field name (e.g. @), also for the accepted notations (. or [])
var fieldExtractionExpression;
if (fieldName[0] === "[") {
fieldExtractionExpression = fieldName;
}
else {
// go ahead with the wrapping (e.g. transform field.child.extrachild[0] into [field].child.extrachild[0])
fieldExtractionExpression = fieldName.replace(/^([^\.]+)/g, "\[\"$1\"]");
}
columnDefs.fieldExtractionExpression = fieldExtractionExpression;
}
});
this.gridOptions.gridColumnDefs = finalPartialGridColumnDefs;
var headerElement = this.templatedHeader.configureSection(gridElement, finalPartialGridColumnDefs);
var footerElement = this.templatedFooter.configureSection(gridElement, templatedFooterPartialGridColumnDefs);
var bodyElement = this.templatedBody.configureSection(gridElement, finalPartialGridColumnDefs);
var templatedBodyRowElement = this.templatedBody.getTemplatedRowElement(bodyElement);
var templatedHeaderRowElement = this.templatedHeader.getTemplatedRowElement(headerElement);
bodyElement.attr(bodyDirectiveAttribute, "");
templatedBodyRowElement.attr("ng-click", "toggleItemSelection(gridItem, $event)");
templatedBodyRowElement.attr("ng-repeat", "gridDisplayItem in filteredItems");
templatedBodyRowElement.attr("ng-init", "gridItem=gridDisplayItem.$$_gridItem;" + templatedBodyRowElement.attr("ng-init"));
// insert our classes in there. watch out for an existing attribute
// this is not properly handled, but it will be refactored in the next major version
var ngClassValue = templatedBodyRowElement.attr("ng-class");
ngClassValue = (ngClassValue || "").replace(/^(\s*\{?)(.*?)(\}?\s*)$/, "{'" + TrNgGrid.rowSelectedCssClass + "':gridOptions.selectedItems.indexOf(gridItem) >= 0" + ", $2}");
templatedBodyRowElement.attr("ng-class", ngClassValue);
this.$compile(headerElement)(scope);
this.$compile(footerElement)(scope);
this.$compile(bodyElement)(scope);
}
catch (ex) {
TrNgGrid.debugMode && this.log("Fixing table structure failed with error " + ex);
throw ex;
}
};
GridController.prototype.computeFormattedItems = function (scope) {
var input = scope.gridOptions.items || [];
TrNgGrid.debugMode && this.log("formatting items of length " + input.length);
try {
var formattedItems = scope.formattedItems = (scope.formattedItems || []);
var gridColumnDefs = scope.gridOptions.gridColumnDefs;
for (var inputIndex = 0; inputIndex < input.length; inputIndex++) {
var gridItem = input[inputIndex];
var outputItem;
// crate a temporary scope for holding a gridItem as we enumerate through the items
var localEvalVars = { gridItem: gridItem };
while (formattedItems.length > input.length && (outputItem = formattedItems[inputIndex]).$$_gridItem !== gridItem) {
formattedItems.splice(inputIndex, 1);
}
if (inputIndex < formattedItems.length) {
outputItem = formattedItems[inputIndex];
if (outputItem.$$_gridItem !== gridItem) {
outputItem = { $$_gridItem: gridItem };
formattedItems[inputIndex] = outputItem;
}
}
else {
outputItem = { $$_gridItem: gridItem };
formattedItems.push(outputItem);
}
for (var gridColumnDefIndex = 0; gridColumnDefIndex < gridColumnDefs.length; gridColumnDefIndex++) {
var fieldName;
try {
var gridColumnDef = gridColumnDefs[gridColumnDefIndex];
if (gridColumnDef.displayFieldName && gridColumnDef.fieldExtractionExpression) {
var displayFormat = gridColumnDef.displayFormat;
if (displayFormat) {
if (displayFormat[0] !== "." && displayFormat[0] !== "|" && displayFormat[0] !== "[") {
// angular filter
displayFormat = " | " + displayFormat;
}
}
outputItem[gridColumnDef.displayFieldName] = scope.$eval("gridItem" + gridColumnDef.fieldExtractionExpression + (displayFormat || ""), localEvalVars);
}
}
catch (ex) {
TrNgGrid.debugMode && this.log("Field evaluation failed for <" + (fieldName || "unknown") + "> with error " + ex);
}
}
}
// remove any extra elements from the formatted list
if (formattedItems.length > input.length) {
formattedItems.splice(input.length, formattedItems.length - input.length);
}
// trigger the filtering
this.scheduleDataFiltering();
}
catch (ex) {
TrNgGrid.debugMode && this.log("Failed to format items " + ex);
throw ex;
}
};
GridController.prototype.extractDataItems = function (formattedItems) {
// copy speed tests: https://jsperf.com/copy-loop-vs-array-slice/13
var dataItems;
if (formattedItems) {
dataItems = new Array(formattedItems.length);
for (var index = 0; index < formattedItems.length; index++) {
dataItems[index] = formattedItems[index].$$_gridItem;
}
}
else {
dataItems = [];
}
return dataItems;
};
GridController.prototype.computeFilteredItems = function (scope) {
try {
if (this.isInServerSideMode) {
// when server side data queries are active, bypass filtering and paging
scope.filteredItems = scope.formattedItems;
}
else {
// apply filters first
scope.filterByDisplayFields = {};
if (scope.gridOptions.filterByFields) {
for (var fieldName in scope.gridOptions.filterByFields) {
scope.filterByDisplayFields[this.getSafeFieldName(fieldName)] = scope.gridOptions.filterByFields[fieldName];
}
}
TrNgGrid.debugMode && this.log("filtering items of length " + (scope.formattedItems ? scope.formattedItems.length : 0));
scope.filteredItems = scope.$eval("formattedItems | filter:gridOptions.filterBy | filter:filterByDisplayFields | " + TrNgGrid.sortFilter + ":gridOptions");
// check if anyone is interested in the filtered items
if (scope.gridOptions.filteredItems) {
scope.gridOptions.filteredItems = this.extractDataItems(scope.filteredItems);
}
// proceed with paging
scope.filteredItems = scope.$eval("filteredItems | " + TrNgGrid.dataPagingFilter + ":gridOptions");
}
// check if anyone is interested in the items on the current page
if (scope.gridOptions.filteredItemsPage) {
scope.gridOptions.filteredItemsPage = this.extractDataItems(scope.filteredItems);
}
}
catch (ex) {
TrNgGrid.debugMode && this.log("Failed to filter items " + ex);
throw ex;
}
};
GridController.prototype.linkAttrs = function (tAttrs, localStorage) {
var propSetter = function (propName, propValue) {
if (typeof (propValue) === "undefined")
return;
switch (propValue) {
case "true":
propValue = true;
break;
case "false":
propValue = false;
break;
}
localStorage[propName] = propValue;
};
for (var propName in localStorage) {
propSetter(propName, tAttrs[propName]);
// watch for changes
(function (propName) {
tAttrs.$observe(propName, function (value) { return propSetter(propName, value); });
})(propName);
}
};
GridController.prototype.log = function (message) {
console.log(tableDirective + "(" + new Date().getTime() + "): " + message);
};
return GridController;
})();
angular.module("trNgGrid", []).directive(tableDirective, [
function () {
return {
restrict: 'A',
scope: {
items: '=',
selectedItems: '=?',
filteredItems: '=?',
filteredItemsPage: '=?',
filterBy: '=?',
filterByFields: '=?',
orderBy: '=?',
orderByReverse: '=?',
pageItems: '=?',
currentPage: '=?',
totalItems: '=?',
autoLoad: '=?',
enableFiltering: '=?',
enableSorting: '=?',
selectionMode: '@',
locale: '@',
onDataRequired: '&',
onDataRequiredDelay: '=?',
fields: '=?'
},
controller: ["$compile", "$parse", "$timeout", "$templateCache", GridController],
compile: function (templateElement, tAttrs) {
// at this stage, no elements can be bound
angular.forEach(templateElement.children(), function (childElement) {
childElement = angular.element(childElement);
childElement.attr("ng-non-bindable", "");
});
return {
pre: function (isolatedScope, instanceElement, tAttrs, controller, transcludeFn) {
controller.discoverTemplates(instanceElement);
},
post: function (isolatedScope, instanceElement, tAttrs, controller, transcludeFn) {
instanceElement.addClass(TrNgGrid.tableCssClass);
//var gridScope = controller.setupScope(isolatedScope, instanceElement, tAttrs);
var gridScope = isolatedScope.$parent.$new();
controller.setupGrid(gridScope, isolatedScope, !!tAttrs.onDataRequired);
controller.configureTableStructure(gridScope, instanceElement);
isolatedScope.$on("$destroy", function () {
gridScope.$destroy();
TrNgGrid.debugMode && controller.log("grid scope destroyed");
});
}
};
}
};
}
]).directive(cellHeaderDirective, [
function () {
var setupColumnTitle = function (scope) {
if (scope.columnOptions.displayName) {
scope.columnTitle = scope.columnOptions.displayName;
}
else if (scope.columnOptions.fieldName) {
// exclude nested notations and invalid letters
var rawTitle = scope.columnOptions.fieldName.replace(/^([^\a-zA-Z]*)([\a-zA-Z]*)(.*)/g, "$2"); // take just the first part
// split by camel-casing
var splitTitleName = rawTitle.split(/(?=[A-Z])/);
if (splitTitleName.length && splitTitleName[0].length) {
splitTitleName[0] = splitTitleName[0][0].toLocaleUpperCase() + splitTitleName[0].substr(1);
}
scope.columnTitle = splitTitleName.join(" ");
}
else {
scope.columnTitle = "";
}
};
return {
restrict: 'A',
require: '^' + tableDirective,
scope: true,
compile: function (templateElement, tAttrs) {
var isCustomized = tAttrs['isCustomized'] == 'true';
wrapTemplatedCell(templateElement, tAttrs, isCustomized, cellHeaderTemplateDirectiveAttribute);
return {
// we receive a reference to a real element that will appear in the DOM, after the controller was created, but before binding setup
pre: function (scope, instanceElement, tAttrs, controller, $transclude) {
// we're not interested in creating an isolated scope just to parse the element attributes,
// so we're gonna have to do this manually
var columnIndex = parseInt(tAttrs[cellHeaderDirective]);
// create a clone of the default column options
var columnOptions = angular.extend(scope.gridOptions.gridColumnDefs[columnIndex], TrNgGrid.defaultColumnOptionsTemplate, TrNgGrid.defaultColumnOptions);
// now match and observe the attributes
controller.linkAttrs(tAttrs, columnOptions);
// set up the new scope
scope.columnOptions = columnOptions;
scope.isCustomized = isCustomized;
scope.toggleSorting = function (propertyName) {
controller.toggleSorting(propertyName);
};
// set up the column title
scope.$watch("columnOptions.displayName", function () {
setupColumnTitle(scope);
});
// set up the filter
// field names starting with $ are ignored by angular in watchers
// https://github.com/angular/angular.js/issues/4581
var isWatchingColumnFilter = false;
scope.$watch("gridOptions.filterByFields['" + columnOptions.fieldName + "']", function (newFilterValue, oldFilterValue) {
if (columnOptions.filter !== newFilterValue) {
columnOptions.filter = newFilterValue;
}
if (!isWatchingColumnFilter) {
scope.$watch("columnOptions.filter", function (newFilterValue, oldFilterValue) {
if (scope.gridOptions.filterByFields[columnOptions.fieldName] !== newFilterValue) {
if (!newFilterValue) {
delete (scope.gridOptions.filterByFields[columnOptions.fieldName]);
}
else {
scope.gridOptions.filterByFields[columnOptions.fieldName] = newFilterValue;
}
// in order for someone to successfully listen for shallow changes, we need to replace it
scope.gridOptions.filterByFields = angular.extend({}, scope.gridOptions.filterByFields);
}
});
isWatchingColumnFilter = true;
}
});
}
};
}
};