-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathGrid.js
2537 lines (2136 loc) · 89 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','ScrollEvent',
function($q, $compile, $parse, gridUtil, uiGridConstants, GridOptions, GridColumn, GridRow, GridApi, rowSorter, rowSearcher, GridRenderContainer, $timeout, ScrollEvent) {
/**
* @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;
/**
* @ngdoc object
* @name footerHeight
* @propertyOf ui.grid.class:Grid
* @description returns the total footer height gridFooter + columnFooter
*/
self.footerHeight = self.calcFooterHeight();
/**
* @ngdoc object
* @name columnFooterHeight
* @propertyOf ui.grid.class:Grid
* @description returns the total column footer height
*/
self.columnFooterHeight = self.calcColumnFooterHeight();
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.verticalScrollSyncCallBackFns = {};
self.horizontalScrollSyncCallBackFns = {};
// 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;
//if true, grid will not respond to any scroll events
self.disableScrolling = false;
function vertical (scrollEvent) {
self.isScrollingVertically = false;
self.api.core.raise.scrollEnd(scrollEvent);
self.scrollDirection = uiGridConstants.scrollDirection.NONE;
}
var debouncedVertical = gridUtil.debounce(vertical, self.options.scrollDebounce);
var debouncedVerticalMinDelay = gridUtil.debounce(vertical, 0);
function horizontal (scrollEvent) {
self.isScrollingHorizontally = false;
self.api.core.raise.scrollEnd(scrollEvent);
self.scrollDirection = uiGridConstants.scrollDirection.NONE;
}
var debouncedHorizontal = gridUtil.debounce(horizontal, self.options.scrollDebounce);
var debouncedHorizontalMinDelay = gridUtil.debounce(horizontal, 0);
/**
* @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(scrollEvent) {
if (!self.isScrollingVertically && !self.isScrollingHorizontally) {
self.api.core.raise.scrollBegin(scrollEvent);
}
self.isScrollingVertically = true;
if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) {
debouncedVerticalMinDelay(scrollEvent);
}
else {
debouncedVertical(scrollEvent);
}
};
/**
* @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(scrollEvent) {
if (!self.isScrollingVertically && !self.isScrollingHorizontally) {
self.api.core.raise.scrollBegin(scrollEvent);
}
self.isScrollingHorizontally = true;
if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) {
debouncedHorizontalMinDelay(scrollEvent);
}
else {
debouncedHorizontal(scrollEvent);
}
};
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.
* The refresh method re-runs both the columnProcessors and the
* rowProcessors, as well as calling refreshCanvas to update all
* the grid sizing. In general you should prefer to use queueGridRefresh
* instead, which is basically a debounced version of refresh.
*
* If you only want to resize the grid, not regenerate all the rows
* and columns, you should consider directly calling refreshCanvas instead.
*
*/
self.api.registerMethod( 'core', 'refresh', this.refresh );
/**
* @ngdoc function
* @name queueGridRefresh
* @methodOf ui.grid.core.api:PublicApi
* @description Request a refresh of the rendered grid on screen, if multiple
* calls to queueGridRefresh are made within a digest cycle only one will execute.
* The refresh method re-runs both the columnProcessors and the
* rowProcessors, as well as calling refreshCanvas to update all
* the grid sizing. In general you should prefer to use queueGridRefresh
* instead, which is basically a debounced version of refresh.
*
*/
self.api.registerMethod( 'core', 'queueGridRefresh', this.queueGridRefresh );
/**
* @ngdoc function
* @name refreshRows
* @methodOf ui.grid.core.api:PublicApi
* @description Runs only the rowProcessors, columns remain as they were.
* It then calls redrawInPlace and refreshCanvas, which adjust the grid sizing.
* @returns {promise} promise that is resolved when render completes?
*
*/
self.api.registerMethod( 'core', 'refreshRows', this.refreshRows );
/**
* @ngdoc function
* @name queueRefresh
* @methodOf ui.grid.core.api:PublicApi
* @description Requests execution of refreshCanvas, if multiple requests are made
* during a digest cycle only one will run. RefreshCanvas updates the grid sizing.
* @returns {promise} promise that is resolved when render completes?
*
*/
self.api.registerMethod( 'core', 'queueRefresh', this.queueRefresh );
/**
* @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 scrollToIfNecessary
* @methodOf ui.grid.core.api:PublicApi
* @description Scrolls the grid to make a certain row and column combo visible,
* in the case that it is not completely visible on the screen already.
* @param {GridRow} gridRow row to make visible
* @param {GridCol} gridCol column to make visible
* @returns {promise} a promise that is resolved when scrolling is complete
*
*/
self.api.registerMethod( 'core', 'scrollToIfNecessary', function(gridRow, gridCol) { return self.scrollToIfNecessary(gridRow, gridCol);} );
/**
* @ngdoc function
* @name scrollTo
* @methodOf ui.grid.core.api:PublicApi
* @description Scroll the grid such that the specified
* row and column is in view
* @param {object} rowEntity gridOptions.data[] array instance to make visible
* @param {object} colDef to make visible
* @returns {promise} a promise that is resolved after any scrolling is finished
*/
self.api.registerMethod( 'core', 'scrollTo', function (rowEntity, colDef) { return self.scrollTo(rowEntity, colDef);} );
/**
* @ngdoc function
* @name registerRowsProcessor
* @methodOf ui.grid.core.api:PublicApi
* @description
* Register a "rows processor" function. When the rows are updated,
* the grid calls each registered "rows processor", which has a chance
* to alter the set of rows (sorting, etc) as long as the count is not
* modified.
*
* @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which
* is run in the context of the grid (i.e. this for the function will be the grid), and must
* return the updated rows list, which is passed to the next processor in the chain
* @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
* for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier.
*
* At present allRowsVisible is running at 50, sort manipulations running at 60-65, filter is running at 100,
* sort is at 200, grouping and treeview at 400-410, selectable rows at 500, pagination at 900 (pagination will generally want to be last)
*/
self.api.registerMethod( 'core', 'registerRowsProcessor', this.registerRowsProcessor );
/**
* @ngdoc function
* @name registerColumnsProcessor
* @methodOf ui.grid.core.api:PublicApi
* @description
* Register a "columns processor" function. When the columns are updated,
* the grid calls each registered "columns processor", which has a chance
* to alter the set of columns as long as the count is not
* modified.
*
* @param {function(renderedColumnsToProcess, rows )} processorFunction columns processor function, which
* is run in the context of the grid (i.e. this for the function will be the grid), and must
* return the updated columns list, which is passed to the next processor in the chain
* @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
* for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier.
*
* At present allRowsVisible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last)
*/
self.api.registerMethod( 'core', 'registerColumnsProcessor', this.registerColumnsProcessor );
/**
* @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 {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed.
* @param {Function} callBack Will be called when the event is emited. The function passes back an array of columns with
* sorts on them, in priority order.
*
* @example
* <pre>
* gridApi.core.on.sortChanged( $scope, function(sortColumns){
* // do something
* });
* </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 {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed.
* @param {Function} callBack Will be called when the event is emited. The function passes back the GridCol that has 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 );
/**
* @ngdoc method
* @name clearAllFilters
* @methodOf ui.grid.core.api:PublicApi
* @description Clears all filters and optionally refreshes the visible rows.
* @param {object} refreshRows Defaults to true.
* @param {object} clearConditions Defaults to false.
* @param {object} clearFlags Defaults to false.
* @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing.
*/
self.api.registerMethod('core', 'clearAllFilters', this.clearAllFilters);
self.registerDataChangeCallback( self.columnRefreshCallback, [uiGridConstants.dataChange.COLUMN]);
self.registerDataChangeCallback( self.processRowsCallback, [uiGridConstants.dataChange.EDIT]);
self.registerDataChangeCallback( self.updateFooterHeightCallback, [uiGridConstants.dataChange.OPTIONS]);
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;
}
height += this.calcColumnFooterHeight();
return height;
};
Grid.prototype.calcColumnFooterHeight = function () {
var height = 0;
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)} columnBuilder 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.queueGridRefresh();
};
/**
* @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.queueGridRefresh();
};
/**
* @ngdoc function
* @name updateFooterHeightCallback
* @methodOf ui.grid.class:Grid
* @description recalculates the footer height,
* registered as a dataChangeCallback on uiGridConstants.dataChange.OPTIONS
* @param {string} name column name
*/
Grid.prototype.updateFooterHeightCallback = function updateFooterHeightCallback( grid ){
grid.footerHeight = grid.calcFooterHeight();
grid.columnFooterHeight = grid.calcColumnFooterHeight();
};
/**
* @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. One of:
* - 'string'
* - 'boolean'
* - 'number'
* - 'date'
* - 'object'
* - 'numberStr'
* Note that if you choose date, your dates should be in a javascript date type
*
*/
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 {
colDef.type = 'string';
}
}
});
};
/**
* @ngdoc function
* @name isRowHeaderColumn
* @methodOf ui.grid.class:Grid
* @description returns true if the column is a row Header
* @param {object} column column
*/
Grid.prototype.isRowHeaderColumn = function isRowHeaderColumn(column) {
return this.rowHeaderColumns.indexOf(column) !== -1;
};
/**
* @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;
var rowHeaderCol = new GridColumn(colDef, gridUtil.nextUid(), 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.queueGridRefresh();
});
});
};
/**
* @ngdoc function
* @name getOnlyDataColumns
* @methodOf ui.grid.class:Grid
* @description returns all columns except for rowHeader columns
*/
Grid.prototype.getOnlyDataColumns = function getOnlyDataColumns() {
var self = this;
var cols = [];
self.columns.forEach(function (col) {
if (self.rowHeaderColumns.indexOf(col) === -1) {
cols.push(col);
}
});
return cols;
};
/**
* @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, use the shorter of columns length and colDefs.length because if a user has given two columns the same name then
// columns will be shorter than columnDefs. In this situation we'll avoid an error, but the user will still get an unexpected result
var len = Math.min(self.options.columnDefs.length, self.columns.length);
for (i = 0; i < len; 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;
var preCompileTemplate = 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);
}
};
this.columns.forEach(function (col) {
if ( col.cellTemplate ){
preCompileTemplate( col );
} else if ( col.cellTemplatePromise ){
col.cellTemplatePromise.then( function() {
preCompileTemplate( col );
});
}
});
};
/**
* @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 hasRightContainer
* @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');