Blame view

directives/TableFor.directive.js 19.1 KB
6e6aa9b0   Tarpit Grover   Basic Setup
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
(function (angular) {
	var module = angular.module('framework.directives.UI');

	module.directive('tableFor', tableForDirective);
	module.directive('tableTitlebar', tableTitlebarDirective);
	module.directive('tableHeading', tableHeadingDirective);
	module.directive('tableDataRows', tableDataRowsDirective);
	module.directive('tableFooter', tableFooterDirective);
	module.filter('publish', publishFilter);
	module.filter('softFilter', softFilter);
	module.filter('pageGroup', pageGroupFilter);



	tableForDirective.$inject = ['$parse', 'Model', '$modal', '$q', '$filter', '$timeout'];
	function tableForDirective($parse, Model, $modal, $q, $filter, $timeout) {
		var defaults = {
			wrapperClass: 'table-responsive',
			tableClass: 'table table-bordered',
			minWidth: '600px'
		}

		function linkFn(scope, element, attrs, ctrls, transcludeFn) {
			var externalSearch = $parse(attrs.filtering)(scope);
			var externalSorting = $parse(attrs.sorting)(scope);
			var externalGrouping = $parse(attrs.grouping)(scope);
			var externalPaging = $parse(attrs.paging)(scope);

			scope.$schema = Model[attrs.schema].$schema;
			scope.$table = {
				actionColumn: false,
				selectionColumn: false,
				cardTemplate: '{{$row | json}}',
				toggleSelectAll: toggleSelectAll,
				toggleRowSelection: toggleRowSelection,
				toggleGroupSelection: toggleGroupSelection,
				allSelected: false,
				reset: reset,
				configureColumns: configureColumns,
				sort: sort,
				getSortingClass: getSortingClass
			};
			scope.$columns = generateColumns(scope.$schema);
			scope.$filtering = externalSearch || {
				$: ''
			}
			scope.$sorting = externalSorting || [];
			scope.$grouping = externalGrouping || {
				value: undefined
			};
			scope.$paging = externalPaging || {
				currentPage: 1, 
				totalItems: 0,
				maxPerPage: 10
			};
			scope.$data = {}; //object as it's grouped
			scope.$datasource = function () {
				return arguments[4]; //returns existing data by default;
			};

			var datasource = $parse(attrs.datasource)(scope);
			if (angular.isArray(datasource)) {
				scope.$datasource = generateLocalDatasource(datasource);
			} else if (angular.isFunction(datasource)) {
				scope.$datasource = datasource;
			} else {
				scope.$datasource = generateModelDatasource(scope.$schema.query);
			}

			scope.$watchCollection(function () { return scope.$filtering; }, debouncedUpdateData);
			scope.$watchCollection(function () { return scope.$sorting; }, debouncedUpdateData);
			scope.$watchCollection(function () { return scope.$grouping; }, debouncedUpdateData);
			scope.$watch(function () { return scope.$paging.currentPage; }, debouncedUpdateData);
			scope.$watch(function () { return scope.$paging.maxPerPage; }, debouncedUpdateData);

			var updateDebounce = null;

			function debouncedUpdateData() {
				if (updateDebounce) {
					$timeout.cancel(updateDebounce);
					updateDebounce = null;
				}
				updateDebounce = $timeout(updateData, 500);
			}

			function updateData() {
				for (var key in scope.$data) {
					delete scope.$data[key];
				}
				scope.$data.$loading = true;
				scope.$data.$error = null;
				scope.$datasource(scope.$filtering, scope.$sorting, scope.$grouping, scope.$paging, scope.$data).then(dataReceived, dataError, dataNotified);
			}

			function dataReceived(data) {
				for (var key in scope.$data) {
					delete scope.$data[key];
				}
				scope.$data.$loading = false;
				angular.extend(scope.$data, data);
			}

			function dataError(error) {
				for (var key in scope.$data) {
					delete scope.$data[key];
				}
				scope.$data.$loading = false;
				scope.$data.$error = error;
			}

			function dataNotified(dataLength) {
				scope.$paging.totalItems = dataLength;
			}

			transcludeFn(scope, function (clone, scope) {
				element.find('table').append(clone);
			});

			function generateLocalDatasource(initialData) {
				var data = initialData;
				return function (filtering, sorting, grouping, paging, existing) {
					var deferred = $q.defer();

					setTimeout(function () {
						var filter = $filter('filter');
						var orderBy = $filter('orderBy');
						var groupBy = $filter('groupBy');
						var pageGroup = $filter('pageGroup');

						deferred.notify(filter(data, filtering).length);

						var amendedSorting = [grouping.value];
						[].push.apply(amendedSorting, sorting);

						var result = pageGroup(groupBy(orderBy(filter(data, filtering), amendedSorting), grouping.value), paging);

						deferred.resolve(result);
					}, 0);

					return deferred.promise;
				}
			}

			function generateModelDatasource(modelQuery) {
				var queryBase = modelQuery;
				return function (filtering, sorting, grouping, paging, existing) {
					var deferred = $q.defer();

					query = queryBase();
					if (grouping.value) {
						query.orderBy(grouping.value);
					}

					angular.forEach(ordering, function (o) { query.orderBy(o); });


					setTimeout(function () {
						var filter = $filter('filter');
						var groupBy = $filter('groupBy');
						var pageGroup = $filter('pageGroup');

						deferred.notify(filter(data, filtering).length);

						var amendedSorting = [grouping.value];
						[].push.apply(amendedSorting, sorting);

						var result = pageGroup(groupBy(orderBy(filter(data, filtering), amendedSorting), grouping.value), paging);

						deferred.resolve(result);
					}, 0);

					return deferred.promise;
				}
			}

			function generateColumns(modelSchema) {
				var columns = [];
				angular.forEach(modelSchema, function (value, key) {
					var config = angular.extend({}, value, value.table || {});
					if (config.hidden) {
						return;
					}
					if (!angular.isDefined(config.visible)) {
						config.visible = true;
					}
					if (!angular.isDefined(config.binding) && config.type === moment) {
						config.binding = key + ".toDate() | date:'dd/MM/yyyy'";
					}
					columns.push({ key: key, title: config.display || key, accessor: angular.isFunction(config.binding) ? config.binding : buildAccessor(config.binding || key), binding: config.binding || key, visible: config.visible, filters: config.filters });
				});
				return columns;
			}

			function toggleSelectAll() {
				scope.$table.allSelected = !scope.$table.allSelected;
				angular.forEach(scope.$data, function (group) {
					toggleGroupSelection(group, scope.$table.allSelected);
				});
			}

			function toggleRowSelection(group, row, force) {
				row.$selected = angular.isDefined(force) ? force : !row.$selected;
				var selected = group.filter(function (d) { return d.$selected; });
				group.$selected = selected.length === group.length;
				
				var groups = 0;
				var selectedGroups = 0;
				angular.forEach(scope.$data, function (group, title) {
					if (title[0] == '$') {
						return;
					}
					groups++;
					if (group.$selected) selectedGroups++;
				});
				scope.$table.allSelected = groups === selectedGroups;
			}

			function toggleGroupSelection(group, force) {
				if (angular.isDefined(force)) {
					group.$selected = force;
				} else {
					group.$selected = !group.$selected;
				}
				angular.forEach(group, function (row) {
					row.$selected = group.$selected;
				});

				if (!angular.isDefined(force)) {
					var groups = 0;
					var selectedGroups = 0;
					angular.forEach(scope.$data, function (group, title) {
						if (title[0] == '$') {
							return;
						}
						groups++;
						if (group.$selected) selectedGroups++;
					});
					debugger;
					scope.$table.allSelected = groups === selectedGroups;
				}
			}

			function setAreAllSelected() {
				scope.$table.allSelected = false;
			}

			function sort(col) {
				//multisort
				var currentSort = scope.$sorting[0];
				if (col == currentSort) {
					scope.$sorting[0] = '-' + col;
				} else if ('-' + col == currentSort) {
					scope.$sorting[0] = col;
				} else {
					scope.$sorting.length = 0;
					scope.$sorting.push(col);
				}
			}

			function getSortingClass(col) {
				if (col == scope.$sorting[0]) {
					return 'icon-Arrow-Down2 brand-primary';
				}
				else if ('-' + col == scope.$sorting[0]) {
					return 'icon-Arrow-Up2 brand-primary';
				} else {
					return 'icon-Arrow-Down';
				}
			}

			function reset() {
				scope.$filtering = externalSearch || {
					$: ''
				}
				scope.$sorting = [];

				//TODO: Deselect ALL

				scope.$columns.length = 0;
				[].push.apply(scope.$columns, generateColumns(scope.$schema));
			}

			function buildAccessor(fieldName) {
				console.log('return row.' + fieldName + ';');
				window.count = window.count || 0;
				return new Function('row', 'return row.' + fieldName + ';');
			}

			function configureColumns() {
				$modal.open({
					template: '' +
							'<div class="modal-header">' +
								'<button class="close" type="button" ng-click="$close()"><i class="icon-Close"></i></button>' +
								'<h3 class="modal-title">Customize Columns</h3>' +
							'</div>' +
							'<div class="modal-body">' +
								'<div ng-repeat="column in columns">' +
									'<a ng-click="moveUp(column)" ng-hide="$first"><i class="icon-Arrow-UpinCircle brand-primary"></i></a>' +
									' &nbsp; {{column.title}}' +
									' &nbsp; <a ng-click="moveDown(column)" ng-hide="$last"><i class="icon-Arrow-DowninCircle brand-primary"></i></a>' +
									'<div class="checkbox pull-right m0">' +
										'<input type="checkbox" id="columncustomise{{::$index}}" ng-model="column.visible" ng-checked="column.visible" />' +
										'<label for="columncustomise{{::$index}}"></label>' +
									'</div><br class="clearfix">' +
								'</div>' +
							'</div>',
					controller: function ($scope, columns) {
						$scope.columns = columns;
						$scope.moveUp = function (column) {
							var index = $scope.columns.indexOf(column);
							move(index, index - 1);
						}
						$scope.moveDown = function (column) {
							var index = $scope.columns.indexOf(column);
							move(index, index + 1);
						}

						function move(old_index, new_index) {
							$scope.columns.splice(new_index, 0, $scope.columns.splice(old_index, 1)[0]);
						}
					},
					size: 'sm',
					resolve: {
						columns: function () {
							return scope.$columns
						}
					}
				});
			}
		}

		function compileFn(element, attrs) {
			return linkFn;
		}

		return {
			scope: true,
			transclude: true,
			template: function (element, attrs) {
				return '<div class="' + (attrs.wrapperClass || defaults.wrapperClass) + '"><table class="' + (attrs.tableClass || defaults.tableClass) + ' module-table" style="min-width:' + (attrs.minWidth || defaults.minWidth) + '"></table></div>'
			},
			compile: function (element, attrs) {
				return linkFn;
			}
		};
	}

	function tableTitlebarDirective() {
		return {
			restrict: 'E',
			scope: true,
			replace: true,
			template: function (element, attrs) {
				var template = '' +
                '<thead><tr><th colspan="100" class="table-arrange">';
				if (attrs.title) {
					template += '<h3 class="table-title">' + attrs.title + '</h3>';
				}
				if (attrs.showCount) {
					template += '<h3 class="table-title brand-primary">({{$visible.length}} / {{ $data.length }})</h3>';
				}
				if (attrs.columnsOptions) {
					template += '<div class="columns-options">' +
                                    '<a href="" ng-click="$table.reset()"><i class="icon-Reset"></i>Reset</a>' +
                                    '<a href="" ng-click="$table.configureColumns()"><i class="icon-Receipt-2"></i>Arrange</a>' +
                                '</div>';
				}
				template += '<div class="pull-right">' +
                                    '<pagination class="pagination-sm"  style="margin: 0;" total-items="$paging.totalItems" ng-model="$paging.currentPage" items-per-page="$paging.maxPerPage" boundary-links="true" max-size="5"></pagination>' +
                                '</div>';
				if (attrs.search) {
					template += '<input type="text" class="form-control pull-right" style="width:300px" placeholder="Search.." ng-model="$filtering.$" />';
				}
				template += '</th></tr></thead>'
				return template;
			}
		}
	}

	function tableHeadingDirective() {
		var defaults = {
		}
		return {
			restrict: 'E',
			scope: true,
			replace: true,
			template: function (element, attrs) {
				var tmpl = '' +
                    '<thead><tr>' +
                        '<th ng-if="::$table.selectionColumn" style="width:40px;text-align:center;">' +
                            '<div class="checkbox"><input type="checkbox" id="table-group-check" ng-click="$table.toggleSelectAll()" ng-checked="$table.allSelected"/><label for="table-group-check"></label></div>' +

                        '</th>' +
                        '<th ng-repeat="$column in $columns | filter: { visible: true }" class="module-table-head">' +
                            '<div><i ng-class="$column.icon"></i> {{ ::$column.title }}' +
                            '<span class="table-sort"><a href="" ng-click="$table.sort($column.key)"><i ng-class="$table.getSortingClass($column.key)"></i></a></span>' +
                            '</div>' + //add filter and search menu
                        '</th>' +
                        '<th ng-if="::$table.actionColumn" style="text-align:center;">' +
                            'Actions' +
                        '</th>' +
                    '</tr>';
				tmpl += '</thead>';
				return tmpl;
			}
		};
	}

	tableDataRowsDirective.$inject = ['$parse', 'Model'];
	function tableDataRowsDirective($parse, Model) {
		return {
			restrict: 'E',
			scope: true,
			replace: true,
			template: function (element, attrs) {
				var tmp = '' +
                    '<tbody ng-repeat="(title, group) in $data track by title">' +
                        '<tr ng-hide="title == \'undefined\'">' +
							'<td ng-if="::$table.selectionColumn" style="width:40px;text-align:center;">' +
                                '<div class="checkbox"><input id="group-check-{{::title}}" type="checkbox" ng-click="$table.toggleGroupSelection(group)" ng-checked="group.$selected"/><label for="group-check-{{::title}}"></label></div>' +
                            '</td>' +
							'<td colspan="1000"><b><u>{{ title }}</u></b></td>' +
						'</tr>' +
                        '<tr ng-repeat="$row in group track by $row.Id">' +
                            '<td ng-if="::$table.selectionColumn" style="width:40px;text-align:center;">' +
                                '<div class="checkbox"><input id="table-check-{{::title}}{{::$index}}" type="checkbox" ng-click="$table.toggleRowSelection(group, $row)" ng-checked="$row.$selected"/><label for="table-check-{{::title}}{{::$index}}"></label></div>' +
                            '</td>' +
                            '<td ng-repeat="$column in $columns | filter: { visible: true } track by $column.key">' +
                                '{{$column.accessor($row)}}' +
                            '</td>' +
                            '<td ng-if="::$table.actionColumn" style="text-align:center;" bind-html-compile="$table.actionColumn.html">' +
                            '</td>' +
                        '</tr>' +
                    '</tbody>';
				return tmp;
			},
			compile: function (element, attrs) {
				var selectionElement = _findSelectionColumn(element);
				var actionsElement = _findActionColumn(element);

				return link;

				function link(scope, element, attrs) {
					scope.$table.actionColumn = actionsElement;
					scope.$table.selectionColumn = selectionElement;
					scope.$table.getCellValue = getCellValue;

					function getCellValue(row, col) {
						console.log('GetCellValue is depreciated for performance, please use "$column.accessor($row)" instead, functions are now precompilied;');
						if (typeof col.binding === 'string')
							return $parse(col.binding)(row);
						else if (angular.isFunction(col.binding))
							return col.binding(row, col);
						else
							return '';
					}
				}
			}
		}

		function _findActionColumn(element) {
			var actionsElement = jQuery(element.context).find('table-actions');
			if (actionsElement.length) {
				return {
					html: actionsElement.html()
				};
			}
			return false;
		}

		function _findSelectionColumn(element) {
			var selectionElement = jQuery(element.context).find('table-selection');
			if (selectionElement.length) {
				return {
					html: selectionElement.html()
				};
			}
			return false;
		}
	}

	function tableFooterDirective() {
		return {
			restrict: 'E',
			scope: true,
			replace: true,
			template: function (element, attrs) {
				var template = '' +
                '<tfoot><tr><th colspan="100" class="table-arrange">';
				if (attrs.title) {
					template += '<h3 class="table-title">' + attrs.title + '</h3>';
				}
				if (attrs.showCount) {
					template += '<b class="brand-primary">(showing {{$paging.maxPerPage}} from {{ $paging.totalItems }})</b>';
				}
				if (attrs.columnsOptions) {
					template += '<div class="columns-options">' +
                                    '<a href="" ng-click="$table.reset()"><i class="icon-Reset"></i>Reset</a>' +
                                    '<a href="" ng-click="$table.configureColumns()"><i class="icon-Receipt-2"></i>Arrange</a>' +
                                '</div>';
				}
				template += '<div class="pull-right">' +
                                    '<pagination class="pagination-sm"  style="margin: 0;" total-items="$paging.totalItems" ng-model="$paging.currentPage" items-per-page="$paging.maxPerPage" boundary-links="true" max-size="5"></pagination>' +
                                '</div>';
				if (attrs.search) {
					template += '<input type="text" class="form-control pull-right" style="width:300px" placeholder="Search.." ng-model="$filtering.$" />';
				}
				template += '</th></tr></tfoot>'
				return template;
			}
		}
	}

	softFilter.$inject = ['$filter'];
	function softFilter($filter) {
		return function (array, filteringConfig) {
			var filterFn = $filter('filter');
			var filtered = filterFn(array, filteringConfig);
			for (var i = 0; i < array.length; i++) {
				var target = array[i];
				if (filtered.indexOf(target) > -1) {
					target.$filtered = true;
				} else {
					target.$filtered = false;
				}
			}
			return array;
		}
	}

	function pageGroupFilter() {
		return function (groups, pagingConfig) {
			var newGroups = {};
			var skip = (pagingConfig.currentPage - 1) * pagingConfig.maxPerPage;
			var take = pagingConfig.maxPerPage;

			if (angular.isArray(groups)) {
				newGroups.undefined = groups.slice(skip, skip + take);
			} else {
				var groupNames = [];
				for (var key in groups) {
					if (groups.hasOwnProperty(key) && key[0] != '$') {
						groupNames.push(key);
					}
				}
				groupNames.sort();

				angular.forEach(groupNames, function (title) {
					var values = groups[title];
					if (take <= 0) {
						return;
					} else if (skip > values.length) {
						skip -= values.length;
						return;
					} else if (skip > 0) {
						values.splice(0, skip);
						skip = 0;
					}

					if (take >= values.length) {
						newGroups[title] = values;
						take -= values.length;
					} else {
						newGroups[title] = values.slice(0, take);
						take = 0;
					}
				});
			}
			return newGroups;
		};
	}

	function pagingFilter() {
		return function (array, pagingConfig) {
			if (array.length > pagingConfig.minimum) {

			} else {
				return array;
			}
		}
	}

	function publishFilter() {
		return function (array, target) {
			if (angular.isArray(target)) {
				target.length = 0;
				[].push.apply(target, array);
			}
			return array;
		}
	}
})(angular);