-
Notifications
You must be signed in to change notification settings - Fork 1
/
table.js
478 lines (421 loc) · 15.9 KB
/
table.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
/**
@toc
@param {Object} scope (attrs that must be defined on the scope (i.e. in the controller) - they can't just be defined in the partial html). REMEMBER: use snake-case when setting these on the partial!
TODO
@param {Object} attrs REMEMBER: use snake-case when setting these on the partial! i.e. my-attr='1' NOT myAttr='1'
TODO
@dependencies
TODO
@usage
partial / html:
TODO
controller / js:
TODO
//end: usage
*/
'use strict'
var module = angular.module('90TechSAS.zl-table', [])
module.directive('zlTable', ['$compile', '$timeout', '$templateCache', function ($compile, $timeout, $templateCache) {
var ID_FIELDS = ['id', '_id', 'uid', 'uuid', '$uid']
function compile (elt) {
var rootElement, bodyRowAttrs, headRowAttrs
rootElement = elt
var head = _.find(elt.children(), 'tagName', 'THEAD')
if (!head) {
throw('zl-table: The table should have one thead child')
}
var tHeadAttrs = head.attributes
var body = _.find(elt.children(), 'tagName', 'TBODY')
if (!body) {
throw('zl-table: The table should have one tbody child')
}
var tBodyAttrs = body.attributes
var availableColumns = getAvailableColumns(head, body)
var headBuilt = buildHeader(tHeadAttrs, headRowAttrs)
var bodyBuilt = buildBody(tBodyAttrs, bodyRowAttrs)
var bodyGrid
head.remove()
body.remove()
return {
pre: function (scope, element) {
scope.availableColumns = availableColumns
element.append($compile(headBuilt)(scope))
element.append($compile(bodyBuilt)(scope))
$timeout(function () {
if (rootElement[0].attributes.getNamedItem('grid-template') != null) {
bodyGrid = '<div ng-if="ctrl.gridMode">' +
'<div class="noselect" style="max-width:400px; float:left;margin:1%;" ng-repeat="elt in ctrl.zlTable | orderBy:ctrl.orderBy:ctrl.reverse"' +
'ng-class="{\'zl-row-selected\': ctrl.isSelected(elt)}"' +
'ng-click="ctrl.selectClick($event, elt)">' +
'<zl-template-compiler ' +
'template="' + escapeQuotes($templateCache.get(rootElement[0].attributes.getNamedItem('grid-template').value)) + '"></zl-template-compiler>' +
'</div>' +
'</div>' +
'<div style="clear:both;"></div>'
element.after($compile(bodyGrid)(scope))
}
})
}
}
function getAvailableColumns (thead, tbody) {
var row = _.find(thead.children, 'tagName', 'TR')
if (!row) {
throw('zl-table: The thead element should have one tr child')
}
headRowAttrs = row.attributes
var bodyRow = _.find(tbody.children, 'tagName', 'TR')
if (!bodyRow) {
throw('zl-table: The tbody element should have one tr child')
}
bodyRowAttrs = bodyRow.attributes
return _.compact(_.map(row.children, function (c, i) {
if (!c.attributes.getNamedItem('id')) {
throw('zl-table: The head cells should have an id')
}
return {
id: c.attributes.getNamedItem('id').value,
headTemplate: c.innerHTML,
template: bodyRow.children[i].innerHTML
}
}))
}
}
function escapeQuotes (str) {
if (str) return str.replace(/"/g, '"')
}
function buildAttributes (attrs) {
return _.reduce(attrs, function (result, attr) {
if (attr.name && attr.value) {
result += attr.name + '=' + attr.value + ' '
}
return result
}, '')
}
function buildHeader (tHeadAttrs, headRowAttrs) {
var elt = '<thead ng-if="!ctrl.gridMode"' + buildAttributes(tHeadAttrs) + '>' +
'<tr ' + buildAttributes(headRowAttrs) + '>' +
'<th ng-click="ctrl.selectAll()" ng-if="ctrl.selectedData"><input name="header-check" type="checkbox" ng-click="ctrl.selectAll(); $event.stopImmediatePropagation()" ng-checked="ctrl.areAllSelected()"/><label for="header-check" ng-click="ctrl.selectAll(); $event.stopImmediatePropagation()" ><span></span></label></th>' +
'<th ng-repeat="col in availableColumns | zlColumnFilter:ctrl.columns track by col.id" ' +
'id="{{col.id}}" ng-click="ctrl.order(col.id)" ' +
'zl-drag-drop zl-drag="col.id" ' +
'zl-drop="ctrl.dropColumn($data, col.id)"' +
'class="zl-col"' +
'ng-class="{\'zl-col-ordered\': ctrl.pagination.orderBy == col.id}"' +
'>' +
'<div ' +
'class="zl-th-container"' +
'ng-class="{\'zl-col-sortable\': ctrl.isSortable(col), \'zl-col-reverse\': ctrl.pagination.orderBy == col.id && ctrl.pagination.reverse}"' +
'>' +
'<zl-template-compiler template="{{col.headTemplate}}"></zl-template-compiler>' +
'<button ng-click="ctrl.dismiss(col.id)" class="zl-table-del-btn"></button>' +
'</div>' +
'</th>' +
'</tr></thead>'
return elt
}
function buildBody (tBodyAttrs, bodyRowAttrs) {
var elt = '<tbody ng-if="!ctrl.gridMode"' + buildAttributes(tBodyAttrs) + '>' +
'<tr ' + buildAttributes(bodyRowAttrs) + 'class="noselect" ng-repeat="elt in ctrl.zlTable track by ctrl.getIdValue(elt, $index)" ng-click="ctrl.rowClick($event, elt)" ng-class="{\'zl-row-selected\': ctrl.isSelected(elt)}">' +
'<td ng-if="ctrl.selectedData" ng-click="ctrl.selectClick($event, elt); $event.stopImmediatePropagation()"><input name="{{elt._id}}" type="checkbox" ng-click="ctrl.selectClick($event, elt); $event.stopImmediatePropagation()" ng-checked="ctrl.isSelected(elt)"/><label for="{{elt._id}}" ng-click="ctrl.selectClick($event, elt); $event.stopImmediatePropagation()" ><span></span></label></td>' +
'<td class="zl-td" ng-repeat="col in availableColumns | zlColumnFilter:ctrl.columns track by col.id"><zl-template-compiler template="{{col.template}}"></zl-template-compiler></td>' +
'</tr></tbody>'
return elt
}
return {
restrict: 'A',
controllerAs: 'ctrl',
scope: {},
bindToController: {
zlTable: '=',
columns: '=',
update: '&',
pagination: '=zlPagination',
selectedData: '=',
selectionChanged: '&',
gridMode: '=',
gridTemplate: '=',
rowClickFn: '&zlRowClick',
idField: '@'
},
compile: compile,
controller: ['$scope', function ($scope) {
var self = this
$scope.$watchGroup([function () {
return self.pagination.perPage
}, function () {
return self.pagination.currentPage
},function(){
return self.columns
}], init, true)
$scope.$watchCollection(function(){return self.columns}, function(){
self.columns.forEach(function(col){
if (/^customFields\./.test(col.id)){
var c = _.find($scope.availableColumns, {id: col.id})
if (!c){
var newColumn = _.clone(_.find($scope.availableColumns, {id: 'customFields'}))
newColumn.id = col.id
newColumn.label = col.label
$scope.availableColumns.push(newColumn)
}
}
})
})
function dropColumn (source, target) {
var new_index = _.findIndex(self.columns, {id: target})
var old_index = _.findIndex(self.columns, {id: source})
self.columns.splice(new_index, 0, self.columns.splice(old_index, 1)[0])
$scope.$apply()
}
function isSortable (col) {
var found = _.find(self.columns, {id: col.id})
return found && found.sortable !== false
}
function selectAll () {
if (!areAllSelected()) {
self.selectedData = _.map(self.zlTable, function (el) {
return el[self.idField]
})
} else {
self.selectedData = []
}
}
function areAllSelected () {
return !_.difference(_.map(self.zlTable, function (el) {
return el[self.idField]
}), self.selectedData).length
}
function selectClick (event, elt) {
if (event.shiftKey && !isSelected(elt)) {
rowClick(event, elt)
} else {
if (isSelected(elt)) {
_.remove(self.selectedData, function (selectedId) {
return selectedId === getIdValue(elt)
})
} else {
self.selectedData.push(getIdValue(elt))
}
self.selectionChanged({$selectedData: self.selectedData})
}
}
function rowClick (event, elt) {
if (event.shiftKey) {
if (isSelected(elt)) {
return
}
var lastClicked = self.selectedData[self.selectedData.length - 1] || getIdValue(self.zlTable[0])
var inside = false
_.each(self.zlTable, function (currentObj) {
if (getIdValue(currentObj) === lastClicked || currentObj === elt) {
inside = !inside
}
if (inside && !isSelected(currentObj)) {
self.selectedData.push(getIdValue(currentObj))
}
})
if (!isSelected(elt)) {
self.selectedData.push(getIdValue(elt))
}
self.selectionChanged({$selectedData: self.selectedData})
} else {
if (self.rowClickFn) {
self.rowClickFn({$event: event, $elt: elt})
}
}
}
function isSelected (elt) {
return _.includes(self.selectedData, getIdValue(elt))
}
function getIdValue (obj, index) {
if (!self.idField) {
var found = _.find(ID_FIELDS, function (f) {
return obj[f]
})
if (found) {
self.idField = found
}
}
return self.idField ? obj[self.idField] : index
}
function updateCall () {
self.update({$pagination: self.pagination})
}
function init () {
self.pagination = self.pagination || {}
self.pagination.currentPage = self.pagination.currentPage || 0
self.pagination.perPage = self.pagination.perPage || 10
// self.selectedData = self.selectedData || []
updateCall()
}
function order (name) {
var correspondingColumn = _.find(self.columns, {id: name})
if (correspondingColumn && correspondingColumn.sortable === false) return
self.pagination.orderBy = name
this.reverse = !this.reverse
self.pagination.reverse = this.reverse
updateCall()
}
function display (name) {
return _.contains(self.columns, name)
}
function dismiss (name) {
_.pull(self.columns, name)
}
_.extend(self, {
order: order,
display: display,
dismiss: dismiss,
rowClick: rowClick,
isSelected: isSelected,
selectClick: selectClick,
selectAll: selectAll,
dropColumn: dropColumn,
availableColumns: $scope.availableColumns,
areAllSelected: areAllSelected,
isSortable: isSortable,
getIdValue:getIdValue
})
// init()
}]
}
}])
module.directive('zlPaginate', ['$compile', '$timeout', function ($compile, $timeout) {
return {
restrict: 'E',
controllerAs: 'paginationCtrl',
scope: {},
template: '<button class="waves-effect waves-teal btn-flat" ng-if="paginationCtrl.pagination.currentPage != 0" ng-click="paginationCtrl.previousPage()"><</button>' +
'<button class="waves-effect waves-teal btn-flat" ng-repeat="elt in paginationCtrl.paginateArray() track by $index" ng-click="paginationCtrl.page($index)">{{$index +1}}</button>' +
'<button class="waves-effect waves-teal btn-flat" ng-if="paginationCtrl.pagination.currentPage < paginationCtrl.paginateArray().length -1" ng-click="paginationCtrl.nextPage()">></button>',
bindToController: {
update: '&',
pagination: '=zlPagination'
},
controller: function () {
var self = this
function updateCall () {
self.update({$pagination: self.pagination})
}
function nextPage () {
self.page(self.pagination.currentPage + 1)
}
function previousPage () {
self.page(self.pagination.currentPage - 1)
}
function page (pageNumber) {
self.pagination.currentPage = pageNumber
updateCall()
}
function paginateArray () {
var pageNumber = Math.ceil(self.pagination.totalElements / self.pagination.perPage)
return new Array(isNaN(pageNumber) ? 0 : pageNumber)
}
_.extend(self, {
paginateArray: paginateArray,
page: page,
previousPage: previousPage,
nextPage: nextPage
})
}
}
}])
module.directive('zlDragDrop', function () {
return {
controller: function () {},
scope: {},
controllerAs: 'dragDropCtrl',
bindToController: {
zlDrag: '=',
zlDrop: '&'
},
link: function (scope, element) {
var el = element[0]
window.addEventListener("dragover",function(e){
e.preventDefault();
},false);
window.addEventListener("drop",function(e){
e.preventDefault();
},false);
if (scope.dragDropCtrl.zlDrag) {
el.draggable = true
el.addEventListener(
'dragstart',
function (e) {
e.dataTransfer.effectAllowed = 'move'
e.dataTransfer.setData('Text', scope.dragDropCtrl.zlDrag)
this.classList.add('drag')
return false
},
false
)
el.addEventListener(
'dragend',
function (e) {
this.classList.remove('drag')
return false
},
false
)
el.addEventListener(
'dragover',
function (e) {
e.dataTransfer.dropEffect = 'move'
if (e.preventDefault) e.preventDefault()
this.classList.add('over')
return false
},
false
)
}
if (scope.dragDropCtrl.zlDrop) {
el.addEventListener(
'drop',
function (e) {
e.preventDefault()
e.stopPropagation()
if (e.stopPropagation) e.stopPropagation()
this.classList.remove('over')
scope.dragDropCtrl.zlDrop({$data: e.dataTransfer.getData('Text'), $event: e})
return false
},
false
)
el.addEventListener(
'dragenter',
function (e) {
this.classList.add('over')
return false
},
false
)
el.addEventListener(
'dragleave',
function (e) {
this.classList.remove('over')
return false
},
false
)
}
}
}
})
module.directive('zlTemplateCompiler', ['$compile', function ($compile) {
return {
restrict: 'E',
link: function (scope, tElement, tAttrs) {
var template = '<div style="display:inline; margin:auto;">' + tAttrs.template + '</div>'
tElement.replaceWith($compile(template)(scope))
}
}
}])
module.filter('zlColumnFilter', function () {
return function (allColumns, columnList) {
var cols = _.filter(columnList, 'visible').map(el => el.id)
return _.sortBy(_.reject(allColumns, function (col) {
return !_.includes(cols, col.id)
}), function (col) {
return cols.indexOf(col.id)
})
}
})