Backup of db before drupal security update
[yaffs-website] / web / core / misc / tabledrag.js
1 /**
2  * @file
3  * Provide dragging capabilities to admin uis.
4  */
5
6 /**
7  * Triggers when weights columns are toggled.
8  *
9  * @event columnschange
10  */
11
12 (function ($, Drupal, drupalSettings) {
13
14   'use strict';
15
16   /**
17    * Store the state of weight columns display for all tables.
18    *
19    * Default value is to hide weight columns.
20    */
21   var showWeight = JSON.parse(localStorage.getItem('Drupal.tableDrag.showWeight'));
22
23   /**
24    * Drag and drop table rows with field manipulation.
25    *
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.
29    *
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
33    * tableDrag.
34    *
35    * @type {Drupal~behavior}
36    */
37   Drupal.behaviors.tableDrag = {
38     attach: function (context, settings) {
39       function initTableDrag(table, base) {
40         if (table.length) {
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]);
44         }
45       }
46
47       for (var base in settings.tableDrag) {
48         if (settings.tableDrag.hasOwnProperty(base)) {
49           initTableDrag($(context).find('#' + base).once('tabledrag'), base);
50         }
51       }
52     }
53   };
54
55   /**
56    * Provides table and field manipulation.
57    *
58    * @constructor
59    *
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().
64    */
65   Drupal.tableDrag = function (table, tableSettings) {
66     var self = this;
67     var $table = $(table);
68
69     /**
70      * @type {jQuery}
71      */
72     this.$table = $(table);
73
74     /**
75      *
76      * @type {HTMLElement}
77      */
78     this.table = table;
79
80     /**
81      * @type {object}
82      */
83     this.tableSettings = tableSettings;
84
85     /**
86      * Used to hold information about a current drag operation.
87      *
88      * @type {?HTMLElement}
89      */
90     this.dragObject = null;
91
92     /**
93      * Provides operations for row manipulation.
94      *
95      * @type {?HTMLElement}
96      */
97     this.rowObject = null;
98
99     /**
100      * Remember the previous element.
101      *
102      * @type {?HTMLElement}
103      */
104     this.oldRowElement = null;
105
106     /**
107      * Used to determine up or down direction from last mouse move.
108      *
109      * @type {number}
110      */
111     this.oldY = 0;
112
113     /**
114      * Whether anything in the entire table has changed.
115      *
116      * @type {bool}
117      */
118     this.changed = false;
119
120     /**
121      * Maximum amount of allowed parenting.
122      *
123      * @type {number}
124      */
125     this.maxDepth = 0;
126
127     /**
128      * Direction of the table.
129      *
130      * @type {number}
131      */
132     this.rtl = $(this.table).css('direction') === 'rtl' ? -1 : 1;
133
134     /**
135      *
136      * @type {bool}
137      */
138     this.striping = $(this.table).data('striping') === 1;
139
140     /**
141      * Configure the scroll settings.
142      *
143      * @type {object}
144      *
145      * @prop {number} amount
146      * @prop {number} interval
147      * @prop {number} trigger
148      */
149     this.scrollSettings = {amount: 4, interval: 50, trigger: 70};
150
151     /**
152      *
153      * @type {?number}
154      */
155     this.scrollInterval = null;
156
157     /**
158      *
159      * @type {number}
160      */
161     this.scrollY = 0;
162
163     /**
164      *
165      * @type {number}
166      */
167     this.windowHeight = 0;
168
169     /**
170      * Check this table's settings for parent relationships.
171      *
172      * For efficiency, large sections of code can be skipped if we don't need to
173      * track horizontal movement and indentations.
174      *
175      * @type {bool}
176      */
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;
184             }
185             if (tableSettings[group][n].limit > 0) {
186               this.maxDepth = tableSettings[group][n].limit;
187             }
188           }
189         }
190       }
191     }
192     if (this.indentEnabled) {
193
194       /**
195        * Total width of indents, set in makeDraggable.
196        *
197        * @type {number}
198        */
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');
208
209       /**
210        *
211        * @type {number}
212        */
213       this.indentAmount = $indentation.get(1).offsetLeft - $indentation.get(0).offsetLeft;
214       testRow.remove();
215     }
216
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); });
220
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) {
225         e.preventDefault();
226         this.toggleColumns();
227       }, this))
228       .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>')
229       .parent()
230     );
231
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..
236     self.initColumns();
237
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); });
244
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
250         // window.
251         showWeight = JSON.parse(e.originalEvent.newValue);
252         this.displayColumns(showWeight);
253       }
254     }, this));
255   };
256
257   /**
258    * Initialize columns containing form elements to be hidden by default.
259    *
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.
263    */
264   Drupal.tableDrag.prototype.initColumns = function () {
265     var $table = this.$table;
266     var hidden;
267     var cell;
268     var columnIndex;
269     for (var group in this.tableSettings) {
270       if (this.tableSettings.hasOwnProperty(group)) {
271
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');
279               break;
280             }
281           }
282         }
283
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
288           // nesting.
289           columnIndex = cell.parent().find('> td').index(cell.get(0)) + 1;
290           $table.find('> thead > tr, > tbody > tr, > tr').each(this.addColspanClass(columnIndex));
291         }
292       }
293     }
294     this.displayColumns(showWeight);
295   };
296
297   /**
298    * Mark cells that have colspan.
299    *
300    * In order to adjust the colspan instead of hiding them altogether.
301    *
302    * @param {number} columnIndex
303    *   The column index to add colspan class to.
304    *
305    * @return {function}
306    *   Function to add colspan class.
307    */
308   Drupal.tableDrag.prototype.addColspanClass = function (columnIndex) {
309     return function () {
310       // Get the columnIndex and adjust for any colspans in this row.
311       var $row = $(this);
312       var index = columnIndex;
313       var cells = $row.children();
314       var cell;
315       cells.each(function (n) {
316         if (n < index && this.colSpan && this.colSpan > 1) {
317           index -= this.colSpan - 1;
318         }
319       });
320       if (index > 0) {
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');
325         }
326         else {
327           // Mark this cell so we can hide it.
328           cell.addClass('tabledrag-hide');
329         }
330       }
331     };
332   };
333
334   /**
335    * Hide or display weight columns. Triggers an event on change.
336    *
337    * @fires event:columnschange
338    *
339    * @param {bool} displayWeight
340    *   'true' will show weight columns.
341    */
342   Drupal.tableDrag.prototype.displayColumns = function (displayWeight) {
343     if (displayWeight) {
344       this.showColumns();
345     }
346     // Default action is to hide columns.
347     else {
348       this.hideColumns();
349     }
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);
353   };
354
355   /**
356    * Toggle the weight column depending on 'showWeight' value.
357    *
358    * Store only default override.
359    */
360   Drupal.tableDrag.prototype.toggleColumns = function () {
361     showWeight = !showWeight;
362     this.displayColumns(showWeight);
363     if (showWeight) {
364       // Save default override.
365       localStorage.setItem('Drupal.tableDrag.showWeight', showWeight);
366     }
367     else {
368       // Reset the value to its default.
369       localStorage.removeItem('Drupal.tableDrag.showWeight');
370     }
371   };
372
373   /**
374    * Hide the columns containing weight/parent form elements.
375    *
376    * Undo showColumns().
377    */
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;
387     });
388     // Change link text.
389     $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights'));
390   };
391
392   /**
393    * Show the columns containing weight/parent form elements.
394    *
395    * Undo hideColumns().
396    */
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;
406     });
407     // Change link text.
408     $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights'));
409   };
410
411   /**
412    * Find the target used within a particular row and group.
413    *
414    * @param {string} group
415    *   Group selector.
416    * @param {HTMLElement} row
417    *   The row HTML element.
418    *
419    * @return {object}
420    *   The table row settings.
421    */
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];
434             }
435           }
436           return rowSettings;
437         }
438       }
439     }
440   };
441
442   /**
443    * Take an item and add event handlers to make it become draggable.
444    *
445    * @param {HTMLElement} item
446    *   The item to add event handlers to.
447    */
448   Drupal.tableDrag.prototype.makeDraggable = function (item) {
449     var self = this;
450     var $item = $(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">&nbsp;</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);
461     }
462     else {
463       $item.find('td').eq(0).prepend(handle);
464     }
465
466     handle.on('mousedown touchstart pointerdown', function (event) {
467       event.preventDefault();
468       if (event.originalEvent.type === 'touchstart') {
469         event = event.originalEvent.touches[0];
470       }
471       self.dragStart(event, self, item);
472     });
473
474     // Prevent the anchor tag from jumping us to the top of the page.
475     handle.on('click', function (e) {
476       e.preventDefault();
477     });
478
479     // Set blur cleanup when a handle is focused.
480     handle.on('focus', function () {
481       self.safeBlur = true;
482     });
483
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);
489       }
490     });
491
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);
497       }
498
499       var keyChange = false;
500       var groupHeight;
501
502       /* eslint-disable no-fallthrough */
503
504       switch (event.keyCode) {
505         // Left arrow.
506         case 37:
507         // Safari left arrow.
508         case 63234:
509           keyChange = true;
510           self.rowObject.indent(-1 * self.rtl);
511           break;
512
513         // Up arrow.
514         case 38:
515         // Safari up arrow.
516         case 63232:
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);
522           }
523           if (previousRow) {
524             // Do not allow the onBlur cleanup.
525             self.safeBlur = false;
526             self.rowObject.direction = 'up';
527             keyChange = true;
528
529             if ($(item).is('.tabledrag-root')) {
530               // Swap with the previous top-level row.
531               groupHeight = 0;
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;
536               }
537               if (previousRow) {
538                 self.rowObject.swap('before', previousRow);
539                 // No need to check for indentation, 0 is the only valid one.
540                 window.scrollBy(0, -groupHeight);
541               }
542             }
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));
550             }
551             // Regain focus after the DOM manipulation.
552             handle.trigger('focus');
553           }
554           break;
555
556         // Right arrow.
557         case 39:
558         // Safari right arrow.
559         case 63235:
560           keyChange = true;
561           self.rowObject.indent(self.rtl);
562           break;
563
564         // Down arrow.
565         case 40:
566         // Safari down arrow.
567         case 63233:
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);
573           }
574           if (nextRow) {
575             // Do not allow the onBlur cleanup.
576             self.safeBlur = false;
577             self.rowObject.direction = 'down';
578             keyChange = true;
579
580             if ($(item).is('.tabledrag-root')) {
581               // Swap with the next group (necessarily a top-level one).
582               groupHeight = 0;
583               var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false);
584               if (nextGroup) {
585                 $(nextGroup.group).each(function () {
586                   groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight;
587                 });
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));
592               }
593             }
594             else {
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));
600             }
601             // Regain focus after the DOM manipulation.
602             handle.trigger('focus');
603           }
604           break;
605       }
606
607       /* eslint-enable no-fallthrough */
608
609       if (self.rowObject && self.rowObject.changed === true) {
610         $(item).addClass('drag');
611         if (self.oldRowElement) {
612           $(self.oldRowElement).removeClass('drag-previous');
613         }
614         self.oldRowElement = item;
615         if (self.striping === true) {
616           self.restripeTable();
617         }
618         self.onDrag();
619       }
620
621       // Returning false if we have an arrow key to prevent scrolling.
622       if (keyChange) {
623         return false;
624       }
625     });
626
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) {
632
633       /* eslint-disable no-fallthrough */
634
635       switch (event.keyCode) {
636         // Left arrow.
637         case 37:
638         // Up arrow.
639         case 38:
640         // Right arrow.
641         case 39:
642         // Down arrow.
643         case 40:
644           return false;
645       }
646
647       /* eslint-enable no-fallthrough */
648
649     });
650   };
651
652   /**
653    * Pointer event initiator, creates drag object and information.
654    *
655    * @param {jQuery.Event} event
656    *   The event object that trigger the drag.
657    * @param {Drupal.tableDrag} self
658    *   The drag handle.
659    * @param {HTMLElement} item
660    *   The item that that is being dragged.
661    */
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;
669     }
670
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');
674     }
675
676     // Create a new rowObject for manipulation of this row.
677     self.rowObject = new self.row(item, 'pointer', self.indentEnabled, self.maxDepth, true);
678
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;
682
683     // Add classes to the handle and row.
684     $(item).addClass('drag');
685
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');
690     }
691   };
692
693   /**
694    * Pointer movement handler, bound to document.
695    *
696    * @param {jQuery.Event} event
697    *   The pointer event.
698    * @param {Drupal.tableDrag} self
699    *   The tableDrag instance.
700    *
701    * @return {bool|undefined}
702    *   Undefined if no dragObject is defined, false otherwise.
703    */
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;
709
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.
714         self.oldY = y;
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);
722         }
723
724         // If we have a valid target, perform the swap and restripe the table.
725         var currentRow = self.findDropTargetRow(x, y);
726         if (currentRow) {
727           if (self.rowObject.direction === 'down') {
728             self.rowObject.swap('after', currentRow, self);
729           }
730           else {
731             self.rowObject.swap('before', currentRow, self);
732           }
733           if (self.striping === true) {
734             self.restripeTable();
735           }
736         }
737       }
738
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
743         // right.
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);
751       }
752
753       return false;
754     }
755   };
756
757   /**
758    * Pointerup behavior.
759    *
760    * @param {jQuery.Event} event
761    *   The pointer event.
762    * @param {Drupal.tableDrag} self
763    *   The tableDrag instance.
764    */
765   Drupal.tableDrag.prototype.dropRow = function (event, self) {
766     var droppedRow;
767     var $droppedRow;
768
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);
777
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);
787                 }
788               }
789             }
790           }
791         }
792
793         self.rowObject.markChanged();
794         if (self.changed === false) {
795           $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');
796           self.changed = true;
797         }
798       }
799
800       if (self.indentEnabled) {
801         self.rowObject.removeIndentClasses();
802       }
803       if (self.oldRowElement) {
804         $(self.oldRowElement).removeClass('drag-previous');
805       }
806       $droppedRow.removeClass('drag').addClass('drag-previous');
807       self.oldRowElement = droppedRow;
808       self.onDrop();
809       self.rowObject = null;
810     }
811
812     // Functionality specific only to pointerup events.
813     if (self.dragObject !== null) {
814       self.dragObject = null;
815       $('body').removeClass('drag');
816       clearInterval(self.scrollInterval);
817     }
818   };
819
820   /**
821    * Get the coordinates from the event (allowing for browser differences).
822    *
823    * @param {jQuery.Event} event
824    *   The pointer event.
825    *
826    * @return {object}
827    *   An object with `x` and `y` keys indicating the position.
828    */
829   Drupal.tableDrag.prototype.pointerCoords = function (event) {
830     if (event.pageX || event.pageY) {
831       return {x: event.pageX, y: event.pageY};
832     }
833     return {
834       x: event.clientX + document.body.scrollLeft - document.body.clientLeft,
835       y: event.clientY + document.body.scrollTop - document.body.clientTop
836     };
837   };
838
839   /**
840    * Get the event offset from the target element.
841    *
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.
844    *
845    * @param {HTMLElement} target
846    *   The target HTML element.
847    * @param {jQuery.Event} event
848    *   The pointer event.
849    *
850    * @return {object}
851    *   An object with `x` and `y` keys indicating the position.
852    */
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};
857   };
858
859   /**
860    * Find the row the mouse is currently over.
861    *
862    * This row is then taken and swapped with the one being dragged.
863    *
864    * @param {number} x
865    *   The x coordinate of the mouse on the page (not the screen).
866    * @param {number} y
867    *   The y coordinate of the mouse on the page (not the screen).
868    *
869    * @return {*}
870    *   The drop target row, if found.
871    */
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++) {
875       var row = rows[n];
876       var $row = $(row);
877       var rowY = $row.offset().top;
878       var rowHeight;
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;
884       }
885       // Other browsers.
886       else {
887         rowHeight = parseInt(row.offsetHeight, 10) / 2;
888       }
889
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) {
896               return null;
897             }
898           }
899         }
900         else {
901           // Do not allow a row to be swapped with itself.
902           if (row === this.rowObject.element) {
903             return null;
904           }
905         }
906
907         // Check that swapping with this row is allowed.
908         if (!this.rowObject.isValidSwap(row)) {
909           return null;
910         }
911
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
914         // draggable row.
915         while ($row.is(':hidden') && $row.prev('tr').is(':hidden')) {
916           $row = $row.prev('tr:first-of-type');
917           row = $row.get(0);
918         }
919         return row;
920       }
921     }
922     return null;
923   };
924
925   /**
926    * After the row is dropped, update the table fields.
927    *
928    * @param {HTMLElement} changedRow
929    *   DOM object for the row that was just dropped.
930    */
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);
937       }
938     }
939   };
940
941   /**
942    * After the row is dropped, update a single table field.
943    *
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.
948    */
949   Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
950     var rowSettings = this.rowSettings(group, changedRow);
951     var $changedRow = $(changedRow);
952     var sourceRow;
953     var $previousRow;
954     var previousRow;
955     var useSibling;
956     // Set the row as its own target.
957     if (rowSettings.relationship === 'self' || rowSettings.relationship === 'group') {
958       sourceRow = changedRow;
959     }
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;
971           }
972         }
973         else {
974           sourceRow = previousRow;
975         }
976       }
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) {
980             sourceRow = nextRow;
981           }
982         }
983         else {
984           sourceRow = nextRow;
985         }
986       }
987     }
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;
996       }
997       // If we found a row.
998       if ($previousRow.length) {
999         sourceRow = $previousRow.get(0);
1000       }
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.
1003       else {
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);
1010         }
1011         useSibling = true;
1012       }
1013     }
1014
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);
1019
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.
1022     if (useSibling) {
1023       rowSettings.relationship = 'sibling';
1024       rowSettings.source = rowSettings.target;
1025     }
1026
1027     var targetClass = '.' + rowSettings.target;
1028     var targetElement = $changedRow.find(targetClass).get(0);
1029
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) {
1035         case 'depth':
1036           // Get the depth of the target row.
1037           targetElement.value = $(sourceElement).closest('tr').find('.js-indentation').length;
1038           break;
1039
1040         case 'match':
1041           // Update the value.
1042           targetElement.value = sourceElement.value;
1043           break;
1044
1045         case 'order':
1046           var siblings = this.rowObject.findSiblings(rowSettings);
1047           if ($(targetElement).is('select')) {
1048             // Get a list of acceptable values.
1049             var values = [];
1050             $(targetElement).find('option').each(function () {
1051               values.push(this.value);
1052             });
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();
1060               }
1061               else {
1062                 this.value = maxVal;
1063               }
1064             });
1065           }
1066           else {
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;
1071               weight++;
1072             });
1073           }
1074           break;
1075       }
1076     }
1077   };
1078
1079   /**
1080    * Copy all tableDrag related classes from one row to another.
1081    *
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
1084    * may have had.
1085    *
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.
1092    */
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;
1098     }
1099   };
1100
1101   /**
1102    * Check the suggested scroll of the table.
1103    *
1104    * @param {number} cursorY
1105    *   The Y position of the cursor.
1106    *
1107    * @return {number}
1108    *   The suggested scroll.
1109    */
1110   Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
1111     var de = document.documentElement;
1112     var b = document.body;
1113
1114     var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth !== 0 ? de.clientHeight : b.offsetHeight);
1115     var scrollY;
1116     if (document.all) {
1117       scrollY = this.scrollY = !de.scrollTop ? b.scrollTop : de.scrollTop;
1118     }
1119     else {
1120       scrollY = this.scrollY = window.pageYOffset ? window.pageYOffset : window.scrollY;
1121     }
1122     var trigger = this.scrollSettings.trigger;
1123     var delta = 0;
1124
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;
1130     }
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;
1135     }
1136   };
1137
1138   /**
1139    * Set the scroll for the table.
1140    *
1141    * @param {number} scrollAmount
1142    *   The amount of scroll to apply to the window.
1143    */
1144   Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
1145     var self = this;
1146
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);
1154       }
1155     }, this.scrollSettings.interval);
1156   };
1157
1158   /**
1159    * Command to restripe table properly.
1160    */
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')
1166       .filter(':visible')
1167       .filter(':odd').removeClass('odd').addClass('even').end()
1168       .filter(':even').removeClass('even').addClass('odd');
1169   };
1170
1171   /**
1172    * Stub function. Allows a custom handler when a row begins dragging.
1173    *
1174    * @return {null}
1175    *   Returns null when the stub function is used.
1176    */
1177   Drupal.tableDrag.prototype.onDrag = function () {
1178     return null;
1179   };
1180
1181   /**
1182    * Stub function. Allows a custom handler when a row is dropped.
1183    *
1184    * @return {null}
1185    *   Returns null when the stub function is used.
1186    */
1187   Drupal.tableDrag.prototype.onDrop = function () {
1188     return null;
1189   };
1190
1191   /**
1192    * Constructor to make a new object to manipulate a table row.
1193    *
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
1198    *   'mouse'.
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
1205    *   relationships.
1206    */
1207   Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
1208     var $tableRow = $(tableRow);
1209
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);
1227       }
1228     }
1229   };
1230
1231   /**
1232    * Find all children of rowObject by indentation.
1233    *
1234    * @param {bool} addClasses
1235    *   Whether we want to add classes to this row to indicate child
1236    *   relationships.
1237    *
1238    * @return {Array}
1239    *   An array of children of the row.
1240    */
1241   Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
1242     var parentIndentation = this.indents;
1243     var currentRow = $(this.element, this.table).next('tr.draggable');
1244     var rows = [];
1245     var child = 0;
1246
1247     function rowIndentation(indentNum, el) {
1248       var self = $(el);
1249       if (child === 1 && (indentNum === parentIndentation)) {
1250         self.addClass('tree-child-first');
1251       }
1252       if (indentNum === parentIndentation) {
1253         self.addClass('tree-child');
1254       }
1255       else if (indentNum > parentIndentation) {
1256         self.addClass('tree-child-horizontal');
1257       }
1258     }
1259
1260     while (currentRow.length) {
1261       // A greater indentation indicates this is a child.
1262       if (currentRow.find('.js-indentation').length > parentIndentation) {
1263         child++;
1264         rows.push(currentRow[0]);
1265         if (addClasses) {
1266           currentRow.find('.js-indentation').each(rowIndentation);
1267         }
1268       }
1269       else {
1270         break;
1271       }
1272       currentRow = currentRow.next('tr.draggable');
1273     }
1274     if (addClasses && rows.length) {
1275       $(rows[rows.length - 1]).find('.js-indentation:nth-child(' + (parentIndentation + 1) + ')').addClass('tree-child-last');
1276     }
1277     return rows;
1278   };
1279
1280   /**
1281    * Ensure that two rows are allowed to be swapped.
1282    *
1283    * @param {HTMLElement} row
1284    *   DOM object for the row being considered for swapping.
1285    *
1286    * @return {bool}
1287    *   Whether the swap is a valid swap or not.
1288    */
1289   Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
1290     var $row = $(row);
1291     if (this.indentEnabled) {
1292       var prevRow;
1293       var nextRow;
1294       if (this.direction === 'down') {
1295         prevRow = row;
1296         nextRow = $row.next('tr').get(0);
1297       }
1298       else {
1299         prevRow = $row.prev('tr').get(0);
1300         nextRow = row;
1301       }
1302       this.interval = this.validIndentInterval(prevRow, nextRow);
1303
1304       // We have an invalid swap if the valid indentations interval is empty.
1305       if (this.interval.min > this.interval.max) {
1306         return false;
1307       }
1308     }
1309
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)')) {
1312       return false;
1313     }
1314
1315     return true;
1316   };
1317
1318   /**
1319    * Perform the swap between two rows.
1320    *
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.
1325    */
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');
1330     });
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);
1335     });
1336     this.changed = true;
1337     this.onSwap(row);
1338   };
1339
1340   /**
1341    * Determine the valid indentations interval for the row at a given position.
1342    *
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).
1349    *
1350    * @return {object}
1351    *   An object with the keys `min` and `max` to indicate the valid indent
1352    *   interval.
1353    */
1354   Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) {
1355     var $prevRow = $(prevRow);
1356     var minIndent;
1357     var maxIndent;
1358
1359     // Minimum indentation:
1360     // Do not orphan the next row.
1361     minIndent = nextRow ? $(nextRow).find('.js-indentation').length : 0;
1362
1363     // Maximum indentation:
1364     if (!prevRow || $prevRow.is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) {
1365       // Do not indent:
1366       // - the first row in the table,
1367       // - rows dragged below a non-draggable row,
1368       // - 'root' rows.
1369       maxIndent = 0;
1370     }
1371     else {
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));
1377       }
1378     }
1379
1380     return {min: minIndent, max: maxIndent};
1381   };
1382
1383   /**
1384    * Indent a row within the legal bounds of the table.
1385    *
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.
1390    *
1391    * @return {number}
1392    *   The number of indentations applied.
1393    */
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);
1401     }
1402
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;
1408
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();
1413         this.indents--;
1414       }
1415       else {
1416         $group.find('td:first-of-type').prepend(Drupal.theme('tableDragIndentation'));
1417         this.indents++;
1418       }
1419     }
1420     if (indentDiff) {
1421       // Update indentation for this row.
1422       this.changed = true;
1423       this.groupDepth += indentDiff;
1424       this.onIndent();
1425     }
1426
1427     return indentDiff;
1428   };
1429
1430   /**
1431    * Find all siblings for a row.
1432    *
1433    * According to its subgroup or indentation. Note that the passed-in row is
1434    * included in the list of siblings.
1435    *
1436    * @param {object} rowSettings
1437    *   The field settings we're using to identify what constitutes a sibling.
1438    *
1439    * @return {Array}
1440    *   An array of siblings.
1441    */
1442   Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) {
1443     var siblings = [];
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;
1456           }
1457
1458           if (!(this.indentEnabled) || (checkRowIndentation === rowIndentation)) {
1459             siblings.push(checkRow[0]);
1460           }
1461           else if (checkRowIndentation < rowIndentation) {
1462             // No need to keep looking for siblings when we get to a parent.
1463             break;
1464           }
1465         }
1466         else {
1467           break;
1468         }
1469         checkRow = checkRow[directions[d]]();
1470       }
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') {
1474         siblings.reverse();
1475         siblings.push(this.element);
1476       }
1477     }
1478     return siblings;
1479   };
1480
1481   /**
1482    * Remove indentation helper classes from the current row group.
1483    */
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');
1492       }
1493     }
1494   };
1495
1496   /**
1497    * Add an asterisk or other marker to the changed row.
1498    */
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);
1504     }
1505   };
1506
1507   /**
1508    * Stub function. Allows a custom handler when a row is indented.
1509    *
1510    * @return {null}
1511    *   Returns null when the stub function is used.
1512    */
1513   Drupal.tableDrag.prototype.row.prototype.onIndent = function () {
1514     return null;
1515   };
1516
1517   /**
1518    * Stub function. Allows a custom handler when a row is swapped.
1519    *
1520    * @param {HTMLElement} swappedRow
1521    *   The element for the swapped row.
1522    *
1523    * @return {null}
1524    *   Returns null when the stub function is used.
1525    */
1526   Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
1527     return null;
1528   };
1529
1530   $.extend(Drupal.theme, /** @lends Drupal.theme */{
1531
1532     /**
1533      * @return {string}
1534      *  Markup for the marker.
1535      */
1536     tableDragChangedMarker: function () {
1537       return '<abbr class="warning tabledrag-changed" title="' + Drupal.t('Changed') + '">*</abbr>';
1538     },
1539
1540     /**
1541      * @return {string}
1542      *   Markup for the indentation.
1543      */
1544     tableDragIndentation: function () {
1545       return '<div class="js-indentation indentation">&nbsp;</div>';
1546     },
1547
1548     /**
1549      * @return {string}
1550      *   Markup for the warning.
1551      */
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>';
1554     }
1555   });
1556
1557 })(jQuery, Drupal, drupalSettings);