forked from lhmyy521125/dataTables.treeGrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataTables.treeGrid.js
450 lines (402 loc) · 16.4 KB
/
dataTables.treeGrid.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
/**
* @summary TreeGrid
* @description TreeGrid extension for DataTable
* @version 1.1.2
* @file dataTables.treeGrid.js
* 2020-04-16 更新日志
* 1、解决dataTable reload() / draw() 时树形失效问题
* 2、采用新的初始化方式,可以外部调用 expandAll() / collapseAll() 方法
* @example
* var table = $('#example').dataTable( { ... } );
* var tree = new $.fn.dataTable.treeGrid( table );
* tree.expandAll();
* 3、更新后更容易对插件进行扩展,可以自定义自己需要实现的功能,参考expandAll() / collapseAll()
* 自己定义自己的方法,处理不同的需求
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery', 'datatables.net'], function ($) {
return factory($, window, document);
});
} else if (typeof exports === 'object') {
// CommonJS
module.exports = function (root, $) {
if (!root) {
root = window;
}
if (!$ || !$.fn.dataTable) {
$ = require('datatables.net')(root, $).$;
}
return factory($, root, root.document);
};
} else {
// Browser
factory(jQuery, window, document);
}
}(function ($, window, document) {
'use strict';
var DataTable = $.fn.dataTable;
//定义全局 TR 子集 二维数组
var treeGridRows = {};
var globalInit;
var TreeGrid = function (dt, init) {
var that = this;
if (!(this instanceof TreeGrid)) {
alert('TreeGrid warning: TreeGrid must be initialised with the "new" keyword.');
return;
}
if (init === undefined || init === true) {
init = {};
}
globalInit = init;
var dtSettings = new $.fn.dataTable.Api(dt).settings()[0];
this.s = {
dt: dtSettings
};
if (dtSettings._oTreeGrid) {
throw 'TreeGrid already initialised on this table';
}
dtSettings._oTreeGrid = this;
if (!dtSettings._bInitComplete) {
dtSettings.oApi._fnCallbackReg(dtSettings, 'aoInitComplete', function () {
that.fnConstruct(init);
}, 'TreeGrid');
} else {
this.fnConstruct(init);
}
};
$.extend(TreeGrid.prototype, {
"fnConstruct": function (oInit) {
var that = this;
this.s = $.extend(true, this.s, TreeGrid.defaults, oInit);
var settings = this.s.dt;
var select = settings._select;
var dataTable = $(settings.nTable).dataTable().api();
var sLeft = this.s.left;
var sExpandAll = this.s.expandAll;
var expandIcon = $(this.s.expandIcon);
var collapseIcon = $(this.s.collapseIcon);
// Expand TreeGrid
dataTable.on('click', 'td.treegrid-control', function (e) {
if (!$(this).html()) {
return;
}
// record selected indexes
var selectedIndexes = [];
select && (selectedIndexes = dataTable.rows({selected: true}).indexes().toArray());
var rows = dataTable.rows();
var parentTr = getParentTr(e.target);
var parentTrId = getTrId();
$(parentTr).attr('id', parentTrId);
var row = dataTable.row(parentTr);
var index = row.index();
var data = row.data();
var td = $(dataTable.cell(getParentTd(e.target)).node());
var paddingLeft = parseInt(td.css('padding-left'), 10);
var layer = parseInt(td.find('span').css('margin-left') || 0, 10) / sLeft;
var icon = collapseIcon.clone();
icon.css('marginLeft', layer * sLeft + 'px');
td.removeClass('treegrid-control').addClass('treegrid-control-open');
td.html('').append(icon);
if (data.children && data.children.length) {
var subRows = treeGridRows[parentTrId] = [];
var prevRow = row.node();
data.children.forEach(function (item) {
var newRow = dataTable.row.add(item);
var node = newRow.node();
var treegridTd = $(node).find('.treegrid-control');
var left = (layer + 1) * sLeft;
$(node).attr('parent-index', index);
treegridTd.find('span').css('marginLeft', left + 'px');
treegridTd.next().css('paddingLeft', paddingLeft + left + 'px');
$(node).insertAfter(prevRow);
prevRow = node;
subRows.push(node);
});
resetEvenOddClass(dataTable);
select && setTimeout(function () {
dataTable.rows(selectedIndexes).select();
}, 0);
}
});
// Collapse TreeGrid
dataTable.on('click', 'td.treegrid-control-open', function (e) {
var selectedIndexes = [];
select && (selectedIndexes = dataTable.rows({selected: true}).indexes().toArray());
var parentTr = getParentTr(e.target);
var parentTrId = $(parentTr).attr('id');
var td = $(dataTable.cell(getParentTd(e.target)).node());
var layer = parseInt(td.find('span').css('margin-left') || 0, 10) / sLeft;
var icon = expandIcon.clone();
icon.css('marginLeft', layer * sLeft + 'px');
td.removeClass('treegrid-control-open').addClass('treegrid-control');
td.html('').append(icon);
resetTreeGridRows(parentTrId);
resetEvenOddClass(dataTable);
select && setTimeout(function () {
dataTable.rows(selectedIndexes).select();
}, 0);
});
//dataTable init 处理
dataTable.on('init.dt', function () {
console.log('Table initialisation complete: ' + new Date().getTime());
//dataTable 初始化完成调用展开
if(sExpandAll){
that.expandAll.call(that)
}
});
//dataTable draw 处理
dataTable.on('draw.dt.DTFC', function () {
that._fnDraw.call(that);
})
var inProgress = false;
// Check parents and children on select
select && select.style === 'multi' && dataTable.on('select', function (e, dt, type, indexes) {
if (inProgress) {
return;
}
inProgress = true;
indexes.forEach(function (index) {
// Check parents
selectParent(dataTable, index);
// Check children
selectChildren(dataTable, index);
});
inProgress = false;
});
// Check parents and children on deselect
select && select.style === 'multi' && dataTable.on('deselect', function (e, dt, type, indexes) {
if (inProgress) {
return;
}
inProgress = true;
indexes.forEach(function (index) {
// Check parents
deselectParent(dataTable, index);
// Check children
deselectChildren(dataTable, index);
});
inProgress = false;
});
},
/**
* @returns {void}
* @example
* var table = $('#example').dataTable( { ... } );
* var tree = new $.fn.dataTable.treeGrid( table );
* tree.expandAll();
*/
"expandAll": function () {
console.log('expandAll: ' + new Date().getTime());
var that = this;
this.s = $.extend(true, this.s, TreeGrid.defaults, globalInit);
var dataTable = $(this.s.dt.nTable).dataTable().api();
var tds = $(dataTable.table().body()).find('td.treegrid-control');
tds.each(function (index, td) {
_expandAll(that, null, td);
});
},
"collapseAll":function(){
console.log('collapseAll: ' + new Date().getTime());
var that = this;
this.s = $.extend(true, this.s, TreeGrid.defaults, globalInit);
var dataTable = $(this.s.dt.nTable).dataTable().api();
var trs = $(dataTable.table().body()).find('tr');
trs.each(function (index, tr) {
if(typeof($(tr).attr("parent-index"))=="undefined"){
var trid = $(tr).attr('id');
resetTreeGridRows(trid);
}
});
},
"_fnDraw": function () {
console.log('_fnDraw: ' + new Date().getTime());
var that = this;
this.s = $.extend(true, this.s, TreeGrid.defaults, globalInit);
/* Draw callback function */
if (this.s.expandAll) {
console.log('expandAll is True: ' + new Date().getTime());
var tds = $(dataTable.table().body()).find('td.treegrid-control');
tds.each(function (index, td) {
_expandAll(that, null, td);
});
}
/* Event triggering */
$(this).trigger('draw.dtfc', {
"left": this.s.left
});
},
});
/**
* 收缩展开处理
* @param trId
*/
function resetTreeGridRows (trId) {
var subRows = treeGridRows[trId];
if (subRows && subRows.length) {
subRows.forEach(function (node) {
var subTrId = $(node).attr('id');
if (treeGridRows[subTrId]) {
resetTreeGridRows(subTrId);
}
dataTable.row($(node)).remove();
$(node).remove();
});
delete treeGridRows[trId];
$('#' + trId).find('.treegrid-control-open').each(function (i, td) {
$(td).removeClass('treegrid-control-open').addClass('treegrid-control');
$(td).html('').append($(globalInit.expandIcon).clone());
});
}
};
function resetEvenOddClass(dataTable) {
var classes = ['odd', 'even'];
$(dataTable.table().body()).find('tr').each(function (index, tr) {
$(tr).removeClass('odd even').addClass(classes[index % 2]);
});
};
function selectParent(dataTable, index) {
var row = dataTable.row(index);
var parentIndex = $(row.node()).attr('parent-index');
if (parentIndex !== null) {
parentIndex = +parentIndex;
var selector = '[parent-index="' + parentIndex + '"]';
var allChildRows = dataTable.rows(selector).nodes();
var selectedChildRows = dataTable.rows(selector, {selected: true}).nodes();
if (allChildRows.length === selectedChildRows.length) {
var parentRow = dataTable.row(parentIndex, {selected: false});
parentRow.select();
if (parentRow.node()) {
selectParent(dataTable, parentIndex);
}
}
}
}
function selectChildren(dataTable, index) {
var rows = dataTable.rows('[parent-index="' + index + '"]', {selected: false});
var childIndexes = rows.indexes().toArray();
if (childIndexes.length) {
rows.select();
childIndexes.forEach(function (childIndex) {
selectChildren(dataTable, childIndex);
});
}
}
function deselectParent(dataTable, index) {
var row = dataTable.row(index);
var parentIndex = $(row.node()).attr('parent-index');
if (parentIndex !== null) {
parentIndex = +parentIndex;
var parentRow = dataTable.row(parentIndex, {selected: true});
parentRow.deselect();
if (parentRow.node()) {
deselectParent(dataTable, parentIndex);
}
}
}
function deselectChildren(dataTable, index) {
var rows = dataTable.rows('[parent-index="' + index + '"]', {selected: true});
var childIndexes = rows.indexes().toArray();
if (childIndexes.length) {
rows.deselect();
childIndexes.forEach(function (childIndex) {
deselectChildren(dataTable, childIndex);
});
}
}
//默认展开方法
function _expandAll(treeGrid, insertTr, tds) {
var settings = treeGrid.s.dt;
var select = settings._select;
var dataTable = $(settings.nTable).dataTable().api();
var sLeft = treeGrid.s.left;
var expandIcon = $(treeGrid.s.expandIcon);
var collapseIcon = $(treeGrid.s.collapseIcon);
if (!tds) {
return
}
// 迭代存在子集的表格行
var parentTr = getParentTr(tds);
var parentTrId = getTrId();
var row = dataTable.row(parentTr);
var index = row.index();
var data = row.data();
if (data.children && data.children.length) {
//由于数据insertAfter插入问题,这里将JSON 倒序
data.children.reverse();
$(parentTr).attr('id', parentTrId);
// var td = $(dataTable.cell(getParentTd(tds)).node());
var td = $(tds);
var paddingLeft = parseInt(td.css('padding-left'), 10);
var layer = parseInt(td.find('span').css('margin-left') || 0, 10) / sLeft;
var icon = collapseIcon.clone();
icon.css('marginLeft', layer * sLeft + 'px');
td.removeClass('treegrid-control').addClass('treegrid-control-open');
td.html('').append(icon);
var subRows = treeGridRows[parentTrId] = [];
var prevRow = row.node();
if (!insertTr) {
insertTr = prevRow;
}
data.children.forEach(function (item) {
var newRow = dataTable.row.add(item);
var node = newRow.node();
var treegridTd = $(node).find('.treegrid-control');
var left = (layer + 1) * sLeft;
$(node).attr('parent-index', index);
treegridTd.find('span').css('marginLeft', left + 'px');
treegridTd.next().css('paddingLeft', paddingLeft + left + 'px');
// $(node).insertAfter(prevRow);
$(node).insertAfter(insertTr);
prevRow = node;
subRows.push(node);
//递归展开子集 当前插入行存在子集则递归
var prevRowData = dataTable.row(prevRow).data();
if (prevRowData.children && prevRowData.children.length) {
var prevTd = $(prevRow).find('td.treegrid-control');
_expandAll(treeGrid, $(node), prevTd);
}
});
select && setTimeout(function () {
dataTable.rows(selectedIndexes).select();
}, 0);
}
};
function getTrId() {
return 'tr-' + Date.now();
}
function getParentTr(target) {
return $(target).parents('tr')[0];
}
function getParentTd(target) {
return target.tagName === 'TD' ? target : $(target).parents('td')[0];
}
TreeGrid.defaults = {
"left": 12,
"expandAll": false,
"expandIcon": '<span>+</span>',
"collapseIcon": '<span>-</span>',
"fnDrawCallback": null
};
TreeGrid.version = '1.1.2';
DataTable.Api.register('treeGrid()', function () {
return this;
});
$(document).on('init.dt.treeGrid', function (e, settings) {
if (e.namespace !== 'dt') {
return;
}
var init = settings.oInit.treeGrid;
var defaults = DataTable.defaults.treeGrid;
if (init || defaults) {
var opts = $.extend({}, init, defaults);
if (init !== false) {
var treeGrid = new TreeGrid(settings, opts);
}
}
});
$.fn.dataTable.TreeGrid = TreeGrid;
$.fn.DataTable.TreeGrid = TreeGrid;
return TreeGrid;
}));