3 * Provide dragging capabilities to admin uis.
7 * Triggers when weights columns are toggled.
12 (function ($, Drupal, drupalSettings) {
17 * Store the state of weight columns display for all tables.
19 * Default value is to hide weight columns.
21 var showWeight = JSON.parse(localStorage.getItem('Drupal.tableDrag.showWeight'));
24 * Drag and drop table rows with field manipulation.
26 * Using the drupal_attach_tabledrag() function, any table with weights or
27 * parent relationships may be made into draggable tables. Columns containing
28 * a field may optionally be hidden, providing a better user experience.
30 * Created tableDrag instances may be modified with custom behaviors by
31 * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods.
32 * See blocks.js for an example of adding additional functionality to
35 * @type {Drupal~behavior}
37 Drupal.behaviors.tableDrag = {
38 attach: function (context, settings) {
39 function initTableDrag(table, base) {
41 // Create the new tableDrag instance. Save in the Drupal variable
42 // to allow other scripts access to the object.
43 Drupal.tableDrag[base] = new Drupal.tableDrag(table[0], settings.tableDrag[base]);
47 for (var base in settings.tableDrag) {
48 if (settings.tableDrag.hasOwnProperty(base)) {
49 initTableDrag($(context).find('#' + base).once('tabledrag'), base);
56 * Provides table and field manipulation.
60 * @param {HTMLElement} table
61 * DOM object for the table to be made draggable.
62 * @param {object} tableSettings
63 * Settings for the table added via drupal_add_dragtable().
65 Drupal.tableDrag = function (table, tableSettings) {
67 var $table = $(table);
72 this.$table = $(table);
83 this.tableSettings = tableSettings;
86 * Used to hold information about a current drag operation.
88 * @type {?HTMLElement}
90 this.dragObject = null;
93 * Provides operations for row manipulation.
95 * @type {?HTMLElement}
97 this.rowObject = null;
100 * Remember the previous element.
102 * @type {?HTMLElement}
104 this.oldRowElement = null;
107 * Used to determine up or down direction from last mouse move.
114 * Whether anything in the entire table has changed.
118 this.changed = false;
121 * Maximum amount of allowed parenting.
128 * Direction of the table.
132 this.rtl = $(this.table).css('direction') === 'rtl' ? -1 : 1;
138 this.striping = $(this.table).data('striping') === 1;
141 * Configure the scroll settings.
145 * @prop {number} amount
146 * @prop {number} interval
147 * @prop {number} trigger
149 this.scrollSettings = {amount: 4, interval: 50, trigger: 70};
155 this.scrollInterval = null;
167 this.windowHeight = 0;
170 * Check this table's settings for parent relationships.
172 * For efficiency, large sections of code can be skipped if we don't need to
173 * track horizontal movement and indentations.
177 this.indentEnabled = false;
178 for (var group in tableSettings) {
179 if (tableSettings.hasOwnProperty(group)) {
180 for (var n in tableSettings[group]) {
181 if (tableSettings[group].hasOwnProperty(n)) {
182 if (tableSettings[group][n].relationship === 'parent') {
183 this.indentEnabled = true;
185 if (tableSettings[group][n].limit > 0) {
186 this.maxDepth = tableSettings[group][n].limit;
192 if (this.indentEnabled) {
195 * Total width of indents, set in makeDraggable.
199 this.indentCount = 1;
200 // Find the width of indentations to measure mouse movements against.
201 // Because the table doesn't need to start with any indentations, we
202 // manually append 2 indentations in the first draggable row, measure
203 // the offset, then remove.
204 var indent = Drupal.theme('tableDragIndentation');
205 var testRow = $('<tr/>').addClass('draggable').appendTo(table);
206 var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent);
207 var $indentation = testCell.find('.js-indentation');
213 this.indentAmount = $indentation.get(1).offsetLeft - $indentation.get(0).offsetLeft;
217 // Make each applicable row draggable.
218 // Match immediate children of the parent element to allow nesting.
219 $table.find('> tr.draggable, > tbody > tr.draggable').each(function () { self.makeDraggable(this); });
221 // Add a link before the table for users to show or hide weight columns.
222 $table.before($('<button type="button" class="link tabledrag-toggle-weight"></button>')
223 .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.'))
224 .on('click', $.proxy(function (e) {
226 this.toggleColumns();
228 .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>')
232 // Initialize the specified columns (for example, weight or parent columns)
233 // to show or hide according to user preference. This aids accessibility
234 // so that, e.g., screen reader users can choose to enter weight values and
235 // manipulate form elements directly, rather than using drag-and-drop..
238 // Add event bindings to the document. The self variable is passed along
239 // as event handlers do not have direct access to the tableDrag object.
240 $(document).on('touchmove', function (event) { return self.dragRow(event.originalEvent.touches[0], self); });
241 $(document).on('touchend', function (event) { return self.dropRow(event.originalEvent.touches[0], self); });
242 $(document).on('mousemove pointermove', function (event) { return self.dragRow(event, self); });
243 $(document).on('mouseup pointerup', function (event) { return self.dropRow(event, self); });
245 // React to localStorage event showing or hiding weight columns.
246 $(window).on('storage', $.proxy(function (e) {
247 // Only react to 'Drupal.tableDrag.showWeight' value change.
248 if (e.originalEvent.key === 'Drupal.tableDrag.showWeight') {
249 // This was changed in another window, get the new value for this
251 showWeight = JSON.parse(e.originalEvent.newValue);
252 this.displayColumns(showWeight);
258 * Initialize columns containing form elements to be hidden by default.
260 * Identify and mark each cell with a CSS class so we can easily toggle
261 * show/hide it. Finally, hide columns if user does not have a
262 * 'Drupal.tableDrag.showWeight' localStorage value.
264 Drupal.tableDrag.prototype.initColumns = function () {
265 var $table = this.$table;
269 for (var group in this.tableSettings) {
270 if (this.tableSettings.hasOwnProperty(group)) {
272 // Find the first field in this group.
273 for (var d in this.tableSettings[group]) {
274 if (this.tableSettings[group].hasOwnProperty(d)) {
275 var field = $table.find('.' + this.tableSettings[group][d].target).eq(0);
276 if (field.length && this.tableSettings[group][d].hidden) {
277 hidden = this.tableSettings[group][d].hidden;
278 cell = field.closest('td');
284 // Mark the column containing this field so it can be hidden.
285 if (hidden && cell[0]) {
286 // Add 1 to our indexes. The nth-child selector is 1 based, not 0
287 // based. Match immediate children of the parent element to allow
289 columnIndex = cell.parent().find('> td').index(cell.get(0)) + 1;
290 $table.find('> thead > tr, > tbody > tr, > tr').each(this.addColspanClass(columnIndex));
294 this.displayColumns(showWeight);
298 * Mark cells that have colspan.
300 * In order to adjust the colspan instead of hiding them altogether.
302 * @param {number} columnIndex
303 * The column index to add colspan class to.
306 * Function to add colspan class.
308 Drupal.tableDrag.prototype.addColspanClass = function (columnIndex) {
310 // Get the columnIndex and adjust for any colspans in this row.
312 var index = columnIndex;
313 var cells = $row.children();
315 cells.each(function (n) {
316 if (n < index && this.colSpan && this.colSpan > 1) {
317 index -= this.colSpan - 1;
321 cell = cells.filter(':nth-child(' + index + ')');
322 if (cell[0].colSpan && cell[0].colSpan > 1) {
323 // If this cell has a colspan, mark it so we can reduce the colspan.
324 cell.addClass('tabledrag-has-colspan');
327 // Mark this cell so we can hide it.
328 cell.addClass('tabledrag-hide');
335 * Hide or display weight columns. Triggers an event on change.
337 * @fires event:columnschange
339 * @param {bool} displayWeight
340 * 'true' will show weight columns.
342 Drupal.tableDrag.prototype.displayColumns = function (displayWeight) {
346 // Default action is to hide columns.
350 // Trigger an event to allow other scripts to react to this display change.
351 // Force the extra parameter as a bool.
352 $('table').findOnce('tabledrag').trigger('columnschange', !!displayWeight);
356 * Toggle the weight column depending on 'showWeight' value.
358 * Store only default override.
360 Drupal.tableDrag.prototype.toggleColumns = function () {
361 showWeight = !showWeight;
362 this.displayColumns(showWeight);
364 // Save default override.
365 localStorage.setItem('Drupal.tableDrag.showWeight', showWeight);
368 // Reset the value to its default.
369 localStorage.removeItem('Drupal.tableDrag.showWeight');
374 * Hide the columns containing weight/parent form elements.
376 * Undo showColumns().
378 Drupal.tableDrag.prototype.hideColumns = function () {
379 var $tables = $('table').findOnce('tabledrag');
380 // Hide weight/parent cells and headers.
381 $tables.find('.tabledrag-hide').css('display', 'none');
382 // Show TableDrag handles.
383 $tables.find('.tabledrag-handle').css('display', '');
384 // Reduce the colspan of any effected multi-span columns.
385 $tables.find('.tabledrag-has-colspan').each(function () {
386 this.colSpan = this.colSpan - 1;
389 $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights'));
393 * Show the columns containing weight/parent form elements.
395 * Undo hideColumns().
397 Drupal.tableDrag.prototype.showColumns = function () {
398 var $tables = $('table').findOnce('tabledrag');
399 // Show weight/parent cells and headers.
400 $tables.find('.tabledrag-hide').css('display', '');
401 // Hide TableDrag handles.
402 $tables.find('.tabledrag-handle').css('display', 'none');
403 // Increase the colspan for any columns where it was previously reduced.
404 $tables.find('.tabledrag-has-colspan').each(function () {
405 this.colSpan = this.colSpan + 1;
408 $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights'));
412 * Find the target used within a particular row and group.
414 * @param {string} group
416 * @param {HTMLElement} row
417 * The row HTML element.
420 * The table row settings.
422 Drupal.tableDrag.prototype.rowSettings = function (group, row) {
423 var field = $(row).find('.' + group);
424 var tableSettingsGroup = this.tableSettings[group];
425 for (var delta in tableSettingsGroup) {
426 if (tableSettingsGroup.hasOwnProperty(delta)) {
427 var targetClass = tableSettingsGroup[delta].target;
428 if (field.is('.' + targetClass)) {
429 // Return a copy of the row settings.
430 var rowSettings = {};
431 for (var n in tableSettingsGroup[delta]) {
432 if (tableSettingsGroup[delta].hasOwnProperty(n)) {
433 rowSettings[n] = tableSettingsGroup[delta][n];
443 * Take an item and add event handlers to make it become draggable.
445 * @param {HTMLElement} item
446 * The item to add event handlers to.
448 Drupal.tableDrag.prototype.makeDraggable = function (item) {
451 // Add a class to the title link.
452 $item.find('td:first-of-type').find('a').addClass('menu-item__link');
453 // Create the handle.
454 var handle = $('<a href="#" class="tabledrag-handle"><div class="handle"> </div></a>').attr('title', Drupal.t('Drag to re-order'));
455 // Insert the handle after indentations (if any).
456 var $indentationLast = $item.find('td:first-of-type').find('.js-indentation').eq(-1);
457 if ($indentationLast.length) {
458 $indentationLast.after(handle);
459 // Update the total width of indentation in this entire table.
460 self.indentCount = Math.max($item.find('.js-indentation').length, self.indentCount);
463 $item.find('td').eq(0).prepend(handle);
466 handle.on('mousedown touchstart pointerdown', function (event) {
467 event.preventDefault();
468 if (event.originalEvent.type === 'touchstart') {
469 event = event.originalEvent.touches[0];
471 self.dragStart(event, self, item);
474 // Prevent the anchor tag from jumping us to the top of the page.
475 handle.on('click', function (e) {
479 // Set blur cleanup when a handle is focused.
480 handle.on('focus', function () {
481 self.safeBlur = true;
484 // On blur, fire the same function as a touchend/mouseup. This is used to
485 // update values after a row has been moved through the keyboard support.
486 handle.on('blur', function (event) {
487 if (self.rowObject && self.safeBlur) {
488 self.dropRow(event, self);
492 // Add arrow-key support to the handle.
493 handle.on('keydown', function (event) {
494 // If a rowObject doesn't yet exist and this isn't the tab key.
495 if (event.keyCode !== 9 && !self.rowObject) {
496 self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true);
499 var keyChange = false;
502 /* eslint-disable no-fallthrough */
504 switch (event.keyCode) {
507 // Safari left arrow.
510 self.rowObject.indent(-1 * self.rtl);
517 var $previousRow = $(self.rowObject.element).prev('tr:first-of-type');
518 var previousRow = $previousRow.get(0);
519 while (previousRow && $previousRow.is(':hidden')) {
520 $previousRow = $(previousRow).prev('tr:first-of-type');
521 previousRow = $previousRow.get(0);
524 // Do not allow the onBlur cleanup.
525 self.safeBlur = false;
526 self.rowObject.direction = 'up';
529 if ($(item).is('.tabledrag-root')) {
530 // Swap with the previous top-level row.
532 while (previousRow && $previousRow.find('.js-indentation').length) {
533 $previousRow = $(previousRow).prev('tr:first-of-type');
534 previousRow = $previousRow.get(0);
535 groupHeight += $previousRow.is(':hidden') ? 0 : previousRow.offsetHeight;
538 self.rowObject.swap('before', previousRow);
539 // No need to check for indentation, 0 is the only valid one.
540 window.scrollBy(0, -groupHeight);
543 else if (self.table.tBodies[0].rows[0] !== previousRow || $previousRow.is('.draggable')) {
544 // Swap with the previous row (unless previous row is the first
545 // one and undraggable).
546 self.rowObject.swap('before', previousRow);
547 self.rowObject.interval = null;
548 self.rowObject.indent(0);
549 window.scrollBy(0, -parseInt(item.offsetHeight, 10));
551 // Regain focus after the DOM manipulation.
552 handle.trigger('focus');
558 // Safari right arrow.
561 self.rowObject.indent(self.rtl);
566 // Safari down arrow.
568 var $nextRow = $(self.rowObject.group).eq(-1).next('tr:first-of-type');
569 var nextRow = $nextRow.get(0);
570 while (nextRow && $nextRow.is(':hidden')) {
571 $nextRow = $(nextRow).next('tr:first-of-type');
572 nextRow = $nextRow.get(0);
575 // Do not allow the onBlur cleanup.
576 self.safeBlur = false;
577 self.rowObject.direction = 'down';
580 if ($(item).is('.tabledrag-root')) {
581 // Swap with the next group (necessarily a top-level one).
583 var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false);
585 $(nextGroup.group).each(function () {
586 groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight;
588 var nextGroupRow = $(nextGroup.group).eq(-1).get(0);
589 self.rowObject.swap('after', nextGroupRow);
590 // No need to check for indentation, 0 is the only valid one.
591 window.scrollBy(0, parseInt(groupHeight, 10));
595 // Swap with the next row.
596 self.rowObject.swap('after', nextRow);
597 self.rowObject.interval = null;
598 self.rowObject.indent(0);
599 window.scrollBy(0, parseInt(item.offsetHeight, 10));
601 // Regain focus after the DOM manipulation.
602 handle.trigger('focus');
607 /* eslint-enable no-fallthrough */
609 if (self.rowObject && self.rowObject.changed === true) {
610 $(item).addClass('drag');
611 if (self.oldRowElement) {
612 $(self.oldRowElement).removeClass('drag-previous');
614 self.oldRowElement = item;
615 if (self.striping === true) {
616 self.restripeTable();
621 // Returning false if we have an arrow key to prevent scrolling.
627 // Compatibility addition, return false on keypress to prevent unwanted
628 // scrolling. IE and Safari will suppress scrolling on keydown, but all
629 // other browsers need to return false on keypress.
630 // http://www.quirksmode.org/js/keys.html
631 handle.on('keypress', function (event) {
633 /* eslint-disable no-fallthrough */
635 switch (event.keyCode) {
647 /* eslint-enable no-fallthrough */
653 * Pointer event initiator, creates drag object and information.
655 * @param {jQuery.Event} event
656 * The event object that trigger the drag.
657 * @param {Drupal.tableDrag} self
659 * @param {HTMLElement} item
660 * The item that that is being dragged.
662 Drupal.tableDrag.prototype.dragStart = function (event, self, item) {
663 // Create a new dragObject recording the pointer information.
664 self.dragObject = {};
665 self.dragObject.initOffset = self.getPointerOffset(item, event);
666 self.dragObject.initPointerCoords = self.pointerCoords(event);
667 if (self.indentEnabled) {
668 self.dragObject.indentPointerPos = self.dragObject.initPointerCoords;
671 // If there's a lingering row object from the keyboard, remove its focus.
672 if (self.rowObject) {
673 $(self.rowObject.element).find('a.tabledrag-handle').trigger('blur');
676 // Create a new rowObject for manipulation of this row.
677 self.rowObject = new self.row(item, 'pointer', self.indentEnabled, self.maxDepth, true);
679 // Save the position of the table.
680 self.table.topY = $(self.table).offset().top;
681 self.table.bottomY = self.table.topY + self.table.offsetHeight;
683 // Add classes to the handle and row.
684 $(item).addClass('drag');
686 // Set the document to use the move cursor during drag.
687 $('body').addClass('drag');
688 if (self.oldRowElement) {
689 $(self.oldRowElement).removeClass('drag-previous');
694 * Pointer movement handler, bound to document.
696 * @param {jQuery.Event} event
698 * @param {Drupal.tableDrag} self
699 * The tableDrag instance.
701 * @return {bool|undefined}
702 * Undefined if no dragObject is defined, false otherwise.
704 Drupal.tableDrag.prototype.dragRow = function (event, self) {
705 if (self.dragObject) {
706 self.currentPointerCoords = self.pointerCoords(event);
707 var y = self.currentPointerCoords.y - self.dragObject.initOffset.y;
708 var x = self.currentPointerCoords.x - self.dragObject.initOffset.x;
710 // Check for row swapping and vertical scrolling.
711 if (y !== self.oldY) {
712 self.rowObject.direction = y > self.oldY ? 'down' : 'up';
713 // Update the old value.
715 // Check if the window should be scrolled (and how fast).
716 var scrollAmount = self.checkScroll(self.currentPointerCoords.y);
717 // Stop any current scrolling.
718 clearInterval(self.scrollInterval);
719 // Continue scrolling if the mouse has moved in the scroll direction.
720 if (scrollAmount > 0 && self.rowObject.direction === 'down' || scrollAmount < 0 && self.rowObject.direction === 'up') {
721 self.setScroll(scrollAmount);
724 // If we have a valid target, perform the swap and restripe the table.
725 var currentRow = self.findDropTargetRow(x, y);
727 if (self.rowObject.direction === 'down') {
728 self.rowObject.swap('after', currentRow, self);
731 self.rowObject.swap('before', currentRow, self);
733 if (self.striping === true) {
734 self.restripeTable();
739 // Similar to row swapping, handle indentations.
740 if (self.indentEnabled) {
741 var xDiff = self.currentPointerCoords.x - self.dragObject.indentPointerPos.x;
742 // Set the number of indentations the pointer has been moved left or
744 var indentDiff = Math.round(xDiff / self.indentAmount);
745 // Indent the row with our estimated diff, which may be further
746 // restricted according to the rows around this row.
747 var indentChange = self.rowObject.indent(indentDiff);
748 // Update table and pointer indentations.
749 self.dragObject.indentPointerPos.x += self.indentAmount * indentChange * self.rtl;
750 self.indentCount = Math.max(self.indentCount, self.rowObject.indents);
758 * Pointerup behavior.
760 * @param {jQuery.Event} event
762 * @param {Drupal.tableDrag} self
763 * The tableDrag instance.
765 Drupal.tableDrag.prototype.dropRow = function (event, self) {
769 // Drop row functionality.
770 if (self.rowObject !== null) {
771 droppedRow = self.rowObject.element;
772 $droppedRow = $(droppedRow);
773 // The row is already in the right place so we just release it.
774 if (self.rowObject.changed === true) {
775 // Update the fields in the dropped row.
776 self.updateFields(droppedRow);
778 // If a setting exists for affecting the entire group, update all the
779 // fields in the entire dragged group.
780 for (var group in self.tableSettings) {
781 if (self.tableSettings.hasOwnProperty(group)) {
782 var rowSettings = self.rowSettings(group, droppedRow);
783 if (rowSettings.relationship === 'group') {
784 for (var n in self.rowObject.children) {
785 if (self.rowObject.children.hasOwnProperty(n)) {
786 self.updateField(self.rowObject.children[n], group);
793 self.rowObject.markChanged();
794 if (self.changed === false) {
795 $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');
800 if (self.indentEnabled) {
801 self.rowObject.removeIndentClasses();
803 if (self.oldRowElement) {
804 $(self.oldRowElement).removeClass('drag-previous');
806 $droppedRow.removeClass('drag').addClass('drag-previous');
807 self.oldRowElement = droppedRow;
809 self.rowObject = null;
812 // Functionality specific only to pointerup events.
813 if (self.dragObject !== null) {
814 self.dragObject = null;
815 $('body').removeClass('drag');
816 clearInterval(self.scrollInterval);
821 * Get the coordinates from the event (allowing for browser differences).
823 * @param {jQuery.Event} event
827 * An object with `x` and `y` keys indicating the position.
829 Drupal.tableDrag.prototype.pointerCoords = function (event) {
830 if (event.pageX || event.pageY) {
831 return {x: event.pageX, y: event.pageY};
834 x: event.clientX + document.body.scrollLeft - document.body.clientLeft,
835 y: event.clientY + document.body.scrollTop - document.body.clientTop
840 * Get the event offset from the target element.
842 * Given a target element and a pointer event, get the event offset from that
843 * element. To do this we need the element's position and the target position.
845 * @param {HTMLElement} target
846 * The target HTML element.
847 * @param {jQuery.Event} event
851 * An object with `x` and `y` keys indicating the position.
853 Drupal.tableDrag.prototype.getPointerOffset = function (target, event) {
854 var docPos = $(target).offset();
855 var pointerPos = this.pointerCoords(event);
856 return {x: pointerPos.x - docPos.left, y: pointerPos.y - docPos.top};
860 * Find the row the mouse is currently over.
862 * This row is then taken and swapped with the one being dragged.
865 * The x coordinate of the mouse on the page (not the screen).
867 * The y coordinate of the mouse on the page (not the screen).
870 * The drop target row, if found.
872 Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) {
873 var rows = $(this.table.tBodies[0].rows).not(':hidden');
874 for (var n = 0; n < rows.length; n++) {
877 var rowY = $row.offset().top;
879 // Because Safari does not report offsetHeight on table rows, but does on
880 // table cells, grab the firstChild of the row and use that instead.
881 // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari.
882 if (row.offsetHeight === 0) {
883 rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2;
887 rowHeight = parseInt(row.offsetHeight, 10) / 2;
890 // Because we always insert before, we need to offset the height a bit.
891 if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) {
892 if (this.indentEnabled) {
893 // Check that this row is not a child of the row being dragged.
894 for (n in this.rowObject.group) {
895 if (this.rowObject.group[n] === row) {
901 // Do not allow a row to be swapped with itself.
902 if (row === this.rowObject.element) {
907 // Check that swapping with this row is allowed.
908 if (!this.rowObject.isValidSwap(row)) {
912 // We may have found the row the mouse just passed over, but it doesn't
913 // take into account hidden rows. Skip backwards until we find a
915 while ($row.is(':hidden') && $row.prev('tr').is(':hidden')) {
916 $row = $row.prev('tr:first-of-type');
926 * After the row is dropped, update the table fields.
928 * @param {HTMLElement} changedRow
929 * DOM object for the row that was just dropped.
931 Drupal.tableDrag.prototype.updateFields = function (changedRow) {
932 for (var group in this.tableSettings) {
933 if (this.tableSettings.hasOwnProperty(group)) {
934 // Each group may have a different setting for relationship, so we find
935 // the source rows for each separately.
936 this.updateField(changedRow, group);
942 * After the row is dropped, update a single table field.
944 * @param {HTMLElement} changedRow
945 * DOM object for the row that was just dropped.
946 * @param {string} group
947 * The settings group on which field updates will occur.
949 Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
950 var rowSettings = this.rowSettings(group, changedRow);
951 var $changedRow = $(changedRow);
956 // Set the row as its own target.
957 if (rowSettings.relationship === 'self' || rowSettings.relationship === 'group') {
958 sourceRow = changedRow;
960 // Siblings are easy, check previous and next rows.
961 else if (rowSettings.relationship === 'sibling') {
962 $previousRow = $changedRow.prev('tr:first-of-type');
963 previousRow = $previousRow.get(0);
964 var $nextRow = $changedRow.next('tr:first-of-type');
965 var nextRow = $nextRow.get(0);
966 sourceRow = changedRow;
967 if ($previousRow.is('.draggable') && $previousRow.find('.' + group).length) {
968 if (this.indentEnabled) {
969 if ($previousRow.find('.js-indentations').length === $changedRow.find('.js-indentations').length) {
970 sourceRow = previousRow;
974 sourceRow = previousRow;
977 else if ($nextRow.is('.draggable') && $nextRow.find('.' + group).length) {
978 if (this.indentEnabled) {
979 if ($nextRow.find('.js-indentations').length === $changedRow.find('.js-indentations').length) {
988 // Parents, look up the tree until we find a field not in this group.
989 // Go up as many parents as indentations in the changed row.
990 else if (rowSettings.relationship === 'parent') {
991 $previousRow = $changedRow.prev('tr');
992 previousRow = $previousRow;
993 while ($previousRow.length && $previousRow.find('.js-indentation').length >= this.rowObject.indents) {
994 $previousRow = $previousRow.prev('tr');
995 previousRow = $previousRow;
997 // If we found a row.
998 if ($previousRow.length) {
999 sourceRow = $previousRow.get(0);
1001 // Otherwise we went all the way to the left of the table without finding
1002 // a parent, meaning this item has been placed at the root level.
1004 // Use the first row in the table as source, because it's guaranteed to
1005 // be at the root level. Find the first item, then compare this row
1006 // against it as a sibling.
1007 sourceRow = $(this.table).find('tr.draggable:first-of-type').get(0);
1008 if (sourceRow === this.rowObject.element) {
1009 sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
1015 // Because we may have moved the row from one category to another,
1016 // take a look at our sibling and borrow its sources and targets.
1017 this.copyDragClasses(sourceRow, changedRow, group);
1018 rowSettings = this.rowSettings(group, changedRow);
1020 // In the case that we're looking for a parent, but the row is at the top
1021 // of the tree, copy our sibling's values.
1023 rowSettings.relationship = 'sibling';
1024 rowSettings.source = rowSettings.target;
1027 var targetClass = '.' + rowSettings.target;
1028 var targetElement = $changedRow.find(targetClass).get(0);
1030 // Check if a target element exists in this row.
1031 if (targetElement) {
1032 var sourceClass = '.' + rowSettings.source;
1033 var sourceElement = $(sourceClass, sourceRow).get(0);
1034 switch (rowSettings.action) {
1036 // Get the depth of the target row.
1037 targetElement.value = $(sourceElement).closest('tr').find('.js-indentation').length;
1041 // Update the value.
1042 targetElement.value = sourceElement.value;
1046 var siblings = this.rowObject.findSiblings(rowSettings);
1047 if ($(targetElement).is('select')) {
1048 // Get a list of acceptable values.
1050 $(targetElement).find('option').each(function () {
1051 values.push(this.value);
1053 var maxVal = values[values.length - 1];
1054 // Populate the values in the siblings.
1055 $(siblings).find(targetClass).each(function () {
1056 // If there are more items than possible values, assign the
1057 // maximum value to the row.
1058 if (values.length > 0) {
1059 this.value = values.shift();
1062 this.value = maxVal;
1067 // Assume a numeric input field.
1068 var weight = parseInt($(siblings[0]).find(targetClass).val(), 10) || 0;
1069 $(siblings).find(targetClass).each(function () {
1070 this.value = weight;
1080 * Copy all tableDrag related classes from one row to another.
1082 * Copy all special tableDrag classes from one row's form elements to a
1083 * different one, removing any special classes that the destination row
1086 * @param {HTMLElement} sourceRow
1087 * The element for the source row.
1088 * @param {HTMLElement} targetRow
1089 * The element for the target row.
1090 * @param {string} group
1091 * The group selector.
1093 Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) {
1094 var sourceElement = $(sourceRow).find('.' + group);
1095 var targetElement = $(targetRow).find('.' + group);
1096 if (sourceElement.length && targetElement.length) {
1097 targetElement[0].className = sourceElement[0].className;
1102 * Check the suggested scroll of the table.
1104 * @param {number} cursorY
1105 * The Y position of the cursor.
1108 * The suggested scroll.
1110 Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
1111 var de = document.documentElement;
1112 var b = document.body;
1114 var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth !== 0 ? de.clientHeight : b.offsetHeight);
1117 scrollY = this.scrollY = !de.scrollTop ? b.scrollTop : de.scrollTop;
1120 scrollY = this.scrollY = window.pageYOffset ? window.pageYOffset : window.scrollY;
1122 var trigger = this.scrollSettings.trigger;
1125 // Return a scroll speed relative to the edge of the screen.
1126 if (cursorY - scrollY > windowHeight - trigger) {
1127 delta = trigger / (windowHeight + scrollY - cursorY);
1128 delta = (delta > 0 && delta < trigger) ? delta : trigger;
1129 return delta * this.scrollSettings.amount;
1131 else if (cursorY - scrollY < trigger) {
1132 delta = trigger / (cursorY - scrollY);
1133 delta = (delta > 0 && delta < trigger) ? delta : trigger;
1134 return -delta * this.scrollSettings.amount;
1139 * Set the scroll for the table.
1141 * @param {number} scrollAmount
1142 * The amount of scroll to apply to the window.
1144 Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
1147 this.scrollInterval = setInterval(function () {
1148 // Update the scroll values stored in the object.
1149 self.checkScroll(self.currentPointerCoords.y);
1150 var aboveTable = self.scrollY > self.table.topY;
1151 var belowTable = self.scrollY + self.windowHeight < self.table.bottomY;
1152 if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) {
1153 window.scrollBy(0, scrollAmount);
1155 }, this.scrollSettings.interval);
1159 * Command to restripe table properly.
1161 Drupal.tableDrag.prototype.restripeTable = function () {
1162 // :even and :odd are reversed because jQuery counts from 0 and
1163 // we count from 1, so we're out of sync.
1164 // Match immediate children of the parent element to allow nesting.
1165 $(this.table).find('> tbody > tr.draggable, > tr.draggable')
1167 .filter(':odd').removeClass('odd').addClass('even').end()
1168 .filter(':even').removeClass('even').addClass('odd');
1172 * Stub function. Allows a custom handler when a row begins dragging.
1175 * Returns null when the stub function is used.
1177 Drupal.tableDrag.prototype.onDrag = function () {
1182 * Stub function. Allows a custom handler when a row is dropped.
1185 * Returns null when the stub function is used.
1187 Drupal.tableDrag.prototype.onDrop = function () {
1192 * Constructor to make a new object to manipulate a table row.
1194 * @param {HTMLElement} tableRow
1195 * The DOM element for the table row we will be manipulating.
1196 * @param {string} method
1197 * The method in which this row is being moved. Either 'keyboard' or
1199 * @param {bool} indentEnabled
1200 * Whether the containing table uses indentations. Used for optimizations.
1201 * @param {number} maxDepth
1202 * The maximum amount of indentations this row may contain.
1203 * @param {bool} addClasses
1204 * Whether we want to add classes to this row to indicate child
1207 Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
1208 var $tableRow = $(tableRow);
1210 this.element = tableRow;
1211 this.method = method;
1212 this.group = [tableRow];
1213 this.groupDepth = $tableRow.find('.js-indentation').length;
1214 this.changed = false;
1215 this.table = $tableRow.closest('table')[0];
1216 this.indentEnabled = indentEnabled;
1217 this.maxDepth = maxDepth;
1218 // Direction the row is being moved.
1219 this.direction = '';
1220 if (this.indentEnabled) {
1221 this.indents = $tableRow.find('.js-indentation').length;
1222 this.children = this.findChildren(addClasses);
1223 this.group = $.merge(this.group, this.children);
1224 // Find the depth of this entire group.
1225 for (var n = 0; n < this.group.length; n++) {
1226 this.groupDepth = Math.max($(this.group[n]).find('.js-indentation').length, this.groupDepth);
1232 * Find all children of rowObject by indentation.
1234 * @param {bool} addClasses
1235 * Whether we want to add classes to this row to indicate child
1239 * An array of children of the row.
1241 Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
1242 var parentIndentation = this.indents;
1243 var currentRow = $(this.element, this.table).next('tr.draggable');
1247 function rowIndentation(indentNum, el) {
1249 if (child === 1 && (indentNum === parentIndentation)) {
1250 self.addClass('tree-child-first');
1252 if (indentNum === parentIndentation) {
1253 self.addClass('tree-child');
1255 else if (indentNum > parentIndentation) {
1256 self.addClass('tree-child-horizontal');
1260 while (currentRow.length) {
1261 // A greater indentation indicates this is a child.
1262 if (currentRow.find('.js-indentation').length > parentIndentation) {
1264 rows.push(currentRow[0]);
1266 currentRow.find('.js-indentation').each(rowIndentation);
1272 currentRow = currentRow.next('tr.draggable');
1274 if (addClasses && rows.length) {
1275 $(rows[rows.length - 1]).find('.js-indentation:nth-child(' + (parentIndentation + 1) + ')').addClass('tree-child-last');
1281 * Ensure that two rows are allowed to be swapped.
1283 * @param {HTMLElement} row
1284 * DOM object for the row being considered for swapping.
1287 * Whether the swap is a valid swap or not.
1289 Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
1291 if (this.indentEnabled) {
1294 if (this.direction === 'down') {
1296 nextRow = $row.next('tr').get(0);
1299 prevRow = $row.prev('tr').get(0);
1302 this.interval = this.validIndentInterval(prevRow, nextRow);
1304 // We have an invalid swap if the valid indentations interval is empty.
1305 if (this.interval.min > this.interval.max) {
1310 // Do not let an un-draggable first row have anything put before it.
1311 if (this.table.tBodies[0].rows[0] === row && $row.is(':not(.draggable)')) {
1319 * Perform the swap between two rows.
1321 * @param {string} position
1322 * Whether the swap will occur 'before' or 'after' the given row.
1323 * @param {HTMLElement} row
1324 * DOM element what will be swapped with the row group.
1326 Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) {
1327 // Makes sure only DOM object are passed to Drupal.detachBehaviors().
1328 this.group.forEach(function (row) {
1329 Drupal.detachBehaviors(row, drupalSettings, 'move');
1331 $(row)[position](this.group);
1332 // Makes sure only DOM object are passed to Drupal.attachBehaviors()s.
1333 this.group.forEach(function (row) {
1334 Drupal.attachBehaviors(row, drupalSettings);
1336 this.changed = true;
1341 * Determine the valid indentations interval for the row at a given position.
1343 * @param {?HTMLElement} prevRow
1344 * DOM object for the row before the tested position
1345 * (or null for first position in the table).
1346 * @param {?HTMLElement} nextRow
1347 * DOM object for the row after the tested position
1348 * (or null for last position in the table).
1351 * An object with the keys `min` and `max` to indicate the valid indent
1354 Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) {
1355 var $prevRow = $(prevRow);
1359 // Minimum indentation:
1360 // Do not orphan the next row.
1361 minIndent = nextRow ? $(nextRow).find('.js-indentation').length : 0;
1363 // Maximum indentation:
1364 if (!prevRow || $prevRow.is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) {
1366 // - the first row in the table,
1367 // - rows dragged below a non-draggable row,
1372 // Do not go deeper than as a child of the previous row.
1373 maxIndent = $prevRow.find('.js-indentation').length + ($prevRow.is('.tabledrag-leaf') ? 0 : 1);
1374 // Limit by the maximum allowed depth for the table.
1375 if (this.maxDepth) {
1376 maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents));
1380 return {min: minIndent, max: maxIndent};
1384 * Indent a row within the legal bounds of the table.
1386 * @param {number} indentDiff
1387 * The number of additional indentations proposed for the row (can be
1388 * positive or negative). This number will be adjusted to nearest valid
1389 * indentation level for the row.
1392 * The number of indentations applied.
1394 Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) {
1395 var $group = $(this.group);
1396 // Determine the valid indentations interval if not available yet.
1397 if (!this.interval) {
1398 var prevRow = $(this.element).prev('tr').get(0);
1399 var nextRow = $group.eq(-1).next('tr').get(0);
1400 this.interval = this.validIndentInterval(prevRow, nextRow);
1403 // Adjust to the nearest valid indentation.
1404 var indent = this.indents + indentDiff;
1405 indent = Math.max(indent, this.interval.min);
1406 indent = Math.min(indent, this.interval.max);
1407 indentDiff = indent - this.indents;
1409 for (var n = 1; n <= Math.abs(indentDiff); n++) {
1410 // Add or remove indentations.
1411 if (indentDiff < 0) {
1412 $group.find('.js-indentation:first-of-type').remove();
1416 $group.find('td:first-of-type').prepend(Drupal.theme('tableDragIndentation'));
1421 // Update indentation for this row.
1422 this.changed = true;
1423 this.groupDepth += indentDiff;
1431 * Find all siblings for a row.
1433 * According to its subgroup or indentation. Note that the passed-in row is
1434 * included in the list of siblings.
1436 * @param {object} rowSettings
1437 * The field settings we're using to identify what constitutes a sibling.
1440 * An array of siblings.
1442 Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) {
1444 var directions = ['prev', 'next'];
1445 var rowIndentation = this.indents;
1446 var checkRowIndentation;
1447 for (var d = 0; d < directions.length; d++) {
1448 var checkRow = $(this.element)[directions[d]]();
1449 while (checkRow.length) {
1450 // Check that the sibling contains a similar target field.
1451 if (checkRow.find('.' + rowSettings.target)) {
1452 // Either add immediately if this is a flat table, or check to ensure
1453 // that this row has the same level of indentation.
1454 if (this.indentEnabled) {
1455 checkRowIndentation = checkRow.find('.js-indentation').length;
1458 if (!(this.indentEnabled) || (checkRowIndentation === rowIndentation)) {
1459 siblings.push(checkRow[0]);
1461 else if (checkRowIndentation < rowIndentation) {
1462 // No need to keep looking for siblings when we get to a parent.
1469 checkRow = checkRow[directions[d]]();
1471 // Since siblings are added in reverse order for previous, reverse the
1472 // completed list of previous siblings. Add the current row and continue.
1473 if (directions[d] === 'prev') {
1475 siblings.push(this.element);
1482 * Remove indentation helper classes from the current row group.
1484 Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () {
1485 for (var n in this.children) {
1486 if (this.children.hasOwnProperty(n)) {
1487 $(this.children[n]).find('.js-indentation')
1488 .removeClass('tree-child')
1489 .removeClass('tree-child-first')
1490 .removeClass('tree-child-last')
1491 .removeClass('tree-child-horizontal');
1497 * Add an asterisk or other marker to the changed row.
1499 Drupal.tableDrag.prototype.row.prototype.markChanged = function () {
1500 var marker = Drupal.theme('tableDragChangedMarker');
1501 var cell = $(this.element).find('td:first-of-type');
1502 if (cell.find('abbr.tabledrag-changed').length === 0) {
1503 cell.append(marker);
1508 * Stub function. Allows a custom handler when a row is indented.
1511 * Returns null when the stub function is used.
1513 Drupal.tableDrag.prototype.row.prototype.onIndent = function () {
1518 * Stub function. Allows a custom handler when a row is swapped.
1520 * @param {HTMLElement} swappedRow
1521 * The element for the swapped row.
1524 * Returns null when the stub function is used.
1526 Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
1530 $.extend(Drupal.theme, /** @lends Drupal.theme */{
1534 * Markup for the marker.
1536 tableDragChangedMarker: function () {
1537 return '<abbr class="warning tabledrag-changed" title="' + Drupal.t('Changed') + '">*</abbr>';
1542 * Markup for the indentation.
1544 tableDragIndentation: function () {
1545 return '<div class="js-indentation indentation"> </div>';
1550 * Markup for the warning.
1552 tableDragChangedWarning: function () {
1553 return '<div class="tabledrag-changed-warning messages messages--warning" role="alert">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('You have unsaved changes.') + '</div>';
1557 })(jQuery, Drupal, drupalSettings);