Newer
Older
Angie Byron
committed
(function ($) {
Dries Buytaert
committed
/**
* Drag and drop table rows with field manipulation.
*
* Using the drupal_add_tabledrag() function, any table with weights or parent
* relationships may be made into draggable tables. Columns containing a field
* may optionally be hidden, providing a better user experience.
*
* Created tableDrag instances may be modified with custom behaviors by
* overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods.
* See blocks.js for an example of adding additional functionality to tableDrag.
*/
Drupal.behaviors.tableDrag = {
Angie Byron
committed
attach: function (context, settings) {
for (var base in settings.tableDrag) {
Dries Buytaert
committed
$('#' + base, context).once('tabledrag', function () {
// Create the new tableDrag instance. Save in the Drupal variable
// to allow other scripts access to the object.
Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]);
});
Dries Buytaert
committed
}
}
};
/**
* Constructor for the tableDrag object. Provides table and field manipulation.
*
* @param table
* DOM object for the table to be made draggable.
* @param tableSettings
* Settings for the table added via drupal_add_dragtable().
*/
Angie Byron
committed
Drupal.tableDrag = function (table, tableSettings) {
Dries Buytaert
committed
var self = this;
// Required object variables.
this.table = table;
this.tableSettings = tableSettings;
this.dragObject = null; // Used to hold information about a current drag operation.
this.rowObject = null; // Provides operations for row manipulation.
this.oldRowElement = null; // Remember the previous element.
this.oldY = 0; // Used to determine up or down direction from last mouse move.
this.changed = false; // Whether anything in the entire table has changed.
this.maxDepth = 0; // Maximum amount of allowed parenting.
Gábor Hojtsy
committed
this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table.
Dries Buytaert
committed
// Configure the scroll settings.
this.scrollSettings = { amount: 4, interval: 50, trigger: 70 };
this.scrollInterval = null;
this.scrollY = 0;
this.windowHeight = 0;
// Check this table's settings to see if there are parent relationships in
// this table. For efficiency, large sections of code can be skipped if we
// don't need to track horizontal movement and indentations.
this.indentEnabled = false;
for (var group in tableSettings) {
for (var n in tableSettings[group]) {
Angie Byron
committed
if (tableSettings[group][n].relationship == 'parent') {
this.indentEnabled = true;
}
Angie Byron
committed
if (tableSettings[group][n].limit > 0) {
this.maxDepth = tableSettings[group][n].limit;
Dries Buytaert
committed
if (this.indentEnabled) {
this.indentCount = 1; // Total width of indents, set in makeDraggable.
// Find the width of indentations to measure mouse movements against.
// Because the table doesn't need to start with any indentations, we
Angie Byron
committed
// manually append 2 indentations in the first draggable row, measure
// the offset, then remove.
var indent = Drupal.theme('tableDragIndentation');
Angie Byron
committed
var testRow = $('<tr/>').addClass('draggable').appendTo(table);
var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent);
Angie Byron
committed
this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft;
Angie Byron
committed
testRow.remove();
Dries Buytaert
committed
}
// Make each applicable row draggable.
// Match immediate children of the parent element to allow nesting.
$('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); });
Dries Buytaert
committed
// Add a link before the table for users to show or hide weight columns.
$(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>')
.attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.'))
.click(function () {
if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
self.hideColumns();
}
else {
self.showColumns();
}
return false;
})
.wrap('<div class="tabledrag-toggle-weight-wrapper"></div>')
.parent()
);
// Initialize the specified columns (for example, weight or parent columns)
// to show or hide according to user preference. This aids accessibility
// so that, e.g., screen reader users can choose to enter weight values and
// manipulate form elements directly, rather than using drag-and-drop..
self.initColumns();
Dries Buytaert
committed
// Add mouse bindings to the document. The self variable is passed along
// as event handlers do not have direct access to the tableDrag object.
Angie Byron
committed
$(document).bind('mousemove', function (event) { return self.dragRow(event, self); });
$(document).bind('mouseup', function (event) { return self.dropRow(event, self); });
Dries Buytaert
committed
};
/**
* Initialize columns containing form elements to be hidden by default,
* according to the settings for this tableDrag instance.
*
* Identify and mark each cell with a CSS class so we can easily toggle
* show/hide it. Finally, hide columns if user does not have a
* 'Drupal.tableDrag.showWeight' cookie.
Dries Buytaert
committed
*/
Drupal.tableDrag.prototype.initColumns = function () {
Dries Buytaert
committed
for (var group in this.tableSettings) {
// Find the first field in this group.
for (var d in this.tableSettings[group]) {
Angie Byron
committed
var field = $('.' + this.tableSettings[group][d].target + ':first', this.table);
if (field.length && this.tableSettings[group][d].hidden) {
Angie Byron
committed
var hidden = this.tableSettings[group][d].hidden;
Angie Byron
committed
var cell = field.closest('td');
Dries Buytaert
committed
break;
}
}
Dries Buytaert
committed
// Mark the column containing this field so it can be hidden.
Angie Byron
committed
if (hidden && cell[0]) {
Dries Buytaert
committed
// Add 1 to our indexes. The nth-child selector is 1 based, not 0 based.
// Match immediate children of the parent element to allow nesting.
var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1;
Angie Byron
committed
$('> thead > tr, > tbody > tr, > tr', this.table).each(function () {
// Get the columnIndex and adjust for any colspans in this row.
var index = columnIndex;
var cells = $(this).children();
cells.each(function (n) {
if (n < index && this.colSpan && this.colSpan > 1) {
index -= this.colSpan - 1;
Dries Buytaert
committed
}
});
if (index > 0) {
Angie Byron
committed
cell = cells.filter(':nth-child(' + index + ')');
if (cell[0].colSpan && cell[0].colSpan > 1) {
// If this cell has a colspan, mark it so we can reduce the colspan.
Angie Byron
committed
cell.addClass('tabledrag-has-colspan');
Dries Buytaert
committed
}
else {
// Mark this cell so we can hide it.
Angie Byron
committed
cell.addClass('tabledrag-hide');
Dries Buytaert
committed
}
Dries Buytaert
committed
}
});
}
}
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
// Now hide cells and reduce colspans unless cookie indicates previous choice.
// Set a cookie if it is not already present.
if ($.cookie('Drupal.tableDrag.showWeight') === null) {
$.cookie('Drupal.tableDrag.showWeight', 0, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
this.hideColumns();
}
// Check cookie value and show/hide weight columns accordingly.
else {
if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
this.showColumns();
}
else {
this.hideColumns();
}
}
};
/**
* Hide the columns containing weight/parent form elements.
* Undo showColumns().
*/
Drupal.tableDrag.prototype.hideColumns = function () {
// Hide weight/parent cells and headers.
$('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none');
// Show TableDrag handles.
$('.tabledrag-handle', 'table.tabledrag-processed').css('display', '');
// Reduce the colspan of any effected multi-span columns.
$('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
this.colSpan = this.colSpan - 1;
});
// Change link text.
$('.tabledrag-toggle-weight').text(Drupal.t('Show row weights'));
// Change cookie.
$.cookie('Drupal.tableDrag.showWeight', 0, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
// Trigger an event to allow other scripts to react to this display change.
$('table.tabledrag-processed').trigger('columnschange', 'hide');
};
/**
* Show the columns containing weight/parent form elements
* Undo hideColumns().
*/
Drupal.tableDrag.prototype.showColumns = function () {
// Show weight/parent cells and headers.
$('.tabledrag-hide', 'table.tabledrag-processed').css('display', '');
// Hide TableDrag handles.
$('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none');
// Increase the colspan for any columns where it was previously reduced.
$('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
this.colSpan = this.colSpan + 1;
});
// Change link text.
$('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights'));
// Change cookie.
$.cookie('Drupal.tableDrag.showWeight', 1, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
// Trigger an event to allow other scripts to react to this display change.
$('table.tabledrag-processed').trigger('columnschange', 'show');
Dries Buytaert
committed
};
/**
* Find the target used within a particular row and group.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.rowSettings = function (group, row) {
Dries Buytaert
committed
var field = $('.' + group, row);
for (var delta in this.tableSettings[group]) {
Angie Byron
committed
var targetClass = this.tableSettings[group][delta].target;
Dries Buytaert
committed
if (field.is('.' + targetClass)) {
// Return a copy of the row settings.
Angie Byron
committed
var rowSettings = {};
Dries Buytaert
committed
for (var n in this.tableSettings[group][delta]) {
rowSettings[n] = this.tableSettings[group][delta][n];
}
return rowSettings;
}
}
};
/**
* Take an item and add event handlers to make it become draggable.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.makeDraggable = function (item) {
Dries Buytaert
committed
var self = this;
// Create the handle.
Gábor Hojtsy
committed
var handle = $('<a href="#" class="tabledrag-handle"><div class="handle"> </div></a>').attr('title', Drupal.t('Drag to re-order'));
Dries Buytaert
committed
// Insert the handle after indentations (if any).
if ($('td:first .indentation:last', item).length) {
$('td:first .indentation:last', item).after(handle);
Dries Buytaert
committed
// Update the total width of indentation in this entire table.
self.indentCount = Math.max($('.indentation', item).length, self.indentCount);
Dries Buytaert
committed
}
else {
$('td:first', item).prepend(handle);
}
// Add hover action for the handle.
Angie Byron
committed
handle.hover(function () {
Dries Buytaert
committed
self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null;
Angie Byron
committed
}, function () {
Dries Buytaert
committed
self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null;
});
// Add the mousedown action for the handle.
Angie Byron
committed
handle.mousedown(function (event) {
Dries Buytaert
committed
// Create a new dragObject recording the event information.
Angie Byron
committed
self.dragObject = {};
Dries Buytaert
committed
self.dragObject.initMouseOffset = self.getMouseOffset(item, event);
self.dragObject.initMouseCoords = self.mouseCoords(event);
if (self.indentEnabled) {
self.dragObject.indentMousePos = self.dragObject.initMouseCoords;
}
Dries Buytaert
committed
// If there's a lingering row object from the keyboard, remove its focus.
Dries Buytaert
committed
if (self.rowObject) {
$('a.tabledrag-handle', self.rowObject.element).blur();
}
// Create a new rowObject for manipulation of this row.
self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true);
Dries Buytaert
committed
// Save the position of the table.
Angie Byron
committed
self.table.topY = $(self.table).offset().top;
Dries Buytaert
committed
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
self.table.bottomY = self.table.topY + self.table.offsetHeight;
// Add classes to the handle and row.
$(this).addClass('tabledrag-handle-hover');
$(item).addClass('drag');
// Set the document to use the move cursor during drag.
$('body').addClass('drag');
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'none');
}
// Hack for Konqueror, prevent the blur handler from firing.
// Konqueror always gives links focus, even after returning false on mousedown.
self.safeBlur = false;
// Call optional placeholder function.
self.onDrag();
return false;
});
// Prevent the anchor tag from jumping us to the top of the page.
Angie Byron
committed
handle.click(function () {
Dries Buytaert
committed
return false;
});
// Similar to the hover event, add a class when the handle is focused.
Angie Byron
committed
handle.focus(function () {
Dries Buytaert
committed
$(this).addClass('tabledrag-handle-hover');
self.safeBlur = true;
});
// Remove the handle class on blur and fire the same function as a mouseup.
Angie Byron
committed
handle.blur(function (event) {
Dries Buytaert
committed
$(this).removeClass('tabledrag-handle-hover');
if (self.rowObject && self.safeBlur) {
self.dropRow(event, self);
Dries Buytaert
committed
}
});
// Add arrow-key support to the handle.
Angie Byron
committed
handle.keydown(function (event) {
Dries Buytaert
committed
// If a rowObject doesn't yet exist and this isn't the tab key.
if (event.keyCode != 9 && !self.rowObject) {
self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true);
Dries Buytaert
committed
}
var keyChange = false;
switch (event.keyCode) {
case 37: // Left arrow.
case 63234: // Safari left arrow.
keyChange = true;
Gábor Hojtsy
committed
self.rowObject.indent(-1 * self.rtl);
Dries Buytaert
committed
break;
case 38: // Up arrow.
case 63232: // Safari up arrow.
var previousRow = $(self.rowObject.element).prev('tr').get(0);
while (previousRow && $(previousRow).is(':hidden')) {
previousRow = $(previousRow).prev('tr').get(0);
}
if (previousRow) {
self.safeBlur = false; // Do not allow the onBlur cleanup.
self.rowObject.direction = 'up';
keyChange = true;
Gábor Hojtsy
committed
if ($(item).is('.tabledrag-root')) {
// Swap with the previous top-level row.
Gábor Hojtsy
committed
var groupHeight = 0;
while (previousRow && $('.indentation', previousRow).length) {
Gábor Hojtsy
committed
previousRow = $(previousRow).prev('tr').get(0);
groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight;
}
if (previousRow) {
self.rowObject.swap('before', previousRow);
// No need to check for indentation, 0 is the only valid one.
window.scrollBy(0, -groupHeight);
}
Dries Buytaert
committed
}
else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) {
Gábor Hojtsy
committed
// Swap with the previous row (unless previous row is the first one
// and undraggable).
Dries Buytaert
committed
self.rowObject.swap('before', previousRow);
Gábor Hojtsy
committed
self.rowObject.interval = null;
self.rowObject.indent(0);
window.scrollBy(0, -parseInt(item.offsetHeight, 10));
Dries Buytaert
committed
}
handle.get(0).focus(); // Regain focus after the DOM manipulation.
}
break;
case 39: // Right arrow.
case 63235: // Safari right arrow.
keyChange = true;
Gábor Hojtsy
committed
self.rowObject.indent(1 * self.rtl);
Dries Buytaert
committed
break;
case 40: // Down arrow.
case 63233: // Safari down arrow.
var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0);
while (nextRow && $(nextRow).is(':hidden')) {
nextRow = $(nextRow).next('tr').get(0);
}
if (nextRow) {
self.safeBlur = false; // Do not allow the onBlur cleanup.
self.rowObject.direction = 'down';
keyChange = true;
Gábor Hojtsy
committed
if ($(item).is('.tabledrag-root')) {
// Swap with the next group (necessarily a top-level one).
var groupHeight = 0;
var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false);
Gábor Hojtsy
committed
if (nextGroup) {
Angie Byron
committed
$(nextGroup.group).each(function () {
groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight;
});
var nextGroupRow = $(nextGroup.group).filter(':last').get(0);
Gábor Hojtsy
committed
self.rowObject.swap('after', nextGroupRow);
// No need to check for indentation, 0 is the only valid one.
window.scrollBy(0, parseInt(groupHeight, 10));
Gábor Hojtsy
committed
}
Dries Buytaert
committed
}
else {
Gábor Hojtsy
committed
// Swap with the next row.
Dries Buytaert
committed
self.rowObject.swap('after', nextRow);
Gábor Hojtsy
committed
self.rowObject.interval = null;
self.rowObject.indent(0);
window.scrollBy(0, parseInt(item.offsetHeight, 10));
Dries Buytaert
committed
}
handle.get(0).focus(); // Regain focus after the DOM manipulation.
}
break;
}
if (self.rowObject && self.rowObject.changed == true) {
$(item).addClass('drag');
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
self.oldRowElement = item;
self.restripeTable();
self.onDrag();
}
// Returning false if we have an arrow key to prevent scrolling.
if (keyChange) {
return false;
}
});
// Compatibility addition, return false on keypress to prevent unwanted scrolling.
// IE and Safari will suppress scrolling on keydown, but all other browsers
Dries Buytaert
committed
// need to return false on keypress. http://www.quirksmode.org/js/keys.html
Angie Byron
committed
handle.keypress(function (event) {
Dries Buytaert
committed
switch (event.keyCode) {
case 37: // Left arrow.
case 38: // Up arrow.
case 39: // Right arrow.
case 40: // Down arrow.
return false;
}
});
};
/**
* Mousemove event handler, bound to document.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.dragRow = function (event, self) {
Dries Buytaert
committed
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
if (self.dragObject) {
self.currentMouseCoords = self.mouseCoords(event);
var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y;
var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x;
// Check for row swapping and vertical scrolling.
if (y != self.oldY) {
self.rowObject.direction = y > self.oldY ? 'down' : 'up';
self.oldY = y; // Update the old value.
// Check if the window should be scrolled (and how fast).
var scrollAmount = self.checkScroll(self.currentMouseCoords.y);
// Stop any current scrolling.
clearInterval(self.scrollInterval);
// Continue scrolling if the mouse has moved in the scroll direction.
if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') {
self.setScroll(scrollAmount);
}
// If we have a valid target, perform the swap and restripe the table.
var currentRow = self.findDropTargetRow(x, y);
if (currentRow) {
if (self.rowObject.direction == 'down') {
self.rowObject.swap('after', currentRow, self);
}
else {
self.rowObject.swap('before', currentRow, self);
}
self.restripeTable();
}
}
// Similar to row swapping, handle indentations.
Gábor Hojtsy
committed
if (self.indentEnabled) {
Dries Buytaert
committed
var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x;
// Set the number of indentations the mouse has been moved left or right.
David Rothstein
committed
var indentDiff = Math.round(xDiff / self.indentAmount);
Gábor Hojtsy
committed
// Indent the row with our estimated diff, which may be further
// restricted according to the rows around this row.
var indentChange = self.rowObject.indent(indentDiff);
// Update table and mouse indentations.
self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl;
self.indentCount = Math.max(self.indentCount, self.rowObject.indents);
Dries Buytaert
committed
}
Dries Buytaert
committed
return false;
Dries Buytaert
committed
}
};
/**
* Mouseup event handler, bound to document.
* Blur event handler, bound to drag handle for keyboard support.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.dropRow = function (event, self) {
Dries Buytaert
committed
// Drop row functionality shared between mouseup and blur events.
if (self.rowObject != null) {
var droppedRow = self.rowObject.element;
// The row is already in the right place so we just release it.
if (self.rowObject.changed == true) {
// Update the fields in the dropped row.
Dries Buytaert
committed
self.updateFields(droppedRow);
// If a setting exists for affecting the entire group, update all the
// fields in the entire dragged group.
for (var group in self.tableSettings) {
var rowSettings = self.rowSettings(group, droppedRow);
if (rowSettings.relationship == 'group') {
for (var n in self.rowObject.children) {
self.updateField(self.rowObject.children[n], group);
}
}
}
Dries Buytaert
committed
self.rowObject.markChanged();
if (self.changed == false) {
Dries Buytaert
committed
$(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');
Dries Buytaert
committed
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
self.changed = true;
}
}
if (self.indentEnabled) {
self.rowObject.removeIndentClasses();
}
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
$(droppedRow).removeClass('drag').addClass('drag-previous');
self.oldRowElement = droppedRow;
self.onDrop();
self.rowObject = null;
}
// Functionality specific only to mouseup event.
if (self.dragObject != null) {
$('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover');
self.dragObject = null;
$('body').removeClass('drag');
clearInterval(self.scrollInterval);
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'block');
}
}
};
/**
* Get the mouse coordinates from the event (allowing for browser differences).
*/
Angie Byron
committed
Drupal.tableDrag.prototype.mouseCoords = function (event) {
Dries Buytaert
committed
if (event.pageX || event.pageY) {
Angie Byron
committed
return { x: event.pageX, y: event.pageY };
Dries Buytaert
committed
}
return {
Angie Byron
committed
x: event.clientX + document.body.scrollLeft - document.body.clientLeft,
y: event.clientY + document.body.scrollTop - document.body.clientTop
Dries Buytaert
committed
};
};
/**
* Given a target element and a mouse event, get the mouse offset from that
* element. To do this we need the element's position and the mouse position.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.getMouseOffset = function (target, event) {
Angie Byron
committed
var docPos = $(target).offset();
Dries Buytaert
committed
var mousePos = this.mouseCoords(event);
Angie Byron
committed
return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top };
Dries Buytaert
committed
};
/**
* Find the row the mouse is currently over. This row is then taken and swapped
* with the one being dragged.
*
* @param x
* The x coordinate of the mouse on the page (not the screen).
* @param y
* The y coordinate of the mouse on the page (not the screen).
*/
Angie Byron
committed
Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) {
Dries Buytaert
committed
var rows = $(this.table.tBodies[0].rows).not(':hidden');
Angie Byron
committed
for (var n = 0; n < rows.length; n++) {
Dries Buytaert
committed
var row = rows[n];
var indentDiff = 0;
Angie Byron
committed
var rowY = $(row).offset().top;
Angie Byron
committed
// Because Safari does not report offsetHeight on table rows, but does on
// table cells, grab the firstChild of the row and use that instead.
// http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari.
if (row.offsetHeight == 0) {
var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2;
Angie Byron
committed
}
// Other browsers.
else {
var rowHeight = parseInt(row.offsetHeight, 10) / 2;
Angie Byron
committed
}
Dries Buytaert
committed
// Because we always insert before, we need to offset the height a bit.
if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) {
if (this.indentEnabled) {
// Check that this row is not a child of the row being dragged.
for (var n in this.rowObject.group) {
Dries Buytaert
committed
if (this.rowObject.group[n] == row) {
return null;
}
}
}
Angie Byron
committed
else {
// Do not allow a row to be swapped with itself.
if (row == this.rowObject.element) {
return null;
}
}
Gábor Hojtsy
committed
// Check that swapping with this row is allowed.
if (!this.rowObject.isValidSwap(row)) {
Dries Buytaert
committed
return null;
}
Gábor Hojtsy
committed
// We may have found the row the mouse just passed over, but it doesn't
Dries Buytaert
committed
// take into account hidden rows. Skip backwards until we find a draggable
// row.
while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) {
row = $(row).prev('tr').get(0);
}
return row;
}
}
return null;
};
/**
* After the row is dropped, update the table fields according to the settings
* set for this table.
*
* @param changedRow
* DOM object for the row that was just dropped.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.updateFields = function (changedRow) {
Dries Buytaert
committed
for (var group in this.tableSettings) {
// Each group may have a different setting for relationship, so we find
// the source rows for each separately.
this.updateField(changedRow, group);
}
};
Dries Buytaert
committed
/**
* After the row is dropped, update a single table field according to specific
* settings.
*
* @param changedRow
* DOM object for the row that was just dropped.
* @param group
* The settings group on which field updates will occur.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
var rowSettings = this.rowSettings(group, changedRow);
// Set the row as its own target.
if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') {
var sourceRow = changedRow;
}
// Siblings are easy, check previous and next rows.
else if (rowSettings.relationship == 'sibling') {
var previousRow = $(changedRow).prev('tr').get(0);
var nextRow = $(changedRow).next('tr').get(0);
var sourceRow = changedRow;
if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) {
if (this.indentEnabled) {
if ($('.indentations', previousRow).length == $('.indentations', changedRow)) {
Dries Buytaert
committed
sourceRow = previousRow;
}
}
else {
sourceRow = previousRow;
Dries Buytaert
committed
}
}
else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) {
if (this.indentEnabled) {
if ($('.indentations', nextRow).length == $('.indentations', changedRow)) {
sourceRow = nextRow;
}
Dries Buytaert
committed
}
else {
sourceRow = nextRow;
}
}
}
// Parents, look up the tree until we find a field not in this group.
// Go up as many parents as indentations in the changed row.
else if (rowSettings.relationship == 'parent') {
var previousRow = $(changedRow).prev('tr');
while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) {
previousRow = previousRow.prev('tr');
}
// If we found a row.
if (previousRow.length) {
sourceRow = previousRow[0];
}
// Otherwise we went all the way to the left of the table without finding
// a parent, meaning this item has been placed at the root level.
else {
// Use the first row in the table as source, because it's guaranteed to
// be at the root level. Find the first item, then compare this row
// against it as a sibling.
Dries Buytaert
committed
sourceRow = $(this.table).find('tr.draggable:first').get(0);
if (sourceRow == this.rowObject.element) {
sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
Dries Buytaert
committed
}
var useSibling = true;
Dries Buytaert
committed
}
Dries Buytaert
committed
// Because we may have moved the row from one category to another,
// take a look at our sibling and borrow its sources and targets.
this.copyDragClasses(sourceRow, changedRow, group);
rowSettings = this.rowSettings(group, changedRow);
Dries Buytaert
committed
// In the case that we're looking for a parent, but the row is at the top
// of the tree, copy our sibling's values.
if (useSibling) {
rowSettings.relationship = 'sibling';
rowSettings.source = rowSettings.target;
}
Dries Buytaert
committed
var targetClass = '.' + rowSettings.target;
var targetElement = $(targetClass, changedRow).get(0);
// Check if a target element exists in this row.
if (targetElement) {
var sourceClass = '.' + rowSettings.source;
var sourceElement = $(sourceClass, sourceRow).get(0);
switch (rowSettings.action) {
case 'depth':
// Get the depth of the target row.
Angie Byron
committed
targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length;
break;
case 'match':
// Update the value.
targetElement.value = sourceElement.value;
break;
case 'order':
var siblings = this.rowObject.findSiblings(rowSettings);
if ($(targetElement).is('select')) {
// Get a list of acceptable values.
Angie Byron
committed
var values = [];
Angie Byron
committed
$('option', targetElement).each(function () {
values.push(this.value);
});
Dries Buytaert
committed
var maxVal = values[values.length - 1];
// Populate the values in the siblings.
Angie Byron
committed
$(targetClass, siblings).each(function () {
Dries Buytaert
committed
// If there are more items than possible values, assign the maximum value to the row.
if (values.length > 0) {
this.value = values.shift();
}
else {
this.value = maxVal;
}
});
}
else {
// Assume a numeric input field.
var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0;
Angie Byron
committed
$(targetClass, siblings).each(function () {
this.value = weight;
weight++;
});
}
break;
Dries Buytaert
committed
}
}
};
/**
* Copy all special tableDrag classes from one row's form elements to a
* different one, removing any special classes that the destination row
* may have had.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) {
Dries Buytaert
committed
var sourceElement = $('.' + group, sourceRow);
var targetElement = $('.' + group, targetRow);
if (sourceElement.length && targetElement.length) {
targetElement[0].className = sourceElement[0].className;
}
};
Angie Byron
committed
Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
Dries Buytaert
committed
var de = document.documentElement;
var b = document.body;
var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight);
var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY));
var trigger = this.scrollSettings.trigger;
var delta = 0;
// Return a scroll speed relative to the edge of the screen.
if (cursorY - scrollY > windowHeight - trigger) {
delta = trigger / (windowHeight + scrollY - cursorY);
delta = (delta > 0 && delta < trigger) ? delta : trigger;
return delta * this.scrollSettings.amount;
}
else if (cursorY - scrollY < trigger) {
delta = trigger / (cursorY - scrollY);
delta = (delta > 0 && delta < trigger) ? delta : trigger;
return -delta * this.scrollSettings.amount;
}
};
Angie Byron
committed
Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
Dries Buytaert
committed
var self = this;
Angie Byron
committed
this.scrollInterval = setInterval(function () {
Dries Buytaert
committed
// Update the scroll values stored in the object.
self.checkScroll(self.currentMouseCoords.y);
var aboveTable = self.scrollY > self.table.topY;
var belowTable = self.scrollY + self.windowHeight < self.table.bottomY;
if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) {
window.scrollBy(0, scrollAmount);
}
}, this.scrollSettings.interval);
};
Angie Byron
committed
Drupal.tableDrag.prototype.restripeTable = function () {
// :even and :odd are reversed because jQuery counts from 0 and
Dries Buytaert
committed
// we count from 1, so we're out of sync.
// Match immediate children of the parent element to allow nesting.
$('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table)
.removeClass('odd even')
.filter(':odd').addClass('even').end()
.filter(':even').addClass('odd');
Dries Buytaert
committed
};
/**
* Stub function. Allows a custom handler when a row begins dragging.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.onDrag = function () {
Dries Buytaert
committed
return null;
};
/**
* Stub function. Allows a custom handler when a row is dropped.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.onDrop = function () {
Dries Buytaert
committed
return null;
};
/**
* Constructor to make a new object to manipulate a table row.
*
* @param tableRow
* The DOM element for the table row we will be manipulating.
* @param method
* The method in which this row is being moved. Either 'keyboard' or 'mouse'.
* @param indentEnabled
* Whether the containing table uses indentations. Used for optimizations.
* @param maxDepth
* The maximum amount of indentations this row may contain.
Dries Buytaert
committed
* @param addClasses
* Whether we want to add classes to this row to indicate child relationships.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
Dries Buytaert
committed
this.element = tableRow;
this.method = method;
Angie Byron
committed
this.group = [tableRow];
this.groupDepth = $('.indentation', tableRow).length;
Dries Buytaert
committed
this.changed = false;
Angie Byron
committed
this.table = $(tableRow).closest('table').get(0);
Dries Buytaert
committed
this.indentEnabled = indentEnabled;
this.maxDepth = maxDepth;
Dries Buytaert
committed
this.direction = ''; // Direction the row is being moved.
if (this.indentEnabled) {
this.indents = $('.indentation', tableRow).length;
Dries Buytaert
committed
this.children = this.findChildren(addClasses);
this.group = $.merge(this.group, this.children);
// Find the depth of this entire group.
for (var n = 0; n < this.group.length; n++) {
this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth);
Dries Buytaert
committed
}
}
};
/**
* Find all children of rowObject by indentation.
*
* @param addClasses
* Whether we want to add classes to this row to indicate child relationships.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
Dries Buytaert
committed
var parentIndentation = this.indents;
var currentRow = $(this.element, this.table).next('tr.draggable');
Angie Byron
committed
var rows = [];
Dries Buytaert
committed
var child = 0;
while (currentRow.length) {
var rowIndentation = $('.indentation', currentRow).length;
// A greater indentation indicates this is a child.
if (rowIndentation > parentIndentation) {
child++;
rows.push(currentRow[0]);
if (addClasses) {
Angie Byron
committed
$('.indentation', currentRow).each(function (indentNum) {
Dries Buytaert
committed
if (child == 1 && (indentNum == parentIndentation)) {
$(this).addClass('tree-child-first');
}
if (indentNum == parentIndentation) {
$(this).addClass('tree-child');
}
else if (indentNum > parentIndentation) {
$(this).addClass('tree-child-horizontal');
}
});
}
}
else {
break;
}
currentRow = currentRow.next('tr.draggable');
}
if (addClasses && rows.length) {
$('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last');
}
return rows;
};
/**
Gábor Hojtsy
committed
* Ensure that two rows are allowed to be swapped.
Dries Buytaert
committed
*
* @param row
Gábor Hojtsy
committed
* DOM object for the row being considered for swapping.
Dries Buytaert
committed
*/
Angie Byron
committed
Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
Dries Buytaert
committed
if (this.indentEnabled) {
Gábor Hojtsy
committed
var prevRow, nextRow;
if (this.direction == 'down') {
prevRow = row;
nextRow = $(row).next('tr').get(0);
Dries Buytaert
committed
}
Gábor Hojtsy
committed
else {
prevRow = $(row).prev('tr').get(0);
nextRow = row;
}
this.interval = this.validIndentInterval(prevRow, nextRow);
Dries Buytaert
committed
Gábor Hojtsy
committed
// We have an invalid swap if the valid indentations interval is empty.
if (this.interval.min > this.interval.max) {
Dries Buytaert
committed
return false;
}
}
Gábor Hojtsy
committed
// Do not let an un-draggable first row have anything put before it.
if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) {
return false;
}
Dries Buytaert
committed
return true;
};
/**
* Perform the swap between two rows.
*
* @param position
* Whether the swap will occur 'before' or 'after' the given row.
* @param row
* DOM element what will be swapped with the row group.
*/
Angie Byron
committed
Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) {
Drupal.detachBehaviors(this.group, Drupal.settings, 'move');
Dries Buytaert
committed
$(row)[position](this.group);
Drupal.attachBehaviors(this.group, Drupal.settings);
Dries Buytaert
committed
this.changed = true;
this.onSwap(row);
};
/**