-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Grid.js
2082 lines (1739 loc) · 66.9 KB
/
Grid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(){
angular.module('ui.grid')
.factory('Grid', ['$q', '$compile', '$parse', 'gridUtil', 'uiGridConstants', 'GridOptions', 'GridColumn', 'GridRow', 'GridApi', 'rowSorter', 'rowSearcher', 'GridRenderContainer', '$timeout',
function($q, $compile, $parse, gridUtil, uiGridConstants, GridOptions, GridColumn, GridRow, GridApi, rowSorter, rowSearcher, GridRenderContainer, $timeout) {
/**
* @ngdoc object
* @name ui.grid.core.api:PublicApi
* @description Public Api for the core grid features
*
*/
/**
* @ngdoc function
* @name ui.grid.class:Grid
* @description Grid is the main viewModel. Any properties or methods needed to maintain state are defined in
* this prototype. One instance of Grid is created per Grid directive instance.
* @param {object} options Object map of options to pass into the grid. An 'id' property is expected.
*/
var Grid = function Grid(options) {
var self = this;
// Get the id out of the options, then remove it
if (options !== undefined && typeof(options.id) !== 'undefined' && options.id) {
if (!/^[_a-zA-Z0-9-]+$/.test(options.id)) {
throw new Error("Grid id '" + options.id + '" is invalid. It must follow CSS selector syntax rules.');
}
}
else {
throw new Error('No ID provided. An ID must be given when creating a grid.');
}
self.id = options.id;
delete options.id;
// Get default options
self.options = GridOptions.initialize( options );
/**
* @ngdoc object
* @name appScope
* @propertyOf ui.grid.class:Grid
* @description reference to the application scope (the parent scope of the ui-grid element). Assigned in ui-grid controller
* <br/>
* use gridOptions.appScopeProvider to override the default assignment of $scope.$parent with any reference
*/
self.appScope = self.options.appScopeProvider;
self.headerHeight = self.options.headerRowHeight;
self.footerHeight = self.calcFooterHeight();
self.rtl = false;
self.gridHeight = 0;
self.gridWidth = 0;
self.columnBuilders = [];
self.rowBuilders = [];
self.rowsProcessors = [];
self.columnsProcessors = [];
self.styleComputations = [];
self.viewportAdjusters = [];
self.rowHeaderColumns = [];
self.dataChangeCallbacks = {};
// self.visibleRowCache = [];
// Set of 'render' containers for self grid, which can render sets of rows
self.renderContainers = {};
// Create a
self.renderContainers.body = new GridRenderContainer('body', self);
self.cellValueGetterCache = {};
// Cached function to use with custom row templates
self.getRowTemplateFn = null;
//representation of the rows on the grid.
//these are wrapped references to the actual data rows (options.data)
self.rows = [];
//represents the columns on the grid
self.columns = [];
/**
* @ngdoc boolean
* @name isScrollingVertically
* @propertyOf ui.grid.class:Grid
* @description set to true when Grid is scrolling vertically. Set to false via debounced method
*/
self.isScrollingVertically = false;
/**
* @ngdoc boolean
* @name isScrollingHorizontally
* @propertyOf ui.grid.class:Grid
* @description set to true when Grid is scrolling horizontally. Set to false via debounced method
*/
self.isScrollingHorizontally = false;
/**
* @ngdoc property
* @name scrollDirection
* @propertyOf ui.grid.class:Grid
* @description set one of the uiGridConstants.scrollDirection values (UP, DOWN, LEFT, RIGHT, NONE), which tells
* us which direction we are scrolling. Set to NONE via debounced method
*/
self.scrollDirection = uiGridConstants.scrollDirection.NONE;
var debouncedVertical = gridUtil.debounce(function () {
self.isScrollingVertically = false;
self.scrollDirection = uiGridConstants.scrollDirection.NONE;
}, 1000);
var debouncedHorizontal = gridUtil.debounce(function () {
self.isScrollingHorizontally = false;
self.scrollDirection = uiGridConstants.scrollDirection.NONE;
}, 1000);
/**
* @ngdoc function
* @name flagScrollingVertically
* @methodOf ui.grid.class:Grid
* @description sets isScrollingVertically to true and sets it to false in a debounced function
*/
self.flagScrollingVertically = function() {
self.isScrollingVertically = true;
debouncedVertical();
};
/**
* @ngdoc function
* @name flagScrollingHorizontally
* @methodOf ui.grid.class:Grid
* @description sets isScrollingHorizontally to true and sets it to false in a debounced function
*/
self.flagScrollingHorizontally = function() {
self.isScrollingHorizontally = true;
debouncedHorizontal();
};
self.scrollbarHeight = 0;
self.scrollbarWidth = 0;
if (self.options.enableHorizontalScrollbar === uiGridConstants.scrollbars.ALWAYS) {
self.scrollbarHeight = gridUtil.getScrollbarWidth();
}
if (self.options.enableVerticalScrollbar === uiGridConstants.scrollbars.ALWAYS) {
self.scrollbarWidth = gridUtil.getScrollbarWidth();
}
self.api = new GridApi(self);
/**
* @ngdoc function
* @name refresh
* @methodOf ui.grid.core.api:PublicApi
* @description Refresh the rendered grid on screen.
*
*/
self.api.registerMethod( 'core', 'refresh', this.refresh );
/**
* @ngdoc function
* @name refreshRows
* @methodOf ui.grid.core.api:PublicApi
* @description Refresh the rendered grid on screen? Note: not functional at present
* @returns {promise} promise that is resolved when render completes?
*
*/
self.api.registerMethod( 'core', 'refreshRows', this.refreshRows );
/**
* @ngdoc function
* @name handleWindowResize
* @methodOf ui.grid.core.api:PublicApi
* @description Trigger a grid resize, normally this would be picked
* up by a watch on window size, but in some circumstances it is necessary
* to call this manually
* @returns {promise} promise that is resolved when render completes?
*
*/
self.api.registerMethod( 'core', 'handleWindowResize', this.handleWindowResize );
/**
* @ngdoc function
* @name addRowHeaderColumn
* @methodOf ui.grid.core.api:PublicApi
* @description adds a row header column to the grid
* @param {object} column def
*
*/
self.api.registerMethod( 'core', 'addRowHeaderColumn', this.addRowHeaderColumn );
/**
* @ngdoc function
* @name sortHandleNulls
* @methodOf ui.grid.core.api:PublicApi
* @description A null handling method that can be used when building custom sort
* functions
* @example
* <pre>
* mySortFn = function(a, b) {
* var nulls = $scope.gridApi.core.sortHandleNulls(a, b);
* if ( nulls !== null ){
* return nulls;
* } else {
* // your code for sorting here
* };
* </pre>
* @param {object} a sort value a
* @param {object} b sort value b
* @returns {number} null if there were no nulls/undefineds, otherwise returns
* a sort value that should be passed back from the sort function
*
*/
self.api.registerMethod( 'core', 'sortHandleNulls', rowSorter.handleNulls );
/**
* @ngdoc function
* @name sortChanged
* @methodOf ui.grid.core.api:PublicApi
* @description The sort criteria on one or more columns has
* changed. Provides as parameters the grid and the output of
* getColumnSorting, which is an array of gridColumns
* that have sorting on them, sorted in priority order.
*
* @param {Grid} grid the grid
* @param {array} sortColumns an array of columns with
* sorts on them, in priority order
*
* @example
* <pre>
* gridApi.core.on.sortChanged( grid, sortColumns );
* </pre>
*/
self.api.registerEvent( 'core', 'sortChanged' );
/**
* @ngdoc function
* @name columnVisibilityChanged
* @methodOf ui.grid.core.api:PublicApi
* @description The visibility of a column has changed,
* the column itself is passed out as a parameter of the event.
*
* @param {GridCol} column the column that changed
*
* @example
* <pre>
* gridApi.core.on.columnVisibilityChanged( $scope, function (column) {
* // do something
* } );
* </pre>
*/
self.api.registerEvent( 'core', 'columnVisibilityChanged' );
/**
* @ngdoc method
* @name notifyDataChange
* @methodOf ui.grid.core.api:PublicApi
* @description Notify the grid that a data or config change has occurred,
* where that change isn't something the grid was otherwise noticing. This
* might be particularly relevant where you've changed values within the data
* and you'd like cell classes to be re-evaluated, or changed config within
* the columnDef and you'd like headerCellClasses to be re-evaluated.
* @param {string} type one of the
* uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN), which tells
* us which refreshes to fire.
*
*/
self.api.registerMethod( 'core', 'notifyDataChange', this.notifyDataChange );
self.registerDataChangeCallback( self.columnRefreshCallback, [uiGridConstants.dataChange.COLUMN]);
self.registerDataChangeCallback( self.processRowsCallback, [uiGridConstants.dataChange.EDIT]);
self.registerStyleComputation({
priority: 10,
func: self.getFooterStyles
});
};
Grid.prototype.calcFooterHeight = function () {
if (!this.hasFooter()) {
return 0;
}
var height = 0;
if (this.options.showGridFooter) {
height += this.options.gridFooterHeight;
}
if (this.options.showColumnFooter) {
height += this.options.columnFooterHeight;
}
return height;
};
Grid.prototype.getFooterStyles = function () {
var style = '.grid' + this.id + ' .ui-grid-footer-aggregates-row { height: ' + this.options.columnFooterHeight + 'px; }';
style += ' .grid' + this.id + ' .ui-grid-footer-info { height: ' + this.options.gridFooterHeight + 'px; }';
return style;
};
Grid.prototype.hasFooter = function () {
return this.options.showGridFooter || this.options.showColumnFooter;
};
/**
* @ngdoc function
* @name isRTL
* @methodOf ui.grid.class:Grid
* @description Returns true if grid is RightToLeft
*/
Grid.prototype.isRTL = function () {
return this.rtl;
};
/**
* @ngdoc function
* @name registerColumnBuilder
* @methodOf ui.grid.class:Grid
* @description When the build creates columns from column definitions, the columnbuilders will be called to add
* additional properties to the column.
* @param {function(colDef, col, gridOptions)} columnsProcessor function to be called
*/
Grid.prototype.registerColumnBuilder = function registerColumnBuilder(columnBuilder) {
this.columnBuilders.push(columnBuilder);
};
/**
* @ngdoc function
* @name buildColumnDefsFromData
* @methodOf ui.grid.class:Grid
* @description Populates columnDefs from the provided data
* @param {function(colDef, col, gridOptions)} rowBuilder function to be called
*/
Grid.prototype.buildColumnDefsFromData = function (dataRows){
this.options.columnDefs = gridUtil.getColumnsFromData(dataRows, this.options.excludeProperties);
};
/**
* @ngdoc function
* @name registerRowBuilder
* @methodOf ui.grid.class:Grid
* @description When the build creates rows from gridOptions.data, the rowBuilders will be called to add
* additional properties to the row.
* @param {function(row, gridOptions)} rowBuilder function to be called
*/
Grid.prototype.registerRowBuilder = function registerRowBuilder(rowBuilder) {
this.rowBuilders.push(rowBuilder);
};
/**
* @ngdoc function
* @name registerDataChangeCallback
* @methodOf ui.grid.class:Grid
* @description When a data change occurs, the data change callbacks of the specified type
* will be called. The rules are:
*
* - when the data watch fires, that is considered a ROW change (the data watch only notices
* added or removed rows)
* - when the api is called to inform us of a change, the declared type of that change is used
* - when a cell edit completes, the EDIT callbacks are triggered
* - when the columnDef watch fires, the COLUMN callbacks are triggered
* - when the options watch fires, the OPTIONS callbacks are triggered
*
* For a given event:
* - ALL calls ROW, EDIT, COLUMN, OPTIONS and ALL callbacks
* - ROW calls ROW and ALL callbacks
* - EDIT calls EDIT and ALL callbacks
* - COLUMN calls COLUMN and ALL callbacks
* - OPTIONS calls OPTIONS and ALL callbacks
*
* @param {function(grid)} callback function to be called
* @param {array} types the types of data change you want to be informed of. Values from
* the uiGridConstants.dataChange values ( ALL, EDIT, ROW, COLUMN, OPTIONS ). Optional and defaults to
* ALL
* @returns {function} deregister function - a function that can be called to deregister this callback
*/
Grid.prototype.registerDataChangeCallback = function registerDataChangeCallback(callback, types, _this) {
var uid = gridUtil.nextUid();
if ( !types ){
types = [uiGridConstants.dataChange.ALL];
}
if ( !Array.isArray(types)){
gridUtil.logError("Expected types to be an array or null in registerDataChangeCallback, value passed was: " + types );
}
this.dataChangeCallbacks[uid] = { callback: callback, types: types, _this:_this };
var self = this;
var deregisterFunction = function() {
delete self.dataChangeCallbacks[uid];
};
return deregisterFunction;
};
/**
* @ngdoc function
* @name callDataChangeCallbacks
* @methodOf ui.grid.class:Grid
* @description Calls the callbacks based on the type of data change that
* has occurred. Always calls the ALL callbacks, calls the ROW, EDIT, COLUMN and OPTIONS callbacks if the
* event type is matching, or if the type is ALL.
* @param {number} type the type of event that occurred - one of the
* uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN, OPTIONS)
*/
Grid.prototype.callDataChangeCallbacks = function callDataChangeCallbacks(type, options) {
angular.forEach( this.dataChangeCallbacks, function( callback, uid ){
if ( callback.types.indexOf( uiGridConstants.dataChange.ALL ) !== -1 ||
callback.types.indexOf( type ) !== -1 ||
type === uiGridConstants.dataChange.ALL ) {
if (callback._this) {
callback.callback.apply(callback._this,this);
}
else {
callback.callback( this );
}
}
}, this);
};
/**
* @ngdoc function
* @name notifyDataChange
* @methodOf ui.grid.class:Grid
* @description Notifies us that a data change has occurred, used in the public
* api for users to tell us when they've changed data or some other event that
* our watches cannot pick up
* @param {string} type the type of event that occurred - one of the
* uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN)
*/
Grid.prototype.notifyDataChange = function notifyDataChange(type) {
var constants = uiGridConstants.dataChange;
if ( type === constants.ALL ||
type === constants.COLUMN ||
type === constants.EDIT ||
type === constants.ROW ||
type === constants.OPTIONS ){
this.callDataChangeCallbacks( type );
} else {
gridUtil.logError("Notified of a data change, but the type was not recognised, so no action taken, type was: " + type);
}
};
/**
* @ngdoc function
* @name columnRefreshCallback
* @methodOf ui.grid.class:Grid
* @description refreshes the grid when a column refresh
* is notified, which triggers handling of the visible flag.
* This is called on uiGridConstants.dataChange.COLUMN, and is
* registered as a dataChangeCallback in grid.js
* @param {string} name column name
*/
Grid.prototype.columnRefreshCallback = function columnRefreshCallback( grid ){
grid.buildColumns();
grid.refresh();
};
/**
* @ngdoc function
* @name processRowsCallback
* @methodOf ui.grid.class:Grid
* @description calls the row processors, specifically
* intended to reset the sorting when an edit is called,
* registered as a dataChangeCallback on uiGridConstants.dataChange.EDIT
* @param {string} name column name
*/
Grid.prototype.processRowsCallback = function processRowsCallback( grid ){
grid.refreshRows();
};
/**
* @ngdoc function
* @name getColumn
* @methodOf ui.grid.class:Grid
* @description returns a grid column for the column name
* @param {string} name column name
*/
Grid.prototype.getColumn = function getColumn(name) {
var columns = this.columns.filter(function (column) {
return column.colDef.name === name;
});
return columns.length > 0 ? columns[0] : null;
};
/**
* @ngdoc function
* @name getColDef
* @methodOf ui.grid.class:Grid
* @description returns a grid colDef for the column name
* @param {string} name column.field
*/
Grid.prototype.getColDef = function getColDef(name) {
var colDefs = this.options.columnDefs.filter(function (colDef) {
return colDef.name === name;
});
return colDefs.length > 0 ? colDefs[0] : null;
};
/**
* @ngdoc function
* @name assignTypes
* @methodOf ui.grid.class:Grid
* @description uses the first row of data to assign colDef.type for any types not defined.
*/
/**
* @ngdoc property
* @name type
* @propertyOf ui.grid.class:GridOptions.columnDef
* @description the type of the column, used in sorting. If not provided then the
* grid will guess the type. Add this only if the grid guessing is not to your
* satisfaction. Refer to {@link ui.grid.service:GridUtil.guessType gridUtil.guessType} for
* a list of values the grid knows about.
*
*/
Grid.prototype.assignTypes = function(){
var self = this;
self.options.columnDefs.forEach(function (colDef, index) {
//Assign colDef type if not specified
if (!colDef.type) {
var col = new GridColumn(colDef, index, self);
var firstRow = self.rows.length > 0 ? self.rows[0] : null;
if (firstRow) {
colDef.type = gridUtil.guessType(self.getCellValue(firstRow, col));
}
else {
gridUtil.logWarn('Unable to assign type from data, so defaulting to string');
colDef.type = 'string';
}
}
});
};
/**
* @ngdoc function
* @name addRowHeaderColumn
* @methodOf ui.grid.class:Grid
* @description adds a row header column to the grid
* @param {object} column def
*/
Grid.prototype.addRowHeaderColumn = function addRowHeaderColumn(colDef) {
var self = this;
//self.createLeftContainer();
var rowHeaderCol = new GridColumn(colDef, self.rowHeaderColumns.length, self);
rowHeaderCol.isRowHeader = true;
if (self.isRTL()) {
self.createRightContainer();
rowHeaderCol.renderContainer = 'right';
}
else {
self.createLeftContainer();
rowHeaderCol.renderContainer = 'left';
}
// relies on the default column builder being first in array, as it is instantiated
// as part of grid creation
self.columnBuilders[0](colDef,rowHeaderCol,self.options)
.then(function(){
rowHeaderCol.enableFiltering = false;
rowHeaderCol.enableSorting = false;
rowHeaderCol.enableHiding = false;
self.rowHeaderColumns.push(rowHeaderCol);
self.buildColumns()
.then( function() {
self.preCompileCellTemplates();
self.refresh();
});
});
};
/**
* @ngdoc function
* @name buildColumns
* @methodOf ui.grid.class:Grid
* @description creates GridColumn objects from the columnDefinition. Calls each registered
* columnBuilder to further process the column
* @param {object} options An object contains options to use when building columns
*
* * **orderByColumnDefs**: defaults to **false**. When true, `buildColumns` will reorder existing columns according to the order within the column definitions.
*
* @returns {Promise} a promise to load any needed column resources
*/
Grid.prototype.buildColumns = function buildColumns(opts) {
var options = {
orderByColumnDefs: false
};
angular.extend(options, opts);
// gridUtil.logDebug('buildColumns');
var self = this;
var builderPromises = [];
var headerOffset = self.rowHeaderColumns.length;
var i;
// Remove any columns for which a columnDef cannot be found
// Deliberately don't use forEach, as it doesn't like splice being called in the middle
// Also don't cache columns.length, as it will change during this operation
for (i = 0; i < self.columns.length; i++){
if (!self.getColDef(self.columns[i].name)) {
self.columns.splice(i, 1);
i--;
}
}
//add row header columns to the grid columns array _after_ columns without columnDefs have been removed
self.rowHeaderColumns.forEach(function (rowHeaderColumn) {
self.columns.unshift(rowHeaderColumn);
});
// look at each column def, and update column properties to match. If the column def
// doesn't have a column, then splice in a new gridCol
self.options.columnDefs.forEach(function (colDef, index) {
self.preprocessColDef(colDef);
var col = self.getColumn(colDef.name);
if (!col) {
col = new GridColumn(colDef, gridUtil.nextUid(), self);
self.columns.splice(index + headerOffset, 0, col);
}
else {
// tell updateColumnDef that the column was pre-existing
col.updateColumnDef(colDef, false);
}
self.columnBuilders.forEach(function (builder) {
builderPromises.push(builder.call(self, colDef, col, self.options));
});
});
/*** Reorder columns if necessary ***/
if (!!options.orderByColumnDefs) {
// Create a shallow copy of the columns as a cache
var columnCache = self.columns.slice(0);
// We need to allow for the "row headers" when mapping from the column defs array to the columns array
// If we have a row header in columns[0] and don't account for it we'll overwrite it with the column in columnDefs[0]
// Go through all the column defs
for (i = 0; i < self.options.columnDefs.length; i++) {
// If the column at this index has a different name than the column at the same index in the column defs...
if (self.columns[i + headerOffset].name !== self.options.columnDefs[i].name) {
// Replace the one in the cache with the appropriate column
columnCache[i + headerOffset] = self.getColumn(self.options.columnDefs[i].name);
}
else {
// Otherwise just copy over the one from the initial columns
columnCache[i + headerOffset] = self.columns[i + headerOffset];
}
}
// Empty out the columns array, non-destructively
self.columns.length = 0;
// And splice in the updated, ordered columns from the cache
Array.prototype.splice.apply(self.columns, [0, 0].concat(columnCache));
}
return $q.all(builderPromises).then(function(){
if (self.rows.length > 0){
self.assignTypes();
}
});
};
/**
* @ngdoc function
* @name preCompileCellTemplates
* @methodOf ui.grid.class:Grid
* @description precompiles all cell templates
*/
Grid.prototype.preCompileCellTemplates = function() {
var self = this;
this.columns.forEach(function (col) {
var html = col.cellTemplate.replace(uiGridConstants.MODEL_COL_FIELD, self.getQualifiedColField(col));
html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
var compiledElementFn = $compile(html);
col.compiledElementFn = compiledElementFn;
if (col.compiledElementFnDefer) {
col.compiledElementFnDefer.resolve(col.compiledElementFn);
}
});
};
/**
* @ngdoc function
* @name getGridQualifiedColField
* @methodOf ui.grid.class:Grid
* @description Returns the $parse-able accessor for a column within its $scope
* @param {GridColumn} col col object
*/
Grid.prototype.getQualifiedColField = function (col) {
return 'row.entity.' + gridUtil.preEval(col.field);
};
/**
* @ngdoc function
* @name createLeftContainer
* @methodOf ui.grid.class:Grid
* @description creates the left render container if it doesn't already exist
*/
Grid.prototype.createLeftContainer = function() {
if (!this.hasLeftContainer()) {
this.renderContainers.left = new GridRenderContainer('left', this, { disableColumnOffset: true });
}
};
/**
* @ngdoc function
* @name createRightContainer
* @methodOf ui.grid.class:Grid
* @description creates the right render container if it doesn't already exist
*/
Grid.prototype.createRightContainer = function() {
if (!this.hasRightContainer()) {
this.renderContainers.right = new GridRenderContainer('right', this, { disableColumnOffset: true });
}
};
/**
* @ngdoc function
* @name hasLeftContainer
* @methodOf ui.grid.class:Grid
* @description returns true if leftContainer exists
*/
Grid.prototype.hasLeftContainer = function() {
return this.renderContainers.left !== undefined;
};
/**
* @ngdoc function
* @name hasLeftContainer
* @methodOf ui.grid.class:Grid
* @description returns true if rightContainer exists
*/
Grid.prototype.hasRightContainer = function() {
return this.renderContainers.right !== undefined;
};
/**
* undocumented function
* @name preprocessColDef
* @methodOf ui.grid.class:Grid
* @description defaults the name property from field to maintain backwards compatibility with 2.x
* validates that name or field is present
*/
Grid.prototype.preprocessColDef = function preprocessColDef(colDef) {
var self = this;
if (!colDef.field && !colDef.name) {
throw new Error('colDef.name or colDef.field property is required');
}
//maintain backwards compatibility with 2.x
//field was required in 2.x. now name is required
if (colDef.name === undefined && colDef.field !== undefined) {
// See if the column name already exists:
var foundName = self.getColumn(colDef.field);
// If a column with this name already exists, we will add an incrementing number to the end of the new column name
if (foundName) {
// Search through the columns for names in the format: <name><1, 2 ... N>, i.e. 'Age1, Age2, Age3',
var nameRE = new RegExp('^' + colDef.field + '(\\d+)$', 'i');
var foundColumns = self.columns.filter(function (column) {
// Test against the displayName, as that's what'll have the incremented number
return nameRE.test(column.displayName);
})
// Sort the found columns by the end-number
.sort(function (a, b) {
if (a === b) {
return 0;
}
else {
var numA = a.match(nameRE)[1];
var numB = b.match(nameRE)[1];
return parseInt(numA, 10) > parseInt(numB, 10) ? 1 : -1;
}
});
// Not columns found, so start with number "2"
if (foundColumns.length === 0) {
colDef.name = colDef.field + '2';
}
else {
// Get the number from the final column
var lastNum = foundColumns[foundColumns.length-1].displayName.match(nameRE)[1];
// Make sure to parse to an int
lastNum = parseInt(lastNum, 10);
// Add 1 to the number from the last column and tack it on to the field to be the name for this new column
colDef.name = colDef.field + (lastNum + 1);
}
}
// ... otherwise just use the field as the column name
else {
colDef.name = colDef.field;
}
}
};
// Return a list of items that exist in the `n` array but not the `o` array. Uses optional property accessors passed as third & fourth parameters
Grid.prototype.newInN = function newInN(o, n, oAccessor, nAccessor) {
var self = this;
var t = [];
for (var i = 0; i < n.length; i++) {
var nV = nAccessor ? n[i][nAccessor] : n[i];
var found = false;
for (var j = 0; j < o.length; j++) {
var oV = oAccessor ? o[j][oAccessor] : o[j];
if (self.options.rowEquality(nV, oV)) {
found = true;
break;
}
}
if (!found) {
t.push(nV);
}
}
return t;
};
/**
* @ngdoc function
* @name getRow
* @methodOf ui.grid.class:Grid
* @description returns the GridRow that contains the rowEntity
* @param {object} rowEntity the gridOptions.data array element instance
*/
Grid.prototype.getRow = function getRow(rowEntity) {
var self = this;
var rows = this.rows.filter(function (row) {
return self.options.rowEquality(row.entity, rowEntity);
});
return rows.length > 0 ? rows[0] : null;
};
/**
* @ngdoc function
* @name modifyRows
* @methodOf ui.grid.class:Grid
* @description creates or removes GridRow objects from the newRawData array. Calls each registered
* rowBuilder to further process the row
*
* Rows are identified using the gridOptions.rowEquality function
*/
Grid.prototype.modifyRows = function modifyRows(newRawData) {
var self = this,
i,
rowhash,
found,
newRow;
if ((self.options.useExternalSorting || self.getColumnSorting().length === 0) && newRawData.length > 0) {
var oldRowHash = self.rowHashMap;
if (!oldRowHash) {
oldRowHash = {get: function(){return null;}};
}
self.createRowHashMap();
rowhash = self.rowHashMap;
var wasEmpty = self.rows.length === 0;
self.rows.length = 0;
for (i = 0; i < newRawData.length; i++) {
var newRawRow = newRawData[i];
found = oldRowHash.get(newRawRow);
if (found) {
newRow = found.row;
}
else {
newRow = self.processRowBuilders(new GridRow(newRawRow, i, self));
}
self.rows.push(newRow);
rowhash.put(newRawRow, {
i: i,
entity: newRawRow,
row:newRow
});
}
//now that we have data, it is save to assign types to colDefs
// if (wasEmpty) {
self.assignTypes();
// }
} else {
if (self.rows.length === 0 && newRawData.length > 0) {
if (self.options.enableRowHashing) {
if (!self.rowHashMap) {
self.createRowHashMap();
}
for (i = 0; i < newRawData.length; i++) {
newRow = newRawData[i];
self.rowHashMap.put(newRow, {
i: i,
entity: newRow
});
}
}
self.addRows(newRawData);
//now that we have data, it is save to assign types to colDefs
self.assignTypes();
}
else if (newRawData.length > 0) {
var unfoundNewRows, unfoundOldRows, unfoundNewRowsToFind;
// If row hashing is turned on
if (self.options.enableRowHashing) {
// Array of new rows that haven't been found in the old rowset
unfoundNewRows = [];
// Array of new rows that we explicitly HAVE to search for manually in the old row set. They cannot be looked up by their identity (because it doesn't exist).
unfoundNewRowsToFind = [];
// Map of rows that have been found in the new rowset
var foundOldRows = {};
// Array of old rows that have NOT been found in the new rowset
unfoundOldRows = [];
// Create the row HashMap if it doesn't exist already
if (!self.rowHashMap) {
self.createRowHashMap();
}
rowhash = self.rowHashMap;
// Make sure every new row has a hash
for (i = 0; i < newRawData.length; i++) {
newRow = newRawData[i];
// Flag this row as needing to be manually found if it didn't come in with a $$hashKey
var mustFind = false;
if (!self.options.getRowIdentity(newRow)) {
mustFind = true;
}
// See if the new row is already in the rowhash
found = rowhash.get(newRow);
// If so...
if (found) {
// See if it's already being used by as GridRow
if (found.row) {
// If so, mark this new row as being found
foundOldRows[self.options.rowIdentity(newRow)] = true;
}
}
else {
// Put the row in the hashmap with the index it corresponds to
rowhash.put(newRow, {
i: i,
entity: newRow
});
// This row has to be searched for manually in the old row set
if (mustFind) {
unfoundNewRowsToFind.push(newRow);
}
else {
unfoundNewRows.push(newRow);
}
}
}
// Build the list of unfound old rows
for (i = 0; i < self.rows.length; i++) {
var row = self.rows[i];
var hash = self.options.rowIdentity(row.entity);
if (!foundOldRows[hash]) {
unfoundOldRows.push(row);
}
}
}
// Look for new rows
var newRows = unfoundNewRows || [];