-
Notifications
You must be signed in to change notification settings - Fork 3
/
jquery.dragtable.js
587 lines (469 loc) · 21.5 KB
/
jquery.dragtable.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
/*!
* dragtable - jquery ui widget to re-order table columns
* version 3.0
*
* Copyright (c) 2010, Jesse Baird <[email protected]>
* 12/2/2010
* https://github.com/jebaird/dragtable
*
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
*
*
* Forked from https://github.com/akottr/dragtable - Andres Koetter [email protected]
*
*
*
*
* quick down and and dirty on how this works
* ###########################################
* so when a column is selected we grab all of the cells in that row and clone append them to a semi copy of the parent table and the
* "real" cells get a place holder class witch is removed when the dragstop event is triggered
*
*
* make it easy to have a button swap columns
*
*
* Events - in order of trigger
* start - when the user mouses down on handle or th, use in favor of display helper
* beforeChange - called when a col will be moved
* change - called after the col has been moved
* stop - the user mouses up and stops dragging and the drag display is removed from the dom
*
*
*
*
* IE notes
* ie8 in quirks mode will only drag once after that the events are lost
*
*/
(function($) {
$.widget("jb.dragtable", {
//TODO: implement this
eventWidgetPrefix: 'dragtable',
options: {
//used to the col headers, data contained in here is used to set / get the name of the col
dataHeader:'data-header',
//class name that handles have
handle:'dragtable-drag-handle',
//draggable items in cols, .dragtable-drag-handle has to match the handle options
items: 'th:not( :has( .dragtable-drag-handle ) ), .dragtable-drag-handle',
//if a col header as this class, cols cant be dragged past it
boundary: 'dragtable-drag-boundary',
//classnames that get applied to the real td, th
placeholder: 'dragtable-col-placeholder',
/*
the drag display will be appended to this element,
if this is set to document.body and has been zeroed off the display will seem to jump
Its either : parent or a dom node
*/
appendTarget: ':parent',
//if true,this will scroll the appendTarget offsetParent when the dragDisplay is dragged past its boundaries
scroll: false
},
// when a col is dragged use this to find the semantic elements, for speed
tableElemIndex:{
head: '0',
body: '1',
foot: '2'
},
tbodyRegex: /(tbody|TBODY)/,
theadRegex: /(thead|THEAD)/,
tfootRegex: /(tfoot|TFOOT)/,
_create: function() {
//console.log(this);
//used start/end of drag
this.startIndex = null;
this.endIndex = null;
//the references to the table cells that are getting dragged
this.currentColumnCollection = [];
//the references the position of the first element in the currentColunmCollection position
this.currentColumnCollectionOffset = {};
//the div wrapping the drag display table
this.dragDisplay = $([])
var self = this,
o = self.options,
el = self.element;
o.appendTarget = ( o.appendTarget === ':parent' ) ? this.element.parent() : $( o.appendTarget );
//grab the ths and the handles and bind them
el.delegate(o.items, 'mousedown.' + self.widgetEventPrefix, function(e){
var $handle = $(this),
elementOffsetTop = self.element.position().top;
//make sure we are working with a th instead of a handle
if( $handle.hasClass( o.handle ) ){
$handle = $handle.closest('th');
//change the target to the th, so the handler can pick up the offsetleft
e.currentTarget = $handle.closest('th')[0]
}
self.getCol( $handle.index() )
.attr( 'tabindex', -1 )
.focus()
.disableSelection()
.css({
top: elementOffsetTop,
//need to account for the scroll left of the append target, other wise the display will be off by that many pix
left: ( self.currentColumnCollectionOffset.left + o.appendTarget[0].scrollLeft )
})
.appendTo( o.appendTarget )
self._mousemoveHandler( e );
//############
});
},
/*
* e.currentTarget is used for figuring out offsetLeft
* getCol must be called before this is
*
*/
_mousemoveHandler: function( e ){
//call this first, catch any drag display issues
this._start( e )
var self = this,
o = self.options,
prevMouseX = e.pageX,
dragDisplayWidth = self.dragDisplay.outerWidth(),
halfDragDisplayWidth = dragDisplayWidth / 2,
appendTargetOP = o.appendTarget.offsetParent()[0],
scroll = o.scroll,
//get the col count, used to contain col swap
colCount = self.element[ 0 ]
.getElementsByTagName( 'thead' )[ 0 ]
.getElementsByTagName( 'tr' )[ 0 ]
.getElementsByTagName( 'th' )
.length - 1;
$( document ).bind('mousemove.' + self.widgetEventPrefix, function( e ){
var columnPos = self._setCurrentColumnCollectionOffset(),
mouseXDiff = e.pageX - prevMouseX,
appendTarget = o.appendTarget[0],
left = ( parseInt( self.dragDisplay[0].style.left ) + mouseXDiff );
self.dragDisplay.css( 'left', left )
/*
* when moving left and e.pageX and prevMouseX are the same it will trigger right when moving left
*
* it should only swap cols when the col dragging is half over the prev/next col
*/
if( e.pageX < prevMouseX ){
//move left
var threshold = columnPos.left - halfDragDisplayWidth;
//scroll left
if( left < ( appendTarget.clientWidth - dragDisplayWidth ) && scroll == true ) {
var scrollLeft = appendTarget.scrollLeft + mouseXDiff
/*
* firefox does scroll the body with target being body but chome does
*/
if( appendTarget.tagName == 'BODY' ) {
window.scroll( window.scrollX + scrollLeft, window.scrollY );
} else {
appendTarget.scrollLeft = scrollLeft;
}
}
if( left < threshold ){
self._swapCol(self.startIndex-1);
}
}else{
//move right
var threshold = columnPos.left + halfDragDisplayWidth ;
//scroll right
if( left > (appendTarget.clientWidth - dragDisplayWidth ) && scroll == true ) {
//console.log( o.appendTarget[0].clientWidth + (e.pageX - prevMouseX))
var scrollLeft = appendTarget.scrollLeft + mouseXDiff
/*
* firefox does scroll the body with target being body but chome does
*/
if( appendTarget.tagName == 'BODY' ) {
window.scroll( window.scrollX + scrollLeft, window.scrollY );
} else {
appendTarget.scrollLeft = scrollLeft;
}
}
//move to the right only if x is greater than threshold and the current col isn' the last one
if( left > threshold && colCount != self.startIndex ){
self._swapCol( self.startIndex + 1 );
}
}
//update mouse position
prevMouseX = e.pageX;
})
.one( 'mouseup.' + self.widgetEventPrefix ,function(e ){
self._stop( e );
});
},
_start: function( e ){
$( document )
//move disableselection and cursor to default handlers of the start event
.disableSelection()
.css( 'cursor', 'move');
// guess the width of the column that is getting dragged and apply it to the drag display. fixes issues with
// cols / tables having fixed widths
this.dragDisplay.width( this.currentColumnCollection[0].clientWidth )
return this._eventHelper('start',e);
},
_stop: function( e ){
// issue #25 reorder the stop event order always remove the stop event
$( document )
.unbind( 'mousemove.' + this.widgetEventPrefix )
.enableSelection()
.css( 'cursor', '');
// clean up
this
.dropCol()
.dragDisplay.remove();
// let the world know we have stopped
this._eventHelper('stop',e,{});
},
_setOption: function(option, value) {
$.Widget.prototype._setOption.apply( this, arguments );
},
/*
* get the selected index cell out of table row
* needs to work as fast as possible. and performance gains in this method are worth the time
* because its used to build the drag display and get the cells on col swap
* http://jsperf.com/binary-regex-vs-string-equality/4
*/
_getCells: function( elem, index ){
//console.time('getcells');
var td,
parentNodeName,
ei = this.tableElemIndex,
//TODO: clean up this format
tds = {
//store where the cells came from
'semantic':{
'0': [],//head throws error if ei.head or ei['head']
'1': [],//body
'2': []//footer
},
//keep a ref in a flat array for easy access
'array':[]
},
//cache regex, reduces looking up the chain
theadRegex = this.theadRegex,
tbodyRegex = this.tbodyRegex,
tfootRegex = this.tfootRegex,
tdsSemanticHead = tds.semantic[ei.head],
tdsSemanticBody = tds.semantic[ei.body],
tdsSemanticFoot = tds.semantic[ei.foot];
//console.log(index);
//check does this col exsist
if(index <= -1 || typeof elem.rows[0].cells[index] == undefined){
return tds;
}
for(var i = 0, length = elem.rows.length; i < length; i++){
td = elem.rows[i].cells[index];
//if the row has no cells dont error out;
if( td == undefined ){
continue;
}
parentNodeName = td.parentNode.parentNode.nodeName;
tds.array.push(td);
//faster to leave out ^ and $ in the regular expression
if( tbodyRegex.test( parentNodeName ) ){
tdsSemanticBody.push( td );
}else if( theadRegex.test( parentNodeName ) ){
tdsSemanticHead.push( td );
}else if( this.tfootRegex.test( parentNodeName ) ){
tdsSemanticFoot.push( td );
}
}
return tds;
},
/*
* returns all element attrs in a string key="value" key2="value"
*/
_getElementAttributes: function(element){
var attrsString = [],
attrs = element.attributes,
i = 0,
length = attrs.length;
for( ; i < length; i++) {
attrsString.push( attrs[i].nodeName + '="' + attrs[i].value+'"' );
}
return attrsString.join(' ');
},
/*
* faster than swap nodes
* only works if a b parent are the same, works great for columns
*/
_swapCells: function(a, b) {
a.parentNode.insertBefore(b, a);
},
/*
* used to trigger optional events
*/
_eventHelper: function(eventName ,eventObj, additionalData){
return this._trigger(
eventName,
eventObj,
$.extend({
column: this.currentColumnCollection,
order: this.order(),
startIndex: this.startIndex,
endIndex: this.endIndex,
dragDisplay: this.dragDisplay,
columnOffset: this.currentColumnCollectionOffset
},additionalData)
);
},
/*
* build copy of table and attach the selected col to it, also removes the select col out of the table
* @returns copy of table with the selected col
*
* populates self.dragDisplay
* TODO: name this something better, like select col or get dragDisplay
*
*/
getCol: function(index){
//console.log('index of col '+index);
//drag display is just simple html
var target,
cells,
clone,
tr,
i,
length,
$table = this.element,
self = this,
eIndex = self.tableElemIndex,
placholderClassnames = ' ' + this.options.placeholder;;
//BUG: IE thinks that this table is disabled, dont know how that happend
self.dragDisplay = $('<table '+self._getElementAttributes($table[0])+'></table>')
.addClass('dragtable-drag-col');
//start and end are the same to start out with
self.startIndex = self.endIndex = index;
cells = self._getCells($table[0], index);
self.currentColumnCollection = cells.array;
//################################
//TODO: convert to for in // its faster than each
$.each(cells.semantic,function(k,collection){
//dont bother processing if there is nothing here
if(collection.length == 0){
return;
}
if ( k == '0' ){
target = document.createElement('thead');
self.dragDisplay[0].appendChild(target);
}else if ( k == 1 ) {
target = document.createElement('tbody');
self.dragDisplay[0].appendChild(target);
}else {
target = document.createElement('tfoot');
self.dragDisplay[0].appendChild(target);
}
for(i = 0,length = collection.length; i < length; i++){
clone = collection[i].cloneNode(true);
collection[i].className+=placholderClassnames;
tr = document.createElement('tr');
tr.appendChild(clone);
target.appendChild(tr);
}
});
this._setCurrentColumnCollectionOffset();
self.dragDisplay = $('<div class="dragtable-drag-wrapper"></div>').append(self.dragDisplay)
return self.dragDisplay;
},
_setCurrentColumnCollectionOffset: function(){
return this.currentColumnCollectionOffset = $( this.currentColumnCollection[0] ).position();
},
/*
* move column left or right
*/
_swapCol: function( to ){
//cant swap if same position
if(to == this.startIndex){
return false;
}
var from = this.startIndex;
this.endIndex = to;
//this col cant be moved past me
var th = this.element.find('th').eq( to );
//check on th
if( th.hasClass( this.options.boundary ) == true ){
return false;
}
//check handle element
if( th.find( '.' + this.options.handle ).hasClass( this.options.boundary ) == true ){
return false;
}
if( this._eventHelper('beforeChange',{}) === false ){
return false;
};
if(from < to) {
//console.log('move right');
for(var i = from; i < to; i++) {
var row2 = this._getCells(this.element[0],i+1);
// console.log(row2)
for(var j = 0, length = row2.array.length; j < length; j++){
this._swapCells(this.currentColumnCollection[j],row2.array[j]);
}
}
} else {
//console.log('move left');
for(var i = from; i > to; i--) {
var row2 = this._getCells(this.element[0],i-1);
for(var j = 0, length = row2.array.length; j < length; j++){
this._swapCells(row2.array[j],this.currentColumnCollection[j]);
}
}
}
this._eventHelper('change',{});
this.startIndex = this.endIndex;
},
/*
* called when drag start is finished
*/
dropCol: function(){
//TODO: cache this when the option is set
var regex = new RegExp("(?:^|\\s)" + this.options.placeholder + "(?!\\S)",'g');
//remove placeholder class
//dont use jquery.fn.removeClass for performance reasons
for(var i = 0, length = this.currentColumnCollection.length; i < length; i++){
var td = this.currentColumnCollection[i];
td.className = td.className.replace(regex,'')
}
return this;
},
/*
* get / set the current order of the cols
*/
order: function(order){
var self = this,
elem = self.element,
options = self.options,
headers = elem.find('thead tr:first').children('th');
if(order == undefined){
//get
var ret = [];
headers.each(function(){
var header = this.getAttribute(options.dataHeader);
if(header == null){
//the attr is missing so grab the text and use that
header = $(this).text();
}
ret.push(header);
});
return ret;
}else{
//set
//headers and order have to match up
if(order.length != headers.length){
return self;
}
for(var i = 0, length = order.length; i < length; i++){
var start = headers.filter('['+ options.dataHeader +'='+ order[i] +']').index();
if(start != -1){
self.startIndex = start;
self.currentColumnCollection = self._getCells(self.element[0], start).array;
self._swapCol(i);
}
}
return self;
}
},
destroy: function() {
var self = this,
o = self.options;
this.element.undelegate( o.items, 'mousedown.' + self.widgetEventPrefix );
$( document ).unbind('.' + self.widgetEventPrefix )
}
});
})(jQuery);